http://stackoverflow.com/comment/90590693
comment on: http://stackoverflow.com/q/51818302
has text: @EdChum The same image, when inside the folder and ran through the first code, has no issues. But when I use the second code, it shows the error
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/90680366
comment on: http://stackoverflow.com/q/51857329
type: Comment
type: QuestionComment
has text: Should the cars bounce when they hit the border or should they just be stopped or slide?
score: 0

http://stackoverflow.com/q/51919077
favorite count: 0
type: UnansweredQuestion
tagged with: python
score: 1
tagged with: recurrent-neural-network
tagged with: tensorflow
has answer: http://stackoverflow.com/a/51991050
type: Question
has body: We would like to make our estimator predict a word or the next work just like the keyboard in your smartphone does. We would like to train it on some text file. So we went ahead and looked in the tensorflow API and found estimator = RNNEstimator( head=tf.contrib.estimator.regression_head(), sequence_feature_columns=[token_emb], rnn_cell_fn=rnn_cell_fn) which seems to be a convenient way to create an estimator for an RNN. Now, we are facing problems with the feature columns. We are setting them up like this token_sequence = sequence_categorical_column_with_hash_bucket( key="text", hash_bucket_size=num_of_categories, dtype=tf.string) token_emb = embedding_column(categorical_column=token_sequence, dimension=8) where 'text' is defined in our input function train_input_fn = tf.estimator.inputs.numpy_input_fn( x={"text": features}, y=labels, batch_size=batch_size, num_epochs=None, shuffle=True) where features is just a long list of 40-character sequences sampled from our original text. The problems Is it possible to use feature columns on string inputs anyway? The documentation does not really give away much. What to do with the labels? At the moment, we get an error since they are never cast to integers Even when introducing arbitrary integers as labels, we still get an error when calling estimator.train(input_fn=train_input_fn, steps=100) which says 'Given type: {}'.format(type(features))) ValueError: features should be a dictionary of Tensors. Given type: so we are definitely doing something wrong here. Any help appreciated :)
tagged with: tensorflow-estimator
upvote count: 1
downvote count: 0
answer count: 1
has title: Train RNN on large string using Estimator API

http://stackoverflow.com/q/51869683
has body: I just started learning basic programming to solve a real-world problem. Currently I am struggling with some regex in Python, and hoping I could get a little bit of help here. I need to telnet into a network switch, get its firmware versions before something else can be done. So, the output of command "show switch" is something looks like this: (Please note that depending on what particular firmware versions are actually running on Primary and Secondary, there may or may not be a line of "patchX-X" displayed.) switch1.1 # show switch SysName: switch1 SysLocation: SysContact: support@extremenetworks.com, +1 888 257 3000 System MAC: 00:01:02:03:04:05 System Type: X440 SysHealth check: Enabled (Normal) Recovery Mode: All System Watchdog: Enabled Current Time: Mon Dec 31 00:00:00 2000 Timezone: [Auto DST Disabled] GMT Offset: 0 minutes, name is UTC. Boot Time: Mon Dec 31 00:00:00 2000 Boot Count: 1 Next Reboot: None scheduled System UpTime: 0 minutes 0 seconds Current State: OPERATIONAL Image Selected: primary Image Booted: primary Primary ver: 12.3.4.5 patch1-2 Secondary ver: 12.6.7.8 patch3-4 Config Selected: primary.cfg Config Booted: primary.cfg Following Python code is used to extract versions out of above output. Desired result will be priVer=="12.3.4.5 patch1-2" and secVer=="12.6.7.8 patch3-4". def updateReadout(): global readout readout = tn.read_very_eager() def checkFirmware(): global priVer global secVer global priPatch global secPatch tn.write("show switch\n") updateReadout() priVer = re.findall(r"(?&lt;=Primary ver:\s{6})\S+",readout)[0] secVer = re.findall(r"(?&lt;=Secondary ver:\s{4})\S+",readout)[0] try: priPatch = re.findall(r"(?&lt;=Primary ver:\s{6}\S{8}\s{19})\S+",readout)[0] priVer = priVer + " " + priPatch except IndexError: print "Oops!IndexError!" pass try: secPatch = re.findall(r"(?&lt;=Secondary ver:\s{4}\S{8}\s{19})\S+",readout)[0] secVer = secVer + " " + secPatch except IndexError: print "Oops!IndexError!" pass print "\n" + "Primary Version =…
tagged with: python-2.7
score: 0
has title: Some certain regex don't match correctly when string is multi-line
type: UnansweredQuestion
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/90696095
has comment: http://stackoverflow.com/comment/90690980
has answer: http://stackoverflow.com/a/51869802
type: Question
has answer: http://stackoverflow.com/a/51869844
answer count: 2
has comment: http://stackoverflow.com/comment/90691075

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

http://stackoverflow.com/a/51865723
upvote count: 1
answers question: http://stackoverflow.com/q/51865367
downvote count: 0
has body: Since the dtype is timedelta64[ns] you can either use between, specifying two timedeltas as the endpoints, or you can first convert the days to a numeric type using numpy. Setup import pandas as pd import numpy as np df = pd.DataFrame({'age': [83, 108, 83, 63, 81]}) df['age'] = pd.to_timedelta(df.age, unit='days') Find those between 82 and 107 days: df[df.age.between(pd.to_timedelta(82, unit='days'), pd.to_timedelta(107, unit='days'))] # age #0 83 days #2 83 days With numpy df[(df.age/np.timedelta64(1, 'D')).between(82, 107)] # age #0 83 days #2 83 days
type: Answer
score: 1

http://stackoverflow.com/comment/90673881
comment on: http://stackoverflow.com/q/51860742
type: QuestionComment
has text: The answer is almost certainly no, you want one file of results. Your goals may vary. Also notice that what @KlausD. is saying is that `return vt_result`, at least, is indented within the `for filename in ...` which means it only reads one file then returns.
score: 0
type: Comment

http://stackoverflow.com/q/51812883
has comment: http://stackoverflow.com/comment/90719200
type: AnsweredQuestion
downvote count: 0
score: 6
favorite count: 0
has comment: http://stackoverflow.com/comment/90689024
tagged with: terminal
type: Question
has answer: http://stackoverflow.com/a/51925328
tagged with: python
upvote count: 6
has comment: http://stackoverflow.com/comment/90809523
accepted answer: http://stackoverflow.com/a/51925328
has comment: http://stackoverflow.com/comment/90688232
has comment: http://stackoverflow.com/comment/90764334
has title: How to reuse an existing sys.ps1 formatter in an IPython prompt?
answer count: 1
has body: I have a function f that produces a PS1 prompt for python, set as such: sys.ps1 = f Following the instructions in the documentation, I ended up with the following: from IPython.terminal.prompts import Prompts, Token from IPython import get_ipython class MyPrompt(Prompts): def in_prompt_tokens(self, cli=None): return [(Token, f())] ipython = get_ipython() ipython.prompts = MyPrompt(ipython) However, this doesn't work, since f returns a string with color codes, which python prints directly to the terminal, leading to a colorful prompt, while ipython prints escaped, leading to a bunch of escape codes. I know I can reconfigure f to use ipython's internal coloring scheme, but is there a way to force it to use the shell's color codes without escaping them? While f is a function that takes into account information about its environment, here's an implementation that shows its output in one situation (it uses colorama behind the hood, so this is just the ouptut on unix systems). def f(): return '\x01\x1b[1m\x1b[33m\x02kavi\x01\x1b[0m\x02 \x01\x1b[38;5;214m\x02/home\x01\x1b[38;5;82m\x02/kavi\x01\x1b[38;5;28m\x02\x01\x1b[0m\x02 \x01\x1b[38;5;38m\x02master\x01\x1b[0m\x02 $ '
has comment: http://stackoverflow.com/comment/90795608
has comment: http://stackoverflow.com/comment/90864008
has comment: http://stackoverflow.com/comment/90717758
tagged with: ipython

http://stackoverflow.com/comment/90672826
type: Comment
comment on: http://stackoverflow.com/q/51859857
score: 0
type: QuestionComment
has text: Yeah I just did!

http://stackoverflow.com/a/51860433
type: Answer
score: 1
accepted answer of: http://stackoverflow.com/q/51859984
upvote count: 1
answers question: http://stackoverflow.com/q/51859984
has body: You can use the with tag: {% with my_obj|get_foo as my_foo %} {{ my_foo.bar }} {% endwith %}
has comment: http://stackoverflow.com/comment/90718163
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/51935309
accepted answer: http://stackoverflow.com/a/51935536
downvote count: 1
type: Question
possible better answer: http://stackoverflow.com/a/51935362
has answer: http://stackoverflow.com/a/51935362
upvote count: 0
has comment: http://stackoverflow.com/comment/90821026
has answer: http://stackoverflow.com/a/51935593
has comment: http://stackoverflow.com/comment/90820781
has comment: http://stackoverflow.com/comment/90820753
has title: Making A Dictionary in Python
has answer: http://stackoverflow.com/a/51935536
score: -1
favorite count: 0
has body: I'm trying to make a dictionary with Bob's sayings, but I keep being told that I'm using "invalid syntax." What am I doing wrong? I'm trying to pull random keys from the dictionary and display quotes... bob_sayings = { 1: "I wish I was where I was when I wished I was here", 2:"There's a fine line between fishing and standing on the shore like an idiot.", 3: "After accomplishing a goal just look around to see whether you lost something or someone"} bob_sayings bob_sayings[randint(1, 3)
answer count: 5
has answer: http://stackoverflow.com/a/51935330
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51935356

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

http://stackoverflow.com/comment/90728855
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51888829
has text: why not pass a meanless numpy to b when it is empty

http://stackoverflow.com/q/51798875
has body: So, I downloaded pandas_datareader through Anaconda. When I try to use pandas_datareader it does not work, or the path is not correct. ModuleNotFoundError: No module named 'pandas_datareader' Earlier I tried to install Anaconda or connect Anaconda to SublimeText3 through the Package Installer of SublimeText3 (ctrl+shift+p). I do not get it work. Searching further, I found a site that explains how to create an environment and install Anaconda, I already did that before. http://damnwidget.github.io/anaconda/ So, it might be that I have a path linking issue. Can you help me out to understand this?
type: UnansweredQuestion
tagged with: pandas
tagged with: sublimetext3
has answer: http://stackoverflow.com/a/51798916
type: Question
score: 0
tagged with: path
tagged with: python
answer count: 1
has title: How to 'connect' Anaconda's packages/modules to Sublimetext?
tagged with: anaconda

http://stackoverflow.com/comment/92397648
type: QuestionComment
has text: @CoreyGoldberg, cause in headless mode, for my specific page(not google) , I am blocked out saying "401 unauthorized access is denied due to invalid credentials"
score: 0
comment on: http://stackoverflow.com/q/51802268
type: Comment

python
tags question: http://stackoverflow.com/q/51828811
tags question: http://stackoverflow.com/q/51811671
tags question: http://stackoverflow.com/q/51880360
tags question: http://stackoverflow.com/q/51879125
tags question: http://stackoverflow.com/q/51842008
tags question: http://stackoverflow.com/q/51804966
tags question: http://stackoverflow.com/q/51905337
tags question: http://stackoverflow.com/q/51882215
tags question: http://stackoverflow.com/q/51872776
tags question: http://stackoverflow.com/q/51937381
tags question: http://stackoverflow.com/q/51843978
tags question: http://stackoverflow.com/q/51878966
tags question: http://stackoverflow.com/q/51854116
tags question: http://stackoverflow.com/q/51948243
tags question: http://stackoverflow.com/q/51799486
tags question: http://stackoverflow.com/q/51905869
tags question: http://stackoverflow.com/q/51895370
tags question: http://stackoverflow.com/q/51930730
tags question: http://stackoverflow.com/q/51915286
tags question: http://stackoverflow.com/q/51895784
tags question: http://stackoverflow.com/q/51921415
tags question: http://stackoverflow.com/q/51802937
tags question: http://stackoverflow.com/q/51890070
tags question: http://stackoverflow.com/q/51869082
tags question: http://stackoverflow.com/q/51924537
tags question: http://stackoverflow.com/q/51901751
tags question: http://stackoverflow.com/q/51905003
tags question: http://stackoverflow.com/q/51804688
tags question: http://stackoverflow.com/q/51878601
tags question: http://stackoverflow.com/q/51853349
tags question: http://stackoverflow.com/q/51826128
tags question: http://stackoverflow.com/q/51941251
tags question: http://stackoverflow.com/q/51832920
tags question: http://stackoverflow.com/q/51861790
tags question: http://stackoverflow.com/q/51805272
tags question: http://stackoverflow.com/q/51886641
tags question: http://stackoverflow.com/q/51918128
tags question: http://stackoverflow.com/q/51818188
tags question: http://stackoverflow.com/q/51910644
tags question: http://stackoverflow.com/q/51885923
tags question: http://stackoverflow.com/q/51927792
tags question: http://stackoverflow.com/q/51806318
tags question: http://stackoverflow.com/q/51843149
tags question: http://stackoverflow.com/q/51826942
tags question: http://stackoverflow.com/q/51809893
tags question: http://stackoverflow.com/q/51906611
tags question: http://stackoverflow.com/q/51922583
tags question: http://stackoverflow.com/q/51801034
tags question: http://stackoverflow.com/q/51847674
tags question: http://stackoverflow.com/q/51901267
tags question: http://stackoverflow.com/q/51902251
tags question: http://stackoverflow.com/q/51901590
tags question: http://stackoverflow.com/q/51826802
tags question: http://stackoverflow.com/q/51854809
tags question: http://stackoverflow.com/q/51879686
tags question: http://stackoverflow.com/q/51884071
tags question: http://stackoverflow.com/q/51903172
tags question: http://stackoverflow.com/q/51820208
tags question: http://stackoverflow.com/q/51894464
tags question: http://stackoverflow.com/q/51822965
tags question: http://stackoverflow.com/q/51814155
tags question: http://stackoverflow.com/q/51824496
tags question: http://stackoverflow.com/q/51850421
tags question: http://stackoverflow.com/q/51930053
tags question: http://stackoverflow.com/q/51938042
tags question: http://stackoverflow.com/q/51861390
tags question: http://stackoverflow.com/q/51835152
tags question: http://stackoverflow.com/q/51939716
tags question: http://stackoverflow.com/q/51829183
tags question: http://stackoverflow.com/q/51809401
tags question: http://stackoverflow.com/q/51919051
tags question: http://stackoverflow.com/q/51888329
tags question: http://stackoverflow.com/q/51930281
tags question: http://stackoverflow.com/q/51808913
tags question: http://stackoverflow.com/q/51899374
tags question: http://stackoverflow.com/q/51867402
tags question: http://stackoverflow.com/q/51818914
tags question: http://stackoverflow.com/q/51918348
tags question: http://stackoverflow.com/q/51923525
tags question: http://stackoverflow.com/q/51880405

http://stackoverflow.com/a/51931902
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51930567
type: Answer
has body: The text widget cannot be written to sparsely. That is, if you want to write to row 10, you must have data on rows 1-9. Likewise, if you want to display something at a specific column, you must have data in all of the columns leading up to it.
accepted answer of: http://stackoverflow.com/q/51930567

python-3.x
tags question: http://stackoverflow.com/q/51943622
tags question: http://stackoverflow.com/q/51804985
tags question: http://stackoverflow.com/q/51936136
tags question: http://stackoverflow.com/q/51836466
tags question: http://stackoverflow.com/q/51903204
tags question: http://stackoverflow.com/q/51922926
tags question: http://stackoverflow.com/q/51937189
tags question: http://stackoverflow.com/q/51848406
tags question: http://stackoverflow.com/q/51925691
tags question: http://stackoverflow.com/q/51855868
tags question: http://stackoverflow.com/q/51953511
tags question: http://stackoverflow.com/q/51866342
tags question: http://stackoverflow.com/q/51929282
tags question: http://stackoverflow.com/q/51873147
tags question: http://stackoverflow.com/q/51916265
tags question: http://stackoverflow.com/q/51862401
tags question: http://stackoverflow.com/q/51952833
tags question: http://stackoverflow.com/q/51898026
tags question: http://stackoverflow.com/q/51859462
tags question: http://stackoverflow.com/q/51927021
tags question: http://stackoverflow.com/q/51822197
tags question: http://stackoverflow.com/q/51939733
tags question: http://stackoverflow.com/q/51875378
tags question: http://stackoverflow.com/q/51852298
tags question: http://stackoverflow.com/q/51949736
tags question: http://stackoverflow.com/q/51940695
tags question: http://stackoverflow.com/q/51952046
tags question: http://stackoverflow.com/q/51869915
tags question: http://stackoverflow.com/q/51891921
tags question: http://stackoverflow.com/q/51879564
tags question: http://stackoverflow.com/q/51862276
tags question: http://stackoverflow.com/q/51955275
tags question: http://stackoverflow.com/q/51893694
tags question: http://stackoverflow.com/q/51804203
tags question: http://stackoverflow.com/q/51878077
tags question: http://stackoverflow.com/q/51906323
tags question: http://stackoverflow.com/q/51822956
tags question: http://stackoverflow.com/q/51888734
tags question: http://stackoverflow.com/q/51821988
tags question: http://stackoverflow.com/q/51917700
tags question: http://stackoverflow.com/q/51819971
tags question: http://stackoverflow.com/q/51805075
tags question: http://stackoverflow.com/q/51828826
tags question: http://stackoverflow.com/q/51802047
tags question: http://stackoverflow.com/q/51887538
tags question: http://stackoverflow.com/q/51939437
tags question: http://stackoverflow.com/q/51870069
tags question: http://stackoverflow.com/q/51905346
tags question: http://stackoverflow.com/q/51826523
tags question: http://stackoverflow.com/q/51940600
tags question: http://stackoverflow.com/q/51852025
tags question: http://stackoverflow.com/q/51817007
tags question: http://stackoverflow.com/q/51872892
tags question: http://stackoverflow.com/q/51862620
tags question: http://stackoverflow.com/q/51815633
tags question: http://stackoverflow.com/q/51920019
tags question: http://stackoverflow.com/q/51872781
tags question: http://stackoverflow.com/q/51867655
tags question: http://stackoverflow.com/q/51902001
tags question: http://stackoverflow.com/q/51800639
tags question: http://stackoverflow.com/q/51845668
tags question: http://stackoverflow.com/q/51900396
tags question: http://stackoverflow.com/q/51808620
tags question: http://stackoverflow.com/q/51920013
tags question: http://stackoverflow.com/q/51854444
tags question: http://stackoverflow.com/q/51914893
tags question: http://stackoverflow.com/q/51860378
tags question: http://stackoverflow.com/q/51859562
tags question: http://stackoverflow.com/q/51916052
tags question: http://stackoverflow.com/q/51878819
tags question: http://stackoverflow.com/q/51892590
tags question: http://stackoverflow.com/q/51955941
tags question: http://stackoverflow.com/q/51935973
tags question: http://stackoverflow.com/q/51802109
tags question: http://stackoverflow.com/q/51873465
tags question: http://stackoverflow.com/q/51807789
tags question: http://stackoverflow.com/q/51916597
tags question: http://stackoverflow.com/q/51853060
tags question: http://stackoverflow.com/q/51952165
tags question: http://stackoverflow.com/q/51887353

pandas
tags question: http://stackoverflow.com/q/51936346
tags question: http://stackoverflow.com/q/51883796
tags question: http://stackoverflow.com/q/51890748
tags question: http://stackoverflow.com/q/51904887
tags question: http://stackoverflow.com/q/51840480
tags question: http://stackoverflow.com/q/51845977
tags question: http://stackoverflow.com/q/51863993
tags question: http://stackoverflow.com/q/51947860
tags question: http://stackoverflow.com/q/51925843
tags question: http://stackoverflow.com/q/51938430
tags question: http://stackoverflow.com/q/51847806
tags question: http://stackoverflow.com/q/51924775
tags question: http://stackoverflow.com/q/51862593
tags question: http://stackoverflow.com/q/51822709
tags question: http://stackoverflow.com/q/51802054
tags question: http://stackoverflow.com/q/51935179
tags question: http://stackoverflow.com/q/51846296
tags question: http://stackoverflow.com/q/51902722
tags question: http://stackoverflow.com/q/51861592
tags question: http://stackoverflow.com/q/51923088
tags question: http://stackoverflow.com/q/51844794
tags question: http://stackoverflow.com/q/51856337
tags question: http://stackoverflow.com/q/51804410
tags question: http://stackoverflow.com/q/51882902
tags question: http://stackoverflow.com/q/51880452
tags question: http://stackoverflow.com/q/51953630
tags question: http://stackoverflow.com/q/51869082
tags question: http://stackoverflow.com/q/51820952
tags question: http://stackoverflow.com/q/51866934
tags question: http://stackoverflow.com/q/51894603
tags question: http://stackoverflow.com/q/51877292
tags question: http://stackoverflow.com/q/51801528
tags question: http://stackoverflow.com/q/51938042
tags question: http://stackoverflow.com/q/51831616
tags question: http://stackoverflow.com/q/51850844
tags question: http://stackoverflow.com/q/51894019
tags question: http://stackoverflow.com/q/51902037
tags question: http://stackoverflow.com/q/51844984
tags question: http://stackoverflow.com/q/51814491
tags question: http://stackoverflow.com/q/51811316
tags question: http://stackoverflow.com/q/51938509
tags question: http://stackoverflow.com/q/51840123
tags question: http://stackoverflow.com/q/51825309
tags question: http://stackoverflow.com/q/51840865
tags question: http://stackoverflow.com/q/51935399
tags question: http://stackoverflow.com/q/51848349
tags question: http://stackoverflow.com/q/51902595
tags question: http://stackoverflow.com/q/51833943
tags question: http://stackoverflow.com/q/51835831
tags question: http://stackoverflow.com/q/51808743
tags question: http://stackoverflow.com/q/51879282
tags question: http://stackoverflow.com/q/51806731
tags question: http://stackoverflow.com/q/51929282
tags question: http://stackoverflow.com/q/51884784
tags question: http://stackoverflow.com/q/51949683
tags question: http://stackoverflow.com/q/51927021
tags question: http://stackoverflow.com/q/51947109
tags question: http://stackoverflow.com/q/51813207
tags question: http://stackoverflow.com/q/51875378
tags question: http://stackoverflow.com/q/51897638
tags question: http://stackoverflow.com/q/51950226
tags question: http://stackoverflow.com/q/51879764
tags question: http://stackoverflow.com/q/51926466
tags question: http://stackoverflow.com/q/51862276
tags question: http://stackoverflow.com/q/51824521
tags question: http://stackoverflow.com/q/51811914
tags question: http://stackoverflow.com/q/51940146
tags question: http://stackoverflow.com/q/51833930
tags question: http://stackoverflow.com/q/51832453
tags question: http://stackoverflow.com/q/51822956
tags question: http://stackoverflow.com/q/51879679
tags question: http://stackoverflow.com/q/51920827
tags question: http://stackoverflow.com/q/51928536
tags question: http://stackoverflow.com/q/51862716
tags question: http://stackoverflow.com/q/51922803
tags question: http://stackoverflow.com/q/51817919
tags question: http://stackoverflow.com/q/51905346
tags question: http://stackoverflow.com/q/51889613
tags question: http://stackoverflow.com/q/51827058
tags question: http://stackoverflow.com/q/51896621

http://stackoverflow.com/q/51804042
tagged with: permissions
favorite count: 0
downvote count: 0
type: UnansweredQuestion
tagged with: django
tagged with: python
score: 3
type: Question
has title: DRF get_permissions doesn't appear to work correctly
answer count: 1
tagged with: django-rest-framework
upvote count: 3
has answer: http://stackoverflow.com/a/51805206
has body: I'm trying to configure permissions for my custom User model and I'm using a Viewset to run CRUD operations for the model. Depending on the operation, I need to set different permission requirements such that: anyone can create a new User instance only owners or admins can retrieve or update users For some reason, when I define the get_permissions method inside my class, like so: def get_permissions(self): if self.action == 'create': return [AllowAny(),] elif self.action == 'me': return [IsAuthenticated(),] return [IsAuthenticated(), IsOwnerOrAdmin()] but when I navigate to /api/v1/users/, the DRF explorer doesn't show the form to create a new User and gives me a 403 error. On the flipside, when I comment this function out, I can see form properly, but obviously can't use it that way. For reference, my custom IsOwnerOrAdmin permissions class looks like: class IsOwnerOrAdmin(permissions.BasePermission): @staticmethod def _is_admin(request): return request.user.is_superuser def has_permission(self, request, view): try: is_owner = str(request.user.id) == view.kwargs.get('pk') return is_owner or self._is_admin(request) # if request.user.uuid is not there (i.e. AnonymousUser) except AttributeError: return False What might be the issue here?

http://stackoverflow.com/q/51832829
downvote count: 0
accepted answer: http://stackoverflow.com/a/51838031
favorite count: 0
tagged with: python-3.x
has title: QMovie unexpected argument QBuffer
tagged with: python
has comment: http://stackoverflow.com/comment/90637997
type: AnsweredQuestion
score: 1
has body: Hi i thought QMovie could take QBuffer? This is my code. a = QByteArray(img) b = QBuffer(a) self.movie = QMovie(b, 'GIF')
tagged with: pyqt5
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51838031
answer count: 1

django-models
tag name: django-models
tags question: http://stackoverflow.com/q/51949293
tags question: http://stackoverflow.com/q/51847892
tags question: http://stackoverflow.com/q/51882107
tags question: http://stackoverflow.com/q/51837124
tags question: http://stackoverflow.com/q/51821722
tags question: http://stackoverflow.com/q/51830948
tags question: http://stackoverflow.com/q/51939726
tags question: http://stackoverflow.com/q/51905712
tags question: http://stackoverflow.com/q/51805421
tags question: http://stackoverflow.com/q/51812656
tags question: http://stackoverflow.com/q/51922396
tags question: http://stackoverflow.com/q/51886425
tags question: http://stackoverflow.com/q/51920779
tags question: http://stackoverflow.com/q/51875173
tags question: http://stackoverflow.com/q/51904755
tags question: http://stackoverflow.com/q/51865703
tags question: http://stackoverflow.com/q/51888992
tags question: http://stackoverflow.com/q/51941280
tags question: http://stackoverflow.com/q/51832490
tags question: http://stackoverflow.com/q/51809804
tags question: http://stackoverflow.com/q/51860652
type: Tag
tags question: http://stackoverflow.com/q/51947018
tags question: http://stackoverflow.com/q/51918856
tags question: http://stackoverflow.com/q/51865212
tags question: http://stackoverflow.com/q/51827609
tags question: http://stackoverflow.com/q/51803756
tags question: http://stackoverflow.com/q/51855147
tags question: http://stackoverflow.com/q/51800593
tags question: http://stackoverflow.com/q/51936447
tags question: http://stackoverflow.com/q/51853072
tags question: http://stackoverflow.com/q/51948947
tags question: http://stackoverflow.com/q/51860605
tags question: http://stackoverflow.com/q/51937219
tags question: http://stackoverflow.com/q/51811839
tags question: http://stackoverflow.com/q/51921794
tags question: http://stackoverflow.com/q/51946844
tags question: http://stackoverflow.com/q/51914373
tags question: http://stackoverflow.com/q/51923655
tags question: http://stackoverflow.com/q/51941457
tags question: http://stackoverflow.com/q/51838628
tags question: http://stackoverflow.com/q/51940077
tags question: http://stackoverflow.com/q/51847019
tags question: http://stackoverflow.com/q/51914449
tags question: http://stackoverflow.com/q/51870088

http://stackoverflow.com/a/51903909
has comment: http://stackoverflow.com/comment/90966549
score: 0
has body: Are you sure your script is running? It seems an odd situation where a record is flagged to be deleted, not saved yet (which would actually delete it) and yet is still having its status changed. The primary problem here is that you are getting the second PO that is to be deleted in a new/separate transaction (and from the database, not from the in-memory data, if that matters) and not saving that transaction. Your first PO that is being deleted is tied to some process that probably naturally ends in a save call, so that's why you don't have to worry about explicitly calling it on the data in the set that triggers your script. However, that natural "save" call there will only save the records on that transaction. When you get a Set from MXServer like that, you are creating a new transaction and putting its data (and any other related data you fetch from it) in that new transaction. When you are done with that, Maximo does not know if you want to keep your changes or not (or for that matter, it doesn't even know when you are actually done with it), so it won't save it on its own. You need to explicitly call "save()" on one of the MBO sets in that transaction (and only one of the sets in that transaction) to get Maximo to persist the changes to the database. Be careful in your case though. Your data is tightly coupled and therefore has a decent chance of already being in the main set that triggered your script. If the data was changed there already, then your change will have the same record modified in two different transactions, which will cause Maximo to throw the dreaded "refetch" error ("Your record has been updated by another user. Please refetch the record and try again.").
has comment: http://stackoverflow.com/comment/90974863
has comment: http://stackoverflow.com/comment/90977892
has comment: http://stackoverflow.com/comment/90789130
has comment: http://stackoverflow.com/comment/91029296
has comment: http://stackoverflow.com/comment/90828850
type: Answer
answers question: http://stackoverflow.com/q/51899484
has comment: http://stackoverflow.com/comment/90996117
has comment: http://stackoverflow.com/comment/90996385

http://stackoverflow.com/comment/90835054
has text: @jalazbe You're right. If a file doesn't have an UUID in that dir, it should be assigned an Unique ID. If a file already has one, then you don't need to append to a new ID
comment on: http://stackoverflow.com/q/51942292
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51812312
tagged with: django-views
has comment: http://stackoverflow.com/comment/90579581
has title: Django2 not connecting to Local Host
has comment: http://stackoverflow.com/comment/90580005
has body: I'm new to Django/Python. I'm currently taking a beginners course and I'm having difficulty setting up my URLs and connecting to a local server. I'm using Python version: 3.7.0 and Django v.2 The command line does not give any errors (0), it tells me to go here: Starting development server at http://127.0.0.1:8000/ Which I believe is the local host, however the site says This site can’t be reached 127.0.0.1 refused to connect. Can anyone let me know what I'm missing I would greatly appreciate it so that I can continue on with my studying. I'm using tutorials on YT Django Tutorial and the guy is using an older Django so I think that may be why I'm having trouble. He says we should still be okay to follow through even on the new version of Django. urls.py from django.contrib import admin from django.urls import path from.import views urlpatterns = [ path('', views.homepage), path('admin/', admin.site.urls), path('about/', views.about), ] views.py from django.http import HttpResponse def homepage(request): return HttpResponse('homepage') def about(request): return HttpResponse('about')
possible better answer: http://stackoverflow.com/a/51821805
has comment: http://stackoverflow.com/comment/90579807
answer count: 2
has comment: http://stackoverflow.com/comment/90579628
has answer: http://stackoverflow.com/a/51821805
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/51814406
tagged with: python
has comment: http://stackoverflow.com/comment/90579560
type: AnsweredQuestion
score: 1
tagged with: django
has comment: http://stackoverflow.com/comment/90579573
upvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/51814406

http://stackoverflow.com/comment/90581112
type: AnswerComment
type: Comment
has text: i have this Error :module 'django.contrib.views' has no attribute 'LoginView'
comment on: http://stackoverflow.com/a/51812915
score: 0

http://stackoverflow.com/q/51945353
favorite count: 0
tagged with: aws-lambda
tagged with: python-3.x
type: Question
tagged with: dns
tagged with: python
answer count: 1
score: 4
has answer: http://stackoverflow.com/a/58421902
upvote count: 4
has title: Exception handling in aws-lambda functions
downvote count: 0
type: UnansweredQuestion
tagged with: amazon-web-services
has body: While trying to implement a DNSRequest, I also needed to do some exception handling and noticed something weird. The following code is able to catch DNS request timeouts def lambda_handler(event, context): hostname = "google.de" dnsIpAddresses = event['dnsIpAddresses'] dnsResolver = dns.resolver.Resolver() dnsResolver.lifetime = 1.0 result = {} for dnsIpAddress in dnsIpAddresses: dnsResolver.nameservers = [dnsIpAddress] try: myAnswers = dnsResolver.query(hostname, "A") print(myAnswers) result[dnsIpAddress] = "SUCCESS" except dns.resolver.Timeout: print("caught Timeout exception") result[dnsIpAddress] = "FAILURE" except dns.exception.DNSException: print("caught DNSException exception") result[dnsIpAddress] = "FAILURE" except: result[dnsIpAddress] = "FAILURE" print("caught general exception") return result Now, if I removed the Timeout block, and assuming that a Timeout would occur, on a DNSException the message caught DNSException exception will never be shown. Now, if I removed the DNSException block, and assuming that a Timeout would occur, the message caught general exception will never be shown. But the Timeout extends the DNSException and the DNSException extends Exception. I had the expectation that at least the general expect block should work. What am I missing?

http://stackoverflow.com/comment/90750292
score: 0
comment on: http://stackoverflow.com/q/51899442
type: Comment
type: QuestionComment
has text: @janbrohl didn't work for me.

http://stackoverflow.com/a/52205913
type: Answer
accepted answer of: http://stackoverflow.com/q/51836076
answers question: http://stackoverflow.com/q/51836076
score: 0
type: AcceptedAnswer
has body: Considering suggestion from @leotrubach, json.dumps(json_list, indent=4, ensure_ascii=False).encode('utf8') worked as desired.

http://stackoverflow.com/comment/90653188
has text: @abarnert There are no pywin32 binary wheels for Python 3.4 at PyPI; there are at Gohlke's site.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51846232
type: AnswerComment

http://stackoverflow.com/a/51828137
has comment: http://stackoverflow.com/comment/90611068
has body: I'm not super happy with this, but here is a solution A = [1,1,2,1,2,1] B= 'text text text text boom boom'.split() T = pd.to_datetime(['2018-08-13','2018-12-13','2018-07-13','2018-09-13','2018-12-13','2018-11-13']) df = pd.DataFrame({'A':A, 'B':B, 'Timestamp':T}) #Here is the solution frames = [] for name, frame in df.sort_values(['A','Timestamp']).groupby('A'): ix = frame.B=='boom' frames.append(frame.loc[:ix.argmax(),:]) before_boom = pd.concat(frames).query('B != "boom"') Output: A B Timestamp 1 text 2018-08-13 1 text 2018-09-13 2 text 2018-07-13 EDIT: I like this better to_join = df[df.B=='boom'].groupby(['A','B']).Timestamp.min().reset_index() new_df=df.merge(to_join, on = 'A', suffixes=['','_y']) new_df.loc[new_df.Timestamp&lt;new_df.Timestamp_y,['A','B','Timestamp']]
has comment: http://stackoverflow.com/comment/90611838
has comment: http://stackoverflow.com/comment/90611269
score: 0
answers question: http://stackoverflow.com/q/51827686
type: Answer

http://stackoverflow.com/comment/103541180
has text: @kevinf Good find! It doesn't show up in the Settings... https://code.visualstudio.com/docs/cpp/faq-cpp#_ccppintellisensecachesize-number
type: Comment
comment on: http://stackoverflow.com/a/57838491
score: 0
type: AnswerComment

http://stackoverflow.com/comment/90859596
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51954057
has text: Oh I understand now what you mean. To make both the `y` axis have the same scale, you can use `ax.set_ylim(a, b)` and `ax2.set_ylim(a, b)` where `a` and `b` are the minimum and maximum `y` value you want to see on the `y` scales. Here I assume that your axes are named `ax` and `ax1`. Modify accordingly if you have other names like `ax1` and `ax2`

pyqt
type: Tag
tags question: http://stackoverflow.com/q/51819688
tags question: http://stackoverflow.com/q/51912609
tags question: http://stackoverflow.com/q/51907009
tags question: http://stackoverflow.com/q/51812530
tags question: http://stackoverflow.com/q/51949157
tags question: http://stackoverflow.com/q/51902501
tags question: http://stackoverflow.com/q/51855013
tags question: http://stackoverflow.com/q/51808557
tags question: http://stackoverflow.com/q/51924743
tags question: http://stackoverflow.com/q/51823289
tags question: http://stackoverflow.com/q/51931924
tags question: http://stackoverflow.com/q/51878265
tags question: http://stackoverflow.com/q/51881088
tags question: http://stackoverflow.com/q/51820536
tags question: http://stackoverflow.com/q/51818723
tags question: http://stackoverflow.com/q/51850861
tags question: http://stackoverflow.com/q/51867142
tags question: http://stackoverflow.com/q/51930019
tags question: http://stackoverflow.com/q/51828943
tags question: http://stackoverflow.com/q/51934283
tags question: http://stackoverflow.com/q/51937193
tags question: http://stackoverflow.com/q/51864808
tags question: http://stackoverflow.com/q/51861471
tags question: http://stackoverflow.com/q/51867811
tags question: http://stackoverflow.com/q/51929135
tags question: http://stackoverflow.com/q/51897455
tags question: http://stackoverflow.com/q/51846715
tags question: http://stackoverflow.com/q/51859908
tags question: http://stackoverflow.com/q/51799699
tag name: pyqt
tags question: http://stackoverflow.com/q/51898371
tags question: http://stackoverflow.com/q/51872798
tags question: http://stackoverflow.com/q/51943782
tags question: http://stackoverflow.com/q/51893313
tags question: http://stackoverflow.com/q/51842371
tags question: http://stackoverflow.com/q/51829622

http://stackoverflow.com/comment/90614287
type: AnswerComment
has text: @excaza: ah, so it is...
type: Comment
comment on: http://stackoverflow.com/a/51826434
score: 0

http://stackoverflow.com/q/51810743
type: Question
tagged with: python-2.7
score: 0
accepted answer: http://stackoverflow.com/a/51812034
answer count: 1
tagged with: tkinter-entry
has title: Is there any function that gets called when you exit an entry widget in tkinter?
has comment: http://stackoverflow.com/comment/90577066
tagged with: python
has body: I want to change the layout of Label when we exit the entry widget. For Eg: a. In the Layout state 1, The first label says "Entry all the names you want" and beside it you have an entry widget to get the details of names. Format is like number of names, name details. Eg: 2,dan,brown. b. Below the first label, you have the second label named "Choose the config for" and beside it you have a drop-down menu window. BUT, c. I wanted to change the label layout to "Choose the config for dan" based on the details entered in the 1st Entry window dynamically. SO wanted to know if there is any function that we can call at the "EXIT" of the entry widget which can go and modify/re-create the Label 2 layout based on the info provided in the Entry 1 and change the layout to "Layout State 2". Update: I tried the below code with bind and FocusOut, but its not doing what is doing as I was expecting. #!/usr/intel/bin/python2.7 import Tkinter import Tkinter as tk from Tkinter import * import ttk import Tkinter from Tkinter import * import subprocess import shlex import os #from PIL import Image, ImageTk #import Image, ImageTk import time import string import tkFont import ttk global aloha_blue_frame_loop aloha_blue_frame_loop = 1 class MyApp: def __init__(self, parent): self.rel3 = None self.rel4 = None self.rel5 = None self.reo1 = None self.ree3 = None self.ree4 = None self.ree5 = None self.aloha_frame = None self.aloha_name = None self.aloha_type = None self.aloha_name_e = [] self.aloha_type_e = [] self.aloha_choose_int_list = {} self.aloha_choose_int_val = StringVar() if not (self.rel4): self.rel4 = Label(root, font=MyFontH2, text="Enter All the Names You Want: ") self.rel4.grid(row=0, column=0, sticky='W') self.rel4.rowconfigure(0,weight=1) else: self.rel4.grid() if not (self.ree4): self.ree4 = Entry(self.aloha_frame, font=MyFontH2) self.ree4.grid(row=0, column=1) self.ree4.rowconfigure(0,weight=1) self.ree4.delete(0, END) self.ree4.insert(0, '') self.ree4.bind('&lt;FocusOut&gt;', …
type: AnsweredQuestion
tagged with: tkinter
has answer: http://stackoverflow.com/a/51812034
tagged with: tkinter-layout

http://stackoverflow.com/comment/90752045
type: AnswerComment
has text: @Rich then just ignore `df = df[df.ticker != df.other]` this line :)
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51886357

http://stackoverflow.com/comment/90790162
has text: I want the Log Seq number to continue like logfile4.
comment on: http://stackoverflow.com/a/51920067
score: 0
type: AnswerComment
type: Comment

image
tags question: http://stackoverflow.com/q/51856575
tags question: http://stackoverflow.com/q/51805562
tags question: http://stackoverflow.com/q/51887993
tags question: http://stackoverflow.com/q/51809419
tags question: http://stackoverflow.com/q/51802320
tags question: http://stackoverflow.com/q/51825178
tags question: http://stackoverflow.com/q/51800593
tags question: http://stackoverflow.com/q/51810407
tags question: http://stackoverflow.com/q/51820023
tags question: http://stackoverflow.com/q/51940070
tags question: http://stackoverflow.com/q/51803617
tags question: http://stackoverflow.com/q/51809017
tags question: http://stackoverflow.com/q/51920849
tags question: http://stackoverflow.com/q/51809040
tags question: http://stackoverflow.com/q/51917478
tags question: http://stackoverflow.com/q/51887331
tag name: image
tags question: http://stackoverflow.com/q/51921388
tags question: http://stackoverflow.com/q/51813194
type: Tag

http://stackoverflow.com/q/51872583
answer count: 1
has comment: http://stackoverflow.com/comment/90697460
favorite count: 0
has comment: http://stackoverflow.com/comment/90713590
has title: Can't install MatPlotLib for python 3 Mac OSX El Capitan
tagged with: python-3.x
score: 2
has body: I am very new to coding and don't understand install processes. I am using Python 3.7.0 on Max OSX El Capitan. I want to install matplotlib but I tried this in terminal : $ pip install matplotlib and it gave me an error that : 192-168-1-107:~ Ada1$ pip install matplotlib Requirement already satisfied: matplotlib in /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python Requirement already satisfied: numpy&gt;=1.5 in /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python (from matplotlib) Requirement already satisfied: python-dateutil in /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python (from matplotlib) Collecting tornado (from matplotlib) Could not fetch URL https://pypi.python.org/simple/tornado/: There was a problem confirming the ssl certificate: [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:590) - skipping Could not find a version that satisfies the requirement tornado (from matplotlib) (from versions: ) No matching distribution found for tornado (from matplotlib) I also tried : $ sudo pip install matplotlib but same error and python gives the error it is not installed. Help?
has comment: http://stackoverflow.com/comment/90696730
upvote count: 3
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90697174
tagged with: python
downvote count: 1
has comment: http://stackoverflow.com/comment/90696765
has comment: http://stackoverflow.com/comment/90723313
tagged with: matplotlib
has answer: http://stackoverflow.com/a/51881073
has comment: http://stackoverflow.com/comment/90697592
type: Question

http://stackoverflow.com/q/51887319
tagged with: python-3.x
upvote count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51887514
tagged with: python
score: 2
type: Question
has title: How to direct one page requests to certain definitions in Flask?
tagged with: flask
downvote count: 0
answer count: 1
linked to: http://stackoverflow.com/q/8395269
favorite count: 0
has body: I have a webpage using the Dimension template, this template uses "popups" instead of new pages when navigating the site. The link is to a demo of this template for illustration. What I would like to do is: client goes to mysite.com/#recipescraper -> 'popup' of submission form -> submit form -> pop up replaced by a "thank you" popup. So far in Python 3.6 I have the following code: @app.route('/') def homepage(): return render_template('index.html') #--- Cookpad Scraper Stuff ---# @app.route('/#Scraper', methods=['GET','POST']) #allow get and post requests def scraper(): # sending via forms as a post request (behind the scenes) #--- Check if its a post or get request: ---# if request.method == 'POST': #this block is only entered if the form is submitted url = request.form.get('recipe') user = request.form['name'] #--- Assign variables to the multiple choices ---# category = request.form.get('category') dessert = request.form.get('dessert') main_dish = request.form.get('main_dish') side_dish = request.form.get('side_dish') soup = request.form.get('soup') mommy = request.form.get('mommy') #--- Make sure a valid url was submitted ---# check_url = 'https://cookpad.com' if check_url in url: #if a string is submitted with https://cookpad.com in it title = recipe(url, category, dessert, main_dish, side_dish, soup, mommy, user) #puts the title_ext returned from recipe() into the title variable send_data(title, url, mommy, category) # send data to rethinkdb: cookpad_scrape database publish(user) #publishes the scraped recipe into wiki telegram(user, title) #notifies telegram return redirect(url_for('thanks', title=title, user=user)) #redirects to url.com/thanks?title=something&amp;user=something_else. Variables are in the link else: #otherwise return bad_link.html return redirect(url_for('bad_link', link=url, user=user)) #--- Make the form ---# return render_template('#Scraper') This works perfectly, up to the point when the client clicks "submit". For some reason I get a 405…

http://stackoverflow.com/comment/112806189
type: Comment
comment on: http://stackoverflow.com/a/63791773
has text: While this code may solve the question, [including an explanation](//meta.stackexchange.com/q/114762) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please [edit] your answer to add explanations and give an indication of what limitations and assumptions apply. [From Review](/review/low-quality-posts/27115370)
score: 2
type: AnswerComment

http://stackoverflow.com/comment/90781789
type: QuestionComment
comment on: http://stackoverflow.com/q/51915741
has text: I don't understand your description of how to play the game and the problem. Perhaps you should remove the random shuffle so the symbols are always the same and then specify exactly what steps to take to reproduce the problem.
score: 0
type: Comment

http://stackoverflow.com/comment/90869664
has text: Thank you very much. I will definitely try this and will get back to you.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51959565

http://stackoverflow.com/a/51984119
downvote count: 0
answers question: http://stackoverflow.com/q/51953186
score: 2
upvote count: 2
type: AcceptedAnswer
has body: What makes two objects from different frame "the same"? - Their size? - Relative position? - Shape/eccentricity? - Tilt? You can measure these quantities per segment easily using skimage.measure.regionprops and then decide for each pair of segments if they belong to the same object or not based on a combination of these measurements. Obviously, you can add intersection over union measure as proposed by Andy Carlson.
type: Answer
accepted answer of: http://stackoverflow.com/q/51953186

http://stackoverflow.com/comment/90756546
score: 1
comment on: http://stackoverflow.com/q/51902666
has text: Try matching that string: [`re.search(r'^\d{2}:\d{2}\s*[AP]M\b', s)`](https://ideone.com/jfV4b6). Is that string always at the string start?
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/90588537
type: Comment
score: 1
comment on: http://stackoverflow.com/q/51817242
has text: If you want to match why do you split?
type: QuestionComment

http://stackoverflow.com/comment/90778585
has text: I fixed the assignment, and added new code.
score: 0
comment on: http://stackoverflow.com/q/51914284
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90570676
score: 1
comment on: http://stackoverflow.com/q/51807763
type: Comment
type: QuestionComment
has text: In many CPU-intensive tasks C code runs much, much faster than plain Python code, so you really should try to install this C module first. You'll need a C (or C++) compiler to do this.

http://stackoverflow.com/q/51913604
has comment: http://stackoverflow.com/comment/90777414
type: AnsweredQuestion
downvote count: 0
has body: So, I have two datasets(I mean dataframe) as follows dataframe 1: name, age, id, acctno abc, 23, 1001, 238238 dhd, 22, 2001, 299299 ddg, 30, 2920, 101010 ssd, 53, 1901, 238003 ggh, 52, 2221, 222222 eet, 50, 9920, 111111 (we can save this as population1.csv) dataframe 2: name, age, id, acctno abc, 11, 1001, 238238 def, 55, 2001, 299299 xxy, 90, 2020, 101010 (we can save this as population2.csv) So, we can read the data as follows df1 = pd.read_csv('population1.csv') df2 = pd.read_csv('population2.csv') And, I want to get the following result res = df1-df2 based on the common columns of id and acctno. We can see that based on id and acctno, dataframe2 is in dataframe1. But the dataframe1 has some more records that are not common in dataframe2. Subsetting two dataframes based on one column is straightforeword, however would like to know how to subset two dataframes based on two columns. So, the result should as something as follows ssd, 53, 1901, 238003 ggh, 52, 2221, 222222 eet, 50, 9920, 111111
favorite count: 0
type: Question
tagged with: pandas
has title: pandas subset two dataframes based on multiple columns
score: 3
tagged with: python
has answer: http://stackoverflow.com/a/51913696
has answer: http://stackoverflow.com/a/51913827
upvote count: 3
tagged with: subset
answer count: 3
possible better answer: http://stackoverflow.com/a/51913815
accepted answer: http://stackoverflow.com/a/51913696
has answer: http://stackoverflow.com/a/51913815
tagged with: dataframe

http://stackoverflow.com/a/51868053
has comment: http://stackoverflow.com/comment/90688148
has comment: http://stackoverflow.com/comment/90694399
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90688114
has body: I'm not familiar with tkinter, so my advice would be rather broad. You can use any split into modules which you feel is better, but as readability counts try making names coherent and do not repeat yourself: guiclasses - your enire progarm is about GUI, and there obviously classes somewhere, why repeath that in a name? imagine typing all that in in import, make it meaningful to type flat structure is better than nested, three modules do not have to go to submodule best split is across layers of abstraction (this is probably hardest and specific to tkinter) anything in a module shoudl be rather self-sufficient and quite isolated from other parts of the program modules should make good entitites for unit testing (eg share same fixtures) can you write an understandable docstring for a module? then it's a good one. try learning by example, I often seek wisdom for naming and package structure in Barry Warsaw mailman, maybe you can try finding some reputable repo with tkinter to follow (eg IDLE?). From purely syntatic view I would have named the modules as: - &lt;package_name&gt; - baseframe - textframe - window - main
type: Answer
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/51867912
answers question: http://stackoverflow.com/q/51867912

http://stackoverflow.com/comment/90667675
comment on: http://stackoverflow.com/a/51842130
score: 0
type: AnswerComment
type: Comment
has text: @BaggelisKotsifakhs you need to explain how do you want to match 41 product code elements against 9 image elements

http://stackoverflow.com/q/51923503
score: 10
has answer: http://stackoverflow.com/a/51931395
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/90796628
tagged with: python
accepted answer: http://stackoverflow.com/a/51931395
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90797001
tagged with: conv-neural-network
tagged with: image-processing
upvote count: 10
has body: I don't have much knowledge of image processing. I am trying to implement a ConvNet. I downloaded some images as data set and made their height and width equal. Then I tried loading them into np.array by this code: train_list = glob.glob('A:\Code\Machine Learning\CNN\ConvolutionalNN1\TrainImg\*.jpg') X_train_orig = np.array([np.array(Image.open(file)) for file in train_list]) But it gave me error that cannot broadcast (420,310) to (420,310,3). Then I printed the shape of array, some were (420,310,3) others (410,320,4). Why is so? And how can I change that to fit it in array?
type: Question
has comment: http://stackoverflow.com/comment/90796714
has title: Why do some images have third dimension 3 while others have 4?

http://stackoverflow.com/q/51844220
type: Question
answer count: 2
tagged with: python-3.6
score: 0
upvote count: 1
downvote count: 1
has body: I need to use winapi for a project and I must use python 3.6 to do so. I have two interpreters installed: python 3.65 and python 2.7 (the original). Whenever I use the pip install pypiwin32 command it tells me it is already installed on the 2.7 version. When I tried to move the files from the 2.7 directory to the 3.65 directory it wouldn't work. How do I install winapi on python 3.65?
favorite count: 0
has title: python winapi installation on 3.65
has answer: http://stackoverflow.com/a/51845276
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90642951
tagged with: python
tagged with: winapi
linked to: http://stackoverflow.com/q/42559222
has answer: http://stackoverflow.com/a/51844792

http://stackoverflow.com/q/51941038
linked to: http://stackoverflow.com/q/22483588
has comment: http://stackoverflow.com/comment/90832077
has comment: http://stackoverflow.com/comment/90832210
has comment: http://stackoverflow.com/comment/90832021
has comment: http://stackoverflow.com/comment/90832044
tagged with: python
has body: Say I have the dataframe below: import pandas as pd data = {'Col1':['(-2.0, 1.0]', '(1.0, 4.0]', '(4.0, 6.0]', '(6.0, 9.0]', '(9.0, 11.0]', '(11.0, 14.0]', '(14.0, 16.0]', '(16.0, 19.0]', '(19.0, 21.0]', '(21.0, 24.0]'], 'Col2':[3.409836, 2.930693, 2.75, 3.140845, 2.971429, 2.592593, 2.6, 3.1875, 2.857143, 0.714286]} df = pd.DataFrame(data, columns=['Col1', 'Col2']) df I want to plot df.Col2 against df.Col1. But since Col1 contains ranges or bins of something, the Col1 values are not float or int - they are strings. Thus, the plot does not show the x-axis in order: import matplotlib.pyplot as plt fig = plt.figure(figsize=(10,5)) plt.plot([str(i) for i in df.Col2], df.Col1) How do I fix this? EDIT: For multiple subplots I can't use df.plot(x='Col1',y='Col2') because I have this plot as one of the subplots: df1 = pd.DataFrame(data, columns=['Col1', 'Col2']) df2 = df1 df3 = df1 fig = plt.figure(figsize=(20,5)) plt.subplot(1,3,1) plt.plot([str(i) for i in df1.Col1], df1.Col2) plt.subplot(1,3,2) plt.plot([str(i) for i in df2.Col1], df2.Col2) plt.subplot(1,3,3) plt.plot([str(i) for i in df3.Col1], df3.Col2) I tried the following: fig, axes = plt.subplots(nrows=1, ncols=3) plt.subplot(1,3,1) df1.plot(x='Col1',y='Col2',ax=axes[0,0]) plt.subplot(1,3,2) df2.plot(x='Col1',y='Col2',ax=axes[0,1]) plt.subplot(1,3,3) df3.plot(x='Col1',y='Col2',ax=axes[0,2]) But got this error: --------------------------------------------------------------------------- IndexError Traceback (most recent call last) &lt;ipython-input-113-b0fcf5cd6711&gt; in &lt;module&gt;() 2 3 plt.subplot(1,3,1) ----&gt; 4 df1.plot(x='Col1',y='Col2',ax=axes[0,0]) 5 6 plt.subplot(1,3,2) IndexError: too many indices for array And I get the exact same error for this as well: fig, axes = plt.subplots(nrows=1, ncols=3) df1.plot(x='Col1',y='Col2',ax=axes[0,0]) df2.plot(x='Col1',y='Col2',ax=axes[0,1]) df3.plot(x='Col1',y='Col2',ax=axes[0,2]) EDIT 2: Ok, I came across the first comment of this answer, and the following works…
tagged with: plot
has comment: http://stackoverflow.com/comment/90832093
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90832032
score: 1
tagged with: matplotlib
has title: How to order axes in matplotlib when the axis points are bins?
has comment: http://stackoverflow.com/comment/90832072
type: Question
tagged with: graph
upvote count: 1
has comment: http://stackoverflow.com/comment/90832013
downvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/90831950
tagged with: pandas
has answer: http://stackoverflow.com/a/51941192
accepted answer: http://stackoverflow.com/a/51941192
has comment: http://stackoverflow.com/comment/90832060

http://stackoverflow.com/comment/90715100
comment on: http://stackoverflow.com/a/51865643
type: Comment
has text: I also get another error code that says "ERROR: no more connections allowed (max_client_conn). It flips back and forth between that and the "ERROR: login rejected am i stuck" error message. I'm guessing that I'm guessing it's something to do with the syntax of my code since I wasn't getting that error message before.
score: 0
type: AnswerComment

http://stackoverflow.com/q/51803046
has body: I'm relatively new to Python, and I keep seeing examples like: def max_wordnum(texts): count = 0 for text in texts: if len(text.split()) &gt; count: count = len(text.split()) return count Is the repeated len(text.split()) somehow optimized away by the interpreter/compiler in Python, or will this just take twice the CPU cycles of storing len(text.split()) in a variable?
has answer: http://stackoverflow.com/a/51803116
accepted answer: http://stackoverflow.com/a/51803116
type: Question
possible better answer: http://stackoverflow.com/a/51803151
has title: Does Python automatically optimize/cache function calls?
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/90562394
score: 8
favorite count: 0
has comment: http://stackoverflow.com/comment/90562696
has answer: http://stackoverflow.com/a/51803151
upvote count: 8
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/51823857
tagged with: tensorflow
type: Question
has body: I am trying to understand tensorflow object detection config fields exactly. And according to this article(https://medium.com/@jonathan_hui/object-detection-speed-and-accuracy-comparison-faster-r-cnn-r-fcn-ssd-and-yolo-5425656ae359), for good balance between accuracy and speed, I changed first_stage_max_proposals from origin 100 to 50. Good news is, it indeed reduced the inference latency(from 4.2 seconds to 2.2 per image), however, bad news is it also decreases the accuracy. Then, I changed max proposals from 50 to 70, accuracy is better. So, I wanna know exactly what the max proposals controls. Does it related to any other config something like max_detections_per_class or max_total_detections .etc? I googled a lot but seems less upon this guy. I use python3.6.4 and tensorflow 1.8.0, and here is my model config: model { faster_rcnn { num_classes: 3 image_resizer { keep_aspect_ratio_resizer { min_dimension: 670 max_dimension: 1013 } } feature_extractor { type: "faster_rcnn_resnet101" first_stage_features_stride: 16 } first_stage_anchor_generator { grid_anchor_generator { height_stride: 16 width_stride: 16 scales: 0.25 scales: 0.5 scales: 1.0 scales: 2.0 aspect_ratios: 0.5 aspect_ratios: 1.0 aspect_ratios: 2.0 } } first_stage_box_predictor_conv_hyperparams { op: CONV regularizer { l2_regularizer { weight: 0.0 } } initializer { truncated_normal_initializer { stddev: 0.01 } } } first_stage_nms_score_threshold: 0.0 first_stage_nms_iou_threshold: 0.7 first_stage_max_proposals: 70 first_stage_localization_loss_weight: 2.0 first_stage_objectness_loss_weight: 1.0 initial_crop_size: 14 maxpool_kernel_size: 2 maxpool_stride: 2 second_stage_box_predictor { mask_rcnn_box_predictor { fc_hyperparams { op: FC regularizer { l2_regularizer { weight: 0.0 } } initializer { variance_scaling_initializer { factor: 1.0 uniform: true mode: FAN_AVG } } } use_dropout: false dropout_keep_probability: 1.0 } } second_stage_post_processing { batch_non_max_suppression { score_threshold: 0.3 iou_t…
answer count: 1
has answer: http://stackoverflow.com/a/51824126
score: 0
type: UnansweredQuestion
tagged with: python
has title: What does tensorflow object detection max proposals mean exactly?

http://stackoverflow.com/a/51947117
type: Answer
has comment: http://stackoverflow.com/comment/90844195
score: 7
has comment: http://stackoverflow.com/comment/90844232
upvote count: 7
accepted answer of: http://stackoverflow.com/q/51946916
has body: Add id attribute in FooSerializer serializer as: class FooSerializer(serializers.HyperlinkedModelSerializer): id = serializers.IntegerField(read_only=True) class Meta: model = Foo fields = '__all__'
answers question: http://stackoverflow.com/q/51946916
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/101809808

http://stackoverflow.com/comment/90844166
type: QuestionComment
type: Comment
has text: You can Check it now
comment on: http://stackoverflow.com/q/51947109
score: 0

http://stackoverflow.com/q/51956261
answer count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/51957297
favorite count: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/51956492
tagged with: python
has comment: http://stackoverflow.com/comment/90863402
score: 2
has body: I'm parsing data in a loop and once it's parsed and structured I would like to then add it to a data frame. The end format of the data frame I would like is something like the following: df: id 2018-01 2018-02 2018-03 234 2 1 3 345 4 5 1 534 5 3 4 234 2 2 3 When I iterate through the data in the loop I have a dictionary with the id, the month and the value for the month, for example: {'id':234,'2018-01':2} {'id':534,'2018-01':5} {'id':534,'2018-03':4} . . . What is the best way to take an empty data frame and add rows and columns with their values to it in a loop? Essentially as I iterate it would look something like this df: id 2018-01 234 2 then df: id 2018-01 234 2 534 5 then df: id 2018-01 2018-03 234 2 534 5 4 and so on...
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/66749579
has title: Pandas adding rows to df in loop
tagged with: dataframe
type: Question
upvote count: 2

http://stackoverflow.com/comment/90605973
has text: are you aware that the `Button` class accepts a `command` option?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51825850
score: 0

http://stackoverflow.com/a/51951480
upvote count: 1
answers question: http://stackoverflow.com/q/51951424
score: 1
type: AcceptedAnswer
downvote count: 0
has body: Two solutions, Threads https://en.wikibooks.org/wiki/Python_Programming/Threading or async like gevent http://sdiehl.github.io/gevent-tutorial/
type: Answer
accepted answer of: http://stackoverflow.com/q/51951424

http://stackoverflow.com/comment/90567878
type: Comment
has text: @Patwie Merging means concating them together. Yes, these CNN are pre-trained.
type: QuestionComment
comment on: http://stackoverflow.com/q/51804688
score: 0

http://stackoverflow.com/comment/90578547
comment on: http://stackoverflow.com/a/51811733
type: Comment
type: AnswerComment
has text: you can keep a a flat 1D list (`idx`). Then use a bit of logic to re-index where necessary.
score: 0

http://stackoverflow.com/q/51919407
downvote count: 0
possible better answer: http://stackoverflow.com/a/51920297
has answer: http://stackoverflow.com/a/51920297
favorite count: 0
has title: Why this answer passes Leetcode Q41
upvote count: 1
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51919442
score: 1
type: Question
tagged with: algorithm
answer count: 2
has body: Question here: https://leetcode.com/problems/first-missing-positive/description/ Your algorithm should run in O(n) time and uses constant extra space. I have a very naive solution that passes, since the question is marked as hard and most people's solution in discussion is much more complicated. def firstMissingPositive(self, nums): """ :type nums: List[int] :rtype: int """ if nums == []: return 1 for i in range(1, max(nums)+2): if i not in nums: return i find max uses O(n), since loop would stop once found the missing positive it would be O(n). range in py3 returns an iterable, every loop of the for statement produces the next number on the fly. So the time complexity should be O(n) space complexity is O(1) since only i is created I suppose the OJ only checks the correctness but not the space/ time complexity. However I cant see how this solution is wrong. Could anyone point it out?
has answer: http://stackoverflow.com/a/51919442

http://stackoverflow.com/q/51956357
downvote count: 1
has comment: http://stackoverflow.com/comment/90865431
type: Question
has comment: http://stackoverflow.com/comment/90865422
tagged with: robotframework
score: -1
has comment: http://stackoverflow.com/comment/90893779
has title: Selenium2library import for keyword access in robot framework
upvote count: 0
has answer: http://stackoverflow.com/a/51972080
answer count: 1
has comment: http://stackoverflow.com/comment/90893638
linked to: http://stackoverflow.com/q/32832629
has comment: http://stackoverflow.com/comment/90894658
favorite count: 0
has comment: http://stackoverflow.com/comment/90894842
has body: please note that attempt is to write python script and not in robot files I have two files api.py import requests from robot.libraries.BuiltIn import BuiltIn from robot.api import logger from robot.running.model import Keyword bi = BuiltIn() class APIRequests: ROBOT_LIBRARY_SCOPE = 'TEST CASE' def something(): return "some string/value" In the same folder, i have another file which I script robot file login.robot *** Settings *** Library BuiltIn Library api.py *** Test Cases *** Valid Weathercheck: ${abc} = something Log to console ${abc} When I execute from the command console robot login.robot I get an error message saying the 'No keyword with name 'something' found.' Query2 When we want to use some existing web driver modules which are existing in python , i am unable to find the needed documentation around it on how I can link/import them as ready keywords
has comment: http://stackoverflow.com/comment/90894193
tagged with: python
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/23703870

http://stackoverflow.com/comment/90660873
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51853992
type: Comment
has text: I mean type of the index, as the first column is the index and there is 0 1 2 ...

http://stackoverflow.com/q/51846188
has comment: http://stackoverflow.com/comment/90649416
answer count: 1
has comment: http://stackoverflow.com/comment/90646234
type: UnansweredQuestion
tagged with: python
has body: Using selenium I need to log in to the site with the current profile. I need the script to work for any random.default profile. Profile has a random name random.default for this I use os.listdir (). But apparently something is wrong. from selenium import webdriver from selenium.webdriver.common.keys import Keys import os default_username = os.getlogin() ffprofile = os.listdir('C:/users/'+default_username+'/AppData/Roaming/Mozilla/Firefox/Profiles/') fp = webdriver.FirefoxProfile('C:/users/'+default_username+'/AppData/Roaming/Mozilla/Firefox/Profiles/'+ffprofile) driver = webdriver.Firefox(fp) driver.get("http://google.com") received error: TypeError Traceback (most recent call last) &lt;ipython-input-15-1fd6227ccf4f&gt; in &lt;module&gt;() 4 default_username = os.getlogin() 5 ffprofile = os.listdir('C:/users/'+default_username+'/AppData/Roaming/Mozilla/Firefox/Profiles/') ----&gt; 6 fp = webdriver.FirefoxProfile('C:/users/'+default_username+'/AppData/Roaming/Mozilla/Firefox/Profiles/'+ffprofile) 7 driver = webdriver.Firefox(fp) 8 driver.get("http://google.com") TypeError: must be str, not list
tagged with: selenium-webdriver
has comment: http://stackoverflow.com/comment/90647683
tagged with: selenium
type: Question
has title: Selenium(python) webdriver authorization using default firefox profile on any PC
tagged with: firefox
score: 0
has answer: http://stackoverflow.com/a/51847297

http://stackoverflow.com/q/51846221
score: 1
upvote count: 1
type: Question
has body: This is the original table: A B C E 0 1 1 5 4 1 1 1 1 1 2 3 3 8 2 I wanted to apply some aggregate functions to this table which I did with: df.sort_values('C').groupby(['A', 'B'], sort=False).agg({'C': 'sum', 'E': 'last'}) My new table looks like this: A B C E 1 1 6 4 3 3 8 2 When I measure the column lenght of the original VS the modified table with this command len(df.columns) , the results differ though. The original table returns 4 columns and the modified table returns 2 columns. My question: Why did this happen and how can I get to return 4 columns with the modified table?
linked to: http://stackoverflow.com/q/21767900
has title: df.sort_values().groupby results in a column length issue
downvote count: 0
favorite count: 0
tagged with: python
duplicate of: http://stackoverflow.com/q/20461165
tagged with: python-3.x
duplicate of: http://stackoverflow.com/q/21767900
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/a/51925299
has comment: http://stackoverflow.com/comment/90820585
has comment: http://stackoverflow.com/comment/90802623
has comment: http://stackoverflow.com/comment/90802418
has comment: http://stackoverflow.com/comment/90807755
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/51925135
has comment: http://stackoverflow.com/comment/90807645
has comment: http://stackoverflow.com/comment/90809103
has comment: http://stackoverflow.com/comment/90808945
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51925135
has body: You could pass the value returned by the slider, to calculate a new value used as a parameter to your graph. Alternatively, you could use a mapping of the values from the sliders to the value you want to use. an (arguably contrived) example with functions that calculate and use a new value from the slider value: import numpy as np import matplotlib.pyplot as plt from matplotlib.widgets import Slider, Button, RadioButtons import math fig, ax = plt.subplots() plt.subplots_adjust(left=0.25, bottom=0.25) t = np.arange(0.0, 1.0, 0.001) a0 = 5 f0 = 3 delta_f = 5.0 s = a0 * np.sin(2 * np.pi * f0 * t) l, = plt.plot(t, s, lw=2, color='red') plt.axis([0, 1, -10, 10]) axcolor = 'lightgoldenrodyellow' axfreq = plt.axes([0.25, 0.1, 0.65, 0.03], facecolor=axcolor) axamp = plt.axes([0.25, 0.15, 0.65, 0.03], facecolor=axcolor) sfreq = Slider(axfreq, 'Freq', 0.1, 30.0, valinit=f0) #, valstep=delta_f) samp = Slider(axamp, 'Amp', 0.1, 10.0, valinit=a0) def get_amp_val(val): return math.exp(val) # replace with a meaningful transformation of your parameters def get_freq_val(val): return math.log(val) # replace with a meaningful transformation of your parameters def update(val): amp = get_amp_val(samp.val) # call a transform on the slider value freq = get_freq_val(sfreq.val) # call a transform on the slider value l.set_ydata(amp * np.sin(2 * np.pi * freq * t)) fig.canvas.draw_idle() sfreq.on_changed(update) samp.on_changed(update) plt.show() using a mapping: get_amp_val = {k, v for v, k in zip(values_you_want_to_use, slider_returned_values)} def update(val): amp = get_amp_val[samp.val] # retrieves the value mapped to the slider value ...
has comment: http://stackoverflow.com/comment/90802982
upvote count: 1
type: Answer

http://stackoverflow.com/comment/90809052
type: AnswerComment
comment on: http://stackoverflow.com/a/51929665
score: 0
type: Comment
has text: @Amadan, Good one.

http://stackoverflow.com/a/51801421
upvote count: 36
downvote count: 0
has body: There's no need to use the pandas for this. from openpyxl import Workbook import openpyxl file = "enter_path_to_file_here" wb = openpyxl.load_workbook(file, read_only=True) ws = wb.active for row in ws.iter_rows("E"): for cell in row: if cell.value == "ABC": print(ws.cell(row=cell.row, column=2).value) #change column number for any cell value you want
score: 36
answers question: http://stackoverflow.com/q/51800122
type: Answer

http://stackoverflow.com/comment/90770703
has text: So is what you are saying to replace self and _p2 with self.magnitude and point.magnitude respectively?
type: AnswerComment
type: Comment
score: 0
comment on: http://stackoverflow.com/a/51910179

http://stackoverflow.com/a/51942076
has comment: http://stackoverflow.com/comment/90834430
has comment: http://stackoverflow.com/comment/90834303
score: 0
has comment: http://stackoverflow.com/comment/90834582
has comment: http://stackoverflow.com/comment/90840858
has comment: http://stackoverflow.com/comment/90833846
has comment: http://stackoverflow.com/comment/90834873
has comment: http://stackoverflow.com/comment/90848128
type: Answer
has comment: http://stackoverflow.com/comment/90867846
has body: First, you want to be able to choose the script: available_scripts = [ 'example.com/1.py', 'example.com/2.py' # and etc. ] # List all scripts available print('Available scripts:') for ind, script in enumerate(available_scripts): print('[%s] %s' %(ind, script)) print('-' * 20) # Makes user choose one script_num =0 while True: try: script_num = int(input('Enter script number: ')) except ValueError: print('Invalid input, try again') continue if script_num &gt;= len(available_scripts) or script_num &lt; 0: print('Input out of range, try again') continue break script_url = available_scripts[script_num] filename = 'local_' + available_scripts[script_num].split('/')[-1] Now that we have the chosen script, we need to download it: import urllib.request urllib.request.urlretrieve(script_url, filename) And finally, we need to run it: import subprocess print('Running script #%s: %s' %(script_num, script_url.split('/')[-1])) subprocess.run(['python', filename]) Also, if you want to clean up after, you should remove the file: import os os.remove(filename)
has comment: http://stackoverflow.com/comment/90834106
answers question: http://stackoverflow.com/q/51941543

http://stackoverflow.com/q/51933300
score: 1
type: Question
has body: Let's say I have an image like this: For which I want to remove the border and get this: So exactly the same image, without the border. I found a "hacky" way to do it which finds the outer contour and draws a line over it... To be honest it's not the best way because I need to adjust the "thickness" of the line so that it is thick enough to cover up the border, but not too thick so it doesn't cover any of the circles. The image variable is the image you see above (already grayscaled, thresholded). cnts = cv2.findContours(image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) cnts = cnts[0] if imutils.is_cv2() else cnts[1] cv2.drawContours(image, cnts, -1, 0, 15) # 15 is the right thickness for this image, but might not be for other ones... The results is the 2nd picture above. Works great, but it doesn't work for ALL images (because of different thickness). Is there a better way to do this?
has comment: http://stackoverflow.com/comment/90817367
accepted answer: http://stackoverflow.com/a/51933482
has comment: http://stackoverflow.com/comment/90817150
favorite count: 0
answer count: 3
has answer: http://stackoverflow.com/a/51935570
has title: Python OpenCV: remove border from image
possible better answer: http://stackoverflow.com/a/51935570
has answer: http://stackoverflow.com/a/65301211
upvote count: 2
has comment: http://stackoverflow.com/comment/90816949
has answer: http://stackoverflow.com/a/51933482
tagged with: python
downvote count: 1
tagged with: opencv
type: AnsweredQuestion

http://stackoverflow.com/comment/90614112
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51829893
has text: How are you getting "HTML from website", is it the same as the `page` you're passing to bs4?
score: 0

http://stackoverflow.com/comment/90737386
type: QuestionComment
comment on: http://stackoverflow.com/q/51888009
score: 1
has text: Also you should use two capture groups in your regex, one for the number, one for the units. Then you should only need one `re.match` call, not two `re.findall` calls. See the doc for how to do that.
type: Comment

http://stackoverflow.com/a/51832487
score: 1
has comment: http://stackoverflow.com/comment/90642980
has body: IIUC wide_to_long pd.wide_to_long(df,'day',i=['date','name','favorite_color'],j='days',sep='_').\ rename(columns={'day':'value'}).\ reset_index() Out[1002]: date name favorite_color days value 0 1/9/2018 Tom Blue 1 27 1 1/9/2018 Tom Blue 2 28 2 1/9/2018 Tom Blue 3 45 3 1/9/2018 Tom Blue 4 30 4 1/10/2018 Stan Red 1 29 5 1/10/2018 Stan Red 2 13 6 1/10/2018 Stan Red 3 16 7 1/10/2018 Stan Red 4 5 8 1/11/2018 Rob Green 1 18 9 1/11/2018 Rob Green 2 7 10 1/11/2018 Rob Green 3 3 11 1/11/2018 Rob Green 4 4 Update tempdf= df.drop('count',1) df1=pd.wide_to_long(tempdf,'day',i=['date','name','favorite_color'],j='days',sep='_').\ rename(columns={'day':'value'}).\ reset_index() df2=df.set_index(['date','name','favorite_color'])'count'.stack().reset_index().rename(columns={'level_3':'days',0:'value'}) pd.concat([df1,df2]) Out[24]: date name favorite_color days value 0 1/9/2018 Tom Blue 1 27 1 1/9/2018 Tom Blue 2 28 2 1/9/2018 Tom Blue 3 45 3 1/9/2018 Tom Blue 4 30 4 1/10/2018 Stan Red 1 29 5 1/10/2018 Stan Red 2 13 6 1/10/2018 Stan Red 3 16 7 1/10/2018 Stan Red 4 5 8 1/11/2018 Rob Green 1 18 9 1/11/2018 Rob Green 2 7 10 1/11/2018 Rob Green 3 3 11 1/11/2018 Rob Green 4 4 0 1/9/2018 Tom Blue count 14 1 1/10/2018 Stan Red count 13 2 1/11/2018 Rob Green count 21
has comment: http://stackoverflow.com/comment/90639165
has comment: http://stackoverflow.com/comment/90642930
upvote count: 1
has comment: http://stackoverflow.com/comment/90640756
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51832453
answers question: http://stackoverflow.com/q/51832453
type: Answer
downvote count: 0

http://stackoverflow.com/comment/90675396
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51861577
has text: They are identical. Prefer the first alternative.
score: 0

http://stackoverflow.com/q/51931008
tagged with: python
tagged with: dictionary
downvote count: 1
type: Question
upvote count: 0
has body: I am exporting a script I have made in Python that sends commands to IP Addresses of projectors to shut them down. The functionality of the code works, and the projectors will shut down. The list of projectors is stored in a dictionary in a different file to the script to allow it to be edited and accessed by other scripts. Once I export my script to an exe using Pyinstaller v3.3.1 for Python 3.5.1, the .exe file no longer updates from the .py file that contains the dictionary, and instead has a version already stored in memory that I cannot update. How can I make the executable file still read from the dictionary and update every time it is run? Thanks, Josh Code: dictonaryfile.py (reduced for security, but format shown). projectors = { '1': '192.168.0.1' } Script that performs shutdown from pypjlink import Projector from file3 import projectors for item in projectors: try: myProjector = Projector.from_address(projectors[item]) myProjector.authenticate('PASSWORD REMOVED FOR SECURITY') state = myProjector.get_power() try: if state == 'on': myProjector.set_power('off') print('Successfully powered off: ', item) except: print('The projector in ', item, ', raised an error, shutdown may not have occurred') continue except: print(item, 'did not respond to state request, it is likely powered off at the wall.') continue
score: -1
has comment: http://stackoverflow.com/comment/90812510
answer count: 1
has answer: http://stackoverflow.com/a/51931276
has title: Updating database after exporting to EXE
tagged with: exe
favorite count: 0
type: UnansweredQuestion
tagged with: pyinstaller

http://stackoverflow.com/comment/90595654
type: AnswerComment
comment on: http://stackoverflow.com/a/51820786
type: Comment
has text: Will you please post sample of the image? That helps us to explore possibilities.
score: 1

http://stackoverflow.com/a/51905257
answers question: http://stackoverflow.com/q/51905129
downvote count: 0
has body: In the recent flask's update, from flask.ext.xxx import xxx has been removed. You should import it directly from its package. And here is a related issue. By the way, this package seems out of date(last updates two years ago).
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/comment/90823566
type: Comment
type: QuestionComment
has text: when you activate the environment do you get (p2) at the beginning of your terminal?
score: 0
comment on: http://stackoverflow.com/q/51936698

http://stackoverflow.com/q/51936253
has comment: http://stackoverflow.com/comment/90822581
has comment: http://stackoverflow.com/comment/90825587
has comment: http://stackoverflow.com/comment/90823972
tagged with: python
has comment: http://stackoverflow.com/comment/90825624
has comment: http://stackoverflow.com/comment/90822770
has comment: http://stackoverflow.com/comment/90845115
answer count: 0
has comment: http://stackoverflow.com/comment/90822720
type: UnansweredQuestion
upvote count: 1
has body: from datetime import datetime as time a = np.random.randn(10000, 64, 8) b = np.random.randn(8, 100) t1 = time.now() res1 = np.dot(a, b) t2 = time.now() res2 = np.zeros((10000, 64, 100)) for i in range(len(a)): res2[i] = a[i].dot(b) t3 = time.now() print('With loop: {}\nWithout: {}'.format((t3 - t2).total_seconds()*1000, (t2 - t1).total_seconds()*1000)) &gt;&gt;&gt;With loop: 562.9920000000001 &gt;&gt;&gt;Without: 2124.908 I chose the dimensions randomly, but they show the difference. Why is it so huge? Also as I increase dimensionality of arrays it only grows. With small dimensions np.dot without loop shows better perfomance than it does with one.
linked to: http://stackoverflow.com/q/33004551
has comment: http://stackoverflow.com/comment/90825708
type: Question
has comment: http://stackoverflow.com/comment/90822635
has comment: http://stackoverflow.com/comment/90822639
has comment: http://stackoverflow.com/comment/90844384
score: 1
duplicate of: http://stackoverflow.com/q/33004551
has comment: http://stackoverflow.com/comment/90845467
tagged with: numpy
has title: Why np.dot's perfomance in loop is better than without loop
has comment: http://stackoverflow.com/comment/90825681
downvote count: 0
has comment: http://stackoverflow.com/comment/90822510
favorite count: 0

http://stackoverflow.com/comment/90736987
type: Comment
has text: @WiktorStribiżew: Saw your comment a bit too late.
comment on: http://stackoverflow.com/q/51893013
score: 0
type: QuestionComment

http://stackoverflow.com/comment/90753504
score: 0
type: AnswerComment
has text: Thanks! It's ax.collections[1] with the full code I posted (including the army group paths). The safest general solution is probably to write `scatter = ax.collections[-1]` right after the plot command.
type: Comment
comment on: http://stackoverflow.com/a/51890764

http://stackoverflow.com/comment/90861653
type: QuestionComment
comment on: http://stackoverflow.com/q/51955386
has text: What should happen to an element in `df2` that does not contain anything from `df1`? What should if multiple elements in `df2` match a given element in `df1`?
score: 0
type: Comment

http://stackoverflow.com/q/51912858
has title: How can I export my python web scrape data to a specific sheet in an existing excel file using pandas?
accepted answer: http://stackoverflow.com/a/51913162
type: Question
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/51913162
has body: I have an Excel file with multiple sheets. I would like to add new data from Python to a new sheet in the same Excel file using pandas. Is this possible to do without affecting my previous data? I am new... Thanks for any help! Here is the Python code I am using so far: from urllib.request import urlopen from lxml import html import cssselect response = urlopen("https://www.xyz.com.shtml") content = response.read() tree = html.fromstring(content) for div in tree.cssselect('.first_name'): for a in div.cssselect('table:nth-child(2) a'): print(a.text) I found this online... I am just a little confused how to use it in my current situation: import pandas as pd df = pd.DataFrame({'Data': [10, 20, 30, 20, 15, 30, 45]}) writer = pd.ExcelWriter('pandas_simple.xlsx', engine='xlsxwriter') df.to_excel(writer, sheet_name='Sheet1') writer.save()
tagged with: css-selectors
tagged with: web-scraping
tagged with: python
tagged with: request
tagged with: excel
type: AnsweredQuestion

http://stackoverflow.com/comment/90857681
has text: Then add a view provider to it and create a Factory which creates your points in any coordinate
score: 1
comment on: http://stackoverflow.com/q/51953163
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/90610494
score: 1
has text: [Minimal, complete, verifiable example](http://stackoverflow.com/help/mcve) applies here. We cannot effectively help you until you post your MCVE code and accurately describe the problem. We should be able to paste your posted code into a text file and reproduce the problem you described.
type: QuestionComment
comment on: http://stackoverflow.com/q/51828044
type: Comment

http://stackoverflow.com/comment/90618077
score: 0
has text: use beautifulSoup ; for a in soup.find_all('input',{'value','Submit'}): ; print(a.get('type'))
comment on: http://stackoverflow.com/q/51831970
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51919916
type: Answer
answers question: http://stackoverflow.com/q/51918652
score: 0
has body: There is no code for actually writing to the file. Where and how are you writing the file? You don't have to add \n explicitly to have newlines. As lenik mentioned, you can use print(arg,file=file_obj) function (Python 3) from __future__ import print_function (Python 2) with file object as a parameter to write to the file. print will take care of appending new lines. Or if you absolutely need to have the strings appended to the list, you can iterate or use "\n".join(list) then write it to the file.

knapsack-problem
type: Tag
tag name: knapsack-problem
tags question: http://stackoverflow.com/q/51941993

http://stackoverflow.com/comment/90808823
type: QuestionComment
comment on: http://stackoverflow.com/q/51929528
score: 0
has text: @SamiKuhmonen what is the difference between dynamic calling and static calling? I mean aren't function names always fixed?
type: Comment

http://stackoverflow.com/comment/90754155
type: Comment
comment on: http://stackoverflow.com/a/51901458
score: 0
type: AnswerComment
has text: In my case it came with experience... I can't suggest books because I never used one...

http://stackoverflow.com/q/51924475
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51925942
has title: Rounding issue with python (implementing Karatsuba's algorithm)
has body: Having the hardest time figuring out rounding issue in my python code that is supposed to output the multiplied value of 2 numbers using Karatsuba's algorithm [1, 2]. This is my code: def mult(num1,num2): if num1 &lt; 10 or num2 &lt; 10: return int(num1*num2) else: n = len(str(num1)) a = int(str(num1)[:-(int(n/2))]) #print(a) c = int(str(num2)[:-(int(n/2))]) #print(c) b = int(str(num1)[-(int(n/2)):]) #print(b) d = int(str(num2)[-(int(n/2)):]) #print(d) val1 = mult(a,c) val2 = mult(b,d) val3 = mult(a+b,c+d) - val1 - val2 ans = val1*(10**int(n)) + val2 + (val3)*(10**(int(n/2))) return int(ans) I will add any additional info needed, please let me know Any help in this regards is much appreciated Thank you
type: Question
tagged with: rounding
score: 0
answer count: 1

http://stackoverflow.com/comment/90618624
type: Comment
type: QuestionComment
has text: `C:\Users\saviosebastian\MYD06_L2.A2008001.0000.006.2013341193524.hdf` is invalid as per you error.
score: 0
comment on: http://stackoverflow.com/q/51832304

http://stackoverflow.com/q/51944309
has body: I am using xlsxwriter to populate dataframe data to excel via the pandas to_excel function. However, the data populated has the prefix 'u' infront of the text displayed in excel. Output in Excel: [u'05-Sep-17'] [u'05-Sep-17'] I understand that 'u' is referring to unicode, are there any means to remove the 'u' prefix? I have tried the following but without any success so far. 1) Handle it via regex before calling the func to_excel() df.loc[:, 'delivery_dt'].replace({r'[^\x00-\x7F]+':''}, regex=True, inplace=True) The print statement gave the result I wanted but when it reaches the to_excel() stage, unicode 'u' prefix appeared in the final output in excel.
tagged with: pandas
accepted answer: http://stackoverflow.com/a/51945352
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python
has title: pandas with xlsxwriter encoding caused 'u' prefix to dataframe text
type: AnsweredQuestion
score: 1
tagged with: xlsxwriter
has answer: http://stackoverflow.com/a/51945352
upvote count: 1
type: Question

http://stackoverflow.com/comment/90724204
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51886156
has text: @Taylor - I looked at the site you mentioned, and found data only on the US. Are you sure there is also data for the rest of the world in it?
score: 0

http://stackoverflow.com/q/51860231
has comment: http://stackoverflow.com/comment/90678981
answer count: 1
downvote count: 0
favorite count: 0
has body: I could like to do a bi-directional communication between server and client. I end up with a problem. I am getting the host ip from server and then connecting to it. but i am not sure how to get it from one def to another. If i specify host ip directly it works. But i dont want it like that. Please post your idea. client program: import socket import os import re class cont(): def get_bd(self): def receive_bd(self): # receive broadcast def get_ip_data(ether_adapter): ip_data = os.popen("ifconfig " + ether_adapter) for line in ip_data: match2 = re.search(r'broadcast\s+(\d+.\d+.\d+.\d+)', line) if match2: bd = match2.group(1) return bd if __name__ == "__main__": ethernet_card = "wlp1s0" inet_list = get_ip_data(ethernet_card) # print(inet_list) self.sock.bind((inet_list, 12345)) msg, client = self.sock.recvfrom(1024) a = (msg.decode()) #here i receive the ip of my server to the client host = a def send_ls(self): #i want the host i received in that receive_bd as a host here host= "here?if i give direct ip of server it works which i dont want to do but directly get it from receive_bd " port=4343 address=host,port client=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) while (True): msg=input("Controller 1 :") client.sendto(bytearray(msg,"utf-8"),address) reply=client.recvfrom(1000) recved=str(reply) print("Main Controller: %s " %(recved)) if __name__=='__main__': c=cont() c.send_ls()
type: UnansweredQuestion
tagged with: sockets
tagged with: python
score: 2
upvote count: 2
tagged with: multithreading
has comment: http://stackoverflow.com/comment/90679448
type: Question
has title: Bi-directional udp communication does not work in python
has answer: http://stackoverflow.com/a/51866872
tagged with: udp
has comment: http://stackoverflow.com/comment/90677841

http://stackoverflow.com/a/51937397
score: 5
answers question: http://stackoverflow.com/q/51937351
accepted answer of: http://stackoverflow.com/q/51937351
type: AcceptedAnswer
has body: You may use re.findall(r'(?&lt;![a-z0-9&amp;])[a-z][0-9](?![a-z0-9&amp;])', s, re.I) See the regex demo Details (?&lt;![a-z0-9&amp;]) - a location that is not immediately preceded with an ASCII letter, digit or &amp; [a-z] - an ASCII letter (note that re.I makes the pattern case insensitive) [0-9] - an ASCII digit (?![a-z0-9&amp;]) - a location that is not immediately followed with an ASCII letter, digit or &amp;. Python demo: import re rx = r"(?&lt;![a-z0-9&amp;])[a-z][0-9](?![a-z0-9&amp;])" s = ".A3 S3- D4(SPACE) D5/ E9R E0&amp;" print(re.findall(rx, s, re.I)) # =&gt; ['A3', 'S3', 'D4', 'D5']
upvote count: 5
type: Answer
has comment: http://stackoverflow.com/comment/90829559
downvote count: 0
has comment: http://stackoverflow.com/comment/90833403

http://stackoverflow.com/comment/90843705
type: QuestionComment
has text: No its different
comment on: http://stackoverflow.com/q/51947109
score: 0
type: Comment

http://stackoverflow.com/comment/90731116
type: Comment
has text: Ah yes, makes sense. I didn't realize the top counted ranges are excluded from the following counts. I think that suits my purpose well. I can't thank you enough.
comment on: http://stackoverflow.com/a/51872822
type: AnswerComment
score: 0

http://stackoverflow.com/q/51913770
possible better answer: http://stackoverflow.com/a/51913957
accepted answer: http://stackoverflow.com/a/51913868
downvote count: 4
upvote count: 0
has comment: http://stackoverflow.com/comment/90777783
score: -4
tagged with: shapes
has answer: http://stackoverflow.com/a/51913868
type: AnsweredQuestion
has title: how to print shapes in python? looking into a different and more efficient way
has answer: http://stackoverflow.com/a/51913957
type: Question
has comment: http://stackoverflow.com/comment/90777544
answer count: 2
has comment: http://stackoverflow.com/comment/90777643
has body: Have tried many ways, such as printing line by line: print (" ------- ") print ("| |") print ("| |") print (" ------- ") Also with * , print ("********") print ("* ") print (" *") print ("********") Personally, I think the dashes (-) look more smooth than the stars(*). Any other ways to do this?
favorite count: 0
has comment: http://stackoverflow.com/comment/90777546
tagged with: python

http://stackoverflow.com/q/51903256
linked to: http://stackoverflow.com/q/24458645
upvote count: 2
tagged with: pandas
answer count: 1
favorite count: 0
has body: I am using sklearn's multilabelbinarizer() to train multiple columns in my machine learning which I use to train my model. After using it I noticed it was mixing up my data when it inverse transforms it. I created a test set of random values where I fit the data, transform it, and inverse_transform the data to get back to the original data. I ran a simple test in jupyter notebook to show the error: In the inverse_transformed value it messes up in row 1 mixing up the state and month. jupyter notebook code First of all, is there an error in how I use the multilabelbinarizer? Is there a different way to achieve the same output? EDIT: Thank you to @Nicolas M. for helping me solve my question. I ended up solving this issue like this. Forgive the rough explanation, but it turned out to be more complicated than I originally thought. I switched to using the label_binarizer instead of the multi_label_binarizer because it I ended up pickling the label_binarizer defaultdict so I can load it and use it in different modules for my machine learning project. One thing that might not be trivial is me adding new headers to dataframe I make for each column. It was in the form of column_name + column number. I did this because I needed to inverse transform the data. To do that I searched for the columns that contained the original column name which separated the larger dataframe into the individual column chunks. here some variables that I used and what they mean for reference: lb_dict - default dict that stores the different label binarizers. binarize_df - dataframe that stores the binarized data. binarized_label - label binarizes one label in the column. header - creates a new header form: column name + number column. inverse_df - dataframe that stores the inverse_transformed data. one_label_list - finds the list of column names with the original column tag. one_label_df - creates a new data frame that only stores the binarized data for one column. single_label - binarized data that…
has title: MultiLabelBinarizer mixes up data when inverse transforming
downvote count: 5
score: -3
tagged with: python
tagged with: multilabel-classification
tagged with: sklearn-pandas
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90759775
tagged with: machine-learning
type: Question
has answer: http://stackoverflow.com/a/51918575
accepted answer: http://stackoverflow.com/a/51918575

http://stackoverflow.com/a/51859936
downvote count: 0
type: Answer
score: 4
answers question: http://stackoverflow.com/q/51856844
upvote count: 4
has body: First ensure column ['Date'] is a datetime object and get a column to represent the difference in time from row to row df.Date = pd.to_datetime(df.Date) df['minD'] = (df.Date -df.Date.shift(1)).astype('timedelta64[m]') Next create a grouping key for your conditions. We shift down one row since we are looking for the time since last x and this can include the next x value as well. Without shifting, we would not include the next x in our group. mask2 = (df.indicator_1.str.cat(df.indicator_2) == 'yu').cumsum().shift(1) mask1 = (df.indicator_1 == 'x').cumsum().shift(1) Now groupby the masks and cumsum() the minute differences, but we need to filter out the cumsum() &lt; 1 of the boolean values since the condition has not yet happened, and thus there should be missing values for difference in time. df['desired_column_1'] = df.groupby(mask1.where(mask1 &gt; 0)).minD.cumsum() df['desired_column_2'] = df.groupby(mask2.where(mask2 &gt; 0)).minD.cumsum() Now you can replace the 0 values in those columns by forward filling the data df.desired_column_1 = df.desired_column_1.replace(0,method='ffill') df.desired_column_2 = df.desired_column_2.replace(0,method='ffill') This yeilds Date indicator_1 indicator_2 desired_column_1 \ 0 2013-04-01 03:50:00 x w NaN 1 2013-04-01 04:00:00 y u 10.0 2 2013-04-01 04:15:00 z v 25.0 3 2013-04-01 04:25:00 x w 35.0 4 2013-04-01 04:25:00 z u 35.0 5 2013-04-01 04:30:00 y u 5.0 6 2013-04-01 04:35:00 y w 10.0 7 2013-04-01 04:40:00 z w 15.0 8 2013-04-01 04:40:00 x u 15.0 9 2013-04-01 04:40:00 y v 15.0 10 2013-04-01 04:50:00 x w 10.0 desired_column_2 0 NaN 1 NaN 2 15.0 3 25.0 4 25.0 5 30.0 6 5.0 7 10.0 8 10.0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51856844

http://stackoverflow.com/comment/90862753
comment on: http://stackoverflow.com/q/51953046
score: 0
type: Comment
type: QuestionComment
has text: Your webserver has to be configured to set the `REMOTE_USER` environment variable, so Django could use it. From the docs: When the Web server takes care of authentication it typically sets the REMOTE_USER environment variable for use in the underlying application.

http://stackoverflow.com/a/51919438
upvote count: 41
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/97863460
has body: Kafka Streams is only available as a JVM library, but there are a few comparable Python implementations of it robinhood/faust (Not maintained as of 2020, but was forked) wintincode/winton-kafka-streams (appears not to be maintained) fluvii (see discussion) bytewax In theory, you could try playing with Jython or Py4j to work with the JVM implementation, but probably would require more work than necessary. Outside of those options, you can also try Apache Beam, Flink or Spark, but they each require an external cluster scheduler to scale out (and also require a Java installation). If you are okay with HTTP methods, then running a KSQLDB instance (again, requiring Java for that server) and invoking its REST interface from Python with the built-in SQL functions can work. However, building your own functions there will requiring writing JVM compiled code, last I checked. If none of those options are suitable, then you're stuck with the basic consumer/producer methods.
has comment: http://stackoverflow.com/comment/97834253
type: Answer
score: 41
downvote count: 0
has comment: http://stackoverflow.com/comment/97939310
answers question: http://stackoverflow.com/q/51918941
has comment: http://stackoverflow.com/comment/131200778
accepted answer of: http://stackoverflow.com/q/51918941
has comment: http://stackoverflow.com/comment/97867395

http://stackoverflow.com/comment/90805032
comment on: http://stackoverflow.com/q/51927650
has text: Your example is not well-expressed. If sentences contains both 'camera' and 'display', then it is unclear what should happen if there is also 'price', since the second if block will never be executed (already returned from previous block).
type: Comment
type: QuestionComment
score: 3

http://stackoverflow.com/a/51831248
score: 2
upvote count: 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51831202
answers question: http://stackoverflow.com/q/51831202
type: Answer
has body: Use expression: (?<=>)[^<:]+(?=:?<) (?<=>) Positive lookbehind for >. [^<:]+ Match anything other than < or :. (?=:?<) Positive lookahead for optional colon :, and <. You can try the expression live here. In Python: import re first_string = ' Foobar: ' second_string = ' Python ' print(re.findall(r'(?<=>)[^<:]+(?=:?<)',first_string)[0]) print(re.findall(r'(?<=>)[^<:]+(?=:?<)',second_string)[0]) Prints: Foobar Python Alternatively you could use expression: (?<=>)[a-zA-Z]+(?=\W*<) (?<=>) Positive lookbehind for >. [a-zA-Z]+ Lower and upper case letters. (?=\W*<) Positive lookahead for any non word characters followed by <. You can test this expression here. print(re.findall(r'(?<=>)[a-zA-Z]+(?=\W*<)',first_string)[0]) print(re.findall(r'(?<=>)[a-zA-Z]+(?=\W*<)',second_string)[0]) Prints: Foobar Python
downvote count: 0

http://stackoverflow.com/a/51891045
has body: You can try this too: ''.join(filter(lambda x: x != '#', '#foo')) # foo
upvote count: 1
score: 1
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51890199

http://stackoverflow.com/a/51824140
answers question: http://stackoverflow.com/q/51823648
accepted answer of: http://stackoverflow.com/q/51823648
score: 0
upvote count: 1
type: AcceptedAnswer
downvote count: 1
has body: discord.ClientUser is a class. You want the ClientUser instance that represents your bots user account. You can get this with bot.user, as commands.Bot is a subclass of Client @bot.command() async def userlist(ctx): for user in bot.user.friends: print (user.name+"#"+user.discriminator)
type: Answer

http://stackoverflow.com/comment/90607085
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51826143
has text: Thanks for the help. I'm a bit confused by the above use of `as_strided()`. How would one set up, as opposed to four 4x4 matrices above, 16 2x2 matrices?
type: AnswerComment

http://stackoverflow.com/comment/90796114
has text: Hello, thanks for checking the problem. I still get the same error like before. It goes well with the real browser.
score: 0
comment on: http://stackoverflow.com/a/51895622
type: Comment
type: AnswerComment

http://stackoverflow.com/q/51824443
has title: What purpose does passing Atom do when creating a python class for use with enaml?
score: 1
tagged with: enaml
has body: I'm trying to code my first GUI with Enaml and I can't figure out the reference to Atom when they're creating a class. I know it's an IDE (I'm using PyCharm) but I'm not sure if that's what it's even referencing. I can't find seem to find any helpful documentation online. Can you explain it to me in this example code from their documentation? I've formatted it below: class Person(Atom): """ A simple class representing a person object. """ last_name = Unicode() first_name = Unicode() age = Range(low=0) debug = Bool(False) @observe('age') def debug_print(self, change): """ Prints out a debug message whenever the person's age changes. """ if self.debug: templ = "{first} {last} is {age} years old." s = templ.format( first=self.first_name, last=self.last_name, age=self.age, ) print(s) I thought I should mention this isn't the entire file provided in the linked documentation! edit: I missed some helpful stuff on their github where I found more, albeit still lacking, documentation.
upvote count: 1
type: AnsweredQuestion
type: Question
has answer: http://stackoverflow.com/a/51849341
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/51849341
favorite count: 0
tagged with: python

http://stackoverflow.com/comment/90718410
has text: @mattalxndr, I have updated my answer to show the effect of the two assignment statements at the end of `reverse_list`.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51880117

http://stackoverflow.com/a/51845124
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51844487
answers question: http://stackoverflow.com/q/51844487
type: Answer
score: 1
upvote count: 1
has body: For efficiency, you should try and manipulate your data as you construct your dataframe rather than as a separate step. However, to split apart your dictionary keys and values you can use a combination of numpy.repeat and itertools.chain. Here's a minimal example: df = pd.DataFrame({'A': [1, 2], 'B': [{'key1': 'val0', 'key2': 'val9'}, {'key1': 'val1', 'key2': 'val2'}], 'C': [{'key3': 'val10', 'key4': 'val8'}, {'key3': 'val3', 'key4': 'val4'}]}) import numpy as np from itertools import chain chainer = chain.from_iterable lens = df['B'].map(len) res = pd.DataFrame({'A': np.repeat(df['A'], lens), 'B': list(chainer(df['B'].map(lambda x: x.values())))}) res.index = chainer(df['B'].map(lambda x: x.keys())) print(res) A B key1 1 val0 key2 1 val9 key1 2 val1 key2 2 val2
type: AcceptedAnswer

http://stackoverflow.com/q/51911864
has answer: http://stackoverflow.com/a/51911916
has comment: http://stackoverflow.com/comment/90773777
tagged with: python
answer count: 4
score: 2
type: AnsweredQuestion
upvote count: 2
has comment: http://stackoverflow.com/comment/90773890
type: Question
has answer: http://stackoverflow.com/a/51911913
has comment: http://stackoverflow.com/comment/90774036
has answer: http://stackoverflow.com/a/51911925
has comment: http://stackoverflow.com/comment/90773954
has answer: http://stackoverflow.com/a/51911894
has title: How to make a class object iterable
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/51911925
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90774006
has body: I have the following point class: import math class Point: """Two-Dimensional Point(x, y)""" def __init__(self, x=0, y=0): # Initialize the Point instance self.x = x self.y = y # def __iter__(self): # return iter(int(self.x)) # return iter(int(self.y)) return self @property def magnitude(self): # """Return the magnitude of vector from (0,0) to self.""" return math.sqrt(self.x ** 2 + self.y ** 2) def distance(self, self2): return math.sqrt((self2.x - self.x) ** 2 + (self2.y - self.y) ** 2) def __str__(self): return 'Point at ({}, {})'.format(self.x, self.y) def __repr__(self): return "Point(x={},y={})".format(self.x, self.y) I want to make 'points' iterable so that the following is possible: point = Point(2, 3) x, y = point print(x) 2 print(y) 3 If you see my commented code, that is what I attempted but it says TypeError: iter() returned non-iterator of type 'Point'. Any ideas on how to correctly do this?
possible better answer: http://stackoverflow.com/a/51911916

http://stackoverflow.com/comment/90609098
type: QuestionComment
has text: Although `input` is always a string and so needs to be converted to a `float`, you're going to hit issues comparing float values; what is the correct answer for `8/3`? Even without the general floating point issues, what answer would be acceptable from the user here?
comment on: http://stackoverflow.com/q/51827374
score: 0
type: Comment

http://stackoverflow.com/q/51887465
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90726408
has title: find token between two delimiters - discord emotes
accepted answer: http://stackoverflow.com/a/51902676
answer count: 1
favorite count: 0
tagged with: python-3.x
tagged with: python
tagged with: discord
score: 0
upvote count: 1
has answer: http://stackoverflow.com/a/51902676
downvote count: 1
has body: i am trying to recognise discord emotes. They are always between two : and don't contain space. e.g. :smile: I know how to split strings at delimiters, but how do i only split tokens that are within exactly two : and contain no space? Thanks in advance!
has comment: http://stackoverflow.com/comment/90756407
type: Question
has comment: http://stackoverflow.com/comment/90743384

http://stackoverflow.com/a/51933252
has comment: http://stackoverflow.com/comment/90816576
type: Answer
answers question: http://stackoverflow.com/q/51933210
has body: You are looping 10 times with for x in range(0,10, 1): So the single match is printed 10 times.
score: 2
upvote count: 3
downvote count: 1

http://stackoverflow.com/comment/90849901
comment on: http://stackoverflow.com/q/51948209
has text: Does this help: https://stackoverflow.com/a/37571199/2064981
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/51953680
type: AnsweredQuestion
score: 1
has title: How to draw four subplots with a double y-axis plot in it
upvote count: 1
has body: I have successfully drawn the four subplots. Later, I wanted on of the subplot to have double yy plot (one x axis and two y axis plot). After a series of trials by adding new code , I did got it. But, problem is, a fifth empty plot has popped up. Please, check below screen shot. Required part of My code is given below: fig, axs = plt.subplots(2, 2, figsize=(14, 10)) fig, add_ax = plt.subplots() plt.rc('font',family='Times New Roman') . . # yy axis plot in fourth subplot add_ax = axs[1][1].twinx() axs[1][1].set_xlabel('Irradiance (W/m^2)', fontsize=16) axs[1][1].set_ylabel('Power (W)', fontsize=16) add_ax.set_ylabel('Module temperature (Deg. C)', fontsize=16) for i,j in zip(IV_start_index,IV_start_index[1:]): # This is simple code to access present and next element in a list . . . axs[1][1].plot(module_allData_df['Irradiance'].iloc[i],p_mpp,'go') add_ax.plot(module_allData_df['Irradiance'].iloc[i],module_allData_df['Temperature'].iloc[i],'bo') plt.suptitle('A NIST Module %s day normalized IV curves '%(module_allData_df['Time'].loc[i].strftime('%Y-%m-%d')),fontsize=18) # plt.savefig('All_day_normalized_IV_plot') Some where, my code is wrong. I have modified my code as per @Bazingaa answer which I accepted below and it solved my problem. Below is the final figure.
type: Question
accepted answer: http://stackoverflow.com/a/51954105
tagged with: matplotlib
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51954105
tagged with: python

homebrew
tags question: http://stackoverflow.com/q/51906096
tag name: homebrew
tags question: http://stackoverflow.com/q/51865823
type: Tag

membership
tag name: membership
tags question: http://stackoverflow.com/q/51903617
type: Tag

http://stackoverflow.com/comment/122913970
type: AnswerComment
has text: For me actually worked out install on VSC this extension https://marketplace.visualstudio.com/items?itemName=ms-toolsai.vscode-ai
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51922482

http://stackoverflow.com/a/52430239
answers question: http://stackoverflow.com/q/51823123
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51823123
type: Answer
has body: I solved this by writing in a special way with the help of multiprocessing.manager.BaseManager So everything is running as it should!

http://stackoverflow.com/q/51801528
tagged with: pandas
has title: Pandas to open json file JSON -ValueError: Expected object or value
upvote count: 1
answer count: 1
linked to: http://stackoverflow.com/q/4750806
favorite count: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/27240982
tagged with: python
has comment: http://stackoverflow.com/comment/101219965
has body: I have the following simple json in a file saved as notepad file t.json [{"a": 1, "b": 2, "c": 3}, {"a": 4, "b": 5, "c": 6}, {"a": 7, "b": 8, "c": 9}] I am trying to open it using ValueError Traceback (most recent call last) &lt;ipython-input-236-487720f2328b&gt; in &lt;module&gt;() ----&gt; 1 data = pd.read_json('t.json') ~\Anaconda3\lib\site-packages\pandas\io\json\json.py in read_json(path_or_buf, orient, typ, dtype, convert_axes, convert_dates, keep_default_dates, numpy, precise_float, date_unit, encoding, lines, chunksize, compression) 420 return json_reader 421 --&gt; 422 result = json_reader.read() 423 if should_close: 424 try: ~\Anaconda3\lib\site-packages\pandas\io\json\json.py in read(self) 527 ) 528 else: --&gt; 529 obj = self._get_object_parser(self.data) 530 self.close() 531 return obj ~\Anaconda3\lib\site-packages\pandas\io\json\json.py in _get_object_parser(self, json) 544 obj = None 545 if typ == 'frame': --&gt; 546 obj = FrameParser(json, **kwargs).parse() 547 548 if typ == 'series' or obj is None: ~\Anaconda3\lib\site-packages\pandas\io\json\json.py in parse(self) 636 637 else: --&gt; 638 self._parse_no_numpy() 639 640 if self.obj is None: ~\Anaconda3\lib\site-packages\pandas\io\json\json.py in _parse_no_numpy(self) 851 if orient == "columns": 852 self.obj = DataFrame( --&gt; 853 loads(json, precise_float=self.precise_float), dtype=None) 854 elif orient == "split": 855 decoded = {str(k): v for k, v in compat.iteritems( ValueError: Expected object or value I have tried creating an absolute path as per the suggestion in this page but it also produces a value error. Can anyone help please?
downvote count: 0
score: 1
tagged with: http://stackoverflow.com/tag/json
type: Question
linked to: http://stackoverflow.com/q/44597662
has answer: http://stackoverflow.com/a/51801902

http://stackoverflow.com/q/51878148
tagged with: django
tagged with: python
has body: I have my apache config set up to point to my virtualenv, but when i load the page and look at the error log it gives the following error: from django.core.wsgi import get_wsgi_application ImportError: No module named django.core.wsgi apache2 000-default.conf file: WSGIDaemonProcess project python-home=/home/django/config/env python-path=/usr/local/bfx/Databases/project WSGIProcessGroup project WSGIScriptAlias / /usr/local/bfx/Databases/project/project/wsgi.py Basically, it will work if I install django, and all my django packages on my server, but what is the point of the virtual env? Thanks
has answer: http://stackoverflow.com/a/51879973
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90707832
has comment: http://stackoverflow.com/comment/90708146
upvote count: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/90708112
has title: What is the point of a django virtualenv, if when deploying with apache, wsgi.py is executed on the server NOT in the virtualenv?
has comment: http://stackoverflow.com/comment/90707619
tagged with: apache2
score: 0
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/51879973
has comment: http://stackoverflow.com/comment/90707571

http://stackoverflow.com/comment/90696206
type: Comment
has text: I am answering the OP. He wants to remove all punctuation marks. `!` is a punctuation mark.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51872382

http://stackoverflow.com/q/51851011
has answer: http://stackoverflow.com/a/51855878
downvote count: 0
has comment: http://stackoverflow.com/comment/90685631
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/90655831
accepted answer: http://stackoverflow.com/a/51855878
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90677921
score: 1
has comment: http://stackoverflow.com/comment/90655912
has comment: http://stackoverflow.com/comment/90655573
upvote count: 1
tagged with: memory
has body: I have two large data frames called df0 (120 million obs) and df1 (50 million obs). They have the same 44 variables (as columns). I need to append the data so that the new data frame has 120+50 = 170 million observations and 44 columns. I use: frames = [df0, df1] df = pd.concat(frames, ignore_index=True) or df = df0.append(df1, ignore_index=True) They work just fine. But when I delete df0 and df1 using del df0 del df1 the system does not release the memory. I've read on stackoverflow that this is typical for python/other languages. However, I run into memory issues after this and python does not release this memory. Any suggestions on how to avoid having so much memory eaten up? SOLVED: As juanpa.arrivillaga pointed out, a surviving reference will mean the data frame will not be deleted. Once I deleted all references to the data frame, the memory is freed up once the data frame is deleted.
type: Question
has title: Delete data frame but still lose memory
has comment: http://stackoverflow.com/comment/90655196
has comment: http://stackoverflow.com/comment/90655884
tagged with: pandas

http://stackoverflow.com/comment/90583766
type: QuestionComment
has text: @Sathya `pip.conf` was only changing faster China-based mirrors. I will add it in the post for sure
type: Comment
score: 0
comment on: http://stackoverflow.com/q/51807743

http://stackoverflow.com/q/51839299
answer count: 1
has comment: http://stackoverflow.com/comment/90631602
type: UnansweredQuestion
tagged with: python
tagged with: loops
tagged with: scrapy
has title: Python - Scrapy crawling the web
type: Question
has body: well here is my project/spider , works fine.... # -*- coding: utf-8 -*- import scrapy import time class SccbotakiSpider(scrapy.Spider): name = 'SccBotaki' start_urls = ['url'] time.sleep(1) def parse(self, response): daten = response.css('#daten').extract() cartext = response.css('div.car_header &gt; b::text').extract() spacerimg = response.css('div.rechts &gt; img::attr(src)').extract() inhalt = response.css('div.inhalt') prodname = inhalt.css('div.prod-name::text').extract() artnr = inhalt.css('div.art-nr &gt; span::text').extract() avaible = inhalt.css('div.ampel &gt; img::attr(src)').extract() price = inhalt.css('div.preis::text').extract() for item in zip(prodname,artnr,avaible,price): scraped_info = { 'prodname' : item[0] , 'artnr' : item[1] , 'avaible' : item[2] , 'price' : item[3] , } yield scraped_info check out the url inside of image because i cannot use tiny url inside this post URL Image but i wanted to scrape daten,cartext,spacerimg aswell im gonna get different/bad results btw in settings.py i did like that to export into csv file: #Export as CSV Feed FEED_FORMAT = "csv" FEED_URI = "UltraRacing.csv" so, my question is why i cannot scrape like my image when im adding "daten,cartext,spacerimg"? if i did scrape all of them together im gonna get in csv just 1 row with all of the informations in 1 cell and if ill remove the "daten,cartext,spacerimg from the loop", ill get the perfect results.... hope this make sense...
has answer: http://stackoverflow.com/a/51842130
score: 0

http://stackoverflow.com/a/51834974
score: 0
type: Answer
has body: Try changing gray = cv2.cvtColor(frame.array, cv2.COLOR_BGR2GRAY)[1] to simply gray = cv2.cvtColor(frame.array, cv2.COLOR_BGR2GRAY)
has comment: http://stackoverflow.com/comment/90670431
answers question: http://stackoverflow.com/q/51827788
accepted answer of: http://stackoverflow.com/q/51827788
has comment: http://stackoverflow.com/comment/90643681
type: AcceptedAnswer

http://stackoverflow.com/a/52020495
downvote count: 1
has comment: http://stackoverflow.com/comment/91003175
has comment: http://stackoverflow.com/comment/90991472
score: -1
has comment: http://stackoverflow.com/comment/91012721
upvote count: 0
has comment: http://stackoverflow.com/comment/91110170
has comment: http://stackoverflow.com/comment/90999528
has comment: http://stackoverflow.com/comment/91021406
has body: You can not run a specific Python function as root, only the Python process executing your script can be run with elevated permissions. So my answer is: your problem as described is unsolvable.
answers question: http://stackoverflow.com/q/51801282
type: Answer

http://stackoverflow.com/comment/90773890
comment on: http://stackoverflow.com/q/51911864
type: QuestionComment
has text: All of the below answers are correct. Is there a specific one which has the most advantages
score: 0
type: Comment

http://stackoverflow.com/comment/90725691
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51876511
has text: the images are labeled according to the name of the directory. In my case, I have 'correct' file and 'wrong' file. I checked the labels with `ImageDataGenerator.class_indices` and it seems like it ok here.
score: 0

http://stackoverflow.com/q/51865716
tagged with: python
has comment: http://stackoverflow.com/comment/90683936
has title: SqlAlchemy - How update a reference to a foreign table via associationproxy?
answer count: 0
type: Question
has comment: http://stackoverflow.com/comment/90683647
tagged with: sqlalchemy
score: 0
tagged with: foreign-keys
tagged with: many-to-one
has body: I have an association_proxy set up on a Fruit class that references a FruitStatus class: Fruit.status = association_proxy('statusObject', 'name'). I'd like to be able to change a Fruit's status field without there being an UPDATE on the FruitStatuses table. Currently, if I instantiate a new Fruit with something like, then change the status, the row in FruitStatuses gets updated, instead of the foreign key in Fruit being updated: # Create an apple that's 'good' apple = Fruit(name='apple', status='good') session.merge(apple) session.commit() # Shows: (1, good), (2, rotten) print(session.query(FruitStatus).all()) # Update the status to 'rotten' apple.status = 'rotten' session.merge(apple) session.commit() print(session.query(FruitStatus).all()) # Shows: (1, rotten), (2, rotten) I'd like for the reference to change to the row whose foreign key is 2, rather than update the original row. Below is a full working example. from sqlalchemy import * from sqlalchemy.orm import * from sqlalchemy.ext.associationproxy import association_proxy metadata = MetaData() fruitStatusTable = Table( 'FruitStatuses', metadata, Column('status_id', Integer, primary_key=True, unique=True), Column('name', String(256)) ) fruitsTable = Table( 'Fruits', metadata, Column('fruit_id', Integer, primary_key=True), Column('status_id', Integer, ForeignKey('FruitStatuses.status_id')), Column('name', String(256)), Column('revision', Integer, nullable=False) ) class FruitStatus(object): def __init__(self, *args, **kwds): for key in kwds: setattr(self, key, kwds[key]) pass return def __repr__(self): return "{}&lt;status_id={}, name={}&gt;".format(self.__class__.__name__, self.status_id, self.name) class Fruit(object): def __init__(self, *args, **kwds): for key in kwds: setattr(self, key, kwds[key]) pass return def __repr__(self): ret = [] for key in sorted(self.__dict__): if key == '_sa_instance_state': continue ret.append("{}: {}".format(key, self.__dict__[key])) pass return "{}&lt;{}&gt;".format(self.__clas…
type: UnansweredQuestion

http://stackoverflow.com/comment/90741266
comment on: http://stackoverflow.com/q/51895280
score: 1
has text: are you maybe doing something like `wordlist = wordlist.append('new_text')` further up?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90813392
has text: It does but you are right it is not save raw_input would be much saver
comment on: http://stackoverflow.com/a/51931631
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/90556765
has text: @Tim thank u man..!!! i was so dumb i couldn't find mistake your suggestion worked for me , thanx a lot
score: 0
comment on: http://stackoverflow.com/q/51800027
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90583032
comment on: http://stackoverflow.com/q/51814121
score: 0
type: Comment
type: QuestionComment
has text: Print after return will not execute

http://stackoverflow.com/q/51910391
type: AnsweredQuestion
score: 2
accepted answer: http://stackoverflow.com/a/51914046
downvote count: 2
tagged with: python-requests
type: Question
has answer: http://stackoverflow.com/a/51914046
has body: I'm trying to use Requests to proxy requests sent to a Flask endpoint to another URL. I want to pass on any data that's posted, so I use json=get_json() in requests.post. However, when the initial request is GET, it doesn't have any JSON, so I get a 400 error with "Failed to decode JSON object: Expecting value: line 1 column 1 (char 0)". I tried json=request.data instead, but I get "TypeError: Object of type 'bytes' is not JSON serializable". How can I get the data without assuming it's JSON? How can I pass the data to Requests without assuming it's JSON? from flask import request import requests @app.route("/pas/&lt;path:arg&gt;", methods=("GET", "POST", "PUT", "DELETE")) def proxy(arg): url = f"http://{config.pasUrl}:{config.pasPort}/{arg}?{request.query_string.decode('utf-8')}" out_request = requests.request( method=request.method, url=url, headers=request.headers, json=request.get_json(), ) return out_request.text
tagged with: flask
upvote count: 4
answer count: 1
favorite count: 0
has title: Issues performing URL Rewrite using Python's Requests library
tagged with: python

http://stackoverflow.com/q/51913956
type: AnsweredQuestion
score: 2
linked to: http://stackoverflow.com/q/20461336
type: Question
downvote count: 0
has title: Kivy: user touch and drag for cropping function
has answer: http://stackoverflow.com/a/51920033
has body: I'm attempting to crop an image. The basic idea is that the user will drag his mouse over the image to crop it. To that end, when you click "Crop", the user can select a lower left point, then drag the rectangle up to the top right. The rectangle should shade the outside area not selected. I've been researching Drag behavior and simpler methods such as this answer (attempted below), but with little results. As a bonus, is it possible to limit the area the user can touch and drag? from kivy.lang import Builder from kivy.app import App from kivy.uix.widget import Widget from kivy.graphics import Rectangle from kivy.graphics import Color from kivy.graphics import Point from kivy.properties import NumericProperty, ObjectProperty from kivy.uix.screenmanager import ScreenManager, Screen Builder.load_string(""" &lt;MyScreenManager&gt;: ThirdScreen: id: third_screen &lt;ThirdScreen&gt;: name: '_third_screen_' id: third_screen BoxLayout: orientation: "vertical" id: third_screen_boxlayout Label: id: main_title text: "Title" size_hint: (1, 0.1) BoxLayout: id: image_box_layout Image: id: main_image source: "C:/Users/OneDrive/0. T2/6. Kivy/4/claymore.jpg" BoxLayout: id: button_boxlayout orientation: "horizontal" padding: 10 size_hint: (1, 0.15) Button: id: accept_button text: "Okay" size_hint: (0.33, 1) on_press: root.image_accepted_by_user(root.image_address) Button: id: crop_button text: "Crop" size_hint: (0.33, 1) on_press: root.enable_cropping() Button: id: cancel_button text: "Cancel" size_hint: (0.33, 1) on_press: root.manager.current = '_first_screen_' """) class MyScreenManager(ScreenManager): pass class ThirdScreen(Screen): def enable_cropping(self): print("\nThirdScreen:") print(self.ids.main_image.pos) print(self.ids.main_image.size) print("\tAbsolute size=", self.ids.main_image.norm_image_size) print("\tAbsolute pos_x=", self.ids.main_image.center_x - self.ids.main_image.norm_image_size[0] / 2.) print("\tAbsolute pos_y=", self.ids.main_image.center_y - self.ids.main_…
answer count: 1
tagged with: kivy
favorite count: 0
tagged with: kivy-language
upvote count: 2
tagged with: python
accepted answer: http://stackoverflow.com/a/51920033

http://stackoverflow.com/comment/90854973
comment on: http://stackoverflow.com/q/51949163
score: 0
type: Comment
type: QuestionComment
has text: It would require ~122GB of RAM in `float32`. I'll stick with `uint8` for the moment :-) but thanks for the remark

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

http://stackoverflow.com/comment/90643100
has text: Thats it working now, thanks for the help mate. Have a good day.
type: Comment
comment on: http://stackoverflow.com/a/51843964
score: 0
type: AnswerComment

http://stackoverflow.com/comment/90734382
comment on: http://stackoverflow.com/a/51891531
score: 0
type: AnswerComment
type: Comment
has text: Yes, I agree. I've updated my answer. The idea is that I thought writing his code with the same style with pointing out the problem, would explain things to him better.

django
tags question: http://stackoverflow.com/q/51915687
tags question: http://stackoverflow.com/q/51801511
tags question: http://stackoverflow.com/q/51928023
tags question: http://stackoverflow.com/q/51949189
tags question: http://stackoverflow.com/q/51860222
tags question: http://stackoverflow.com/q/51852131
tags question: http://stackoverflow.com/q/51954549
tags question: http://stackoverflow.com/q/51906346
tags question: http://stackoverflow.com/q/51951876
tags question: http://stackoverflow.com/q/51877837
tags question: http://stackoverflow.com/q/51892193
tags question: http://stackoverflow.com/q/51943555
tags question: http://stackoverflow.com/q/51862924
tags question: http://stackoverflow.com/q/51846572
tags question: http://stackoverflow.com/q/51946341
tags question: http://stackoverflow.com/q/51896025
tags question: http://stackoverflow.com/q/51915943
tags question: http://stackoverflow.com/q/51818204
tags question: http://stackoverflow.com/q/51920695
tags question: http://stackoverflow.com/q/51927603
tags question: http://stackoverflow.com/q/51910667
tags question: http://stackoverflow.com/q/51825212
tags question: http://stackoverflow.com/q/51830831
tags question: http://stackoverflow.com/q/51929531
tags question: http://stackoverflow.com/q/51947561
tags question: http://stackoverflow.com/q/51852455
tags question: http://stackoverflow.com/q/51836887
tags question: http://stackoverflow.com/q/51943578
tags question: http://stackoverflow.com/q/51834217
tags question: http://stackoverflow.com/q/51805867
tags question: http://stackoverflow.com/q/51830948
tags question: http://stackoverflow.com/q/51942404
tags question: http://stackoverflow.com/q/51805464
tags question: http://stackoverflow.com/q/51942120
tags question: http://stackoverflow.com/q/51867526
tags question: http://stackoverflow.com/q/51904737
tags question: http://stackoverflow.com/q/51939726
tags question: http://stackoverflow.com/q/51902019
tags question: http://stackoverflow.com/q/51905712
tags question: http://stackoverflow.com/q/51818252
tags question: http://stackoverflow.com/q/51809849
tags question: http://stackoverflow.com/q/51806580
tags question: http://stackoverflow.com/q/51917799
tags question: http://stackoverflow.com/q/51815161
tags question: http://stackoverflow.com/q/51881276
tags question: http://stackoverflow.com/q/51814066
tags question: http://stackoverflow.com/q/51901655
tags question: http://stackoverflow.com/q/51812656
tags question: http://stackoverflow.com/q/51933083
tags question: http://stackoverflow.com/q/51889294
tags question: http://stackoverflow.com/q/51941830
type: Tag
tags question: http://stackoverflow.com/q/51815306
tags question: http://stackoverflow.com/q/51846183
tags question: http://stackoverflow.com/q/51899546
tags question: http://stackoverflow.com/q/51922396
tags question: http://stackoverflow.com/q/51815459
tags question: http://stackoverflow.com/q/51851434
tags question: http://stackoverflow.com/q/51869434
tags question: http://stackoverflow.com/q/51813570
tags question: http://stackoverflow.com/q/51889933
tags question: http://stackoverflow.com/q/51920779
tags question: http://stackoverflow.com/q/51903927
tags question: http://stackoverflow.com/q/51829364
tags question: http://stackoverflow.com/q/51873093
tags question: http://stackoverflow.com/q/51873513
tags question: http://stackoverflow.com/q/51947018
tags question: http://stackoverflow.com/q/51844260
tags question: http://stackoverflow.com/q/51838887
tags question: http://stackoverflow.com/q/51899335
tags question: http://stackoverflow.com/q/51862796
tags question: http://stackoverflow.com/q/51878839
tags question: http://stackoverflow.com/q/51827609
tags question: http://stackoverflow.com/q/51850065
tags question: http://stackoverflow.com/q/51834431
tags question: http://stackoverflow.com/q/51912227
tags question: http://stackoverflow.com/q/51941255
tags question: http://stackoverflow.com/q/51799125
tags question: http://stackoverflow.com/q/51923867
tags question: http://stackoverflow.com/q/51855147

http://stackoverflow.com/comment/91135196
comment on: http://stackoverflow.com/q/51844679
has text: @abarnert the solution to this was to re-write so that the process just passes the file location, as you said. However this means I cannot make my temp file auto-delete which could cause clean up issues. I think the better solution may be to restrucure so that each process is running the full analysis on a set of files, then returning the result. This is a bit of a re-write though, so I think this issue can be closed, do you want to post your answers?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51893702
has body: I wonder if the following can be done better: import numpy as np def label_items(items): data = np.array(items) labels = np.zeros(len(items), dtype='int') for label, value in enumerate(set(items)): labels[data==value] = label return labels for example: label_items(['a', 'a', 'c', 'd', 'e', 'b', 'e', 'e', 'd', 'c']) will return array([0, 0, 1, 4, 3, 2, 3, 3, 4, 1]) Addendum: the letters are merely an example, it could be a list of anything. That's why I called the function "label_items". The order of the labels doesn't matter.
tagged with: python
accepted answer: http://stackoverflow.com/a/51893769
type: AnsweredQuestion
score: 2
tagged with: list
upvote count: 2
has comment: http://stackoverflow.com/comment/90738381
has answer: http://stackoverflow.com/a/51893757
has answer: http://stackoverflow.com/a/51893769
type: Question
tagged with: numpy
tagged with: algorithm
has comment: http://stackoverflow.com/comment/90738407
answer count: 2
has title: How to create a list of labels for a list of items?
has comment: http://stackoverflow.com/comment/90738442
downvote count: 0
linked to: http://stackoverflow.com/q/3172509
possible better answer: http://stackoverflow.com/a/51893757
favorite count: 0
has comment: http://stackoverflow.com/comment/90738199

http://stackoverflow.com/q/51815641
tagged with: python
has body: I am trying to optimize using cvxpy. w=cvxpy.Variable((10,1)) cvxpy.kron(w,w) this is not working saying that first argument should be constant, and then I tried to use numpy numpy.kron(w,w) and then, it says that incompatible dimensions (10,1) (10,1) shouldn't it work?? How should I do the kronecker product on it
type: AnsweredQuestion
score: 1
has title: Python CVXPY kronecker product dimensions
upvote count: 1
has answer: http://stackoverflow.com/a/52306787
type: Question
tagged with: cvxpy
accepted answer: http://stackoverflow.com/a/52306787
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/q/51942665
has comment: http://stackoverflow.com/comment/90836072
downvote count: 0
answer count: 1
has title: Selenium in Python. When launching the test, a message about the auxiliary class pops up
has body: I have a problem with the helper class when running the test. As it is only in the Contakt class: class Contact: def __init__(self, firstname, middlename, lastname, nickname): self.firstname = firstname self.middlename = middlename self.lastname = lastname self.nickname = nickname it's all ok and the test works. And how will I do it: class Contact: def __init__(self, firstname, middlename, lastname, nickname, title_photo, email, email2, email3): self.firstname = firstname self.middlename = middlename self.lastname = lastname self.nickname = nickname self.title_photo = title_photo self.email = email self.email2 = email2 self.email3 = email3 this test does not work in the console pops up such a message: enter image description here I have added parameters for testing: def test_add_contact_in_book_address(self): wd = self.wd self.open_home_page(wd) self.login(wd, username="admin", password="secret") self.user_data(wd, Contact(firstname="Lukasz", middlename="Ebi", lastname="Blaszkowski", nickname="lblaszkowski")) self.adding_a_picture_and_name(wd, Contact(title_photo="Chomik")) self.e_mail_data(wd, Contact(email="janekkolasa@wp.pl", email2="janekkolasa2@wp.pl", email3="janekkolasa3@wp.pl"))
favorite count: 0
has comment: http://stackoverflow.com/comment/90836292
tagged with: python
tagged with: selenium-webdriver
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51945361
score: 1
tagged with: selenium
has comment: http://stackoverflow.com/comment/90836550
upvote count: 1
has comment: http://stackoverflow.com/comment/90836467
tagged with: webdriver
type: Question
accepted answer: http://stackoverflow.com/a/51945361

http://stackoverflow.com/q/51826730
has body: I'm trying to solve this system of non linear equations using scipy.optimize.fsolve , I took this from an example in one other post here my system of equation is the follow : for i in range(len(self.time)-1): def equations(variable): k1,k2 = variable f1 = -k1 + self.f(self.time[i]+ (0.5+np.sqrt(3)/6)* self.dt , self.u[i]+0.25*self.dt* k1+ (0.25+ np.sqrt(3)/6)*self.dt*k2) f2 = -k2 + self.f(self.time[i]+ (0.5-np.sqrt(3)/6)* self.dt , self.u[i]+(0.25-np.sqrt(3)/6)*self.dt *k1 + 0.25*self.dt* k2) return (f1,f2) k1,k2 = fsolve(equations,(5,5)) when I run the code I got : TypeError: fsolve: there is a mismatch between the input and output shape of the 'func' argument 'equations'.Shape should be (2,) but it is (2, 1). EDIT I don't know why this mismatch and how to fix it .. I tried : for i in range(len(self.time)-1): ui = self.u[i] ti = self.time[i] def equations(variable): k1,k2 = variable f1 = -k1 + self.f(ti+ (0.5+np.sqrt(3)/6)* self.dt , ui+0.25*self.dt* k1+ (0.25+ np.sqrt(3)/6)*self.dt*k2) f2 = -k2 + self.f(ti+ (0.5-np.sqrt(3)/6)* self.dt , ui+(0.25-np.sqrt(3)/6)*self.dt *k1 + 0.25*self.dt* k2) return (f1,f2) k1,k2 = fsolve(equations,(1,1)) EDIT I've tried : return np.array([f1,f2]) and I got the same mismatch error!
has title: Error solving a system of non linear equation using scipy
tagged with: python
has comment: http://stackoverflow.com/comment/90607828
has answer: http://stackoverflow.com/a/51828177
tagged with: scipy
type: Question
score: 2
has comment: http://stackoverflow.com/comment/90608516
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/90608220
favorite count: 0
has comment: http://stackoverflow.com/comment/90607846
linked to: http://stackoverflow.com/q/40783190
has comment: http://stackoverflow.com/comment/90608139
upvote count: 2
has comment: http://stackoverflow.com/comment/90608059
type: UnansweredQuestion

http://stackoverflow.com/q/51815969
tagged with: pandas
has comment: http://stackoverflow.com/comment/90619994
answer count: 0
type: UnansweredQuestion
score: 0
has title: to_csv is missing out 'NA' values
tagged with: python
linked to: http://stackoverflow.com/q/36405994
has comment: http://stackoverflow.com/comment/90586242
type: Question
has body: I have created a categorical column like this: 0-20 6988298 20-40 2397062 40-60 586665 NA 26071 60-80 3255 80-100 7 Name: CNT_INSTALMENT_BKT, dtype: int64 I changed the datatype to 'category'. Then I tried to write the df to a csv file using to_csv, but it is missing out the values having 'NA'. I changed the datatype of the column to 'object', but still facing the same issue. This is my code: newdf.to_csv(r'D:\blah.csv',index=False) After writing to a new file, it is giving me this output: 0-20 6988298 20-40 2397062 40-60 586665 60-80 3255 80-100 7 Name: CNT_INSTALMENT_BKT, dtype: int64 Any help will be appreciated. Thank you.
linked to: http://stackoverflow.com/q/34537048
has comment: http://stackoverflow.com/comment/90587414

http://stackoverflow.com/a/51806763
answers question: http://stackoverflow.com/q/51805137
score: 1
has body: assert would throw an error if it does not fit, and render your code unusable with versions you did not test, even if it could have worked. If you code doesn't do anything bad to the computer (e.g. wipe disks, corrupt files) or the system if it fails to run correctly, which it probably doesn't, seeing that you work in a research environment, then you should let it run. If it encounters an error, then it stops. If it doesn't, it runs on. However, you should include a docstring at the head of your file with your tested versions in it, like this, """ Tested with python &lt;= 2.8, matplotlib &gt;= 2.3 ... ... rest of docstring ... """ ... rest of your code ...
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90585773
type: Answer
accepted answer of: http://stackoverflow.com/q/51805137
upvote count: 1

http://stackoverflow.com/a/51865955
has body: If you want chrome and chromedriver to stay open, you have to use the 'detach' option when starting chromedriver. In your case add : from selenium.webdriver.chrome.options import Options chrome_options = Options() chrome_options.add_experimental_option("detach", True) before you pass in the options to the browser browser = webdriver.Chrome('drivers/chromedriver.exe', options=chrome_options) Or you can run the code in debug mode with breakpoint at the end and when it pauses 'kill' the program and take over the browser if you want to, but this works in IDE only. Update: As of Jan. 24, chrome_options parameter when initializing Webdriver is now only "options".
has comment: http://stackoverflow.com/comment/128938856
has comment: http://stackoverflow.com/comment/100130295
answers question: http://stackoverflow.com/q/51865300
upvote count: 93
score: 93
has comment: http://stackoverflow.com/comment/130074628
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51865300
has comment: http://stackoverflow.com/comment/104624551
has comment: http://stackoverflow.com/comment/135154088
type: Answer
has comment: http://stackoverflow.com/comment/97538757

http://stackoverflow.com/comment/90610377
has text: onClick(or the submission of the form) is when the python function is triggered to take the string input and convert it to a date. This date is now supposed to be passed on to the JS.
type: Comment
comment on: http://stackoverflow.com/q/51827089
score: 0
type: QuestionComment

http://stackoverflow.com/q/51911171
has answer: http://stackoverflow.com/a/52026745
accepted answer: http://stackoverflow.com/a/52026745
downvote count: 0
upvote count: 3
favorite count: 0
has answer: http://stackoverflow.com/a/51911578
possible better answer: http://stackoverflow.com/a/51978343
tagged with: python
answer count: 4
tagged with: opencv
type: AnsweredQuestion
score: 3
has body: I am using TrackerCSRT for object tracking in a video, and currently I use the init method on the tracker to set the region of interest tracker = cv2.TrackerCSRT_create() tracker.init(frame, region_of_interest) The region of interst include my object, but it also include irrelevant pixels from the background or other objects. I would like to use a mask to refine which pixels I'm interested in. Looking over the documentation, I can see method setInitialMask on the C++ version, but I cannot find the equivalent method in the Python wrapper. How do I set a mask in TrackerCSRT on openCV for Python?
has answer: http://stackoverflow.com/a/52017006
type: Question
has answer: http://stackoverflow.com/a/51978343
has title: How to use setInitialMask on TrackerCSRT?

http://stackoverflow.com/q/51853480
tagged with: opencv
has body: With Python 2.7, I'm trying to recognize digits on playing cards. I've figured out the font being used (Herculanum) and created a reference image of the digits. Multiple cards may be in an image at different angles (upside down for example) and will likely overlap. Eventually, color will come into play, but I want to identify numbers first. Ideally, I would want to know of presence of a number and possibly its location in the image. I've tried a few methods using pytesseract and OpenCV. I'm also in the process of training a TensorFlow neural network, but I think it's overkill for what seems to be a simple problem. I have some code to read in the reference digits, but I'm struggling to tie it back to an example card image. from imutils import contours import numpy as np import imutils import cv2 ref = cv2.imread('ocr_a_reference.png') ref = cv2.cvtColor(ref, cv2.COLOR_BGR2GRAY) ref = cv2.threshold(ref, 10, 255, cv2.THRESH_BINARY_INV)[1] refCnts = cv2.findContours(ref.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) refCnts = refCnts[0] if imutils.is_cv2() else refCnts[1] refCnts = contours.sort_contours(refCnts, method="left-to-right")[0] digits = {} for (i, c) in enumerate(refCnts): # compute the bounding box for the digit, extract it, and resize # it to a fixed size (x, y, w, h) = cv2.boundingRect(c) roi = ref[y:y + h, x:x + w] roi = cv2.resize(roi, (57, 88)) # update the digits dictionary, mapping the digit name to the ROI digits[i] = roi From a known font, is it possible to identify matching digits in an image? It would almost be like searching for an image within an bigger image for the closest match. The ideal end output would be a list of digits and the count within the image. Is this possible with pytesseract and/or OpenCV? Or is there another library I should be looking at? Thanks for the advice!
has title: Determine if Digit Exists in Image from Known Font (OCR + OpenCV)
score: 1
has answer: http://stackoverflow.com/a/51857378
type: Question
tagged with: python-2.7
answer count: 1
downvote count: 0
tagged with: python
tagged with: ocr
favorite count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: tesseract

http://stackoverflow.com/q/51910136
score: 0
has comment: http://stackoverflow.com/comment/90882097
has body: I can see from the documentation that there is a module named covercp. It says to "simply" put the line: cherrypy.engine.subscribe('start', covercp.start) but when I do that it tells me that covercp is not defined. Clearly I need to set something up, but I don't understand what. What I really want is a simple example that shows setting it up, and viewing the results. But my google searching has turned up nothing. Any ideas?
answer count: 0
has title: Set up code coverage with CherryPy?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90777439
has comment: http://stackoverflow.com/comment/90771681
type: Question
tagged with: cherrypy
tagged with: code-coverage
tagged with: python
has comment: http://stackoverflow.com/comment/90770437
has comment: http://stackoverflow.com/comment/90793816
has comment: http://stackoverflow.com/comment/90771656

http://stackoverflow.com/comment/90834430
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51942076
has text: im the OP hah!, no i want it to run on the server not on their machines i just want them to call on it but leave all the operations on server side

http://stackoverflow.com/q/51871257
favorite count: 0
type: UnansweredQuestion
tagged with: apache-beam
tagged with: python
has title: Google Cloud Dataflow (Python) - Not installing dependencies correctly
has body: I'm trying to run the official Dataflow example here:https://github.com/GoogleCloudPlatform/dataflow-prediction-example However, the Dataflow job is not able to start correctly (and the same error is happening with my other jobs too), due to the following type of error in the logs: (happens 2nd) Could not install packages due to an EnvironmentError: [Errno 2] No such file or directory: '/usr/local/lib/python2.7/dist-packages/tensorflow-1.9.0.dist-info/METADATA' (happens 1st) Successfully built tensorflow-module I followed the directions on Github exactly, and here is the output of pip freeze of the virtualenv for this example: absl-py==0.4.0 apache-beam==2.6.0 astor==0.7.1 avro==1.8.2 backports.weakref==1.0.post1 cachetools==2.1.0 certifi==2018.8.13 chardet==3.0.4 crcmod==1.7 dill==0.2.8.2 docopt==0.6.2 enum34==1.1.6 fasteners==0.14.1 funcsigs==1.0.2 future==0.16.0 futures==3.2.0 gapic-google-cloud-pubsub-v1==0.15.4 gast==0.2.0 google-apitools==0.5.20 google-auth==1.5.1 google-auth-httplib2==0.0.3 google-cloud-bigquery==0.25.0 google-cloud-core==0.25.0 google-cloud-pubsub==0.26.0 google-gax==0.15.16 googleapis-common-protos==1.5.3 googledatastore==7.0.1 grpc-google-iam-v1==0.11.4 grpcio==1.14.1 hdfs==2.1.0 httplib2==0.11.3 idna==2.7 Markdown==2.6.11 mock==2.0.0 monotonic==1.5 numpy==1.14.5 oauth2client==4.1.2 pbr==4.2.0 ply==3.8 proto-google-cloud-datastore-v1==0.90.4 proto-google-cloud-pubsub-v1==0.15.4 protobuf==3.6.1 pyasn1==0.4.4 pyasn1-modules==0.2.2 pydot==1.2.4 pyparsing==2.2.0 pytz==2018.4 PyVCF==0.6.8 PyYAML==3.13 requests==2.19.1 rsa==3.4.2 six==1.11.0 tensorboard==1.10.0 tensorflow==1.10.0 termcolor==1.1.0 typing==3.6.4 urllib3==1.23 Werkzeug==0.14.1 This pip dependency issue happened for all the other jobs that I tried, so I decided to try the official github example, and it's happening for this one too. This job id is: 2018-08-15_23_42_57-394561747688459326, and I'm using Python 2.7. Thanks for the help, and any pointers!
has answer: http://stackoverflow.com/a/53046415
score: 1
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51878096
tagged with: google-cloud-dataflow
answer count: 2
tagged with: google-cloud-platform
downvote count: 0

http://stackoverflow.com/comment/90826587
score: 1
type: Comment
type: QuestionComment
has text: @PatrickHaugh You're right, it's not technically impossible. But it is useless. In CPython 3.x, while you can mutate a `listiterator` behind its back by calling `__reduce__` then `__setstate__` (replacing or mutating the list or index), there's nothing useful you can do with a `set_iterator`. (Its `__reduce__` just returns a call to construct a fresh iterator from a list of the remaining values, instead of a call to construct an empty iterator and `__setstate__` it, and it doesn't have a `__setstate__`).
comment on: http://stackoverflow.com/q/51937482

http://stackoverflow.com/a/51884871
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/51884709
upvote count: 1
has body: My attempt: Kinda ugly having to do unique at the end but worked import numpy as np A=np.array([2,3,2,1,1,1,3,4,5,6,6,6,6,3]) def index(my_list, element): return [i for i, x in enumerate(my_list) if x == element] print np.unique(np.array([index(A,i) for i in A])) &gt;&gt; [[0, 2] [1, 6, 13] [3, 4, 5] [7] [8] [9, 10, 11, 12]]

http://stackoverflow.com/a/51834103
accepted answer of: http://stackoverflow.com/q/51832019
upvote count: 1
type: AcceptedAnswer
has body: To click on each name through xpath on the website https://www.dechert.com/content/dechert/en/people.html#firstName=&amp;lastInitial=&amp;lastName=&amp;office=Philadelphia&amp;page=1&amp;q=&amp;school=Villanova+University you need to wait for the names to be visible and then collect the href attributes to traverse sequencially as follows: Code Block: from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC hrefs= [] base_url = "https://www.dechert.com/content/dechert/en/people.html#firstName=&amp;lastInitial=&amp;lastName=&amp;office=Philadelphia&amp;page=1&amp;q=&amp;school=Villanova+University" options = webdriver.ChromeOptions() options.add_argument("start-maximized") options.add_argument('disable-infobars') driver=webdriver.Chrome(chrome_options=options, executable_path=r'C:\Utility\BrowserDrivers\chromedriver.exe') driver.get(base_url) persons = WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.XPATH, "//div[@class='name']//a[contains(@href,'/people/')]"))) for person in persons: hrefs.append(person.get_attribute("href")) for href in hrefs: driver.get(href) print(driver.current_url) driver.get(base_url) Console Output: https://www.dechert.com/people/b/april-banko.html https://www.dechert.com/people/c/nicholas-carroll.html https://www.dechert.com/people/e/william-elder.html https://www.dechert.com/people/g/joe-gribbin.html https://www.dechert.com/people/t/joseph-tate.html https://www.dechert.com/people/t/marissa-tribuiani.html Perhaps you can also use @Andersson's solution which was near perfect with certain modification as follows: links = [link.get_attribute('href') for link in WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.XPATH, "//div[@class='name']//a[contains(@href,'/people/')]")))] for link in links: driver.get(link) print(driver.current_url) driver.get(base_url)
type: Answer
answers question: http://stackoverflow.com/q/51832019
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/90641298

http://stackoverflow.com/q/51830947
type: Question
upvote count: 9
has title: How to compute standard deviation in Apache Beam
score: 9
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/52958771
favorite count: 0
accepted answer: http://stackoverflow.com/a/52958771
tagged with: apache-beam
tagged with: python
has body: I'm new to Apache Beam, and I want to calculate the mean and std deviation over a large dataset. Given a .csv file of the form "A,B" where A, B are ints, this is basically what I have. import apache_beam as beam from apache_beam.options.pipeline_options import PipelineOptions from apache_beam.io.textio import ReadFromText class Split(beam.DoFn): def process(self, element): A, B = element.split(',') return [('A', A), ('B', B)] with beam.Pipeline(options=PipelineOptions()) as p: # parse the rows rows = (p | ReadFromText('data.csv') | beam.ParDo(Split())) # calculate the mean avgs = (rows | beam.CombinePerKey( beam.combiners.MeanCombineFn())) # calculate the stdv per key # ??? std &gt;&gt; beam.io.WriteToText('std.out') I'd like to do something like: class SquaredDiff(beam.DoFn): def process(self, element): A = element[0][1] B = element[1][1] return [('A', A - avgs[0]), ('B', B - avgs[1])] stdv = (rows | beam.ParDo(SquaredDiff()) | beam.CombinePerKey( beam.combiners.MeanCombineFn())) or something, but I can't figure out how.
type: AnsweredQuestion

http://stackoverflow.com/q/51916797
has comment: http://stackoverflow.com/comment/90783481
has comment: http://stackoverflow.com/comment/90783453
has title: Retrieve the help page to a file
has body: I am learning selenium to parse a page &gt;&gt;&gt; link_elem = browser.find_element_by_class_name("pager_next") &gt;&gt;&gt; type(link_elem) selenium.webdriver.remote.webelement.WebElement In the interactive mode, the manual could be checked as: &gt;&gt;&gt; help(link_elem) I tried to redirect it to disk as &gt;&gt;&gt; help(link_elem) &gt; manual.md NameError: name 'manual' is not defined How could I retrieve the help page to a file?
has answer: http://stackoverflow.com/a/51916847
score: 0
answer count: 1
type: UnansweredQuestion
tagged with: python
tagged with: selenium
type: Question

http://stackoverflow.com/comment/90789028
type: Comment
comment on: http://stackoverflow.com/a/51919380
has text: Yep, convert it to integer first. So do `df.PLU = pd.to_numeric(df.PLU, errors='coerce')`, then try the code
score: 0
type: AnswerComment

http://stackoverflow.com/q/51890489
upvote count: 2
tagged with: python
has title: Extracting parts of array elements using python
score: 2
type: AnsweredQuestion
has body: I am working to extract all integer values from a specific column (left, top, length and width) in a csv file with multiple rows and columns. I have used pandas to isolate the columns I am interested in but Im stuck on how to use a specific parts of an array. Let me explain: I need to use the CSV file's column with "left, top, length and width" attributes to then obtain xmin, ymin, xmax and ymax (these are coordinated of boxes in images). Example of a row in this column looks like so: [{"left":171,"top":0,"width":163,"height":137,"label":"styrofoam container"},{"left":222,"top":42,"width":45,"height":70,"label":"chopstick"}] And I need to extract the 171, 0, 163 and 137 to do the necessary operations for finding my xmax, xmin, ymax and ymin The above line is a single row in my pandas array, how do I extract the numbers I need for running my operations? Here is the code I wrote to extract the column and this is what I have so far: import os import csv import pandas import numpy as np csvPath = "/path/of/my/csvfile/csvfile.csv" data = pandas.read_csv(csvPath) csv_coords = data['Answer.annotation_data'].values #column with the coordinates image_name = data ['Input.image_url'].values print csv_coords[2]
has answer: http://stackoverflow.com/a/51890633
accepted answer: http://stackoverflow.com/a/51890633
type: Question
possible better answer: http://stackoverflow.com/a/51890585
answer count: 2
tagged with: arrays
downvote count: 0
tagged with: data-science
favorite count: 0
has comment: http://stackoverflow.com/comment/90732647
tagged with: pandas
has comment: http://stackoverflow.com/comment/90732309
has answer: http://stackoverflow.com/a/51890585

http://stackoverflow.com/a/76018018
type: Answer
answers question: http://stackoverflow.com/q/51832672
has body: For spark: def days360(df, start_date, end_date, method_eu=False): def is_leap_year(year): return F.when((year%4==0) &amp; (~(year%100==0) | (year%400==0)), True).otherwise(False) start_day = F.dayofmonth(start_date) start_month =F.month(start_date) start_year = F.year(start_date) end_day = F.dayofmonth(end_date) end_month =F.month(end_date) end_year = F.year(end_date) is_method_eu = F.lit(method_eu==False) condition_1 = (start_day==31) | (is_method_eu &amp; ((start_month==2) &amp; ((start_day == 29) | ((start_day == 28) &amp; (is_leap_year(start_year)==False))))) start_day = F.when(condition_1, 30).otherwise(start_day) condition_2 = (end_day==31) condition_3 = (is_method_eu) &amp; (start_day != 30) condition_4 = (end_month == 12) end_day = F.when(condition_2, F.when(condition_2 &amp; condition_3, 1).otherwise(30)).otherwise(end_day) end_year = F.when(condition_2 &amp; condition_3 &amp; condition_4, end_year + 1).otherwise(end_year) end_month = F.when(condition_2 &amp; condition_3 &amp; condition_4, 1).otherwise(F.when(condition_2 &amp; condition_3, end_month+1).otherwise(end_month)) return ( end_day + end_month * 30 + end_year * 360 - start_day - start_month * 30 - start_year * 360) # df.select(days360(df, df['start_date'], df['end_date'])).show()
score: 0

http://stackoverflow.com/comment/90848469
type: Comment
type: QuestionComment
has text: 1. `user.dob|` ==> `user.DOB|`
score: 0
comment on: http://stackoverflow.com/q/51949293

http://stackoverflow.com/q/51821018
answer count: 1
accepted answer: http://stackoverflow.com/a/51821291
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/51821291
score: 2
type: AnsweredQuestion
downvote count: 0
type: Question
has title: Python Defining parameters for nested function on outer function call
has body: I have the following function: def splot (self,what): df = pd.DataFrame((self.spec[what]).compute()).plot() plt.show() return df I want to be able to pass parameters to the .plot() method when I call the splot function, like below: def splot (self,what,arg=None): df = pd.DataFrame((self.spec[what]).compute()).plot(arg) plt.show() return df So when I call splot, I give it two arguments: 'what' (a string), and the arguments I want the plot command to take. However, this doesn't work: if I pass the argument as a string, I get a KeyError, and if not, it throws a variable error. I have a feeling that *args should be involved somewhere, but not sure how to use it in this instance.
upvote count: 2
has comment: http://stackoverflow.com/comment/90596230
tagged with: pandas

http://stackoverflow.com/q/51860945
has title: Why can't I access self when creating a list in pdb?
has comment: http://stackoverflow.com/comment/90674244
answer count: 0
downvote count: 0
has body: I currently have pdb imported in the calibrate function in a large python class called Machine. In another file, I create an instance of this class and run calibrate. I'm trying to access self.r_error which is a dictionary that points to a function, and it definitely exists and is normally recognized by the shell, but for some reason I can't iterate through it in a list: (Pdb) self &lt;direct_simulation.Machine object at 0x033D7110&gt; (Pdb) self.r_error["xRx"](5) 1.9352496986596831e-10 (Pdb) y2 = [self.r_error["xRx"](i) for i in x] *** NameError: name 'self' is not defined What's going on? Here are some parts of the code that may or may not be relevant: direct_simulation.py: from collections import defaultdict import numpy as np class Machine(object): ... def _init_error(self): get5rands = lambda: [np.random.normal(0,1) for _ in range(5)] def rot_error_curve(a,b,c,d,e): def curve(x): ... (build a curve over the real numbers with a,b,c,d, and e) ... return curve self.r_error = defaultdict(lambda: rot_error_curve(*get5rands()),{}) ... def calibrate(self): ... (things happen that create self.r_error["xRx"]) ... import pdb;pdb.set_trace() dsim_test.py: import direct_simulation as ds ... def do_cal(): global mm mm = ds.Machine() mm.calibrate() ... if __name__ == "__main__": do_cal() And then in the shell, I ran python3 -i dsim_test.py. There weren't any errors, but self remains undefined precisely whenever it's in a list.
has comment: http://stackoverflow.com/comment/90674320
tagged with: pdb
type: Question
has comment: http://stackoverflow.com/comment/90674519
linked to: http://stackoverflow.com/q/24149168
upvote count: 3
favorite count: 0
has comment: http://stackoverflow.com/comment/90674389
type: UnansweredQuestion
tagged with: python
duplicate of: http://stackoverflow.com/q/24149168
score: 3

http://stackoverflow.com/q/51908815
tagged with: comparison-operators
tagged with: dataframe
has title: How does the Pandas deal with the situation when a column with type "object" is compared with an integer?
tagged with: pandas
has answer: http://stackoverflow.com/a/51909545
answer count: 1
downvote count: 0
linked to: http://stackoverflow.com/q/4806911
has body: My question is about the rule that pandas uses to compare a column with type "object" with an integer. Here is my code: In [334]: df Out[334]: c1 c2 c3 c4 id1 1 li -0.367860 5 id2 2 zhao -0.596926 5 id3 3 sun 0.493806 5 id4 4 wang -0.311407 5 id5 5 wang 0.253646 5 In [335]: df &lt; 2 Out[335]: c1 c2 c3 c4 id1 True True True False id2 False True True False id3 False True True False id4 False True True False id5 False True True False In [336]: df.dtypes Out[336]: c1 int64 c2 object c3 float64 c4 int64 dtype: object Why does the "c2" column get True for all? P.S. I also tried: In [333]: np.less(np.array(["s","b"]),2) Out[333]: NotImplemented
favorite count: 0
score: 9
has comment: http://stackoverflow.com/comment/90768679
tagged with: python
linked to: http://stackoverflow.com/q/3270680
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51909545
has comment: http://stackoverflow.com/comment/91240485
type: Question
upvote count: 9

http://stackoverflow.com/comment/90579807
type: Comment
type: QuestionComment
has text: Fixed it! I was able to go into the admin page and it said "You may need to add '127.0.0.1' into your ALLOWED_HOSTS section. I did that fired it up again and it works! Finally. lol
comment on: http://stackoverflow.com/q/51812312
score: 0

group-by
tags question: http://stackoverflow.com/q/51851697
tags question: http://stackoverflow.com/q/51835891
tags question: http://stackoverflow.com/q/51897304
tags question: http://stackoverflow.com/q/51883761
tags question: http://stackoverflow.com/q/51838479
tag name: group-by
tags question: http://stackoverflow.com/q/51835552
tags question: http://stackoverflow.com/q/51812382
type: Tag
tags question: http://stackoverflow.com/q/51850299
tags question: http://stackoverflow.com/q/51907282
tags question: http://stackoverflow.com/q/51879764
tags question: http://stackoverflow.com/q/51842354

http://stackoverflow.com/a/51806882
answers question: http://stackoverflow.com/q/51805651
downvote count: 0
score: 1
has body: If you need to parse id from href: catalog_id = response.xpath("//div[contains(@class, 'result-nombre-container')]/h5[2]/a/@href").re_first( r'(\d+)$' )
upvote count: 1
type: Answer

http://stackoverflow.com/comment/94651375
score: 1
comment on: http://stackoverflow.com/a/51843972
type: AnswerComment
type: Comment
has text: It is also worth noting you don't need to implement shuffling yourself in `on_epoch_end`. You can just set `shuffle=True` in `fit_generator` which will shuffle instances of `Sequence`.

http://stackoverflow.com/q/51825969
tagged with: matrix
answer count: 4
upvote count: 5
has answer: http://stackoverflow.com/a/51827019
downvote count: 0
has body: I have the following 8x8 matrix in Python, which I have represented as either an 8-by-8 numpy array, or a pandas DataFrame: import numpy as np import pandas as pd x = range(64) x = np.reshape(x,(8,8)) print(x) # [[ 0 1 2 3 4 5 6 7] # [ 8 9 10 11 12 13 14 15] # [16 17 18 19 20 21 22 23] # [24 25 26 27 28 29 30 31] # [32 33 34 35 36 37 38 39] # [40 41 42 43 44 45 46 47] # [48 49 50 51 52 53 54 55] # [56 57 58 59 60 61 62 63]] df = pd.DataFrame(x) print(df) # 0 1 2 3 4 5 6 7 # 0 0 1 2 3 4 5 6 7 # 1 8 9 10 11 12 13 14 15 # 2 16 17 18 19 20 21 22 23 # 3 24 25 26 27 28 29 30 31 # 4 32 33 34 35 36 37 38 39 # 5 40 41 42 43 44 45 46 47 # 6 48 49 50 51 52 53 54 55 # 7 56 57 58 59 60 61 62 63 I'm trying to calculate the sum of the values if it were a 2-by-2 matrix, and replace the above values with this sum. My end result would be # 0 1 2 3 4 5 6 7 # 0 216 216 216 216 280 280 280 280 # 1 216 216 216 216 280 280 280 280 # 2 216 216 216 216 280 280 280 280 # 3 216 216 216 216 280 280 280 280 # 4 728 728 728 728 792 792 792 792 # 5 728 728 728 728 792 792 792 792 # 6 728 728 728 728 792 792 792 792 # 7 728 728 728 728 792 792 792 792 So, the top corner matrix has a count 216 because 0+1+2+3+8+9+10+11+16+17+18+19+24+25+26+27=216 Similarly, 32+33+34+35+40+41+42+43+48+49+50+51+56+57+58+59=728 4+5+6+7+12+13+14+15+20+21+22+23+28+29+30+31=280 36+37+38+39+44+45+46+47+52+53+54+55+60+61+62+63=792 Is there numpy/pandas functionality to make this calculate easier? Especially for much larger matrices whereby manually setting the coordinates of the "sum matrices" could be quite cumbersome.
tagged with: python
has answer: http://stackoverflow.com/a/51826287
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51826446
has answer: http://stackoverflow.com/a/51826143
accepted answer: http://stackoverflow.com/a/51826143
has answer: http://stackoverflow.com/a/51826446
type: Question
tagged with: numpy
score: 5
favorite count: 0
has title: How to calculate the sum of "submatrix" entries with numpy/pandas?
tagged with: pandas

http://stackoverflow.com/q/51928521
answer count: 2
has body: When i start my python3 script with subproccess from an other script i get the following error: Select the keyword preset you want to use:Traceback (most recent call last): File "test2.py", line 9, in &lt;module&gt; keywordselect=input("Select the keyword preset you want to use:") EOFError But when i start the script normally with python3 generate.py it works totally fine with no error. script1: import subprocess p = subprocess.Popen(["python3", "test2.py"]) script2: print("Keyword") print("1. Preset1") print("2. Preset2") print("3. Preset3") print("4. Preset4") print("You can edit the presets in /presets/keywords/.") selecting = 1 while selecting == 1: keywordselect=input("Select the keyword preset you want to use:") if keywordselect == "1": print("You selected keyword preset 1.") selectedkeywordlist = "presets/keywords/preset1.txt" elif keywordselect == "2": print("You selected keyword preset 2.") selectedkeywordlist = "presets/keywords/preset2.txt" elif keywordselect == "3": print("You selected keyword preset 3.") selectedkeywordlist = "presets/keywords/preset3.txt" elif keywordselect == "4": print("You selected keyword preset 4.") selectedkeywordlist = "presets/keywords/preset4.txt" else: print("You didn't select a valid option, please try again.")
favorite count: 0
has comment: http://stackoverflow.com/comment/90806908
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90807073
tagged with: eoferror
tagged with: python
has answer: http://stackoverflow.com/a/51929289
has comment: http://stackoverflow.com/comment/90807665
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90807801
score: 3
has answer: http://stackoverflow.com/a/51929357
tagged with: subprocess
accepted answer: http://stackoverflow.com/a/51929357
has comment: http://stackoverflow.com/comment/90807194
has title: EOFError when starting with subproccess
upvote count: 3
linked to: http://stackoverflow.com/q/7681715
type: Question
has comment: http://stackoverflow.com/comment/90807501
downvote count: 0
has comment: http://stackoverflow.com/comment/90807031
has comment: http://stackoverflow.com/comment/90806781
possible better answer: http://stackoverflow.com/a/51929289

http://stackoverflow.com/q/51935750
has comment: http://stackoverflow.com/comment/90821595
has answer: http://stackoverflow.com/a/51935790
type: AnsweredQuestion
has body: I have to build a json out of an array and send it through a socket to a java application and open it there. I have somehting like array = ["a","b","c"] { "events":[ {"id":array[0], "name":"bla1"}, {"id":array[1], "name":"bla2"} ], "name": "bla" } I have try to use concatenation to no success. How can I do it?
favorite count: 0
tagged with: python-3.x
type: Question
tagged with: python
accepted answer: http://stackoverflow.com/a/51935790
upvote count: 2
score: 0
downvote count: 2
has comment: http://stackoverflow.com/comment/90821544
has title: Dynamically build a JSON object with an array inside in Python3?
answer count: 1

http://stackoverflow.com/comment/90859024
type: AnswerComment
type: Comment
score: 1
has text: @jdarap: can't think right now. read a tutorial on *combinatorics*. there's a few variations on these ideas, how to select, combine and order things. seem easy, but they are quite tricky to get right.
comment on: http://stackoverflow.com/a/51954125

http://stackoverflow.com/comment/90576582
has text: Hi jpp, sorry I will edit my question next time to add data. Thanks for your help. fyi answer below has solved my question.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51810322
score: 0

http://stackoverflow.com/comment/90645622
has text: That's a bad idea. If you can decrypt your stored passwords, then anybody can. Can you explain more why you want to "un-jumble" them? Is this just to check that the user has entered a valid password?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51846150

http://stackoverflow.com/comment/90612759
type: QuestionComment
has text: First i assigin Console() to self.Console on the line 556 then on line 995 I use it.
comment on: http://stackoverflow.com/q/51828943
score: 0
type: Comment

http://stackoverflow.com/q/51884530
tagged with: python
score: 2
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/51884783
has title: Removing timestamp, day and month from Pandas dataframe for a time series plot
type: Question
tagged with: ticker
possible better answer: http://stackoverflow.com/a/51884783
upvote count: 2
answer count: 2
tagged with: pandas
accepted answer: http://stackoverflow.com/a/51884744
favorite count: 0
has answer: http://stackoverflow.com/a/51884744
has body: import pandas as pd import matplotlib.pyplot as plt import numpy as np I have two dataframes I want to plot two time series for. I want the time series to be stacked on top of each other which I'm struggling to get to work for a Pandas dataframe. Furthermore, I am having issues with the x-tickers. The dates and times are given as strings and are already chronologically ordered. Here is a sample of the data (taken from a larger set of data) df1 = pd.DataFrame([["2004-03-01 00:00", 2.3], ["2004-03-05 00:00", 2.4], ["2004-03-25 00:00", 2.25], ["2004-07-01 00:00", 2.7], ["2005-01-01 00:00", 2.9], ["2005-02-17 00:00", 3.1], ["2005-12-01 00:00", 3.5], ["2006-02-01 00:00", 3.3], ["2006-04-05 00:00", 3.08], ["2006-08-22 00:00", 2.4], ["2007-07-01 00:00", 2.1]], columns = ['Date and Time', 'Values 1']) df2 = pd.DataFrame([["2004-03-01 00:00", 12.3], ["2004-03-05 00:00", 14.5], ["2004-03-25 00:00", 12.1], ["2004-07-01 00:00", 10.0], ["2005-01-01 00:00", 12.1], ["2005-02-17 00:00", 9.3], ["2005-12-01 00:00", 8.1], ["2006-02-01 00:00", 6.5], ["2006-04-05 00:00", 7.5], ["2006-08-22 00:00", 6.4], ["2007-07-01 00:00", 4.1]], columns = ['Date and Time', 'Values 2']) first of all. If I try to plot df1, df1.plot(x='Date and Time', y='Values 1', legend=False) plt.xlabel('Year') plt.ylabel('Values 1') plt.show() the output is the graph I want, but the x-tickers are formatted years-month-date-time. In this example, I want just "years" 2004, 2005, 2006, 2007 to appear as tickers and more importantly, that they are correctly scaled (so the 2005 ticker will be close to the "2005-01-01" datapoint). Is this possible? Furthermore, I want to plot these graphs stacked on top of each other, I tried the code below to no avail. plt.figure(1) plt.subplot(211) df1.plot(x='Date and Time', y='Values 1', legend=False) plt.xlabel('Year') plt.ylabel('Values 1') plt.subplot(212) df2.plot(x='Date and Time', y='Values 2', legend=False) plt.xlabel('Year') plt.ylabel('Values 2') plt.show()

http://stackoverflow.com/a/51903913
has comment: http://stackoverflow.com/comment/90758966
upvote count: 3
score: 3
has comment: http://stackoverflow.com/comment/90762266
has comment: http://stackoverflow.com/comment/90762299
has comment: http://stackoverflow.com/comment/90758935
answers question: http://stackoverflow.com/q/51903882
has comment: http://stackoverflow.com/comment/90762202
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51903882
type: Answer
has body: What you probably want to do is build a dict, mapping each letter grade to a value. You can do this explicitly: gradevalues = {'A+': 13, 'A': 12, …, 'F': 1} But it's probably better to do it programmatically, because less repetition means fewer places to make a typo: grades = 'A+ A A- B+ B B- C+ C C- D+ D D- F'.split() grades.reverse() gradevalues = {grade: i for i, grade in enumerate(grades, 1)} assert gradevalues['F'] == 1 assert gradevalues['A+'] == 13

http://stackoverflow.com/q/51897251
has comment: http://stackoverflow.com/comment/90746535
tagged with: python
has comment: http://stackoverflow.com/comment/90746138
has comment: http://stackoverflow.com/comment/90746600
accepted answer: http://stackoverflow.com/a/51903195
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90746673
upvote count: 2
has comment: http://stackoverflow.com/comment/90746582
tagged with: cython
type: Question
tagged with: numpy
tagged with: performance
tagged with: algorithm
has title: Check, if one Line Segment intersects with a set of line segments
has body: I have a a line segment AB (2d) from point A to point B. For the representation of a coastline (closed polygon, 3*10^3 vertices), I have a NumPy array (2d) of points which start and end at the same point. I want to know, if the connection between point A and B intersects the coastline. My first approach was to iterate over each line segment of the closed polygon and check if it intersects with AB. Here is the underlying method. Even if I do this working with NumPy arrays or translating the function with cython, it is not fast enough, because I have to do it a lot of times for different As and Bs. I thought, this may be a conceptual problem and I was wondering, if there is a smarter way to check only, if at least one intersection exists (True/False)? I tried to use shapely as well. But this was kind of slow. from shapely.geometry import LineString import numpy as np coastline = LineString(np.dstack(x_values,y_values)) def intersection(A,B,Coastline): AB = LineString([(A[0], A[1]), (B[0], B[1])]) if AB.intersection(coastline).is_empty: return False return True
has comment: http://stackoverflow.com/comment/90745486
downvote count: 0
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51903195

http://stackoverflow.com/comment/90593350
has text: I had to proceed with naming the series created in for loop like this: tmp.name = 'new_' + i; then it worked as desired.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51809970
type: AnswerComment

http://stackoverflow.com/a/51838953
has comment: http://stackoverflow.com/comment/90631176
has comment: http://stackoverflow.com/comment/90631130
has comment: http://stackoverflow.com/comment/90631085
has comment: http://stackoverflow.com/comment/90632735
has comment: http://stackoverflow.com/comment/90660971
has comment: http://stackoverflow.com/comment/90631501
type: Answer
has comment: http://stackoverflow.com/comment/90632372
has comment: http://stackoverflow.com/comment/90632431
has comment: http://stackoverflow.com/comment/90634754
has comment: http://stackoverflow.com/comment/90633597
downvote count: 0
has comment: http://stackoverflow.com/comment/90634419
has body: Try to replace if driver.find_element_by_id("smc") with if driver.find_elements_by_id("smc")
has comment: http://stackoverflow.com/comment/90633849
has comment: http://stackoverflow.com/comment/90630974
has comment: http://stackoverflow.com/comment/90633446
has comment: http://stackoverflow.com/comment/90631211
score: 1
has comment: http://stackoverflow.com/comment/90633755
has comment: http://stackoverflow.com/comment/90632476
has comment: http://stackoverflow.com/comment/90632947
has comment: http://stackoverflow.com/comment/90631143
answers question: http://stackoverflow.com/q/51838719
has comment: http://stackoverflow.com/comment/90631244
upvote count: 1
has comment: http://stackoverflow.com/comment/90631330

http://stackoverflow.com/q/51828603
has comment: http://stackoverflow.com/comment/90612043
has answer: http://stackoverflow.com/a/51829429
has answer: http://stackoverflow.com/a/51828907
tagged with: lambda
has comment: http://stackoverflow.com/comment/90611893
type: Question
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51828907
linked to: http://stackoverflow.com/q/19189274
has comment: http://stackoverflow.com/comment/90612188
has answer: http://stackoverflow.com/a/51828841
has comment: http://stackoverflow.com/comment/90613393
accepted answer: http://stackoverflow.com/a/51829429
answer count: 3
has comment: http://stackoverflow.com/comment/90612170
downvote count: 0
has body: I saw this example at pythontips. I do not understand the second line when defaultdict takes an argument "tree" and return a "tree". import collections tree = lambda: collections.defaultdict(tree) some_dict = tree() some_dict['color']['favor'] = "yellow" # Works fine After I run this code, I checked the type of some_dict defaultdict(&lt; function &lt; lambda &gt; at 0x7f19ae634048 &gt;, {'color': defaultdict( &lt; function &lt; lambda &gt; at 0x7f19ae634048 &gt;, {'favor': 'yellow'})})
has comment: http://stackoverflow.com/comment/90612369
favorite count: 0
tagged with: defaultdict
upvote count: 8
has comment: http://stackoverflow.com/comment/90612306
has title: don't understand this lambda expression with defaultdict
tagged with: python
score: 8
tagged with: python-3.x

http://stackoverflow.com/comment/90843308
type: Comment
type: QuestionComment
has text: @dirkgroten Exactly what I was looking for! If you could post it as an answer I'll accept it.
comment on: http://stackoverflow.com/q/51946341
score: 0

http://stackoverflow.com/q/51867897
tagged with: javascript
score: 0
answer count: 1
has title: console logging the python script console output in node.js
has body: I'm working on opencv python and node.js server in which python script prints out the string "moved" useful for my node server I'm using 'python-shell' for spawning python script as a child process but the problem is that i'm working on a video file in opencv and node only console logs only after the cv2.imshow(video window) is exited. I want it to console log the output in node from python script on real-time. Neither i'm getting the argument in the conditional statement (message === 'moved') server.js var express = require('express'); var app = express(); var PythonShell = require('python-shell'); var pyshell = new PythonShell(__dirname + './script.py'); pyshell.on('message', function (message) { // received a message sent from the Python file script.py (returns "moved" string) console.log(message); console.log(message + 'hi'); if(true){ console.log('hey') } if(message === 'moved'){ console.log('hit') } }); Console in Node.js moved hived hey also why did 'moved' and 'hi' concatenated to 'hived'?
has answer: http://stackoverflow.com/a/51937994
tagged with: python
tagged with: node.js
type: AnsweredQuestion
type: Question
tagged with: opencv
accepted answer: http://stackoverflow.com/a/51937994
tagged with: stdout

http://stackoverflow.com/comment/90744398
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51896669
has text: @pault, I think my question is different. From answer above I got it -m stands for module. But not getting what are other modules available in python.

http://stackoverflow.com/q/51800895
accepted answer: http://stackoverflow.com/a/51800987
type: AnsweredQuestion
downvote count: 0
score: 6
tagged with: django
has title: Django returning webpage instead of JSON
type: Question
tagged with: http://stackoverflow.com/tag/json
upvote count: 6
answer count: 1
tagged with: django-rest-framework
favorite count: 0
has body: I am fairly new to Django and am trying to implement a basic REST API in Django. I am having a news list in MySQL Database, and following various tutorials, successfully managed to implement a webservice that responds the news list. http://127.0.0.1:8000/rest/news_infos/ The above URL(local) produces the following page: As you can see, I am getting a webpage here. But what I actually needed is that the above API to return just the json. I don't want to have this kind of pages available in my webservice, just the JSON response. Of course I can get it json only by appending format=json to the request. But that is not what I require. I want the web page to be gone and calling http://127.0.0.1:8000/rest/news_infos/ to return the json instead. Following is my views.py code: from rest_framework import viewsets from .models import NewsContent, NewsInfo from .serializers import NewsContentSerializer, NewsInfoSerializer class NewsContentViewSet(viewsets.ViewSet): queryset = NewsContent.objects.all()[:10] serializer_class = NewsContentSerializer class NewsInfoViewSet(viewsets.ModelViewSet): queryset = NewsInfo.objects.all()[:10] serializer_class = NewsInfoSerializer Please let me know if any other code/info is required. Couldn't find any proper solution online.
tagged with: python
has answer: http://stackoverflow.com/a/51800987

http://stackoverflow.com/q/51802047
has body: How can I make 8-12 to be displayed as 12-August. I tried the following but somewhere I'm going wrong that is why I'm getting an error. Tried like: import datetime dt = datetime.datetime.strptime("8-12", '%d-%b').strftime('%b-%d') print(dt) Output I'm expecting: 12-August Error I'm having: File "C:\Users\WCS\AppData\Local\Programs\Python\Python36-32\lib\_strptime.py", line 362, in _strptime (data_string, format)) ValueError: time data '8-12' does not match format '%d-%b'
score: 0
has title: Can't fix the date using datetime
has answer: http://stackoverflow.com/a/51802072
answer count: 1
tagged with: python-3.x
tagged with: datetime
tagged with: python
type: Question
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51802072

http://stackoverflow.com/comment/90725348
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51885792
type: AnswerComment
has text: Thanks, this really helped me figure out what was going on - code works now!

contacts
tags question: http://stackoverflow.com/q/51878259
type: Tag
tag name: contacts

http://stackoverflow.com/comment/90642951
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51844220
has text: Usually, for *Python3*, it's *pip3* (but you also need to have in your *%PATH%*). Did you try using it with the full path (e.g. *"C:\Program Files\Python\36\Scripts\pip3.exe"* ...)? That way there's no room left for confusion. Also what is *winapi*? Are you talking about *pywin32*?
type: Comment

http://stackoverflow.com/comment/90828185
has text: Write your own coroutine and `send` the new tuple to add to it.
score: 1
comment on: http://stackoverflow.com/q/51938903
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90705430
type: Comment
score: 0
comment on: http://stackoverflow.com/a/51877025
has text: Very clean solution. +1 for that. What do you think about trying to cast to an `int` and catch the `ValueError` instead of using `isnumeric()`?
type: AnswerComment

http://stackoverflow.com/q/51828930
downvote count: 0
tagged with: python-typing
favorite count: 0
has title: Unknown variable for Python typehint
has answer: http://stackoverflow.com/a/51829507
tagged with: python
has answer: http://stackoverflow.com/a/51830033
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51829507
upvote count: 3
has body: I have a wrapper function, what should I put as the return value if the variable to be returned is unknown? def try_catch_in_loop(func_to_call: callable, *args): for attempt in range(NUM_RETRYS + 1): try: if attempt < NUM_RETRYS: return func_to_call(*args) else: raise RunTimeError("Err msg") except gspread.exceptions.APIError: request_limit_error() Specifically looking what to put at the end of the function call ie: def try_catch_in_loop(...) -> {What do I put here}:
type: Question
accepted answer: http://stackoverflow.com/a/51830033
answer count: 2
score: 3

http://stackoverflow.com/q/51909310
type: Question
upvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/90768963
has comment: http://stackoverflow.com/comment/90768743
has comment: http://stackoverflow.com/comment/90768871
answer count: 1
has title: Apply condition to multiple arrays
has comment: http://stackoverflow.com/comment/90768724
has answer: http://stackoverflow.com/a/51909411
has comment: http://stackoverflow.com/comment/90768939
tagged with: filter
score: 2
type: AnsweredQuestion
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/51909411
has body: How to apply a same condition to multiple arrays? import numpy as np a = np.array([1,2,3,4,5]) b = np.array([2,3,4,5,6]) c = np.array([5,6,7,8,9]) a,b = a[c&gt;6],b[c&gt;6] print (a,b) Like this, I want to filter out elements in 'a' and 'b' using the same filter, then replace the original value. Although this code works fine, it will be very long if I want to apply this filter to many arrays.

http://stackoverflow.com/comment/90576426
type: AnswerComment
has text: What exactly do you mean by "range"?
score: 0
comment on: http://stackoverflow.com/a/51810701
type: Comment

http://stackoverflow.com/q/51953511
has answer: http://stackoverflow.com/a/51953611
has comment: http://stackoverflow.com/comment/90858009
has answer: http://stackoverflow.com/a/51953783
has title: Python: Cannot create thread without starting it
tagged with: python-3.x
type: UnansweredQuestion
tagged with: multithreading
tagged with: python
has answer: http://stackoverflow.com/a/51953862
answer count: 4
has body: I am trying to make a python program that would download multiple images simultaneously by means of threading. However, the problem is that I have to ask the user how many images he/she wants to download, so I have to create a new thread for each download using a loop. I tried that, and it turns out that I cannot create a thread without starting it too. I want both the threads created by the loop to start at roughly the same time. However, the loop progresses only after the thread constructed in the loop has finished executing - so I cannot simultaneously download the images. import urllib.request import threading import time def set_name(url, name): #This function tells the compiler what extension to save the image by, so that the computer can read it. if url.endswith("png"): return name + ".png" elif url.endswith("jpg"): return name + ".jpg" elif url.endswith("gif"): return name + ".gif" else: print("Please check your link") links = [] names = [] def get_img_parameters(): #Takes the name and url of the images and stores them in separate lists. img_count = int(input("How many images would you like to download?")) x = 1 while x &lt; img_count + 1: link = str(input("Paste the link of the image %d: " % x)) links.append(link) name = str(input("Name your image: ")) full_name = name + str(set_name(link, name)) names.append(full_name) x += 1 def img_down(url, name): urllib.request.urlretrieve(url, name) get_img_parameters() for i in range(len(links)): #len(links) just tells how many threads I have to make t = threading.Thread(target = img_down(links[i], names[i])) continue It seems like it does not matter if I include t.start() in the loop, since the thread starts automatically due to the line - t = threading.Thread(target = img_down(links[i], names[i])) I want the first thread to start and the loop to repeat with the next thread, so that both downloads can run simultaneously. For now, the loop moves to the next iteration only when the first thread has finished.
score: 0
has answer: http://stackoverflow.com/a/51953732
type: Question

http://stackoverflow.com/a/51855952
type: AcceptedAnswer
has body: You should take a look at your CSV file in a file editor and ensure that each line contains at least 3 entries. A common problem is when your CSV file contains a blank link e.g. the last line. You could always add if len(row) == 3: before doing your append, this would then have the effect of skipping over any lines that are not correctly formated, for example: import csv array_of_ids = [] with open('reactions/by_ids.csv', 'r', newline='') as f: reader = csv.reader(f) for row in reader: if len(row) == 3: array_of_ids.append(row[2])
answers question: http://stackoverflow.com/q/51809507
type: Answer
accepted answer of: http://stackoverflow.com/q/51809507
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/q/51924312
type: UnansweredQuestion
upvote count: 1
tagged with: python
tagged with: soa
has body: In weblogic Server 11g, is it possible to change the Composite Audit Level via commands ? I was able to find some SOA Composite Application Management Commands which helped me create a python script to perform various action on the composites. PFB the commands: sca_startComposite sca_stopComposite sca_activateComposite sca_retireComposite sca_assignDefaultComposite sca_getDefaultCompositeRevision sca_listDeployedComposites Do we have any command which can be used to switch the Composite Audit Level between production, Off, Development and inherit ?
tagged with: composite
tagged with: wlst
score: 1
type: Question
downvote count: 0
tagged with: weblogic11g
has title: Changing Composite Audit Log via commands
favorite count: 0
answer count: 0

numpy
tags question: http://stackoverflow.com/q/51931720
tags question: http://stackoverflow.com/q/51875213
tags question: http://stackoverflow.com/q/51935456
tags question: http://stackoverflow.com/q/51868455
tags question: http://stackoverflow.com/q/51861691
tags question: http://stackoverflow.com/q/51876012
tags question: http://stackoverflow.com/q/51934871
tags question: http://stackoverflow.com/q/51930384
tags question: http://stackoverflow.com/q/51800651
tags question: http://stackoverflow.com/q/51898099
tags question: http://stackoverflow.com/q/51910421
tags question: http://stackoverflow.com/q/51844794
tags question: http://stackoverflow.com/q/51820746
tags question: http://stackoverflow.com/q/51857973
tags question: http://stackoverflow.com/q/51818188
tags question: http://stackoverflow.com/q/51927792
tags question: http://stackoverflow.com/q/51878397
tags question: http://stackoverflow.com/q/51926781
tags question: http://stackoverflow.com/q/51920005
tags question: http://stackoverflow.com/q/51919953
tags question: http://stackoverflow.com/q/51913147
tags question: http://stackoverflow.com/q/51825969
tags question: http://stackoverflow.com/q/51856836
tags question: http://stackoverflow.com/q/51951639
tags question: http://stackoverflow.com/q/51918099
tags question: http://stackoverflow.com/q/51805137
tags question: http://stackoverflow.com/q/51834129
tags question: http://stackoverflow.com/q/51846590
tags question: http://stackoverflow.com/q/51801187
tags question: http://stackoverflow.com/q/51839761
tags question: http://stackoverflow.com/q/51847671
tags question: http://stackoverflow.com/q/51954743
tags question: http://stackoverflow.com/q/51849237
tags question: http://stackoverflow.com/q/51851884
tags question: http://stackoverflow.com/q/51900396
tags question: http://stackoverflow.com/q/51914893
tags question: http://stackoverflow.com/q/51956198
tags question: http://stackoverflow.com/q/51902711
tags question: http://stackoverflow.com/q/51882973
tags question: http://stackoverflow.com/q/51861904
tags question: http://stackoverflow.com/q/51915907
tags question: http://stackoverflow.com/q/51854761
tags question: http://stackoverflow.com/q/51897251
tags question: http://stackoverflow.com/q/51858428
tags question: http://stackoverflow.com/q/51941807
tags question: http://stackoverflow.com/q/51943661
tags question: http://stackoverflow.com/q/51814180
tags question: http://stackoverflow.com/q/51860245
tags question: http://stackoverflow.com/q/51895374
tags question: http://stackoverflow.com/q/51953829
tags question: http://stackoverflow.com/q/51828755
tags question: http://stackoverflow.com/q/51905176
tags question: http://stackoverflow.com/q/51931800
tags question: http://stackoverflow.com/q/51807560
tags question: http://stackoverflow.com/q/51856769
tags question: http://stackoverflow.com/q/51940556
tags question: http://stackoverflow.com/q/51845092
tags question: http://stackoverflow.com/q/51831561
tags question: http://stackoverflow.com/q/51953186
tags question: http://stackoverflow.com/q/51867433
tags question: http://stackoverflow.com/q/51949023
tags question: http://stackoverflow.com/q/51886660
tags question: http://stackoverflow.com/q/51815172
tags question: http://stackoverflow.com/q/51920645
tags question: http://stackoverflow.com/q/51946728
tags question: http://stackoverflow.com/q/51880270
tags question: http://stackoverflow.com/q/51916515
tags question: http://stackoverflow.com/q/51923846
tags question: http://stackoverflow.com/q/51873510
tags question: http://stackoverflow.com/q/51953748
tags question: http://stackoverflow.com/q/51914697
tags question: http://stackoverflow.com/q/51953018
tags question: http://stackoverflow.com/q/51893841
tags question: http://stackoverflow.com/q/51813335
tags question: http://stackoverflow.com/q/51846930
tags question: http://stackoverflow.com/q/51837627
tags question: http://stackoverflow.com/q/51881157
tags question: http://stackoverflow.com/q/51921101
tags question: http://stackoverflow.com/q/51876794
tags question: http://stackoverflow.com/q/51870724

libvlc
tags question: http://stackoverflow.com/q/51858476
type: Tag
tag name: libvlc

recursion
type: Tag
tags question: http://stackoverflow.com/q/51951904
tags question: http://stackoverflow.com/q/51913744
tags question: http://stackoverflow.com/q/51921782
tags question: http://stackoverflow.com/q/51864688
tag name: recursion
tags question: http://stackoverflow.com/q/51910933
tags question: http://stackoverflow.com/q/51954938
tags question: http://stackoverflow.com/q/51914087
tags question: http://stackoverflow.com/q/51939174
tags question: http://stackoverflow.com/q/51946790
tags question: http://stackoverflow.com/q/51809957
tags question: http://stackoverflow.com/q/51908760
tags question: http://stackoverflow.com/q/51899115
tags question: http://stackoverflow.com/q/51904479
tags question: http://stackoverflow.com/q/51890152
tags question: http://stackoverflow.com/q/51863982
tags question: http://stackoverflow.com/q/51848855
tags question: http://stackoverflow.com/q/51812241
tags question: http://stackoverflow.com/q/51806201
tags question: http://stackoverflow.com/q/51801736

http://stackoverflow.com/q/51884044
answer count: 1
accepted answer: http://stackoverflow.com/a/51884491
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/csv
downvote count: 0
has body: I'm trying to run a .csv file through a python code in order to give me a new csv with better formatting. I could use help because the script that I have written is not working. I'm pretty new to this stuff. I'm adding two photos to this message, one is an example input file and the other is an example of the desired output file. Obviously, the output file would be much easier to use, to make pivot table, graphs, etc in excel. I think I'm getting stuck on the fields list, [0],2,2, etc. I'm also getting stuck on whether or not this should be a tab-delimited or comma-delimited file, because there are a lot of symbols in the document,randomly: ; , @ : - etc. input file output file person_name = '' birth_date = '' sex = '' def read_file(file_name,out_file): global person_name, birth_date, sex, date_loanrequest, date_loanreturned, type, amount, days_returned with open(file_name, 'r+') as in_file: with open(out_file, 'w+') as out_file: for line in in_file: line = line.strip() if line == "": continue fields = line.split('\t') print(fields[0]) print(fields[1]) print(fields[2]) print(fields[3]) print(fields[4]) print(fields[5]) print(len(fields)) if line.find('Person Name') != -1: patient_name, Birth Date = fields[1], fields[2] elif line.find('Address') != -1: sex = fields[3] elif line.find('Date LoanRequest') != -1: date_loanrequest = fields[3] elif line.find('Date LoanReturned') != -1: date_loanreturned = fields[3] elif line.find('Type') != -1: type = fields[3] elif line.find('Amount') != -1: amount = fields[3] elif line.find('Days Returned') != -1: days_returned = fields[3] else: out_file.write('%s,%s,%s,%s,%s,%s,%s,%s,%s' % (person_name, birth_date, sex, date_loanrequest, date_loanreturned, type, amount, days_returned fields[0], fields[1], fields[2], fields[3], fields[4], fields[5] + '\n')) if __name__=='__main__': '''file_name=sys.argv[1] out_file=sys.argv[2]''' file_name = 'file_name.csv' out_file = 'out_file.csv' read_file(file_name,out_file)
score: 1
has comment: http://stackoverflow.com/comment/90724588
favorite count: 0
has comment: http://stackoverflow.com/comment/90719739
has answer: http://stackoverflow.com/a/51884491
type: Question
has title: python - trying to turn a csv file into a cleaner csv! new to python and Stack
tagged with: python
upvote count: 1

http://stackoverflow.com/a/51886652
answers question: http://stackoverflow.com/q/51886555
type: AcceptedAnswer
upvote count: 2
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/90725383
has comment: http://stackoverflow.com/comment/90725330
has comment: http://stackoverflow.com/comment/90724728
has body: Normally, when you call a function, you want to get some result. For example, when I write s = sorted([3,2,1]), that call to sorted returns [1,2,3]. If it didn't, there wouldn't be any reason for me to ever call it. A return statement is the way a function provides that result. There's no other way to do that, so it's not a matter of style; if your function has a useful result, you need a return statement. In some cases, you're only calling a function for its side-effects, and there is no useful result. That's the case with print. In Python, a function always has to have a value, even if there's nothing useful, but None is a general-purpose "no useful value" value, and leaving off a return statement means you automatically return None. So, if your function has nothing useful to return, leave off a return statement. You could explicitly return None, but don't do that—use that when you want the reader to know you're specifically returning None as a useful value (e.g., if your function returns None on Tuesday, 3 on Friday, and 'Hello' every other day, it should use return None on Tuesdays, not nothing). When you're writing a "procedure", a function that's called only for side-effects and has no value, just don't return. Now, let's look at your two examples: def helloNot(): a = print("Heya!") This prints out Heya!, and assigns the return value of print to a local variable, which you never use, then falls off the end of the function and implicitly returns None. def hello(): a = print("Heya!") return a This prints out Heya!, and assigns the return value of print to a local variable, and then returns that local variable. As it happens, print always returns None, so either way, you happen to be returning None. hello is probably a little clearer: it tells the reader that we're returning the (possibly useless) return value of print. But a better way to write this function is: def hi(): print("Heya!") After all, we know that print never has anything useful to return. Even if y…
has comment: http://stackoverflow.com/comment/90725115
downvote count: 0
has comment: http://stackoverflow.com/comment/90724976
accepted answer of: http://stackoverflow.com/q/51886555
has comment: http://stackoverflow.com/comment/90724926
has comment: http://stackoverflow.com/comment/90725226

http://stackoverflow.com/a/51948127
type: Answer
accepted answer of: http://stackoverflow.com/q/51928536
has body: I've found a solution: 1) First of all get rid of interpolate() and put a limit=1 in fillna(). This allows long bursts of NaN vaues to remain in the data gaps. Of course you can use your fillna method and custom limit depending on the task. df_align = df1.join(df2, how='outer').resample('2S').mean().fillna(method='backfill', limit=1) 2) Then, use dropna() to drop all NaN values (i.e. the values inside the time gaps) df_align = df_align.dropna() Final results: import pandas as pd import datetime import numpy as np import matplotlib.pyplot as plt d1 = np.random.random_integers(0,7000,[4000,1]) d2 = np.random.random_integers(0,7000,[2000,1]) dfA = pd.DataFrame(d1) dfB = pd.DataFrame(d2) dfA.columns = ['data1'] dfB.columns = ['data2'] dfA['time'] = pd.date_range('1970-01-01 00:01:00', periods=dfA.shape[0], freq='1S') dfB['time'] = pd.date_range('1970-01-01 00:00:00', periods=dfB.shape[0], freq='1S') dfA.set_index('time', inplace=True) dfB.set_index('time', inplace=True) dfA1 = dfA.between_time('00:00:00', '00:09:00') dfA2 = dfA.between_time('00:14:00', '00:16:00') dfB1 = dfB.between_time('00:00:00', '00:12:00') dfB2 = dfB.between_time('00:15:00', '00:16:00') df1 = pd.concat([dfA1, dfA2]) df2 = pd.concat([dfB1, dfB2]) df_aligned = df1.join(df2, how='outer').resample('2S').mean().fillna(method='backfill', limit=1) df_align = df_align.dropna() print(df_aligned.head()) df_aligned.plot() plt.plot(df_aligned['data1'].values) plt.plot(df_aligned['data2'].values) plt.show()
answers question: http://stackoverflow.com/q/51928536
type: AcceptedAnswer
score: 0

http://stackoverflow.com/q/51832901
tagged with: python
score: -2
has title: Return knowing the previous beautiful soup - Python3
has comment: http://stackoverflow.com/comment/90619876
downvote count: 2
has answer: http://stackoverflow.com/a/51834923
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90619836
type: Question
has body: I started using BeautifulSoup4 two days ago. I want to get the knowing the previous tag ( ). I tried to get the number of episodes( Episodi ) etc from https://www.animeclick.it/anime/2683/yojouhan-shinwa-taikei but since they aren't static (it can be that sometimes the tag that I want isn't everytime the third tag, for example) I wanted to know how to get it.
upvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/51834923
favorite count: 0
tagged with: beautifulsoup
tagged with: python-3.x

http://stackoverflow.com/a/51853379
has body: My solution using python's pandas package: import os import re import pandas as pd FILE_PATTERN = re.compile(r'(.*)_(\d{8})_result.csv') def addDate(file_dir): csv_list = [csvfile for csvfile in os.listdir(file_dir) if re.fullmatch(FILE_PATTERN, csvfile)] for csvname in csv_list: date = re.fullmatch(FILE_PATTERN, csvname).group(2) df = pd.read_csv(os.path.join(file_dir, csvname)) df.insert(loc=1, column='date', value=[date]*len(df)) df.to_csv(os.path.join(file_dir, csvname), index=False) Sample input: NYC_20180814_result.csv in some_path: A B C 0 0 1 2 1 3 4 5 2 6 7 8 Same csv after executing addDate(some_path): A date B C 0 0 20180814 1 2 1 3 20180814 4 5 2 6 20180814 7 8 P.S. You'll not see the index column in your csv file.
answers question: http://stackoverflow.com/q/51853149
downvote count: 0
score: 1
type: Answer
upvote count: 1

http://stackoverflow.com/q/51843254
has title: Operating on a multidimensional Array in C#
tagged with: c#
has comment: http://stackoverflow.com/comment/90639649
has comment: http://stackoverflow.com/comment/90639577
score: 0
has comment: http://stackoverflow.com/comment/90640990
answer count: 1
tagged with: nested
favorite count: 0
linked to: http://stackoverflow.com/q/28902728
tagged with: multidimensional-array
has answer: http://stackoverflow.com/a/78643888
has comment: http://stackoverflow.com/comment/90640958
linked to: http://stackoverflow.com/q/2893297
upvote count: 1
tagged with: python
linked to: http://stackoverflow.com/q/16661568
downvote count: 1
type: AnsweredQuestion
has body: I am looking to convert the following Python(Numpy and Scipy) code into C#. IronPython isn't an option in my case. The code here is for an image processing program, and is operating on a multidimensional array of floats that represent a grayscale image. It is looking for the cumulative differences between rows and columns and then checking for the 5th and 95th percentile of differences so that it can crop to that. lower_percentile=5, upper_percentile=95 # row-wise differences rw = np.cumsum(np.sum(np.abs(np.diff(image, axis=1)), axis=1)) # column-wise differences cw = np.cumsum(np.sum(np.abs(np.diff(image, axis=0)), axis=0)) # compute percentiles upper_column_limit = np.searchsorted(cw, np.percentile(cw, upper_percentile), side='left') lower_column_limit = np.searchsorted(cw, np.percentile(cw, lower_percentile), side='right') upper_row_limit = np.searchsorted(rw, np.percentile(rw, upper_percentile), side='left') lower_row_limit = np.searchsorted(rw, np.percentile(rw, lower_percentile), side='right') What I have so far is some C# code to get the multidimensional array, and I have looked at other solutions. This solution handles the np.diff operation but only for a 1D arrays. I have also looked at solutions for using nested loops operate on 2D arrays like this one. I know that I likely need to combine these approaches, but I am not sure how. Ultimately, the goal here is to do a somewhat intelligent crop of a multidimensional array before continuing to process it. Looks like this could be used to do the crop once the important area of the array is defined. I am definitely open to other ways of getting there. I currently have the following C# code which returns a multidimensional array: using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Net; namespace ImageTest { class Program { static void Main(string[] args) { Bitmap img; WebClient client = new WebClient(); byte[] b = client.DownloadData("https://pixabay.com/static/uploads/photo/2012/11/…
type: Question
tagged with: numpy
accepted answer: http://stackoverflow.com/a/78643888

http://stackoverflow.com/comment/90737534
has text: The goal here is to get an javascript object looking like this: `code` data = { "questions":"http://127.0.0.1:8000/api/questions/?format=json", "choices":"http://127.0.0.1:8000/api/choices/?format=json" } `code` Im trying to get it work with this more simple api first of all.
score: 0
comment on: http://stackoverflow.com/a/51893130
type: Comment
type: AnswerComment

http://stackoverflow.com/q/51904479
has body: I've recently came across a cool algorithm to reduce any problem of the sort "Find n numbers in an array that sum to a target" to a Two Sum problem. However, I am having a hard time understanding one line of the code. def findNsum(nums, target, N, result, results): if len(nums) &lt; N or N &lt; 2 or target &lt; nums[0]*N or target &gt; nums[-1]*N: # early termination return if N == 2: # two pointers solve sorted 2-sum problem l,r = 0,len(nums)-1 while l &lt; r: s = nums[l] + nums[r] if s == target: results.append(result + [nums[l], nums[r]]) l += 1 while l &lt; r and nums[l] == nums[l-1]: l += 1 elif s &lt; target: l += 1 else: r -= 1 else: # recursively reduce N for i in range(len(nums)-N+1): if i == 0 or (i &gt; 0 and nums[i-1] != nums[i]): findNsum(nums[i+1:], target-nums[i], N-1, result+[nums[i]], results) results = [] findNsum(sorted(nums), 0, 3, [], results) return results The condition: if i == 0 or (i &gt; 0 and nums[i-1] != nums[i]): Does not make sense to me. Why do I have to check if nums[i-1] != nums[i]? If I try it out with, say, with nums = [-1, 0, 1, 2, 2, -1, -4], I get [[-4, 2, 2], [-1, -1, 2], [-1, 0, 1]] with the condition. If I take it out I get [[-4, 2, 2], [-1, -1, 2], [-1, 0, 1], [-1, 0, 1]]. Can any one make sense of this? Cheers!
has title: Reducing a N-Sum to a Two Sum
has answer: http://stackoverflow.com/a/51904524
type: Question
answer count: 1
tagged with: python
type: UnansweredQuestion
score: 0
tagged with: recursion
tagged with: algorithm

http://stackoverflow.com/q/51852691
has title: How to iterate a sync iterator and an async generator with the same for statement?
tagged with: python-3.x
tagged with: python-asyncio
has answer: http://stackoverflow.com/a/51883194
accepted answer: http://stackoverflow.com/a/51883194
tagged with: python
type: AnsweredQuestion
type: Question
has body: I had this simple sync code: if item: items = [item] else: items = get_items() for i in items: # do something Now get_items is an async generator. for i in items won't work with an async generator, and async for i in items won't iterate over my [item] list. Is there a way of iterating over a variable that could be a normal iterator or an async generator? If not, can I create a one-liner ad-hoc async generator that simply yields this one item?
score: 3
upvote count: 3
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/90579902
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51811839
has text: This smells like a bad design and feels like a XY problem. I suggest you to take a sheet of paper, write down on it some sample data and follow your ideas. Apply your assumptions to real data. Realize complexity and possible problems with understanding, debugging, troubleshooting performance. Probably you'll come up with some other model schema and some entity that will look like `ModuleGrants (user, module, is_granted)`.

http://stackoverflow.com/a/51842189
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/51841557
has comment: http://stackoverflow.com/comment/90640209
answers question: http://stackoverflow.com/q/51841557
has comment: http://stackoverflow.com/comment/90640009
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90641156
downvote count: 0
upvote count: 2
has body: Let's go through touch parts is the parameter that provides the events on_touch_XXX and is MotionEvent, so if you want to find information you should go to that part of the documents, checking the docs you get the following: ud = None User data dictionary. Use this dictionary to save your own data on the touch. Then the description tells us that if you want to share some information that you want to use in the other events on_touch_xxx it is correct to save it in that dictionary: def on_touch_XXX(self, touch): touch.ud["some_info"] = some_value def on_touch_YYY(self, touch): value = touch.ud["some_info"] print(value) In the case of the particular example, the instance of the Line created in on_touch_down is saved, since on_touch_move you need it to add more points.

http://stackoverflow.com/a/51804681
score: 5
has body: You can try to send a HEAD request first in order to check that the URL is valid, and only then download the package via a GET request. #!/usr/bin/env python2.7 listOfWebsites = [ website1, website2, website3, website4, and so on ] goodWebsites = [] for eachWebsite in listOfWebsites: genURL = eachWebsite + "/" + packageName res = requests.head(genUrl) if res.ok: goodWebsites.append(genURL)
type: AcceptedAnswer
upvote count: 5
type: Answer
answers question: http://stackoverflow.com/q/51804534
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51804534

http://stackoverflow.com/q/51862318
has comment: http://stackoverflow.com/comment/90764475
favorite count: 0
has comment: http://stackoverflow.com/comment/90738288
has comment: http://stackoverflow.com/comment/90751886
possible better answer: http://stackoverflow.com/a/74248692
tagged with: python-asyncio
tagged with: python
has answer: http://stackoverflow.com/a/51912456
type: AnsweredQuestion
tagged with: aiohttp
upvote count: 14
has comment: http://stackoverflow.com/comment/90752025
has comment: http://stackoverflow.com/comment/90737608
has comment: http://stackoverflow.com/comment/90746974
has body: I'm trying to resolve this error: RuntimeError: Cannot close a running event loop in my asyncio process. I believe it's happening because there's a failure while tasks are still pending, and then I try to close the event loop. I'm thinking I need to await the remaining responses prior to closing the event loop, but I'm not sure how to accomplish that correctly in my specific situation. def start_job(self): if self.auth_expire_timestamp < get_timestamp(): api_obj = api_handler.Api('Api Name', self.dbObj) self.api_auth_resp = api_obj.get_auth_response() self.api_attr = api_obj.get_attributes() try: self.queue_manager(self.do_stuff(json_data)) except aiohttp.ServerDisconnectedError as e: logging.info("Reconnecting...") api_obj = api_handler.Api('API Name', self.dbObj) self.api_auth_resp = api_obj.get_auth_response() self.api_attr = api_obj.get_attributes() self.run_eligibility() async def do_stuff(self, data): tasks = [] async with aiohttp.ClientSession() as session: for row in data: task = asyncio.ensure_future(self.async_post('url', session, row)) tasks.append(task) result = await asyncio.gather(*tasks) self.load_results(result) def queue_manager(self, method): self.loop = asyncio.get_event_loop() future = asyncio.ensure_future(method) self.loop.run_until_complete(future) async def async_post(self, resource, session, data): async with session.post(self.api_attr.api_endpoint + resource, headers=self.headers, data=data) as response: resp = [] try: headers = response.headers['foo'] content = await response.read() resp.append(headers) resp.append(content) except KeyError as e: logging.error('KeyError at async_post response') logging.error(e) return resp def shutdown(self): //need to do something here to await the remaining tasks and then I need to re-start a new event loop, which i think i can do, just don't know how to appropriately stop the current one. self.loop.close() return True How can I handle the error and properly close the event loop so I can start a new one a…
type: Question
linked to: http://stackoverflow.com/q/30765606
accepted answer: http://stackoverflow.com/a/51912456
has comment: http://stackoverflow.com/comment/90752055
has comment: http://stackoverflow.com/comment/90734777
answer count: 2
score: 14
has title: RuntimeError: Cannot close a running event loop
has answer: http://stackoverflow.com/a/74248692
downvote count: 0
tagged with: asynchronous

http://stackoverflow.com/comment/90804837
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51923237
has text: @georgexsh how is this used? do you mean `traceback.print_exc`?
type: Comment

http://stackoverflow.com/comment/90823590
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51936698
has text: @ikuamike : yes, the terminal prompt begints `(p2)`.
type: Comment

http://stackoverflow.com/q/51852616
favorite count: 0
tagged with: python-3.x
tagged with: python
type: AnsweredQuestion
downvote count: 0
has body: I want to write a program that opens a countryInfo.csv file and extracts the country name, capital city and population from each row, then writes a new file named country_simple_info.csv with country, capital and population in each row, with the rows sorted by population size, largest first. The file has columns with other information such as continent, languages, etc. but the code should ignore those. The following is my attempt at the code: import csv import operator import sys with open('countryInfo.csv','r', encoding='utf-8') as csvfile: reader = csv.DictReader(csvfile, delimiter='\t') result = sorted(reader, key = lambda d: float(d['population']),reverse = True) with open('country_simple_info.csv', 'w', encoding='utf-8') as outputFile: writer = csv.DictWriter(outputFile, reader.fieldnames) writer.writeheader() writer.writerows(result) The code works perfectly in the part where it has to order the countries based on population. It, however, prints everything in the file instead of just 3 columns. How would I change my code to do this. Below is the input file: iso alpha2 iso alpha3 iso numeric fips code name capital areaInSqKm population continent languages currency geonameId AD AND 020 AN Andorra Andorra la Vella 468.0 84000 EU ca EUR 3041565 AE ARE 784 AE United Arab Emirates Abu Dhabi 82880.0 4975593 AS ar-AE,fa,en,hi,ur AED 290557 AF AFG 004 AF Afghanistan Kabul 647500.0 29121286 AS fa-AF,ps,uz-AF,tk AFN 1149361 AG ATG 028 AC Antigua and Barbuda St. John's 443.0 86754 NA en-AG XCD 3576396 AI AIA 660 AV Anguilla The Valley 102.0 13254 NA en-AI XCD 3573511 AL ALB 008 AL Albania Tirana 28748.0 2986952 EU sq,el ALL 783754 AM ARM 051 AM Armenia Yerevan 29800.0 2968000 AS hy AMD 174982 AO AGO 024 AO Angola Luanda 1246700.0 13068161 AF pt-AO AOA 3351879 AQ ATA 010 AY Antarctica 1.4E7 0 AN 6697173 AR ARG 032 AR Argentina Buenos Aires 2766890.0 41343201 SA es-AR,en,it,de,fr,gn ARS 3865483 AS ASM 016 AQ American Samoa Pago Pago 199.0 57881 OC en-AS,sm,to USD 5880801 AT…
score: 1
has title: Extracting 3 columns of a file only
type: Question
upvote count: 1
answer count: 1
has answer: http://stackoverflow.com/a/51852679
accepted answer: http://stackoverflow.com/a/51852679

http://stackoverflow.com/comment/90844995
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51947506
has text: its installed in anaconda installation. python 3.6 is a seperate directory as you can see above. and i want it to be available for all programs so virtualenv is not an option

http://stackoverflow.com/a/51850865
has body: Use FeatureHasher.transform(). For example, try this in your code: fh.transform(['A','B']).toarray() # array([[ 1.], [-1.]])
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/51840865
score: 1
accepted answer of: http://stackoverflow.com/q/51840865

http://stackoverflow.com/a/51927788
answers question: http://stackoverflow.com/q/51927682
downvote count: 0
type: Answer
has body: Python is an untyped language. That means you do not need to declare the variables such as i. You can give a bit more clarity to compiler , and your understanding by doing the edit: mylist = [1,2,3,4,5] print(sum(int(i) for i in mylist )) So, Python is just very smart in giving type to variables, and flexible too as compared to static C code.
score: 1
upvote count: 1

http://stackoverflow.com/comment/90586171
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51815890
has text: Yes, let me add them as answer, would that be OK?

http://stackoverflow.com/comment/90784854
score: 0
type: QuestionComment
type: Comment
has text: Well, at least it's not supposed to be `models = EventModel` it's `model` property. Not `model>>S<<`.
comment on: http://stackoverflow.com/q/51917397

http://stackoverflow.com/q/51928064
has answer: http://stackoverflow.com/a/51928396
downvote count: 0
favorite count: 0
tagged with: python-3.x
answer count: 5
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51931129
tagged with: selenium-webdriver
score: 3
upvote count: 3
tagged with: selenium
has answer: http://stackoverflow.com/a/75681008
tagged with: webdriver
type: Question
has answer: http://stackoverflow.com/a/51930095
linked to: http://stackoverflow.com/q/36132158
has body: I am trying to write a program in Python that click to the next page until the it reaches to the last page. I followed some old posts on Stackoverflow and wrote the following code: from selenium import webdriver from selenium.common.exceptions import NoSuchElementException driver = webdriver.Chrome(executable_path="/Users/yasirmuhammad/Downloads/chromedriver") driver.get("https://stackoverflow.com/users/37181/alex-gaynor?tab=tags") while True: try: driver.find_element_by_link_text('next').click() except NoSuchElementException: break However, when I run the program, it throws following error: selenium.common.exceptions.WebDriverException: Message: unknown error: Element &lt;a href="/users/37181/alex-gaynor?tab=tags&amp;amp;sort=votes&amp;amp;page=3" rel="next" title="go to page 3"&gt;...&lt;/a&gt; is not clickable at point (1180, 566). Other element would receive the click: &lt;html class=""&gt;...&lt;/html&gt; (Session info: chrome=68.0.3440.106) I also followed a thread of Stackoverflow (selenium exception: Element is not clickable at point) but no luck.
has title: Python: Element is not clickable selenium
has answer: http://stackoverflow.com/a/68273799

http://stackoverflow.com/comment/90681141
has text: My question was not how to reuse a validator, but I was actually wondering how to get the warning as shown in the screenshot. Putting the validator in another file seems to only change the structure of the code.
type: Comment
comment on: http://stackoverflow.com/a/51862351
type: AnswerComment
score: 0

http://stackoverflow.com/q/51948753
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51950391
downvote count: 0
score: 1
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/51948838
has answer: http://stackoverflow.com/a/51948838
tagged with: django
tagged with: python
answer count: 2
upvote count: 1
has answer: http://stackoverflow.com/a/51950391
tagged with: heroku
has body: I just deployed my app to Heroku and I am getting an error when opening the application, it says: "ModuleNotFoundError: No module named 'crispy_forms'" and the same for MultiSelectField. I have tried to install these packages in the console at the platform, but it seems to have no effect, every time I run 'heroku run pip freeze' I get the same packages. I have tried to do this in my local console running the following commands: heroku run bash pip install django-crispy-forms pip install django-multiselectfield pip freeze # To check if the packages where installed Then I get that everything seems fine, django-crispy-forms and django-multiselectfield appear in the packages list in the 'pip freeze' command, but when I check in the platform, the updates are not there. As suggested below, I added the "requirements.txt" file in the root folder, with the Pipfile, Procfile. The "requirements.txt" file was added with the code pip freeze > requirements.txt: argon2-cffi==18.1.0 bcrypt==3.1.4 certifi==2018.4.16 cffi==1.11.5 chardet==3.0.4 dj-database-url==0.4.2 Django==2.0 django-crispy-forms==1.7.2 -e git://github.com/AndrewIngram/django-extra- views.git@aa58167af84d89feea286f9567a72cc5941360e4#egg=django_extra_views django-heroku==0.1.0 django-multiselectfield==0.1.8 django-session-timeout==0.0.3 gunicorn==19.7.1 idna==2.7 mailsnake==1.6.4 numpy==1.14.5 pandas==0.23.3 Pillow==5.2.0 pipenv==2018.5.18 psycopg2==2.7.3.2 pycparser==2.18 python-dateutil==2.7.3 pytz==2017.3 requests==2.19.1 six==1.11.0 stripe==2.4.0 urllib3==1.23 virtualenv==16.0.0 virtualenv-clone==0.3.0 whitenoise==3.3.1 My Pipfile is the following: source url = "https://pypi.python.org/simple" verify_ssl = true [packages] django = "*" gunicorn = "*" django-heroku = "*" django-crispy-forms = "*" django-multiselectfield = "*" [requires] python_version = "3.6" The output of my git push heroku master is the following: Counting objects: 3, done. Delta compression using up to 4 threads. Compressing objects: 100% (…
has title: Can't Install Django Packages in Heroku

http://stackoverflow.com/comment/90646970
score: 0
has text: @ScalaBoy Well, your question is then actually two questions: "how to find the nested dictionary?" and "how to find the key of a minimum value in a dictionary?", so both questions ask for an answer, which is more work than answering just one question, and more work understanding what was asked...
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51846590

http://stackoverflow.com/comment/90716857
has text: The first one is not only a terrible idea, it doesn't work, either, because `"<class '__main__.XmlListConfig'>"` is not equal to `"__main__.XmlListConfig"`.
score: 1
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51882262

http://stackoverflow.com/comment/90657858
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51852539
type: AnswerComment
has text: This is really Cool. this really works for both of my queries.! I am still trying to understand this!

http://stackoverflow.com/q/51869608
type: UnansweredQuestion
tagged with: django
tagged with: python
type: Question
has body: I would like to be able to view my uploaded files. I really have a poor grasp of what I am doing. views.py def upload_file(request): if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('learning_logs:topics')) else: form = DocumentForm() return render(request, 'learning_logs/model_form_upload.html', {'form':form}) def file_preview(request): videos = Document.objects.all() context = {'videos':videos} return render(request, 'learning_logs/video.html', context) models.py class Document(models.Model): docfile = models.FileField(upload_to = 'documents/') upload_at = models.DateTimeField(auto_now_add = True) forms.py class DocumentForm(forms.ModelForm): class Meta: model = Document fields = ['docfile'] I have uploaded videos and pictures. As the files are passed onto the HTML, I can only see the names of the files I uploaded. I can't click on the links and view the files. I would like to have an actual video player to play the videos, or view the pictures.
answer count: 1
tagged with: upload
has title: Django, viewing uploaded files and videos
tagged with: filefield
score: 0
has answer: http://stackoverflow.com/a/51871668
tagged with: http://stackoverflow.com/tag/html

http://stackoverflow.com/a/51920811
has body: class Circle(Point): means that the class Circle is inherited from the class Point and therefore the function __iadd__ of Point too. I do not see why you would want to inherit Circle from Point. I would suggest removing the inheritance, i.e. having simply class Circle: and defining a function __iadd__ for circle which is the function that defines what circle1 += circle2 does.
accepted answer of: http://stackoverflow.com/q/51920729
upvote count: 2
answers question: http://stackoverflow.com/q/51920729
type: AcceptedAnswer
type: Answer
score: 2
downvote count: 0

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

http://stackoverflow.com/comment/90812259
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51878112
has text: For Spark, you're probably using YARN, not a standalone Spark master. You would need to use `setMaster('yarn")` (which requires additional setup for YARN and to know that Hive needs to be used, or how to reach HDFS, you can't just run that after installing pyspark or extracting from the Spark website). For Hive connection, it doesn't use port 8020 or the namenode, you need to use the address of a HiveServer with port 10000 https://stackoverflow.com/a/45689705/2308683 PyArrow looks like it should work, but I've not use it
score: 0

http://stackoverflow.com/q/51879956
has title: Slow regex with python and javascript but fast to fail in go and php
type: Question
upvote count: 4
has answer: http://stackoverflow.com/a/51881217
downvote count: 0
tagged with: javascript
score: 4
favorite count: 0
has answer: http://stackoverflow.com/a/51880777
tagged with: go
has answer: http://stackoverflow.com/a/51883751
tagged with: python
tagged with: regex
answer count: 4
has body: I wrote a regex to parse PostgreSQL errors to try and show to the user which field had duplicated data. The regex is this one: ^DETAIL:.[^\(]+.(.[^\)]+).[^\(]+.(.[^\)]+). already exists It will be pretty fast if you run it against the right message like this one (https://regex101.com/r/GZuREV/1): ERROR: duplicate key value violates unique constraint "uq_content_block_internal_name_store_id" DETAIL: Key (lower(internal_name::text), store_id)=(some content block-32067683, 0c6d20a7-d843-44f3-af9c-4a2cf2a47e4c) already exists. But if PostgreSQL emits another message like the following one, it will take python about 30 seconds in my machine to answer (https://regex101.com/r/GZuREV/2). ERROR: null value in column "active" violates not-null constraint DETAIL: Failing row contains (2018-08-16 14:23:52.214591+00, 2018-08-16 14:23:52.214591+00, null, 6f6d1bc9-c47e-46f8-b220-dae49bd58090, bf24d26e-4871-4335-9f18-83c5a52f1b3a, Some Product-a1c03dde-2de9-401c-92d5-5c1500908984, {"de_DE": "Fugit tempore voluptas quos est vitae.", "en_GB": "Qu..., {"de_DE": "Fuga reprehenderit nobis reprehenderit natus magni es..., {"de_DE": "Fuga provident dolorum. Corrupti sunt in tempore quae..., my-product-53077578, SKU-53075778, 600, 4300dc25-04e2-4193-94c0-8ee97b636739, 52553d24-6d1c-4ce6-89f9-4ad765599040, null, 38089c3c-423f-430c-b211-ab7a57dbcc13, 7d7dc30e-b06b-48b7-b674-26d4f705583b, null, {}, 0, null, 9980, 100, 1, 5). If go to the regex101 link you can see that if you toggle to different languages like php or go, they all return quite fast saying that no match was found but if you choose python or javascript you will get a timeout. My quick dirty fix was something like this: match = 'already exists' in error_message and compiled_regex.search(error_message) What do you think that could be causing that? Could it be the greedy operators to consume until I reach my desired data? Update 1 Using re.IGNORECASE in python, makes it around 9 seconds slower as it spends too much time lowercasing …
has comment: http://stackoverflow.com/comment/90711858
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51880274

scipy
tags question: http://stackoverflow.com/q/51810375
tags question: http://stackoverflow.com/q/51898882
tags question: http://stackoverflow.com/q/51943661
tags question: http://stackoverflow.com/q/51902996
tags question: http://stackoverflow.com/q/51946345
tags question: http://stackoverflow.com/q/51953003
tags question: http://stackoverflow.com/q/51902519
tags question: http://stackoverflow.com/q/51892741
tags question: http://stackoverflow.com/q/51885609
tags question: http://stackoverflow.com/q/51808922
tags question: http://stackoverflow.com/q/51953345
tags question: http://stackoverflow.com/q/51839028
tags question: http://stackoverflow.com/q/51847870
tags question: http://stackoverflow.com/q/51818557
type: Tag
tags question: http://stackoverflow.com/q/51857121
tags question: http://stackoverflow.com/q/51903754
tag name: scipy
tags question: http://stackoverflow.com/q/51911597
tags question: http://stackoverflow.com/q/51875466
tags question: http://stackoverflow.com/q/51798720
tags question: http://stackoverflow.com/q/51881148
tags question: http://stackoverflow.com/q/51847193
tags question: http://stackoverflow.com/q/51932766
tags question: http://stackoverflow.com/q/51894150
tags question: http://stackoverflow.com/q/51823688
tags question: http://stackoverflow.com/q/51954307
tags question: http://stackoverflow.com/q/51803054
tags question: http://stackoverflow.com/q/51884060
tags question: http://stackoverflow.com/q/51848746
tags question: http://stackoverflow.com/q/51816167
tags question: http://stackoverflow.com/q/51815361
tags question: http://stackoverflow.com/q/51924976
tags question: http://stackoverflow.com/q/51885703
tags question: http://stackoverflow.com/q/51867317
tags question: http://stackoverflow.com/q/51873797
tags question: http://stackoverflow.com/q/51907340
tags question: http://stackoverflow.com/q/51862680
tags question: http://stackoverflow.com/q/51828828
tags question: http://stackoverflow.com/q/51803649
tags question: http://stackoverflow.com/q/51896674
tags question: http://stackoverflow.com/q/51906063
tags question: http://stackoverflow.com/q/51849871
tags question: http://stackoverflow.com/q/51917377
tags question: http://stackoverflow.com/q/51901594
tags question: http://stackoverflow.com/q/51886164
tags question: http://stackoverflow.com/q/51827029
tags question: http://stackoverflow.com/q/51923465
tags question: http://stackoverflow.com/q/51910306
tags question: http://stackoverflow.com/q/51803670
tags question: http://stackoverflow.com/q/51840615
tags question: http://stackoverflow.com/q/51880343
tags question: http://stackoverflow.com/q/51876184
tags question: http://stackoverflow.com/q/51953186
tags question: http://stackoverflow.com/q/51826044
tags question: http://stackoverflow.com/q/51920645
tags question: http://stackoverflow.com/q/51935456
tags question: http://stackoverflow.com/q/51841244
tags question: http://stackoverflow.com/q/51839690
tags question: http://stackoverflow.com/q/51946728
tags question: http://stackoverflow.com/q/51813317
tags question: http://stackoverflow.com/q/51826730
tags question: http://stackoverflow.com/q/51926560
tags question: http://stackoverflow.com/q/51955019
tags question: http://stackoverflow.com/q/51829554
tags question: http://stackoverflow.com/q/51811800

http://stackoverflow.com/comment/90831265
score: 1
comment on: http://stackoverflow.com/q/51940703
has text: By the way, any new Python development should use Python3. Python also includes pip for all latest releases, so you installed it separately?
type: Comment
type: QuestionComment

keras
tags question: http://stackoverflow.com/q/51910188
tags question: http://stackoverflow.com/q/51898548
tags question: http://stackoverflow.com/q/51850633
tags question: http://stackoverflow.com/q/51799047
tags question: http://stackoverflow.com/q/51878392
tags question: http://stackoverflow.com/q/51915835
tags question: http://stackoverflow.com/q/51923075
tags question: http://stackoverflow.com/q/51907189
tags question: http://stackoverflow.com/q/51808941
tags question: http://stackoverflow.com/q/51828770
tags question: http://stackoverflow.com/q/51921075
tags question: http://stackoverflow.com/q/51827712
tags question: http://stackoverflow.com/q/51829396
tags question: http://stackoverflow.com/q/51843541
tags question: http://stackoverflow.com/q/51904845
tags question: http://stackoverflow.com/q/51822003
tags question: http://stackoverflow.com/q/51951805
tags question: http://stackoverflow.com/q/51926624
tags question: http://stackoverflow.com/q/51827602
tags question: http://stackoverflow.com/q/51879667
tags question: http://stackoverflow.com/q/51923048
tags question: http://stackoverflow.com/q/51911088
tags question: http://stackoverflow.com/q/51867876
tags question: http://stackoverflow.com/q/51879904
tags question: http://stackoverflow.com/q/51815429
tags question: http://stackoverflow.com/q/51861062
tags question: http://stackoverflow.com/q/51841441
tags question: http://stackoverflow.com/q/51864864
tags question: http://stackoverflow.com/q/51889255
tags question: http://stackoverflow.com/q/51874695
tags question: http://stackoverflow.com/q/51939618
tags question: http://stackoverflow.com/q/51835926
tags question: http://stackoverflow.com/q/51934111
tags question: http://stackoverflow.com/q/51829810
tags question: http://stackoverflow.com/q/51886576
tags question: http://stackoverflow.com/q/51851774
tags question: http://stackoverflow.com/q/51837387
tags question: http://stackoverflow.com/q/51809624
tags question: http://stackoverflow.com/q/51956000
tags question: http://stackoverflow.com/q/51845497
tags question: http://stackoverflow.com/q/51952231
tags question: http://stackoverflow.com/q/51835810
tags question: http://stackoverflow.com/q/51811797
tags question: http://stackoverflow.com/q/51827349
tags question: http://stackoverflow.com/q/51939468
tags question: http://stackoverflow.com/q/51798784
tags question: http://stackoverflow.com/q/51799234
tags question: http://stackoverflow.com/q/51919417
tags question: http://stackoverflow.com/q/51854463
tags question: http://stackoverflow.com/q/51874760
tags question: http://stackoverflow.com/q/51861036
tags question: http://stackoverflow.com/q/51954691
tags question: http://stackoverflow.com/q/51839019
tags question: http://stackoverflow.com/q/51948810
tags question: http://stackoverflow.com/q/51932767
tags question: http://stackoverflow.com/q/51860770
tags question: http://stackoverflow.com/q/51890070
tags question: http://stackoverflow.com/q/51885923
tags question: http://stackoverflow.com/q/51843149
tags question: http://stackoverflow.com/q/51933123
tags question: http://stackoverflow.com/q/51914294
tags question: http://stackoverflow.com/q/51819213
tags question: http://stackoverflow.com/q/51848406
tags question: http://stackoverflow.com/q/51953766
tags question: http://stackoverflow.com/q/51828298
tags question: http://stackoverflow.com/q/51857831
tags question: http://stackoverflow.com/q/51930566
tags question: http://stackoverflow.com/q/51897990
tags question: http://stackoverflow.com/q/51886718
tags question: http://stackoverflow.com/q/51919639
tags question: http://stackoverflow.com/q/51877834
tags question: http://stackoverflow.com/q/51833821
tags question: http://stackoverflow.com/q/51859815
tags question: http://stackoverflow.com/q/51895184
tags question: http://stackoverflow.com/q/51870384
tags question: http://stackoverflow.com/q/51821537
tags question: http://stackoverflow.com/q/51946114
tags question: http://stackoverflow.com/q/51902539
tags question: http://stackoverflow.com/q/51810185
tags question: http://stackoverflow.com/q/51939825

http://stackoverflow.com/comment/90787104
type: Comment
comment on: http://stackoverflow.com/q/51918348
score: 0
has text: No, no PM on SO (I wish we had). It seems you're pretty new to ANN's so I recommend against starting up with LSTMs, which are somewhat more complicated. You should probably get acquainted with the basics. I suggest going for some learning material based on Keras examples. Ultimately you have to have some training/input data and label/output data for the network to learn from. Don't worry about the output not being exactly what you need. As I said, you can always transform those to whatever you need after you run data trough the ANN, e.g., scaling them.
type: QuestionComment

http://stackoverflow.com/comment/90649991
type: Comment
comment on: http://stackoverflow.com/a/51847687
type: AnswerComment
score: 0
has text: Okay. Thank you very much for your help. I envy you that you can get information easily from Bitmex site...haha:)

http://stackoverflow.com/comment/90918206
has text: Actually if you remove the second loop for sub_item in ítem that should do it
comment on: http://stackoverflow.com/a/51951376
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/90669952
has text: Using nditer because of numpy array, is there any other way to iterate through it? indicator_values are a list of numpy arrays.. indicator_names are a list of predefined headers which are appointed to every element of the numpy arrays..
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51856685
score: 0

http://stackoverflow.com/a/66233791
upvote count: 10
has body: I would just do a simple map to get the answer. If we have a dictionary as d = {'abc':'1/2/2003', 'def':'1/5/2017', 'ghi':'4/10/2013'} And a dataframe as: Member Group Date 0 xyz A np.Nan 1 uvw B np.Nan 2 abc A np.Nan 3 def B np.Nan 4 ghi B np.Nan Then a simple map will solve the problem. df["Date"] = df["Member"].map(d) map() will lookup the dictionary for value in df['Member'], and for each value in Member, it will get the Value from dictionary d and assign it back to Date. If the value does not exist, it will assign NaN. We don't need to do loop or apply.
type: Answer
downvote count: 0
score: 10
answers question: http://stackoverflow.com/q/51881503
has comment: http://stackoverflow.com/comment/138041798

arrays
tags question: http://stackoverflow.com/q/51947326
tags question: http://stackoverflow.com/q/51888819
tags question: http://stackoverflow.com/q/51807198
tags question: http://stackoverflow.com/q/51814307
tags question: http://stackoverflow.com/q/51852645
tags question: http://stackoverflow.com/q/51838620
tags question: http://stackoverflow.com/q/51890489
type: Tag
tags question: http://stackoverflow.com/q/51851434
tags question: http://stackoverflow.com/q/51809544
tags question: http://stackoverflow.com/q/51917448
tags question: http://stackoverflow.com/q/51950399
tags question: http://stackoverflow.com/q/51811937
tags question: http://stackoverflow.com/q/51810407
tags question: http://stackoverflow.com/q/51949826
tags question: http://stackoverflow.com/q/51864822
tags question: http://stackoverflow.com/q/51937095
tags question: http://stackoverflow.com/q/51820952
tags question: http://stackoverflow.com/q/51804599
tags question: http://stackoverflow.com/q/51913147
tags question: http://stackoverflow.com/q/51944834
tags question: http://stackoverflow.com/q/51843855
tags question: http://stackoverflow.com/q/51904126
tags question: http://stackoverflow.com/q/51935459
tags question: http://stackoverflow.com/q/51888836
tags question: http://stackoverflow.com/q/51881176
tags question: http://stackoverflow.com/q/51880957
tags question: http://stackoverflow.com/q/51850773
tags question: http://stackoverflow.com/q/51897822
tags question: http://stackoverflow.com/q/51941149
tags question: http://stackoverflow.com/q/51923273
tags question: http://stackoverflow.com/q/51824306
tags question: http://stackoverflow.com/q/51815087
tags question: http://stackoverflow.com/q/51930384
tags question: http://stackoverflow.com/q/51898099
tags question: http://stackoverflow.com/q/51857973
tags question: http://stackoverflow.com/q/51901789
tags question: http://stackoverflow.com/q/51915286
tags question: http://stackoverflow.com/q/51813567
tags question: http://stackoverflow.com/q/51856836
tags question: http://stackoverflow.com/q/51951639
tag name: arrays
tags question: http://stackoverflow.com/q/51898314
tags question: http://stackoverflow.com/q/51933830
tags question: http://stackoverflow.com/q/51861904
tags question: http://stackoverflow.com/q/51858428
tags question: http://stackoverflow.com/q/51860245
tags question: http://stackoverflow.com/q/51905176
tags question: http://stackoverflow.com/q/51852091
tags question: http://stackoverflow.com/q/51806091
tags question: http://stackoverflow.com/q/51867433
tags question: http://stackoverflow.com/q/51949023
tags question: http://stackoverflow.com/q/51891518
tags question: http://stackoverflow.com/q/51900624
tags question: http://stackoverflow.com/q/51920645
tags question: http://stackoverflow.com/q/51814619
tags question: http://stackoverflow.com/q/51914697
tags question: http://stackoverflow.com/q/51953018
tags question: http://stackoverflow.com/q/51893841
tags question: http://stackoverflow.com/q/51879839
tags question: http://stackoverflow.com/q/51866791
tags question: http://stackoverflow.com/q/51933273
tags question: http://stackoverflow.com/q/51936781
tags question: http://stackoverflow.com/q/51883429
tags question: http://stackoverflow.com/q/51819370
tags question: http://stackoverflow.com/q/51918214
tags question: http://stackoverflow.com/q/51849495
tags question: http://stackoverflow.com/q/51881958
tags question: http://stackoverflow.com/q/51939224
tags question: http://stackoverflow.com/q/51860716
tags question: http://stackoverflow.com/q/51885861
tags question: http://stackoverflow.com/q/51907888
tags question: http://stackoverflow.com/q/51932712
tags question: http://stackoverflow.com/q/51885609
tags question: http://stackoverflow.com/q/51828197
tags question: http://stackoverflow.com/q/51860382
tags question: http://stackoverflow.com/q/51809076
tags question: http://stackoverflow.com/q/51852109
tags question: http://stackoverflow.com/q/51801785
tags question: http://stackoverflow.com/q/51923599

http://stackoverflow.com/q/51928090
has comment: http://stackoverflow.com/comment/90805878
accepted answer: http://stackoverflow.com/a/51928126
tagged with: numpy
has body: I am trying to separate the pixel values of an image in python which are in a numpy array of 'object' data-type in a single quote like this: ['238 236 237 238 240 240 239 241 241 243 240 239 231 212 190 173 148 122 104 92 .... 143 136 132 127 124 119 110 104 112 119 78 20 17 19 20 23 26 31 30 30 32 33 29 30 34 39 49 62 70 75 90'] The shape of the numpy array is coming as 1. There are a total of 784 numbers but I cannot access them individually. I wanted something like: [238, 236, 237, ......, 70, 75, 90] of dtype int or float. There are 1000 such numpy arrays like the one above. Thanks in advance.
has answer: http://stackoverflow.com/a/51928316
score: 2
possible better answer: http://stackoverflow.com/a/51928316
type: Question
type: AnsweredQuestion
tagged with: python
favorite count: 0
answer count: 2
has title: Separate the numbers in a numpy array which are in single quote separated by spaces
downvote count: 1
has comment: http://stackoverflow.com/comment/90805964
has comment: http://stackoverflow.com/comment/90806266
has answer: http://stackoverflow.com/a/51928126
upvote count: 3

http://stackoverflow.com/a/52083377
type: Answer
answers question: http://stackoverflow.com/q/51892451
has body: Did you manually decorate any functions? I have run kernprof with mpi4py programs and also had empty results unless I specified particular functions with @profile.
score: 0

http://stackoverflow.com/comment/90861439
comment on: http://stackoverflow.com/q/51954010
score: 0
has text: So that means that the locator is good but you've either got a timing issue or the elements are in an IFRAME. If it's a timing issue, you will need to add a wait. You probably should look again and make sure the elements are not in an IFRAME. Can you post a link to the page?
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51807787
has title: How to find the distance between sprites?
has answer: http://stackoverflow.com/a/51812609
has comment: http://stackoverflow.com/comment/90574307
has comment: http://stackoverflow.com/comment/90573308
linked to: http://stackoverflow.com/q/49799619
upvote count: 1
linked to: http://stackoverflow.com/q/51785931
type: Question
linked to: http://stackoverflow.com/q/4978323
accepted answer: http://stackoverflow.com/a/51812609
has comment: http://stackoverflow.com/comment/90577521
answer count: 1
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/90573370
favorite count: 0
linked to: http://stackoverflow.com/q/20453545
tagged with: python-3.x
tagged with: python
has body: I want to check when the worker object comes closely to any of the fence objects in order to print a notification message. By "closely" I mean the distance of 20 pixels between the worker and the border of fence. For example, something like "distances_list = worker.get_dist(fences)", where "distances_list" would contain the current distances to all fences. I could adopt the approach proposed here, but maybe there is some built-in function for my task? In pygame we can use different collision detection functions, but in the case described above there is no collision. Is there any built-in function to find the distance between the sprites? import pygame, random import sys WHITE = (255, 255, 255) GREEN = (20, 255, 140) GREY = (210, 210 ,210) RED = (255, 0, 0) PURPLE = (255, 0, 255) SCREENWIDTH=1000 SCREENHEIGHT=578 IMG_BACKGROUND = "background.jpg" IMG_WORKER_RUNNING = "images/workers/worker_1.png" IMG_WORKER_IDLE = "images/workers/worker_2.png" IMG_WORKER_ACCIDENT = "images/workers/accident.png" class Background(pygame.sprite.Sprite): def __init__(self, image_file, location, *groups): # we set a _layer attribute before adding this sprite to the sprite groups # we want the background to be actually in the back self._layer = -1 pygame.sprite.Sprite.__init__(self, groups) # let's resize the background image now and only once self.image = pygame.transform.scale(pygame.image.load(image_file).convert(), (SCREENWIDTH, SCREENHEIGHT)) self.rect = self.image.get_rect(topleft=location) class GeoFenceInfluenceZone(pygame.sprite.Sprite): def __init__(self, rect, *groups): # we set a _layer attribute before adding this sprite to the sprite groups self._layer = 0 pygame.sprite.Sprite.__init__(self, groups) self.image = pygame.surface.Surface((rect.width, rect.height)) self.image.fill(GREY) self.rect = rect class GeoFence(pygame.sprite.Sprite): def __init__(self, rect, risk_level, *groups): # we set a _layer attribute before adding this sprite to the sprite groups self._layer = 1 pyg…
tagged with: pygame
type: AnsweredQuestion

http://stackoverflow.com/q/51943095
has comment: http://stackoverflow.com/comment/90836980
upvote count: 1
has body: When I try to display the data of the population nothing is shown as output but when I comment the code to display population everything works fine so what is the problem in code? from mpl_toolkits.basemap import Basemap import matplotlib.pyplot as plt import numpy as np import matplotlib.cm as cm plt.figure(figsize=(25,15)) # lon_0 is central longitude of robinson projection. # resolution = 'c' means use crude resolution coastlines. m=Basemap(projection='mill',llcrnrlat=5,urcrnrlat=40,\ llcrnrlon=65,urcrnrlon=95,resolution='i') #set a background colour m.drawmapboundary(fill_color='#85A6D9') # draw coastlines, country boundaries, fill continents. m.fillcontinents(color='white',lake_color='#85A6D9') m.drawcoastlines(color='#6D5F47', linewidth=.4) m.drawcountries(color='#6D5F47', linewidth=.4) # draw lat/lng grid lines every 30 degrees. m.drawmeridians(np.arange(-180, 180, 5), color='#bbbbbb') m.drawparallels(np.arange(-90, 90, 5), color='#bbbbbb') # lat/lon coordinates of states lats = [16.00,28.00,26.24,25.11,21.29513,28.38000,28.38000,22.30943,29.23848,32.08421,32.44000,23.45000,15.31728,10.85052,23.47332,19.60119,24.44000,25.30000,23.30000,26.00000,20.94092,30.40000,27.39128,27.30000,11.12712,23.74513,28.20761,30.15000,22.97862] lngs = [80.00,95.00,92.53,85.32000,81.82823,77.12000,72.12000,72.13623,76.43189,77.57117,74.54000,85.30000,75.71389,76.27108,77.94800,75.55298,93.58000,91.00000,20.52000,94.20000,84.80347,75.50000,73.43262,88.30000,78.65689,91.74683,79.82666,79.15000,87.74780] populations = [84.58,1.38,31.20,104.099452,25.545198,16.787941,1.458545,60.439692,25.351462,6.864602,12.541302,32.988134,61.095297,33.406061,72.626809,112.374333,2.855794,2.966889,1.097206,1.978502,41.974218,27.743338,68.548437,0.610577,72.14703,3.673917,199.812341,10.086292,91.276115] #millions # compute the native map projection coordinates for cities x,y = m(lngs,lats) #scale populations to emphasise different relative pop sizes s_populations = [p * p for p in populations] #defin…
type: Question
downvote count: 0
has title: Plotting data on map on python
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90925720
answer count: 0
score: 1
tagged with: matplotlib

http://stackoverflow.com/comment/90823476
comment on: http://stackoverflow.com/a/51936724
score: 0
has text: by "score" I mean the closest flui that matches the recommendations. E.g. : Quantity 23 means fluid 4
type: AnswerComment
type: Comment

http://stackoverflow.com/q/51828943
accepted answer: http://stackoverflow.com/a/51829328
favorite count: 0
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/51856368
has comment: http://stackoverflow.com/comment/90612759
tagged with: python
has comment: http://stackoverflow.com/comment/90612650
type: AnsweredQuestion
tagged with: subprocess
tagged with: pyqt5
has comment: http://stackoverflow.com/comment/90612820
type: Question
has title: PyQt5 and subprocess.Popen(...)
has answer: http://stackoverflow.com/a/51856368
score: 4
has body: I have 3 classes One is the Console class: class Console(QWidget): def __init__(self): super().__init__() self.editor = QPlainTextEdit(self) self.editor.setReadOnly(True) self.font = QFont() self.font.setFamily(editor["editorFont"]) self.font.setPointSize(12) self.layout = QVBoxLayout() self.layout.addWidget(self.editor, 1) self.setLayout(self.layout) self.output = None self.error = None self.editor.setFont(self.font) def run(self, command): """Executes a system command.""" out, err = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate() self.output = out self.error = err self.editor.setPlainText((self.output + self.error).decode()) return self.output + self.error The other one is a Tabs class which assigns Console() to the variable self.console. And then I have the Main class which has a function called Terminal which can be called by a keyboard shortcut Shift+F10 That will take the current filename of the file opened (this is handled with the Tabs class) and run it using subprocess. Now we get to the problem: when running some programs that aren't instant, the whole GUI freezes and I can't figure out how to make the GUI responsive when the Console class has executed the run function. The whole code can be found here: https://github.com/Fuchsiaff/PyPad
upvote count: 4
answer count: 2
tagged with: pyqt
downvote count: 0
has answer: http://stackoverflow.com/a/51829328
has comment: http://stackoverflow.com/comment/90612577

http://stackoverflow.com/comment/90711700
type: Comment
comment on: http://stackoverflow.com/a/51879230
has text: I also came across this: https://machinelearningmastery.com/save-load-keras-deep-learning-models/ It saves structure and weights separably though?
score: 0
type: AnswerComment

http://stackoverflow.com/a/64528725
has body: A similar but shorter workaround is to annotate the member with a Union type, duplicating the Callable type: from typing import Callable, Union class SomeClass: reference: Union[Callable[[], int], Callable[[], int]] def __init__(self, reference: Callable[[], int]): self.reference = reference c = SomeClass(lambda: 42) print(c.reference())
has comment: http://stackoverflow.com/comment/115702235
upvote count: 5
score: 5
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51811024

http://stackoverflow.com/comment/90594208
comment on: http://stackoverflow.com/a/51819864
score: 0
type: Comment
has text: There is always a fixed size items in each list, but the number of lists can differ. So in my example in OP, both lists have 4 rows. But in reality one could have 3 and another 6. Would this still work ?
type: AnswerComment

http://stackoverflow.com/comment/90659550
type: QuestionComment
comment on: http://stackoverflow.com/q/51852551
score: 0
type: Comment
has text: Can you elaborate? you wrote that when using KFold you get an error. is this in the code you attached? on what line

http://stackoverflow.com/comment/90587491
type: QuestionComment
type: Comment
has text: Fair enough. Let's see...
comment on: http://stackoverflow.com/q/51816284
score: 0

http://stackoverflow.com/comment/90770196
score: 0
comment on: http://stackoverflow.com/q/51907487
has text: You are asking two different questions. I think. One is about the Web concurrent architecture. Why do you need `tf.Graph()` when you are using Keras ? Isn't Keras [thread-safe](https://github.com/keras-team/keras/issues/6124) ? if you are worried about queueing in TF consider the thread-safe queues like PriorityQueue.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90582532
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51813619
has text: Yes, it's still small. But what are the steps to switch over? Do I just change the backend engine?
type: AnswerComment

http://stackoverflow.com/comment/90656084
has text: yeah, and I created a new virtualenv via PyCharm. That's why Pycharm can run this code unlike the terminal.
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51851570

dataframe
tags question: http://stackoverflow.com/q/51895536
tags question: http://stackoverflow.com/q/51838479
tags question: http://stackoverflow.com/q/51824736
tags question: http://stackoverflow.com/q/51938713
tags question: http://stackoverflow.com/q/51902887
tags question: http://stackoverflow.com/q/51955019
tags question: http://stackoverflow.com/q/51866229
tags question: http://stackoverflow.com/q/51955391
tags question: http://stackoverflow.com/q/51922609
tags question: http://stackoverflow.com/q/51906998
tags question: http://stackoverflow.com/q/51839761
tags question: http://stackoverflow.com/q/51929945
tags question: http://stackoverflow.com/q/51928886
tags question: http://stackoverflow.com/q/51855777
tags question: http://stackoverflow.com/q/51914164
tags question: http://stackoverflow.com/q/51939703
tags question: http://stackoverflow.com/q/51806880
tags question: http://stackoverflow.com/q/51883057
tags question: http://stackoverflow.com/q/51936227
tags question: http://stackoverflow.com/q/51850819
tags question: http://stackoverflow.com/q/51948034
tags question: http://stackoverflow.com/q/51851214
tags question: http://stackoverflow.com/q/51907234
tags question: http://stackoverflow.com/q/51831921
tags question: http://stackoverflow.com/q/51900253
tags question: http://stackoverflow.com/q/51913841
tags question: http://stackoverflow.com/q/51870255
tags question: http://stackoverflow.com/q/51840708
tags question: http://stackoverflow.com/q/51819357
tags question: http://stackoverflow.com/q/51910798
tags question: http://stackoverflow.com/q/51836554
tags question: http://stackoverflow.com/q/51845703
tags question: http://stackoverflow.com/q/51919570
tags question: http://stackoverflow.com/q/51885769
tags question: http://stackoverflow.com/q/51954419
tags question: http://stackoverflow.com/q/51856769
tags question: http://stackoverflow.com/q/51830567
tags question: http://stackoverflow.com/q/51865950
tags question: http://stackoverflow.com/q/51879576
tags question: http://stackoverflow.com/q/51883926
tags question: http://stackoverflow.com/q/51937709
tags question: http://stackoverflow.com/q/51814173
tags question: http://stackoverflow.com/q/51880972
tags question: http://stackoverflow.com/q/51840315
tags question: http://stackoverflow.com/q/51945763
tags question: http://stackoverflow.com/q/51828429
tags question: http://stackoverflow.com/q/51924332
tags question: http://stackoverflow.com/q/51817573
tags question: http://stackoverflow.com/q/51864081
tags question: http://stackoverflow.com/q/51887781
tags question: http://stackoverflow.com/q/51879839
tags question: http://stackoverflow.com/q/51823134
tags question: http://stackoverflow.com/q/51824082
tags question: http://stackoverflow.com/q/51860990
tags question: http://stackoverflow.com/q/51862324
tags question: http://stackoverflow.com/q/51851082
tags question: http://stackoverflow.com/q/51922259
tags question: http://stackoverflow.com/q/51954806
tags question: http://stackoverflow.com/q/51851144
tags question: http://stackoverflow.com/q/51871187
tags question: http://stackoverflow.com/q/51814615
tags question: http://stackoverflow.com/q/51848724
tags question: http://stackoverflow.com/q/51914247
tags question: http://stackoverflow.com/q/51847181
tags question: http://stackoverflow.com/q/51950162
tags question: http://stackoverflow.com/q/51846001
tags question: http://stackoverflow.com/q/51879610
tags question: http://stackoverflow.com/q/51803698
tags question: http://stackoverflow.com/q/51822161
tags question: http://stackoverflow.com/q/51834317
tags question: http://stackoverflow.com/q/51908185
tags question: http://stackoverflow.com/q/51814162
tags question: http://stackoverflow.com/q/51820011
tags question: http://stackoverflow.com/q/51897182
tags question: http://stackoverflow.com/q/51934942
tags question: http://stackoverflow.com/q/51884792
tags question: http://stackoverflow.com/q/51877097
tags question: http://stackoverflow.com/q/51845732
tags question: http://stackoverflow.com/q/51886484
tags question: http://stackoverflow.com/q/51819367

http://stackoverflow.com/q/51909771
tagged with: function
upvote count: 5
accepted answer: http://stackoverflow.com/a/51909829
tagged with: class
has comment: http://stackoverflow.com/comment/90769747
has comment: http://stackoverflow.com/comment/90770197
answer count: 1
downvote count: 0
tagged with: attributes
favorite count: 0
has body: Consider this class definition: def func(): x = 5 class Foo: x = x func() I expected this to create a class with an attribute x set to 5 - but instead, it throws a NameError: Traceback (most recent call last): File "untitled.py", line 7, in &lt;module&gt; func() File "untitled.py", line 4, in func class Foo: File "untitled.py", line 5, in Foo x = x NameError: name 'x' is not defined However, that error is only raised inside of a function, and only if x is a local variable. All of these snippets work just fine: x = 5 class Foo: x = x x = 5 def func(): class Foo: x = x func() class Bar: x = 5 class Foo: x = x def func(): x = 5 class Foo: y = x func() What's causing this strange behavior?
tagged with: python
has answer: http://stackoverflow.com/a/51909829
has comment: http://stackoverflow.com/comment/90769751
type: AnsweredQuestion
type: Question
score: 5
has title: Why does assigning to a class attribute with the same name as a local variable raise a NameError?

http://stackoverflow.com/q/51930973
downvote count: 1
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: selenium-webdriver
upvote count: 0
type: Question
has title: Handle digital certificate using selenium in python
score: -1
has answer: http://stackoverflow.com/a/51932155
has body: I am creating a website automation for bank website using selenium in Python in which I am able to open internet explorer and then website , when I am trying to login after inserting user credentials , a security window open to select digital certificate of hdfc bank website. Please tell me how to select digital certificate from that window,due to privacy I cannot share screenshot.

http://stackoverflow.com/q/51882407
has comment: http://stackoverflow.com/comment/90718493
has comment: http://stackoverflow.com/comment/90718293
type: Question
tagged with: flask
has comment: http://stackoverflow.com/comment/90825068
tagged with: python-multithreading
has title: Why does my Python 3 thread not show up every time I call threading.enumerate?
tagged with: python
answer count: 0
score: 0
type: UnansweredQuestion
has body: I have a long running process that I have put on a thread. import subprocess import threading def start_process(): target = subprocess.run(["python3", "workers.py"]) create_thread(target) def create_thread(target): threads = [] name = target.__name__ for t in threading.enumerate(): threads.append(t.name) if name in threads: return False # Thread exists t = threading.Thread(None, target, name) t.start() return "Thread Created." I created a function/Flask route to monitor the thread to see if it is active. This function is for a UI update. @app.route("/info", methods=['GET']) def worker_info(): threads = [] for t in threading.enumerate(): threads.append(t.name) return jsonify({ "thread_count" : threading.active_count(), "ident" : threading.get_ident(), "threads" : threads }) The problem is that the thread name does not always appear when I call threading.enumerate via the flask route. Sometimes it does and sometimes it doesn't.

http://stackoverflow.com/q/51940415
score: 1
type: Question
has answer: http://stackoverflow.com/a/51940461
accepted answer: http://stackoverflow.com/a/51940461
has title: Django NoReverseMatch URL pattern
has body: I am stuck on this error and I am unable to solve it. It a NoReverse Match error. My initial thoughts is they way my url pattern is written. I've tried many different url patterns and it doesn't seem to work. I am not to familiar with when to use path vs re_path. error: django.urls.exceptions.NoReverseMatch: Reverse for 'topic' with arguments '('',)' not found. 1 pattern(s) tried: ['topic/(?P<entry_id>\\d+)/$'] file urls.py: urlpatterns = [ # Home page path('', views.index, name='index'), # Show all Categories path('categories/', views.categories, name='categories'), # Show all topics associated with category re_path(r'^topics/(?P<category_id>\d+)/$', views.topics, name='topics'), # Show single topics re_path(r'^topic/(?P<entry_id>\d+)/$', views.topic, name='topic'), ] views.py: from django.shortcuts import render from .models import Category, Entry, Topic # Create your views here. def index(request): """The home page for Learning Logs""" return render(request, 'blogging_logs/index.html') def categories(request): """show all categories""" categories = Category.objects.all() context = {'categories': categories} return render(request, 'blogging_logs/categories.html', context) def topics(request, category_id): """Show all topics for a single category""" category = Category.objects.get(id=category_id) # get category that was requested topics = category.topic_set.all() # get all topics associated with category that was requested context = {'category': category, 'topics': topics} return render(request, 'blogging_logs/category.html', context) def topic(request, entry_id): """Show entry for single topic""" topic = Topic.objects.get(id=entry_id) entries = topic.entry_set.all() context = {'topic': topic, 'entries': entries} return render(request, 'blogging_logs/topic.html', context) Categories.html {% block content %} Categories {% for category in categories %} {{ category }} {% empty %} No categories entered yet. {% endfor %} {% endblock content %} Category.html {% block con…
upvote count: 1
answer count: 1
tagged with: url
favorite count: 0
tagged with: django
tagged with: python
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/comment/90599252
comment on: http://stackoverflow.com/q/51822589
has text: Wonderful@Brenlla, thks. Could you esplain why does it work?
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/90597361
score: 0
has text: ok, should be good now. Thanks for the help!
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51820271

http://stackoverflow.com/comment/90812052
score: 1
comment on: http://stackoverflow.com/a/51928911
type: AnswerComment
type: Comment
has text: oh wait silly me i've removed my old code :/ also thank you so much for the help!

http://stackoverflow.com/a/52102676
upvote count: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51844679
answers question: http://stackoverflow.com/q/51844679
type: Answer
has body: The problem is that you're trying to pass an np.memmap between processes, and that doesn't work. The simplest solution is to instead pass the filename, and have the child process memmap the same file. When you pass an argument to a child process or pool method via multiprocessing, or return a value from one (including doing so indirectly via a ProcessPoolExecutor), it works by calling pickle.dumps on the value, passing the pickle across processes (the details vary, but it doesn't matter whether it's a Pipe or a Queue or something else), and then unpickling the result on the other side. A memmap is basically just an mmap object with an ndarray allocated in the mmapped memory. And Python doesn't know how to pickle an mmap object. (If you try, you will either get a PicklingError or a BrokenProcessPool error, depending on your Python version.) A np.memmap can be pickled, because it's just a subclass of np.ndarray—but pickling and unpickling it actually copies the data and gives you a plain in-memory array. (If you look at data._mmap, it's None.) It would probably be nicer if it gave you an error instead of silently copying all of your data (the pickle-replacement library dill does exactly that: TypeError: can't pickle mmap.mmap objects), but it doesn't. It's not impossible to pass the underlying file descriptor between processes—the details are different on every platform, but all of the major platforms have a way to do that. And you could then use the passed fd to build an mmap on the receiving side, then build a memmap out of that. And you could probably even wrap this up in a subclass of np.memmap. But I suspect if that weren't somewhat difficult, someone would have already done it, and in fact it would probably already be part of dill, if not numpy itself. Another alternative is to explicitly use the shared memory features of multiprocessing, and allocate the array in shared memory instead of a mmap. But the simplest solution is, as I said at the top, to just pass t…
score: 2

http://stackoverflow.com/comment/90730429
has text: @MadWombat make sense... but my output Tensor remained the same in both examples (as I am trying to predict the a future sequence of length `95` of only 1 feature - i.e. output tensor has shape: `[1,95]`). So technically I am predicting the output as accurately, as the labels are the same in both methods. It is just the input tensor that is shaped differently. Any thoughts?
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51886943
type: Comment

http://stackoverflow.com/a/51825728
accepted answer of: http://stackoverflow.com/q/51825336
score: 0
answers question: http://stackoverflow.com/q/51825336
has comment: http://stackoverflow.com/comment/90613167
has comment: http://stackoverflow.com/comment/90617917
has body: You can try this method (I'm trying to find a link after current page): next_page_url = response.xpath('//li[ ./a[@class="curr"] ]/following-sibling::li[1]/a/@href').extract_first() #next_page_url = response.urljoin(next_page_url) if next_page_url: yield scrapy.Request(url = next_page_url, callback = self.parse) UPDATE According to your new HTML you need this code: next_page_url = response.xpath('//li/a[@aria-label="Next"]/@href').extract_first() if next_page_url: yield scrapy.Request(url = next_page_url, callback = self.parse)
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/90607662
has comment: http://stackoverflow.com/comment/90608093
has comment: http://stackoverflow.com/comment/90607598
has comment: http://stackoverflow.com/comment/90607914
has comment: http://stackoverflow.com/comment/90607592

http://stackoverflow.com/a/51902460
type: Answer
has body: I was able to figure it out. What I was missing was a way to index the query by using "[@name='VARIABLE']" in the XML search. import urllib2 import xml.etree.ElementTree as ET url = "https://MyFirewall/api" response = urllib2.urlopen(url) html = response.read() contents = ET.fromstring(html) rules = [] for item in contents.findall('./result/security/rules/entry'): rules.append(item.attrib['name']) for rule in rules: for item in contents.findall(".//*[@name='" + rule + "']/source/member"): #This line is what I was missing source = item.text for item in contents.findall(".//*[@name='" + rule + "']/destination/member"): #This line is what I was missing destination = item.text if ("any" in source) or ("any" in destination): print "Rule " + rule + "in Device Group : " + device + "contains an ANY" #do stuff
accepted answer of: http://stackoverflow.com/q/51884058
answers question: http://stackoverflow.com/q/51884058
score: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/90770715
type: Comment
type: QuestionComment
score: 0
has text: you passed a point as `self2`, but you aren't referencing it
comment on: http://stackoverflow.com/q/51910150

http://stackoverflow.com/q/51917913
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90785655
tagged with: python
has body: What does myLink = data["items"][0]["link"] do in the code snippet below? I get that it says; if my json data structure has the key "items", but what does the [0]["link"] part do? response = requests.get(resUrl) data = response.json() if data.has_key("items"): myLink = data["items"][0]["link"] else: myLink = "no link found"
score: -3
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/90785637
has answer: http://stackoverflow.com/a/51917983
tagged with: http://stackoverflow.com/tag/json
downvote count: 4
has title: Python; what does myLink = data["items"][0]["link"] do?
answer count: 1
has comment: http://stackoverflow.com/comment/90785666

http://stackoverflow.com/a/75319943
upvote count: 1
answers question: http://stackoverflow.com/q/51846634
downvote count: 0
has body: I'm not sure if this is considered best practice, but another way to achieve the same effect is to use click.get_current_context() as part of a function that computes the default value: @click.command() @click.option( "--param1", type=str, prompt="First parameter", ) @click.option( "--param2", type=str, prompt="Second parameter", default=lambda: myfunct(click.get_current_context().params.get("param1", None)), ) def cmd(param1, param2): pass
type: Answer
score: 1

http://stackoverflow.com/comment/90623153
comment on: http://stackoverflow.com/a/51834703
score: 0
type: AnswerComment
type: Comment
has text: I'm using str as a dummy example here. My actual type of `foo` is a custom class type that does not have a easy default. I have addtional checks to make sure `self.foo` is not used until it's set. But PyLint seems do not know that..

http://stackoverflow.com/comment/90700346
score: 0
type: Comment
has text: @Arpit Regex will only find one match per character. It has already found the match for the first character based on "oracle sql". You can't find every single one.
comment on: http://stackoverflow.com/a/51862990
type: AnswerComment

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

http://stackoverflow.com/a/51895705
accepted answer of: http://stackoverflow.com/q/51895252
answers question: http://stackoverflow.com/q/51895252
score: 2
has body: Use list comprehension with dict comprehension for filtering by colums names: L is list of input data device_data = [{k: v for k, v in x.items() if k in ['type','id']} for x in L] print (device_data) [{'id': 474378238, 'type': 'mdm'}, {'id': 5674657356, 'type': 'mdm'}, {'id': 5674657465, 'type': 'mdm'}, {'id': 9756756756, 'type': 'mdm'}] df = pd.DataFrame(device_data) print (df) id type 0 474378238 mdm 1 5674657356 mdm 2 5674657465 mdm 3 9756756756 mdm
downvote count: 0
upvote count: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90744038
type: Answer

http://stackoverflow.com/comment/90612097
score: 0
type: Comment
has text: Would you please explain why `np.minimum(np.asarray(s1),np.asarray(s2))` leads to `array([ 1., 2., 3., 0., 5.])` instead?
type: AnswerComment
comment on: http://stackoverflow.com/a/51827716

http://stackoverflow.com/a/51944980
score: 2
has comment: http://stackoverflow.com/comment/90842275
upvote count: 2
has comment: http://stackoverflow.com/comment/90839994
has comment: http://stackoverflow.com/comment/90839716
has body: From the documentation Message resource for which one is returned for each message in the response. id string The immutable ID of the message. threadId string The ID of the thread the message belongs to. To add a message or draft to a thread, the following criteria must be met: The requested threadId must be specified on the Message or Draft.Message you supply with your request. The References and In-Reply-To headers must be set in compliance with the RFC 2822 standard. -The Subject headers must match. You cant do a message.get on a message.threadid message.get requires a message.id Can't I query all the messages as a JSON without querying, again and again, using every Id? It seems Google API may block me using throttling mechanism If I query that much of time since I have to query 150000 ids. No there is a limit on the maxResults that can be returned. I think its around 100 but i am not seeing it documented. You are going to have to use the nextPageToken returned in the request to get the next page of results. There is a limit to how fast you can make requests. So keep things reasonable or you will be throttled. Update in response to question edit Can't I query all the fields- If you run the following using fields=* Doc on fields paramater results = service.users().messages().list(userId='me',q="from:xyz@wso2.com", maxResults=10,fields=*).execute() You will notices the response is the same { "id": "1655bb6d0f2b5f8f", "threadId": "1655bb6d0f2b5f8f" }, That is all the fields in the response of a files.list. If you want more information you must do a message.get Gmail quota The quota is large for Gmail for this reason. Most of them can also be extended.
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51944861
accepted answer of: http://stackoverflow.com/q/51944861
has comment: http://stackoverflow.com/comment/90839918
type: Answer
has comment: http://stackoverflow.com/comment/90840044

http://stackoverflow.com/q/51799089
tagged with: slice
type: Question
accepted answer: http://stackoverflow.com/a/51799113
has body: Using slice method in Python we are able to reverse strings and numbers easily. However, how could it be done when the number is negative? def reverse(x): string = str(x) return int(string[::-1]) print(reverse(-123)) Gives an error as it returns 321- EDIT: Now let's have two more assumptions: If the reversed number is not within [−2^31, 2^31 − 1] it should return 0. For numbers like 120, it should return 21 as its reverse. Now, how can we reverse -120 into -21?
has comment: http://stackoverflow.com/comment/90555897
has comment: http://stackoverflow.com/comment/90554740
answer count: 3
tagged with: python
has title: Reversing a negative number in Python
favorite count: 0
has answer: http://stackoverflow.com/a/51799104
possible better answer: http://stackoverflow.com/a/59572502
has answer: http://stackoverflow.com/a/59572502
downvote count: 2
has answer: http://stackoverflow.com/a/51799113
type: AnsweredQuestion
upvote count: 3
score: 1

http://stackoverflow.com/a/51940631
type: Answer
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/118111034
has body: I use os.system to pipe the text to the clip command. I was worried this would be insecure at first because a user could input a shell command as the text to be copied into the clipboard, but I realized since this is a calculator program it should have input validation to not accept any non-numerical input anyway so that solves that problem. def clipboard(text): cmd = 'echo | set /p nul=' + str(text) + '| clip' os.system(cmd)
answers question: http://stackoverflow.com/q/51921386
downvote count: 0
has comment: http://stackoverflow.com/comment/127866626
has comment: http://stackoverflow.com/comment/127866485

http://stackoverflow.com/a/51871155
type: Answer
has comment: http://stackoverflow.com/comment/90693838
answers question: http://stackoverflow.com/q/51871101
has body: Although your question seems a bit unclear but what I infer is that you want a REST API which returns a JSON response after running a business logic on the request params/body. You might want to have a look at http://www.django-rest-framework.org/ to start with writing a REST API with django-rest-framework.
score: 0
has comment: http://stackoverflow.com/comment/90693892

http://stackoverflow.com/comment/90727260
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51888027
score: 1
has text: Dear Obsidian Age and DYZ, I've already tried to replicate this exact same answer, I've already added `#!/usr/bin/env python` and saw dozens of similar posts. Anyway, I couldn't solve the problem. I respectfully ask you to remove the "duplicate" label from my question.

http://stackoverflow.com/comment/90646524
has text: And, how is this related to `numpy` at all?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51846590
score: 1

http://stackoverflow.com/q/51949157
tagged with: factory
has comment: http://stackoverflow.com/comment/90854473
answer count: 0
upvote count: 2
score: 1
tagged with: design-patterns
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/90862994
tagged with: pyqt
has comment: http://stackoverflow.com/comment/90855378
has body: Problem I want a convenient way to create a widget that has a QHBoxLayout or QVBoxLayout as its layout. The type of the widget could be any container widget unknown initially and but specified upon creation. Usage As a class decorator I am repeating a lot of code similar to this. ie. creating the layout and setting it as the layout for the parent widget before adding items. # Insted of this class JukeBox(QDialog): PLAYING, STOPPED, PAUSED = range(3) def __init__(self, *args, **kwargs): super(JukeBox, self).__init__(self, *args, **kwargs) self.state = STOPPED self.mainLayout = QVBoxLayout() self.playBtn = QPushbutton("Play") self.mainLayout.addWidget(self.playBtn) self.setLayout(self.mainLayout) # I want to write this @BoxWidget(QDialog, Qt.Vertical) class JukeBox: PLAYING, STOPPED, PAUSED = range(3) def __init__(self, *args, **kwargs): self.state = JukeBox.STOPPED self.playBtn = QButton("Play") self.layout().addWidget(self.playBtn) As a callable If I can use it as a callable that returns an instance of a specific widget that will be a plus. Then I will not necessarily need to create a subclass each time I wish to use a convenient container widget. # Conveniently create a button box # without having to write a subclass btnBox = BoxedWidget(QFrame, Qt.Horizontal) btnBox.addtoLayout(QPushbutton("OK")) btnBox.addtoLayout(QPushbutton("Cancel") Possible Solutions From the research that I've done it seems the following solutions may solve the problem. Override __new__: I really do not understand the mechanism and behind the scenes work of the __new__ method despite all the blog posts I've read. I mean I do not understand enough to even ask the right questions. Use a metaclass: I'm not really sure about if this solution is possible but like the __new__ I don't really understand the mechanism Create a factory function: Create a BoxedMainWindow, BoxedDialog, BoxedFrame subclasses of BoxedWidget. The factory function then decides from the parameters which type to use in the cr…
tagged with: decorator
has title: Create a subclass whose superclass is known only when it is being created
favorite count: 0
has comment: http://stackoverflow.com/comment/90851437
has comment: http://stackoverflow.com/comment/90855182
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/51937148
tagged with: src
type: Question
answer count: 1
tagged with: beautifulsoup
has body: In python 3 I want to get the links from photos that are on certain pages, such as: http://divulgacandcontas.tse.jus.br/divulga/#/candidato/2018/2022802018/AC/10000600209 http://divulgacandcontas.tse.jus.br/divulga/#/candidato/2018/2022802018/SP/250000627809 I did so: from urllib.request import urlopen from bs4 import BeautifulSoup import urllib.request, urllib.parse, urllib.error html = urlopen('http://divulgacandcontas.tse.jus.br/divulga/#/candidato/2018/2022802018/AC/10000600209') soup = BeautifulSoup(html, "html.parser") link = soup.find("img", {"class": "img-thumbnail img-responsive dvg-cand-foto"}) print(link) None html = urlopen('http://divulgacandcontas.tse.jus.br/divulga/#/candidato/2018/2022802018/SP/250000627809') soup = BeautifulSoup(html, "html.parser") link = soup.find("img", {"class": "img-thumbnail img-responsive dvg-cand-foto"}) print(link) None I intended to collect the set of items next to the photo and define another strategy to get the exact point of the src. As: http://divulgacandcontas.tse.jus.br/candidaturas/oficial/2018/BR/AC/2022802018/10000600209/foto_1532971768767.jpg But what appears in the Inspect Element of the Firefox browser (img class='img-thumbnail img-responsive dvg-cand-foto') was not the same as the html.parser it collected Please, does anyone know how I can collect this photo link on the site? -/- With the use of selenium: from selenium import webdriver from selenium.common.exceptions import NoAlertPresentException from selenium.webdriver.support.select import Select from bs4 import BeautifulSoup profile = webdriver.FirefoxProfile() browser = webdriver.Firefox(profile) browser.implicitly_wait(10) browser.get('http://divulgacandcontas.tse.jus.br/divulga/#/candidato/2018/2022802018/SP/250000627809') html = browser.page_source soup = BeautifulSoup(html, "html.parser") browser.close() link = soup.find("img", {"class": "img-thumbnail img-responsive dvg-cand-foto"})['src'] print(link) http://divulgacandcontas.tse.jus.br/candidaturas/…
has answer: http://stackoverflow.com/a/51937485
tagged with: python
score: 0
has comment: http://stackoverflow.com/comment/90824833
type: UnansweredQuestion
has title: In beautifulsoup, how to collect a photo link that does not appear in the parser?

http://stackoverflow.com/a/51860045
answers question: http://stackoverflow.com/q/51859929
score: 0
type: Answer
has body: I have not worked with spotify api, but from a quick glance at the API docs you should be able to use this https://developer.spotify.com/documentation/web-api/reference/tracks/get-track/ set is_playable to True and you should be able to play it. Code I would do: import requests headers = { 'Authorization': 'Bearer {your access token}', } response = requests.get('https://api.spotify.com/v1/tracks/11dFghVXANMlKmJXsNCbNl', headers=headers) is_playable field will be returned back in the GET call.

http://stackoverflow.com/q/51826131
tagged with: python
has answer: http://stackoverflow.com/a/51826229
has answer: http://stackoverflow.com/a/51827116
score: 0
answer count: 2
possible better answer: http://stackoverflow.com/a/51826229
has body: Lately I've been learning web scraping, with the goal of scraping some news sites. Today I first tried to scrape some search results, but, to my surprise, even though I can find them on Google Chrome's inspector, they don't appear on my BeautifulSoup object. I tried scraping this website: https://www.latercera.com/search/?q=camila%20vallejo I noticed the links are under the tag div, with class 'gsc-wrapper' , so I try: html = urlopen('https://www.latercera.com/search/?q=camila%20vallejo') bs = BeautifulSoup(html, 'html.parser') bs.find('div',{'class':'gsc-wrapper'}) But that brings a Nonetype. After inspecting every link in my object, there's no trace of the search result links. Anyone has any idea of what could be happening? Edit: forgot to mention, the lowest I can go in the parse tree is here: bs.find('div',{'class':'searchresults'}) Which only brings: &lt;div class="searchresults"&gt; &lt;gcse:searchresults-only&gt;&lt;/gcse:searchresults-only&gt; &lt;/div&gt; Even though it should bring every search result
tagged with: web-scraping
tagged with: urllib
accepted answer: http://stackoverflow.com/a/51827116
type: AnsweredQuestion
tagged with: beautifulsoup
type: Question
has title: Search results not appearing for scraping

http://stackoverflow.com/comment/90729545
type: Comment
type: QuestionComment
has text: Could you also add your Product model here
comment on: http://stackoverflow.com/q/51889294
score: 0

http://stackoverflow.com/comment/90848153
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51948766
has text: I tried to change the shell script with "--master yarn --deploy-mode cluster" but it still got the same error.The reason I run spark job with cluster mode is that the local machine is company's server which is limited in resources.When I run the job with client mode,it run successfully.

http://stackoverflow.com/comment/90609449
type: Comment
has text: Its for mocking, not production code. I agree its wonky, but could result in faster mocking. I maybe misunderstanding the role of super().__init__ as well.
type: QuestionComment
comment on: http://stackoverflow.com/q/51827513
score: 0

http://stackoverflow.com/a/51818014
type: Answer
upvote count: 1
has body: Your problem is the scope of the variable cmap. This declaration inside the build method has only local scope. cmap={} If you want to use a global inside a function you need to use the keyword global. global cmap cmap = {} cmap.update(cmap1) cmap.update(cmap2)
score: 1
accepted answer of: http://stackoverflow.com/q/51813091
answers question: http://stackoverflow.com/q/51813091
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/90813885
comment on: http://stackoverflow.com/q/51931752
has text: @BearBrown I've added full traceback
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90594080
score: 0
has text: Is dictionary is what you want?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51820017

http://stackoverflow.com/comment/90850566
has text: It gives Object { data: null, status: -1, headers: zd(), config: {…}, statusText: "", xhrStatus: "error" } and the response now returns HTTP405 OPTIONS response..
comment on: http://stackoverflow.com/a/51826220
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/51824628
accepted answer: http://stackoverflow.com/a/51824838
has body: I have installed pycryptodomex module on python 3.6.5 but when i try to execute the below call, i get the error mentioned in the headline from Crypto.Cipher import AES I want to encrypt a file using AES. How to proceed now ?
possible better answer: http://stackoverflow.com/a/56642877
answer count: 7
favorite count: 0
has comment: http://stackoverflow.com/comment/90603470
linked to: http://stackoverflow.com/q/19623267
tagged with: pycryptodome
tagged with: python
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51824799
has answer: http://stackoverflow.com/a/51824838
downvote count: 1
has answer: http://stackoverflow.com/a/51824697
has answer: http://stackoverflow.com/a/78445545
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/76005430
has answer: http://stackoverflow.com/a/56642877
score: 17
has title: ModuleNotFoundError: No module named 'Crypto' Error
upvote count: 18
type: Question
has answer: http://stackoverflow.com/a/61964541

http://stackoverflow.com/a/51921534
answers question: http://stackoverflow.com/q/51921470
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/103093798
has comment: http://stackoverflow.com/comment/101681846
score: 10
type: AcceptedAnswer
has body: UPDATE as of 2019-07-09 The changelog for PyInstaller==3.5 does state that they now support Python 3.7 on Windows 10. I updated my answer to account for several necro-bumps "it works now", "the second answer should be accepted" and "downvotes" disregarding the time at which the question was asked. The second answer was not the actual solution back then, it clearly fails to state that pip3.7 install PyInstaller==3.5 is a solid fix since 2019-07-09. The question however was asked long before that date. BEFORE 2019-07-09 Not a solution to your problem, but PyInstaller does not support Python 3.7.
accepted answer of: http://stackoverflow.com/q/51921470
has comment: http://stackoverflow.com/comment/104713999
upvote count: 10

http://stackoverflow.com/comment/90669985
type: Comment
comment on: http://stackoverflow.com/q/51857567
has text: @N Chauhan yes i know this
score: 0
type: QuestionComment

http://stackoverflow.com/a/51914046
accepted answer of: http://stackoverflow.com/q/51910391
type: AcceptedAnswer
downvote count: 0
has body: Replace json=request.get_json() with data=request.get_data(). The data parameter of requests.request() takes a dictionary, list of tuples, bytes, or file-like object, and Flask's request.get_data() returns the raw bytes of the body of the request.
upvote count: 2
type: Answer
score: 2
answers question: http://stackoverflow.com/q/51910391

http://stackoverflow.com/comment/90727212
type: AnswerComment
score: 0
type: Comment
has text: Thank you for your response! Very helpful. Can't believe I overlooked that haha. I had one more question, if possible, is there any change I can make to fix the formatting?? For example, the 2. options always has a space. @blhsing
comment on: http://stackoverflow.com/a/51887965

http://stackoverflow.com/a/52039125
type: Answer
downvote count: 1
upvote count: 6
score: 5
has comment: http://stackoverflow.com/comment/98861105
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/98854515
accepted answer of: http://stackoverflow.com/q/51948425
has body: You need to give explicit path of gunicorn. Though I'm not sure about pipenv, but the error you are getting is because supervisor tries to find gunicorn in the directory. You should change your config file into something like this: [program:back] directory=/home/dev/app/ command=/path/to/pipenv run /path/to/gunicorn config.wsgi:application --bind 127.0.0.1:8005 Then you must restart your supervisord in order to load the settings. sudo service supervisord reload
answers question: http://stackoverflow.com/q/51948425

http://stackoverflow.com/a/51846685
score: 0
answers question: http://stackoverflow.com/q/51840520
has body: There are a few things wrong with your code. One of the main issues being that input returns a string, not a float. You need to cast the input value from the user. The standard way to do is like so. item = input("Enter the price, or type 'done'") if item == 'done': ... # Likely break from your loop try: item = float(item) except ValueError: print('Invalid input') The second critical issue is that numbers is a list of list, you should use purchase_amount instead. Although, poping from the list is unnecessary here as you can simply loop over it or, even better, use sum. Here is a fixed version of your code. Fixed code purchase_amount = [] while True: item = input("Enter the price, or type 'done'") if item == 'done': break try: purchase_amount.append(float(item)) except ValueError: print('Invalid input') print(purchase_amount) total = sum(purchase_amount) print(total)
type: Answer

http://stackoverflow.com/q/51895335
has comment: http://stackoverflow.com/comment/90741340
tagged with: pyserial
has body: Read Serial Using PySerial the following program was created: import serial class comunicacao(): def __init__(self, porta, baud): s = serial.Serial(porta, baud) data = s.read(18) data = data print("Data: ", (data)) comunicacao('COM7', 57600) It is receiving the number 10000 in decimal for tests, and the print output is: Data: b'\x020000000000002710\x03' Because 2710 in HEX is 10000 in DEC. Conversion So trying to convert with the following ways: print("Data: ", int(data, 16)) gives teh error: print("Data: ", int(data, 16)) ValueError: invalid literal for int() with base 16: b'\x020000000000002710\x03' With data = s.read(18).decode() the print output is Data: 0000000000002710 and trying to convert with int() gives the error: print("Data: ", int(data, 16)) ValueError: invalid literal for int() with base 16: '\x020000000000002710\x03' data = data.lstrip("0") with data = s.read(18).decode() didn't strip the leading zeroes. And data = data.lstrip("0") with data = s.read(18) gives the error: print("Data: ", (data.lstrip("0"))) TypeError: a bytes-like object is required, not 'str' Question How to convert this data type (I think it is as ASCII, but is a HEX number) to DEC?
answer count: 1
has comment: http://stackoverflow.com/comment/90741665
linked to: http://stackoverflow.com/q/509211
has comment: http://stackoverflow.com/comment/90741232
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51895906
has comment: http://stackoverflow.com/comment/90741259
tagged with: python
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/90742559
type: Question
accepted answer: http://stackoverflow.com/a/51895906
has comment: http://stackoverflow.com/comment/90741735
has title: Read Serial and Convert HEX to DEC

http://stackoverflow.com/q/51926889
has title: Read 3 files into Pandas Dataframe with latest modified time
type: Question
linked to: http://stackoverflow.com/q/168409
has comment: http://stackoverflow.com/comment/90804335
has body: I have a folder in which my python program generated text files (data in CSV format) are stored. I want to read 3 files (File Name Starts with LogFile_Date) into Pandas Dataframe with latest modified time. I am using Windows Operating System and Python 3.
possible better answer: http://stackoverflow.com/a/51929206
score: 0
has comment: http://stackoverflow.com/comment/90805240
answer count: 2
tagged with: pandas
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/51928068
tagged with: python
has answer: http://stackoverflow.com/a/51929206
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51928068
has comment: http://stackoverflow.com/comment/90804878

http://stackoverflow.com/comment/90708336
has text: Assuming they're already in sorted order (the assumption this answer makes) and sticking with the using a `dict` to retain the last entry then it's a little simpler to use: `res = list({el[0]: el for el in d}.values())`
comment on: http://stackoverflow.com/a/51878124
score: 1
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/90664795
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51856268
has text: As @tobias_k said, you would end up replacing all `Type:` throughout the sentence. You could use `startswith` here before replacing
type: AnswerComment

http://stackoverflow.com/comment/90729028
has text: I suppose the question might not be very clear but jdehesa's answer is what I was looking for.
comment on: http://stackoverflow.com/q/51880270
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90670617
score: 0
type: Comment
has text: So you want the weights in pairs (I suppose to balance bar ... one at each end) I think you just need to double the plates so the list will be 90, 70, 50, 20 and so on ... and then execute the same algorithm.
comment on: http://stackoverflow.com/a/51853563
type: AnswerComment

http://stackoverflow.com/a/51929741
type: AcceptedAnswer
has body: Basically, because of the Zen of Python which says: Explicit is better than implicit. Complex is better than complicated. From the OOD (object-oriented design) perspective you are having strong dependencies between two classes, since you cannot initialize B without calling specific method of class A, that may be ok for now, but moving forward such dependency may lead to the problems in long time run. To get deeper understanding of that make sure you are familiart Single responsibility principle and Separation of concerns principles. Generally speaking - If some method of the another class shall be always called during initializing, maybe that method shall be moved out from another class. As an alternative, you can create utility function which will handle that without introducing hard dependency between classes. Also, the solution provided in the SO question differs, since it has dynamic call of the method to the name isn't hardcoded like in your sample.
type: Answer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51929528
answers question: http://stackoverflow.com/q/51929528
score: 3
upvote count: 3

http://stackoverflow.com/comment/90836714
type: QuestionComment
comment on: http://stackoverflow.com/q/51942246
score: 0
has text: a better idea is change the `__str__` in profile to `print (self.user)`
type: Comment

http://stackoverflow.com/a/51874098
has comment: http://stackoverflow.com/comment/90702077
has comment: http://stackoverflow.com/comment/90701588
has comment: http://stackoverflow.com/comment/90702955
type: Answer
has comment: http://stackoverflow.com/comment/90699713
has body: I don't see a problem with the current code. I think you can double check if the extractor is able to find the relevant places/entities or not. You can always run the extractor to see what entities it has fetched from the URL. Extractor code to get a better understanding of what is happening behind the scenes. from geograpy import extraction e = extraction.Extractor(url='https://www.netmagicsolutions.com/cloud-infrastructure-services') e.find_entities() You can also access all the places - by using e.places
answers question: http://stackoverflow.com/q/51873598
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/90699753
has comment: http://stackoverflow.com/comment/90700267
has comment: http://stackoverflow.com/comment/90702062
has comment: http://stackoverflow.com/comment/90699823
has comment: http://stackoverflow.com/comment/90701970
has comment: http://stackoverflow.com/comment/90699912
upvote count: 1

http://stackoverflow.com/comment/90715247
type: Comment
comment on: http://stackoverflow.com/a/51881810
score: 0
type: AnswerComment
has text: @GergesDib: thanks, edited

http://stackoverflow.com/a/51918296
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51918244
score: 1
answers question: http://stackoverflow.com/q/51918244
has comment: http://stackoverflow.com/comment/90786877
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90786482
has comment: http://stackoverflow.com/comment/90787447
has comment: http://stackoverflow.com/comment/90786493
has comment: http://stackoverflow.com/comment/90786707
has body: You can use a neat trick with sum() to join nested lists: [[sum(l, [])] for l in a] #[[[1, 2, 3, 4, 5, 6]], [[7, 8, 9, 10, 11, 12]]] Just to make it clearer why this works, consider the following example: &gt;&gt;&gt; sum([[1,2], [3,4]], []) [1, 2, 3, 4] Or you could use the more efficient itertools.chain_from_iterable method: flatten = itertools.chain.from_iterable [[list(flatten(l))] for l in a] #[[[1, 2, 3, 4, 5, 6]], [[7, 8, 9, 10, 11, 12]]]
has comment: http://stackoverflow.com/comment/90786470
type: Answer

http://stackoverflow.com/a/51935131
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51934958
has body: AFAIK {int} is not a meaningful format specifier for Bokeh tooltips, and if it is displaying anything at all, that's only because the unknown specifier is being ignored. There is fairly detailed documentation on formatting hover tooltips in the Formatting Tooltip Fields section of the User's Guide. Offhand, it looks like you want something like: tooltip_net_rev = [("Net Revenue", "%@y{0,0.00}")]
has comment: http://stackoverflow.com/comment/90820442
accepted answer of: http://stackoverflow.com/q/51934958
upvote count: 7
score: 7
type: AcceptedAnswer

http://stackoverflow.com/a/51922076
type: Answer
answers question: http://stackoverflow.com/q/51921965
upvote count: 2
score: 2
downvote count: 0
has body: You can easily play music in loops with PyGame, which is pre-installed in the Pi I believe: import pygame pygame.mixer.init() pygame.mixer.music.load("myFile.wav") pygame.mixer.music.play(-1) # note -1 for playing in loops # do whatever # when ready to stop do: pygame.mixer.pause() If you want to unpause: pygame.mixer.unpause()

http://stackoverflow.com/comment/90733546
has text: @DanielRoseman thank you for the thorough feedback. I have amended the query above with the solution.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51890199

http://stackoverflow.com/comment/90557508
has text: These are called multisets and can be generated with `multiset_permutations ` from `sympy` .
score: 0
comment on: http://stackoverflow.com/q/51799320
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51841722
has comment: http://stackoverflow.com/comment/90636637
has comment: http://stackoverflow.com/comment/90636611
type: Answer
has comment: http://stackoverflow.com/comment/90636839
has comment: http://stackoverflow.com/comment/90636552
has comment: http://stackoverflow.com/comment/90636671
has comment: http://stackoverflow.com/comment/90636750
has comment: http://stackoverflow.com/comment/90637021
has comment: http://stackoverflow.com/comment/90637089
has comment: http://stackoverflow.com/comment/90636570
has comment: http://stackoverflow.com/comment/90637023
answers question: http://stackoverflow.com/q/51841653
has body: replace loads with load when dealing with file object which supports read like operation def main(conn): global link, link_ID with open('ad_link.json', 'r') as statusFile: status = json.load(statusFile) status=json.loads(status) link = status["link"] link_ID = status["link_id"] print(link) print(link_ID)
has comment: http://stackoverflow.com/comment/90636602
score: 0
has comment: http://stackoverflow.com/comment/90637003
has comment: http://stackoverflow.com/comment/90636748

http://stackoverflow.com/comment/90702986
has text: Ok, I have now my data but with ����. What should I do in client side application?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51873624
type: AnswerComment

http://stackoverflow.com/comment/90673021
comment on: http://stackoverflow.com/q/51860382
score: 0
type: QuestionComment
has text: Does it have to be in pure python or can you use numpy?
type: Comment

http://stackoverflow.com/a/51807041
downvote count: 0
has body: My answer is not that different from others, except I don't understand why everyone is using lists. A list is not required here because it won't be altered, a tuple is fine and more efficient: for item in '2/1.5','-3/-4.5': # Don't need a list here num1, num2 = item.split('/') print((float(num1) + float(num2)) / 2)
has comment: http://stackoverflow.com/comment/90569702
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/51806906
score: 1

http://stackoverflow.com/comment/90596159
comment on: http://stackoverflow.com/q/51821166
has text: It is not a good practice to use the `file` as variable name. Consider switching to a different variable name such as `inFile`. Regarding your error, it has to do with `from os import *` line as it is mentioned in a different question [here](https://stackoverflow.com/questions/1046656/an-integer-is-required-open).
type: Comment
type: QuestionComment
score: 1

global
type: Tag
tags question: http://stackoverflow.com/q/51829362
tags question: http://stackoverflow.com/q/51887533
tag name: global

http://stackoverflow.com/comment/90569813
has text: what type `candidates` is?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51804721

http://stackoverflow.com/q/51874257
has comment: http://stackoverflow.com/comment/90700842
answer count: 1
has comment: http://stackoverflow.com/comment/90700985
has answer: http://stackoverflow.com/a/51874987
type: UnansweredQuestion
tagged with: pandas
upvote count: 0
has comment: http://stackoverflow.com/comment/90700342
has body: INPUT 9(05) X(5) X(15) X(15) X(15) S9(07) S9(2)V9(2) OUTPUT a b c d 9 05 NaN NaN X 5 NaN NaN X 15 NaN NaN S9 07 NaN NaN S9 02 V9 2
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/90700698
tagged with: python
score: -2
has title: In a dataframe I had a column like this. 9(05) X(5) X(15) X(15) X(15) S9(07) S9(2)V9(2) I want to split them into four different into columns
downvote count: 2

http://stackoverflow.com/q/51842371
downvote count: 0
type: UnansweredQuestion
tagged with: pyqt5
tagged with: qtableview
tagged with: unit-testing
type: Question
score: 1
tagged with: pyqt
upvote count: 1
answer count: 1
has body: My GUI (PyQt5, Python3.6) displays data from an SQLite database, mostly using QTableViews. I'm unit-testing the application using defined input files, and I want to check whether everything is shown in the GUI at the right place. Now, all the data is in the model attached to the QTableView, not the QTableView itself. And I sometimes use QTableView.hideRow() to hide some of the columns which are present in the raw data but not desired to be shown in this particular view. How can I test that everything is displayed in the expected place in the QTableView? Here's a mini example class I'd like to write unit tests for: #!/usr/bin/python3 # -*- coding: utf-8 -*- from PyQt5 import QtSql from PyQt5.QtWidgets import (QWidget, QTableView, QApplication, QHBoxLayout) import sys class Example(QWidget): def __init__(self): super().__init__() self.resize(400, 150) self.createConnection() self.fillTable() self.createModel() self.initUI() def createConnection(self): self.db = QtSql.QSqlDatabase.addDatabase("QSQLITE") self.db.setDatabaseName("test.db") if not self.db.open(): print("Cannot establish a database connection") return False def fillTable(self): self.db.transaction() q = QtSql.QSqlQuery() q.exec_("DROP TABLE IF EXISTS Cars;") q.exec_("CREATE TABLE Cars (Company TEXT, Model TEXT, Year NUMBER);") q.exec_("INSERT INTO Cars VALUES ('Honda', 'Civic', 2009);") q.exec_("INSERT INTO Cars VALUES ('VW', 'Golf', 2013);") q.exec_("INSERT INTO Cars VALUES ('VW', 'Polo', 1999);") self.db.commit() def createModel(self): self.model = QtSql.QSqlTableModel() self.model.setTable("Cars") self.model.select() def initUI(self): layout = QHBoxLayout() self.setLayout(layout) view = QTableView() layout.addWidget(view) view.setModel(self.model) view.hideRow(1) def closeEvent(self, e): if (self.db.open()): self.db.close() def main(): app = QApplication(sys.argv) ex = Example() ex.show() sys.exit(app.exec_()) if __name__ == '__main__': main() I can test the data in the model, of course: self.assertEqua…
favorite count: 0
has title: Unit Test for content of PyQt.QTableView
tagged with: python
has answer: http://stackoverflow.com/a/51843027

http://stackoverflow.com/comment/90565831
comment on: http://stackoverflow.com/q/51804842
type: Comment
score: 0
has text: The test_data is from 2018-01-01 to 2018-07-12
type: QuestionComment

http://stackoverflow.com/q/51862682
accepted answer: http://stackoverflow.com/a/51862872
tagged with: dataframe
has answer: http://stackoverflow.com/a/51863059
has title: Pandas Assign Same Number of Random Values
possible better answer: http://stackoverflow.com/a/51862756
tagged with: numpy
answer count: 4
has answer: http://stackoverflow.com/a/51862756
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51862853
type: Question
has body: I have a dataframe of tasks that I need to randomly assign to workers. Each task should receive one random worker, and each worker should have the same number of tasks as the other workers. import pandas as pd import numpy as np tasks = ['Task 1','Task 2','Task 3','Task 4','Task 5','Task 6','Task 7','Task 8','Task 9'] df = pd.DataFrame({'Tasks':tasks}) Tasks 0 Task 1 1 Task 2 2 Task 3 3 Task 4 4 Task 5 5 Task 6 6 Task 7 7 Task 8 8 Task 9 What I want is to assign a random number between 1-3 to each task. But each number should happen 3 times. So expected result: Tasks Assign 0 Task 1 1 1 Task 2 2 2 Task 3 2 3 Task 4 3 4 Task 5 3 5 Task 6 1 6 Task 7 2 7 Task 8 3 8 Task 9 1 I've thought about using numpy, but can't find the function that fits my requirement. something like np.random.randint(1,4, size=(1,9)) perhaps? If there is not an equal number of tasks to workers - assign the last task randomly
tagged with: pandas
tagged with: python
has answer: http://stackoverflow.com/a/51862872
score: 0

http://stackoverflow.com/q/51879954
upvote count: 1
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51880318
possible better answer: http://stackoverflow.com/a/51880157
tagged with: join
has body: I have these two urls: absolute_url = 'https://ciechgroup.com/en/relacje-inwestorskie/reports/current-reports' relative_url = 'en/relacje-inwestorskie/reports/current-reports/2018/242018/' And I'd like to join them to create this: https://ciechgroup.com/en/relacje-inwestorskie/reports/current-reports/2018/242018/ However, urljoin doesn't join the urls together correctly: from urllib.parse import urljoin urljoin(absolute_url, relative_url) &gt;&gt; https://ciechgroup.com/en/relacje-inwestorskie/reports/en/relacje-inwestorskie/reports/current-reports/2018/242018/ Do you know how I can achieve this without duplicating part of the url?
tagged with: urllib
type: Question
answer count: 2
downvote count: 0
tagged with: url
score: 1
accepted answer: http://stackoverflow.com/a/51880318
tagged with: python
favorite count: 0
has title: Python urljoin not joining relative and absolute urls together correctly
has answer: http://stackoverflow.com/a/51880157

http://stackoverflow.com/a/51914205
has comment: http://stackoverflow.com/comment/90802197
type: Answer
has comment: http://stackoverflow.com/comment/91048480
has comment: http://stackoverflow.com/comment/90802603
downvote count: 0
has comment: http://stackoverflow.com/comment/91048377
has comment: http://stackoverflow.com/comment/90801827
score: 1
has comment: http://stackoverflow.com/comment/91048182
has body: You can use ^(?:[\w ](?! (AND|OR) ))+$ The repeated [\w ] ensures that all characters are either word characters or spaces, nothing else. After each character, negative lookahead for (AND|OR) to ensure that neither of those are standalone words: https://regex101.com/r/LyRr5U/2 If you also want to exclude standalone words, add positive lookahead to the beginning of the regex to ensure that there are some word characters separated by spaces somewhere in the string: ^(?=.*\w +\w)(?:[\w ](?! (AND|OR) ))+$
has comment: http://stackoverflow.com/comment/90801436
accepted answer of: http://stackoverflow.com/q/51914173
has comment: http://stackoverflow.com/comment/90802100
answers question: http://stackoverflow.com/q/51914173
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91047933

http://stackoverflow.com/a/51848929
accepted answer of: http://stackoverflow.com/q/51848856
score: 0
answers question: http://stackoverflow.com/q/51848856
type: AcceptedAnswer
has body: d = poly[1] That will extract a reference to the dictionary in the second position of the poly list and store it in the new name d. You can then use it to get what you want print(d['MenuSelections']['MenuSelection']) You can also index poly[1] directly: print(poly[1]['MenuSelections']['MenuSelection'][0]['PLU']) will print 44
type: Answer
upvote count: 1
downvote count: 1

http://stackoverflow.com/a/51955808
answers question: http://stackoverflow.com/q/51951686
score: 1
upvote count: 1
has body: In your model define a column like this: editing_date = db.Column(db.DateTime, onupdate=datetime.utcnow)
downvote count: 0
type: Answer

http://stackoverflow.com/q/51924836
has title: python-docx will not autocomplete on IDEs
tagged with: python-docx
score: 0
tagged with: python
tagged with: pycharm
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/73532441
has body: I recently started using python-docx to work with Word documents and for some reason, it doesn't show up in the autocomplete. I tried VSCode and PyCharm. Other added libraries autocomplete fine in both. I found this issue, but it is closed and the response is to ask in SO. I would appreciate any help. Also, if this doesn't work out, is there any other python library to work with docx?
tagged with: autocomplete
has answer: http://stackoverflow.com/a/51936397
type: Question
answer count: 2
tagged with: visual-studio-code

http://stackoverflow.com/q/51878112
has body: I have the following problem. I want to extract data from hdfs (a table called 'complaint'). I wrote the following script which actually works: import pandas as pd from hdfs import InsecureClient import os file = open ("test.txt", "wb") print ("Step 1") client_hdfs = InsecureClient ('http://XYZ') N = 10 print ("Step 2") with client_hdfs.read('/user/.../complaint/000000_0') as reader: print('new line') features = reader.read(1000000) file.write(features) print('end') file.close() My problem now is that the folder "complaint" contains 4 files ( i don't know which file type) and the read operation gives me back bytes which I can't use further (I saved it to a textfile as a test and it looks like that: In HDFS it looks like this: My question now is: Is it possible to get the data separated for each column in a senseful way? I only found solutions with .csv files and like that and somehow stuck here... :-) EDIT I made changes to my solution and tried different approaches but none of them is going to work really. Here's the updated code: import pandas as pd from hdfs import InsecureClient import os import pypyodbc import pyspark from pyspark import SparkConf, SparkContext from hdfs3 import HDFileSystem import pyarrow.parquet as pq import pyarrow as pa from pyhive import hive #Step 0: Configurations #Connections with InsecureClient (this basically works) #Notes: TMS1 doesn't work because of txt files #insec_client_tms1 = InsecureClient ('http://some-adress:50070') insec_client_tms2 = InsecureClient ('http://some-adress:50070') #Connection with Spark (not working at the moment) #Error: Java gateway process exited before sending its port number #conf = SparkConf().setAppName('TMS').setMaster('spark://adress-of-node:7077') #sc = SparkContext(conf=conf) #Connection via PyArrow (not working) #Error: File not found #fs = pa.hdfs.connect(host='hdfs://node-adress', port =8020) #print("FS: " + fs) #connection via HDFS3 (not working) #The module couldn't be load #client_hdfs = HDFil…
has comment: http://stackoverflow.com/comment/90714283
has comment: http://stackoverflow.com/comment/90717995
has comment: http://stackoverflow.com/comment/90744722
has title: Python on Hadoop read blocks
has comment: http://stackoverflow.com/comment/90712122
has comment: http://stackoverflow.com/comment/90773442
answer count: 0
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/44027519
has comment: http://stackoverflow.com/comment/90709998
has comment: http://stackoverflow.com/comment/90730079
type: Question
tagged with: hadoop
tagged with: hdfs
has comment: http://stackoverflow.com/comment/90812259
has comment: http://stackoverflow.com/comment/90802857
has comment: http://stackoverflow.com/comment/90713397
score: 0

http://stackoverflow.com/q/51915625
has title: Using pytest when tests are in a separate folder
has comment: http://stackoverflow.com/comment/90782026
answer count: 1
favorite count: 0
tagged with: python-3.x
linked to: http://stackoverflow.com/q/10253826
has body: my python folder structure is as follows repository -libraries -image -imagefuncs.py -videos -videofuncs.py -text -textfuncs.py -docs -tests -test_imagefuncs.py For the life of me i cannot figure out how I am supposed to test my functions defined in imagefuncs.py in test_imagefuncs.py I cannot import the libraries folder in test_imagefuncs.py so none of those functions are visible to my testing code. I'm using python3 and all i want to achieve is do py.test from my root repository folder and have all my tests execute without throwing import errors. Is modifying the python path the only way to go about achieving this? I want to achieve this without modifying the system path or python path
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51939701
upvote count: 4
has comment: http://stackoverflow.com/comment/90782089
tagged with: pytest
downvote count: 0
has comment: http://stackoverflow.com/comment/90781214
tagged with: unit-testing
type: Question
score: 4

http://stackoverflow.com/a/51852931
upvote count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/90733063
has body: specify the id field explicitly and add empty validators as, class IPSerializer(serializers.ModelSerializer): id = serializers.IntegerField(validators=[]) class Meta: model = IP fields = ['id', 'host_name', 'ip_address'] UPDATE class IPSerializer(serializers.ModelSerializer): class Meta: model = IP fields = ['id', 'host_name', 'ip_address'] def __init__(self, *args, **kwargs): nested = kwargs.pop('nested', False) super().__init__(*args, **kwargs) if nested: self.fields.update( {"id": serializers.IntegerField(validators=[])} ) class IPGroupSerializer(serializers.ModelSerializer): ips = IPSerializer(many=True, nested=True) # Your code
has comment: http://stackoverflow.com/comment/90658664
type: Answer
answers question: http://stackoverflow.com/q/51850412
score: 1
has comment: http://stackoverflow.com/comment/90658734
has comment: http://stackoverflow.com/comment/90742892
has comment: http://stackoverflow.com/comment/90659301
has comment: http://stackoverflow.com/comment/90659319

http://stackoverflow.com/q/51903521
answer count: 3
tagged with: http://stackoverflow.com/tag/html
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51905096
tagged with: selenium
has answer: http://stackoverflow.com/a/51903832
type: Question
has body: I'm new to selenium and javascript but I'm trying to write Python that will change a date for sports results. The scoreboard page has a &lt; MM/DD/YYYY > at the top. The "current" date (01/05/2018 opens as the default when the page is loaded) is in the middle and &lt; &amp; > have: &lt;a href="javascript:changeDate('01/05/2018');"&gt;&lt;&lt;/a&gt; " 01/05/2018 " &lt;a href="javascript:changeDate('01/07/2018);"&gt;&gt;&lt;/a&gt; ==$0 &lt;form name="params_form" action="/team/schedule_list" method="post"&gt; &lt;input id="params_form_schedule_date" type="hidden" name="schedule_date" value="01/05/2018"&gt; == $0 &lt;/form&gt; Earlier in the html the site has: &lt;script language="javascript"&gt; function changeDate(val){ $('#params_form_schedule_date').val(val); document.params_form.submit(); } In Python I have tried: date = input ('Enter Date (mm/dd/yyyy): ') driver.execute_script('changeDate()', date) driver.execute_script(''' var date = arguments[0]; changeDate().value;''', date) I've tried a few others too but nothing works. The loading circle will show that something is happening, but the default date does not change. Any help here would be appreciated. (Also I tried to follow the proper formatting here, but I apologize for any mistakes, it's my first time posting).
has answer: http://stackoverflow.com/a/51905135
has title: How can I execute javascript to change a date with python and selenium
tagged with: javascript
score: 0

http://stackoverflow.com/q/51885086
has body: I need to find the position of an index based on the existence of an value in a numerical array. I understand that I can use the .index(value) method for list but the thing is I don't want the code to exit or given None or any other type of exception if the value is not present in the array. Instead I would like to know the adjacent array indices values if the exact value is not present in the list. Hope the below example makes the problem statement clear. arr = [10,20,30,40,50] Input: 25 Output: 1,2 Input: 20 Output: 1 Basically the code returns the indices of the adjacent values in the array within which the search input is looked for.
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51885147
duplicate of: http://stackoverflow.com/q/3196610
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/90721744
has comment: http://stackoverflow.com/comment/90721883
score: 0
linked to: http://stackoverflow.com/q/3196610
upvote count: 1
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/90721832
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/51885147
has title: Position of an element in an array
tagged with: python
has comment: http://stackoverflow.com/comment/90721783

getstream-io
type: Tag
tag name: getstream-io
tags question: http://stackoverflow.com/q/51939633

http://stackoverflow.com/comment/90831559
type: QuestionComment
comment on: http://stackoverflow.com/q/51940556
has text: If your library can implement the concept of a linear operator, with a matrix-vector product, you might be able to use the sparse linear algebra package: https://docs.scipy.org/doc/scipy/reference/sparse.linalg.html
score: 0
type: Comment

http://stackoverflow.com/q/51818252
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90590681
score: 1
has comment: http://stackoverflow.com/comment/90590428
has body: I'm trying to create my own decorator in order to validate a REST call with Django (using Django Rest Framework). The decorator looks like this: def allowed_states(allowed=[]): def decorator(func): def wrapper(self, request, *args, **kwargs): print(func) result = func(self, request, *args, **kwargs) return result return wrapper return decorator The request API looks something like this: @swagger_auto_schema( operation_id="my_api", responses={ status.HTTP_204_NO_CONTENT: "", } ) @action(detail=True, methods=["DELETE"]) @allowed_states(allowed=["state1", "state2"]) def my_api(self, request, *args, **kwargs): # do some stuff here When my @allowed_states decorator is removed, the call works just fine. When I add it back I get a 404 error from Django framework saying it could not find a url pattern to execute for this call. I tried removing self from wrapper (and from the func invoke as well). Also I tried changing the decorators order above the function call. Both didn't work. The stack trace doesn't say much, merely that django could not find the url pattern: Using the URLconf defined in my_project.urls, Django tried these URL patterns, in this order: (and then the order of url patterns as they appear in my_project.urls)
has comment: http://stackoverflow.com/comment/90592116
has comment: http://stackoverflow.com/comment/90590448
has comment: http://stackoverflow.com/comment/90590628
has comment: http://stackoverflow.com/comment/90590480
has comment: http://stackoverflow.com/comment/90591085
downvote count: 0
answer count: 1
has title: Using a decorator with Django blocks the request
tagged with: django-rest-framework
has answer: http://stackoverflow.com/a/51824629
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/90590821
tagged with: python-decorators
has comment: http://stackoverflow.com/comment/90590834
has comment: http://stackoverflow.com/comment/90590774
accepted answer: http://stackoverflow.com/a/51824629
tagged with: django
upvote count: 1
has comment: http://stackoverflow.com/comment/90590508
type: Question

http://stackoverflow.com/comment/90586238
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51815777
score: 0
has text: What is `folds`?

http://stackoverflow.com/q/51865326
tagged with: sap-gui
has comment: http://stackoverflow.com/comment/90683281
tagged with: win32com
has comment: http://stackoverflow.com/comment/90684271
has answer: http://stackoverflow.com/a/51865603
has comment: http://stackoverflow.com/comment/90683737
has comment: http://stackoverflow.com/comment/90683952
has answer: http://stackoverflow.com/a/51865582
has comment: http://stackoverflow.com/comment/90683185
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/51865438
has comment: http://stackoverflow.com/comment/90683048
has comment: http://stackoverflow.com/comment/90683247
score: 0
has comment: http://stackoverflow.com/comment/90683342
has body: Is there an easy way to execute time delay (like time.sleep(3)) between every statement of Python code without having to explicitly write between every statement? Like in the below Python Script which performs certain action on SAP GUI window. Sometimes, the script continues to the next statement before the previous statement is complete. So, I had to add a time delay between every statement so that it executes correctly. It is working with time delay, but I end up adding time.sleep(3) between every line. Just wondering if there is a better way? import win32com.client import time sapgui = win32com.client.GetObject("SAPGUI").GetScriptingEngine session = sapgui.FindById("ses[0]") def add_record(employee_num, start_date, comp_code): try: time.sleep(3) session.findById("wnd[0]/tbar[0]/okcd").text = "/npa40" time.sleep(3) session.findById("wnd[0]").sendVKey(0) time.sleep(3) session.findById("wnd[0]/usr/ctxtRP50G-PERNR").text = employee_num time.sleep(3) session.findById("wnd[0]").sendVKey(0) time.sleep(3) session.findById("wnd[0]/usr/ctxtRP50G-EINDA").text = start_date time.sleep(3) session.findById("wnd[0]/usr/tblSAPMP50ATC_MENU_EVENT/ctxtRP50G-WERKS[1,0]").text = comp_code time.sleep(3) session.findById("wnd[0]/usr/tblSAPMP50ATC_MENU_EVENT/ctxtRP50G-PERSG[2,0]").text = "1" time.sleep(3) session.findById("wnd[0]/usr/tblSAPMP50ATC_MENU_EVENT/ctxtRP50G-PERSK[3,0]").text = "U1" time.sleep(3) session.findById("wnd[0]/usr/tblSAPMP50ATC_MENU_EVENT").getAbsoluteRow(0).selected = True time.sleep(3) return "Pass" except: return "failed"
has comment: http://stackoverflow.com/comment/90683884
has comment: http://stackoverflow.com/comment/90684477
tagged with: python
has comment: http://stackoverflow.com/comment/90682866
has title: Add time delay between every statement of python code
has comment: http://stackoverflow.com/comment/90683234
answer count: 4
has comment: http://stackoverflow.com/comment/90683104
favorite count: 0
has comment: http://stackoverflow.com/comment/90683033
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90683050
downvote count: 2
has comment: http://stackoverflow.com/comment/90683580
has comment: http://stackoverflow.com/comment/90683371
has answer: http://stackoverflow.com/a/51865416

http://stackoverflow.com/comment/90806039
comment on: http://stackoverflow.com/q/51927850
has text: @tobias_k It's about hashing. Integers hash to themself, with no salting.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90562320
score: 0
type: Comment
type: QuestionComment
has text: In case it's Nmap causing the problem, add `--noninteractive` to your Nmap options to tell it not to look for terminal input.
comment on: http://stackoverflow.com/q/51799687

http://stackoverflow.com/comment/90748837
score: 2
has text: Think about a pandas series as a dictionnary. The first columns are the keys and the second the values. Therefore `targets_test[0]` should do the trick. (or `targets_test.iloc[0]` if you have a custom index).
comment on: http://stackoverflow.com/q/51898845
type: Comment
type: QuestionComment

nao-robot
tags question: http://stackoverflow.com/q/51847900
tag name: nao-robot
type: Tag

http://stackoverflow.com/comment/90777164
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51913511
has text: It dosesn't work

http://stackoverflow.com/q/51893313
favorite count: 0
upvote count: 8
has answer: http://stackoverflow.com/a/51897617
tagged with: python
type: AnsweredQuestion
has body: I need a QTableWidget based on a QTabelModel and QTableView with some buttons added above the table. See the following figure: The width of the QTableWidget should be adjusted so that it is not smaller than a reasonable minimum and not extend beyond the buttons above it; in particular, the size of the columns 1, 2, and 4 should be adjusted to their contents, and the 3rd column, Aberrations, should be expanded to fill in the gap on the right side. I'd like to know how to do this in code. The following is a minimal example of the code I use for the custom QTableWidget (PyQt5, Python3): from PyQt5 import QtGui, QtCore, QtWidgets import numpy as np #-- Table Model class MyTableModel(QtCore.QAbstractTableModel): def __init__(self, data, parent=None, *args): super(MyTableModel, self).__init__(parent) # table data self.table_data = data self.rows_nr, self.columns_nr = data.shape # vertical &amp; horizontal header labels self.hheaders = ["Head-{}".format(i) for i in range(self.columns_nr)] self.vheaders = ["Row-{}".format(i) for i in range(self.rows_nr)] # nr of rows def rowCount(self, parent): return self.rows_nr # nr of columns def columnCount(self, parent): return self.columns_nr # row and column headers def headerData(self, section, orientation, role): if role == QtCore.Qt.DisplayRole: if orientation == QtCore.Qt.Horizontal: return self.hheaders[section] #END if #ELSE: return QtCore.QVariant() # display table contents def data(self, index, role=QtCore.Qt.DisplayRole): r_ = index.row() c_ = index.column() if role == QtCore.Qt.DisplayRole: return "{}".format(data[r_, c_]) #ELSE: return QtCore.QVariant() # set data def setData(self, index, value, role): r_ = index.row() c_ = index.column() # editable fields if role == QtCore.Qt.EditRole: # interprete values self.table_data[r_,c_] = str(value) return True # view/edit flags def flags(self, index): r_ = index.row() c_ = index.column() return QtCore.Qt.ItemIsEnabled class MyTableWidget(QtWidgets.QWidget): def __init__(self, da…
tagged with: pyqt5
type: Question
accepted answer: http://stackoverflow.com/a/51897617
tagged with: qtablewidget
score: 8
has title: Adjust the size (width/height) of a custom QTableWidget
tagged with: pyqt
answer count: 1
downvote count: 0
tagged with: resize

http://stackoverflow.com/comment/90758200
type: AnswerComment
type: Comment
has text: I'm having trouble understanding how X[i] can be substracted by self.X_train. The foremost is a matrix of size (1x3072) while the other one is of size (5000x3072). Substraction of matrices requires them to be of the same size, no? What exactly tells Python that it needs to execute the substraction of the left-component on each individual row of the right-component? And in what order (since to save into `dists[i]`, it should know somehow that the first row of the right-component should be associated with the first row of the `dists` matrix)?
score: 0
comment on: http://stackoverflow.com/a/51902523

http://stackoverflow.com/comment/90803148
score: 3
comment on: http://stackoverflow.com/q/51926781
type: Comment
type: QuestionComment
has text: What are you trying to do, and what is the expected output?

http://stackoverflow.com/comment/90651568
type: QuestionComment
has text: @NathanielJones Oh I see about the "..." thing. I have no idea why `python.exe` isn't in your tarball. I think it should be...
score: 0
comment on: http://stackoverflow.com/q/51832108
type: Comment

http://stackoverflow.com/comment/90576504
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51810751
type: Comment
has text: This is exactly what I needed, I will accept this answer!

http://stackoverflow.com/q/51944520
type: Question
upvote count: 15
has answer: http://stackoverflow.com/a/51952033
downvote count: 0
answer count: 1
score: 15
has title: Python type hinting a deque filled with myclass objects
accepted answer: http://stackoverflow.com/a/51952033
tagged with: python-typing
favorite count: 0
has body: using Python 3.6 or newer, I want to type hint a function myfunc that returns an object of MyClass. How can I hint, that myqueue is a deque filled with MyClass objects? from collections import deque global_queue = deque() class MyClass: pass def myfunc(myqueue=global_queue) -&gt; MyClass: return myqueue.popleft() for i in range(10): global_queue.append(MyClass())
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/a/51945481
downvote count: 0
has body: You can change the color of your text and also the size: size='x-small' for x111,y1 in zip(x1,loss_list): plt.text(x111, y1, '%.2f' % y1,color='black',horizontalalignment='center',verticalalignment='bottom') for x112,y2 in zip(x1,val_loss_list): plt.text(x112, y2, '%.2f' % y2,color='black',horizontalalignment='center',verticalalignment='bottom')
upvote count: 2
type: Answer
score: 2
answers question: http://stackoverflow.com/q/51945206

http://stackoverflow.com/q/51814313
score: 0
has comment: http://stackoverflow.com/comment/90619688
has comment: http://stackoverflow.com/comment/90618784
type: UnansweredQuestion
tagged with: python
answer count: 0
type: Question
has body: Is it possible to have the results of this loop outputted to a calendar? from datetime import datetime from datetime import timedelta turns = 2 dayson = 11 dayoff = 17 total_day = 0 for j in range(0,(turns)): for k in range(0,dayson): d = datetime.now() + timedelta(days=total_day) dt = d.strftime('%m/%d/%Y') + " Do Task" print(dt) total_day += 1 for l in range(0,dayoff): d = datetime.now() + timedelta(days=total_day) dt = d.strftime('%m/%d/%Y') + " Don't Do Task" print(dt) total_day += 1 This is a partial output of the results. I would like to have it look like a calendar with the Do Task or Don't Do Task in the date box. 08/12/2018 Do Task 08/13/2018 Do Task 08/14/2018 Do Task 08/15/2018 Do Task 08/16/2018 Do Task 08/17/2018 Do Task 08/18/2018 Do Task 08/19/2018 Do Task 08/20/2018 Do Task 08/21/2018 Do Task 08/22/2018 Do Task 08/23/2018 Don't Do Task 08/24/2018 Don't Do Task 08/25/2018 Don't Do Task 08/26/2018 Don't Do Task 08/27/2018 Don't Do Task Thanks
has comment: http://stackoverflow.com/comment/90583312
has comment: http://stackoverflow.com/comment/90653105
has title: For Loop to create Date/Task and convert to calendar

http://stackoverflow.com/q/51859794
has answer: http://stackoverflow.com/a/51859953
accepted answer: http://stackoverflow.com/a/51859953
has body: I have a dataframe like this (many rows): Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec a 34 24 47 30 11 57 47 44 22 33 16 39 b 50 53 42 23 19 29 38 46 21 18 13 24 . . . . . . . I would like to create a new df with the rolling 3 month percentage change values, so the [1,1] element will be the % change between the value of Apr and the value of Jan, the [1,2] element wiil be the % change between May and Feb etc... Therefore, for each value, I want the % change between this value and the value 3 months ago This is the sample output that I want (for example the first value is [(30-34)/34]*100 = -11.7): Apr May Jun Jul Aug Sep Oct Nov Dec a -11.7% -54.1% 0% 56.6% 300% .. .. .. .. . . . . I know that pandas have the .pct_change but this does not calculate the percentages in the way that I want. Any ideas on how I can do this in python? Thank you
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
has title: Rolling percentage change in Python data frame
tagged with: python
type: AnsweredQuestion
type: Question
score: 3
upvote count: 3

http://stackoverflow.com/comment/90808869
comment on: http://stackoverflow.com/q/51929133
has text: This answer might help: https://stackoverflow.com/a/40586333/4604579
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/51863993
type: AnsweredQuestion
has title: Add new level to MultiIndex when concatenating
has comment: http://stackoverflow.com/comment/90680513
score: 1
accepted answer: http://stackoverflow.com/a/51864122
type: Question
tagged with: concatenation
answer count: 1
downvote count: 0
favorite count: 0
has body: A few data frames identical in size, columns and indices but varying a bit in content are concatenated. What would be the best way of generating a new index such that the original indices remain the same, but the outermost index now represents the data frame number that was concatenated? DataFrame A: Idx1 | Idx2 || Col 0 0 'A' 1 'B' 1 0 'C' 1 'D' DataFrame B: Idx1 | Idx2 || Col 0 0 'E' 1 'F' 1 0 'G' 1 'H' DataFrame AB: Idx0 | Idx1 | Idx2 || Col 0 0 0 'A' 1 'B' 1 0 'C' 1 'D' 1 0 0 'E' 1 'F' 1 0 'G' 1 'H' I'm still not so comfortable with my indices and stacking, but I imagine that would be needed. Any help is greatly appreciated! Sandbox: A = pd.DataFrame({'Col': ['A', 'B', 'C', 'D'], 'Idx1': [0,0,1,1], 'Idx2':[0,1,0,1]}) B = pd.DataFrame({'Col': ['E', 'F', 'G', 'H'], 'Idx1': [0,0,1,1], 'Idx2':[0,1,0,1]}) A.set_index(keys=['Idx1', 'Idx2'], inplace=True) B.set_index(keys=['Idx1', 'Idx2'], inplace=True)
tagged with: pandas
linked to: http://stackoverflow.com/q/49620538
has answer: http://stackoverflow.com/a/51864122
has comment: http://stackoverflow.com/comment/90680443
upvote count: 1
tagged with: python

http://stackoverflow.com/q/51867433
tagged with: performance
tagged with: arrays
answer count: 2
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/51870034
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51869760
tagged with: python
has title: Value in an array between two numbers in python
has body: So making a title that actually explains what i want is harder than i thought, so here goes me explaining it. I have an array filled with zeros that adds values every time a condition is met, so after 1 time step iteration i get something like this (minus the headers): current_array = bubble_size y_coord 14040 42 3943 71 6345 11 0 0 0 0 .... After this time step is complete this current_array gets set as previous_array and is wiped with zeros because there is not a guaranteed number of entries each time. NOW the real question is i want to be able to check all rows in the first column of the previous_array and see if the current bubble size is within say 5% either side and if so i want to take the current y position away for the value associated with the matching bubble size number in the previous_array's second column. currently i have something like; if bubble_size in current_array[:, 0]: do_whatever but i don't know how to pull out the associated y_coord without using a loop, which i am fine with doing (there is about 100 rows to the array and atleast 1000 time steps so i want to make it as efficient as possible) but would like to avoid i have included my thoughts on the for loop (note the current and previous_array are actually current and previous_frame) for y in range (0, array_size): if bubble_size &gt;&gt; previous_frame[y,0] *.95 &amp;&amp;&lt;&lt; previous_frame[y, 0] *1.05: distance_travelled = current_y_coord - previous_frame[y,0] y = y + 1 Any help is greatly appreciated :)
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/90691836
has comment: http://stackoverflow.com/comment/90721672
type: Question
tagged with: numpy

http://stackoverflow.com/comment/90791405
score: 2
type: AnswerComment
type: Comment
has text: *"... create 3 more classes, maybe called Wall, GreenRect, and BlackRect which implement their own update method."* Yes, I recommend creating several subclasses instead of the different `update` methods as well. The walls can stay normal `pygame.Rect`s.
comment on: http://stackoverflow.com/a/51918644

http://stackoverflow.com/a/51935314
accepted answer of: http://stackoverflow.com/q/51934283
type: AcceptedAnswer
has body: If you want to pass an additional argument to the slots you can use partial as shown below: import sys from functools import partial from PyQt5 import QtWidgets QSS = """ QToolButton::checked{ background-color: blue } """ class Widget(QtWidgets.QWidget): def __init__(self, parent=None): super(Widget, self).__init__(parent) self.listA = [0 for _ in range(24)] self.listB = [0 for _ in range(24)] lay = QtWidgets.QVBoxLayout(self) hlay1 = QtWidgets.QHBoxLayout() hlay2 = QtWidgets.QHBoxLayout() lay.addLayout(hlay1) lay.addLayout(hlay2) for i, val in enumerate(self.listA): button = QtWidgets.QToolButton() button.setCheckable(True) hlay1.addWidget(button) button.clicked.connect(partial(self.callbackA, i)) button.setStyleSheet(QSS) for i, val in enumerate(self.listB): button = QtWidgets.QToolButton() button.setCheckable(True) hlay2.addWidget(button) button.clicked.connect(partial(self.callbackB, i)) button.setStyleSheet(QSS) def callbackA(self, index, state): self.listA[index] = 1 if state else 0 print("listA: ") print(self.listA) def callbackB(self, index, state): self.listB[index] = 1 if state else 0 print("listB: ") print(self.listB) if __name__ == '__main__': import sys app = QtWidgets.QApplication(sys.argv) w = Widget() w.show() sys.exit(app.exec_())
upvote count: 3
type: Answer
has comment: http://stackoverflow.com/comment/90820763
downvote count: 0
answers question: http://stackoverflow.com/q/51934283
score: 3

http://stackoverflow.com/a/62940228
upvote count: 1
type: Answer
downvote count: 0
score: 1
has body: I am also a MAC user, but found adding the code below fixed my problem with "no module named sip": from PyQt5.QtCore import QCoreApplication
answers question: http://stackoverflow.com/q/51808229

http://stackoverflow.com/comment/90797194
has text: Because the OP is checking if the value is greater than 130. `range(-50, 130)` gives the sequence [-50, 129], so negating using `not` is equivalent to checking `>= 130`, not `> 130`.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51923690

http://stackoverflow.com/comment/90667841
has text: yes it would omit if you are using 3 months. But if there are no three months left to re sample, then you can stop your resampling right there and for those extra two months, you can use different resampling criteria
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51857010

http://stackoverflow.com/a/51851920
has body: I think you do not need to assign the index since it is from 0 to len(df), also using the numpy array with mix data type will cause problem , since you output data type is object not int pd.DataFrame({'A':[1,4,7],'B':[2,5,8],'C':[3,6,9]}) Out[1104]: A B C 0 1 2 3 1 4 5 6 2 7 8 9
has comment: http://stackoverflow.com/comment/90656700
downvote count: 0
upvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/90656786
score: 2
answers question: http://stackoverflow.com/q/51851884
has comment: http://stackoverflow.com/comment/90656773

http://stackoverflow.com/q/51919664
upvote count: 1
has answer: http://stackoverflow.com/a/51920670
answer count: 1
favorite count: 0
has body: I have a feature in my pandas data frame which can take on (potentially) several levels. I can obtain the unique levels using the following: reasons = df["Reason"].unique() I can plot a the counts of all the levels on a single graph doing the following: for reason in reasons: df[df['Reason']== reason].groupby('date').count()['twp'].plot() plt.title(reason) plt.tight_layout() How can I modify this code so that it can create a separate graph for each level? Furthermore, I would want ensure scalability as well. (For example if the number of unique levels is currently 3, but in the future we can end up with 5 levels). Thank you in advance!
has comment: http://stackoverflow.com/comment/90789248
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90789100
downvote count: 0
score: 1
tagged with: matplotlib
type: Question
accepted answer: http://stackoverflow.com/a/51920670
has title: Python Plots - Loop through unique values of a feature and plot
tagged with: pandas

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

http://stackoverflow.com/q/51886044
answer count: 2
score: -1
has body: I have a dictionary text file and I want to add to every word a string like "http://" + word + ".com" I tried this: f = open('esp.txt', 'r') urls = open('urls.txt', 'w') while True: nline = 1 contentCOM = 'http://www.' + f.readlines(nline) + '.com' contentCOM.write(urls) nline = nline + 1 But it gives me the following error: TypeError: Must be str, not list
accepted answer: http://stackoverflow.com/a/51886220
has comment: http://stackoverflow.com/comment/90723626
downvote count: 2
upvote count: 1
possible better answer: http://stackoverflow.com/a/51886171
has answer: http://stackoverflow.com/a/51886220
favorite count: 0
tagged with: python-3.x
has title: How to add a string to a string read in a text file in Python 3?
has comment: http://stackoverflow.com/comment/90723873
tagged with: python
has comment: http://stackoverflow.com/comment/90723670
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51886171
type: Question
has comment: http://stackoverflow.com/comment/90723742

dialogflow-es
tags question: http://stackoverflow.com/q/51821919
tag name: dialogflow-es
tags question: http://stackoverflow.com/q/51871907
tags question: http://stackoverflow.com/q/51823453
tags question: http://stackoverflow.com/q/51945916
type: Tag
tags question: http://stackoverflow.com/q/51868606
tags question: http://stackoverflow.com/q/51855169
tags question: http://stackoverflow.com/q/51835669
tags question: http://stackoverflow.com/q/51916177

http://stackoverflow.com/comment/90666416
type: Comment
comment on: http://stackoverflow.com/a/51848512
has text: Also is there a way I could create grid lines around those circles such that each circle should be inside the grid box?
score: 0
type: AnswerComment

http://stackoverflow.com/q/51836870
tagged with: svm
score: 0
tagged with: libsvm
answer count: 1
type: UnansweredQuestion
has title: Calculate equation of hyperplane using LIBSVM support vectors and coefficients in Python
tagged with: python
has answer: http://stackoverflow.com/a/51850808
has body: I am using the LIBSVM library in python and am trying to reconstruct the equation (w'x + b) of the hyperplane from the calculated support vectors. The model appears to train correctly but I am unable to manually calculate prediction results that match the output of svm_predict for the test data. I have used the below link from the FAQ to try and troubleshoot but I am still not able to calculate the correct results. https://www.csie.ntu.edu.tw/~cjlin/libsvm/faq.html#f804 My code is as follows: from svmutil import * import numpy as np ytrain, xtrain = svm_read_problem('small_train.libsvm') # Change labels from 0 to -1 for index in range(len(ytrain)): if ytrain[index] == 0: ytrain[index] = -1.0 print ("Training set loaded...") m = svm_train(ytrain, xtrain, '-q') print ("Model trained...") sv = np.asarray(m.get_SV()) sv_coef = np.asarray(m.get_sv_coef()) sv_indices = np.asarray(m.get_sv_indices()) rho = m.rho[0] w = np.zeros(len(xtrain[0])) b = -rho # weight vector w = sum over i ( coefsi * xi ) for index, coef in zip(sv_indices, sv_coef): ai = coef[0] for key in xtrain[index-1]: w[key] = w[key] + (ai * xtrain[index-1][key]) # From LIBSVM FAQ - Doesn't seem to impact results # if m.label[1] == -1: # w = np.negative(w) # b = -b print(np.round(w,2)) ytest, xtest = svm_read_problem('small_test.libsvm') # Change labels from 0 to -1 for index in range(len(ytest)): if ytest[index] == 0: ytest[index] = -1.0 print ("Test set loaded...") print ("Predict test set...") p_label, p_acc, p_val = svm_predict(ytest, xtest, m) print("p_label: ", p_label) print("p_val: ", np.round(p_val,3)) for i in range(len(ytest)): wx = 0 for key in xtest[i]: wx = wx + (xtest[i][key] * w[key]) print("Manual calc: ", np.round(wx + b,3)) My understanding is that my manually calcualted results, using wx+b, should match those contained in p_val. I have tried negating both w and b and have still not been able to get the same results as those in p_val. The data sets (LIBSVM format) I am using are: small_tra…
type: Question

http://stackoverflow.com/q/51903619
linked to: http://stackoverflow.com/q/20960110
tagged with: python
tagged with: module
score: 2
has title: How to throw DeprecationWarning when users are importing a module?
type: AnsweredQuestion
upvote count: 2
accepted answer: http://stackoverflow.com/a/51903782
has comment: http://stackoverflow.com/comment/90758518
type: Question
has comment: http://stackoverflow.com/comment/90758649
tagged with: warnings
has body: So I looked for a bit but I wasn't finding anything that talked about my issue, so I decided to open a new question. My question is, how can I throw a DeprecationError in python if a user were to import a module that has been renamed? Quick Example of what I would be trying to accomplish: &gt;&gt;&gt; import foo.bar as foobar DeprecationWarning: import foo.bar is deprecated and will be removed in a future release, please use import foo.bar2 in order to access the goodness of foo bar I tried to something like this in the bar file (for this example): bar.py import stuff warnings.warn("import foo.bar is deprecated and will be removed in a future release, please use import foo.bar2 in order to access the goodness of foo bar", DeprecationWarning) But unfortunately this did not work when I ran a test script and imported the module. Is there something that I am missing? How can I run the code in the module on loading of the module?
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/51903782
favorite count: 0

http://stackoverflow.com/comment/90593741
score: 0
has text: @iam.Carrot Then just use `*`: `"([- ]*)".join`. Or maybe you want something more precise like `"(\s*(-)?\s*)".join` which does not match things like `----`. the point is the grouping. By using `(-)?|( )` the alternation `|` is *not* just between `(-)?` and `( )` but its scope extends to the words around making it match stuff like `a-` or `b` but not `a-b`... Hope you got this
comment on: http://stackoverflow.com/q/51819606
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90690890
comment on: http://stackoverflow.com/a/51843832
type: Comment
score: 0
has text: You can! Check my edited answer for a more fleshed out example. Is that what you're looking for? You can have any number of Django views returning the same template.
type: AnswerComment

http://stackoverflow.com/q/51804872
has comment: http://stackoverflow.com/comment/90565580
has answer: http://stackoverflow.com/a/51805010
downvote count: 0
tagged with: pandas
type: AnsweredQuestion
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/90565614
accepted answer: http://stackoverflow.com/a/51805010
type: Question
tagged with: candlestick-chart
answer count: 2
has comment: http://stackoverflow.com/comment/90565638
upvote count: 1
has comment: http://stackoverflow.com/comment/90565666
has title: Working with Pandas - Max, Min, First, Last
tagged with: python
has answer: http://stackoverflow.com/a/51804940
has body: I have a pandas dataframe in python that is stock prices by the minute. I want to use it to create a "3 minute" chart. To do that I need to work backwards across the dataframe and consolidate it as follows. Open is the first "open" value in the set of 3 High is the max value in the set of 3 Min is the min value in the set of 3 Close is the las "close value in the set of 3 I need help with the right sytanx to: create sets of 3 pull out the values that I need and put into a new dataframe Here is what I have so far but it isn't working. I'm doing something wrong. import pandas as pd stock = 'SPY' api = 'https://api.iextrading.com/1.0/stock/'+stock+'/chart/1d' df = pd.read_json(api) df['stock'] = stock df1= df'stock', 'label', 'open', 'high', 'low', 'close' dct = {'open': 'first', 'high': 'max', 'low': 'min', 'close': 'last', 'stock': 'first', 'label': 'last'} (df1.set_index(pd.to_datetime(df1.label, errors='coerce')) .groupby(pd.Grouper(freq='3min')) .agg(dct) .reset_index(drop=True) )
possible better answer: http://stackoverflow.com/a/51804940

http://stackoverflow.com/q/51854735
upvote count: 1
has title: Dictionary to global environment python
answer count: 1
has body: I have attempted to open a list of cvs files in a loop using python. I started with the idea to open the files to a dictionary as I been told to do not attempt to dynamically create names on the fly, I tried the following code Load all csv files filenames = ["broaderRelationsSkillPillar.csv","ISCOGroups_en.csv"] dataframes ={} ## create a dictionary Create the list of three DataFrames: dataframes for i in filenames : dataframes[i] = pd.read_csv(i) until here it all happens smoothly. for k ,v in dataframes.items(): [k] = pd.DataFrame.from_dict(dataframes[k]) note - my issue happens here ,my result here is only one of the 2 data frames would I be able to open this csv files directly froma loop and name them on the fly? I have around 20 csv's and I'm trying to automate a bit the code. tks Question edited to facilitate support create dictionaies d = {'col1': [1, 2], 'col2': [3, 4]} a = {'col3': [1, 2], 'col4': [3, 4]} c = {'col3': [1, 2], 'col4': [3, 4]} Pass to a data frame d= pd.DataFrame(data=d) a= pd.DataFrame(data=a) c= pd.DataFrame(data=c) create a list of dataframes filenames = [a ,d ,c] create a dictionary of dataframes dataframes ={} ## create a dictionary for i in filenames : dataframes[i] = i del a , c, d from a dictionary of data frames back to data frames ( here is where i failed , why?) for k ,v in dataframes.items(): k = pd.from_dict(dataframes[k])
favorite count: 0
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/51854783
has comment: http://stackoverflow.com/comment/90665130
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51854783
has comment: http://stackoverflow.com/comment/90664425
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/90661856
type: Question
has comment: http://stackoverflow.com/comment/90675334
has comment: http://stackoverflow.com/comment/90661835
has comment: http://stackoverflow.com/comment/90661959
has comment: http://stackoverflow.com/comment/90661868
tagged with: pandas

http://stackoverflow.com/q/51898999
has answer: http://stackoverflow.com/a/51899185
upvote count: 0
has comment: http://stackoverflow.com/comment/90749050
type: AnsweredQuestion
score: -1
has comment: http://stackoverflow.com/comment/90748992
type: Question
tagged with: numpy
answer count: 3
has comment: http://stackoverflow.com/comment/90749589
has answer: http://stackoverflow.com/a/51900636
has title: Python - cut only the descending part of the dataset
has comment: http://stackoverflow.com/comment/90749358
accepted answer: http://stackoverflow.com/a/51899185
favorite count: 0
possible better answer: http://stackoverflow.com/a/51899135
has answer: http://stackoverflow.com/a/51899135
tagged with: pandas
downvote count: 1
has body: I have a timeseries with various downcasts. My question is how do I slice a pandas dataframe (or in this case the array, just to keep it simple) to get the data and its indexes of the descending bits of the timeseries? import matplotlib.pyplot as plt import numpy as np b = np.asarray([ 1.3068586 , 1.59882279, 2.11291473, 2.64699527, 3.23948166, 3.81979878, 4.37630243, 4.97740025, 5.59247254, 6.18671493, 6.77414586, 7.43078595, 8.02243495, 8.59612224, 9.22302662, 9.83263379, 10.43125902, 11.0956864 , 11.61107838, 12.09616684, 12.63973254, 12.49437955, 11.6433792 , 10.61083269, 9.50534291, 8.47418827, 7.40571742, 6.56611512, 5.66963658, 4.89748187, 4.10543794, 3.44828054, 2.76866318, 2.24306623, 1.68034463, 1.26568186, 1.44548443, 2.01225076, 2.60715524, 3.21968562, 3.8622007 , 4.57035958, 5.14021305, 5.77879484, 6.42776897, 7.09397923, 7.71722028, 8.30860725, 8.96652218, 9.66157193, 10.23469208, 10.79889453, 10.5788411 , 9.38270646, 7.82070643, 6.74893389, 5.68200335, 4.73429009, 3.78358222, 3.05924946, 2.30428171, 1.78052369, 1.27897065, 1.16840532, 1.59452726, 2.13085096, 2.70989933, 3.3396291 , 3.97318058, 4.62429262, 5.23997774, 5.91232803, 6.5906609 , 7.21099657, 7.82936331, 8.49636247, 9.15634983, 9.76450244, 10.39680729, 11.04659976, 11.69287237, 12.35692643, 12.99957563, 13.66228386, 14.31806385, 14.91871927, 15.57212978, 16.22288287, 16.84697357, 17.50502002, 18.15907842, 18.83068151, 19.50945548, 20.18020639, 20.84441358, 21.52792846, 22.17933087, 22.84614545, 23.51212887, 24.18308399, 24.8552263 , 25.51709528, 26.18724379, 26.84531493, 27.50690265, 28.16610365, 28.83394822, 29.49621179, 30.15118676, 30.8019521 , 31.46714114, 32.1213546 , 32.79366952, 33.45233007, 34.12158193, 34.77502197, 35.4532211 , 36.11018053, 36.76540453, 37.41746323]) plt.plot(-b) plt.show()
tagged with: python

http://stackoverflow.com/a/51849911
type: Answer
has comment: http://stackoverflow.com/comment/90653194
answers question: http://stackoverflow.com/q/51849851
has comment: http://stackoverflow.com/comment/90653204
has body: That doesn't look like valid json to me... {"jsonrpc": "2.0", "result": [{"status": "3", "name": "Linux operating system", "triggers": [{"triggerid": "10010"}, {"triggerid": "10011"}, {"triggerid": "10012"}, {"triggerid": "10016"}, {"triggerid": "10021"}, {"triggerid": "10041"}, {"triggerid": "10042"}, {"triggerid": "10043"}, {"triggerid": "10044"}, {"triggerid": "10045"}, {"triggerid": "10047"}, {"triggerid": "10190"}, {"triggerid": "13000"}, {"triggerid": "13243"}, {"triggerid": "13508"}, {"triggerid": "17316"}, {"triggerid": "17317"}, {"triggerid": "17318"}, {"triggerid": "17319"}, {"triggerid": "17320"}], "items": [{"name": "Host name of apache running"}, {"name": "local ping"}, {"name": "Version of apache-agent(d) running"}, {"name": "Maximum number of opened files"}, {"name": "Maximum number of processes"}, {"name": "Number of running processes"}, {"name": "Number of processes"}, {"name": "Host boot time"}, {"name": "calls per second"}, {"name": "Processor load (2 min average per core)"}, {"name": "Processor load (15 min average per core)"}, {"name": "Processor load (5 min average per core)"}, {"name": "Context switches per second"}, {"name": "CPU $2 time"}, {"name": "CPU $2 time"}, {"name": "CPU $2 time"}, {"name": "CPU $2 time"}, {"name": "CPU $2 time"}, {"name": "CPU $2 time"}, {"name": "CPU $2 time"}, {"name": "CPU $2 time"}, {"name": "Host name"}, {"name": "Host local time"}, {"name": "Free swap space"}, {"name": "Free swap space in %"}, {"name": "Total swap space"}, {"name": "System information"}]}]} Try testing yours out... https://jsonformatter.curiousconcept.com/ https://jsonformatter.org/
score: 0

http://stackoverflow.com/q/51935107
has comment: http://stackoverflow.com/comment/90821686
tagged with: pathlib
linked to: http://stackoverflow.com/q/48836470
has comment: http://stackoverflow.com/comment/90820449
has answer: http://stackoverflow.com/a/51940038
answer count: 1
has comment: http://stackoverflow.com/comment/90820452
has comment: http://stackoverflow.com/comment/90826710
favorite count: 0
has comment: http://stackoverflow.com/comment/90822082
has title: pathlib.Path(path).mkdir(), not creating directory
has comment: http://stackoverflow.com/comment/90822524
has comment: http://stackoverflow.com/comment/90821394
has body: I am trying to implement logging for my flask project on a virtual machine (running Ubuntu-16.04). I have the following function for creating a new directory. def mkdir_p(path): try: pathlib.Path(path).mkdir(parents=True, exist_ok=True) except FileExistsError as exc: raise And the following file handler inheriting from RotatingFileHandler. class MyRotatingFileHandler(RotatingFileHandler): def __init__(self, filename, mode='a', maxBytes=0, backupCount=0, encoding=None, delay=0): mkdir_p(os.path.dirname(filename)) RotatingFileHandler.__init__(self, filename, mode, maxBytes, backupCount, encoding, delay) This all works fine when registering a new logger at runtime, on my local machine, but when I try and run this same code on an azure instance, the path and file I am passing in ('log/error.log'), isn't created. I have made sure the user running the code has write permissions set on the directory. I really can't think of any other reason why this might be happening though.
has comment: http://stackoverflow.com/comment/90821043
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51940038
tagged with: mkdir
has comment: http://stackoverflow.com/comment/90820759
upvote count: 2
score: 1
has comment: http://stackoverflow.com/comment/90820793
has comment: http://stackoverflow.com/comment/90820425
downvote count: 1
tagged with: logging
type: Question

http://stackoverflow.com/q/51904459
answer count: 2
has comment: http://stackoverflow.com/comment/90760257
has body: I have a number of classes where there are functions inside are almost the same. Say function x: class A(): def x_A (self): ... ...do the same thing ... run a function that is unique in class A itself, say u_A ... ...do the same thing ... class B(): def x_B (self): ... ...do the same thing .. run a function that is unique in class B itself, say u_B ... ...do the same thing ... So I came up with an idea to re-write function x in a new class(say x_C in class C) to replace x_A and x_B. And I just have to import that new class when I need it. something like: import C class A(): def x_A (self): C.x_C(u_A) class B(): def x_B (self): C.x_C(u_A) but I am confused of how to pass in the unique function (u_A and u_B) as a variable and make python to run it properly. class C(): def x_C (self,unique_function): ... ...do the same thing .. run unique_function here ... ...do the same thing ... Thx in advance blow is newly edited: hi trying to specify my question: I have a number of crawlers, at the end of each I got "run_before_insert" to check if they can run properly. Currently I just copy and paste this function at end of every finished crawler with some edits. But now I would like to simplify my code by importing "run_before_insert" from other files, and then comes my questions. def run_before_insert(self): try: #store_list = [] comp_name = 'HangTen' start = time.time() print('{} runBeforeInsert START'.format(comp_name), '\n') ###Here is the part where small edits in the function: store_list = self.get_stores_2() ###the rest is the same script_info = {} running_time = round(time.time() - start,2) total = str(len(store_list)) script_info['running_time'] = running_time script_info['total_stores'] = total print('\n{} total stores : {}'.format(comp_name,script_info['total_stores']), '\n') print('{} running time : {}'.format(comp_name,script_info['running_time']), '\n') print('{} runBeforeInsert Done'.format(comp_name), '\n') print('\n') return script_info except Exception as e: tra…
type: UnansweredQuestion
has title: use functions from other class in python
tagged with: class
has answer: http://stackoverflow.com/a/51904492
tagged with: function
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90760254
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/51905055
score: 0

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

http://stackoverflow.com/q/51838479
type: Question
tagged with: indexing
score: 3
has body: Say I have the dataset from the example here: import pandas as pd raw_data = {'regiment': ['Nighthawks', 'Nighthawks', 'Nighthawks', 'Nighthawks', 'Dragoons', 'Dragoons', 'Dragoons', 'Dragoons', 'Scouts', 'Scouts', 'Scouts', 'Scouts'], 'company': ['1st', '1st', '2nd', '2nd', '1st', '1st', '2nd', '2nd','1st', '1st', '2nd', '2nd'], 'name': ['Miller', 'Jacobson', 'Ali', 'Milner', 'Cooze', 'Jacon', 'Ryaner', 'Sone', 'Sloan', 'Piger', 'Riani', 'Ali'], 'preTestScore': [4, 24, 31, 2, 3, 4, 24, 31, 2, 3, 2, 3], 'postTestScore': [25, 94, 57, 62, 70, 25, 94, 57, 62, 70, 62, 70]} df = pd.DataFrame(raw_data, columns = ['regiment', 'company', 'name', 'preTestScore', 'postTestScore']) df I want to do a boxplot of regiment vs preTestScore. For that, I need to find out the relative distribution of these 2 variables. So, I group regiment by preTestScore: df1 = df['regiment'].groupby(df['preTestScore']).count() df1 preTestScore 2 3 3 3 4 2 24 2 31 2 Name: regiment, dtype: int64 If I try to do the boxplot now, it gives an error: import seaborn as sns sns.boxplot(data=df1) --------------------------------------------------------------------------- KeyError Traceback (most recent call last) &lt;ipython-input-131-8296ca940a25&gt; in &lt;module&gt;() 1 df1 = df['regiment'].groupby(df['preTestScore']).count() 2 df1 ----&gt; 3 sns.boxplot(data=df1) ~\AppData\Local\Continuum\anaconda3\lib\site-packages\seaborn\categorical.py in boxplot(x, y, hue, data, order, hue_order, orient, color, palette, saturation, width, dodge, fliersize, linewidth, whis, notch, ax, **kwargs) 2209 plotter = _BoxPlotter(x, y, hue, data, order, hue_order, 2210 orient, color, palette, saturation, -&gt; 2211 width, dodge, fliersize, linewidth) 2212 2213 if ax is None: ~\AppData\Local\Continuum\anaconda3\lib\site-packages\seaborn\categorical.py in __init__(self, x, y, hue, data, order, hue_order, orient, color, palette, saturation, width, dodge, fliersize, linewidth) 439 width, dodge, fliersize, linewidth): 440 --&gt; 441…
tagged with: group-by
tagged with: dataframe
tagged with: pandas
downvote count: 0
answer count: 1
linked to: http://stackoverflow.com/q/45273731
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/51838619
has title: How to convert the data structure obtained after performing a groupby operation on a pandas dataframe into a dataframe?
type: AnsweredQuestion
upvote count: 3
accepted answer: http://stackoverflow.com/a/51838619

http://stackoverflow.com/comment/90819019
type: QuestionComment
score: 6
comment on: http://stackoverflow.com/q/51934451
has text: If this is **working code** that you think could be improved, see [codereview.se]. If not, please clarify the problem with it.
type: Comment

opencv
tags question: http://stackoverflow.com/q/51826607
type: Tag
tags question: http://stackoverflow.com/q/51930429
tags question: http://stackoverflow.com/q/51834411
tags question: http://stackoverflow.com/q/51891535
tags question: http://stackoverflow.com/q/51931508
tags question: http://stackoverflow.com/q/51955059
tags question: http://stackoverflow.com/q/51801087
tags question: http://stackoverflow.com/q/51867897
tags question: http://stackoverflow.com/q/51872363
tags question: http://stackoverflow.com/q/51856575
tags question: http://stackoverflow.com/q/51818302
tags question: http://stackoverflow.com/q/51844477
tags question: http://stackoverflow.com/q/51888441
tags question: http://stackoverflow.com/q/51873110
tags question: http://stackoverflow.com/q/51805471
tags question: http://stackoverflow.com/q/51895602
tags question: http://stackoverflow.com/q/51864651
tags question: http://stackoverflow.com/q/51892431
tags question: http://stackoverflow.com/q/51812780
tags question: http://stackoverflow.com/q/51881545
tags question: http://stackoverflow.com/q/51877436
tags question: http://stackoverflow.com/q/51934382
tags question: http://stackoverflow.com/q/51939360
tags question: http://stackoverflow.com/q/51824718
tags question: http://stackoverflow.com/q/51920907
tags question: http://stackoverflow.com/q/51933300
tags question: http://stackoverflow.com/q/51875114
tags question: http://stackoverflow.com/q/51853018
tags question: http://stackoverflow.com/q/51834420
tags question: http://stackoverflow.com/q/51798812
tags question: http://stackoverflow.com/q/51833379
tags question: http://stackoverflow.com/q/51855013
tags question: http://stackoverflow.com/q/51860246
tags question: http://stackoverflow.com/q/51808202
tags question: http://stackoverflow.com/q/51867834
tags question: http://stackoverflow.com/q/51816575
tags question: http://stackoverflow.com/q/51812483
tags question: http://stackoverflow.com/q/51884727
tag name: opencv
tags question: http://stackoverflow.com/q/51940070
tags question: http://stackoverflow.com/q/51946371
tags question: http://stackoverflow.com/q/51955394
tags question: http://stackoverflow.com/q/51816826
tags question: http://stackoverflow.com/q/51942059
tags question: http://stackoverflow.com/q/51814397
tags question: http://stackoverflow.com/q/51808908
tags question: http://stackoverflow.com/q/51858428
tags question: http://stackoverflow.com/q/51833444
tags question: http://stackoverflow.com/q/51911171
tags question: http://stackoverflow.com/q/51818763
tags question: http://stackoverflow.com/q/51885997
tags question: http://stackoverflow.com/q/51851198
tags question: http://stackoverflow.com/q/51866280
tags question: http://stackoverflow.com/q/51919841
tags question: http://stackoverflow.com/q/51908677
tags question: http://stackoverflow.com/q/51842495
tags question: http://stackoverflow.com/q/51914683
tags question: http://stackoverflow.com/q/51909532
tags question: http://stackoverflow.com/q/51921388
tags question: http://stackoverflow.com/q/51846933
tags question: http://stackoverflow.com/q/51920849
tags question: http://stackoverflow.com/q/51924219
tags question: http://stackoverflow.com/q/51897313
tags question: http://stackoverflow.com/q/51809040
tags question: http://stackoverflow.com/q/51857066
tags question: http://stackoverflow.com/q/51912354
tags question: http://stackoverflow.com/q/51878226
tags question: http://stackoverflow.com/q/51810443
tags question: http://stackoverflow.com/q/51889346
tags question: http://stackoverflow.com/q/51904518
tags question: http://stackoverflow.com/q/51878371
tags question: http://stackoverflow.com/q/51827788
tags question: http://stackoverflow.com/q/51853480
tags question: http://stackoverflow.com/q/51856485
tags question: http://stackoverflow.com/q/51808101
tags question: http://stackoverflow.com/q/51883629
tags question: http://stackoverflow.com/q/51879090
tags question: http://stackoverflow.com/q/51915475
tags question: http://stackoverflow.com/q/51921631

http://stackoverflow.com/a/51884744
has comment: http://stackoverflow.com/comment/90721562
accepted answer of: http://stackoverflow.com/q/51884530
answers question: http://stackoverflow.com/q/51884530
has comment: http://stackoverflow.com/comment/90721451
type: AcceptedAnswer
has body: Let's use set_major_formatter and set_major_locator on xaxis and plt.subplots: import pandas as pd import matplotlib.pyplot as plt import numpy as np import matplotlib.dates as mdates df1 = pd.DataFrame([["2004-03-01 00:00", 2.3], ["2004-03-05 00:00", 2.4], ["2004-03-25 00:00", 2.25], ["2004-07-01 00:00", 2.7], ["2005-01-01 00:00", 2.9], ["2005-02-17 00:00", 3.1], ["2005-12-01 00:00", 3.5], ["2006-02-01 00:00", 3.3], ["2006-04-05 00:00", 3.08], ["2006-08-22 00:00", 2.4], ["2007-07-01 00:00", 2.1]], columns = ['Date and Time', 'Values 1']) df2 = pd.DataFrame([["2004-03-01 00:00", 12.3], ["2004-03-05 00:00", 14.5], ["2004-03-25 00:00", 12.1], ["2004-07-01 00:00", 10.0], ["2005-01-01 00:00", 12.1], ["2005-02-17 00:00", 9.3], ["2005-12-01 00:00", 8.1], ["2006-02-01 00:00", 6.5], ["2006-04-05 00:00", 7.5], ["2006-08-22 00:00", 6.4], ["2007-07-01 00:00", 4.1]], columns = ['Date and Time', 'Values 2']) yearFmt = mdates.DateFormatter('%Y') years = mdates.YearLocator() df1['Date and Time'] = pd.to_datetime(df1['Date and Time']) fig, ax = plt.subplots(2,1, figsize=(10,10)) df1.plot(x='Date and Time', y='Values 1', legend=False, ax=ax[0]) ax[0].set_xlabel('Year') ax[0].set_ylabel('Values 1') ax[0].xaxis.set_major_formatter(yearFmt) ax[0].xaxis.set_major_locator(years) df2['Date and Time'] = pd.to_datetime(df2['Date and Time']) df2.plot(x='Date and Time', y='Values 2', legend=False, ax=ax[1]) ax[1].set_xlabel('Year') ax[1].set_ylabel('Values 2') ax[1].xaxis.set_major_formatter(yearFmt) ax[1].xaxis.set_major_locator(years) plt.tight_layout() plt.show() Output:
score: 0
type: Answer

http://stackoverflow.com/comment/90619468
comment on: http://stackoverflow.com/q/51832272
type: Comment
type: QuestionComment
has text: Does jwt 1.5.6 and jwt 2.1.0 use the same hashing function? Are you hashing the same data (dicts in python are not JSON)? Interesting question, but from a design standpoint, you probably shouldn't be doing this :)
score: 0

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

http://stackoverflow.com/a/51890825
has body: Adding the line matplotlib.pyplot.figure(figsize=(3.75,3.52)) as suggested by Foxan Ng does not seem to work on my end. The only thing that does seem to work is changing the decimal separator to . in the Windows settings under Control Panel | Region and Language | Formats | Additional Settings | Decimal Separator (I'm still on Windows 7) . Now it works: But now of course, I'm running the risk of messing up everything else in other Power BI reports. So I'm really hoping that the Power BI team gets on this or that others are able to provide even better answers.
answers question: http://stackoverflow.com/q/51859000
score: 0
type: Answer

http://stackoverflow.com/q/51900869
answer count: 1
downvote count: 0
has title: How do I listen for a DBus signal in a GTK (python 3, Gio) app?
score: 4
tagged with: linux
tagged with: gio
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: gtk
tagged with: networkmanager
has answer: http://stackoverflow.com/a/70748303
type: Question
upvote count: 4
has body: I'm trying to make my GTK app responsive to network connection state changes. My approach is what I said in the question: Listen on a (NetworkManager) DBus signal. I have a python3 GTK app (a very minimal one, I should add), using python-gi. As python-dbus (aka "import dbus") is deprecated to the best of my knowledge, I'd like to use Gio via python-gi. I have an older script that listens for the signal I'm interested in on the system DBus which uses "import dbus" with this code: dbus.mainloop.glib.DBusGMainLoop(set_as_default=True) bus = dbus.SystemBus() bus.add_signal_receiver(NMSignalHandler, dbus_interface=NM_INTERFACE, signal_name='StateChanged') (followed by a gobject.MainLoop().run()) I thought this would be relatively straightforward to "port" to Gio, but even after two hours of reading the docs, I don't see how to do that. Any help would be appreciated. I already tried using Gio.NetworkMonitor.get_default() and its 'network-changed' signal, but it appears to report with net_available (second parameter) always being true and the default monitor doesn't seem to report a sensible result either. I would deeply appreciate any help.

http://stackoverflow.com/comment/90571581
score: 0
type: QuestionComment
type: Comment
has text: You can publish the `mplwidget.py` ?
comment on: http://stackoverflow.com/q/51807875

http://stackoverflow.com/q/51830722
type: Question
tagged with: for-loop
tagged with: python-3.5
linked to: http://stackoverflow.com/q/17688385
answer count: 1
downvote count: 0
has body: I am trying to create a rather large list of buttons in a for loop that is also linked to their corresponding function to be called in a dictionary. There are a few similar posts here and here that discuss using lambda assigning the name=name, but I cant seem to figure out how to incorporate that into this specific instance where each one calls a different function in the dictionary, rather than altering a single parameter of single function. Here is an example. import tkinter as tkinter root = tkinter.Tk() def funct1(): print("Printed Func1") def funct2(): print("Printed Func2") buttons_dict = {"button1": "Func1", "button2": "Func2"} row = 0 for name in buttons_dict: buttons = tkinter.Button(root, text=name) # command=lambda name=name: root(name)) buttons.grid(row=row) buttons.config() row += 1 root.mainloop() What would be the correct method for assigning the name to the function when gathering the information from a dictionary like this?
has answer: http://stackoverflow.com/a/51830769
favorite count: 0
linked to: http://stackoverflow.com/q/42951770
tagged with: tkinter
has title: tkinter - linking buttons in a for loop to a dictionary of functions {name : function}
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/51830769
tagged with: lambda
type: AnsweredQuestion
score: 1

http://stackoverflow.com/q/51870617
has answer: http://stackoverflow.com/a/51870713
has body: I'm a very beginner in computer language (2 days) and am writing a basic slot machine code in python. import random import time balance = 1000 print("Welcome to the Slot World") player_name = input("What's your name?") while balance &gt; 0: print(player_name, ", you have $",balance, " to bet.") bet = int(input("How much do you want to bet?")) x = random.randint(1, 5) y = random.randint(1, 5) z = random.randint(1, 5) numbers = [x, y, z] if bet != int: print("Please enter correct amount") continue elif bet &gt; balance: print("You do not have sufficient amount") continue elif bet &lt;= 0: print("Please enter correct amount") continue else: print("You have bet $", bet) time.sleep(0.5) print(numbers) balance = balance - bet if x == y and y == z: if x == 1: print("Winner 20x!") bet = bet * 20 balance = balance + bet elif x == 2: print("Winner 30x!") bet = bet * 30 balance = balance + bet elif x == 3: print("Winner 40x!") bet = bet * 40 balance = balance + bet elif x == 4: print("Winner 50x!") bet = bet * 50 balance = balance + bet elif x == 5: print("Winner 100x!") bet = bet * 100 balance = balance + bet elif x == y and not y == z: if x == 1: print("Winner 2x") bet = bet * 2 balance = balance + bet elif x == 2: print("Winner 3x") bet = bet * 3 balance = balance + bet elif x == 3: print("Winner 4x") bet = bet * 4 balance = balance + bet elif x == 4: print("Winner 5x") bet = bet * 5 balance = balance + bet elif x == 5: print("Winner 10x") bet = bet * 10 balance = balance + bet elif not x == y and y == z: if y == 1: print("Winner 2x") bet = bet * 2 balance = balance + bet elif y == 2: print("Winner 3x") bet = bet * 3 balance = balance + bet elif y == 3: print("Winner 4x") bet = bet * 4 balance = balance + bet elif y == 4: print("Winner 5x") bet = bet * 5 balance = balance + bet elif y == 5: print("Winner 10x") bet = bet * 10 balance = balance + bet elif not x == y and x == z: if x == 1: print("Winner 2x") bet = bet * 2 balance = balance + bet elif x == 2: print("Winner 3x")…
upvote count: 0
favorite count: 0
score: -1
linked to: http://stackoverflow.com/q/23294658
linked to: http://stackoverflow.com/q/1841565
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51870674
tagged with: python
has answer: http://stackoverflow.com/a/51870686
has title: How do you check if a input value is int and otherwise put in a loop?
answer count: 4
duplicate of: http://stackoverflow.com/q/23294658
has answer: http://stackoverflow.com/a/51870658
has comment: http://stackoverflow.com/comment/90692709
downvote count: 1
has comment: http://stackoverflow.com/comment/90692639
type: Question

http://stackoverflow.com/comment/90771283
has text: @juanpa.arrivillaga yes you are right. got the solution. thank you
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51852658
score: 0

http://stackoverflow.com/a/51895021
answers question: http://stackoverflow.com/q/51894583
type: Answer
score: 0
has body: Managed to fix it. The program was writing to the JSON file before it set the python program off and the FileWriter object hadn't been closed causing the issue.

http://stackoverflow.com/q/51820023
type: Question
has answer: http://stackoverflow.com/a/51821413
score: 0
answer count: 1
tagged with: python
has body: I have 2 images in a folder named as 1.jgp , 2.jpg. I want to write a python code to display all the images one after another in the same location of the pane after 2 second delay. I tried to add the same code one after another with image 2.jpg, but it doesn't work. What changes do I need to make in this code to display image 2.jpg after 1.jpg is displayed and cleared. I have tried the following code: from tkinter import * from PIL import Image, ImageTk import time root = Tk() filename1="1.jpg" filename2="2.jpg" canvas = Canvas(width=800, height=800, bg='white') canvas.pack() image = Image.open(filename) photo = ImageTk.PhotoImage(image) canvas.create_image(250, 250, image=photo) root.mainloop()
tagged with: tkinter
has title: How to update new image in the Tkinter after clearing an existing image.?
type: AnsweredQuestion
tagged with: image
accepted answer: http://stackoverflow.com/a/51821413

http://stackoverflow.com/comment/90730318
comment on: http://stackoverflow.com/q/51879948
type: Comment
has text: I am not sure I follow. How many jar jobs are there? Please create an example about your structure and the idea you've got with the echo command. Also how are those jars used, what are those operators?
score: 0
type: QuestionComment

http://stackoverflow.com/comment/90604316
type: AnswerComment
has text: Can I not save arrays at all with msgpack?
comment on: http://stackoverflow.com/a/51824716
score: 0
type: Comment

http://stackoverflow.com/comment/90844214
type: Comment
type: QuestionComment
has text: I mean before plotting, write ‘print (x,y)’ and tell me what is printed on the screen
comment on: http://stackoverflow.com/q/51945803
score: 0

http://stackoverflow.com/q/51887781
type: Question
has answer: http://stackoverflow.com/a/51888303
has title: Converting dataframe into column of other dataframe in Python
has comment: http://stackoverflow.com/comment/90727054
has comment: http://stackoverflow.com/comment/90727063
tagged with: dataframe
has comment: http://stackoverflow.com/comment/90726828
score: 0
has comment: http://stackoverflow.com/comment/90727251
answer count: 2
tagged with: pandas
has answer: http://stackoverflow.com/a/51888583
has comment: http://stackoverflow.com/comment/90727320
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90726978
has body: I have two two datasets: df1: Name Answers Questions People-reached Reputation Alex Gaynor 154 44 ~1.4m 8,871 df2: Project Total-score Post python 337 93 django-templates 22 4 slug 12 1 google-app-engine 8 1 django 235 57 clang 22 2 Is there any way in Python (pandas or other library) I merge the two dataframe in a way so that df2 becomes new column in df1? Desired output would be: Name Answers Questions People-reached Reputation Project-details Alex Gaynor 154 44 ~1.4m 8,871 python 337 93 django-templates 22 4 slug 12 1 google-app-engine 8 1

http://stackoverflow.com/comment/116961613
type: AnswerComment
has text: Specifically, the lib subfolder
type: Comment
score: 2
comment on: http://stackoverflow.com/a/57132010

http://stackoverflow.com/a/51838457
upvote count: 3
type: Answer
score: 3
answers question: http://stackoverflow.com/q/51838301
has body: In your list comprehension, i is one of the tuples, so ('John', 'Samantha', {'source': 'family'}) or ('John', 'Jill', {'source': 'work'}). That's not a dictionary, so you can't treat it like one! If your tuples are always consisting of 3 elements and the 3rd element is a dictionary with a source key, use: [i for i in my_list if i[2]['source'] == 'family'] You'll have to add some more code if any of those assumptions do not hold. For example, if the dictionary is always there but the 'source' key could be missing, you could use dict.get() to return a default when the key is not there: [i for i in my_list if i[2].get('source') == 'family'] If the length of the tuple can vary, but the dictionary is always the last element, you can use a negative index: [i for i in my_list if i[-1]['source'] == 'family'] etc. As a programmer, you always have to check for such assumptions.
has comment: http://stackoverflow.com/comment/90632060
downvote count: 0

ubuntu
tags question: http://stackoverflow.com/q/51801353
tags question: http://stackoverflow.com/q/51812530
tags question: http://stackoverflow.com/q/51943050
tags question: http://stackoverflow.com/q/51927653
tags question: http://stackoverflow.com/q/51829150
tags question: http://stackoverflow.com/q/51832638
tag name: ubuntu
tags question: http://stackoverflow.com/q/51825800
tags question: http://stackoverflow.com/q/51909250
type: Tag

http://stackoverflow.com/comment/90727896
type: Comment
has text: You can do this with the implication pattern https://stackoverflow.com/questions/38717933/jsonschema-attribute-conditionally-required/38781027#38781027
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/51882304

http://stackoverflow.com/comment/90857157
has text: Thank you very much! But why the values of 'Trip8' & ''Trip9' on row 0 were not removed?
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51940922

http://stackoverflow.com/q/51901478
tagged with: python-2.7
answer count: 1
downvote count: 0
has title: Python2.7 socket error 37 "Operation already in progress"
favorite count: 0
has answer: http://stackoverflow.com/a/51902384
tagged with: sockets
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90754323
has comment: http://stackoverflow.com/comment/90755910
score: 1
upvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/51902384
has comment: http://stackoverflow.com/comment/90755880
has body: I'm making a script that reads a file full of proxy servers and checks if they are up or down. import socket proxyFile = open("proxies.txt","r"); lines = proxyFile.readlines(); class Colors: none = "\033[0m"; red = "\033[31m"; green = "\033[32m"; yellow = "\033[33m"; blue = "\033[34m"; purple = "\033[35m"; cyan = "\033[36m"; sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM); sock.settimeout(3); for line in lines: line = line.replace(":"," : "); reader = line.split(); ip = reader[reader.index(":") - 1]; port = int(reader[reader.index(":") + 1]); try: sock.connect((ip,port)); print Colors.cyan + ip + ":" + str(port) + Colors.none + " is " + Colors.green + "UP"; sock.close(); except socket.timeout: print Colors.cyan + ip + Colors.yellow + ":" + Colors.cyan + str(port) + Colors.none + " is " + Colors.red + "DOWN"; It seems that the file reads fine and the socket creates, but it only connects to one server then it gives the error. Proxy File: 1.0.134.56:8080 1.165.192.248:3128 1.172.185.143:53281 1.179.156.233:8080 1.179.164.213:8080 1.179.185.253:8080 1.192.242.191:3128 1.20.169.166:8080 1.20.179.68:8080 1.20.99.163:8080
has comment: http://stackoverflow.com/comment/90754180
has comment: http://stackoverflow.com/comment/90770630

http://stackoverflow.com/q/51889943
has title: Plotly xaxis in weekday name
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51907922
upvote count: 1
type: Question
tagged with: plotly
has body: I’ve looked into the documentation but they didn’t seem to mention it. https://plot.ly/python/axes/ How can I change the label on x axis to show “Mon 20-7”, “Tue 21-7”, etc. The 'date' used for xaxis is in the format "20-7-2018 11:00:00am", etc. I use the following Python Plotly script: trace0=go.Scatter(x=df_pre.index,y=df_pre['Total'],line=dict(color=('rgb(16,25,109)'),width=1),name='Period_1') trace1=go.Scatter(x=df_post.index,y=df_post['Total'],line=dict(color=('rgb(77,221,26)'),width=2),name='Period_2') data=[trace0,trace1] layout=dict(title='Total',width=960,height=768, yaxis=dict(title='Avg',ticklen=5,zeroline=False,gridwidth=2,), xaxis=dict(title='Date',ticklen=5,zeroline=False,gridwidth= 2,)) fig=dict(data=data,layout=layout) iplot(fig,filename='Total') Any help would be much appreciated
possible better answer: http://stackoverflow.com/a/51890231
has answer: http://stackoverflow.com/a/51890231
answer count: 2
has answer: http://stackoverflow.com/a/51907922
downvote count: 0
score: 1
favorite count: 0

http://stackoverflow.com/comment/90629771
score: 0
type: Comment
has text: @LaurentH. I can't accept both, can I?
comment on: http://stackoverflow.com/a/51838127
type: AnswerComment

http://stackoverflow.com/comment/90565878
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51804930
has text: @hemnathmouli I tried `subprocess.call(['ssh', '-t', nodename, '"bash -l"']) and it came up with the error `bash: bash -l: command not found`. However, I just type in `ssh -t [NODENAME] "bash -l"`, it works perfectly fine.

http://stackoverflow.com/q/51894281
score: 0
tagged with: raspberry-pi3
has body: I need to calculate the distance of a bluetooth device from a raspberry pi. I am using below code - def calculate_accuracy(txpower, rssi): if rssi == 0: return -1 else: ratio = rssi/txpower if ratio &lt; 1: return ratio**10 else: return 0.89976 * ratio**7.7095 + 0.111 I am able to retrieve the rssi value but not the TxPower. Does anyone know how to retrieve TxPower from a bluetooth device? Thanks in Advance!
has comment: http://stackoverflow.com/comment/90739643
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90739503
answer count: 0
type: Question
has title: How to retrieve TxPower of a bluetooth raspberry beacon?
tagged with: bluetooth

http://stackoverflow.com/comment/90797365
type: Comment
comment on: http://stackoverflow.com/q/51920348
score: 0
type: QuestionComment
has text: Ok Thank you FYI wiki space link is closed can you provide alternate link for documentation ?

http://stackoverflow.com/a/65215893
upvote count: 6
type: Answer
score: 6
answers question: http://stackoverflow.com/q/51863881
downvote count: 0
has body: You can populate connections using environment variables using the connection URI format. The environment variable naming convention is AIRFLOW_CONN_&lt;conn_id&gt;, all uppercase. So if your connection id is my_prod_db then the variable name should be AIRFLOW_CONN_MY_PROD_DB. In general, Airflow’s URI format is like so: my-conn-type://my-login:my-password@my-host:5432/my-schema?param1=val1&amp;param2=val2 Note that connections registered in this way do not show up in the Airflow UI.

http://stackoverflow.com/q/51811060
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/90577938
has body: I'm developing development on a Mac and deploying to a Centos 7.4 install. When running on the latest docker/docker-compose I'm getting a weird error on one of them after upgrading. On the Mac the command works as intended. The setup.sh script executes. On Centos it chokes: backend_1 | python: can't open file 'sh': [Errno 2] No such file or directory The command successfully launched in both environments previously. version: '2' services: db: image: postgres volumes_from: - data depends_on: - data nginx: image: nginx:alpine build: nginx/. restart: always volumes: - ./nginx/nginx.conf:/etc/nginx/conf.d/default.conf:ro - ./nginx/ssl-bundle.crt:/etc/nginx/ssl/site_com/ssl_bundle.crt - ./nginx/site_com.crt:/etc/ssl/certs/ssl-bundle.crt - ./nginx/site.key:/etc/nginx/ssl/site_com/site.key - ./nginx/site.key:/etc/ssl/private/site.key - static:/usr/share/nginx/html/static depends_on: - backend ports: - "80:80" - "443:443" links: - backend:backend backend: image: colstrom/python:legacy build: context: . dockerfile: backend/Dockerfile command: sh docker/setup.sh volumes: - /usr/src/app - static:/code/site/static depends_on: - db expose: - "8000" data: image: cogniteev/echo command: echo 'Data Container for PostgreSQL' volumes: - /var/lib/postgresql/data volumes: static: Mac docker-compose version 1.22.0, build f46880f Docker version 18.06.0-ce, build 0ffa825 Centos docker-compose version 1.22.0, build f46880f Docker version 18.06.0-ce, build 0ffa825 Any ideas?
tagged with: docker
answer count: 1
has title: Error launching a docker-compose command on Centos
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/90581238
tagged with: python
has answer: http://stackoverflow.com/a/51813394
type: AnsweredQuestion
tagged with: docker-compose
score: 1
accepted answer: http://stackoverflow.com/a/51813394

http://stackoverflow.com/q/51833310
has comment: http://stackoverflow.com/comment/90620533
has comment: http://stackoverflow.com/comment/90620511
has comment: http://stackoverflow.com/comment/103397205
tagged with: machine-learning
type: Question
has body: I have a simple Python code for a machine learning project. I have a relatively big database of spontaneous speech. I started to train my speech model. Since it's a huge database I let it work overnight. In the morning I woke up and saw a mysterious Killed: 9 line in my Terminal. Nothing else. There is no other error message or something to work with. The code run well for about 6 hours which is 75% of the whole process so I really don't understand whats went wrong. What is Killed:9 and how to fix it? It's very frustrating to lose hours of computing time... I'm on macOS Mojave beta if it's matter. Thank you in advance!
upvote count: 20
has title: What is Killed:9 and how to fix in macOS Terminal?
has answer: http://stackoverflow.com/a/68586691
has answer: http://stackoverflow.com/a/79020255
linked to: http://stackoverflow.com/q/33978241
score: 20
has comment: http://stackoverflow.com/comment/103430264
linked to: http://stackoverflow.com/q/16338884
has answer: http://stackoverflow.com/a/72140478
has comment: http://stackoverflow.com/comment/121211793
downvote count: 0
tagged with: macos
has answer: http://stackoverflow.com/a/76751178
favorite count: 0
tagged with: terminal
has comment: http://stackoverflow.com/comment/103432632
answer count: 5
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90620491
has answer: http://stackoverflow.com/a/77907937
tagged with: python
has comment: http://stackoverflow.com/comment/127898337

http://stackoverflow.com/comment/90808203
comment on: http://stackoverflow.com/q/51929135
type: Comment
type: QuestionComment
has text: I have set the path in environment variables for both of them but still not working. Shall I set only one i.e. Python 2.7?
score: 1

http://stackoverflow.com/comment/90604021
score: 0
type: Comment
type: QuestionComment
has text: @user2906838 Added at the end of the post :)
comment on: http://stackoverflow.com/q/51824455

http://stackoverflow.com/q/51925284
has comment: http://stackoverflow.com/comment/90801614
has title: Flask-Migrate "ModuleNotFoundError"
type: Question
has comment: http://stackoverflow.com/comment/90799957
tagged with: database
tagged with: flask
has comment: http://stackoverflow.com/comment/90800835
accepted answer: http://stackoverflow.com/a/51926417
answer count: 3
score: 2
downvote count: 0
tagged with: migrate
favorite count: 0
possible better answer: http://stackoverflow.com/a/57954220
tagged with: importerror
has comment: http://stackoverflow.com/comment/90800801
has answer: http://stackoverflow.com/a/57954220
has comment: http://stackoverflow.com/comment/90801818
has body: I'm trying to make migrations on my Flask api based on SQLite db. Here is my project structure ├── app.py ├── blueprints ├── conf.py ├── db.sqlite ├── __init__.py ├── migrations ├── models.py └── templates Then i initialize my migrate class in the app.py from flask import Flask, jsonify, request, render_template from flask_sqlalchemy import SQLAlchemy from conf import ErrorResponses, SuccessResponses # initialization app = Flask(__name__) db = SQLAlchemy(app) from models import User, db, BlackListToken # extensions from flask_migrate import Migrate mig = Migrate(app, db) But it fails on importing from custom modules while flask db migrate -m "rm id and made name/surname nullable". Usage: flask db migrate [OPTIONS] Error: While importing "api_flask.app", an ImportError was raised: Traceback (most recent call last): File "/usr/local/lib/python3.6/dist-packages/flask/cli.py", line 235, in locate_app __import__(module_name) File "/home/zahessi/all/bubbie_D/api_flask/app.py", line 9, in &lt;module&gt; from conf import ErrorResponses, SuccessResponses ModuleNotFoundError: No module named 'conf' Here is how models.py looks: from app import db class User(db.Model): __tablename__ = 'users' username = db.Column(db.String(32), index=True, unique=True, nullable=False) email = db.Column(db.String(64), unique=True, nullable=False) password_hash = db.Column(db.String(64), nullable=False) name = db.Column(db.String(32)) surname = db.Column(db.String(32)) public_id = db.Column(db.String(32)) creation_date = db.Column(db.DateTime) ... When I remove all imports from custom py files, all seems to work, however, this is a lot of unnecessary work. Do you have any suggestions why does it work in that way? UPD: Added conf.py. It fails on every local import, on blueprints as well, depending on the order of the imports. from re import findall class ErrorResponses: usernameOrPasswordBlank = { "success": False, "error": "Username and password cannot be blank." } userAlreadyExists = {"success":…
tagged with: python
has comment: http://stackoverflow.com/comment/90800113
has comment: http://stackoverflow.com/comment/90802114
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/75238144
upvote count: 2
has answer: http://stackoverflow.com/a/51926417
has comment: http://stackoverflow.com/comment/90801653

http://stackoverflow.com/a/51899360
score: 15
type: AcceptedAnswer
type: Answer
has body: It means you have an extra space. Though pd.to_datetime is very good at parsing dates normally without any format specified, when you actually specify a format, it has to match EXACTLY. You can likely solve your issue by adding .str.strip() to remove the extra whitespace before converting. import pandas as pd df['Time stamp'] = pd.to_datetime(df['Time stamp'].str.strip(), format='%d/%m/%Y') Alternatively, you can take advantage of its ability to parse various formats of dates by using the dayfirst=True argument df['Time stamp'] = pd.to_datetime(df['Time stamp'], dayfirst=True) Example: import pandas as pd df = pd.DataFrame({'Time stamp': ['01/02/1988', '01/02/1988 ']}) pd.to_datetime(df['Time stamp'], format= '%d/%m/%Y') ValueError: unconverted data remains: pd.to_datetime(df['Time stamp'].str.strip(), format='%d/%m/%Y') #0 1988-02-01 #1 1988-02-01 #Name: Time stamp, dtype: datetime64[ns] pd.to_datetime(df['Time stamp'], dayfirst=True) #0 1988-02-01 #1 1988-02-01 #Name: Time stamp, dtype: datetime64[ns]
upvote count: 15
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51898826
answers question: http://stackoverflow.com/q/51898826

http://stackoverflow.com/comment/101681846
type: Comment
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/51921534
has text: This answer is no longer valid. From your link: "Works out-of-the-box with any Python version 2.7 / 3.4-3.7"

http://stackoverflow.com/a/51834277
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/51834217
downvote count: 0
has body: If I understood correctly you need the template syntax. Try: {% for i in a %} {% for k in i %} {{ k }} {% endfor %} {% endfor %} To divide the list to N chunks use. data_lis = [1,2,3,4,5,6,7,8,9] N = 3 a = [data_lis[i:i+N] for i in range(0, len(data_lis), N)] print(a) Output: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

http://stackoverflow.com/comment/90702715
has text: I'm sure my EC2 and Neptune shares the same VPC
comment on: http://stackoverflow.com/q/51843816
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51805995
type: Question
tagged with: pandas
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/90581233
tagged with: flask-sqlalchemy
has comment: http://stackoverflow.com/comment/90567889
has title: (Python (analysis)) Unable to resolve 'pandas'. IntelliSense may be missing for this module
favorite count: 0
has body: I am working on a python app in Visual Studio Code and would like to import pandas, sqlalchemy, and flask libraries. However, when I enter code such as import pandas as pd import sqlalchemy I get the error [Python (analysis)] Unable to resolve 'pandas'. IntelliSense may be missing for this module Likewise with sqlalchemy. I checked the version of pandas in the command line by pip3 install --upgrade pandas and it returns "Requirement already up-to-date". So I am not sure what the issue is. Any suggestions? Many thanks.
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51813215
tagged with: visual-studio
score: 3
upvote count: 3
tagged with: sqlalchemy

http://stackoverflow.com/comment/90626715
score: 1
comment on: http://stackoverflow.com/a/51836649
type: AnswerComment
has text: @Arun for all view, yeah. I haven't noticed that you need it to be for specific view.
type: Comment

http://stackoverflow.com/a/51915833
has comment: http://stackoverflow.com/comment/90798089
score: 0
answers question: http://stackoverflow.com/q/51915672
has body: You can use list comprehension to get rid of -- &gt;&gt;&gt; code='''Although never is often better than right now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those!''' &gt;&gt;&gt; &gt;&gt;&gt; [word for word in code.split() if word != '--'] ['Although', 'never', 'is', 'often', 'better', 'than', 'right', 'now.', 'If', 'the', 'implementation', 'is', 'hard', 'to', 'explain,', "it's", 'a', 'bad', 'idea.', 'If', 'the', 'implementation', 'is', 'easy', 'to', 'explain,', 'it', 'may', 'be', 'a', 'good', 'idea.', 'Namespaces', 'are', 'one', 'honking', 'great', 'idea', "let's", 'do', 'more', 'of', 'those!']
has comment: http://stackoverflow.com/comment/90799608
type: Answer

http://stackoverflow.com/comment/90845282
type: AnswerComment
type: Comment
score: 0
has text: Thanks Joe. That was just what I needed. Is there is good webiste that explains how these things work? Something simple to intermediate level? I Googled for an answer for a while before posting my question, and I tried several ideas, but I just couldn't get anything to work.
comment on: http://stackoverflow.com/a/51942813

http://stackoverflow.com/q/51898533
tagged with: python
tagged with: maps
tagged with: dictionary
has title: How do I extract items which are in a list from python dictionary
tagged with: list
has comment: http://stackoverflow.com/comment/90748087
type: Question
upvote count: 0
score: -2
has comment: http://stackoverflow.com/comment/90749902
answer count: 2
has body: I am quite new to python and I am struggling with this particular question. I have the follow script: landmask_regions = 'Africa': ['mask_M01.map', 'mask_M02.map', 'mask_M03.map', \ 'mask_M05.map', 'mask_M06.map', 'mask_M07.map', 'mask_M08.map', \ 'mask_M09.map'], \ 'Asia': ['mask_M04.map', 'mask_M05.map', 'mask_M10.map', 'mask_M11.map', \ 'mask_M12.map', 'mask_M13.map', 'mask_M14.map', 'mask_M15.map', \ 'mask_M16.map', 'mask_M17.map', 'mask_M18.map', 'mask_M19.map', \ 'mask_M20.map', 'mask_M21.map', 'mask_M22.map', 'mask_M23.map'], \ 'Europe': ['mask_M26.map', 'mask_M28.map', 'mask_M32.map', 'mask_M33.map', \ 'mask_M34.map'], \ 'N-America': ['mask_M25.map', 'mask_M35.map', 'mask_M36.map', 'mask_M37.map', \ 'mask_M38.map', 'mask_M39.map', 'mask_M40.map', 'mask_M41.map', \ 'mask_M42.map', 'mask_M43.map', 'mask_M44.map', 'mask_M45.map', 'mask_M46.map'], \ 'Australia': ['mask_M47.map', 'mask_M48.map', 'mask_M49.map'], \ 'S-America': ['mask_M24.map', 'mask_M50.map', 'mask_M51.map', \ 'mask_M52.map', 'mask_M53.map']} So this script is a dictionary which is divided into continents, and for each continents it includes maps of certain regions. Now I want to be able to read these maps for these occassions; Read all the maps of the whole world all together Read all the maps of one region, for example just 'Africa' or 'Asia' etc. Read one specific region within a continent, say only mask_M08.map How am I supposed to arrange a script which is able to do all of that? I'm a bit stuck on this.
has comment: http://stackoverflow.com/comment/90748063
favorite count: 0
has answer: http://stackoverflow.com/a/51898672
has answer: http://stackoverflow.com/a/51898684
type: UnansweredQuestion
downvote count: 2

http://stackoverflow.com/a/51872419
downvote count: 0
type: Answer
has body: Here's way to union multiple sets without creating a list s = set() for n in range(5): s = s.union({n, 2*n})
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/90696526
has comment: http://stackoverflow.com/comment/90699027
answers question: http://stackoverflow.com/q/51871836

http://stackoverflow.com/comment/90617687
type: Comment
comment on: http://stackoverflow.com/a/51831706
has text: @Akavall Then you do a similar thing with a `collections.Counter` instead of a set.
score: 0
type: AnswerComment

http://stackoverflow.com/a/51890635
type: AcceptedAnswer
downvote count: 0
has body: You can use string format, code looks elegant more details is here https://www.programiz.com/python-programming/methods/string/format # inventory.py stuff = {"coal":42,"dagger":1,"iron": 20,"torch":2} total_items = 0 def display_inventory(inventory): for k,v in inventory.items(): print("{}:{}".format(k,v)) global total_items total_items = total_items + v print("\n") print("Total: " + str(total_items))
upvote count: 2
type: Answer
accepted answer of: http://stackoverflow.com/q/51890512
answers question: http://stackoverflow.com/q/51890512
score: 2

http://stackoverflow.com/q/51955624
possible better answer: http://stackoverflow.com/a/51955944
has answer: http://stackoverflow.com/a/51955944
tagged with: while-loop
tagged with: python
accepted answer: http://stackoverflow.com/a/51955674
type: AnsweredQuestion
tagged with: python-3.x
has title: Alternative to writing 15 if else statements in python
has body: I'm wondering if there is a better way doing this: I'm checking to see if a calculation is 0, if 0 nothing happens. If not 0 money gets added to player. The problem is that I have to check 15 different calculations of dividends right now, how would this be smart to do? I could do 15 if/else statements but that would be messy. My one idea was to have the code below but if the statements true, to continue the loop to also check the other statements and if true act on them. Is this possible in Python? My other idea was to do a while loop and basically every 60 seconds, just setattr the dividens for all stocks even if the dividens are 0, but I think this has a chance to become a bug if the player does something else during the execution. Some sample code: import random import sys import time import os def playerStatus(): playerStatus.playerMoney = 10000 playerStatus.playerLoan = 0 def dividends(): while True: networthCalc() pm = playerStatus.playerMoney print("cash:", pm) dividends.aapl = networthCalc.aapl / random.randint (20,30) dividends.goog = networthCalc.goog / random.randint (20,30) time.sleep(1) if dividends.aapl &gt; 0: newCash = dividends.aapl + pm setattr(playerStatus, "playerMoney", newCash) print("aapl payed div:", dividends.aapl) elif dividends.goog &gt; 0: newCash = dividends.goog + pm setattr(playerStatus, "playerMoney", newCash) print("goog payed div:", dividends.goog) else: pass def networthCalc(): networthCalc.aapl = getattr(stockPrice, "aapl") * getattr(showAssets, "aapl") networthCalc.goog = getattr(stockPrice, "goog") * getattr(showAssets, "goog") def showAssets(): showAssets.aapl = 10 showAssets.goog = 10 def stockPrice(): stockPrice.aapl = 200 stockPrice.goog = 200 playerStatus() showAssets() stockPrice() networthCalc() dividends()
type: Question
tagged with: if-statement
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/51955674

http://stackoverflow.com/q/51837006
tagged with: python
tagged with: sprite
has comment: http://stackoverflow.com/comment/90627363
has comment: http://stackoverflow.com/comment/90627346
score: 1
has comment: http://stackoverflow.com/comment/90629145
type: Question
has comment: http://stackoverflow.com/comment/90627677
has answer: http://stackoverflow.com/a/51838288
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/90628800
favorite count: 0
has comment: http://stackoverflow.com/comment/90629459
has title: Why does it say I don't have a rect
tagged with: pygame
tagged with: attributes
has comment: http://stackoverflow.com/comment/90627477
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90628213
has body: I have put in the code self.rect = pygame.Rect(x, y, 100, 100). There is an AttributeError: type object 'MobRow1' has no attribute 'rect'. Why does this error keep popping up when I have put the rect in. I have tried self.rect = pygame.Rect(self.x, self.y, 100, 100) This still doesn't work. class MobRow1(pygame.sprite.Sprite): def __init__(self, x, y): pygame.sprite.Sprite.__init__(self) self.image = pygame.image.load(badguy_file).convert_alpha() self.image = pygame.transform.scale(self.image, (50, 50)) self.x = x self.y = y self.rect = pygame.Rect(x, y, 100, 100) self.mask = pygame.mask.from_surface(self.image) def update(self): self.rect.y += self.speedy self.rect.x += self.speedx
upvote count: 1

http://stackoverflow.com/q/51889375
has comment: http://stackoverflow.com/comment/90730149
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/90730695
type: Question
has title: Date Time format and adding time to date
accepted answer: http://stackoverflow.com/a/51889848
has comment: http://stackoverflow.com/comment/90730571
has body: I have a data file that contains the evendata such as event starting date (Date), starting time (KOTime) and event time (EveTime). The following is the sample of data. df = pd.DataFrame() df['Date'] = ['2018/08/12','2018/08/12','2018/08/12','2018/08/12','2018/08/12','2018/08/12'] df['KOTime'] = ['12:30:00','12:30:00','12:30:00','12:30:00','12:30:00','12:30:00'] df['EveTime'] = ['04:50:00','01:03:00','1900-01-03 05:22:00','1900-01-02 16:04:00','1900-01-01 10:28:00','1900-01-01 16:23:00'] Evetime is not formatted in the raw data file as can be seen in the data. if the Evetime is greater than 24 hours, it is shown as 1900-01-xx . If we look at the 3rd value of EveTime, it is shown as 1900-01-03 05:22:00. It is supposed to be 2018/08/12 13:47:22. I want to create a new column that contains Date and EveTime and the expected output is as follow: 2018/08/12 12:34:50 2018/08/12 12:31:03 2018/08/12 13:47:22 2018/08/12 13:34:04 2018/08/12 12:40:28 2018/08/12 12:46:23 Can anyone suggest me how to do to get the format mentioned above?
tagged with: pandas
has comment: http://stackoverflow.com/comment/90730214
has answer: http://stackoverflow.com/a/51889848
answer count: 1
downvote count: 0
favorite count: 0
tagged with: datetime
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/90703716
type: QuestionComment
comment on: http://stackoverflow.com/q/51874297
score: 0
has text: @jpp would you be able to help please?
type: Comment

http://stackoverflow.com/comment/90717779
type: Comment
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/51882666
has text: read this https://stackoverflow.com/questions/659865/multiprocessing-sharing-a-large-read-only-object-between-processes @PapeK24

osx-elcapitan
tag name: osx-elcapitan
type: Tag
tags question: http://stackoverflow.com/q/51848122

http://stackoverflow.com/comment/90746535
type: Comment
type: QuestionComment
has text: Is your problem ACTUALLY just one line segment or will you check for more line segments? The answer may depend on that, because then it may be worthwile to do something to the coastline segments like indexing or whatnot.
comment on: http://stackoverflow.com/q/51897251
score: 0

http://stackoverflow.com/q/51900253
tagged with: dataframe
tagged with: sorting
has answer: http://stackoverflow.com/a/51900662
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/90752568
has title: Re-arranging Dataframe columns based on substrings in column names
score: 1
tagged with: string
favorite count: 0
has body: I have a dataframe, df, that has values of two characters over quarters of the year. [Q1 = Jan, Feb, Mar; Q2 = Apr, May, Jun, ...etc]. The quarters are the previous four quarters trailing the current quarter (ex. if Current Quarter = Q3 17, quarters measured are Q3 16, Q4 16, Q1 17, Q2 17). Quarter Q1 17 Q2 17 Q3 16 Q4 16 Character Sonic 10.0 6.0 19.0 3.0 Shadow 5.0 5.0 7.0 23.0 I would like to reorder the columns in a time applied manner, Q3 16, Q4 16, Q1 17, Q2 17, to get this: Quarter Q3 16 Q4 16 Q1 17 Q2 17 Character Sonic 19.0 3.0 10.0 6.0 Shadow 7.0 23.0 5.0 5.0 I've thought about sorting by substring where the year is contained. But is there a cleaner and quicker way to do this? [EDIT] For clarification, I created substrings of the year: columns = list(scar_pivot.columns.values) sort_columns_years = [int(c[3:5]) for c in columns] sort_columns_years= [17, 17, 16, 16] Since this code in question is used periodically over time, a user would be measuring different quarters depending on when the code is used. (ex. Current quarter is Q2 17, there would be three values of 16 and one value of 17 in sort_columns_years, for Q2-4 16, and Q1 17. After sorting sort_columns_years, I am thinking I can use count to measure how many of a smaller value exists, to do something in the case of hree quarters in the preceding year like this: new_list = [] `if sort_columns_years.count(16) == 3: sort_quarters = ['Q2','Q3','Q4','Q1'] for each in range(0,len(sort_quarters)): new_list.append(sort_column_years[each] + sort_column_years(sort_quarters[each])) to get new_list = ['Q2 16', 'Q3 16', 'Q4 16', 'Q1 17'] but I don't know how to do something similar avoiding hard coding 16 or 17.
accepted answer: http://stackoverflow.com/a/51900662
upvote count: 1
tagged with: python
type: AnsweredQuestion
type: Question

http://stackoverflow.com/comment/90751058
comment on: http://stackoverflow.com/a/51899930
type: AnswerComment
score: 0
type: Comment
has text: My modules are not packaged, and I am only importing numpy, not the math module. The fact that _NumPy_ is unable to import the standard math module by writing `import math`, because I have a file named `math.py` in my local folder, is completely insane.

http://stackoverflow.com/a/51912184
has body: One way to make your approach more general is to do the scalar * column multiplication without explicitly having to name each column. If you can be sure that your H dictionary keys will always exactly match your DataFrame column names, try this: # Multiply each DF column with its corresponding dict value temp = df_H.transform(lambda x: x * H[x.name]) # Add up transformed rows and divide by the sum of all dict values df_H['COI'] = temp.sum(axis=1) / sum(H.values()) Runnable example df_H = pd.DataFrame({'G1_H': [0, 1, 2, 3], 'G2_H': [2, 4, 6, 8], 'G3_H': [-1, 0, 1, 2]}) H = dict(G1_H=1, G2_H=2, G3_H=3) temp = df_H.transform(lambda x: x * H[x.name]) df_H['COI'] = temp.sum(axis=1) / sum(H.values()) H {'G1_H': 1, 'G2_H': 2, 'G3_H': 3} temp G1_H G2_H G3_H 0 0 4 -3 1 1 8 0 2 2 12 3 3 3 16 6 df_H G1_H G2_H G3_H COI 0 0 2 -1 0.166667 1 1 4 0 1.500000 2 2 6 1 2.833333 3 3 8 2 4.166667 Wordy Explanation temp = df_H.transform(lambda x: x * H[x.name]) What df.transform() does is process each column of df, and for each column, return a result with the same length as the input column. So running df.transform() always results in a DataFrame with the same shape. df.transform() takes in a function, which in this case is a lambda function (a function with no name defined in-place, as opposed to in advance with def func_name(arg1):). lambda x: x * H[x.name] says for each column "x" in df, multiply it with the dictionary value whose key is x.name, which is each column's name. (Remember, the columns in a DataFrame are just Series, and each column name is accessible through Series.name.) This function works because your python dictionary H has keys that exactly match the columns in your DF. df_H['COI'] = temp.sum(axis=1) / sum(H.values()) By order of operations, this line first adds up the values in each row of temp (due to axis=1), resulting in a Series with only one column in it. (The default dimension of most pandas methods is axis=0, which acts on the values in each column, which woul…
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90788934
has comment: http://stackoverflow.com/comment/90784717
type: Answer
accepted answer of: http://stackoverflow.com/q/51910798
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/51910798

http://stackoverflow.com/comment/90699753
score: 1
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51874098
has text: Can you try a different URL, does it happen with all the URLs?

http://stackoverflow.com/q/51856843
tagged with: matplotlib
type: Question
tagged with: 3d
answer count: 1
tagged with: scatter
score: 0
has answer: http://stackoverflow.com/a/51858130
has body: Here is my code: import numpy as np import matplotlib.pyplot as plt import matplotlib as mpl from matplotlib import cm #from matplotlib.patches import Circle ri = 100 ra = 300 h=20 # input xy coordinates xy = np.array([[ri,0],[ra,0],[ra,h],[ri,h],[ri,0]]) # radial component is x values of input r = xy[:,0] # angular component is one revolution of 30 steps phi = np.linspace(0, 2*np.pi, 50) # create grid R,Phi = np.meshgrid(r,phi) # transform to cartesian coordinates X = R*np.cos(Phi) Y = R*np.sin(Phi) # Z values are y values, repeated 30 times Z = np.tile(xy[:,1],len(Y)).reshape(Y.shape) fig = plt.figure() ax = fig.add_subplot(1, 1, 1, projection='3d') ax.set_zlim(0,200) ax.plot_surface(X, Y, Z, alpha=0.5, color='grey', rstride=1, cstride=1, linewidth=0, edgecolor='none') arr = np.array([[100, 15], [114.28, 17], [128.57, 18], [142.85, 24], [157.13, 26], [171.13, 28], [185.69, 29], [199.97, 30], [214.25, 31], [228.53, 32], [242.81, 35], [257.09, 36], [271.37, 37], [288.65, 40]]) #interpolating between the single values of the arrays new_x = np.concatenate([np.linspace(arr[i,0],arr[i+1,0], num=20) for i in range(len(arr)-1)]) new_y = np.interp(new_x, arr[:,0], arr[:,1]) t=np.arange(260) tmp_phi = np.linspace(0,2*np.pi,20)[:,None] # angle data linesurf_x = new_x*np.cos(tmp_phi) linesurf_y = new_x*np.sin(tmp_phi) linesurf_z = np.broadcast_to(new_y, linesurf_x.shape) linesurf_c = np.broadcast_to(t, linesurf_x.shape) # color according to t colors = cm.jet(linesurf_c/linesurf_c.max()) # grab actual colors for the surface ax.plot_surface(linesurf_x, linesurf_y, 1.5*linesurf_z, facecolors=colors, rstride=1, cstride=3, linewidth=1, edgecolor='none') cax, _ = mpl.colorbar.make_axes(plt.gca(), shrink=0.8) cax.yaxis.set_ticks_position('right') cbar = mpl.colorbar.ColorbarBase(cax, cmap='jet', label='test', norm=mpl.colors.Normalize(vmin=15, vmax=41)) plt.show() The problem is the speed. It calculates quite a long time but this is not the biggest problem. After the graph has been …
type: UnansweredQuestion
tagged with: python
has title: How to increase speed of matplotlib scatter plot?

http://stackoverflow.com/comment/90819088
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51934474
score: 0
has text: How are you generating scores? This is confusing. Have you read through the help center on proper question writing?

http://stackoverflow.com/q/51815361
has title: Scipy imsave and imread change format
answer count: 2
has comment: http://stackoverflow.com/comment/90608290
score: 3
favorite count: 0
possible better answer: http://stackoverflow.com/a/51826990
has comment: http://stackoverflow.com/comment/90609419
has answer: http://stackoverflow.com/a/51826990
has comment: http://stackoverflow.com/comment/90609581
tagged with: python
has comment: http://stackoverflow.com/comment/90609402
tagged with: image-formats
type: AnsweredQuestion
has body: When I save the image, the format it has is numpy.uint16, when I load it, it is numpy.uint8, and it messes up the whole pipeline for me. How do I prevent this from happening? I am calling from scipy.misc import imread, imsave image = imread(path) imread(image_path)
upvote count: 3
tagged with: image-processing
tagged with: scipy
type: Question
has answer: http://stackoverflow.com/a/51815792
has comment: http://stackoverflow.com/comment/90589991
has comment: http://stackoverflow.com/comment/90607407
downvote count: 0
accepted answer: http://stackoverflow.com/a/51815792

http://stackoverflow.com/comment/90724837
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51886517
type: AnswerComment
has text: The library I'm using checks one command on Linux/Windows/Mac. Making a special case for it to run two commands just for some wonky windows bug is possible but not desirable. Better, would be python + windows behaving properly, second case would be a way to fix up a single command to give me a valid STDOUT. Worst case is upstream logic for something problematic like we have here.

http://stackoverflow.com/q/51953003
has comment: http://stackoverflow.com/comment/90856509
tagged with: python
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90856906
tagged with: scipy
has comment: http://stackoverflow.com/comment/90856551
has comment: http://stackoverflow.com/comment/90856701
has body: I have the following code which throws me error: RuntimeError: Optimal parameters not found: Number of calls to function has reached maxfev = 1000 I think it is due to the def func in the loop. How can it be fixed? I am using curve_fit from scipy and I want to find better values for many independent groups. I is working WITHOUT LOOP perfectly. thanks! RuntimeError: Optimal parameters not found: Number of calls to function has reached maxfev = 1000. df_fit = pd.DataFrame() for (group, df_gp) in df.groupby(['label']): df_gp.sort_values(['animal']).reset_index(drop=True) if len(df_gp) &gt; 0: if len(df_gp) % 2 == 0: df_gp = pd.concat([df_gp, df_gp.tail(1)], axis=0); x = np.arange(1,len(df_gp)+1) y = df_gp['price'] xx = np.linspace(x.min(),x.max(), len(df_gp)) # interpolate + smooth itp = interp1d(x,y, kind='linear') #kind = 'linear', 'nearest' (dobre vysledky), slinear (taky ok), cubic (nebrat), quadratic - nebrat # window size must be odd window_size, poly_order = len(df_gp), 2 yy_sg = savgol_filter(itp(xx), window_size, poly_order) def func(x, A, B, x0, sigma): return A+B*np.tanh((x-x0)/sigma) fit, _ = curve_fit(func, x, y) yy_fit = func(xx, *fit) #fit1 = np.poly1d(np.polyfit(x, y, 3)) #df_gp = df_gp.drop_duplicates(subset= 'sku',keep = 'first', inplace =True) # pridani promennych do dataframe df_gp['yy_fit'] = yy_fit df_gp['yy_sg'] = yy_sg df_fit = pd.concat([df_fit,df_gp], axis = 0) df_fit = df_fit.sort_values(['sku']).reset_index(drop=True)
has comment: http://stackoverflow.com/comment/90856855
type: Question
score: 0
has comment: http://stackoverflow.com/comment/90857482
tagged with: pandas
has comment: http://stackoverflow.com/comment/90856607
has title: RuntimeError: Optimal parameters not found: Number of calls to function has reached maxfev = 1000
has comment: http://stackoverflow.com/comment/90856476

http://stackoverflow.com/q/51814926
has comment: http://stackoverflow.com/comment/90584269
tagged with: python
has body: I'm using pip install wikipedia to make a simple "Philosophy step counter" and can't get the result I'm looking for. No matter what page I enter the code never finds a link that matches any of the words in the first few sentences of the article. Code is below: import os import string import wikipedia wikipedia.set_lang("en") print("Please type the name of a wikipedia article: ") page = input() print("Searching wikipedia for: " + page) wikiPage = wikipedia.page(page) print("Using top result: " + wikiPage.title) # currentPage = wikipedia.page(wikiPage.links[0]) # List of links (sorted alphabetically, makes our job much harder) links = wikiPage.links # Split the beginning of the article into words words = wikipedia.summary(wikiPage, sentences=3).split() words = [''.join(c for c in s if c not in string.punctuation) for s in words] # Sanitize list of words to remove punctuation # comparisons = [a == b for (a, b) in itertools.product(words, links)] x = 0 while words[x] not in links: print(words[x]) x = x + 1 newPage = wikipedia.page(words[x]) Is this a fault of the library I'm using or my code? The link list appears to be ordered alphabetically if that makes any difference (hence why I'm doing all this in the first place)
score: 4
answer count: 0
type: UnansweredQuestion
tagged with: wikipedia
type: Question
upvote count: 4
has comment: http://stackoverflow.com/comment/90615679
downvote count: 0
has title: Simple wikipedia library that returns link list is not behaving as expected
has comment: http://stackoverflow.com/comment/90584299
has comment: http://stackoverflow.com/comment/90784567
favorite count: 0

http://stackoverflow.com/comment/90795904
type: Comment
score: 1
has text: @ Oysisyl, I got it. Your suggestion above works!!! My only question now is that the x axis in the plot shows 'Fri 20-07 03:00:00'. Is there any chance we can get rid of the time part in the plot display? I cannot remove the time in data because that will remove the number of data points.
type: AnswerComment
comment on: http://stackoverflow.com/a/51907922

http://stackoverflow.com/q/51814659
tagged with: python
linked to: http://stackoverflow.com/q/9502183
score: 1
type: Question
has title: Is it possible to create a python object which does not have either a __slots__ nor a __dict__?
has body: Is it possible to create a python object which does not have either a __slots__ a __dict__?
upvote count: 1
has comment: http://stackoverflow.com/comment/90583884
answer count: 1
downvote count: 0
tagged with: slots
has answer: http://stackoverflow.com/a/51814776
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion

http://stackoverflow.com/comment/90601827
comment on: http://stackoverflow.com/a/51822672
score: 0
type: Comment
has text: @DaveHonley You could do a simple membership check for the substring `any(word in message.content for word in word_set)`, but that will also catch innocent substrings. If you want to ban the word "sword", this would also catch "swordfish" and "password". That's a non-trivial problem, and probably involves some degree of natural language processing and fuzzy string matching.
type: AnswerComment

http://stackoverflow.com/a/51909121
type: AcceptedAnswer
score: 0
answers question: http://stackoverflow.com/q/51908481
type: Answer
accepted answer of: http://stackoverflow.com/q/51908481
has body: The error (which is yet unknown to us) in your last code seems to be arising due to the exceeding limit or overwritten plots as you are plotting 45xiN number of plots in contrast to your original long code where you plot 45 plots. I created a workaround to avoid the second for loop. I created two lists of indices to be used for labels. By doing so, you just need one for loop. Following is the code. You can print the list indices to make sure that the combination of indices matches your first long code. # Create indices for labels indices = [(i, j) for i in range(10) for j in range(10) if i &lt; j] x, y = zip(*indices) plt.figure(figsize=(10, 5)) for i in range(45): plt.plot(vDT, mPR[i,:], label= asX[x[i]] + asX[y[i]])

http://stackoverflow.com/q/51851410
has title: Generating file created date and last modified date with Python
has comment: http://stackoverflow.com/comment/90656290
downvote count: 0
has answer: http://stackoverflow.com/a/51851862
tagged with: postgresql
answer count: 1
score: 1
linked to: http://stackoverflow.com/q/237079
favorite count: 0
has comment: http://stackoverflow.com/comment/90659469
type: UnansweredQuestion
has body: I am building a script that walks through a directory (and its subdirectories) the user specifies and uploads the files to a postgres DB. It all works -- after a lot of trial and error! -- and now I'm trying to implement a check before uploading that the same filename + modified date do not exist in the DB prior to uploading. (If the same file version does exist, I want to skip it.) Can anyone advise me on how to go about this? """A tool for saving files to and from a postgresql db. *** THIS IS WRITTEN FOR PYTHON 2.7 *** """ import os import sys import argparse import psycopg2 import time import datetime import msvcrt as m db_conn_str = "xxx" # Define your table schema create_table_stm = """ CREATE TABLE IF NOT EXISTS test_table ( id serial PPRIMARY KEY, orig_filename TEXT NOT NULL, file_extension TEXT NOT NULL, created_date DATE NOT NULL, last_modified_date DATE NOT NULL, upload_timestamp_UTC TIMESTAMP NOT NULL, uploaded_by TEXT NOT NULL, file_size_in_bytes INTEGER NOT NULL, original_containing_folder TEXT NOT NULL, file_data BYTEA NOT NULL ) """ uploaded_by = raw_input("Please, enter your [Firstname] [Lastname]: ") if not uploaded_by: print "You did not enter your name. Press ENTER to exit this script, then attempt to run the script again." m.getch() exit() else: print "Thank you, " + uploaded_by + "! Please, press ENTER to upload the files." m.getch() # Walk through the directory def main(): parser = argparse.ArgumentParser() parser_action = parser.add_mutually_exclusive_group(required=True) parser_action.add_argument("--store", action='store_const', const=True, help="Load an image from the named file and save it in the DB") parser_action.add_argument("--fetch", type=int, help="Fetch an image from the DB and store it in the named file, overwriting it if it exists. Takes the database file identifier as an argument.", metavar='42') parser.add_argument("parentdir", help="Name of folder to write to / fetch from") args = parser.parse_args() conn = psycopg2.connect(db_…
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/90656254
has comment: http://stackoverflow.com/comment/90656279
type: Question
tagged with: for-loop

http://stackoverflow.com/comment/90799231
comment on: http://stackoverflow.com/a/51916006
has text: @BenyaminJafari this error means Python is installed successfully. Run the resulting container and run three commands: `which -a python3`, `which -a pip3` and `pip3 list`, what is the output?
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/51881487
type: Question
has comment: http://stackoverflow.com/comment/90714386
has comment: http://stackoverflow.com/comment/90714375
has answer: http://stackoverflow.com/a/51881623
has answer: http://stackoverflow.com/a/51881569
has answer: http://stackoverflow.com/a/51881691
answer count: 3
linked to: http://stackoverflow.com/q/8450472
upvote count: 1
has comment: http://stackoverflow.com/comment/90714506
has comment: http://stackoverflow.com/comment/90714970
possible better answer: http://stackoverflow.com/a/51881623
tagged with: string
favorite count: 0
has title: How to prevent different sized spaces between strings?
tagged with: python
has body: This may be quite a vague question so i'll try to explain the best way i can. Say if i have 2 variables (with different sized length) variable_one = "John Doe" variable_two = "Thomas Smith" How would i print them in such a way that the output would be consistently spaced in between each variable without knowing the exact length of the strings? For Example if i print them out normally with things in the middle: print(variable_one + " - Age: 40") print(variable_two + " - Age: 2") The output would be: John Doe - Age: 40 Thomas Smith - Age: 2 How would i automatically make the output consistent with spaces so it would look something like this: John Doe - Age: 40 Thomas Smith - Age: 2 Thank you :) ~ Pete
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90714430
downvote count: 0
has comment: http://stackoverflow.com/comment/90714383
score: 1
tagged with: formatting
linked to: http://stackoverflow.com/q/9535954
accepted answer: http://stackoverflow.com/a/51881569
has comment: http://stackoverflow.com/comment/90714512

http://stackoverflow.com/comment/90897937
comment on: http://stackoverflow.com/a/51965157
score: 0
type: AnswerComment
type: Comment
has text: You're welcome:) Let me know how it works. I didn't see any *Python* version, so I assumed it's 3. For *Python 2* it's simpler since you can ignore the 2nd bullet.

http://stackoverflow.com/comment/90802114
has text: @needtobe thanks a lot, that solved the problem with imports, god bless you)
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51925284
type: QuestionComment

http://stackoverflow.com/q/51951686
answer count: 2
has answer: http://stackoverflow.com/a/51955808
tagged with: flask
possible better answer: http://stackoverflow.com/a/51955808
has title: Save flask-admin editing history
tagged with: flask-admin
tagged with: python
has answer: http://stackoverflow.com/a/51953451
accepted answer: http://stackoverflow.com/a/51953451
has body: I'm trying implement method that will add to column 'editing-date' the date of editing OF ANOTHER column. Like I'm changing username in a row and simultaneously on 'editing-date' appears something like '23.08.18'. What is the best way to do it?
type: AnsweredQuestion
type: Question
score: 0

http://stackoverflow.com/q/51839083
has answer: http://stackoverflow.com/a/51956399
downvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90643373
has comment: http://stackoverflow.com/comment/90691406
score: 1
has body: I am using MacOS. I used following command: gcloud beta functions deploy start --runtime python37 --trigger-http --memory 2048MB --timeout 540s But while deploying google cloud functions I got this error: (gcloud.beta.functions.deploy) OperationError: code=3, message=Build failed: USER ERROR: pip_download_wheels had stderr output: Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-wheel-8b_hn74q/PyWavelets/ error: pip_download_wheels returned code: 1 I added scikit-image in my requirements.txt, which was not added before. Code was successfully deploying when scikit-image was not added in requirements.txt. Any ideas?
has title: Deploying Google Cloud Functions
type: Question
answer count: 2
tagged with: google-cloud-platform
upvote count: 1
has comment: http://stackoverflow.com/comment/91694555
has answer: http://stackoverflow.com/a/64228383
favorite count: 0
tagged with: google-cloud-functions
tagged with: python

http://stackoverflow.com/comment/90817698
has text: Look, since /messages/page_not_found.html?eBayErrorEventName=p4buoaj···, it looks like you are hitting the wrong page or the correct page but wrongly in some way. It doesn't looks at all as Google App Engine blocking regular requests. Have you solved your problem already?
score: 0
comment on: http://stackoverflow.com/q/51886180
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90686181
has text: You want to know where the difference jumps by more than 1?
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51867074

http://stackoverflow.com/q/51886844
tagged with: python
type: AnsweredQuestion
has title: Tensorflow: Raw prediction output with large values
upvote count: 1
tagged with: tensorflow
has answer: http://stackoverflow.com/a/55700106
type: Question
has comment: http://stackoverflow.com/comment/90737806
has comment: http://stackoverflow.com/comment/90758657
answer count: 1
downvote count: 0
tagged with: neural-network
score: 1
accepted answer: http://stackoverflow.com/a/55700106
has body: I have a neural network in TensorFlow (1.8) which has (seemingly) large values for the output vector. Here are some lines from a training session at about 1 hour into training, where we have a classification network for training to three labels (ie. classes). The loss &amp; accuracy for both training &amp; test data can be seen, as well as the Standard Deviation of the three raw output values (Ypred node in listing below). These are raw values before softmax. These values seem unreasonably large compared to other NNs I've seen where the values should be much closer to one. #1350000: Training Loss=89.791, Acc=0.735; Test Loss=79.961, Acc=0.792; RawStDev=[175.123, 382.312, 130.729, ] #1360000: Training Loss=91.001, Acc=0.729; Test Loss=77.937, Acc=0.787; RawStDev=[172.724, 366.065, 134.253, ] #1370000: Training Loss=86.340, Acc=0.751; Test Loss=83.953, Acc=0.773; RawStDev=[181.191, 383.081, 130.524, ] #1380000: Training Loss=86.987, Acc=0.743; Test Loss=83.830, Acc=0.790; RawStDev=[182.473, 381.195, 137.126, ] #1390000: Training Loss=88.804, Acc=0.729; Test Loss=79.096, Acc=0.787; RawStDev=[175.505, 371.759, 135.942, ] #1400000: Training Loss=83.822, Acc=0.754; Test Loss=81.093, Acc=0.798; RawStDev=[173.978, 376.775, 136.153, ] #1410000: Training Loss=85.469, Acc=0.735; Test Loss=79.343, Acc=0.793; RawStDev=[180.332, 386.373, 129.154, ] #1420000: Training Loss=86.125, Acc=0.738; Test Loss=77.993, Acc=0.803; RawStDev=[190.086, 386.139, 129.828, ] #1430000: Training Loss=85.288, Acc=0.732; Test Loss=82.180, Acc=0.782; RawStDev=[183.839, 381.932, 125.370, ] #1440000: Training Loss=83.263, Acc=0.747; Test Loss=79.853, Acc=0.806; RawStDev=[177.329, 367.796, 125.690, ] The code for the top three (dense) layers and the SGD definitions are shown below: with tf.name_scope('DensePost'): Xnew = tf.matmul(gathered, weights['Post1']) + biases['Post1'] Xnew = tf.nn.dropout(Xnew, keep_prob) Xnew = tf.matmul(Xnew, weights['Post2']) + biases['Post2'] Xnew = tf.nn.dropout(Xnew, keep_pr…
favorite count: 0

http://stackoverflow.com/comment/90602190
score: 0
type: Comment
type: QuestionComment
has text: Console.log gives me -> Possibly unhandled rejection: {"data":null,"status":-1,"config":{"method":"GET","transformRequest":[null],"transformResponse":[null],"jsonpCallbackParam":"callback","url":"http://localhost:8888/app","headers":{"Accept":"application/json, text/plain, */*"}},"statusText":"","xhrStatus":"error"}
comment on: http://stackoverflow.com/q/51823778

http://stackoverflow.com/q/51895207
has body: All, I have a code that looks like this: if condition if condition: do something elif condition: do something else: break else: do something I have a nested if condition and I introduced a break in the inner "if condition" with the intention to break from that inner if condition if conditions are not met and move on to the "else" of the outer if condition. In your opinion, does it make sense to do that way? is there a simple way of writing the problem.
has comment: http://stackoverflow.com/comment/90741122
favorite count: 0
has comment: http://stackoverflow.com/comment/90740979
has answer: http://stackoverflow.com/a/51895591
has title: nested if condition and break
tagged with: python
possible better answer: http://stackoverflow.com/a/51895386
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51895386
score: 1
accepted answer: http://stackoverflow.com/a/51895351
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/90741158
tagged with: if-statement
has comment: http://stackoverflow.com/comment/90740918
answer count: 3
has comment: http://stackoverflow.com/comment/90741168
downvote count: 0
has comment: http://stackoverflow.com/comment/90740997
has answer: http://stackoverflow.com/a/51895351

http://stackoverflow.com/q/51826748
upvote count: 1
answer count: 1
favorite count: 0
has title: Querying a .csv file with conditions using Pandas and .shift
tagged with: http://stackoverflow.com/tag/csv
has body: I'm having trouble querying a simple .csv file of trade data with conditions. The .csv file has 5 columns - [open, high, low, close, volume] with a time-series index, of minute by minute trades. What I want to do is build a script that (1) tells me how many times the close price minus the open price of the previous minute is positive. (2) the volume of the previous minute is greater than that of the minute before it. So far I have the first half (1) down with: ts2 = ts[(ts["close"]-ts["open"].shift(1))&gt;0] However, I am having trouble combining it with the volume conditions (2) I require. I have attempted the following, both resulting in syntax and other errors. ts2 = ts[(ts["close"]-ts["open"].shift(1))&gt;0] ts3 = ts[(ts["volume"].shift(1)-ts["volume"].shift(2))&gt;0] ts4 = ts[ts2 &amp; ts3] ts4 = ts[(ts["close"]-ts["open"].shift(1)&gt;0) &amp; (ts["volume"].shift(1)-ts["volume"].shift(2)&gt;0) Ultimately I would use the: print(len(ts4)) To find how many occurrences there are in my csv file of the conditional query. Please let me know how I can combine both conditions, and if there is a way to improve my current methodology. Thank you, all help is greatly appreciated!
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 1
accepted answer: http://stackoverflow.com/a/51831809
type: Question
tagged with: conditional-statements
has answer: http://stackoverflow.com/a/51831809
tagged with: querying
tagged with: pandas

http://stackoverflow.com/comment/90810939
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51930429
has text: I thought the code will stretch the question. I have 3-4 approaches but none is working perfectly on all cases.

http://stackoverflow.com/comment/90629704
comment on: http://stackoverflow.com/a/51837554
type: AnswerComment
type: Comment
score: 0
has text: Ok, I think I have other problems in the data before dealing with my missing values.

http://stackoverflow.com/comment/91012725
type: Comment
has text: I'm so sorry! I literally clicked on the wrong answer -- that bounty was meant for you. Honest apologies.
comment on: http://stackoverflow.com/a/51936407
type: AnswerComment
score: 0

http://stackoverflow.com/a/51845434
downvote count: 1
has body: I think you need better timings. I also disagree with the accepted answer. b is a dictionary with 9 keys; the values are lists of arrays. That means both pickle.dump and np.save will be using each other - pickle uses save to pickle the arrays, save uses pickle to save the dictionary and list. save writes arrays. That means it has to wrap your dictionary in a object dtype array in order to save it. In [6]: np.save('test1',b) In [7]: d=np.load('test1.npy') In [8]: d Out[8]: array({0: [array([0, 0, 0, 0])], 1: [array([1, 0, 0, 0]), array([0, 1, 0, 0]), .... array([ 1, -1, 0, 0]), array([ 1, 0, -1, 0]), array([ 1, 0, 0, -1])]}, dtype=object) In [9]: d.shape Out[9]: () In [11]: list(d[()].keys()) Out[11]: [0, 1, 2, 3, 4, 5, 6, 7, 8] Some timings: In [12]: timeit np.save('test1',b) 850 µs ± 36.9 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) In [13]: timeit d=np.load('test1.npy') 566 µs ± 6.44 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) In [20]: %%timeit ...: with open('testpickle', 'wb') as myfile: ...: pickle.dump(b, myfile) ...: 505 µs ± 9.24 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) In [21]: %%timeit ...: with open('testpickle', 'rb') as myfile: ...: g1 = pickle.load(myfile) ...: 152 µs ± 4.83 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each) In my timings pickle is faster. The pickle file is slightly smaller: In [23]: ll test1.npy testpickle -rw-rw-r-- 1 paul 5740 Aug 14 08:40 test1.npy -rw-rw-r-- 1 paul 4204 Aug 14 08:43 testpickle
score: 3
upvote count: 4
answers question: http://stackoverflow.com/q/51837627
type: Answer

http://stackoverflow.com/a/51880545
has comment: http://stackoverflow.com/comment/90713184
has comment: http://stackoverflow.com/comment/90714482
type: Answer
answers question: http://stackoverflow.com/q/51822922
has body: Should avoid the call to apply. Pandas has built-in str methods. Something like this: mask = df['Size'].str.startswith('=') df.loc[mask, 'Size'] = "'" + df.loc[mask, 'Size']
has comment: http://stackoverflow.com/comment/90713663
score: 0

http://stackoverflow.com/comment/90784611
has text: I'd say you should subclass `list` and `dict` and overwrite the existing `__add__`.
score: 0
comment on: http://stackoverflow.com/q/51917400
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52290741
score: 0
type: AcceptedAnswer
type: Answer
has body: After some research (and a lot of experiments) I have come to some conclusions which might help others facing the same problem. Failing to detect any object probably means that the model has collapsed in some part of training. A possible indication of this in my case was some extremely high values of loss values when training. While I have models that this happened and does not seem to affect the model too much (at least not too much to make it useless) an increasing amount of these values is a good sign that something is fatally wrong. Notice that the frequency of appearance of these values is not necessarily increasing all the time. More classes the better: After the first period I was conducting my experiments with just 1 class. While this is legitimate and nothing has been mentioned (to my knowledge) about avoiding it (I even read tutorials using 1 class object detection) this also intensified the crack rate. Using 2 classes seems to partially alleviate the problem. When I trained my model with 11 classes the problem seems to vanish. Small variation in bbox's sizes helps: Experimenting with bounding boxes varying a lot in size I came to the conclusion that largely homogeneous bbox's sizes help to also alleviate the issue. More classes may increase performance: I have noticed also that while 11 classes problem seem quite heavier task than 1 class due to the limitations in training the model with 1 class performance is some cases was higher in the former case. My final conclusion is that my model for some reason was experiencing at some point an overflow on some weights that prevent it from returning to the normal again. The fact that I have augmented my data (maybe similar images were fed one after the other and intensified certain weights for example) maybe increased the frequency of the problem occurrence but the problem was still present in non-augmented dataset.
accepted answer of: http://stackoverflow.com/q/51931564
answers question: http://stackoverflow.com/q/51931564

http://stackoverflow.com/q/51812976
tagged with: python
possible better answer: http://stackoverflow.com/a/51813014
has body: The top 5 rows in my data frame: roster_data.head() No. Player Flag Pos Age Ht Wt S/C Exp 27.0 Karl Alzner ca D 29 3-Jun 217 L/- 9 8.0 Jordie Benn ca D 30 2-Jun 198 L/- 6 41.0 Paul Byron ca C/LW 28 9-May 162 L/- 7 43.0 Daniel Carr ca LW 26 Jun-00 193 L/- 2 24.0 Phillip Danault ca LW 24 1-Jun 195 L/- 3 Using Age and YearsExperience (EXP column), how do I calculate what player from the list started playing for the NHL at the earliest age? I am unable to get the logic of the code.
has answer: http://stackoverflow.com/a/51813014
type: AnsweredQuestion
upvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/51813023
has title: Compute some metric using two columns of a DataFrame
answer count: 2
tagged with: pandas
has comment: http://stackoverflow.com/comment/90580846
downvote count: 0
score: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51813023

http://stackoverflow.com/a/51858908
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51858833
has body: You can give the key parameter a lambda which will extract the timestamp from the entry. By default, the sorting is in natural sorting. You can do a reverse sorting by giving reverse=True &gt;&gt;&gt; l= ["scan-localhost-201808150818.xml","scan-scanme.nmap.org-201808150746.xml"] &gt;&gt;&gt; &gt;&gt;&gt; sorted(l, key = lambda x: x.rsplit('-')[-1].split(".")[0] , reverse = True) ['scan-localhost-201808150818.xml', 'scan-scanme.nmap.org-201808150746.xml'] &gt;&gt;&gt;
has comment: http://stackoverflow.com/comment/90670018
type: Answer
upvote count: 2
has comment: http://stackoverflow.com/comment/90670209
has comment: http://stackoverflow.com/comment/90670064
accepted answer of: http://stackoverflow.com/q/51858833
score: 2

http://stackoverflow.com/comment/90596101
has text: I mean is it possible just to loop over the bare cursor object ?
type: Comment
comment on: http://stackoverflow.com/a/51820230
score: 0
type: AnswerComment

http://stackoverflow.com/q/51861488
has comment: http://stackoverflow.com/comment/90678344
tagged with: anaconda
downvote count: 0
has body: I need to run a Flask application as a Windows service. I managed to convert it to a Windows service using win32serviceutil. The problem I have is that it only works when I manually run PythonService.exe (with the -debug flag) from the "activated" environment (of course). Is there a way to activate the environment before attempting to run the service? I see some people used the Task Scheduler as a workaround but I'd prefer if Windows service manager could be used instead.
tagged with: windows-services
type: Question
has comment: http://stackoverflow.com/comment/90676098
upvote count: 2
has title: Windows service running in a Anaconda environment?
has answer: http://stackoverflow.com/a/51863823
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: windows
tagged with: python
has comment: http://stackoverflow.com/comment/90675370
score: 2

http://stackoverflow.com/q/51828304
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/70730512
tagged with: iot
answer count: 2
tagged with: raspberry-pi
downvote count: 0
has comment: http://stackoverflow.com/comment/90621957
tagged with: amazon-web-services
favorite count: 0
has body: I have the pubSub code example working, so I can publish to MQTT topics. And it is my understanding that I just need to change the topic to "mything/shadow/update", and the shadow would be updated, but it doesn't. My current shadow state looks like: { "desired":{ "welcome": "aws-iot" }, "reported":{ "welcome": "aws-iot" } }
has title: AWS IoT: Shadow not updating
type: UnansweredQuestion
tagged with: python
tagged with: aws-iot
score: 1
has answer: http://stackoverflow.com/a/51834194

http://stackoverflow.com/comment/90833290
has text: @ALee. The other question can be deemed a duplicate of this one, but not vice versa. OP is asking for a conversion, not just a clip operation. The first answer posted here is incomplete.
score: 2
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51941650

http://stackoverflow.com/q/51885609
tagged with: loops
tagged with: scipy
type: Question
tagged with: numpy
score: 3
possible better answer: http://stackoverflow.com/a/51886097
has title: Efficient way to subset and combine arrays of different lengths
has answer: http://stackoverflow.com/a/51886097
accepted answer: http://stackoverflow.com/a/51891193
answer count: 2
tagged with: arrays
downvote count: 0
favorite count: 0
has body: Given a 3 dimensional boolean data: np.random.seed(13) bool_data = np.random.randint(2, size=(2,3,6)) &gt;&gt; bool_data array([[[0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 1, 0], [0, 0, 0, 0, 0, 1]], [[1, 0, 1, 1, 0, 0], [0, 1, 1, 1, 1, 0], [1, 1, 1, 0, 0, 0]]]) I wish to count the number of consecutive 1's bounded by two 0's in each row (along axis=1) and return a single array with the tally. For bool_data, this would give array([1, 1, 2, 4]). Due to the 3D structure of bool_data and the variable tallies for each row, I had to clumsily convert the tallies into nested lists, flatten them using itertools.chain, then back-convert the list into an array: # count consecutive 1's bounded by two 0's def count_consect_ones(input): return np.diff(np.where(input==0)[0])-1 # run tallies across all rows in bool_data consect_ones = [] for i in range(len(bool_data)): for j in range(len(bool_data[i])): res = count_consect_ones(bool_data[i, j]) consect_ones.append(list(res[res!=0])) &gt;&gt; consect_ones [[], [1, 1], [], [2], [4], []] # combines nested lists from itertools import chain consect_ones_output = np.array(list(chain.from_iterable(consect_ones))) &gt;&gt; consect_ones_output array([1, 1, 2, 4]) Is there a more efficient or clever way for doing this?
tagged with: python
has answer: http://stackoverflow.com/a/51891193
type: AnsweredQuestion
upvote count: 3

http://stackoverflow.com/comment/90704224
type: QuestionComment
has text: Could you provide a proper printout of your dataframes (with column names)?
comment on: http://stackoverflow.com/q/51874297
score: 0
type: Comment

http://stackoverflow.com/q/51814209
score: 0
tagged with: pylama
has comment: http://stackoverflow.com/comment/91301171
has body: To All, How do I set python-mode so the linters check for Python 3 versus Python 2 errors depending on if I am editing a Python 3 or a Python 2 file? After the last update of python-mode, the linters seems to be defaulting to Python 3. For example there are lots of complaints about print statements - print "hello world" instead of print functions - print("hello world") when I am in a Python 2 file. Note that let g:pymode_python = 'python' is not the solution so I could not find an answer in :help pymode Thanks, Steve
tagged with: python
tagged with: python-3.x
linked to: http://stackoverflow.com/q/23052637
has title: How to set python-mode so linters check for python 3 versus python 2 errors
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91340118
tagged with: pylint
tagged with: python-mode
type: Question

http://stackoverflow.com/comment/90689941
comment on: http://stackoverflow.com/a/51834194
score: 0
type: AnswerComment
has text: Yes, update/accepted won’t show anything. We are just subscribing to the thing. It is the correct behaviour.
type: Comment

http://stackoverflow.com/q/51895320
has answer: http://stackoverflow.com/a/67937165
type: Question
upvote count: 4
answer count: 2
has comment: http://stackoverflow.com/comment/90745960
downvote count: 0
score: 4
has comment: http://stackoverflow.com/comment/90746157
has answer: http://stackoverflow.com/a/51895510
tagged with: python
has comment: http://stackoverflow.com/comment/90741344
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
has body: I recently came across a very interesting talk by James Powell on YouTube (LINK, around 12 minutes into the video). In his PyData talk, he states that "[...] The Python data model is a means by which you can implement protocols [...]". He relates his statement to the use of dunder-methods (like __init__, __repr__, etc.). I've been programming for quite a while with Python, but I haven't come across POP. The video didn't really define what it is. What is POP in Python actually and how is it used in practice?
linked to: http://stackoverflow.com/q/49731376
has comment: http://stackoverflow.com/comment/90745986
has comment: http://stackoverflow.com/comment/90742931
has title: Using Protocol-Oriented Programming (POP) in Python

http://stackoverflow.com/q/51874753
score: 0
accepted answer: http://stackoverflow.com/a/52292678
possible better answer: http://stackoverflow.com/a/51874870
tagged with: python
has answer: http://stackoverflow.com/a/51874885
has answer: http://stackoverflow.com/a/51874870
has body: I have a Django project. I have installed django-extensions from terminal and added django-extensions to installed apps. In pycharm i have selected the proper venv path for python interpreter Now in pycharm when I run the server it says django-extension not found. But I can run the server from terminal without any errors. In pycharm &gt; settings &gt; python interpreter : django-extensions is not shown. I checked pip list in terminal and it shows django-extension package. Also I can see django-extension folder in site-packages. I am not able to understand what's the problem. In Pycharm most of the pacakges are shown but only few are not shown
answer count: 4
tagged with: pycharm
tagged with: django
has title: pycharm: says package not installed but server runs fine from terminal without any error
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52292678
has answer: http://stackoverflow.com/a/51874897

http://stackoverflow.com/comment/90851823
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51937709
has text: I'd try to go with a `Graph Theory` solution ... Seems like you have a sequence of directed nodes, and you want to hold the information of the first and last nodes only. The directed edge from `x` to `y` (`x -> y`) can mean `x` replaces `y`, such that you'd just get first and last node info at the end

http://stackoverflow.com/q/51916775
tagged with: linux
answer count: 1
tagged with: shell
has comment: http://stackoverflow.com/comment/90783488
has comment: http://stackoverflow.com/comment/90783592
favorite count: 0
has comment: http://stackoverflow.com/comment/90783657
has comment: http://stackoverflow.com/comment/90784250
has comment: http://stackoverflow.com/comment/90783860
has answer: http://stackoverflow.com/a/51917294
tagged with: python
has comment: http://stackoverflow.com/comment/90783454
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90783814
has comment: http://stackoverflow.com/comment/90783557
has comment: http://stackoverflow.com/comment/90783884
has comment: http://stackoverflow.com/comment/90783709
tagged with: command-line-arguments
has comment: http://stackoverflow.com/comment/90783387
has comment: http://stackoverflow.com/comment/90783736
downvote count: 1
has title: Retrieving the cmd line arguments as it is in Python
has comment: http://stackoverflow.com/comment/90783873
type: Question
has comment: http://stackoverflow.com/comment/90783500
has comment: http://stackoverflow.com/comment/90783969
upvote count: 0
accepted answer: http://stackoverflow.com/a/51917294
has body: I am writing a wrapper tool in python. Invocation of the tool is as below: &lt;wrapper program&gt; &lt;actual program&gt; &lt;arguments&gt; The wrapper program just adds one more argument and executes the actual program: &lt;actual program&gt; &lt;arguments&gt; &lt;additional args added&gt; The tricky part is that has some strings that are escaped and some are not escaped Example arguments format: -d \"abc\" -f "xyz" "pqr" and more args The wrapper tool is generic and it shouldn't know about the actual program and parameters, other than adding an additional argument I understand that this is related to the shell. Any suggestions on how to implement the wrapper tool. I tried implementing by escaping all the "". There are some cases in which "" are not escaped in the invocation, so the tool is not able to execute the actual program correctly. Is it possible to preserve the original arguments as provided by the user ?. Wrapper.py Source: import sys import os if __name__ == '__main__': cmd = sys.argv[1] + " " args = sys.argv[2:] args.insert(0, "test") cmd_string = cmd + " ".join(args) print("Executing:", cmd_string) os.system(cmd_string) Output: wrapper.py tool -d "abc" -f \"pqr\" 123 Executing: tool test -d abc -f "pqr" 123 Expected execution: tool test -d "abc" -f \"pqr\" 123
has comment: http://stackoverflow.com/comment/90783901
score: -1
has comment: http://stackoverflow.com/comment/90783466
has comment: http://stackoverflow.com/comment/90783674
has comment: http://stackoverflow.com/comment/90783471

http://stackoverflow.com/comment/90789241
has text: Why are you using `params=q`? `data=q` is the usual way of submitting post data.
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51919643

http://stackoverflow.com/comment/90856896
comment on: http://stackoverflow.com/q/51951876
type: Comment
type: QuestionComment
has text: I mean delete the named directory which contains `bin`, `lib`, etc.
score: 0

http://stackoverflow.com/a/51931165
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51931137
has comment: http://stackoverflow.com/comment/90820858
answers question: http://stackoverflow.com/q/51931137
has comment: http://stackoverflow.com/comment/90819923
has body: Use DataFrame.lookup: df['value'] = df.lookup(df.index, df['selected']) print (df) id option_1 option_2 option_3 option_4 selected value 0 0 10.0 NaN NaN 110.0 option_4 110.0 1 1 NaN 20.0 200.0 NaN option_2 20.0 2 2 NaN 300.0 30.0 NaN option_3 30.0 3 3 400.0 NaN NaN 40.0 option_1 400.0 4 4 600.0 700.0 50.0 50.0 option_3 50.0
score: 4
type: AcceptedAnswer
type: Answer
upvote count: 4

http://stackoverflow.com/q/51927850
linked to: http://stackoverflow.com/q/14956313
has comment: http://stackoverflow.com/comment/90805426
has answer: http://stackoverflow.com/a/51927929
favorite count: 0
linked to: http://stackoverflow.com/q/12897374
duplicate of: http://stackoverflow.com/q/14956313
linked to: http://stackoverflow.com/q/12165200
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90806927
has comment: http://stackoverflow.com/comment/90805560
score: 4
has comment: http://stackoverflow.com/comment/90805334
has title: Is set deterministic?
has comment: http://stackoverflow.com/comment/90805452
has comment: http://stackoverflow.com/comment/90805361
has body: When reading such questions as Get unique values from a list in python you can see the remarks the order can be not preserved. This is understandable. What is bugging me that it goes farther -- as I can see the execution is not even deterministic, i.e: list(set(values_list)) I will get the unique values, the problem is with each run the outcome would be in different order. So this would mean set (constructor or enumerator) is not deterministic. I wonder how it happened? I don't see a reason why on single thread execution (?) you would get non-deterministic behavior. Sure, one can sort the outcome to enforce deterministic behavior, but you can get such idea once you observe you have non-deterministic code at hand. Update: The essence of my code -- the file is a pickle with array of 10 000 strings (with 3 unique values). combined = pickle.load(open("labels.p", "rb")) label_keys = list(set(combined)) print(label_keys) At each run I get different order. Oh, I use Python 3.6.4.
downvote count: 1
type: Question
linked to: http://stackoverflow.com/q/3812429
has comment: http://stackoverflow.com/comment/90805436
has comment: http://stackoverflow.com/comment/90805391
upvote count: 5
has comment: http://stackoverflow.com/comment/90805540
has comment: http://stackoverflow.com/comment/90805562
has comment: http://stackoverflow.com/comment/90807387
has comment: http://stackoverflow.com/comment/90806039
has comment: http://stackoverflow.com/comment/90806018
answer count: 1

http://stackoverflow.com/comment/90691115
type: Comment
score: 0
comment on: http://stackoverflow.com/q/51869729
has text: Yeah, but in the first game, the role is reversed for the other team... right?
type: QuestionComment

http://stackoverflow.com/a/51938121
downvote count: 0
score: 10
has body: It's already too late to influence the creation of the root logger when you called setLoggerClass(...). The root logger was already instantiated, it's created at the time of executing import logging, and exists as a RootLogger instance in the logging module's namespace. That getLogger() call is just returning the existing instance. However, any other logger you subsequently create, e.g. logging.getLogger('mylogger'), will be an instance of your subclass. Generally you will have this at the top of your module: log = logging.getLogger(__name__) And this log will by a MyLogger instance. Now, you shouldn't really care what class the root logger is, since you don't want events handled by it anyway. However, since this is Python and we're permitted to shoot our own grandparents if we really wish to, it's possible to morph the root logger's type all the same: &gt;&gt;&gt; root = logging.getLogger() &gt;&gt;&gt; root.__class__ = MyLogger &gt;&gt;&gt; root &lt;MyLogger root (WARNING)&gt; A root logger is not that different to any other logger, except that it must have a logging level. Provided you obeyed Liskov substitution principle when implementing MyLogger, this should work fine - any events that reach the root logger will be able to use MyLogger's customizations.
accepted answer of: http://stackoverflow.com/q/51938027
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51938027
upvote count: 10
type: Answer

http://stackoverflow.com/comment/90596696
score: 0
has text: In the end-state, I want this workflow to track finished runs of notebooks, export the whole notebook (including the outputs) to a html/pdf file, and save it in a remote directory, in order to keep track of running experiments.If I write a workflow that runs outside of the notebook, will it be possible to determine which notebook has finished it's run?
comment on: http://stackoverflow.com/q/51820891
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51827724
has comment: http://stackoverflow.com/comment/90613926
has body: Since i increases exponentially, you will be inserting floor(log3(L)) elements into heap. Assuming that an insertion is O(log(n)), where n is the number of elements already in the heap (not the array L), doing m insertions to an initially empty heap will have complexity O(log 1 + log 2 + log 3 + ... log (m - 1)) = O(log([m - 1]!) = O(log(m!)). According to Stirling's Approximation, ln(n!) = n ln n - n + O(ln n). Substituting in the number of insertions, and ignoring the overshadowed O(n) terms, we have: T(L) = O(log([floor(log3(L))]!)) = O([floor(log3(L))][log(floor(log3(L)))]) // apply Stirling = O([log3(L)][log(log3(L))]) // a number rounded down only differs from its value by less than 1 = O(log L * log log L) // base of log only contributes to a constant
type: Answer
has comment: http://stackoverflow.com/comment/90616193
score: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51827510
answers question: http://stackoverflow.com/q/51827510
upvote count: 2
type: AcceptedAnswer

yahoo
type: Tag
tags question: http://stackoverflow.com/q/51833491
tag name: yahoo

http://stackoverflow.com/comment/116609542
comment on: http://stackoverflow.com/q/51939257
has text: Are there any news about this question? I can implement one of the solutions suggested by [hoefling](https://stackoverflow.com/users/2650249/hoefling) and i welcome those one, but it would be still nicer to obtain a clean futureproof solution which does not depend on internal API.
type: Comment
type: QuestionComment
score: 0

ibm-cloud-functions
tag name: ibm-cloud-functions
type: Tag
tags question: http://stackoverflow.com/q/51901638

http://stackoverflow.com/comment/90609419
type: Comment
has text: I don't understand. That's what my answer below shows.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51815361

http://stackoverflow.com/comment/90651427
type: Comment
type: QuestionComment
has text: Can you post the problem code? Also have you considered using a dictionary instead to namespace your variables?
comment on: http://stackoverflow.com/q/51849056
score: 0

http://stackoverflow.com/comment/90883974
type: AnswerComment
type: Comment
has text: @tigerninjaman, nice to hear! Since you are going for this solution, beware that the call to `swriter.exe` (and I guess `soffice.exe` too) is not blocking - the application completes from the DOS window *before* an output file is produced. It continues running in the background until the conversion is complete. Also, if the HTML is finicky to parse, it might be worthwhile looking into all the other output formats LibreOffice can produce, such as doc**x**, RTF, Abiword format and DocBook https://en.wikipedia.org/wiki/DocBook For HTML parsing: https://www.crummy.com/software/BeautifulSoup/
comment on: http://stackoverflow.com/a/51948145
score: 0

http://stackoverflow.com/comment/90643292
comment on: http://stackoverflow.com/q/51844897
score: 0
type: Comment
type: QuestionComment
has text: What were you expecting instead?

http://stackoverflow.com/q/51908825
accepted answer: http://stackoverflow.com/a/51910847
has comment: http://stackoverflow.com/comment/90767987
tagged with: python
has comment: http://stackoverflow.com/comment/90768371
tagged with: tkinter
downvote count: 0
has title: Python Text widget only opening in a window
has body: I have got this code to put a text widget in my code however when I run the entire code it only opens the text widget in a new window instead of adding it to the existing gui. I'm quite new so do I need to add a command or something to specify it to go into the existing window? import tkinter as tk import time import random from tkinter import * root = tk.Tk() root.geometry("1600x8000") root.title("Cafe au Lait") tops = tk.Frame(root, width=1600, relief="sunken") tops.pack(side="top") f1 = tk.Frame(root, width=800, height=700, relief="sunken") f1.pack(side="left") roots = Tk() t = Text(roots) t.grid(row=6, column=6) roots.grid_rowconfigure(6, weight=1) roots.grid_columnconfigure(6, weight=1) tk.Label(f1, font=('arial', 16, 'bold'),text="Takeaway",bd=16,anchor="w").grid(row=2, column=2) txt_takeaway=tk.Entry(f1, font=('arial',16,'bold'),textvariable=takeaway,bd=10,insertwidth=4,bg="powder blue",justify='right') txt_takeaway.grid(row=2,column=3) root.bind("&lt;Return&gt;", ref) root.mainloop() I have got that existing gui with the root = tk part added to it but its making a new window.
type: AnsweredQuestion
score: 1
type: Question
has comment: http://stackoverflow.com/comment/90767849
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/90769202
favorite count: 0
has comment: http://stackoverflow.com/comment/90768346
has answer: http://stackoverflow.com/a/51910847

http://stackoverflow.com/comment/90660107
has text: You are comparing user.status with a variable named `offline`, which of course does not exist
comment on: http://stackoverflow.com/q/51853854
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/q/51878772
tagged with: pyside2
tagged with: python
tagged with: qt
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90713377
has title: Unable to get Maya's workspaceControl window geometry in closeEvent
type: Question
has comment: http://stackoverflow.com/comment/90714370
has answer: http://stackoverflow.com/a/51890874
has comment: http://stackoverflow.com/comment/90710596
accepted answer: http://stackoverflow.com/a/51890874
has comment: http://stackoverflow.com/comment/90712873
has comment: http://stackoverflow.com/comment/90719196
has comment: http://stackoverflow.com/comment/90713174
score: 0
has body: I've been using an adaptation of the this wrapper in Maya, so that I can parent a Qt window to workspaceControl, which makes it dockable with different parts of the user interface. Basically it creates an empty dockable window using Maya's own code, gets the C++ pointer to it, and wraps the Qt window inside of that window. The version linked does not handle closeEvents correctly, so I adapted it so it'll always trigger upon closing down. I did this by setting Qt.WA_DeleteOnClose as an attribute on the Qt window and linking the destroyed signal to close(). However, I found that the functions like geometry, width, move, etc, don't work properly as the window is in multiple levels of parents. In fact, to get any of those values, you need to call self.parent().parent().parent().parent().parent().func(). The issue arises when the window is closed, as it seems to delete the higher level parents before closeEvent is called, resulting in an error since self.parent().parent() returns None after that. I would like to be able to save the window position on exit, but can't figure out how to get access to the information before it's deleted. Other than just recording it each time any function is run, is there a way I could cleanly do it at the end? Here's the most trimmed down example I could come up with: from PySide2 import QtWidgets, QtCore from shiboken2 import wrapInstance import maya.OpenMayaUI as omUI import pymel.core as pm def dockable_window(window_class): main_control = pm.workspaceControl(window_class.ID) win_ptr = omUI.MQtUtil.findControl(window_class.ID) control_wrap = wrapInstance(int(win_ptr), QtWidgets.QWidget) control_wrap.setAttribute(QtCore.Qt.WA_DeleteOnClose) win = window_class(control_wrap) control_wrap.destroyed.connect(win.close) class MyWindow(QtWidgets.QMainWindow): ID = 'testing' def __init__(self, parent, *args, **kwargs): QtWidgets.QMainWindow.__init__(self, parent) #Create a button that will show the geometry when clicked b = QtWidgets.QPushButton(…
answer count: 1
tagged with: maya
has comment: http://stackoverflow.com/comment/90711319

http://stackoverflow.com/a/51892203
type: Answer
downvote count: 0
has body: Figured it out by searching for python_files in the repo, then found a buried example. This works: python_files = test_*.py *_test.py testing/*/*.py example_*.py You just add spaces between all the patten matches you want. Not sure this is documented. I've put an issue here to see if it's worth expanding on.
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/51890981

http://stackoverflow.com/comment/90568017
type: Comment
comment on: http://stackoverflow.com/a/51803896
has text: Ok sorry, see my updated answer. Also have you tried to plot the 3-channel image using a colormap to see if it makes sense?
type: AnswerComment
score: 0

http://stackoverflow.com/q/51852997
tagged with: logging
type: Question
has answer: http://stackoverflow.com/a/51854591
has comment: http://stackoverflow.com/comment/90658806
has comment: http://stackoverflow.com/comment/90658966
has comment: http://stackoverflow.com/comment/90659047
upvote count: 2
answer count: 2
has answer: http://stackoverflow.com/a/51853439
tagged with: flask
favorite count: 0
has body: I have the following directory structure in Flask and I am trying to add logging to this system. My APIs are defined in main.py and backend.py provides some backend logic to the APIs. ├── README.md ├── __init__.py ├── main.py ├── module │ ├── __init__.py │ └── backend.py My APIs are defined in main.py and logging related components in the file are as below: from logging.config import dictConfig import logging from module import backend log_level = "DEBUG" LOGFILENAME = "flask.log" dictConfig({ 'version': 1, 'formatters': {'default': { 'format': '[%(asctime)s] {%(pathname)s:%(funcName)s:%(lineno)d} %(levelname)s - %(message)s', }}, 'handlers': {'default': { 'level': 'DEBUG', 'formatter': 'default', 'class': 'logging.handlers.RotatingFileHandler', 'filename': LOGFILENAME, 'maxBytes': 5000000, 'backupCount': 10 }}, 'root': { 'level': log_level, 'handlers': ['default'] } }) app = Flask(__name__) logger = logging.getLogger(__name__) @app.route('/') def hello(): logger.debug("DEBUG: Inside the home function") logger.info("INFO: Inside the home function") backend.test() return "Welcome" Logging works as expected in main.py. Depending on the log_level, logs get written to LOGFILENAME. Problems occur when I try to enable logging via the below steps inside of backend.py. import logging logger = logging.getLogger(__name__) def test(): logger.info("info test") logger.debug("debug test") I do not see any logs from backend.py getting written to flask.log. I sense I am missing something but do not understand what. Any help appreciated.
has title: Flask logging across multiple modules
tagged with: python
score: 2
has comment: http://stackoverflow.com/comment/90658756
downvote count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/51813194
score: 0
has title: Python Opencv Image Stitching Creates Empty file
upvote count: 1
answer count: 1
downvote count: 1
favorite count: 0
has body: I am using Python 3 and when running this code i end up with an empty file named "result.jpg". Would appreciate any help, thanks; import cv2 stitcher = cv2.createStitcher(True) foo = cv2.imread("one.jpg") bar = cv2.imread("two.jpg") result = stitcher.stitch((foo,bar)) cv2.imwrite("result.jpg", result[1]) I have no errors showing, just the empty file output. Is there an error if the function fails to stitch the images together?
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52912519
has comment: http://stackoverflow.com/comment/90624385
type: Question
tagged with: opencv
tagged with: image

http://stackoverflow.com/comment/90945253
type: Comment
comment on: http://stackoverflow.com/a/51920263
score: 0
type: AnswerComment
has text: COM addin - sure. You can use the Word Editor API to highlight the text.

http://stackoverflow.com/q/51904941
tagged with: python
tagged with: dictionary
has title: Associating multiple values to a single key in python
has comment: http://stackoverflow.com/comment/90760595
score: -4
has body: So I am making a program, a part of which should have the following output. dic_friends={'Ron' :['soccer' , 'tennis' ], 'Scott' :['swimming' , skiing',' tennis' ], 'Amanda' :[' cricket' , 'badminton' , 'hockey' ]} places_dic={ 'New York' : [ 'Pool' ,' tennis' ], 'Florida' : ['swimming', 'hockey' , 'soccer' ] : 'Washington' :[ 'Cricket' , 'pool', 'soccer' , 'tennis' ,' badminton' ]} Basically, I want to assign multiple values (in form of a list) to a key, in python. And I am unable to do that. I want the help with the syntax. So can you please provide me with the correct syntax to get the above mentioned output? EDIT Thanks to all for ur help. But I guess my question is not clear enough. The above mentioned format should be the output of the program. I need the syntax/code of how I can take the input from the user &amp; the syntax to how I can display the out in the above format PLEASE HELP!! IN THE HOPE OF AN EARLY AND POSITIVE RESPONSE FROM YOUR SIDE.
type: Question
answer count: 2
downvote count: 4
upvote count: 0
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/90760677
has answer: http://stackoverflow.com/a/51904982
has comment: http://stackoverflow.com/comment/90760588
favorite count: 0
has answer: http://stackoverflow.com/a/51905103
type: UnansweredQuestion

http://stackoverflow.com/q/51944834
tagged with: bisection
downvote count: 1
type: Question
tagged with: numpy
tagged with: arrays
score: -1
has answer: http://stackoverflow.com/a/51945316
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/90839364
favorite count: 0
type: UnansweredQuestion
tagged with: python
has title: Bisection_method in array - numpy
has body: I have an equation where my unknown is h and TR which is an array (2D). I would like to solve the equation below by bisect method and as a result get a new array(2D), which will represent my h Tpow,k,t - constant h = np.empty_like(TR) def f(h): return (-TR+(Tpow-T1)*(1-exp((h**2*alfa*t)/k**2)*(1.0-erf(h*sqrt(alfa*t)/k)))) for i in range(len(TR)): for j in range(len(TR[0])): h[i][j] = scipy.optimize.bisect(f,0,600)

http://stackoverflow.com/comment/90933724
type: QuestionComment
has text: I meant this https://stackoverflow.com/questions/4599980/python-close-file-descriptor-question
comment on: http://stackoverflow.com/q/51938963
score: 0
type: Comment

http://stackoverflow.com/q/51941664
has answer: http://stackoverflow.com/a/51942119
type: AnsweredQuestion
has body: I am trying to gather a list from a .txt file, tally the results and then print them out like this Bones found: Ankylosaurus: 3 Pachycephalosaurus: 1 Tyrannosaurus Rex: 1 Struthiomimus: 2 An eample of the dot text file is Ankylosaurus Pachycephalosaurus Ankylosaurus Tyrannosaurus Rex Ankylosaurus Struthiomimus Struthiomimus My current code pulls all the names from the .txt file, except im completely stuck from there frequency = {} for line in open('bones.txt'): bones = line.split() print(bones) Any help please?
has title: read from a text file, tally the results and print them out (python)
type: Question
has answer: http://stackoverflow.com/a/51941678
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/51942174
accepted answer: http://stackoverflow.com/a/51942174
possible better answer: http://stackoverflow.com/a/51941678
tagged with: python

http://stackoverflow.com/q/51828671
answer count: 1
has comment: http://stackoverflow.com/comment/111858852
has title: Python inspect.getmembers does not return all members?
has comment: http://stackoverflow.com/comment/111839470
tagged with: python
has answer: http://stackoverflow.com/a/51828857
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/111792633
tagged with: torch
type: Question
has comment: http://stackoverflow.com/comment/90612017
has comment: http://stackoverflow.com/comment/111883925
has body: Is this a bug in inspect.getmembers, or is this the expected behavior? torch.bmm in inspect.getmembers(torch) False
accepted answer: http://stackoverflow.com/a/51828857
has comment: http://stackoverflow.com/comment/111898469
score: 0

http://stackoverflow.com/q/51846458
answer count: 0
type: UnansweredQuestion
has title: Groupby function in Python not summing correctly
type: Question
linked to: http://stackoverflow.com/q/25952790
has comment: http://stackoverflow.com/comment/90646280
has comment: http://stackoverflow.com/comment/90646244
has body: I'm working in python, and have a dataframe(EAD), which includes the column 'CLIENT'. There is also another column called NPV, which is made up of numbers. CLIENT NPV 0 1 50 1 1 90 2 2 130 3 2 -11 4 2 57 5 3 105 ... ... My goal is to group by CLIENT and then sum the NPV's of a client together. My expected result would be like so: CLIENT NPV 0 1 140 1 2 176 2 3 105 ... I did this by using a groupby function, like so: EAD_CLIENT = EAD.groupby('COUNTERPARTYNAME')['NPV'].sum().reset_index() However, when I did so, I got strange output NPV's that weren't correct math. Output: CLIENT NPV 0 1 140 1 2 27 2 3 -150 ... Now this is an example, and a tiny portion of my data, but it should illustrate my point. It's clear that for some reason the NPV's are simply not summing correctly. I next tried this: EAD['SUM(NPV)'] = EAD.groupby('COUNTERPARTYNAME')['NPV'].transform('sum') But that gave me the same result. I thought perhaps 'NPV' was still a string, so I tried several ways of turning it into an integer. I added a line above EAD['SUM(NPV)'] that said: EAD['NPV']=int(EAD['NPV'] but it claimed that TypeError: cannot convert the series to I also tried: EAD['NPV']=EAD['NPV'].astype(int). That didnt work either however, and I'm really struggling to understand what I'm doing wrong. TLDR; I can't figure out how to get Python to do the math right.
score: 0
tagged with: pandas
tagged with: python
duplicate of: http://stackoverflow.com/q/25952790
has comment: http://stackoverflow.com/comment/90646277

http://stackoverflow.com/comment/90657559
score: 0
has text: Downvote is hardly necessary, I can edit my response.
type: AnswerComment
comment on: http://stackoverflow.com/a/51850086
type: Comment

http://stackoverflow.com/a/51863635
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51862164
has body: I found my ans of my question. Here Is my code:- import glob a=open('content.txt','w') filesname=glob.glob('*.txt') for line in filesname: with open(line) as con: for l in con: l=l.strip() if l!="": print l a.write(a+'\n') a.close()

http://stackoverflow.com/a/51799142
upvote count: 1
has comment: http://stackoverflow.com/comment/90555954
has comment: http://stackoverflow.com/comment/90555947
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/90555916
has comment: http://stackoverflow.com/comment/90555951
score: 1
has body: Before being able to use pivot, group by or aggregate functions to get your summary statistics, be sure that your dataframe is in a tidy format: basically 1 observation/row, 1 variable/column, 1 value/cell. In your case, you have list elements (several values) in your "resumo" column. You need to change that. I would use the same solution as given by this post to "distribute" those list elements over rows: df_serie = df_selecao_atual.apply(lambda x: pd.Series(x['resumo']),axis=1).stack().reset_index(level=1, drop=True) df_serie.name = 'resumo' df_selecao_atual.drop('resumo', axis=1).join(df_serie)
answers question: http://stackoverflow.com/q/51798913
has comment: http://stackoverflow.com/comment/90555970

http://stackoverflow.com/a/51922056
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51921977
type: Answer
upvote count: 1
score: 1
has body: The trick lies in the descriptor protocol here: If an instance’s dictionary has an entry with the same name as a data descriptor, the data descriptor takes precedence. If an instance’s dictionary has an entry with the same name as a non-data descriptor, the dictionary entry takes precedence. @property def fullname(self): return '{} {}'.format(self._fname, self._lname) This is a data descriptor, because the property object returned by the decorator always defines __set__, even if you don't define the setter (then __set__ will raise an AttributeError, see code here). &gt;&gt;&gt; MyClass.fullname &lt;property object at 0x7f30e3917958&gt; &gt;&gt;&gt; MyClass.fullname.__set__ &lt;method-wrapper '__set__' of property object at 0x7f30e3917958&gt; Thus, the data descriptor takes precedence. Since the other examples already behave like you expect, this should be enough to complete your understanding.
answers question: http://stackoverflow.com/q/51921977

http://stackoverflow.com/q/51924767
tagged with: python
tagged with: rfc822
answer count: 0
downvote count: 0
type: Question
score: 3
upvote count: 3
has title: Python email library - Parsing message/rfc822 attachments
has body: I'm using python 2.7 and trying to parse emails that are being forwarded as an attachment to an inbox. I can't seem to parse the headers/email of the attached message. I see it as 'message/rfc822' but when i try to parse it, it shows empty. I pull the messages via a generator and it works fine, as below: res, data = self.imap_client.fetch(msg_id, '(RFC822)') msg = email.message_from_string(data[0][1]) yield msg This msg is then pushed into another function where i pull the attachments (via walk()) attachments = [] for part in msg.walk(): content_disposition = part.get('Content-Disposition', None) if content_disposition: attachments.append(Attachment(part, email_date)) return attachments The Attachment class is as follows: class Attachment(object): def __init__(self, attachment, email_date=None): self.content_type = attachment.get_content_type() self.attachment = attachment fname = None if self.content_type.startswith('message/'): self.data = attachment.as_string() fname = 'mail.eml' else: self.data = attachment.get_payload(decode=True) try: self.size = len(self.data) except TypeError: self.size = 0 if self.attachment.get_filename(): fname = self.attachment.get_filename().strip().replace(' ', '-') self.name = re.sub(r'(?u)[^-\w.]', '', fname) self.date = email_date I have tried to pull the attachment using get_payload and passing it (as above) using just as_string(), but to no avail. When I try to parse the email attachment, it don't get any data: if attachment.content_type == "message/rfc822": msg = email.message_from_string(attachment.data) print msg.get('Subject', None)
tagged with: email
tagged with: eml
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/51881526
tagged with: cron
linked to: http://stackoverflow.com/q/36720607
tagged with: python
score: 1
tagged with: scheduled-tasks
has body: I want to repeat a function very 2 minutes on a list and move every time one element further of the list. I use the 'schedule' to do the task. The script is the following: if __name__ == '__main__': machines_queue=[[...],[...],...] # list of the sublists global counter counter= 0 def job(sub_list): somefunction(sub_list) # here I want each 2 min iteration a sublist from machine_queue further counter= counter +1 # here is pop the Error on the counter print("I'm working...") schedule.every(1).minutes.do(job,sub_list= machines_queue[counter]) print(counter) while True : schedule.run_pending()` The first time it goes well , them I get an on the counter this Error: "UnboundLocalError: local variable 'counter' referenced before assignment." I don't understand because I set before the variable as global so I don't get the scope issue. If you have an idea please .... :) Thank you in advance for your help
upvote count: 1
has answer: http://stackoverflow.com/a/51930374
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51881583
has answer: http://stackoverflow.com/a/51881583
type: Question
answer count: 2
accepted answer: http://stackoverflow.com/a/51930374
downvote count: 0
favorite count: 0
tagged with: scope
has comment: http://stackoverflow.com/comment/90714618
has title: Python Cron Job with Schedule not working

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

http://stackoverflow.com/comment/90617034
comment on: http://stackoverflow.com/a/51818443
score: 0
type: Comment
has text: I am using Windows system. I tried the windows equivalent of this command but no luck. Tried setting http_proxy, https_proxy variables but did not help. I keep getting connection reset 10054 error.
type: AnswerComment

http://stackoverflow.com/q/51819367
has answer: http://stackoverflow.com/a/51819464
upvote count: 1
answer count: 1
has body: I have this data frame df delta_clean delta_time new_index 2017-05-24 11:59:29 -2.837001e-01 1.472778 0 2017-05-24 13:02:18 -2.546754e-02 1.046944 0 2017-05-24 14:05:06 -1.039444e-01 1.046667 0 2017-05-24 15:29:12 5.573439e+00 1.401667 0 2017-05-24 16:32:02 -1.567387e-01 1.047222 0 2017-05-24 17:34:52 -8.079458e-02 1.047222 0 2017-05-24 18:37:41 -5.220998e-02 1.046944 0 2017-05-24 19:40:31 -2.302334e-02 1.047222 0 2017-05-24 20:43:20 -4.382400e-02 1.046944 0 2017-05-24 21:46:10 -1.675438e-02 1.047222 0 2017-05-24 22:49:01 -5.994632e-02 1.047500 0 2017-05-24 23:51:53 -4.845164e-02 1.047778 0 2017-05-24 23:59:59 -2.226252e-02 0.135000 0 2017-05-25 00:00:01 -9.161529e-05 0.000556 0 2017-05-25 00:54:45 -1.504323e-01 0.912222 0 2017-05-25 01:57:38 -5.539247e-02 1.048056 0 2017-05-25 06:34:57 -2.389934e-01 4.621944 0 2017-05-25 07:37:48 1.037526e-01 1.047500 0 2017-05-25 08:40:38 -2.081650e-01 1.047222 0 2017-05-25 09:43:27 -5.335963e-02 1.046944 0 2017-05-25 10:46:16 -8.687169e-02 1.046944 0 2017-05-25 11:49:05 -2.209528e-01 1.046944 0 2017-05-25 12:51:54 -4.416145e-02 1.046944 0 2017-05-25 13:54:43 -3.051953e-02 1.046944 0 2017-05-25 14:57:31 -4.792480e-02 1.046667 0 2017-05-25 16:00:20 -1.288275e-02 1.046944 0 2017-05-25 17:03:09 3.362946e-02 1.046944 0 2017-05-25 18:05:59 -6.533723e-02 1.047222 0 2017-05-25 19:08:49 -6.509860e-02 1.047222 0 I need that every time I find this condition df['delta_clean']/df['delta_time']&gt;2, to increment the value of new index how can I proceed?
tagged with: dataframe
has title: how to increment a dataframe column under a condition in python?
accepted answer: http://stackoverflow.com/a/51819464
tagged with: pandas
type: AnsweredQuestion
downvote count: 0
score: 1
favorite count: 0
type: Question
tagged with: python

http://stackoverflow.com/q/51800831
tagged with: python-decorators
favorite count: 0
downvote count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51800897
score: 2
type: Question
upvote count: 2
answer count: 1
has title: How to use decorators on a function of a Base Class and have the decorator work on that function when the Base Class is inherited
tagged with: inheritance
tagged with: class
tagged with: python
has body: I have a base class Example with an abstract method example. I want to add another decorator on the example function, which I have done below - the decorator is @foo. When I use this base Example class to create new classes where I create an appropriate example function, what @foo should do, doesn't end up working. I believe the issue is that it is being 'overridden' when I create the example function on a new class. from abc import ABCMeta, abstractmethod class Example(object): __metaclass__ = ABCMeta def __init__(self): self.num = 0 @abstractmethod @foo def example(self, output): pass class ExampleSum(Example): def example(self, output): self.num = self.num + output Any guidance? Basically I would like @foo behavior to be in the example function of ExampleSum without explicitly coding it.

http://stackoverflow.com/comment/90620645
type: AnswerComment
has text: This should be the accepted answer. It is uses the resources Django gives you with querysets.
comment on: http://stackoverflow.com/a/51832144
type: Comment
score: 0

http://stackoverflow.com/a/51880117
has comment: http://stackoverflow.com/comment/90719646
score: 1
has comment: http://stackoverflow.com/comment/90712082
has comment: http://stackoverflow.com/comment/90732826
has comment: http://stackoverflow.com/comment/90717693
answers question: http://stackoverflow.com/q/51879319
has body: This Stackoverflow post contains good information about argument passing in Python: How do I pass a variable by reference? The following two lines in your reverse_list function are the problem: head.val = prev.val head.next = prev.next Here's what I think is happening: # Marker 1 head.val = prev.val head.next = prev.next # Marker 2 At Marker 1, the list looks like this: None &lt;--- 1 &lt;--- 2 &lt;--- 3 &lt;--- 4 ^ ^ | | head prev At Marker 2, the list looks like this: ---------------------- | | | | | v --- 4 &lt;--- 2 &lt;--- 3 &lt;--- 4 ^ ^ | | head prev Thus, at the end of reverse_list, head still points to the first node, but it has value 4. And head.next points to node that contains 3, so you get the loop as shown in diagram. My suggestion is that you return a reference to first node of the reversed list. The modified reversed_list would look as follows: def reverse_list(head): if not head or not head.next: return current = head prev = None while current: static_next = current.next current.next = prev prev = current current = static_next return prev And your test can be modified to: class TestSuite(unittest.TestCase): def test_reverse_list(self): head = create_list([1, 2, 3, 4]) rev = reverse_list(head) self.assertFalse(is_list_cyclic(rev)) self.assertEqual([4, 3, 2, 1], convert_list(rev)) Edit @mattalxndr, on reading your comments, the main question seems to be how to reverse the list "in place" without returning a value. The simplest solution I can think of is: make of the copy of the list (save into copied_list) reverse copied_list start traversing original list of left to right start traversing copied_list from right to left copy val from copied_list to original list This technique makes another copy of the list, so uses O(n) space. Better algorithms may exist, but I am not able to think of any at this time.
has comment: http://stackoverflow.com/comment/90718410
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51879319
has comment: http://stackoverflow.com/comment/90732663
has comment: http://stackoverflow.com/comment/90711955
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90712566
has comment: http://stackoverflow.com/comment/90717778
type: Answer
has comment: http://stackoverflow.com/comment/90713127
has comment: http://stackoverflow.com/comment/90755256

http://stackoverflow.com/comment/90833703
comment on: http://stackoverflow.com/q/51942005
type: Comment
type: QuestionComment
score: 1
has text: Meanwhile, is there a reason you can't just `f.write(os.stat.__doc__)` instead of trying to capture it from stdout? IIRC, the only thing `help` adds is the signature on top, and you can always write that first, then write the docstring, if you really need that.

http://stackoverflow.com/q/51802974
accepted answer: http://stackoverflow.com/a/51804648
possible better answer: http://stackoverflow.com/a/51803106
has answer: http://stackoverflow.com/a/51803317
has body: Let's say we have a dict that will always have keys first_name and last_name but they may be equal to None. { 'first_name': None, 'last_name': 'Bloggs' } We want to save the first name if it is passed in or save it as an empty string if None is passed in. first_name = account['first_name'] if account['first_name'] else "" vs first_name = account['first_name'] or "" Both of these work, however, what is the difference behind the scenes? Is one more efficient than the other?
type: Question
has title: if-else vs "or" operation for None-check
answer count: 6
has answer: http://stackoverflow.com/a/51803106
downvote count: 1
favorite count: 0
upvote count: 20
has answer: http://stackoverflow.com/a/51803275
has answer: http://stackoverflow.com/a/51803103
has answer: http://stackoverflow.com/a/51803069
tagged with: python
score: 19
has comment: http://stackoverflow.com/comment/90597751
has answer: http://stackoverflow.com/a/51804648
type: AnsweredQuestion

http://stackoverflow.com/a/51839989
accepted answer of: http://stackoverflow.com/q/51839412
has comment: http://stackoverflow.com/comment/90633151
has body: From what I understand you want an Image where you are allowed to handle the on_press event, for it the Behaviors as I show below: from kivy.app import App from kivy.uix.behaviors import ButtonBehavior from kivy.uix.image import Image class ImageButton(ButtonBehavior, Image): pass class MyApp(App): def build(self): return ImageButton(source="kivy.png", on_press=lambda *args: print("press")) if __name__ == "__main__": MyApp().run()
answers question: http://stackoverflow.com/q/51839412
has comment: http://stackoverflow.com/comment/90633244
type: Answer
upvote count: 3
score: 3
has comment: http://stackoverflow.com/comment/90633249
has comment: http://stackoverflow.com/comment/90633177
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/51914198
linked to: http://stackoverflow.com/q/23286254
downvote count: 1
type: Question
duplicate of: http://stackoverflow.com/q/23286254
has body: I have a list E = [1,2,3,4,5,6,7,8] and I will like to convert it into E = [{1,2}, {3,4}, {5,6}, {7,8}] in the least computationally expensive manner. In particular, I will like to extend this to large instances of E. Is there an efficient way to do this in Python (3.5 &amp; later)? Remark: E will always be given as an even-sized list, as I am working on graphs related topics
answer count: 3
possible better answer: http://stackoverflow.com/a/51914262
has answer: http://stackoverflow.com/a/51914262
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90778467
has title: (Python) How can I convert a list of integers into a list of sets where each set is a pair of these integers?
has answer: http://stackoverflow.com/a/51914214
tagged with: python
has comment: http://stackoverflow.com/comment/90778483
type: AnsweredQuestion
score: 2
has answer: http://stackoverflow.com/a/51914234
tagged with: list
accepted answer: http://stackoverflow.com/a/51914214
upvote count: 3
tagged with: set

http://stackoverflow.com/a/51861144
has body: Using the answer referenced in the comment, one can do: wsize = n_roll cols = df.shape[1] out = group.stack(dropna=False).rolling(window=wsize * cols, min_periods=1).mean().reset_index(-1, drop=True).sort_index() out.groupby(out.index).last() out.iloc[:nroll-1] = np.nan In my case it was important to specify dropna=False in stack, otherwise the length of the rolling window would not be correct. But I am looking forward to other approaches as this does not feel very elegant/efficient.
score: 0
answers question: http://stackoverflow.com/q/51860691
type: Answer

http://stackoverflow.com/comment/90561031
type: Comment
score: 0
comment on: http://stackoverflow.com/q/51801646
type: QuestionComment
has text: 1.3.0, not 1.13.0

http://stackoverflow.com/a/51865023
type: Answer
has comment: http://stackoverflow.com/comment/90685338
has comment: http://stackoverflow.com/comment/90684828
has comment: http://stackoverflow.com/comment/90685294
has comment: http://stackoverflow.com/comment/90684553
has comment: http://stackoverflow.com/comment/90684137
has comment: http://stackoverflow.com/comment/90684831
has comment: http://stackoverflow.com/comment/90685555
score: 0
has comment: http://stackoverflow.com/comment/90684948
has body: I believe pandas will make your job much easier. pip install pandas Here's an example on how to get multiple tables from a wikipedia html and input it into a Pandas DataFrame and save it to disk. import pandas as pd url = "https://en.wikipedia.org/wiki/List_of_American_films_of_2017" wikitables = pd.read_html(url, header=0, attrs={"class":"wikitable"}) for idx,df in enumerate(wikitables): df.to_csv('{}.csv'.format(idx),index=False) For your use case, something like this should work: import pathlib as path import pandas as pd def save_as_xlsx(read_directory): read_path = path.Path(read_directory) for html in read_path.glob('*.html'): save_path = read_path.joinpath(html.stem + '.xlsx') dfs_from_html = pd.read_html(html, header=0,) for idx, df in enumerate(dfs_from_html): df.to_excel('{}.xlsx'.format(idx),index=False) ** Make sure to set the correct html attribute in the pd.read_html function.
answers question: http://stackoverflow.com/q/51860448
has comment: http://stackoverflow.com/comment/90684110

http://stackoverflow.com/a/51876933
has comment: http://stackoverflow.com/comment/90705148
downvote count: 0
has body: Try this: from collections import defaultdict diction = defaultdict(list) with open("file.txt") as f: for line in f: key, _, *values = line.strip().split() diction[key].extend(values) print(diction) This is a solution for Python 3, because the statement a, *b = tuple1 is invalid in Python 2. Look at the solution of @cha0site if you are using Python 2.
type: Answer
has comment: http://stackoverflow.com/comment/90705016
score: 1
has comment: http://stackoverflow.com/comment/90705037
upvote count: 1
answers question: http://stackoverflow.com/q/51876794

http://stackoverflow.com/q/51903751
has body: I have the same code block in four of my functions. Is there a way that can avoid repeating the same code block? Here is the same code block: def function_name(): # ...some code... hot_news_48h = h_mostViewed(48, News, '-pv') hot_news_1w = w_mostViewed(1, News, '-pv') # ...some code... return render(request, "template_name.html", { # ...some code... 'hot_news_48h': hot_news_48h, 'hot_news_1w': hot_news_1w, # ...some code... }) Here is function1: def newsDetailView(request, news_pk): news = get_object_or_404(News, id=news_pk) tags = news.tag.annotate(news_count=Count('news')) News.objects.filter(id=news_pk).update(pv=F('pv') + 1) hot_news_48h = h_mostViewed(48, News, '-pv') hot_news_1w = w_mostViewed(1, News, '-pv') relative_news = News.objects.filter(tag__id__in=news.tag.all()).exclude(id=news_pk)[:6] return render(request, "news_detail.html", { 'news': news, 'tags': tags, 'hot_news_48h': hot_news_48h, 'hot_news_1w': hot_news_1w, 'relative_news': relative_news }) Here is function2: def tagNewsList(request, tag_pk): tag = get_object_or_404(Tag, pk=tag_pk) news_list = News.objects.filter(tag=tag) hot_news_48h = h_mostViewed(48, News, '-pv') hot_news_1w = w_mostViewed(1, News, '-pv') return render(request, "tags_list.html", { 'news_list': news_list, 'tag': tag, 'hot_news_48h': hot_news_48h, 'hot_news_1w': hot_news_1w, }) How can I avoid it?
has comment: http://stackoverflow.com/comment/90761334
has comment: http://stackoverflow.com/comment/90758548
type: Question
score: 0
has comment: http://stackoverflow.com/comment/90758588
has comment: http://stackoverflow.com/comment/90759694
type: UnansweredQuestion
tagged with: django
tagged with: python
tagged with: django-templates
has title: How can I avoid repeating same code block in Django?
linked to: http://stackoverflow.com/q/48020797
tagged with: django-views
answer count: 0

http://stackoverflow.com/comment/90620947
has text: @McGuile Edited mine
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51833440

http://stackoverflow.com/comment/90606048
type: Comment
type: QuestionComment
has text: No. What I meant is that I should assign new orders with, let's say, some method (like .addNextDate(5028) and a new column would appear like 2014-01-02 with TotalOrders of 5028. I'm wondering what is the simplest way to do that without having to create a full index, join the DataFrames and then add the values.
comment on: http://stackoverflow.com/q/51825793
score: 0

http://stackoverflow.com/comment/90695707
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51853451
has text: Thanks for the reply. But I am getting this error Exception: Java gateway process exited before sending its port number after execution of spark = SparkSession.builder.master("local[*]").getOrCreate()`
type: AnswerComment

http://stackoverflow.com/q/51885238
linked to: http://stackoverflow.com/q/51884017
tagged with: python
has answer: http://stackoverflow.com/a/51885284
has title: Unicode decode error when I wanted to read a text file
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90722060
type: Question
score: 0
answer count: 1
linked to: http://stackoverflow.com/q/5552555
accepted answer: http://stackoverflow.com/a/51885284
has body: I have a file that hungarian and I want to modify it by code, but there is problem with it. Here is my simple code: f = open('nametext','r') text=f.read() print(text) f.close() the nametext file contains the following strings: Bevallás iparűzési adófeltöltési kötelezettségről 2013 Gépjárműadó-kedvezmény mentesség bevallás 2013 Helyi iparűzési adóbevallás 2013 Idegenforgalmi adóbevallás 2013 Kommunális adóbevallás 2013 Talajterhelési díj bevallás 2013 And I have got an error message, what is the following: Traceback (most recent call last): File "python", line 2, in &lt;module&gt; UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe1 in position 6: invalid continuation byte The position 6 is the 7th character int the text what is an hungarian letter: ű How to compile it? I have compiled the file at repl.it. I have almost the same problem with Ruby. There is a problem with text coding, but I still have not solution.

http://stackoverflow.com/comment/90787754
score: 1
type: Comment
has text: @Aarushi you may wish to use `pd.to_numeric(df['column_name'], errors='coerce')` and then either `.dropna()` to get rid of invalid values or use `.fillna(0)` to introduce a value that'll count towards the number of items in a group but not it's sum...
comment on: http://stackoverflow.com/a/51918191
type: AnswerComment

http://stackoverflow.com/a/51823093
has comment: http://stackoverflow.com/comment/90600309
type: Answer
has comment: http://stackoverflow.com/comment/139527554
has comment: http://stackoverflow.com/comment/90604718
has comment: http://stackoverflow.com/comment/90600841
upvote count: 17
answers question: http://stackoverflow.com/q/51822820
has body: I'm not aware a native way of adjusting the Entry's padding, but here's one way to get something like it. Make the entry's border invisible by giving it a FLAT style, and embed the entry in a Frame that acts as the entry's border. Then you can specify the padding by adjusting the entry's borderwidth. Example: import tkinter as tk root = tk.Tk() frame = tk.Frame(root, borderwidth=5, relief=tk.SUNKEN) frame.pack() entry = tk.Entry(frame, borderwidth=15, relief=tk.FLAT) entry.pack() root.mainloop() Result:
score: 17
has comment: http://stackoverflow.com/comment/90600621
accepted answer of: http://stackoverflow.com/q/51822820
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/51927893
favorite count: 0
tagged with: python-3.x
duplicate of: http://stackoverflow.com/q/25445439
tagged with: python
has answer: http://stackoverflow.com/a/51927924
has answer: http://stackoverflow.com/a/51927926
has body: So I started learning python 3 and I wanted to run a very simple code on ubuntu: print type("Hello World") ^ SyntaxError: invalid syntax When I tried to compile that with command python3 hello.py in terminal it gave me the error above, but when used python hello.py (I think it means to use python 2 instead of 3) then it's all fine. Same when using python 3 and 2 shells in the terminal. It seems like I'm missing something really stupid because I did some research and found no one with the same issue.
type: UnansweredQuestion
has title: print type(x) SyntaxError: invalid syntax
type: Question
score: -1
linked to: http://stackoverflow.com/q/32122868
upvote count: 2
tagged with: syntax-error
answer count: 3
downvote count: 3
has answer: http://stackoverflow.com/a/51927942

http://stackoverflow.com/comment/90678480
has text: Good Q @zwer, I wouldn't want that to count. It would be some form of regex separating that word using spaces or punctuation. I would want to pass it a word and only have that word be matched.
score: 0
comment on: http://stackoverflow.com/q/51862922
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51884763
tagged with: numpy
linked to: http://stackoverflow.com/q/49412694
has answer: http://stackoverflow.com/a/51884821
has answer: http://stackoverflow.com/a/51884942
tagged with: dataframe
answer count: 3
tagged with: pandas
downvote count: 0
score: 1
has body: I have two data frames: df1: Produtos Jan Feb Mar Apr May Jun \ 0 100 15884.0 8194.0 41070.0 8294.0 17308.0 18146.0 1 10057 0.0 0.0 0.0 24900.0 0.0 0.0 2 10058 0.0 0.0 0.0 30900.0 0.0 0.0 3 10236 11638.0 8450.0 1690.0 3380.0 10140.0 1690.0 4 10267 0.0 0.0 0.0 11490.0 0.0 0.0 5 10273 18157.0 32434.0 4900.0 0.0 10588.0 15094.0 df2: Produtos Jan Feb Mar Apr May Jun Jul Aug 0 100 600.0 200.0 1100.0 300.0 500.0 1600.0 0.0 0.0 1 10057 0.0 0.0 0.0 100.0 0.0 0.0 0.0 0.0 2 10058 0.0 0.0 0.0 100.0 0.0 0.0 0.0 0.0 3 10236 700.0 500.0 100.0 200.0 600.0 100.0 200.0 100.0 4 10267 0.0 0.0 0.0 100.0 0.0 0.0 0.0 0.0 5 10273 400.0 700.0 100.0 0.0 200.0 300.0 300.0 300.0 I am trying to divide one dataframe by another, in order to create a new one. However, I don`t know how to make this division without considering the first column 'Produtos'. Doing this: v = df1.values / df2.values I get the first column divided as well.
favorite count: 0
possible better answer: http://stackoverflow.com/a/51884802
accepted answer: http://stackoverflow.com/a/51884942
has answer: http://stackoverflow.com/a/51884802
has title: Divide one dataframe by another disconsidering one column
upvote count: 1
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90721071
type: Question

http://stackoverflow.com/comment/90584203
type: AnswerComment
comment on: http://stackoverflow.com/a/51808661
type: Comment
has text: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/177918/discussion-between-priya-and-atline).
score: 0

http://stackoverflow.com/comment/90727692
comment on: http://stackoverflow.com/q/51888251
type: Comment
score: 0
type: QuestionComment
has text: See jordanm's answer, it is what I was looking for. I also added an edit for clarification

http://stackoverflow.com/q/51888101
has comment: http://stackoverflow.com/comment/90779703
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90785959
has comment: http://stackoverflow.com/comment/90727327
accepted answer: http://stackoverflow.com/a/52021740
type: Question
has comment: http://stackoverflow.com/comment/90785942
has body: I'm trying to create a 3D matrix that holds information in the format: """ The data below is in a text file Part#1 parameterA 10 10 20 10 10 30 10 30 10 20 30 parameterB 10 10 20 10 10 30 10 30 10 30 10 parameterC 10 20 10 10 30 10 20 10 30 10 20 parameterD 10 10 20 10 10 30 10 30 10 20 30 Part#2 parameterA 10 20 10 10 30 10 20 10 30 10 20 parameterB 10 20 10 30 10 20 10 20 10 20 10 parameterC 10 20 10 10 30 10 20 30 30 10 20 parameterD 10 10 20 20 20 30 10 10 20 20 30 Part#3 parameterA 10 20 10 30 10 20 10 20 10 20 10 parameterB 10 10 20 10 10 30 10 30 10 20 30 parameterC 10 20 10 30 10 10 10 20 10 20 10 parameterD 10 20 10 10 30 10 20 10 30 10 20 parameterE 10 20 10 10 10 10 30 30 30 10 20 """ The data should be separated like this (just showing the format of the indexes of the DS): matrix[index for parts][index for parameters][index for line of values] Being each part in brackets an index in some type of frame, so I can call them individually for instance: matrix[0][0] = 10 10 20 10 10 30 10 30 10 20 30 keeping in mind this format: matrix[part#1][parameter][10 10 20 10 10 30 10 30 10 20 30] The function below parses the file, but is not doing it correctly def parse_file_into_matrix(inputFilename): with open(inputFilename) as inputFile: content = inputFile.readlines() content = [x.strip() for x in content] lines =[] parts = [] parameterNames = [] parameterValues = [] # separates the runs from each line of elements and its values and adds it to a new list "lines" for i in range(len(content)): # Keeps the run numbers if true otherwise assign an element/values line into lines if re.match(r"Part #[0-3]+",content[i]): part = int(re.findall(r"Part #([0-3]+)",content[i])[0]) parts.append("Part #"+ str(runs)) else: lines.append(content[i]) # will contain everything categorized (parts/Parameter/Values) matrix_3D = np.arange(len(parts)) # separates the parameter name from its values and assigns each one to # a list of parameters and a list of values based on its order for j…
score: 0
tagged with: matrix
has title: How to fill a 3D Matrix with arrays of different dimensions?
answer count: 1
has comment: http://stackoverflow.com/comment/90786233
tagged with: multidimensional-array
has answer: http://stackoverflow.com/a/52021740
has comment: http://stackoverflow.com/comment/90779762
has comment: http://stackoverflow.com/comment/90780151

http://stackoverflow.com/comment/90598347
comment on: http://stackoverflow.com/q/51818413
score: 0
type: QuestionComment
has text: Yes but i kinda messed up .. and i gave this piece of code. I want for future to be something like for each new snapshot then copy.
type: Comment

http://stackoverflow.com/comment/90724062
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51885802
type: QuestionComment
has text: Was there no message after `psycopg2.OperationalError`? Because when I tried to connect with the wrong information (user, password, database) I got something like `psycopg2.OperationalError: FATAL: database "learning" does not exist`

http://stackoverflow.com/q/51869524
tagged with: heroku
score: 0
has comment: http://stackoverflow.com/comment/90692153
has title: i have deployed Django project in Heroku.where users can upload images shows up for some hours after some hours images gets dont showup in screen
tagged with: postgresql
has comment: http://stackoverflow.com/comment/90691211
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90691005
tagged with: django
tagged with: python
linked to: http://stackoverflow.com/q/17716055
answer count: 0
has body: i have deployed my project in Heroku.what happens is i have form where users can upload files(images) which is reflected back to pages after being uploaded problem is those uploaded images shows on page for some hours and then images gets dont showup in screen after some hours. but again wen some users fill up the form a upload the images ,it shows up in the screen but rest of the previously uploaded images dont show up .in this newly uploaded image also disappears after some hour . also every time i do git push heruko masters those images disappears. you can visit the site(http://productpanditapp.herokuapp.com/) settings.py # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.0/howto/static-files/ STATICFILES_DIRS = [ os.path.join(BASE_DIR,'producthunt/static/') ] STATIC_ROOT = os.path.join(BASE_DIR,'static') STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR,'media') MEDIA_URL = '/media/' models.py from django.db import models from django.contrib.auth.models import User class Product(models.Model): title = models.CharField(max_length=255) pub_date = models.DateTimeField() body = models.TextField() image = models.ImageField(upload_to='images/') icon = models.ImageField(upload_to='images/') url = models.TextField() votes_total = models.IntegerField(default=1) hunter = models.ForeignKey(User,on_delete=models.CASCADE) def __str__(self): return self.title def summary(self): return self.body[:100] def short_pub_date(self): return self.pub_date.strftime('%b %e %Y') views.py def home(request): products = Product.objects.all().order_by("-pub_date") query = request.GET.get("q") if query: products= products.filter(Q(title__icontains=query)| Q(body__icontains=query)| Q(hunter__username__icontains=query)).distinct() paginator = Paginator(products, 5) # Show 25 contacts per page page = request.GET.get('page') list = paginator.get_page(page) return render(request,'products/home.html',{'product':list}) home.html {% extends 'base.html' %} {% block…
type: Question

http://stackoverflow.com/a/51961422
has body: If you are in python, you need to initialize your spark session import os import sys spark_home = os.environ.get('SPARK_HOME', None) sys.path.insert(0, os.path.join(spark_home, 'python')) sys.path.insert(0, os.path.join(spark_home, 'python/lib/py4j-0.10.4-src.zip')) execfile(os.path.join(spark_home, 'python/pyspark/shell.py')) Above is my code, you may need to find the corresponding libraries in your spark installation and replace the paths above. If you lucky, you will see something like this Python 2.7.13 |Anaconda, Inc.| (default, Sep 22 2017, 00:47:24) [GCC 7.2.0] on linux2 Type "help", "copyright", "credits" or "license" for more information. Welcome to ____ __ / __/__ ___ _____/ /__ _\ \/ _ \/ _ `/ __/ '_/ /__ / .__/\_,_/_/ /_/\_\ version 2.2.1-mapr-1803 /_/ Using Python version 2.7.13 (default, Sep 22 2017 00:47:24) SparkSession available as 'spark'. &gt;&gt;&gt; from pyspark.conf import SparkConf &gt;&gt;&gt; SparkConf &lt;class 'pyspark.conf.SparkConf'&gt; &gt;&gt;&gt;
answers question: http://stackoverflow.com/q/51923086
score: 0
type: Answer

http://stackoverflow.com/q/51886499
answer count: 1
favorite count: 0
tagged with: python-3.x
tagged with: python
tagged with: dictionary
has title: Is there a way in python to loop multiple key value pairs in a dict in single iteration of a loop
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/51886764
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/90724738
has comment: http://stackoverflow.com/comment/90724813
tagged with: python-3.6
has body: I have the following example code and was interested if there was a way in Python to loop multiple key value pairs in a single loop iteration? If you see my example I have a dictionary with four key value pairs is there a way in python to loop this in a single pass? my_dict = {'key1':'value1', 'key2':'value2', 'key3':'value3', 'key4':'value4'} count = 1 for key, value in my_dict.items(): print('the count is {} the key is {} and the value is {}'.format(count, key, value)) count += 1 the count is 1 the key is key4 and the value is value4 the count is 2 the key is key3 and the value is value3 the count is 3 the key is key1 and the value is value1 the count is 4 the key is key2 and the value is value2 expected return data would look like this iteration count 1 - key1 value1, key2 value2, key3 value3, key4 value4
has comment: http://stackoverflow.com/comment/90724625
has comment: http://stackoverflow.com/comment/90724606
accepted answer: http://stackoverflow.com/a/51886764
downvote count: 0

http://stackoverflow.com/comment/90801827
type: AnswerComment
has text: Add some positive lookahead to the beginning of the regex. `^(?=.*\w\W+\w)` This ensures that there's at least one place where two word characters are separated by non-word characters.
type: Comment
comment on: http://stackoverflow.com/a/51914205
score: 0

http://stackoverflow.com/q/51931559
favorite count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: python
score: 2
tagged with: tensorflow
type: Question
has body: I want to build a data input pipeline to read bounding box information. Therefore I've got multiple .txt files which store information about x, y, width and height in each row, for example: 952 607 9 18 947 1176 14 12 937 228 17 22 895 1118 66 53 804 596 12 13 651 722 13 8 667 306 28 51 586 1148 20 32 231 280 33 31 859 629 102 172 806 486 155 111 487 506 55 69 263 476 372 339 4 589 114 106 273 724 164 192 4 4 350 292 All filenames are saved in a list filenames_bb = input_tools.get_required_filenames(args.dataset_dir, "train", params) I use tf.data.Dataset to build the input pipeline dataset = tf.data.Dataset.from_tensor_slices(filenames_bb) dataset = dataset.map(parse_fnc, params.num_parallel_calls) Now my question is how to implement the parse_fnc? What I want is a tensor of shape [batch_size, number_of_bounding_boxes, 4]. Currently the parse_fnc looks as follows: def parse_fnc(filenames): bb = tf.read_file(filenames) return bb It returns a tensor of shape=(?,) and dtype=string, but how can I convert it to a float tensor with required dimensions?
downvote count: 0
answer count: 1
has title: Tensorflow tf.data.Dataset convert string tensor to float tensor
has answer: http://stackoverflow.com/a/51935729

http://stackoverflow.com/q/51877032
answer count: 2
downvote count: 0
tagged with: exec
favorite count: 0
tagged with: http://stackoverflow.com/tag/zip
has body: I want to execute a python function that have 2 parameters in my TCL program. My python function for dezipping a file.zip is defined by this code: # -*- coding: utf8 -*- import zipfile import os.path import os def dezipFile(filezip, pathdst = ''): if pathdst == '': pathdst = os.getcwd() zfile = zipfile.ZipFile(filezip,'r') for i in zfile.namelist(): print (i) if os.path.isdir(i): try: os.makedirs(pathdst + os.sep + i) except: pass else: try: os.makedirs(pathdst + os.sep + os.path.dirname(i)) except: pass data = zfile.read(i) fp = open(pathdst + os.sep + i, "wb") fp.write(data) fp.close() zfile.close() Then, I want to execute this function in my TCL program. I have used exec. TCL script: puts "--outzip is: $outZip" puts "--destinationDeZip is: $destinationDeZip" set zip_status [ catch {exec python dezipFile.py ${outZip} ${destinationDeZip}} id ] if {$zip_status == 1} { puts "**** Error: $id *********" } else { puts "**** Pass: the zipped file $fileName is extracted *********" } In the result report, I have found the message **** Pass: the zipped file $fileName is extracted *********. The command seems to be passed, however the the zipped files are not extracted as expected. Is there any error in my program? Thks.
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51877368
score: 1
has title: Calling python script with parameters from tcl
upvote count: 1
has comment: http://stackoverflow.com/comment/90829056
has answer: http://stackoverflow.com/a/51939548
type: Question
possible better answer: http://stackoverflow.com/a/51939548
accepted answer: http://stackoverflow.com/a/51877368
tagged with: tcl

http://stackoverflow.com/a/71060884
answers question: http://stackoverflow.com/q/51853018
type: Answer
score: 2
has body: -&gt;pip install opencv-python you can use this. But if this code does not working then you can check python version on cmd and anaconda because they are different. So you type command in anaconda prompt and cmd, it will work. You can check this -&gt; pip list
downvote count: 1
upvote count: 3

http://stackoverflow.com/comment/90674018
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51860650
has text: yeah. I did interpret that OP wanted what elements at the same index were different, and that the length inequality meant they were unequal. Still think that is valid in some interpretation - but with such a poor question who knows.
type: Comment

encryption
tags question: http://stackoverflow.com/q/51939932
tags question: http://stackoverflow.com/q/51937382
tags question: http://stackoverflow.com/q/51801265
tag name: encryption
tags question: http://stackoverflow.com/q/51846150
tags question: http://stackoverflow.com/q/51943598
type: Tag
tags question: http://stackoverflow.com/q/51830450

coordinates
tags question: http://stackoverflow.com/q/51946256
tag name: coordinates
tags question: http://stackoverflow.com/q/51860245
tags question: http://stackoverflow.com/q/51933517
type: Tag
tags question: http://stackoverflow.com/q/51829403
tags question: http://stackoverflow.com/q/51859165
tags question: http://stackoverflow.com/q/51809746

http://stackoverflow.com/a/51916847
score: 2
has comment: http://stackoverflow.com/comment/90783527
has comment: http://stackoverflow.com/comment/90783743
has comment: http://stackoverflow.com/comment/90784044
has comment: http://stackoverflow.com/comment/90783528
has body: &gt; in python is not acting like &gt; in bash, to save content into a file you need to use the open() function. The following code does what you are trying to achieve: with open("manual.md", "w") as file: file.write(help(link_elem))
upvote count: 3
has comment: http://stackoverflow.com/comment/90788441
has comment: http://stackoverflow.com/comment/90783568
downvote count: 1
has comment: http://stackoverflow.com/comment/90783520
type: Answer
answers question: http://stackoverflow.com/q/51916797

http://stackoverflow.com/comment/90695408
comment on: http://stackoverflow.com/q/51845668
score: 0
type: QuestionComment
has text: For one you're cd is into a bat file, not a folder. that's probably it.
type: Comment

http://stackoverflow.com/a/51948838
has body: Don't try and install packages manually. You should create a requirements.txt file and commit it to git, then Heroku will automatically install the packages on deploy. The reason what you have done does not work is that heroku run bash - or any command - creates a completely new dyno; you install the packages there, but the dyno is immediately killed when you quit and other dynos are not affected.
score: 0
has comment: http://stackoverflow.com/comment/90849228
answers question: http://stackoverflow.com/q/51948753
type: Answer
has comment: http://stackoverflow.com/comment/90852158
has comment: http://stackoverflow.com/comment/90849751

http://stackoverflow.com/a/53389805
has body: I believe that for now the best (most reliable) way to clean image datasets is manually. There might be some techniques that could be applied. For now, services like Azure and Amazon ML have some ways to clean data, however, I don't know if they apply that to images (https://learn.microsoft.com/en-us/azure/machine-learning/team-data-science-process/prepare-data). For sure there are companies that have a well developed way of doing this. Maybe you can get inspired by this paper: https://stefan.winklerbros.net/Publications/icip2014a.pdf
score: 2
upvote count: 2
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/51840815
downvote count: 0
answers question: http://stackoverflow.com/q/51840815

http://stackoverflow.com/comment/90793816
comment on: http://stackoverflow.com/q/51910136
type: Comment
type: QuestionComment
has text: Hi, please file a bug on GitHub to have it properly tracked.
score: 0

neural-network
tags question: http://stackoverflow.com/q/51905448
tags question: http://stackoverflow.com/q/51816714
tags question: http://stackoverflow.com/q/51902539
tags question: http://stackoverflow.com/q/51845056
tags question: http://stackoverflow.com/q/51952712
tags question: http://stackoverflow.com/q/51849044
tags question: http://stackoverflow.com/q/51824393
tags question: http://stackoverflow.com/q/51868299
tags question: http://stackoverflow.com/q/51902088
tags question: http://stackoverflow.com/q/51824328
tags question: http://stackoverflow.com/q/51818163
tags question: http://stackoverflow.com/q/51945455
tags question: http://stackoverflow.com/q/51814651
tags question: http://stackoverflow.com/q/51889378
tags question: http://stackoverflow.com/q/51799144
tags question: http://stackoverflow.com/q/51878608
tags question: http://stackoverflow.com/q/51806570
tags question: http://stackoverflow.com/q/51802631
tags question: http://stackoverflow.com/q/51893903
tags question: http://stackoverflow.com/q/51949122
tags question: http://stackoverflow.com/q/51818052
tags question: http://stackoverflow.com/q/51923048
tags question: http://stackoverflow.com/q/51862530
tags question: http://stackoverflow.com/q/51882681
type: Tag
tags question: http://stackoverflow.com/q/51891743
tags question: http://stackoverflow.com/q/51871271
tags question: http://stackoverflow.com/q/51921075
tags question: http://stackoverflow.com/q/51867981
tags question: http://stackoverflow.com/q/51905199
tags question: http://stackoverflow.com/q/51814138
tags question: http://stackoverflow.com/q/51889255
tags question: http://stackoverflow.com/q/51872781
tags question: http://stackoverflow.com/q/51886844
tags question: http://stackoverflow.com/q/51827349
tags question: http://stackoverflow.com/q/51835124
tags question: http://stackoverflow.com/q/51854463
tags question: http://stackoverflow.com/q/51839019
tags question: http://stackoverflow.com/q/51906709
tag name: neural-network
tags question: http://stackoverflow.com/q/51841810
tags question: http://stackoverflow.com/q/51801648
tags question: http://stackoverflow.com/q/51907813
tags question: http://stackoverflow.com/q/51918348
tags question: http://stackoverflow.com/q/51857274
tags question: http://stackoverflow.com/q/51819213
tags question: http://stackoverflow.com/q/51917036
tags question: http://stackoverflow.com/q/51930566
tags question: http://stackoverflow.com/q/51805991
tags question: http://stackoverflow.com/q/51867943

http://stackoverflow.com/comment/90783860
comment on: http://stackoverflow.com/q/51916775
has text: @melpomene was also wondering that... but was guessing there's something somewhat more complicated going on in the Python wrapper to calculate/retrieve those extra arguments instead of just trying to extend them :)
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51827513
has title: Python Set Parent to an Instance
has comment: http://stackoverflow.com/comment/90609960
has comment: http://stackoverflow.com/comment/90609500
type: Question
answer count: 1
downvote count: 0
score: 1
tagged with: inheritance
favorite count: 0
has comment: http://stackoverflow.com/comment/90609602
has comment: http://stackoverflow.com/comment/90609369
has comment: http://stackoverflow.com/comment/90609449
has comment: http://stackoverflow.com/comment/90609779
tagged with: python
has comment: http://stackoverflow.com/comment/90609451
has comment: http://stackoverflow.com/comment/90609738
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90610026
type: UnansweredQuestion
upvote count: 1
has answer: http://stackoverflow.com/a/51827700
has body: Is there a way to just set a parent object to a particular instance? I have a utility that initializes a complex object for me and i'd like to have it init some objects for mocking. Example: class ComplexObject: def __init__(arg1, arg2, arg3): #do some stuff return class ComplexObject_Mock(ComplexObject): def __init__(): complexObject = ComplexObjectFactory.NewComplexObject() return super() = complexObject Now I know the above doesn't work, because of the last line. Usually I create the instance of the parent class by using super().__init(arg1, arg2, arg3), but instead of that i'd like to just set the instance to something initialized by the factory.

http://stackoverflow.com/comment/90750317
comment on: http://stackoverflow.com/a/51899391
has text: I was also thinking about that! But why there is no way? I feel that I’m touching something strange, cause in other languages with memory management / pointers it could be totally straightforward. Maybe something with decorators could make the deal?
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/51887405
favorite count: 0
type: UnansweredQuestion
tagged with: windows
tagged with: python
has body: Hello I learning python using pycharm and following one small youtube series where I want to delete .db file from project folder. but I am getting an error that states java.io.IOException. Please suggest what is the main problem. Thanks in advance.
answer count: 0
tagged with: pycharm
has title: python error in deleting db file
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/90726640
type: Question
has comment: http://stackoverflow.com/comment/90726112
score: 0
tagged with: sqlite

http://stackoverflow.com/a/51905420
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51858248
has body: Try pinning Werkzeug==0.12.2. I think we've run into the same issue, though I haven't had time to sort it out far enough to know if it's Python's issue, Werkzeug's issue, or an issue with our environment. I didn't have time to dig very deep; needed to roll back to our old pinned versions and keep moving. The quick summary of what I found last time I went looking was that Werkzeug semi-recently changed to use SpooledTemporaryFile: https://github.com/pallets/werkzeug/pull/1198 https://github.com/pallets/werkzeug/issues/1210 https://github.com/pallets/werkzeug/issues/1220 https://github.com/pallets/werkzeug/issues/1222 but SpooledTemporaryFile seems to have some known deficiencies documented on the Python bug tracker https://bugs.python.org/issue26175 https://bugs.python.org/issue32600 and here on SO: Why doesn&#39;t tempfile.SpooledTemporaryFile implement readable, writable, seekable? Update: After seeing that we aren't the only ones running into this, I've decided to go ahead and file an issue with Werkzeug (https://github.com/pallets/werkzeug/issues/1344)

http://stackoverflow.com/q/51820281
has title: TypeError: __str__ returned non-string (type Error)
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90594350
tagged with: python
has comment: http://stackoverflow.com/comment/90594395
tagged with: python-requests
type: Question
has body: I have a url, which i can hit with postman as well as directly on browser. But with python, i always get this error.Also tried with verify=False. Please check and suggest. Additional info: OS: MAC Python: 2.7 &gt;&gt;&gt; requests.get(url) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/Library/Python/2.7/site-packages/requests/api.py", line 69, in get return request('get', url, params=params, **kwargs) File "/Library/Python/2.7/site-packages/requests/api.py", line 50, in request response = session.request(method=method, url=url, **kwargs) File "/Library/Python/2.7/site-packages/requests/sessions.py", line 465, in request resp = self.send(prep, **send_kwargs) File "/Library/Python/2.7/site-packages/requests/sessions.py", line 573, in send r = adapter.send(request, **kwargs) File "/Library/Python/2.7/site-packages/requests/adapters.py", line 370, in send timeout=timeout File "/Library/Python/2.7/site-packages/requests/packages/urllib3/connectionpool.py", line 544, in urlopen body=body, headers=headers) File "/Library/Python/2.7/site-packages/requests/packages/urllib3/connectionpool.py", line 344, in _make_request self._raise_timeout(err=e, url=url, timeout_value=conn.timeout) File "/Library/Python/2.7/site-packages/requests/packages/urllib3/connectionpool.py", line 314, in _raise_timeout if 'timed out' in str(err) or 'did not complete (read)' in str(err): # Python 2.6 TypeError: __str__ returned non-string (type Error)
has comment: http://stackoverflow.com/comment/90622192
score: 0

http://stackoverflow.com/comment/90707658
type: Comment
has text: Seeking recommendations for software libraries is explicitly off-topic here, as you may recall from your study of the material in the help centre. Had you asked how to perfect your own implementation of the code to make the calculations you need to make, well that would be a different, and most likely on-topic question.
comment on: http://stackoverflow.com/q/51877897
score: 0
type: QuestionComment

http://stackoverflow.com/q/51852983
upvote count: 1
has comment: http://stackoverflow.com/comment/90659159
downvote count: 1
linked to: http://stackoverflow.com/q/29547104
has comment: http://stackoverflow.com/comment/90658588
has comment: http://stackoverflow.com/comment/90661783
has comment: http://stackoverflow.com/comment/90659079
has comment: http://stackoverflow.com/comment/90658850
has body: Recently, I watched a video about writing a code to decode the title and contents of the file from decimal numbers into strings. However, it is written in python2 so I decided to rewrite the code in python3. Unfortunately, I am having trouble in decoding the contents of the picture. This is the original code in python2: #!/usr/bin/env python import os directory = '1262404985085867488371' def decrypt(number): return hex(int(number))[2:].replace("L","").decode("hex") os.chdir(directory) for i in os.listdir('.'): try: print(decrypt(i)) c = open(i).read() open(decrypt(i),'w').write(decrypt(c)) #o.write(decrypt(c)) except: print("FAILED WITH",i) And this is the code written in python3: #!/usr/bin/env python3 import os directory = '1262404985085867488371' def decrypt(number): hex_num = hex(int(number))[2:].replace("L","") return bytes.fromhex(hex_num).decode("ascii") os.chdir(directory) for i in os.listdir('.'): try: print(decrypt(i)) c = open(i).read() open(decrypt(i),'w').write(decrypt(c)) #o.write(decrypt(c)) except: print("FAILED WITH",i) Can anyone help me to have a look how can I solve this problem? This is the problem about: My computer got infected with ransomware and now none of my documents are accessible anymore! If you help me out, I'll reward you a flag! https://static.tjctf.org/7459b0c272ba30c9fea94391c7d7051d78e1732c871c3a6f27070fcb34f9e734_encrypted.tar.gz Basically, I have tried by changing the ascii into utf-8 and open the file with the mode in "wb" or "rb" but neither of them works...
type: Question
has title: Difference between python2 and python3 in the decode function
tagged with: python-2.7
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/90659209
has comment: http://stackoverflow.com/comment/90659204
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51853166
has comment: http://stackoverflow.com/comment/90659034
has comment: http://stackoverflow.com/comment/90658739
linked to: http://stackoverflow.com/q/3283984
has comment: http://stackoverflow.com/comment/90660383
tagged with: python
has comment: http://stackoverflow.com/comment/90658612
has comment: http://stackoverflow.com/comment/90662137
has comment: http://stackoverflow.com/comment/90659194
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90659028
has comment: http://stackoverflow.com/comment/90658968

http://stackoverflow.com/comment/91526621
has text: @AlwaysLearningForever Yes, the returned parameters are the best fit values for `theta` and `phi`. As this is generic data, I generated it by providing a given line adding random numbers. This is the 'original line' and the fit, hence, should be close to this line.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51891284

http://stackoverflow.com/comment/90976611
score: 0
has text: Sorry CristiFati, I just created the sample code to figure out this issue between Python and C. but Thanks a lot!. I will keep in mind to have the sample example at first place.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51965157

http://stackoverflow.com/comment/124073476
type: Comment
score: 1
comment on: http://stackoverflow.com/a/51892947
has text: Dummy question: In your code, are `clientCrt` and `clientKey` supposed to be file paths or strings containg the certificate and key themselves? If the former, how can I do that if I have only the latter?
type: AnswerComment

http://stackoverflow.com/comment/90854711
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51951883
has text: I decided to use the other answer because it is much simpler. Thank you for trying, I upvoted your post.
type: AnswerComment

http://stackoverflow.com/comment/90693672
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51870964
has text: Use collection ;) see code below
type: QuestionComment

http://stackoverflow.com/a/51847823
answers question: http://stackoverflow.com/q/51840455
type: Answer
has body: Consider SQLite's ATTACH DATABASE command to query external databases and then walk through every table of the attached database for appending data to the first database. Specifically, below opens first database and then iteratively attaches each database in a directory that contains the SQLite databases. Then within each database, table names are queried and then looped to append each of their content. Outer loop is wrapped in a context manager, with(), of the first database connection, so there is no need to run conn.close() at end. library(os) library(sqlite3) mypath = "/path/to/sqlite/databases" # OPEN CONNECTION TO FIRST DATABASE with sqlite3.connect(os.path.join(mypath, "myfirst.db")) as conn: cur = conn.cursor() # LOOP THROUGH EACH DB TO ATTACH for db in os.listdir(mypath): if db != "myfirst.db" and db.endswith(".db"): # PASS FULL FILE NAME AS PARAMETER cur.execute("ATTACH ? AS curr_db;", os.path.join(mypath, db)) # GET ALL TABLES IN curr_db cur.execute("SELECT name FROM curr_db.sqlite_master WHERE type='table';") all_tbls = cur.fetchall() # LOOP THROUGH EACH TABLE for tbl in all_tbls: # APPEND DATA (ASSUMING SAME COLUMNS IN SAME POSITION) sql = "INSERT INTO mytable SELECT * FROM curr_db.[{}];".format(tbl[0]) cur.execute(sql) conn.commit() cur.execute("DETACH curr_db;") cur.close() Be sure to update mypath, myfirstdb, and mytable for actual names. If all runs properly, the first database's mytable will maintain all records across all tables in all databases. You may need to manually append each table within only the first database into mytable prior to or after looping.
score: 4
upvote count: 4
downvote count: 0

http://stackoverflow.com/comment/90661389
type: QuestionComment
has text: I need to find many different words in the file (about 400,000), so I can't write a regex for each individual one unfortunatley.
comment on: http://stackoverflow.com/q/51854116
score: 0
type: Comment

http://stackoverflow.com/comment/90657787
comment on: http://stackoverflow.com/a/51852462
type: Comment
score: 2
has text: Great answer. On my machine, I had to compile with `-fPIC`. Do you have to do that?
type: AnswerComment

http://stackoverflow.com/a/51872382
has comment: http://stackoverflow.com/comment/90696491
has comment: http://stackoverflow.com/comment/90696413
has comment: http://stackoverflow.com/comment/90697797
has comment: http://stackoverflow.com/comment/90696206
has comment: http://stackoverflow.com/comment/90697947
has comment: http://stackoverflow.com/comment/90697095
accepted answer of: http://stackoverflow.com/q/51871693
has comment: http://stackoverflow.com/comment/90696241
has body: You can use pattern: [!,.:;-](?= |$) To match any characters !,,,.,:,; and - that are followed by whitespace or end of string. In Python: import re text = "Hi! We are looking for smart, young and hard-working c++ developer. Our perfect candidate should know: - c++, c#, .NET in expert level;" print (re.sub(r'[!,.:;-](?= |$)',r'',text)) Prints: Hi We are looking for smart young and hard-working c++ developer Our perfect candidate should know c++ c# .NET in expert level
answers question: http://stackoverflow.com/q/51871693
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90697132
has comment: http://stackoverflow.com/comment/90696271
has comment: http://stackoverflow.com/comment/90696910
type: Answer
has comment: http://stackoverflow.com/comment/90697414
downvote count: 0
has comment: http://stackoverflow.com/comment/90696291
has comment: http://stackoverflow.com/comment/90696632
score: 1
has comment: http://stackoverflow.com/comment/90696618

http://stackoverflow.com/q/51943419
tagged with: mysql
has comment: http://stackoverflow.com/comment/90837934
type: Question
has answer: http://stackoverflow.com/a/75670472
has answer: http://stackoverflow.com/a/51944591
downvote count: 0
tagged with: apache-spark
has answer: http://stackoverflow.com/a/65183850
tagged with: python
answer count: 4
favorite count: 0
score: 8
has body: I want to connect mysql with pyspark. I am using jupyter notebook to run pyspark. However when I do this, dataframe_mysql = sqlContext.read.format("jdbc").options( url="jdbc:mysql://localhost:3306/playground", driver = "com.mysql.jdbc.Driver", dbtable = "play1", user="root", password="sp123").load() I get an error as Py4JJavaError: An error occurred while calling o89.load. : java.lang.ClassNotFoundException: com.mysql.jdbc.Driver. How can I resolve this error and load mysql data in pyspark dataframe?
upvote count: 8
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/72573624
has title: connecting mysql with pyspark
tagged with: pyspark
linked to: http://stackoverflow.com/q/30983982

http://stackoverflow.com/q/51887758
downvote count: 0
has answer: http://stackoverflow.com/a/78440161
has body: I am working in an environment where writing to the disk space with a folder name like .ipynb_checkpoints is disallowed. Unfortunately, this is Jupyter Notebook's default path for Save and Checkpoint. Is there a way to configure Jupyter Notebook to not use the checkpoint feature or allow a different folder name?
has answer: http://stackoverflow.com/a/51887811
tagged with: python
favorite count: 0
tagged with: jupyter-notebook
has answer: http://stackoverflow.com/a/53865194
answer count: 5
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/70757077
has title: Is there a way to disable saving to checkpoints for Jupyter Notebooks?
has answer: http://stackoverflow.com/a/78789556
score: 19
upvote count: 19
type: Question

http://stackoverflow.com/a/51942007
accepted answer of: http://stackoverflow.com/q/51941175
answers question: http://stackoverflow.com/q/51941175
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: I'm guessing you copy and pasted from a Windows property pane, switching backslashes to forward slashes manually. Problem is, the properties dialog shoves a Unicode LEFT-TO-RIGHT EMBEDDING character into the path so the display is consistent, even in locales with right-to-left languages (e.g. Arabic, Hebrew). You can read more about this on Raymond Chen's blog, The Old New Thing. The solution is to delete that invisible character from your path string. Selecting everything from the initial " to the first forward slash, deleting it, then retyping "C:/, should do the trick.
score: 1
upvote count: 1

http://stackoverflow.com/comment/90573288
score: 0
type: Comment
has text: So basically speaking ... the variables inside outer function is closure for inner function. And the benefit of this is that inner function can keep variable from outer function even if outer function has finished. Am I right?
type: AnswerComment
comment on: http://stackoverflow.com/a/51809094

http://stackoverflow.com/comment/90736032
type: AnswerComment
type: Comment
has text: Thanks, I edited my question now.. Sorry for the inconvenience
comment on: http://stackoverflow.com/a/51892544
score: 0

http://stackoverflow.com/comment/90659845
has text: Do you check source HTML (`Ctrl+U`) ? Can you post it here?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51852895
type: QuestionComment

http://stackoverflow.com/comment/90602822
has text: Possibly you are looking for `plt.hist2d`?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51824174

http://stackoverflow.com/comment/90747512
type: Comment
has text: You should really post a small sample matrix in your post, as well as your attempt to solve the problem, with your expected output.
score: 3
comment on: http://stackoverflow.com/q/51898197
type: QuestionComment

http://stackoverflow.com/q/51807151
tagged with: netmiko
has answer: http://stackoverflow.com/a/51813923
has title: Python | Netmiko
possible better answer: http://stackoverflow.com/a/60613486
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/60613486
accepted answer: http://stackoverflow.com/a/51813923
score: 1
favorite count: 0
tagged with: python-3.x
type: Question
tagged with: python
upvote count: 2
has body: I am writing a script in Python using Netmiko to Automate the Upgrade of 450+ routers. They are a mix of 881/887, 1921 and 2901. I am using Netmiko and have worked out on how to determine the Model and copy the appropriate IOS version. What I am having issues with is reloading the router. I am trying to use the send_command_expect function but I have been unable to get it to work. Here is how I am trying to achieve it. Any help is appreciated. import getpass import time from netmiko import ConnectHandler, file_transfer host = "10.0.0.1" u = "cisco" p = "cisco" source_file = "c800-universalk9-mz.SPA.155-3.M5.bin" router = { 'device_type': "cisco_ios", 'ip': host, 'username': u, 'password': p, } try: ssh_conn = ConnectHandler(**router) print ("Connection successful\n") except: print ("Login failure\n") sys.exit() output = ssh_conn.send_command_expect('write mem') output += ssh_conn.send_command('reload') output += ssh_conn.send_command('\n')enter code here Below is the error message: 192-168-1-6:CiscoUpgrade sudarshanv$ python3 test.py Connection successful Traceback (most recent call last): File "test.py", line 25, in &lt;module&gt; output += ssh_conn.send_command('reload') File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/netmiko/base_connection.py", line 1112, in send_command search_pattern)) OSError: Search pattern never detected in send_command_expect: HomeRTR\# 192-168-1-6:CiscoUpgrade sudarshanv$
has answer: http://stackoverflow.com/a/61203310
answer count: 3
downvote count: 1

http://stackoverflow.com/a/51940849
accepted answer of: http://stackoverflow.com/q/51940830
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51940830
downvote count: 0
type: Answer
score: 2
upvote count: 2
has body: Pure python solution: x = np.array(['test_a','help_b','apple_c']) a, b = zip(*[k.split('_') for k in x.tolist()]) &gt;&gt;&gt; a # can always make this list(a) ('test', 'help', 'apple') Using pandas &gt;&gt;&gt; pd.DataFrame(pd.Series(x).str.split('_').tolist()) 0 1 0 test a 1 help b 2 apple c such that &gt;&gt;&gt; df2[0].tolist() ['test', 'help', 'apple']

http://stackoverflow.com/q/51914505
tagged with: yaml
has comment: http://stackoverflow.com/comment/90781426
downvote count: 0
has comment: http://stackoverflow.com/comment/90779005
favorite count: 0
accepted answer: http://stackoverflow.com/a/51915357
upvote count: 8
tagged with: python
has comment: http://stackoverflow.com/comment/90778987
has answer: http://stackoverflow.com/a/60630398
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90780686
tagged with: http://stackoverflow.com/tag/json
possible better answer: http://stackoverflow.com/a/60630398
has title: Python YAML to JSON to YAML
type: Question
score: 8
has answer: http://stackoverflow.com/a/51915357
answer count: 2
has body: I'm new to python so I am building a simple program to parse YAML to JSON and JSON to YAML. The yaml2json converts YAML to JSON on a single line, but a JSON validator says it is correct. This is my code so far: def parseyaml(inFileType, outFileType): infile = input('Please enter a {} filename to parse: '.format(inFileType)) outfile = input('Please enter a {} filename to output: '.format(outFileType)) with open(infile, 'r') as stream: try: datamap = yaml.safe_load(stream) with open(outfile, 'w') as output: json.dump(datamap, output) except yaml.YAMLError as exc: print(exc) print('Your file has been parsed.\n\n') def parsejson(inFileType, outFileType): infile = input('Please enter a {} filename to parse: '.format(inFileType)) outfile = input('Please enter a {} filename to output: '.format(outFileType)) with open(infile, 'r') as stream: try: datamap = json.load(stream) with open(outfile, 'w') as output: yaml.dump(datamap, output) except yaml.YAMLError as exc: print(exc) print('Your file has been parsed.\n\n') An example of the original YAML vs. the new YAML Original: inputs: webTierCpu: type: integer minimum: 2 default: 2 maximum: 5 title: Web Server CPU Count description: The number of CPUs for the Web nodes New: inputs: dbTierCpu: {default: 2, description: The number of CPUs for the DB node, maximum: 5, minimum: 2, title: DB Server CPU Count, type: integer} It doesn't look like its decoding all of the JSON so I'm not sure where I should go next...
has comment: http://stackoverflow.com/comment/90778958

http://stackoverflow.com/q/51946730
accepted answer: http://stackoverflow.com/a/51946731
type: Question
tagged with: ruamel.yaml
has body: I have a YAML document in a file that I need to update with some structured information, that I get from a library. The order in which keys from this information are dumped is important. The YAML file (input.yaml) looks like: %YAML 1.1 --- - element 1 # this is the first element - element 2 (please don't ask why the next program in the chain only support YAML 1.1, even though 1.2 has been out for over nine years) My program: import sys from collections import OrderedDict from pathlib import Path import ruamel.yaml path = Path('input.yaml') yaml = ruamel.yaml.YAML() # defaults to round-trip yaml.version = (1, 1) yaml.explicit_start = True data = yaml.load(path) data.append( OrderedDict([ ('hosts', 'all'), ('vars', {'some_var': True}), ('tasks', [ OrderedDict([('name', 'print some_var'), ('debug', {'var': 'some_var'})]) ]), ])) yaml.dump(data, sys.stdout) with output: %YAML 1.1 --- - element 1 # this is the first element - element 2 - !!omap - hosts: all - vars: some_var: true - tasks: - !!omap - name: print some_var - debug: var: some_var How can I output the OrderedDicts without getting the !!omap tags and without key-value as a single elements in a list? I am using ruamel.yaml to preserve existing comments. I get this structure from a library, and I cannot specify that it should use ruamel.yaml's CommentedMap. I know how to recursively walk over the structure, before appending, and converting OrderedDict in ruamel.yaml's CommentedMap, but that is to slow.
has title: Dump OrderedDict in a more concise way
tagged with: yaml
downvote count: 0
answer count: 1
tagged with: ordereddict
has answer: http://stackoverflow.com/a/51946731
favorite count: 0
has comment: http://stackoverflow.com/comment/90842913
tagged with: python
score: 2
type: AnsweredQuestion
upvote count: 2

http://stackoverflow.com/comment/90576210
type: Comment
has text: '10-Aug-2018' is two times similarly '9-Aug-2018' is also two times. My code is real and i think there is some misunderstanding.
comment on: http://stackoverflow.com/a/51810546
type: AnswerComment
score: 0

http://stackoverflow.com/comment/90698431
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/51872412
has text: I think this error happens because your network expects an input with 3 channels. That is why I suggested converting your image to rgb.

http://stackoverflow.com/comment/90873070
type: Comment
score: 1
has text: Padding applies before strides. Without padding (also called "valid" padding), an image of size n (in one dimension) and a filter of size k would produce an output of size n - k + 1. "Same" padding adds k-1 zeroes to the image so that the result has size n (n - k + 1 + k -1). If you are using strides (as in your max pooling layers), this will still reduce the output size by a factor (2 in your case). Stride + "same" padding just means the output size is n/2 and not (n - k + 1)/2.
comment on: http://stackoverflow.com/a/51953008
type: AnswerComment

http://stackoverflow.com/comment/90780187
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51914968
has text: Possible duplicate of [Scraping dynamic content using python-Scrapy](https://stackoverflow.com/questions/30345623/scraping-dynamic-content-using-python-scrapy)

http://stackoverflow.com/comment/90721536
comment on: http://stackoverflow.com/q/51883897
score: 0
type: Comment
type: QuestionComment
has text: What do you mean by that? `df.query(str())` is just querying an empty string. But `df.query(str(something))` is fine. It's not often _useful_, because `something` is usually already a string (as it is in your case), but it's certainly _supported_.

http://stackoverflow.com/comment/90559038
type: AnswerComment
has text: `df = pd.DataFrame({'B':range(4, 10), 'A':[0,1,0,1,1,1]})`, seems issue?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51800729

http://stackoverflow.com/a/53169086
has comment: http://stackoverflow.com/comment/93330839
downvote count: 0
has body: The answer is quite simple. Before you do model.fit() you can stick anything to the model. I just sticked X_train and Y_train to it. You can here stick the validation or test data to it, whatever you want. model.X_train=X_train model.Y_train=Y_train Then, you use those values with the sklearn library to calculate any performance (accuracy, f1, kappa, ... ) First, add variables to self to enable later appending each epoch result to the variable class yourowncallbackname(Callback): def_on_train_begin(self,logs={}): self.val_f1=[] #define the variable to collect results self.val_kappa=[] then define what happens on the end of each epoch in the same class "yourowncallbackname" (on epoch end works best). Here you use the data sticked to the model (e.g. model.x_train) to get the results from model.predict. def on_epoch_end(self, epoch, logs={}): #LOAD DATA train_predict= (np.asarray(self.model.predict(self.model.X_train))) train_true=self.model.Y_train_jan val_predict = np.asarray(self.model.predict(self.validation_data[0])) val_true = self.validation_data[1] Maybe, depending on what you want to predict you have to round the predictions with .round val_predict = (np.asarray(self.model.predict(self.model.X_train))).round() Then calculate any performance you like on the predicted data (same as defined in on_train_begin) for e.g. test and validation _train_f1= f1_score(train_true, train_predict, labels=...) _train_k= cohen_kappa_score(train_true.ravel(),train_predict,labels=...) _val_f1= f1_score(val_true, val_predict, labels=...) _val_k= cohen_kappa_score(val_true.ravel(), val_predict, labels=...) To collect them, stick them now to self. This will stick to the callback itself which you can later call again. self.train_f1.append(_train_f1) self.train_kappa.append(_train_k) self.val_f1.append(_val_f1) self.val_kappa.append(_val_k) This callback you have to initialize now wherever you want to fit your model callbackmetric=yourowncallbackname() Then you can put it into the fit:…
type: Answer
has comment: http://stackoverflow.com/comment/93324968
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/51837387

http://stackoverflow.com/comment/90786332
score: 0
has text: Good catch! Thank you I forgot to add `len` .
type: Comment
comment on: http://stackoverflow.com/a/51908692
type: AnswerComment

http://stackoverflow.com/comment/90748523
type: Comment
has text: Can you please post your robot script, and the way you run the .py script from the command line?
comment on: http://stackoverflow.com/a/51881696
type: AnswerComment
score: 0

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

http://stackoverflow.com/q/51813278
has comment: http://stackoverflow.com/comment/90589576
accepted answer: http://stackoverflow.com/a/51813822
upvote count: 3
has answer: http://stackoverflow.com/a/51836970
type: Question
has title: Error when trying to setup Python pip installation behind corporate firewall
answer count: 3
score: 3
downvote count: 0
has answer: http://stackoverflow.com/a/51818443
has comment: http://stackoverflow.com/comment/90582402
favorite count: 0
tagged with: python-3.x
has body: I am trying to configure global proxy options for python pip installer so that it works behind corporate firewall. The command I tried: pip config --global set proxy "http://user:pass@host:port" The above command gives error with below trace: Traceback (most recent call last): File "c:\users\username\appdata\local\programs\python\python37-32\lib\site-packages\pip\_internal\basecommand.py", line 228, in main status = self.run(options, args) File "c:\users\username\appdata\local\programs\python\python37-32\lib\site-packages\pip\_internal\commands\configuration.py", line 122, in run handlers[action](options, args[1:]) File "c:\users\username\appdata\local\programs\python\python37-32\lib\site-packages\pip\_internal\commands\configuration.py", line 167, in set_name_value self.configuration.set_value(key, value) File "c:\users\username\appdata\local\programs\python\python37-32\lib\site-packages\pip\_internal\configuration.py", line 153, in set_value section, name = _disassemble_key(key) ValueError: not enough values to unpack (expected 2, got 1) Any ideas on what I am doing wrong? Also, I tried creating the pip.ini file in %AppData% (windows) as suggested in many posts. Didn't work for me.
possible better answer: http://stackoverflow.com/a/51818443
tagged with: firewall
tagged with: pip
tagged with: python
has answer: http://stackoverflow.com/a/51813822
type: AnsweredQuestion

http://stackoverflow.com/a/51865402
answers question: http://stackoverflow.com/q/51865187
score: 1
upvote count: 1
downvote count: 0
has body: Your data contains duplicates, probably because you are only including a subset of the columns. You need something else in your data other than price (e.g. two different days could close at the same price, but you wouldn't aggregate the volume from the two). Assuming that the price is unique for a given timestamp, market and company and you first sort on your timestamp column if any (not required if there is only one price per company and market): df = pd.DataFrame({ 'company': ['EK', 'SQ', 'EK', 'EK', 'EK', 'SQ', 'EK'], 'date': ['2018-08-13'] * 3 + ['2018-08-14'] * 4, 'market': ['LA'] * 7, 'price': [206] * 3 + [36] * 4}) &gt;&gt;&gt; (df.groupby(['market', 'date', 'company'])['price'] .agg({'price': 'last', 'volume': 'count'}'price', 'volume' .reset_index() market date company price volume 0 LA 2018-08-13 EK 206 2 1 LA 2018-08-13 SQ 206 1 2 LA 2018-08-14 EK 36 3 3 LA 2018-08-14 SQ 36 1
type: Answer

pivot-table
tags question: http://stackoverflow.com/q/51833343
tag name: pivot-table
tags question: http://stackoverflow.com/q/51820952
tags question: http://stackoverflow.com/q/51899382
tags question: http://stackoverflow.com/q/51831921
tags question: http://stackoverflow.com/q/51880972
tags question: http://stackoverflow.com/q/51798913
type: Tag

http://stackoverflow.com/a/51954834
has comment: http://stackoverflow.com/comment/106100176
has comment: http://stackoverflow.com/comment/106100102
type: Answer
upvote count: 1
has body: Thanks for the pointers @AChampion. The problem turned out to be requesting scope https://www.googleapis.com/auth/spreadsheets.readonly when I had only authorized scope https://www.googleapis.com/auth/spreadsheets. I thought spreadsheets would be a superset of spreadsheets.readonly but that doesn't seem to be the case. My get_service code: def get_service(api_name, api_version, scopes, key_file_location): """Get a service that communicates to a Google API. Args: api_name: The name of the api to connect to. api_version: The api version to connect to. scopes: A list auth scopes to authorize for the application. key_file_location: The path to a valid service account JSON key file. Returns: A service that is connected to the specified API. """ credentials = ServiceAccountCredentials.from_json_keyfile_name( key_file_location, scopes=scopes) # credentials = service_account.Credentials.from_service_account_file( # key_file_location, scopes=scopes) delegated_credentials = credentials.create_delegated('name@example.com') delegated_http = delegated_credentials.authorize(Http()) # Build the service object. service = build(api_name, api_version, http=delegated_http) return service And my call to get_service: scope = 'https://www.googleapis.com/auth/spreadsheets' key_file_location = '/path/to/keyfile.json' service = get_service( api_name='sheets', api_version='v4', scopes=[scope], key_file_location=key_file_location)
accepted answer of: http://stackoverflow.com/q/51939408
answers question: http://stackoverflow.com/q/51939408
type: AcceptedAnswer
downvote count: 0
score: 1

http://stackoverflow.com/q/51932766
type: Question
tagged with: numpy
upvote count: 1
has answer: http://stackoverflow.com/a/51932827
accepted answer: http://stackoverflow.com/a/51932827
downvote count: 0
answer count: 3
has comment: http://stackoverflow.com/comment/90815732
possible better answer: http://stackoverflow.com/a/51933289
favorite count: 0
has body: I want to create a numpy three channel image with dimensions 10x5 and a fixed color of [0, 1, 2]. I'm currently doing it using the following code: x = np.array([0, 1, 2]) x = np.array((x,) * 10) x = np.array((x,) * 5) This works, but is not very elegant. What is the best / most efficient way to achieve the same with less code?
has title: Best way to create a three channel image with a fixed color?
tagged with: python
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/51932831
has answer: http://stackoverflow.com/a/51933289
tagged with: scipy

http://stackoverflow.com/comment/90746956
type: Comment
type: QuestionComment
score: 1
has text: Just hook them up using websockets. Easy and painfree realtime communication
comment on: http://stackoverflow.com/q/51897917

http://stackoverflow.com/comment/90859961
has text: @Interested_Programmer it seems to be working now although I didn't change anything... Thanks for you're help I guess:)
score: 0
comment on: http://stackoverflow.com/q/51954292
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51841506
tagged with: python
has title: Data Standardization vs Normalization vs Robust Scaler
has body: I am working on data preprocessing and want to compare the benefits of Data Standardization vs Normalization vs Robust Scaler practically. In theory, the guidelines are: Advantages: Standardization: scales features such that the distribution is centered around 0, with a standard deviation of 1. Normalization: shrinks the range such that the range is now between 0 and 1 (or -1 to 1 if there are negative values). Robust Scaler: similar to normalization but it instead uses the interquartile range, so that it is robust to outliers. Disadvantages: Standardization: not good if the data is not normally distributed (i.e. no Gaussian Distribution). Normalization: get influenced heavily by outliers (i.e. extreme values). Robust Scaler: doesn't take the median into account and only focuses on the parts where the bulk data is. I created 20 random numerical inputs and tried the above-mentioned methods (numbers in red color represent the outliers): I noticed that -indeed- the Normalization got affected negatively by the outliers and the change scale between the new values became tiny (all values almost identical -6 digits after the decimal point- 0.000000x) even there is noticeable differences between the original inputs! My questions are: Am I right to say that also Standardization gets affected negatively by the extreme values as well? If not, why according to the result provided? I really can't see how the Robust Scaler improved the data because I still have extreme values in the resulted data set? Any simple complete interpretation?
has answer: http://stackoverflow.com/a/51842540
answer count: 2
tagged with: machine-learning
downvote count: 1
accepted answer: http://stackoverflow.com/a/58106925
possible better answer: http://stackoverflow.com/a/51842540
upvote count: 33
score: 32
tagged with: standardized
tagged with: normalization
type: AnsweredQuestion
tagged with: scikit-learn
favorite count: 0
has answer: http://stackoverflow.com/a/58106925
type: Question

http://stackoverflow.com/comment/90574371
has text: What have you tried already? Do you have some sample code and something like a `docker-compose.yml` or a `docker run` command for the main service you can share?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51809633
score: 0

http://stackoverflow.com/a/51898852
downvote count: 0
has comment: http://stackoverflow.com/comment/90749516
type: Answer
score: 1
upvote count: 1
has body: That is usually called in TensorFlow the "global step", and it has some helper functions for it: global_step = tf.train.create_global_step() optimizer.minimize(loss, global_step=global_step) tf.train.get_global_step really just creates a variable, but making sure it is not trainable and adding it to the right collections. You also have tf.train.get_global_step so you can do: optimizer.minimize(loss, global_step=tf.train.create_global_step()) And at some other point in the code retrieve the tensor like: global_step = tf.train.get_global_step() Moreover, you can use tf.train.get_or_create_global_step if you are not sure which part of the graph definition will go first. The is one more function, tf.train.global_step, but I don't think it serves any purpose currently, since it just runs the given tensor in the given session and returns its value as an integer.
answers question: http://stackoverflow.com/q/51893694

http://stackoverflow.com/q/51932277
type: Question
possible better answer: http://stackoverflow.com/a/51932597
has answer: http://stackoverflow.com/a/51932597
tagged with: flask
has body: I have this array of arrays: [['Frutta', ['M01', '2018-08-06 08:35:00', '2018-08-06 10:13:00'], ['M02', '2018-08-06 10:18:00', '2018-08-06 11:42:00'], ['M04', '2018-08-06 15:19:00', '2018-08-06 16:37:00']], ['verdura', ['M01', '2018-08-06 08:35:00', '2018-08-06 10:25:00']]] and I want to print each field so, with flask I tried like this: {% for prodotto in range(inserisci_ordine[1]| length) %} {{ inserisci_ordine[prodotto][0] }}&lt;br&gt; {% for macchine in range(inserisci_ordine[prodotto]| length) %} {{ inserisci_ordine[prodotto][macchine] }}&lt;br&gt; {{ inserisci_ordine[prodotto][macchine][2] }}&lt;br&gt; {% endfor %} {% endfor %} I would like to print something like this: frutta M01, 2018-08-06 08:35:00, 2018-08-06 10:13:00 M02, 2018-08-06 10:18:00, 2018-08-06 11:42:00 M04, 2018-08-06 15:19:00, 2018-08-06 16:37:00 verdura M01, 2018-08-06 08:35:00, 2018-08-06 10:25:00 But I can't figure it out.. EDIT. Is it possible in some way, print also the machine utilized in the previous cycle? for example: frutta M01, 2018-08-06 08:35:00, 2018-08-06 10:13:00 #I want to print here , NULL M02, 2018-08-06 10:18:00, 2018-08-06 11:42:00 #Here the , M01 M04, 2018-08-06 15:19:00, 2018-08-06 16:37:00 #here the , M02 verdura M01, 2018-08-06 08:35:00, 2018-08-06 10:25:00 #here , NULL
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/51932604
favorite count: 0
has title: Print values of array of arrays in flask
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51932604
upvote count: 1
downvote count: 1

http://stackoverflow.com/comment/90645219
type: Comment
type: QuestionComment
has text: Yes, that is what gives it the visual effect of being raised. If it was a solid color it wouldn't look like it was a button.
score: 0
comment on: http://stackoverflow.com/q/51845416

http://stackoverflow.com/q/51818102
answer count: 2
has title: Make migrations using models corresponding to the different databases in Django
tagged with: django-rest-framework
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51821140
tagged with: django
tagged with: python
type: Question
has answer: http://stackoverflow.com/a/58145009
has body: This is my models.py file in app. from django.db import models class ImaraInventory(models.Model): branch = models.CharField(max_length=255) channel_type = models.CharField(max_length=255) day = models.DateField() partner_id = models.CharField(max_length=255) qty = models.BigIntegerField() sku_id = models.CharField(max_length=255) is_virtual = models.IntegerField() class Meta: unique_together = ('channel_type', 'branch', 'partner_id', 'day', 'sku_id') class ImaraSales(models.Model): attribution = models.CharField(max_length=255) branch = models.CharField(max_length=255) channel_type = models.CharField(max_length=255) day = models.DateField() partner_id = models.CharField(max_length=255) sku_id = models.CharField(max_length=255) live = models.BooleanField() disc_value = models.DecimalField(decimal_places=3,max_digits=12) revenue = models.DecimalField(decimal_places=3,max_digits=12) sales_qty = models.IntegerField() class Meta: unique_together = ('attribution', 'branch' , 'channel_type', 'day', 'partner_id', 'sku_id') class ImaraReturns(models.Model): branch = models.CharField(max_length=255) channel_type = models.CharField(max_length=255) partner_id = models.CharField(max_length=255) sku_id = models.CharField(max_length=255) day = models.DateField() return_qty = models.IntegerField() class Meta: unique_together = ('branch', 'channel_type', 'partner_id', 'sku_id', 'day') class WrognInventory(models.Model): branch = models.CharField(max_length=255) channel_type = models.CharField(max_length=255) day = models.DateField() partner_id = models.CharField(max_length=255) qty = models.BigIntegerField() sku_id = models.CharField(max_length=255) is_virtual = models.IntegerField() class Meta: unique_together = ('channel_type', 'branch', 'partner_id', 'day', 'sku_id') class WrognSales(models.Model): attribution = models.CharField(max_length=255) branch = models.CharField(max_length=255) channel_type = models.CharField(max_length=255) day = models.DateField() partner_id = models.C…
score: 0

http://stackoverflow.com/q/51844317
tagged with: decorator
tagged with: patch
favorite count: 0
type: UnansweredQuestion
tagged with: python
answer count: 0
upvote count: 2
has body: I have a project with a config file in __init__.py file of the main directory. The file could be accessed via project_name.config. I want to patch the config for tests. I am patching with the following command: mock.patch.dict(project_name.config, {'key': 'test_val'}). mock is from unittest. When I try to patch it using with inside test function everything works fine but when I try to patch it using decorator patching does not work. So what is wrong with the decorator?
has title: Why patch.dict does not work when used as decorator?
type: Question
tagged with: testing
has comment: http://stackoverflow.com/comment/130182190
score: 2
downvote count: 0

http://stackoverflow.com/a/51881601
score: -1
type: Answer
answers question: http://stackoverflow.com/q/51881503
downvote count: 1
upvote count: 0
has body: for i in range(len(df)): if df['Member'][i] in d: df['Date'][i] = d[df['Member'][i]] P.S. it's bad practise to name variables with reserved words (i.e. dict).

http://stackoverflow.com/comment/90648051
type: QuestionComment
has text: Do you have the file open in an editor?
score: 0
comment on: http://stackoverflow.com/q/51847159
type: Comment

http://stackoverflow.com/comment/90833895
has text: I need it every minute while my program is running
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51942198
type: Comment

http://stackoverflow.com/q/51808255
has body: I am trying to read the following value 9.692 Deposit: 9.692 I can't seem to be able to get text outside the span tag. I can retrieve the text deposit with the following: driver.find_elements_by_xpath("//span[@class='tab-box']")
tagged with: python
tagged with: selenium-webdriver
type: AnsweredQuestion
has title: Retrieving value 'outside' a span class selenium
score: 1
has answer: http://stackoverflow.com/a/51808348
tagged with: selenium
upvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/51808348
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/q/51878819
has comment: http://stackoverflow.com/comment/90709377
tagged with: keyboard-shortcuts
linked to: http://stackoverflow.com/q/17547473
linked to: http://stackoverflow.com/q/23011836
tagged with: python-3.x
has body: I cannot open a new tab using Firefox WebDriver. I've found a lot of suggestions, e.g. here, here, and here, but they do not work. E.g. none of these worked: ActionChains(driver)\ .move_to_element(driver.find_element_by_tag_name("body"))\ .key_down(Keys.CONTROL)\ .key_down("t")\ .key_up(Keys.CONTROL) \ .key_up("t") \ .perform() or driver.find_element_by_tag_name("body").send_keys(Keys.CONTROL + "t") Only this works: driver.execute_script("window.open()") driver.switch_to.window(driver.window_handles[1]) Can anyone present a better working solution without a need to use JavaScript features?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90710496
tagged with: python
has comment: http://stackoverflow.com/comment/90866213
answer count: 0
linked to: http://stackoverflow.com/q/28431765
score: 0
tagged with: selenium
has title: Cannot open a new tab using Firefox WebDriver
type: Question
has comment: http://stackoverflow.com/comment/90710240
tagged with: firefox
has comment: http://stackoverflow.com/comment/121636172

http://stackoverflow.com/comment/90634629
type: AnswerComment
score: 0
type: Comment
has text: @DebadriDutta - Check edited answer.
comment on: http://stackoverflow.com/a/51840474

http://stackoverflow.com/comment/90851692
type: Comment
type: QuestionComment
score: 0
has text: What you've done is exactly how you do it, except that you don't need to first call `forget_grid` (which doesn't exist), or `grid_forget` (which exists, but unnecessary in this case). You simply need to call the `grid` method on the widget and give it new coordinates.
comment on: http://stackoverflow.com/q/51949536

http://stackoverflow.com/a/51811884
score: 15
upvote count: 15
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51808229
has comment: http://stackoverflow.com/comment/116291083
type: Answer
answers question: http://stackoverflow.com/q/51808229
has comment: http://stackoverflow.com/comment/110226576
has body: According to Agile_Eagle's suggestion from the comments I just uninstalled pyqt5 and pyqt5-tools packages and the reinstalled them. Problem solved! PS.: If you still got problems with PyQt, try uninstalling all of the PyQt related libraries: pip uninstall PyQt5 pip uninstall PyQt5-sip pip uninstall PyQtWebEngine Then install them again, this will fix: ModuleNotFoundError: No module named 'PyQt5.sip' ModuleNotFoundError: No module named 'PyQt5.QtWebEngineWidgets' PPS.:If you got problems uninstalling the libraries, go to your Python folder, like C:\Users\&lt;USERNAME&gt;\AppData\Local\Programs\Python\Python&lt;PYTHON-VERSION&gt;\Lib\site-packages and manually delete the PyQt folders, then uninstall everything and install again (Make sure you have the latest Python version and upgraded your pip too)

http://stackoverflow.com/comment/135449714
type: Comment
score: 1
has text: don't use the variable name `len` for the length. It is a builtin function name.
type: AnswerComment
comment on: http://stackoverflow.com/a/58885306

http://stackoverflow.com/comment/90588829
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51817237
score: 0
has text: Have you tried `return (errors, 400)`?

http://stackoverflow.com/q/51897708
linked to: http://stackoverflow.com/q/2464959
has body: I have the following pandas dataframe df: Description Code 0 Apples 014 1 Oranges 015 2 Bananas 017 3 Grapes 021 I need to convert it to a tuple of tuples, like this: my_fruits = ( ('Apples', '014'), ('Oranges', '015'), ('Bananas', '017'), ('Grapes', '021') ) Can you help me, please? I have tried the following code but it does not return what I really want: list(zip(df.columns,df.T.values.tolist())) Thanks in advance!!!
upvote count: 8
type: Question
has answer: http://stackoverflow.com/a/51897781
linked to: http://stackoverflow.com/q/1207457
tagged with: tuples
answer count: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/74392479
score: 8
favorite count: 0
downvote count: 0
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51897843
has title: Convert pandas dataframe to tuple of tuples
tagged with: dataframe

http://stackoverflow.com/a/51846730
type: Answer
accepted answer of: http://stackoverflow.com/q/51846590
answers question: http://stackoverflow.com/q/51846590
has comment: http://stackoverflow.com/comment/90651596
score: 7
upvote count: 7
has comment: http://stackoverflow.com/comment/90646783
has comment: http://stackoverflow.com/comment/90646932
has comment: http://stackoverflow.com/comment/90647411
has body: You can reverse the keys and the values, then obtain the key with the minimum value: a = {0: {0: 7, 1: 2, 2: 5}, 1: {0: 3, 1: 10, 2: 10}} dict(zip(a[0].values(),a[0].keys())).get(min(a[0].values())) here we create a new dictionary whose keys and values are the reverse of the original dictionary. eg dict(zip(a[0].values(),a[0].keys())) Out[1575]: {7: 0, 2: 1, 5: 2} Then from here, we obtain the minimum value in the original dictionary and use that as the key in this reversed dictionary EDIT As indicated in the comments, one can simply use the key within the min function: min(a[0],key = a[0].get)
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/51864040
type: Question
has answer: http://stackoverflow.com/a/51864110
has answer: http://stackoverflow.com/a/51864120
has comment: http://stackoverflow.com/comment/90680313
score: 0
has body: if __name__ == '__main__': strSize = input() inpt = input() strArrSize = strSize.split() if (len(strArrSize) ==2): n = strArrSize[0] m = strArrSize[1] inptArray = inpt.split() print(n) print(len(inptArray)) if (n == len(inptArray)): print("true") else: print("Given " + str(n) + " integers but entered " + str(len(inptArray))) else: print("Invalid itnput. The first line must have two space seperated integers.") Here is the input and output I got. PS S:\Study\CH1> python tt.py 1 2 1 1 1 Given 1 integers but entered 1
answer count: 3
has title: Python - comparing numbers. I am comparing 1 with 1 but it is failing - please see code - Can anyone tell me what is the issue?
has comment: http://stackoverflow.com/comment/90680276
tagged with: relational-operators
has answer: http://stackoverflow.com/a/51864125
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90680307
has comment: http://stackoverflow.com/comment/90681213

http://stackoverflow.com/comment/90615936
has text: @coder80 did you make any progress with your program?
type: Comment
comment on: http://stackoverflow.com/q/51827374
score: 0
type: QuestionComment

http://stackoverflow.com/q/51865950
answer count: 2
has title: How to merge 2 data frames?
tagged with: pandas
possible better answer: http://stackoverflow.com/a/51866599
tagged with: python
has answer: http://stackoverflow.com/a/51866599
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51867137
has comment: http://stackoverflow.com/comment/90684351
score: 0
has comment: http://stackoverflow.com/comment/90684329
has comment: http://stackoverflow.com/comment/90684419
type: Question
has comment: http://stackoverflow.com/comment/90684295
has body: I have this table1: A B C D 0 1 2 k l 1 3 4 e r df.dtypes gets me this: A int64 B int64 C object D object Now, I want to create a table2 which only includes objects (column C and D) using this command table2=df.select_dtypes(include=[object]). Then, I want to encode table2 using this command pd.get_dummies(table). It gives me this table2: C D 0 0 1 1 1 0 The last thing I want to do is append both tables together (table 1 + table 2), so that the final table looks like this: A B C D 0 1 2 0 1 1 3 4 1 0 Can somebody help?
has comment: http://stackoverflow.com/comment/90684298
tagged with: dataframe
has comment: http://stackoverflow.com/comment/90684256
accepted answer: http://stackoverflow.com/a/51867137

http://stackoverflow.com/q/51821498
type: AnsweredQuestion
tagged with: pyqt5
upvote count: 1
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51824712
score: 0
has body: I'm trying to make a player for a custom file in PyQT5 and I have a set of images that I want to render in a PyQt widget one after another so I can play it as a continious video. So my question is how can I do something like that? Some code example or a guide would be great. Thank you. EDIT: class Example(QMainWindow): def __init__(self): super().__init__() self.scene = QGraphicsScene() self.pixmap = QGraphicsPixmapItem() self.scene.addItem(self.pixmap) self.initUI().graphicsView.setScene(self.scene) self.initUI() def initUI(self): graphicsView = QGraphicsView() self.setGeometry(300, 300, 300, 200) self.setWindowTitle('Test') self.show()
answer count: 1
accepted answer: http://stackoverflow.com/a/51824712
favorite count: 0
has title: PyQt5 changing images
tagged with: python

http://stackoverflow.com/q/51955547
type: AnsweredQuestion
score: 6
has answer: http://stackoverflow.com/a/51957123
type: Question
has title: How do I add an extra field in Django Admin?
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/51957123
favorite count: 0
tagged with: django
tagged with: python
has body: I'm just starting out with Django and I've just revamped my project so that instead of using the base user, I use an AbstractUser model, as defined in my models.py folder #accounts/models.py from django.contrib.auth.models import AbstractUser from django.db import models class CustomUser(AbstractUser): # add additional fields in here favourite_colour = models.CharField("Favourite Colour", max_length=100) def __str__(self): return self.email I've also created the creation forms that work well with my signup system #accounts/forms.py from django.contrib.auth.forms import UserCreationForm, UserChangeForm from django.contrib.auth.models import User from django import forms from .models import CustomUser class CustomUserCreationForm(UserCreationForm): class Meta(UserCreationForm.Meta): model = CustomUser fields = ('username', 'email', 'favourite_colour') help_texts = { 'username': 'Make something unique', 'email': None, } class CustomUserChangeForm(UserChangeForm): class Meta: model = CustomUser fields = ('username', 'email', 'favourite_colour') And now I am trying to edit the admin page so that I can change a users favourite_colour attribute. So far I have this in my admin.py file #accounts/admin.py from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .forms import CustomUserCreationForm, CustomUserChangeForm from .models import CustomUser class CustomUserAdmin(UserAdmin): add_form = CustomUserCreationForm form = CustomUserChangeForm model = CustomUser list_display = ['username', 'email', 'favourite_colour'] admin.site.register(CustomUser, CustomUserAdmin) Which shows me the favourite_colour of each user My question is, how do I make a field to edit this CustomUser attribute once you've clicked on a user?, for example like this I'd welcome any help at all as I'm not too good at reading the docs. Please ask if you need more code adding to the question, I've never asked a Django question before
linked to: http://stackoverflow.com/q/15012235
upvote count: 6

http://stackoverflow.com/q/51894591
score: 1
has body: I'm trying to apply a text sorting algorithm and unfortunately I have an error import sklearn import numpy as np from sklearn import svm from sklearn.pipeline import Pipeline from sklearn.model_selection import train_test_split from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfTransformer from sklearn.metrics import precision_recall_fscore_support as score from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.multiclass import OneVsRestClassifier from sklearn.metrics import accuracy_score from sklearn import metrics from sklearn.metrics import confusion_matrix from sklearn.metrics import precision_recall_fscore_support import pandas as pd import pandas dataset = pd.read_csv('train.csv', encoding = 'utf-8') data = dataset['data'] labels = dataset['label'] X_train, X_test, y_train, y_test = train_test_split (data.data, labels.target, test_size = 0.2, random_state = 0) vecteur = CountVectorizer() X_train_counts = vecteur.fit_transform(X_train) tfidf = TfidfTransformer() X_train_tfidf = tfidf_transformer.fit_transform(X_train_counts) clf = MultinomialNB().fit(X_train_tfidf, y_train) #SVM clf = svm.SVC(kernel = 'linear', C = 10).fit(X_train, y_train) print(clf.score(X_test, y_test)) I have the following error: Traceback (most recent call last): File "bayes_classif.py", line 22, in dataset = pd.read_csv('train.csv', encoding = 'utf-8') File "/usr/local/lib/python3.6/dist-packages/pandas/io/parsers.py", line 678, in parser_f return _read(filepath_or_buffer, kwds) File "/usr/local/lib/python3.6/dist-packages/pandas/io/parsers.py", line 446, in _read data = parser.read(nrows) File "/usr/local/lib/python3.6/dist-packages/pandas/io/parsers.py", line 1036, in read ret = self._engine.read(nrows) File "/usr/local/lib/python3.6/dist-packages/pandas/io/parsers.py", line 1848, in read data = self._reader.read(nrows) File "pandas/_libs/parsers.pyx", line 876, in pandas._libs.parsers.TextReader.read File "pa…
type: Question
has title: Error in classifying SVM texts
has comment: http://stackoverflow.com/comment/90740207
upvote count: 1
answer count: 1
downvote count: 0
tagged with: scikit-learn
tagged with: pandas
has comment: http://stackoverflow.com/comment/90739782
tagged with: python
has answer: http://stackoverflow.com/a/51895936
favorite count: 0
accepted answer: http://stackoverflow.com/a/51895936
has comment: http://stackoverflow.com/comment/90739702
tagged with: python-3.x
linked to: http://stackoverflow.com/q/18039057
has comment: http://stackoverflow.com/comment/90740715
type: AnsweredQuestion

http://stackoverflow.com/a/51853724
answers question: http://stackoverflow.com/q/51853545
score: 0
type: Answer
has body: jq '.[] | select( .filterkey == "filtervalue") | to_entries[1]| .key' sample.json Select by filterkey, turn the objects into key value entires, then take the second entry's key. Output is: "key1"

http://stackoverflow.com/comment/90722589
score: 0
has text: You can create an array and then add each occurrence of the string
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/51882835

http://stackoverflow.com/comment/90862129
has text: Can you edit your post with the code that you tried and I will take a look?
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/51954737
score: 0

http://stackoverflow.com/comment/91036048
type: Comment
has text: hey, i just got this error: AttributeError: 'module' object has no attribute 'APIError'. How do I fix this ? please help !!
comment on: http://stackoverflow.com/a/51935450
score: 0
type: AnswerComment

http://stackoverflow.com/q/51840604
type: Question
has answer: http://stackoverflow.com/a/56429865
tagged with: manova
upvote count: 1
has comment: http://stackoverflow.com/comment/90635946
downvote count: 0
answer count: 1
favorite count: 0
type: UnansweredQuestion
has title: Statsmodels MANOVA : IndexError: index 1 is out of bounds for axis 0 with size 1
tagged with: python
tagged with: statsmodels
has body: I have spent hours trying to make statsmodels do my MANOVA without success. Here is the code: from statsmodels.multivariate.manova import MANOVA df = data feats_list = ['col1', 'col2', 'col3' ... 'col4'] var_list = ['col5', 'col6'] endog, exog = np.asarray(df[feats_list]), np.asarray(df[var_list]) manov = MANOVA(endog, exog) manov.mv_test() Providing: --------------------------------------------------------------------------- IndexError Traceback (most recent call last) &lt;ipython-input-16-c3fc1d1f16f6&gt; in &lt;module&gt;() 1 manov = MANOVA(endog, exog) ----&gt; 2 manov.mv_test() ~\Anaconda3\lib\site-packages\statsmodels\multivariate\manova.py in mv_test(self, hypotheses) 68 name = 'x%d' % (i) 69 L = np.zeros([1, self.exog.shape[1]]) ---&gt; 70 L[i] = 1 71 hypotheses.append([name, L, None]) 72 IndexError: index 1 is out of bounds for axis 0 with size 1 I tried also to put the hypotheses by myself and I always get a SingularMatrixError so I suppose that I am not using the class correctly. Thanks in advance for your help.
has comment: http://stackoverflow.com/comment/90636020
has comment: http://stackoverflow.com/comment/90636419
score: 1

http://stackoverflow.com/comment/90570532
comment on: http://stackoverflow.com/a/51805852
type: Comment
has text: @jdtaylor7 Do you have a default `CFLAGS` in your gcc setup or bash profile or elsewhere?
score: 0
type: AnswerComment

http://stackoverflow.com/comment/90829498
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51939764
has text: change `helper(a)` to `Solution.helper(a)` and add `@staticmethod` over `def helper(...)`

http://stackoverflow.com/comment/90684839
comment on: http://stackoverflow.com/q/51865766
score: 0
type: Comment
type: QuestionComment
has text: I think [this answer](https://stackoverflow.com/questions/32485907/matplotlib-and-numpy-create-a-calendar-heatmap/32492179#32492179) is a great starting point.

http://stackoverflow.com/comment/90609117
comment on: http://stackoverflow.com/a/51827332
score: 1
type: AnswerComment
has text: @tgikal On my Windows system (which isn't Windows 10), there's one `calc.exe` no matter how many windows it has open (and even if you close the last window, it doesn't always go away). Meanwhile, the OP reports that in his Windows 10 system, there is no `calc.exe` in the Task Manager, only `calculator.exe`. Either way, killing the process he started isn't going to do any good.
type: Comment

http://stackoverflow.com/comment/90859456
comment on: http://stackoverflow.com/q/51954234
score: 0
has text: Is your gerrit configured to use basic auth?
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51844279
answers question: http://stackoverflow.com/q/51844209
has body: I an guessing height is an int. What your script does is that it returns a list of all distinct values from 0 to 'height' , height not included, that do not appear in your array.
score: 0
type: Answer

http://stackoverflow.com/comment/90805714
type: Comment
comment on: http://stackoverflow.com/a/51927865
has text: @tobias_k Agreed, have deleted the code snippet, it wasn't that relevant anyway
type: AnswerComment
score: 0

http://stackoverflow.com/q/51868433
has title: How to make a python file using a previous version?
has body: I have Python 3.7 installed, and want to make an .exe out of it, so I'm trying to make a 3.6.5 file so pyinstaller will work on it. How can I make it so the version of python the file uses is 3.6.5 and not 3.7(my default). When I type python in cmd it goes in 3.7. When I type python --version, it says 3.7. Keep in mind, I typed all of this in the directory of where 3.6.5 is. 3.7 is installed on my C though, while 3.6.5 is installed in my programs/local/python directory. What should I do?
score: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51868484
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/90688936
tagged with: python-3.6
has comment: http://stackoverflow.com/comment/90688856
tagged with: python-3.7
has answer: http://stackoverflow.com/a/51868492
tagged with: pyinstaller
has comment: http://stackoverflow.com/comment/90688734
tagged with: python
tagged with: exe

http://stackoverflow.com/q/51860592
has answer: http://stackoverflow.com/a/51860623
has answer: http://stackoverflow.com/a/51862391
favorite count: 0
tagged with: python-3.x
tagged with: python
has title: Pandas Dataframe replace values in a Series
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51860623
type: Question
has comment: http://stackoverflow.com/comment/90673680
score: 4
has body: I am trying to update my_df based on conditional selection as in: my_df[my_df['group'] == 'A']['rank'].fillna('A+') However, this is not persistence ... e.g: the my_df still have NaN or NaT ... and I am not sure how to do this in_place. Please advise on how to persist the the update to my_df.
upvote count: 4
possible better answer: http://stackoverflow.com/a/51860629
answer count: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/51860629
downvote count: 0

http://stackoverflow.com/comment/90729972
type: Comment
has text: Thanks worked perfectly. I don't understand why it would matter. I thought stock.set("") would clear it each time and it would then overwrite it.
type: AnswerComment
comment on: http://stackoverflow.com/a/51889220
score: 0

http://stackoverflow.com/a/51922742
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/51922622
score: 1
has body: Seems like you need cummin and a simple loc df['cummin_'] = df.groupby('ID').value.cummin() df['condition'] = df.value &gt;= df.cummin_ + 2 ID value cummin_ condition 0 1 0.6 0.6 False 1 1 1.5 0.6 False 2 1 1.6 0.6 False 3 1 1.2 0.6 False 4 1 2.8 0.6 True 5 1 0.3 0.3 False 6 1 0.2 0.2 False Another option is to use expanding. Take, for example, df = pd.DataFrame({'ID': [1,1,1,1,1,1,1,2,2], 'value': [0.6, 1.5, 1.6, 1.2, 2.8, 0.3, 0.2,0.4,2.9]}) Then df.groupby('ID').value.expanding(2).min() ID 1 0 NaN 1 0.6 2 0.6 3 0.6 4 0.6 5 0.3 6 0.2 2 7 NaN 8 0.4 The expanding function yields your NaNs at first while cummin accounts for the first value. Just a matter of understanding how you want results to be interpreted.
has comment: http://stackoverflow.com/comment/90795283
accepted answer of: http://stackoverflow.com/q/51922622
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/51864477
type: Question
tagged with: anaconda
has answer: http://stackoverflow.com/a/51864524
has comment: http://stackoverflow.com/comment/90681094
tagged with: conda
accepted answer: http://stackoverflow.com/a/51864524
has comment: http://stackoverflow.com/comment/90681135
answer count: 2
has title: Transfer Pip packages to conda
downvote count: 0
favorite count: 0
tagged with: python-3.x
upvote count: 8
tagged with: python
linked to: http://stackoverflow.com/q/35802939
score: 8
type: AnsweredQuestion
has body: I am currently using a shared Ubuntu machine which has python2.7 and multiple packages installed via pip. $ python --version Python 2.7.12 $ pip --version pip 18.0 from /usr/local/lib/python2.7/dist-packages/pip (python 2.7) $ pip list Package Version ---------------------------------- ----------- asn1crypto 0.24.0 awscli 1.11.101 backports-abc 0.5 ... .. . I want to install conda and have Python 2.7 and Python 3.6 environment. How can I install all the packages currently installed (pip list) in both conda env (2.7 and 3.6) ? I am not concerned with package version. Fine to install the same version or latest version for each package.
has comment: http://stackoverflow.com/comment/90681113
possible better answer: http://stackoverflow.com/a/59822823
tagged with: pip
has answer: http://stackoverflow.com/a/59822823

http://stackoverflow.com/comment/90722952
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51885673
has text: But that only gets me the corresponding number after each date traversed.

http://stackoverflow.com/q/51940708
favorite count: 0
tagged with: oracle-database
tagged with: python
has answer: http://stackoverflow.com/a/51940841
score: 1
has title: Trying to call pl/sql function in python but receiving ORA-01858 error with to_date
upvote count: 1
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51940841
type: Question
has body: I am trying to call a pl/sql function using python. I am having issues using the 'to_date()' built in function. Here is the "create_batch" function declaration create or replace function create_batch( p_batchnumber in VARCHAR, p_userid in VARCHAR, p_received_date in VARCHAR, p_workstation IN VARCHAR ) RETURN VARCHAR IS This is the line of coding I am trying to use to call this function. batch_id = cur.callfunc("create_batch", cx_Oracle.STRING, ['100001','test','to_date(\'05/15/2018\',\'MM/dd/yyyy\')','01']) This is the error message. File "test_oracle.py", line 7, in &lt;module&gt; batch_id = cur.callfunc("create_batch", cx_Oracle.STRING, ['100001','test','to_date(\'05/15/2018\',\'MM/dd/yyyy\')','01']) cx_Oracle.DatabaseError: ORA-01858: a non-numeric character was found where a numeric was expected ORA-06512: at "CFT.CREATE_BATCH", line 10 ORA-06512: at line 1 Any help that you could provide would be much appreciated! Thanks!
answer count: 1
downvote count: 0

http://stackoverflow.com/q/51859070
answer count: 2
has comment: http://stackoverflow.com/comment/90670728
has body: Consider the following data set, Name Age Grade Person1 18 50 Person2 19 100 Person3 20 0 Person4 21 -25 Person5 22 -125 Person6 23 80 Person7 24 -70 If I wanted to group together the students based on the aggregation of their grades, how would I go about it? What I mean is - I want to make groups of students such as the sum of the grades of all the students in that grade is 0 or as close to zero as possible. So, ideally - the answer to the dataset would be something like - Group 1 ----> Person1, Person2, Person4, Person5 (because their added grades are 0) Group 2 ----> Person3 (because the grade is 0) Group 3 ----> Person6, Person7 (because the added sum is 10) How I went on about approaching this was - new_dt = pd.read_csv('../tt.csv') a = list(itertools.chain.from_iterable( [[j for i in el for j in i] for el in itertools.combinations(new_dt.values.tolist(),i)] for i in range(1, len(new_dt)+1) ) ) out = pd.DataFrame(a) So, basically I am finding out all the possible combinations using itertools.combinations 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 0 Person1 18 50 1 Person2 19 100 2 Person3 20 0 3 Person4 21 -25 4 Person5 22 -125 5 Person6 23 80 6 Person7 24 -70 7 Person1 18 50 Person2 19 100 8 Person1 18 50 Person3 20 0 9 Person1 18 50 Person4 21 -25 10 Person1 18 50 Person5 22 -125 11 Person1 18 50 Person6 23 80 12 Person1 18 50 Person7 24 -70 13 Person2 19 100 Person3 20 0 14 Person2 19 100 Person4 21 -25 15 Person2 19 100 Person5 22 -125 16 Person2 19 100 Person6 23 80 17 Person2 19 100 Person7 24 -70 18 Person3 20 0 Person4 21 -25 19 Person3 20 0 Person5 22 -125 20 Person3 20 0 Person6 23 80 21 Person3 20 0 Person7 24 -70 22 Person4 21 -25 Person5 22 -125 23 Person4 21 -25 Person6 23 80 24 Person4 21 -25 Person7 24 -70 25 Person5 22 -125 Person6 23 80 26 Person5 22 -125 Person7 24 -70 27 Person6 23 80 Person7 24 -70 28 Person1 18 50 Person2 19 100 Person3 20 0 29 Person1 18 50 Person2 19 100 Person4 21 -25 30 Person1 18 50 Person2 19 100 Person5 22…
favorite count: 0
has comment: http://stackoverflow.com/comment/90672144
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90673125
has comment: http://stackoverflow.com/comment/90711672
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90673256
tagged with: python
has comment: http://stackoverflow.com/comment/90673394
has title: Python - Group combinations based on condition
score: 3
tagged with: mathematical-optimization
downvote count: 0
has comment: http://stackoverflow.com/comment/90692036
type: Question
tagged with: combinations
tagged with: python-itertools
has comment: http://stackoverflow.com/comment/90670857
has answer: http://stackoverflow.com/a/51860598
has answer: http://stackoverflow.com/a/51860720
upvote count: 3

http://stackoverflow.com/q/51905686
has answer: http://stackoverflow.com/a/51905730
tagged with: python-3.x
type: Question
linked to: http://stackoverflow.com/q/5893163
tagged with: python
score: 4
duplicate of: http://stackoverflow.com/q/5893163
has body: Can someone please point out what the point of assigning the result(s) of a plot to a dummy variable _ is like so: _ = plt.plot(x_vers, y_vers, marker = '.', linestyle = 'none') Usually I see code like this: plt.plot(x_vers, y_vers, marker = '.', linestyle = 'none') Is it better practice to use the dummy _ even if it is never used? if so, why?
has title: assign results to dummy variable _
accepted answer: http://stackoverflow.com/a/51905730
answer count: 1
has comment: http://stackoverflow.com/comment/90762100
upvote count: 4
type: AnsweredQuestion
downvote count: 0
favorite count: 0

http://stackoverflow.com/a/51942121
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51941830
has body: Maybe you could write a single command that can be executed once and it does the whole job. cd desktop/reference/django/mel &amp;&amp; python3 manage.py runserver This is not a python script, but you can achieve what you want easily with this.

http://stackoverflow.com/q/51907813
tagged with: deep-learning
answer count: 1
has title: Tensorflow does not learn
has body: The code: import numpy as np import tensorflow as tf import pandas as pd from sklearn.model_selection import train_test_split x_data = np.linspace(0, 1000, 100000) y_true = np.square(x_data) y_true += np.random.randn(len(x_data)) feature_columns = [tf.feature_column.numeric_column('x', shape=[1])] estimator = tf.estimator.DNNRegressor(feature_columns=feature_columns, hidden_units=[2, 2], optimizer=lambda: tf.train.AdamOptimizer( learning_rate=0.001 )) X_train, X_test, y_train, y_test = train_test_split(x_data, y_true, test_size=0.3) input_function = tf.estimator.inputs.numpy_input_fn({'x': X_train},y_train, batch_size=20, num_epochs=10000, shuffle=True) train_input_function = tf.estimator.inputs.numpy_input_fn({'x': X_train},y_train, batch_size=8, num_epochs=10000, shuffle=False) test_input_function = tf.estimator.inputs.numpy_input_fn({'x': X_test},y_test, batch_size=8, num_epochs=10000, shuffle=False) estimator.train(input_fn=input_function, steps=1000) train_metrics = estimator.evaluate(input_fn=train_input_function, steps=1000) test_metrics = estimator.evaluate(input_fn=test_input_function, steps=1000) print('TRAINING DATA METRICS') print(train_metrics) print() print('TEST DATA METRICS') print(test_metrics) print() ### new_data = np.linspace(0, 1000, 10) input_function_predict = tf.estimator.inputs.numpy_input_fn({'x':new_data}, shuffle=False) print(list(estimator.predict(input_fn=input_function_predict))) Gives the following output: TRAINING DATA METRICS {'average_loss': 200498430000.0, 'label/mean': 332774.78, 'loss': 1603987400000.0, 'prediction/mean': 0.97833574, 'global_step': 1000} TEST DATA METRICS {'average_loss': 197508330000.0, 'label/mean': 332257.22, 'loss': 1580066700000.0, 'prediction/mean': 0.97833574, 'global_step': 1000} [{'predictions': array([0.9783435], dtype=float32)}, {'predictions': array([0.9783435], dtype=float32)}, {'predictions': array([0.9783435], dtype=float32)}, {'predictions': array([0.9783435], dtype=float32)}, {'predictions': arr…
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51908969
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/90767731
has comment: http://stackoverflow.com/comment/90767919
tagged with: loss
tagged with: neural-network
linked to: http://stackoverflow.com/q/39921607
score: 0

http://stackoverflow.com/comment/90790326
type: Comment
type: QuestionComment
score: 0
has text: @Goyo, I did not understand what do you mean. You mean that we cannot show such image resolution using plt.imshow() ?
comment on: http://stackoverflow.com/q/51919953

http://stackoverflow.com/q/51846057
upvote count: 2
tagged with: python
has body: I have a file that contains: a[0 a[1 a[2 a[3 a[4 a[5 a[6 a[7 a[8 \ a[9 a[10 a[11 a[12 a[13 a[14 a[15 a[16 \ a[17 a[18 a[19 a[20 a[21 a[22 a[23 a[24 \ a[25 a[26 a[27 a[28 a[29 a[30 a[31 b[0 b[1 \ b[2 b[3 b[4 b[5 b[6 b[7 b[8 b[9 b[10 \ b[11 b[12 b[13 b[14 b[15 b[16 b[17 b[18 \ b[19 b[20 b[21 b[22 b[23 b[24 b[25 b[26 \ b[27 b[28 b[29 b[30 b[31 I want to insert a closing bracket for each variable. The numbers can grow for future variables. How can we do it using regex?
tagged with: regex
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51846128
downvote count: 2
possible better answer: http://stackoverflow.com/a/51846105
has answer: http://stackoverflow.com/a/51846105
type: Question
has answer: http://stackoverflow.com/a/51846098
tagged with: python-2.7
score: 0
has title: Insert a closing bracket for variables using RegEx
answer count: 3
favorite count: 0
accepted answer: http://stackoverflow.com/a/51846098

http://stackoverflow.com/a/51943902
answers question: http://stackoverflow.com/q/51942250
score: 0
has body: I would suggest you create a class with static methods: class Fibonacii(object): def __init__(self): # this is the constructor you can initialize stuff here if required # if not just pass it like in this example pass @staticmethod def fib(n): if n&lt;=1: return n else: return (Fibonacii.fib(n-1) + Fibonacii.fib(n-2)) @staticmethod def facts(n): if n == 0 or n == 1: return 1 if n&gt;=1: return n * Fibonacii.facts(n-1) static method have the advantage that they can be used without creating an object of that class. So in your script you can do: if __name__ == "__main__": n = int(input("Enter number of terms:")) print("Fibonacii series are: ") for i in range (n): print(Fibonacii.fib(i)) #for factorial n=int(input("Enter the no to find factorial: ")) print("The facatorial of a given no",str(n),"is:",Fibonacii.facts(n)) The part after main is the part of the script that is being executed if it is the main script. Notice that the class is never used to create a object. But it is used to save your two functions and can be used to call them.
type: Answer

http://stackoverflow.com/a/51895597
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51895326
score: 5
type: Answer
has body: cursor.execute() returns a vendor-defined value (it's not specified in the db-api spec), and for pyscopg2 it is actually documented as returning None indeed, so this: def query_database(self, sql_statement, *args): return self.my_cursor.execute(sql_statement, *args) def fetch_one(self, sql_statement, *args): result = self.query_database(sql_statement, *args) if result is None: return False return result.fetchone() will obviously not work as you expect. You could return self.my_cursor() from query_database() instead, ie: def query_database(self, sql_statement, *args): self.my_cursor.execute(sql_statement, *args) return self.my_cursor def fetch_one(self, sql_statement, *args): cursor = self.query_database(sql_statement, *args) return cursor.fetchone() but there's a fundamental flaw with this code, which is that it's not reentrant (nor thread safe FWIW). Actually, your class should NOT store a cursor as part of it's state and reuse it over and over (db-api cursors are not meant to be used that way) but create a new cursor for every operation (which is the indented use). Also, you should not rely on __del__(self) to close your connection. The __del__() method is not a proper C++/Java style finalizer and is not even garanteed to be called when the object is collected. Actually, trying to wrap a db connection and cursor in a class is usually not a good idea, at least not this way.
upvote count: 5
answers question: http://stackoverflow.com/q/51895326
type: AcceptedAnswer

http://stackoverflow.com/q/51862572
tagged with: sqlalchemy
accepted answer: http://stackoverflow.com/a/51863204
type: Question
answer count: 1
has comment: http://stackoverflow.com/comment/90677524
downvote count: 0
has comment: http://stackoverflow.com/comment/90677512
tagged with: flask
tagged with: flask-sqlalchemy
upvote count: 7
tagged with: python
favorite count: 0
has body: I have two tables( location and country ) that am trying to query; which are represented by the models below in my flask application from sqlalchemy import Column, DateTime, ForeignKey, Integer, \ Numeric, SmallInteger, String, Table from sqlalchemy.orm import relationship from sqlalchemy.schema import FetchedValue from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() class Country(db.Model): __tablename__ = 'country' country_id = db.Column(db.Integer, primary_key=True) country_name = db.Column(db.String(30), nullable=False) full_country_name = db.Column(db.String(90), nullable=False) country_code = db.Column(db.String(4), nullable=False) def __str__(self): return '%s' % self.country_name def __repr__(self): return '&lt;Country %r&gt;' % self.country_name class Location(db.Model): __tablename__ = 'location' location_id = db.Column(db.Integer, primary_key=True) location_name = db.Column(db.String(75), nullable=False) country_id = db.Column(db.ForeignKey('mashamba.country.country_id'), nullable=False, index=True) country = db.relationship('Country', primaryjoin='Location.country_id == Country.country_id', backref='locations') def __str__(self): return '%s' % self.location_name def __repr__(self): return '&lt;Location %r&gt;' % self.location_name What am trying to do is get all columns from both tables by performing a join using the following code Location.query.join(Country).\ filter_by(location_name='Cairo', country_id=67).first() Problem is when i run the code i get the following error sqlalchemy.exc.InvalidRequestError: Entity '&lt;class 'app.models.Country'&gt;' has no property 'location_name' Everything works fine when you run for example this code Location.query.join(Country).all() What is wrong here and how can this be solved?
type: AnsweredQuestion
score: 7
has comment: http://stackoverflow.com/comment/90678797
has comment: http://stackoverflow.com/comment/90678092
has title: Filtering after a join in Flask-SQLAlchemy
has answer: http://stackoverflow.com/a/51863204

http://stackoverflow.com/q/51940600
type: AnsweredQuestion
tagged with: audio
upvote count: 0
has comment: http://stackoverflow.com/comment/90843041
has comment: http://stackoverflow.com/comment/90869680
tagged with: tensorflow
type: Question
has body: I've been following the tutorials on how to make a Simple Audio Recognition. First I encountered an error when I entered python tensorflow/examples/speech_commands/freeze.py saying python: can't open file 'tensorflow/examples/speech_commands/freeze.py': [Errno 2] No such file or directory So I just went to the directory of tensorflow then drag the file in cmd... but then I encountered another error saying: "tensorflow.python.framework.errors_impl.UnknownError: FindFirstFile failed for: ./config/systemprofile/AppData/Local/Microsoft/Windows/INetCache/Content.IE5 : Access is denied. ; Input/output error" I'm running it as administrator as you can see here. How can I fix this?
score: -1
has answer: http://stackoverflow.com/a/52005743
accepted answer: http://stackoverflow.com/a/52005743
has title: Tensorflow Simple Audio Recognition Error on Freeze.py
has comment: http://stackoverflow.com/comment/90880005
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/90907741
tagged with: speech-recognition
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90837062
tagged with: python
has comment: http://stackoverflow.com/comment/90879783

http://stackoverflow.com/comment/90640968
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51798916
has text: You probably just installed the package for the wrong version of python. Make sure you are using the right pip. Usually the safest thing to do is to run: sudo python3 -m pip install pandas_datareader if you are trying to install the package for your python3 installation {pip install pandas_datareader}

http://stackoverflow.com/comment/90571866
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51800593
has text: did you check my answer/
score: 0

http://stackoverflow.com/comment/90674907
type: Comment
type: QuestionComment
has text: You can use pandas library it has method called df.to_csv("filename.csv") using which you can save it to csv
comment on: http://stackoverflow.com/q/51861326
score: 0

http://stackoverflow.com/comment/90580714
comment on: http://stackoverflow.com/q/51812913
score: 0
type: QuestionComment
type: Comment
has text: you could also just do a integer loop in the comprehension.

tensorflow
tags question: http://stackoverflow.com/q/51821537
tags question: http://stackoverflow.com/q/51839415
tags question: http://stackoverflow.com/q/51942546
tags question: http://stackoverflow.com/q/51948171
tags question: http://stackoverflow.com/q/51886844
tags question: http://stackoverflow.com/q/51895395
tags question: http://stackoverflow.com/q/51809624
tags question: http://stackoverflow.com/q/51888996
tags question: http://stackoverflow.com/q/51931559
tags question: http://stackoverflow.com/q/51832351
tags question: http://stackoverflow.com/q/51835810
tags question: http://stackoverflow.com/q/51955693
tags question: http://stackoverflow.com/q/51837878
tags question: http://stackoverflow.com/q/51904143
tags question: http://stackoverflow.com/q/51934087
tags question: http://stackoverflow.com/q/51833026
tags question: http://stackoverflow.com/q/51835124
tags question: http://stackoverflow.com/q/51885739
tags question: http://stackoverflow.com/q/51851733
tags question: http://stackoverflow.com/q/51799234
tags question: http://stackoverflow.com/q/51919417
tags question: http://stackoverflow.com/q/51837914
tags question: http://stackoverflow.com/q/51891047
tags question: http://stackoverflow.com/q/51854463
tags question: http://stackoverflow.com/q/51861036
tags question: http://stackoverflow.com/q/51944387
tags question: http://stackoverflow.com/q/51872304
tags question: http://stackoverflow.com/q/51888829
tags question: http://stackoverflow.com/q/51852089
tags question: http://stackoverflow.com/q/51839019
tags question: http://stackoverflow.com/q/51950983
tags question: http://stackoverflow.com/q/51906709
tags question: http://stackoverflow.com/q/51904877
tags question: http://stackoverflow.com/q/51887518
tags question: http://stackoverflow.com/q/51879053
tags question: http://stackoverflow.com/q/51912999
tags question: http://stackoverflow.com/q/51944909
tags question: http://stackoverflow.com/q/51814062
tags question: http://stackoverflow.com/q/51811510
tags question: http://stackoverflow.com/q/51904266
tags question: http://stackoverflow.com/q/51952712
tags question: http://stackoverflow.com/q/51849044
tags question: http://stackoverflow.com/q/51831589
tags question: http://stackoverflow.com/q/51896733
tags question: http://stackoverflow.com/q/51860849
tags question: http://stackoverflow.com/q/51950002
tags question: http://stackoverflow.com/q/51799228
tags question: http://stackoverflow.com/q/51849937
tags question: http://stackoverflow.com/q/51824393
tags question: http://stackoverflow.com/q/51834382
tags question: http://stackoverflow.com/q/51907813
tags question: http://stackoverflow.com/q/51880052
tags question: http://stackoverflow.com/q/51861790
tags question: http://stackoverflow.com/q/51914294
tags question: http://stackoverflow.com/q/51917036
tags question: http://stackoverflow.com/q/51909312
tags question: http://stackoverflow.com/q/51897990
tags question: http://stackoverflow.com/q/51849433
tags question: http://stackoverflow.com/q/51945508
tags question: http://stackoverflow.com/q/51904912
tags question: http://stackoverflow.com/q/51858970
tags question: http://stackoverflow.com/q/51803371
tags question: http://stackoverflow.com/q/51944199
tags question: http://stackoverflow.com/q/51919539
tags question: http://stackoverflow.com/q/51851916
tags question: http://stackoverflow.com/q/51898314
tags question: http://stackoverflow.com/q/51832803
tags question: http://stackoverflow.com/q/51902539
tags question: http://stackoverflow.com/q/51810283
tags question: http://stackoverflow.com/q/51912217
tags question: http://stackoverflow.com/q/51860307
tags question: http://stackoverflow.com/q/51912155
tags question: http://stackoverflow.com/q/51949208
tags question: http://stackoverflow.com/q/51836484
tags question: http://stackoverflow.com/q/51856613
tags question: http://stackoverflow.com/q/51830549
tags question: http://stackoverflow.com/q/51889794
tags question: http://stackoverflow.com/q/51814224
tags question: http://stackoverflow.com/q/51881957
tags question: http://stackoverflow.com/q/51907487

http://stackoverflow.com/q/51868299
type: Question
has comment: http://stackoverflow.com/comment/90688950
answer count: 1
tagged with: neural-network
downvote count: 0
has comment: http://stackoverflow.com/comment/90720694
has comment: http://stackoverflow.com/comment/90688480
favorite count: 0
tagged with: data-analysis
type: UnansweredQuestion
has body: I am trying to have a data set imported for my machine learning model. Data is of images stored as values of pixels of each image. Image size is 48X48. I need to convert this to ndarray but as its space separated so X = data[:, 1].reshape(data.shape[0],1,48, 48).astype( 'float32' ) doesn't work. I need help in converting this data to ndarray of(nX48X48).(n->no. of rows.) EDIT:- I tried, `data=pd.read_csv('../input/fer2013.csv').values X=data[:,1] for i in range(len(X)): X[i]=np.asarray(X[i].split(" "),dtype=np.float32) X[i]=X[i].reshape(1,48,48).astype('float32')` It does not change shape of column. I wish the shape of X to be(n,1,48,48) But doing above keeps the shape to be(n).sample row of data Format of data: pixels column of dataset Thanks and regards,
tagged with: machine-learning
upvote count: 1
tagged with: python
has title: Space seprated values to ndarray
has answer: http://stackoverflow.com/a/51868560
tagged with: conv-neural-network
score: 1

http://stackoverflow.com/comment/90684627
comment on: http://stackoverflow.com/q/51865819
score: 0
type: Comment
type: QuestionComment
has text: Ah ... try `fileout.write(val1 + '\n')`. My apologies -- wrong package.

http://stackoverflow.com/comment/90640003
has text: I visited url and there is nothing about error, at beginning it says that state is accepted and final status undefined and when wc.py breaks state is killed and final status is killed. @cricket_007
comment on: http://stackoverflow.com/q/51841873
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/51830993
type: UnansweredQuestion
tagged with: django
upvote count: 1
tagged with: python
score: 1
has answer: http://stackoverflow.com/a/51831107
type: Question
has title: How to specify typings for dynamic fields similar to django Model/Field?
answer count: 1
downvote count: 0
has body: For example: # field base class class F: pass # represent integer class AF(F): pass # represent string class BF(F): pass class M: a = AF() b = BF() def __init__(self): pass # generate dynamic attrs based on specified static attrs m = M() # m.a should have inferred type integer Maybe it is just IDE (PyCharm) feature with all these type hint, and this feature is hard-bind to django's Model class?
favorite count: 0
tagged with: pycharm

http://stackoverflow.com/comment/90742560
type: Comment
score: 0
comment on: http://stackoverflow.com/q/51889653
has text: till day, i used to enter the values directly into python code, like this ..zone=[4001,4002,4003,4004,4005,4006,4007,4011,4012,4014,4015,4016,4501,4502,4503,4504,4505,4507,4508,4509,4601,4602,4603,4701,4702,4703,4707,4801,4802,4803,4804,4805,4806] fro=[1,3,3,4,5,7,8,8,8,9,11,11,12,12,13,13,14,14,15,16,17,17,18,18,20,22,22,24,24,24,24,24,25] to=[6,3,1,2,1,1,4,10,12,22,8,4,9,21,16,11,21,8,20,14,13,18,16,19,17,23,30,9,23,12,5,28,7] now i want this inputs to be directly taken from txt file or excel.
type: QuestionComment

http://stackoverflow.com/q/51806342
has comment: http://stackoverflow.com/comment/90568230
tagged with: python
has comment: http://stackoverflow.com/comment/90568200
has comment: http://stackoverflow.com/comment/90568276
has answer: http://stackoverflow.com/a/51806933
tagged with: tree
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90568818
upvote count: 1
accepted answer: http://stackoverflow.com/a/51806933
downvote count: 1
has body: I'm having a hell of a hard time trying to figure out why my print(Node(3).value) is printing 0. Any ideas? When I run this code, I get First: 6 Value: 8 Children: [9] First: 8 Value: 23 Children: [9] First: 3 Value: 3 Children: [5] First: 6 Value: 8 Children: [7] First: 4 Value: 20 Children: [8] First: 1 Value: 17 Children: [8] First: 8 Value: 23 Children: [10] First: 5 Value: 11 Children: [8] First: 1 Value: 17 Children: [2] 0 Any ideas? I know I'm not saving the Nodes anywhere but my mind can't wrap around it. Any help would be appreciated, thanks! # Complete the primeQuery function below. n = 10 first = [6, 8, 3, 6, 4, 1, 8, 5, 1] second = [9, 9, 5, 7, 8, 8, 10, 8, 2] values = [17, 29, 3, 20, 11, 8, 3, 23, 5, 15] queries = [1, 8, 9, 6, 4, 3] class Node(object): def __init__(self, data, value=0): self.data = data self.value = value self.children = [] def addChild(self, child): self.children.append(child) def setValue(self, givenV): self.value = givenV def primeQuery(n, first, second, values, queries): i = 0 while i &lt; n - 1: f = Node(first[i], values[first[i] - 1]) s = Node(second[i], values[second[i] - 1]) f.addChild(s.data) print(f"First: {f.data} Value: {f.value} Children: {f.children}") i += 1 print(Node(3).value) primeQuery(n, first, second, values, queries)
has comment: http://stackoverflow.com/comment/90568324
type: Question
has comment: http://stackoverflow.com/comment/90568221
linked to: http://stackoverflow.com/q/1238606
has comment: http://stackoverflow.com/comment/90568226
has title: Save changes of state for custom class instances in Python
score: 0
has comment: http://stackoverflow.com/comment/90568405
answer count: 1
has comment: http://stackoverflow.com/comment/90568237
has comment: http://stackoverflow.com/comment/90568194
linked to: http://stackoverflow.com/q/9158294
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90568391

http://stackoverflow.com/q/51941494
favorite count: 0
upvote count: 1
tagged with: python
type: AnsweredQuestion
tagged with: list
has title: How can I have a function run within another function, but evaluate from different lists in each function?
score: 1
accepted answer: http://stackoverflow.com/a/51942965
type: Question
tagged with: function
has body: I am using one function to do the testing (func1) and the other two functions have different x lists. What I am attempting to do is have the function refer to different x lists for different functions (func2 and func3). Is there anyway func1 can refer to different x lists within func2 and func3. def func1(letter): if letter in x: print True def func2(letter): x = [a,b,c,d,e] return func1 def func2(letter): x = [e,d,c,b,a] return func2
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/90832618
has answer: http://stackoverflow.com/a/51942965

http://stackoverflow.com/comment/90808424
type: Comment
type: AnswerComment
has text: @max9111 thanks, not an expert on the computational nuts and bolts at the memory bandwidth level. Is there a reason you changed the OP's `V()` function to include `(dist_rel +1)` instead of just `dist_rel`? I maintained it becasue I wasn't sure what would happen if I didn't.
score: 0
comment on: http://stackoverflow.com/a/51926953

http://stackoverflow.com/q/51813991
tagged with: dataframe
has comment: http://stackoverflow.com/comment/90582756
type: Question
upvote count: 2
answer count: 2
has body: It was hard for me to come up with clear title but an example should make things more clear. Index C1 1 [dinner] 2 [brunch, food] 3 [dinner, fancy] Now, I'd like to create a set of binary features for each of the unique values in this column. The example above would turn into: Index C1 dinner brunch fancy food 1 [dinner] 1 0 0 0 2 [brunch, food] 0 1 0 1 3 [dinner, fancy] 1 0 1 0 Any help would be much appreciated.
linked to: http://stackoverflow.com/q/29034928
has answer: http://stackoverflow.com/a/51814215
has title: Python - Attempting to create binary features from a column with lists of strings
tagged with: pandas
tagged with: python
has answer: http://stackoverflow.com/a/51814028
favorite count: 0
linked to: http://stackoverflow.com/q/11587782
downvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90582749
score: 2
has comment: http://stackoverflow.com/comment/90582741

http://stackoverflow.com/q/51928627
has comment: http://stackoverflow.com/comment/90807063
tagged with: python-unittest
has comment: http://stackoverflow.com/comment/90814343
downvote count: 1
accepted answer: http://stackoverflow.com/a/51931628
type: Question
upvote count: 0
score: -1
tagged with: flask
answer count: 1
has comment: http://stackoverflow.com/comment/90812880
favorite count: 0
has comment: http://stackoverflow.com/comment/90807544
tagged with: python
has body: I have a structure like this: flask_api api __init__.py tests test_base.py manage.py In init.py: def create_app(): connexion_app = connexion.App(__name__, specification_dir='swagger/') connexion_app.add_api('output.yaml', resolver=RestyResolver('api'), validate_responses=True) app = connexion_app.app CORS(app) app.register_blueprint(utils) ... return app In manager.py: from api import create_app app = create_app() manager = Manager(app) @manager.command def test(): print(app.root_path) tests = unittest.TestLoader().discover( 'api/tests', pattern='test*.py' ) result = unittest.TextTestRunner(verbosity=2).run(tests) if result.wasSuccessful(): return 0 return 1 if __name__ == '__main__': manager.run() and in test_base.py: from flask_api import app Now, when I run python menage.py test I get the error: File "/home/flask_api/api/tests/test_base.py", line 7, in &lt;module&gt; from flask_api import app ModuleNotFoundError: No module named 'flask_api How can I import app into the test_base?
has comment: http://stackoverflow.com/comment/90807107
has comment: http://stackoverflow.com/comment/90813083
type: AnsweredQuestion
has title: Can not import flask app
has answer: http://stackoverflow.com/a/51931628

http://stackoverflow.com/a/51805868
has body: Error Statement -1: list(int(range(1,27)) You have missed one closing bracket ')' in line offset = list(int(range(1,27)) Even after correction, there is error in code: range will return list of values, while int takes single numeral value, So int should not be use in this case. After correction: list(range(1,27)) String Library String library does not have attribute ascii, instead use ascii_lowercase Use dir(module) to get list of all the functions supported by module Error Statement -2: offset//2 Arithmetic operations can be applied in value of List, not on List as container
accepted answer of: http://stackoverflow.com/q/51805718
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/90567695
type: AcceptedAnswer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/51805718

http://stackoverflow.com/comment/90589484
score: 0
type: Comment
type: QuestionComment
has text: you need to use x2 `-` in order to set psm mode. See [tesseract CLI usage](https://github.com/tesseract-ocr/tesseract/wiki/Command-Line-Usage#tesseract---help-extra)
comment on: http://stackoverflow.com/q/51816709

http://stackoverflow.com/comment/90750404
has text: I'm actually interested in the solution that affects all columns globally, since I'm trying to map to a database created from ASP.NET EntityFramework. For completeness, could you please include the solution using `before_parent_attach`?
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51893234

http://stackoverflow.com/a/51935824
answers question: http://stackoverflow.com/q/51911674
score: 0
has body: I solved this issue. response = make_response(jsonify(map1=map1, number=number, featureCount=json.loads(featureCount), map2=json.loads(map2), point=point)) Had to do with the jsons being json like strings rather than JSON objects. Pandas only creates json style strings.
type: Answer

http://stackoverflow.com/comment/90573721
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51809248
has text: Im not able to . when i type python -m SimpleHTTPServer 8001 on commandpromt it says- C:\users\dante\anaconda3\python.exe:No module named SimpleHTTPServer
score: 0

http://stackoverflow.com/q/51913046
favorite count: 0
tagged with: python
has body: I'm trying to get the generated URL of a file in a test model I've created, and I'm trying to get the correct url of the file by: modelobject.file.url which does give me the correct url if the file is public, however if the file is private it does not automatically generate a signed url for me, how is this normally done with django-storages? Is the API supposed to automatically generate a signed url for private files? I am getting the expected Access Denied Page for 'none' signed urls currently, and need to get the signed 'volatile' link to the file. Thanks in advance
score: 2
downvote count: 0
has title: django-storages boto3 accessing file url of a private file
type: UnansweredQuestion
tagged with: django
type: Question
tagged with: boto3
has answer: http://stackoverflow.com/a/51913176
upvote count: 2
answer count: 1

http://stackoverflow.com/q/51856567
accepted answer: http://stackoverflow.com/a/51856966
type: AnsweredQuestion
score: 2
type: Question
has answer: http://stackoverflow.com/a/51857753
tagged with: mongodb
answer count: 2
has title: How to delete the document in Mongodb after 3 mins based on created time by Python
downvote count: 0
has comment: http://stackoverflow.com/comment/90665836
possible better answer: http://stackoverflow.com/a/51857753
linked to: http://stackoverflow.com/q/20431833
has body: This is my code: timestamp = datetime.datetime.now() mongo.db.user.ensure_index("createAt", expireAfterSeconds=180) mongo.db.user.insert_one({'username':json['username'],'password':json['password'],"createAt": timestamp}) This above way deletes all the documents in the collection after 3 mins. I want to delete the specific user after 3 mins based on "createAt". Ex: { "_id" : ObjectId("5b73f30a7d1312555a4ea629"), "username" : "hanson01@gmail.com", "password" : "111111", "createAt" : ISODate("2018-08-15T09:30:00.066Z") } { "_id" : ObjectId("5b73f30a7d131255asdasdas"), "username" : "hanson02@gmail.com", "password" : "111111", "createAt" : ISODate("2018-08-15T09:31:00.066Z") } The account with username hanson01@gmail.com will be deleted before hanson02@gmail.com Does anyone have any ideas? Thank you.
has answer: http://stackoverflow.com/a/51856966
has comment: http://stackoverflow.com/comment/90689098
has comment: http://stackoverflow.com/comment/90667780
favorite count: 0
tagged with: python-3.x
upvote count: 2
tagged with: python

http://stackoverflow.com/a/51898376
answers question: http://stackoverflow.com/q/51873708
upvote count: 3
has comment: http://stackoverflow.com/comment/90763918
type: Answer
downvote count: 0
has body: Is there a way to log the Python/Django traceback from within a PostgreSQL trigger? No, there is not The (SQL) query is executed on the DBMS-server, and so is the code inside the trigger The Python code is executed on the client which is a different process, possibly executed by a different user, and maybe even on a different machine. The only connection between the server (which detects the condition) and the client (which needs to perform the stackdump) is the connected socket. You could try to extend the server's reply (if there is one) by some status code, which is used by the client to stackddump itself. This will only work if the trigger is part of the current transaction, not of some unrelated process. The other way is: massive logging. Make the DBMS write every submitted SQL to its logfile. This can cause huge amounts of log entries, which you have to inspect.
score: 3

http://stackoverflow.com/comment/90776444
comment on: http://stackoverflow.com/q/51913142
has text: Whats your expected output?
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51940744
tagged with: python
linked to: http://stackoverflow.com/q/33666545
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51940939
tagged with: hive
score: 2
downvote count: 0
has title: HiveContext vs spark sql
type: Question
upvote count: 2
tagged with: apache-spark-sql
has comment: http://stackoverflow.com/comment/90831336
favorite count: 0
has body: I am trying to compare spark sql vs hive context, may I know any difference, is the hivecontext sql use the hive query, while spark sql use the spark query? Below is my code: sc = pyspark.SparkContext(conf=conf).getOrCreate() sqlContext = HiveContext(sc) sqlContext.sql ('select * from table') While sparksql: spark.sql('select * from table') May I know the difference of this two?
answer count: 1

http://stackoverflow.com/a/51955713
accepted answer of: http://stackoverflow.com/q/51955169
answers question: http://stackoverflow.com/q/51955169
type: AcceptedAnswer
score: 0
has body: There is not currently (as of version 0.13) any way to have multi-line labels. This has been recently requested in #8169 which you can follow for updates. (I can't speculate when this feature might be able to be prioritized). In recent version of Bokeh, group labels can be rotated by setting group_label_orientation on the axis, in case that is an option for your situation. Otherwise, the groups pretty much already always take up the maximum available canvas screen space available to them. In order to make more space for them, you would need to make more space for them, i,e. make your plot physically wider or reduce the padding on the sides of the plot, or both. That said, you might be able to get a little extra space by setting, e.g. the group_padding to zero (you want to remove empty padding space, not increase it).
type: Answer

http://stackoverflow.com/q/51888774
has body: Let's say I have some code like this: default_pos = (21,45) #I do some more stuff now, then change my mind to change the default_pos #So, I overwrite default_pos and assign something else to it default_pos = (756,600) What if instead of this I declared a new variable called default_pos_changed and left the old one just how it is? That would mean an unnecessary variable. So,wouldn't it use up a bit more memory than needed? Now, if there were hundreds of unused variables like this, it might be a problem, right?
tagged with: memory-management
tagged with: python
has title: Do more unnecessary variables in Python mean more memory usage?
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90728730
linked to: http://stackoverflow.com/q/9363557
has comment: http://stackoverflow.com/comment/90728712
tagged with: memory
has comment: http://stackoverflow.com/comment/90728676
type: Question
tagged with: variables
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/90728666
has comment: http://stackoverflow.com/comment/90728817
has answer: http://stackoverflow.com/a/51889072
accepted answer: http://stackoverflow.com/a/51889072

http://stackoverflow.com/comment/90851180
type: QuestionComment
score: 1
has text: rereading the question, I don't think the result you're getting matches the code you provided. you should get something like `ValueError: invalid literal for int() with base 10: 'file97'`
comment on: http://stackoverflow.com/q/51950399
type: Comment

http://stackoverflow.com/a/51919998
score: 1
has body: Have you tried pdfkit? It is easy to use as well - import pdfkit pdfkit.from_file('test.html', 'out.pdf')
upvote count: 2
type: AcceptedAnswer
downvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/51919976
accepted answer of: http://stackoverflow.com/q/51919976

http://stackoverflow.com/comment/90793662
type: Comment
has text: Why do you need to use `join()` here at all? See my previous comment about easier ways to print the results.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51921949

http://stackoverflow.com/comment/139230198
type: Comment
has text: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
comment on: http://stackoverflow.com/a/78949390
score: 0
type: AnswerComment

http://stackoverflow.com/q/51904656
answer count: 1
tagged with: hdfstore
type: UnansweredQuestion
tagged with: python
has title: Drop Dataframe index when writing to HDFStore
tagged with: hdf5
has comment: http://stackoverflow.com/comment/90760353
tagged with: pytables
type: Question
has answer: http://stackoverflow.com/a/51940718
has body: Is there some way to prevent writing the integer index of a Dataframe to HDF5, when using HDFStore.append
score: 0
tagged with: pandas

http://stackoverflow.com/comment/90768800
comment on: http://stackoverflow.com/a/51908969
has text: Thanks. What other activation_fn are possible to put into estimator? I mean, their names in tf or something - the actual code not only names of them
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/90799952
has text: thank you so much @ggorlen! I got the output I want! but I have another issue. Is there any way to shuffle it around such that I only have one parameter, which is "stopwords"? below is my attempt: stopwords = open("stop1.txt","r").read().split() def remove_stop(stopwords): disallowed = set(stopwords) text = open("yelp2.txt","r").read().split() return [word for word in text if word not in disallowed] print(remove_stop(stopwords))
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51925072
type: Comment

python-asyncio
tags question: http://stackoverflow.com/q/51919188
tags question: http://stackoverflow.com/q/51894809
tags question: http://stackoverflow.com/q/51899138
tags question: http://stackoverflow.com/q/51921943
tags question: http://stackoverflow.com/q/51898935
tags question: http://stackoverflow.com/q/51908915
tags question: http://stackoverflow.com/q/51855868
tags question: http://stackoverflow.com/q/51838154
tags question: http://stackoverflow.com/q/51849758
tags question: http://stackoverflow.com/q/51810479
tags question: http://stackoverflow.com/q/51939533
tags question: http://stackoverflow.com/q/51836370
tags question: http://stackoverflow.com/q/51808871
tags question: http://stackoverflow.com/q/51800340
tags question: http://stackoverflow.com/q/51887784
tag name: python-asyncio
tags question: http://stackoverflow.com/q/51933418
type: Tag
tags question: http://stackoverflow.com/q/51808018
tags question: http://stackoverflow.com/q/51862318
tags question: http://stackoverflow.com/q/51852691

http://stackoverflow.com/comment/91013637
has text: @user3508811 if the gerrit version is earlier than 2.14 then it most likely uses digest auth. Later versions use basic.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51954234
score: 0

http://stackoverflow.com/comment/113491613
has text: Same error here. Have you found any solution (windows 10 python3.8)
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51812530

http://stackoverflow.com/comment/90856305
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51952833
score: 0
has text: @RafaelC Just as I thought ;)

http://stackoverflow.com/q/51863147
accepted answer: http://stackoverflow.com/a/51863343
tagged with: sum
linked to: http://stackoverflow.com/q/40821161
has title: Total sum amount per month using date time in Python
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/51863413
tagged with: datetime
has body: Now I have a list of dates and values, but I don't know how to do calculations with the date structure. It looks like [[datetime.date(2018, 8, 10) 1076.2392505636847] [datetime.date(2018, 8, 11) 3537.9781979862732] [datetime.date(2018, 8, 12) 8637.536518161462] [datetime.date(2018, 8, 13) 15660.768121458246] [datetime.date(2018, 8, 14) 21087.477911830327] [datetime.date(2018, 8, 15) 21087.477911830327] [datetime.date(2018, 8, 16) 15660.768121458246] [datetime.date(2018, 8, 17) 8637.536518161465] [datetime.date(2018, 8, 18) 3537.9781979862732] [datetime.date(2018, 8, 19) 1076.2392505636856]] also, I know that startdate = datetime.date(2018, 8, 10) enddate = datetime.date(2018,8, 19) I want to create another list that consists of ['Year-Month' data, total sum of the month]. In this case, it will be just ['2018-8' total sum]. if enddate is like 2020,8,19, then the length would be 25 (two years and a month). Could you share some useful functions/approaches that I may use?
tagged with: python
has answer: http://stackoverflow.com/a/51863343
possible better answer: http://stackoverflow.com/a/51863401
has comment: http://stackoverflow.com/comment/90678767
has answer: http://stackoverflow.com/a/51863560
answer count: 4
has answer: http://stackoverflow.com/a/51863401
type: AnsweredQuestion
tagged with: list
upvote count: 3
type: Question
score: 3
has comment: http://stackoverflow.com/comment/90678613

http://stackoverflow.com/comment/90873820
comment on: http://stackoverflow.com/a/51952690
score: 0
type: AnswerComment
has text: @yajantb I'm not sure it's possible. What behavior do you expect when the user scans the code? Because this behavior depends of the data format: print a text if plain text, open a web browser if URL, open a mail client if email, ...
type: Comment

http://stackoverflow.com/a/51943080
has body: try this: app.config['SQLALCHEMY_DATABASE_URI']='mysql:////myapp:password@localhost/mydatabase?auth_plugin=mysql_native_password' http://docs.sqlalchemy.org/en/latest/core/engines.html#sqlalchemy.engine.url.URL.params.query
upvote count: 1
answers question: http://stackoverflow.com/q/51802862
downvote count: 0
score: 1
type: Answer

bots
tags question: http://stackoverflow.com/q/51838134
tags question: http://stackoverflow.com/q/51915418
type: Tag
tag name: bots
tags question: http://stackoverflow.com/q/51905306
tags question: http://stackoverflow.com/q/51818387
tags question: http://stackoverflow.com/q/51914326
tags question: http://stackoverflow.com/q/51851334

http://stackoverflow.com/comment/90791391
score: 0
comment on: http://stackoverflow.com/q/51919248
type: QuestionComment
type: Comment
has text: schwobaseggl, eyllanesc and Jerin Peter George. Thanks for your comments! They were useful. Next time you can answer, so I could vote up and rise your reputation a bit :-)

http://stackoverflow.com/a/51931218
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/51877778
score: 2
has body: For this who are looking for an answer, I transposed the data frame and then did a comparison. from pyspark.sql.functions import array, col, explode, struct, lit def Transposedf(df, by,colheader): # Filter dtypes and split into column names and type description cols, dtypes = zip(*((c, t) for (c, t) in df.dtypes if c not in by)) # Spark SQL supports only homogeneous columns assert len(set(dtypes)) == 1, "All columns have to be of the same type" # Create and explode an array of (column_name, column_value) structs kvs = explode(array([ struct(lit(c).alias("Field"), col(c).alias(colheader)) for c in cols ])).alias("kvs") return df.select(by + [kvs]).select(by + ["kvs.Field", "kvs."+colheader]) Then the comparison looks like this def Compare_df(df_Expected,df_Actual): df_combined = (df_Actual .join(df_Expected, ((df_Actual.id == df_Expected.id) &amp; (df_Actual.Field == df_Expected.Field) &amp; (df_Actual.Actual_value != df_Expected.Expected_value))) .select([df_Actual.account_unique_id,df_Actual.Field,df_Actual.Actual_value,df_Expected.Expected_value]) ) return df_combined I called these 2 functions as df_Actual=Transposedf(df_Actual, ["id"],'Actual_value') df_Expected=Transposedf(df_Expected, ["id"],'Expected_value') #Compare the expected and actual df_result=Compare_df(df_Expected,df_Actual)
upvote count: 2
answers question: http://stackoverflow.com/q/51877778
type: AcceptedAnswer

http://stackoverflow.com/comment/90811450
comment on: http://stackoverflow.com/q/51930384
score: 4
has text: https://github.com/numpy/numpy/issues/6051
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51872956
score: 0
answers question: http://stackoverflow.com/q/51872648
has body: OR: length = 2 text_values = ["option1", "option2"] print([dict(viewclass="MDMenuItem", text=option) for option in text_values])
has comment: http://stackoverflow.com/comment/90702496
type: Answer

http://stackoverflow.com/comment/90660679
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51853854
has text: It will run, but it does not give the desired result
score: 0

http://stackoverflow.com/a/51902067
has body: You need to encode the link properly; escaping the invalid character(s). You can do that with urllib. &gt;&gt;&gt; import urllib &gt;&gt;&gt; filename = urllib.parse.quote('c:\temp\my Folder\1.jpg') &gt;&gt;&gt; 'https://upload.mysite.com/' + filename 'https://upload.mysite.com/c%3A%09emp%5Cmy%20Folder%01.jpg'
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/90756406
type: Answer
answers question: http://stackoverflow.com/q/51902001
upvote count: 1
has comment: http://stackoverflow.com/comment/90756434

http://stackoverflow.com/q/51871376
score: 1
has title: Convert date and time columns in a pandas df to a timestamp
type: Question
tagged with: pandas
upvote count: 1
answer count: 1
favorite count: 0
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51871407
accepted answer: http://stackoverflow.com/a/51871407
downvote count: 0
has body: i am new to python and used to code in R. I have a Pandas df that has a column of dates and times. date time 0 2018-06-25 07:32:25 1 2018-06-25 09:36:38 2 2018-06-25 13:31:47 3 2018-06-25 13:29:56 4 2018-06-29 04:00:13 I used to select these columns and create numercial vectors to convert them into one vector of timestamps in R. Is there a possibility to do something similar in python? I already tried this: strtime = df1['time'].astype(str) strdate = df1['date'].astype(str) timestamp = pd.to_datetime(strdate + ' ' + strtime) But it gives me the output: "ValueError: Unknown string format" I believe this might be an easy task so please be kind.

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

http://stackoverflow.com/comment/120701410
type: AnswerComment
comment on: http://stackoverflow.com/a/51956230
type: Comment
has text: Thank you. So, given a time series, do we have to tokenize it using Tokenizer please?
score: 0

http://stackoverflow.com/q/51910031
upvote count: 0
has comment: http://stackoverflow.com/comment/90770243
answer count: 1
accepted answer: http://stackoverflow.com/a/51910297
has comment: http://stackoverflow.com/comment/90770385
has comment: http://stackoverflow.com/comment/90770184
favorite count: 0
has comment: http://stackoverflow.com/comment/90770136
has comment: http://stackoverflow.com/comment/90770254
tagged with: python
has comment: http://stackoverflow.com/comment/90770128
has comment: http://stackoverflow.com/comment/90770228
has comment: http://stackoverflow.com/comment/90770268
has title: Try / Except Statements in python
has answer: http://stackoverflow.com/a/51910297
type: Question
type: AnsweredQuestion
score: -5
has comment: http://stackoverflow.com/comment/90770208
has body: I'm trying to create a python program that uses try/except statements. Everything works fine except, I'm still getting a value error, even after defining the except statement. my code: inventory = {847502: ['APPLES 1LB', 1.99, 50], 847283: ['OLIVE OIL', 10.99, 100], 839529: ['TOMATOS 1LB', 1.29, 25], 483946: ['MILK 1/2G', 3.45, 35], 493402: ['FLOUR 5LB', 2.99, 40], 485034: ['BELL PEPPERS 1LB', 1.35, 28], 828391: ['WHITE TUNA', 1.69, 100], 449023: ['CHEESE 1/2LB', 4.99, 15]} upc_input = int(input('Enter a UPC number: ')) description = input('Enter a, item description: ') unit_price = float(input('Enter the unit price: ')) quantity = int(input('Enter th quantity: ')) try: if upc_input in inventory.keys(): print('Inventory Updating') inventory[upc_input] = [description,unit_price,quantity] except Excetption as exp: print('Error occurred!',exp) try: if upc_input not in inventory.keys(): print('Adding new inventory') inventory[upc_input] = [description,unit_price,quantity] except Excetption as exp: print('Error occurred!',exp) print() print(inventory) --------------------------------------------------------------------------- ValueError Traceback (most recent call last) &lt;ipython-input-17-1313cc5c500f&gt; in &lt;module&gt;() ----&gt; 1 upc_input = int(input('Enter a UPC number: ')) 2 description = input('Enter a, item description: ') 3 unit_price = float(input('Enter the unit price: ')) 4 quantity = int(input('Enter th quantity: ')) 5 ValueError: invalid literal for int() with base 10: 'eeeee'
downvote count: 5
has comment: http://stackoverflow.com/comment/90770320
has comment: http://stackoverflow.com/comment/90770203
tagged with: try-except

http://stackoverflow.com/comment/90640987
score: 0
has text: @MatthewStory thanks for your answer. Can you explain a litte more this: "here are 2 approaches to this: either use a local mailer daemon on this box that will relay the email out and handle retries, or use a system that provides you with a rest interface (like SES) that will retry for you" I do not finish to understand if like this now it is ok or do I have to make a change to make it scalable?. Thanks!
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51843755

http://stackoverflow.com/q/51875347
type: Question
has comment: http://stackoverflow.com/comment/90706479
accepted answer: http://stackoverflow.com/a/51875563
score: 0
has body: I'm using python to automate an action in photoshop. I want to select an area but I get this error: Traceback (most recent call last): File "&lt;pyshell#90&gt;", line 1, in &lt;module&gt; docRef.Selection.Select(sel_area) File "&lt;COMObject &lt;unknown&gt;&gt;", line 3, in Select pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'Adobe Photoshop', 'Illegal argument - argument 1\n- Only arrays with dimension 1 are supported', None, 0, -2147220262), None) My code: from win32com.client import Dispatch app = Dispatch("Photoshop.Application") file=r"dog.bmp" #size = 512*512 docRef=app.Open(file) sel_area = ((0,0), (0, 10), (10, 10), (10, 0)) docRef.Selection.Select(sel_area) All the examples I saw did the same thing as I do. What exactly I need to change to pass it as 1D array?
answer count: 1
linked to: http://stackoverflow.com/q/10166064
tagged with: photoshop
has answer: http://stackoverflow.com/a/51875563
tagged with: python
has comment: http://stackoverflow.com/comment/90702494
tagged with: photoshop-script
type: AnsweredQuestion
has title: Select an area in Photoshop using python return an error

http://stackoverflow.com/comment/90574794
has text: If you login using putty there should be a newline after the username and password. But your code does not seem to deal with this newline. Hard to imagine that this works on localhost.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51809401

http://stackoverflow.com/a/51920823
type: Answer
has comment: http://stackoverflow.com/comment/90832367
type: AcceptedAnswer
score: 0
has body: me = User.query.filter_by(username=me) them = User.query.filter_by(username=them) my_friends = me.friends their_friends = them.friends my_friends.intersect(their_friends) is what I needed.
accepted answer of: http://stackoverflow.com/q/51920541
answers question: http://stackoverflow.com/q/51920541

http://stackoverflow.com/a/51942174
type: Answer
answers question: http://stackoverflow.com/q/51941664
has body: Using collections.defaultdict Ex: from collections import defaultdict d = defaultdict(int) with open(filename) as infile: #Open File for line in infile: #Iterate Each Line d[line.strip()] += 1 print("Bones found:") for k, v in d.items(): print("{}: {}".format(k, v)) Output: Bones found: Struthiomimus: 2 Pachycephalosaurus: 1 Ankylosaurus: 3 Tyrannosaurus Rex: 1
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51941664

boost
tags question: http://stackoverflow.com/q/51905284
tags question: http://stackoverflow.com/q/51805078
tag name: boost
tags question: http://stackoverflow.com/q/51887916
type: Tag
tags question: http://stackoverflow.com/q/51906096

http://stackoverflow.com/comment/90685021
comment on: http://stackoverflow.com/q/51866152
score: 0
type: Comment
type: QuestionComment
has text: No dataframe. It's just a numpy array of numpy arrays.

http://stackoverflow.com/q/51930496
tagged with: python-3.x
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51930531
duplicate of: http://stackoverflow.com/q/10645986
type: Question
score: 0
has body: I have the list of strings: ['bsdf', 'dfgds', 'asdf'] I defined alphabet order: 'dfgsab' I would like to sort my strings according to the order defined in my alphabet. So in this example the output would be: ['dfgds', 'asdf', 'bsdf'] How should I do it in the most efficient way?
linked to: http://stackoverflow.com/q/10645986
answer count: 1
has title: Sort strings by my own alphabet order

http://stackoverflow.com/q/51876287
tagged with: python
has comment: http://stackoverflow.com/comment/95334255
has body: I have a virtualenv that holds all my Flask packages, I have Pandas and NumPy installed when I activate the environment Pandas and NumPy works just fine. When I try to use WSGI and activate_this.py I get the error, ImportError: Missing required dependencies ['numpy'] So after a lot more digging around, I think wsgi is running with python2.7 and not python3, so all the script imports fail. Any suggestions on how I can get mod_wsgi to work with packages for python3.
has title: ImportError: Missing required dependencies ['numpy'] on centos 7
score: 2
answer count: 0
tagged with: mod-wsgi
upvote count: 3
type: UnansweredQuestion
downvote count: 1
type: Question
tagged with: numpy
tagged with: flask
favorite count: 0
tagged with: pandas

http://stackoverflow.com/a/51890585
type: Answer
score: 0
answers question: http://stackoverflow.com/q/51890489
has body: To access one field in your DataFrame `data.loc[row][column]` or `data.loc[row,column]` e.g. `data.loc[0]['left'] To find, e.g. the minimum of the top values globally min(data['top'])
has comment: http://stackoverflow.com/comment/90732720
has comment: http://stackoverflow.com/comment/90733107

http://stackoverflow.com/q/51877360
tagged with: setuptools
has title: Make a python module collection installable
has comment: http://stackoverflow.com/comment/90706417
type: Question
score: 0
has comment: http://stackoverflow.com/comment/90707412
has body: We have a bunch of python scripts and want to make them installable using setuptools. At the end importing our modules (after installing them) should work like this: import companyname.productA.moduleA Our first draft for the structure looks like this: repository/ setup.py companyname/ __init__.py productA/ moduleA/ __init__.py moduleA.py moduleB/ __init__.py moduleB.py productB/ moduleA/ __init__.py moduleA.py moduleB/ __init__.py moduleB.py This already seems to work, but it produce an installer for the whole collection. We also need to make installer for only product or even only a module, because not every customer will need everything. This seems to be possible by duplicating the whole repository and removing all products / modules which should not go into the installer. This approach doesn't sound very good to me, so my first question is: Is there a better way to this? There's also another problem: How do handle version, author, maintainer? setup.py currently looks like this: setuptools.setup( version='...', author='...', author_email='...', maintainer='...', maintainer_email='...', packages=setuptools.find_packages(), ... ) Should we add all authors of all modules into setup.py? Is it possible to assign each module a version? Or do we need to make a combined version number of all moduls for setup.py? If yes, whats the best approach to do this?
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90707011
type: UnansweredQuestion
tagged with: python
answer count: 0

http://stackoverflow.com/comment/90569514
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51806965
score: 1
has text: @jpp If the dataframe has many columns and all of them the same dtype even `axis=1` is vectorized (at least it was at some point). But you're right about `Series.apply` it's just a loop and given that it also performs a conversion from `np.int_` -> `int` it's likely that it has a significant overhead.

http://stackoverflow.com/comment/138787474
comment on: http://stackoverflow.com/a/77680612
type: Comment
score: 1
type: AnswerComment
has text: Didn't work on my Linux box,s till getting `DEBUG:fba.http.network:Fetching path='/' from domain='xxx.xxx.xxx' failed. exception[<class 'requests.exceptions.SSLError'>]='HTTPSConnectionPool(host='xxx.xxx.xxx', port=443): Max retries exceeded with url: / (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:992)')))'`

http://stackoverflow.com/q/51840123
favorite count: 0
has body: how to merge columns from a dataframe to multiindex dataframe header . i.e, how to merge the respective subject values and create new dataframe import pandas as pd import numpy as np df = pd.DataFrame({'Maths':[95,96,97,98] ,'Science': [91,92,93,94]}) df1 = pd.DataFrame({'Social':[85,86,87,88] ,'English': [81,82,83,84]}) print df Maths Science 0 95 91 1 96 92 2 97 93 3 98 94 print df1 English Social 0 81 85 1 82 86 2 83 87 3 84 88
accepted answer: http://stackoverflow.com/a/51840151
tagged with: python
type: AnsweredQuestion
has title: how to merge columns from a dataframe to another dataframe
upvote count: 3
type: Question
score: 3
has answer: http://stackoverflow.com/a/51840151
tagged with: pandas
answer count: 1
downvote count: 0

http://stackoverflow.com/a/51922482
has body: Your problem is that you installed two different Pythons, a 32-bit 3.6, and a 64-bit 3.6. The first pip on your PATH is the one for the 32-bit 3.6. So, when you pip install numpy, it's downloading the 32-bit NumPy, and installing into the site-packages for the 32-bit Python. But your py launcher is defaulting to running the 64-bit 3.6, which can't see the site-packages for a completely different Python installation, and couldn't use them even if it did see them. The simplest solution is to start over from scratch: Uninstall both Pythons, pick the one you want, and reinstall that. (You could just uninstall the one you don't want, leaving the other… but that may cause problems, like leaving py configured wrong so it can't run Python at all. At the very least you should re-run the installer for the one you want to keep and tell it to update the existing installation.) If you can't do that, you may want to consider using virtual environments. With a virtual environment active, pip, python and py will all come from the active environment, so it doesn't matter what else you have anywhere on your system. If you can't do that, just don't run pip, run py -m pip. This guarantees that you're using the pip for the right Python installation, and installing packages for that installation. (And the same goes for other tools—run py -m 2to3, not 2to3, and so on.)
type: Answer
answers question: http://stackoverflow.com/q/51922364
downvote count: 1
score: 14
upvote count: 15
has comment: http://stackoverflow.com/comment/122913970
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51922364

http://stackoverflow.com/q/51936924
has answer: http://stackoverflow.com/a/51936987
favorite count: 0
has title: Post to django view from another view
possible better answer: http://stackoverflow.com/a/51936987
tagged with: django
tagged with: python
type: AnsweredQuestion
score: 4
tagged with: django-views
accepted answer: http://stackoverflow.com/a/51936980
type: Question
has answer: http://stackoverflow.com/a/51937126
has body: Facing some constraints in a website, I was obligated to try to post data to some view from another view (I suppose it does make sense), like: def view1(request): if request.method == 'POST': value = request.POST.get('h1') ''' ''' And in my view2, I would do something like: def view2(request): if constraint: python.post(/url/view1/,data={'h1':1}) # Doesn't exist # Just a demonstration Is there a way to do what I want?
tagged with: post
upvote count: 4
answer count: 3
has answer: http://stackoverflow.com/a/51936980
downvote count: 0

http://stackoverflow.com/q/51841553
answer count: 1
favorite count: 0
has title: Odoo v11: Automatically upgrade all modules mentioned in __manifest.py
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90759734
tagged with: odoo-11
has comment: http://stackoverflow.com/comment/90691179
upvote count: 3
has comment: http://stackoverflow.com/comment/90636169
type: Question
has body: I have created a startup project myapp_main for all my Odoo projects. Whenever I install this main project; Odoo installs all depends modules (x, y, z) Here's manifest.py file: # -*- coding: utf-8 -*- { 'name': 'myapp_main', 'version': '1.0', 'summary': 'MyApp main project', 'depends': ['x', 'y', 'z' ], 'demo': [], 'installable': True, 'auto_install': False, 'application': True, } This approach works fine for fresh installation but doesn't work when we are upgrading. I expect that all dependent modules should also get auto-upgraded whenever I upgrade the main project. Has anyone achieved this? Any ideas please.
has comment: http://stackoverflow.com/comment/90636150
downvote count: 0
has answer: http://stackoverflow.com/a/51956894
score: 3

http://stackoverflow.com/comment/90765801
comment on: http://stackoverflow.com/q/51907237
has text: @JerinPeterGeorge I have created a DB with the name `shield_dev` but still, it is not working so could you please explain in detail what I need to do from my end.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/90781424
type: Comment
type: QuestionComment
score: 1
has text: @Jean-FrançoisFabre Understood. But until the OP clarifies we don't need more answers from people guessing the actual requirements. ;)
comment on: http://stackoverflow.com/q/51915495

http://stackoverflow.com/comment/90823468
type: Comment
type: QuestionComment
has text: *django_allauth
comment on: http://stackoverflow.com/q/51936437
score: 0

http://stackoverflow.com/a/53870033
answers question: http://stackoverflow.com/q/51946012
score: 0
type: Answer
has body: Try this: ... from kivy.properties import StringProperty ... class TreeViewButton(Button, TreeViewNode): #id = "" id = StringProperty('') #or other type def __init__(self, **kwargs): super(TreeViewButton, self).__init__(**kwargs) self.bind(is_selected = self.clk) def clk(self): #prints only on the selection and not on the deselection if self.is_selected: print(id) class OrgChart(Screen, TreeViewButton): ... def createTree(self): tv = TreeView() for dict in self.extractNames(): for key, value in dict.items(): if key == "Button_ID": self.ids.tv.add_node(TreeViewButton(id = value)) #self.id=value #self.bind(on_press=self.clk) Cheers.

http://stackoverflow.com/comment/90617867
score: 0
type: Comment
has text: @python_newbie I've shown how it handles duplicates. If the output isn't to your liking, please explain how you want duplicates to be handled.
comment on: http://stackoverflow.com/a/51831706
type: AnswerComment

http://stackoverflow.com/comment/90772774
type: AnswerComment
has text: @Pravat if you were having problem with float then now it should work btw you should have mentioned that key can be float
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51910692

http://stackoverflow.com/q/51803698
tagged with: pandas
downvote count: 0
has answer: http://stackoverflow.com/a/51805293
favorite count: 0
has answer: http://stackoverflow.com/a/51803786
accepted answer: http://stackoverflow.com/a/51805293
tagged with: python
possible better answer: http://stackoverflow.com/a/51803786
type: AnsweredQuestion
type: Question
has body: I'm trying to figure out how to take a dataframe representing players in a game, the dataframe has unique users and records of each day the particular user has been active. I am trying to get the average playtime and average moves for each week in the various users lifetime. (Week is defined by a user's first record, i.e. if a user's first record is 3rd of January, their 1st week starts then and the 2nd week start the 10th of January). Example userid date secondsPlayed movesMade ++/acsbP2NFC2BvgG1BzySv5jko= 2016-04-28 413.88188 85 ++/acsbP2NFC2BvgG1BzySv5jko= 2016-05-01 82.67343 15 ++/acsbP2NFC2BvgG1BzySv5jko= 2016-05-05 236.73809 39 ++/acsbP2NFC2BvgG1BzySv5jko= 2016-05-10 112.69112 29 ++/acsbP2NFC2BvgG1BzySv5jko= 2016-05-11 211.42790 44 -----------------------------------CONT---------------------------------- ++/8ij1h8378h123123koF3oer1 2016-05-05 200.73809 11 ++/8ij1h8378h123123koF3oer1 2016-05-10 51.69112 14 ++/8ij1h8378h123123koF3oer1 2016-05-14 65.42790 53 The end result for this would be the following table: userid date secondsPlayed_w movesMade_w ++/acsbP2NFC2BvgG1BzySv5jko= 2016-04-28 496.55531 100 ++/acsbP2NFC2BvgG1BzySv5jko= 2016-05-05 236.73809 68 -----------------------------------CONT---------------------------------- ++/8ij1h8378h123123koF3oer1 2016-05-05 252.42921 25 ++/8ij1h8378h123123koF3oer1 2016-05-12 65.42790 53 Failed attempt #1: So far I've tried doing a lot of different things, but the most useful dataframe I've managed to create was the following: df_grouped = df.groupby('userid').apply(lambda x: x.set_index('date').resample('1D').first().fillna(0)) df_result = df_grouped.groupby(level=0)['secondsPlayed'].apply(lambda x: x.rolling(min_periods=1, window=7).mean()).reset_index(name='secondsPlayed_week') Which is a very slow and wasteful computation, but nonetheless can be used as a intermediate step. userid date secondsPlayed_w ++/acsbP2NFC2BvgG1BzySv5jko= 2016-04-28 4.138819e+02 ++/acsbP2NFC2BvgG1BzySv5jko= 2016-04-29 2.069409e+02 ++/acsbP2NFC…
tagged with: dataframe
has title: Pandas - Get week average for each user
score: 4
upvote count: 4
answer count: 2

http://stackoverflow.com/comment/90789239
type: Comment
type: QuestionComment
score: 1
has text: See my first comment here https://github.com/chhantyal/taggit-selectize/issues/16
comment on: http://stackoverflow.com/q/51844921

http://stackoverflow.com/comment/90703369
type: AnswerComment
has text: This is what i want to achieve and you helped me in this http://trendinganalytica.com/twitter/
comment on: http://stackoverflow.com/a/51875857
type: Comment
score: 0

http://stackoverflow.com/comment/90578833
type: QuestionComment
comment on: http://stackoverflow.com/q/51811937
score: 1
has text: The first creates a new list, while the second modifies the list on the left.
type: Comment

http://stackoverflow.com/q/51873598
favorite count: 0
has comment: http://stackoverflow.com/comment/90698903
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90698962
downvote count: 0
score: 1
has title: All the results producing empty lists from geograpy
tagged with: web-scraping
has body: Below is a simple code to fetch all the cities from a URL specified : import geograpy url = 'https://www.netmagicsolutions.com/cloud-infrastructure-services' places = geograpy.get_place_context(url=url) print places.cities But this is giving a empty list. Tried alot of solutions but couldn't find a proper solution. Any one having idea about this ? or is there any python lib which can extract city/country from 'URL' ? Below is terminal snap : runfile('D:/KJ/Nagesh/Downloads/WebScraping/geography.py', wdir='D:/KJ/Nagesh/Downloads/WebScraping') []
type: Question
has answer: http://stackoverflow.com/a/51874098
upvote count: 1
answer count: 1

http://stackoverflow.com/comment/90849519
has text: Yes, if `daily_info` is list solution working if matched number of columns with number of values in list `daily_info`, so `if len(daily_info) == 5:` is necessary.
comment on: http://stackoverflow.com/a/51948205
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/51895280
answer count: 3
tagged with: pandas
has comment: http://stackoverflow.com/comment/90741932
possible better answer: http://stackoverflow.com/a/51895816
tagged with: python-3.x
has title: TypeError when replacing strings with a list comprehension
tagged with: python
has body: My code is pretty simple: ['found' if 'some_string' in word else word for word in wordlist] But it returns TypeError Traceback (most recent call last) &lt;ipython-input-108-990cad51d935&gt; in &lt;module&gt;() ----&gt; 1 [word for word in wordlist if 'some_string' in word ] &lt;ipython-input-108-990cad51d935&gt; in &lt;listcomp&gt;(.0) ----&gt; 1 [word for word in wordlist if 'some_string' in word ] TypeError: argument of type 'NoneType' is not iterable (I've tried rearranging it in several ways to no avail.) By comparison, this code does exactly as expected: for word in wordlist: if 'some_string' in word: print ('found') else: print(word) All I want is to replace the any string that contains 'some_string' with 'found'. Further context: wordlist is the values from a column of a Pandas dataframe in a Jupyter notebook. wordlist = list(df.sender.values) type(wordlist) list
has comment: http://stackoverflow.com/comment/90741091
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90741266
has answer: http://stackoverflow.com/a/51895816
has comment: http://stackoverflow.com/comment/90741096
accepted answer: http://stackoverflow.com/a/51896055
has comment: http://stackoverflow.com/comment/90741342
type: Question
has comment: http://stackoverflow.com/comment/90742100
has comment: http://stackoverflow.com/comment/90741153
has answer: http://stackoverflow.com/a/51896055
score: 0
has answer: http://stackoverflow.com/a/51895955

http://stackoverflow.com/q/51901499
has answer: http://stackoverflow.com/a/51929043
type: Question
has comment: http://stackoverflow.com/comment/90802746
has title: Tornado: Websocket connection limit
tagged with: tornado
linked to: http://stackoverflow.com/q/985431
score: 0
has body: I am developing a web application with Tornado and have encountered the following problem: I can't run more than 6 instances of my application in one browser probably because each instance creates websocket connection to Tornado server. I use standard WebSocketHandler class. They close properly, i.e. if I close the 6th tab, then I'd be able to open another application tab. Is there any way to circumvent it? I will provide any additional information if needed. EDIT: Connection information (I have 6 identical tabs here, 7th won't load):
answer count: 1
tagged with: websocket
linked to: http://stackoverflow.com/q/561046
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/90756650
comment on: http://stackoverflow.com/q/51902666
type: Comment
has text: If you just need the first two non-whitespace chunks, why not use `" ".join(s.split(" ", 2)[:2])`?
score: 0
type: QuestionComment

http://stackoverflow.com/q/51860316
tagged with: fonts
has title: font error - python tkinter label
downvote count: 1
accepted answer: http://stackoverflow.com/a/51860659
type: Question
upvote count: 0
has comment: http://stackoverflow.com/comment/90672861
score: -1
tagged with: label
has body: im using the anurati (google it if you dont know what it is) font on win 10 i tried calling it from tkinter to recive the error my code is : from tkinter import * root = Tk() root.title("P.E.T.A.R") txt = Label(root, text = "welcome to project petar") txt.grid(column = 0, row = 0, font=("Anurati Regular")) and the error is ================ RESTART: C:\Users\dell\Desktop\p.e.t.a.r.py ================ Traceback (most recent call last): File "C:\Users\dell\Desktop\p.e.t.a.r.py", line 6, in &lt;module&gt; txt.grid(column = 0, row = 0, font=("Anurati Regular", 50)) File "C:\Users\dell\AppData\Local\Programs\Python\Python35-32\lib\tkinter\__init__.py", line 2082, in grid_configure + self._options(cnf, kw)) _tkinter.TclError: bad option "-font": must be -column, -columnspan, -in, -ipadx, -ipady, -padx, -pady, -row, -rowspan, or -sticky &gt;&gt;&gt; why does this happen
has comment: http://stackoverflow.com/comment/90675288
answer count: 1
favorite count: 0
tagged with: tkinter
has comment: http://stackoverflow.com/comment/90673008
tagged with: python
has comment: http://stackoverflow.com/comment/90674347
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90675316
has answer: http://stackoverflow.com/a/51860659

http://stackoverflow.com/a/51901591
score: 0
has body: I have an idea.. Suppose we have all the subseries ready and neat. First vertically stack all subseries. Then loop through every column and concatenate them one after another. So we avoid the sorting because of the structure of the subseries. Example: &gt;&gt; s1 array([Timestamp('2013-12-28 00:00:00'), Timestamp('2014-12-27 00:00:00'), Timestamp('2015-12-26 00:00:00'), Timestamp('2016-12-24 00:00:00'), Timestamp('2017-12-23 00:00:00')], dtype=object) &gt;&gt; s2 array([Timestamp('2014-01-04 00:00:00'), Timestamp('2015-01-03 00:00:00'), Timestamp('2016-01-02 00:00:00'), Timestamp('2016-12-31 00:00:00'), Timestamp('2017-12-30 00:00:00')], dtype=object) &gt;&gt; np.vstack([s1, s2]).T.reshape([1, -1], order = 'c')[0] array([Timestamp('2013-12-28 00:00:00'), Timestamp('2014-01-04 00:00:00'), Timestamp('2014-12-27 00:00:00'), Timestamp('2015-01-03 00:00:00'), Timestamp('2015-12-26 00:00:00'), Timestamp('2016-01-02 00:00:00'), Timestamp('2016-12-24 00:00:00'), Timestamp('2016-12-31 00:00:00'), Timestamp('2017-12-23 00:00:00'), Timestamp('2017-12-30 00:00:00')], dtype=object)
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/51901495
answers question: http://stackoverflow.com/q/51901495

http://stackoverflow.com/a/51951105
accepted answer of: http://stackoverflow.com/q/51949736
has body: The error you are getting in train_test_split is clearly indicated and solved by @Alexis. And once again I also suggest to not use train_test_split as it will not do anything except shuffling, which you have already done. But I want to highlight another important point, i.e., If you are keeping your train and test files separately, then just don't fit vectorizers separately. It will create different columns for train and test files. Example: cv = CountVectorizer() train=['Hi this is stack overflow'] cv.fit(train) cv.get_feature_names() Output: ['hi', 'is', 'overflow', 'stack', 'this'] test=['Hi that is not stack overflow'] cv.fit(test) cv.get_feature_names() Output: ['hi', 'is', 'not', 'overflow', 'stack', 'that'] Hence, fitting them separately will result in columns mismatch. So, you should merge train and test files firstly and then fit_transform vectorizer collectively, or if you don't have test data beforehand you could only transform the test data using vectorizer fitted on train data, which will ignore the words not present in train data.
answers question: http://stackoverflow.com/q/51949736
downvote count: 0
score: 5
type: AcceptedAnswer
upvote count: 5
type: Answer

http://stackoverflow.com/a/51818747
score: 1
upvote count: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90618544
downvote count: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/51816097
has body: You cannot directly plot a dictionary in matplotlib. It needs x values and y values. You can see that type(df) will be a &lt;class 'dict'&gt; which contains the value something like this: {'TSLA': {'2017-02-09': {'open': 266.25, 'high': 271.18, 'low': 266.15, 'close': 269.2, 'volume': 7820222}}} so, if you want to get it graphed, you need to convert it into pandas dataFrame your code has to change like this: from iexfinance import Stock import matplotlib.pyplot as plt tsla = Stock('TSLA') tsla.get_close() tsla.get_price() from iexfinance import get_historical_data from datetime import datetime import pandas as pd pd.set_option('display.max_rows', 1000) start = datetime(2017, 2, 9) end = datetime(2017, 5, 24) df = get_historical_data("TSLA", start=start, end=end, output_format='json') df = pd.DataFrame(df["TSLA"]).transpose() #transpose to get dates as x df = df.drop(columns = "volume") #deleted volume column, else it make other graphs smaller df.index = pd.to_datetime(df.index) #change string to date format df.plot() plt.show(); You will get a graph like this: Graph
answers question: http://stackoverflow.com/q/51816097

http://stackoverflow.com/q/51911927
tagged with: boto3
accepted answer: http://stackoverflow.com/a/51920174
has comment: http://stackoverflow.com/comment/90774496
has answer: http://stackoverflow.com/a/70810185
upvote count: 38
downvote count: 0
tagged with: nested
has answer: http://stackoverflow.com/a/59910906
favorite count: 0
score: 38
answer count: 5
tagged with: python
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/8511281
tagged with: amazon-dynamodb
has title: Update nested map dynamodb
has answer: http://stackoverflow.com/a/59062665
type: Question
has answer: http://stackoverflow.com/a/71110148
has body: I have a dynamodb table with an attribute containing a nested map and I would like to update a specific inventory item that is filtered via a filter expression that results in a single item from this map. How to write an update expression to update the location to "in place three" of the item with name=opel,tags include "x1" (and possibly also f3)? This should just update the first list elements location attribute. { "inventory": [ { "location": "in place one", # I want to update this "name": "opel", "tags": [ "x1", "f3" ] }, { "location": "in place two", "name": "abc", "tags": [ "a3", "f5" ] }], "User" :"test" }
has answer: http://stackoverflow.com/a/51920174
possible better answer: http://stackoverflow.com/a/59062665

http://stackoverflow.com/q/51923273
upvote count: 2
possible better answer: http://stackoverflow.com/a/51923324
type: Question
accepted answer: http://stackoverflow.com/a/51923300
tagged with: numpy
has title: Randomize the splitting of data for training and testing for this function
has answer: http://stackoverflow.com/a/51923324
answer count: 2
tagged with: arrays
downvote count: 0
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51923300
has body: I wrote a function to split numpy ndarrays x_data and y_data into training and test data based on a percentage of the total size. Here is the function: def split_data_into_training_testing(x_data, y_data, percentage_split): number_of_samples = x_data.shape[0] p = int(number_of_samples * percentage_split) x_train = x_data[0:p] y_train = y_data[0:p] x_test = x_data[p:] y_test = y_data[p:] return x_train, y_train, x_test, y_test In this function, the top part of the data goes to the training dataset and the bottom part of the data samples go to the testing dataset based on percentage_split. How can this data split be made more randomized before being fed to the machine learning model?
tagged with: python
score: 2
type: AnsweredQuestion

http://stackoverflow.com/q/51817573
has comment: http://stackoverflow.com/comment/90590680
answer count: 3
tagged with: pandas
tagged with: python
has answer: http://stackoverflow.com/a/57720650
type: UnansweredQuestion
upvote count: 1
has answer: http://stackoverflow.com/a/51818089
has body: I have a dataframe df with multiple columns (not sure how many). One of the columns is called x. I have defined a function my_function that takes 2 columns as inputs and does something them and returns a new column. I want to perform the my_function(df[x], df[y]) on all columns of the dataframe (where y is all columns one by one except for x) and return a new df with exact same column names but update values from my_function: new_df = my_function(df[x], df[y]) where y = all columns in df except for x. What is the fastest way to do this?
score: 1
tagged with: dataframe
tagged with: apply
type: Question
tagged with: function
downvote count: 0
has answer: http://stackoverflow.com/a/51818164
has title: pandas dataframe fast apply function on multiple columns
favorite count: 0

http://stackoverflow.com/comment/90902901
score: 0
type: Comment
type: QuestionComment
has text: Because your premise *"searching the df twice"* ⇏ *"less efficient"*. So either you could ask *"How to make this more efficient?"* or *"How to avoid searching the df twice?"* But not both. (By the way it's a (pandas) dataframe not a (numpy) matrix. If you did this on a numpy matrix the most efficient methods would likely be different again).
comment on: http://stackoverflow.com/q/51932428

http://stackoverflow.com/q/51863208
has body: I am importing matplotlib into my python script as follows import matplotlib.pyplot as plt I have matplotlib installed on my machine and I did it through the command prompt. It's located in the folder C:\Users\Br. David Klecker\Downloads\WPy-3701\python-3.7.0.amd64\Lib\site-packages This is the error I am getting from the IDLE screen. import matplotlib.pyplot as plt ModuleNotFoundError: No module named 'matplotlib' I could have sworn this was working yesterday, so the fact that it is not working today is strange. Can anyone provide a hint so to how this could have changed or if there is something I may have overlooked?
score: 0
has comment: http://stackoverflow.com/comment/90678727
type: UnansweredQuestion
tagged with: matplotlib
tagged with: import
type: Question
has comment: http://stackoverflow.com/comment/90681642
has title: Python: matplotlib not recognize even when it's installed
answer count: 1
has answer: http://stackoverflow.com/a/51864900
tagged with: python

pyinstaller
tags question: http://stackoverflow.com/q/51868433
tags question: http://stackoverflow.com/q/51954444
tags question: http://stackoverflow.com/q/51846073
tags question: http://stackoverflow.com/q/51950122
tags question: http://stackoverflow.com/q/51801282
type: Tag
tags question: http://stackoverflow.com/q/51847801
tags question: http://stackoverflow.com/q/51909209
tags question: http://stackoverflow.com/q/51899207
tag name: pyinstaller
tags question: http://stackoverflow.com/q/51806127
tags question: http://stackoverflow.com/q/51921470
tags question: http://stackoverflow.com/q/51836628
tags question: http://stackoverflow.com/q/51933498
tags question: http://stackoverflow.com/q/51931668
tags question: http://stackoverflow.com/q/51931008
tags question: http://stackoverflow.com/q/51830992
tags question: http://stackoverflow.com/q/51847455
tags question: http://stackoverflow.com/q/51948219

http://stackoverflow.com/q/51895714
tagged with: appium
score: 0
has comment: http://stackoverflow.com/comment/90742323
has title: WebDriverException when Background
answer count: 0
type: UnansweredQuestion
tagged with: android
tagged with: python
has body: We have a recurring error testing Android. When I do self.driver.background_app(3) sometimes we receive a WebDriverException. We have to do background to update the XML tree of uiAutomator. If we don't do that, I can't wait for any element there because they never appear. My questions are the following: Can we do another thing to refresh the XML tree? What can we do to avoid WebDriverExceptions? Here i add some code where this happens: def click_byId(id): global driver, var_debug if var_debug: print(" DEBUG: Clicking button by id: '%s'" % id) element = driver.find_element_by_id(id) element.click() . . . click_byId("Entrar") self.driver.background_app(3) click_byId("Inicio") the problem is that this happens from time to time, with the same mobile phone and the same script. In appium we can read something like this: [ADB] Running 'C:/../platform-tools/adb.exe' with args: ["-p",5037,"-s","LGM250LJEE65QCLVHQ","shell","dumpsys","window","windows"] [ADB] Found package: 'com.app.miapp' and fully qualified activity name: 'com.app.miapp.MainActivity' [MJSONWP] Responding to client with driver.background() result: null [HTTP] &lt;-- POST /wd/hub/session/542532453-ecde-43a9-7a8788d171b/appium/app/background 200 7408 ms - 76 [HTTP] --> POST /wd/hub/session/542532453-ecde-43a9-7a8788d171b/element {"using":"id","sessionId":"542532453-ecde-43a9-7a8788d171b","value":"Inicio"} [MJSONWP] Calling AppiumDriver.findElement() with args: ["id","Inicio","542532453-ecde-43a9-7a8788d171b"] Then, the execution is blocked and stop running. Later, all finish and we receive by console: ('Unexpected error:', class 'selenium.common.exceptions.WebDriverException') We experience different behaviors changing the time of background. Sometimes when we define the time of background to 1 the exception disappear. The real question is: Is there any other way to refresh the app's elements in selenium? or appium? Thanks for the help and sorry for my inexperience.
has comment: http://stackoverflow.com/comment/90748551
tagged with: selenium
tagged with: webdriver
type: Question

http://stackoverflow.com/q/51902037
tagged with: openpyxl
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/90761258
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/90755309
has comment: http://stackoverflow.com/comment/90768922
type: Question
has comment: http://stackoverflow.com/comment/90756475
has answer: http://stackoverflow.com/a/51914883
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/90756564
has body: I appended information from several Excel files into a single data frame. Each Excel file has the same structure but corresponds to a different city. The city name is always located in the same cell (C2). How can I extract the city name in each file so that it appears as a column for the corresponding rows in my newly created data frame? My appended data frame looks like this: Col1 Col2 40 34 104 108 23 1 43 21 Hence, I can't tell which rows belong to file X or file Y. Ideally, I'd like to have a data frame such as: Col1 Col2 Col3 City A 40 34 City A 104 108 City B 23 1 City B 43 21 I'm not sure if I should edit/write directly to the Excel files before I append them in order to add the corresponding city column. Or if I should this after or in the process of appending to my data frame. Any guidance would be great. Edit: This is my best attempt at reproducing the structure of my Excel sheets. Note the column A and rows 5, 6 and 7 are blank. The city name is located in row 2 column C. I want to extract the information in rows 8 through 11 and add the city name in cell C3 as a column next to these rows. ColA ColB ColC ColD ColE ColF ColG Row1 Type XYZ Row2 CityName XXX Row3 CityCode 10 Row4 RYear 13 Row5 Row6 Row7 Row8 Rank Cat. 88 89 90 91 Row9 11 A 111 106 102 101 Row10 12 B 121 144 126 121 Row11 13 C 100 107 100 101 Edit2: Following ALollz's advice, I tried the following code unsuccessfully. I get an error " 'DataFrame' object has no attribute 'ColC' ". Note that files_xlsx is a list that includes all Excel files. all_data = pd.DataFrame() for f in files_xlsx: city_name = pd.read_excel(f, "SheetA", nrows=2).ColC[1] data = pd.read_excel(f, "SheetA", parse_cols="B:J") data['col_city'] = city_name all_data = all_data.append(data,ignore_index=True) Edit3: Kept trying and finally found something that works. The only issue is that cityname is only set to one row and not the entire column, which is what I want. Any help? df = pd.DataFrame() for f in files_xlsx: city_name =…
has comment: http://stackoverflow.com/comment/90755815
has title: Python/Pandas: Create column in appended file based on Excel cell
accepted answer: http://stackoverflow.com/a/51914883
has comment: http://stackoverflow.com/comment/90755869
tagged with: pandas
has comment: http://stackoverflow.com/comment/90769199
has comment: http://stackoverflow.com/comment/90755395
has comment: http://stackoverflow.com/comment/90756001
favorite count: 0

http://stackoverflow.com/comment/90709122
has text: You need to use at least `locale.setlocale(locale.LC_TIME, '')` to make the locale effective. See also the respective section from Python's [documentation](https://docs.python.org/2/library/locale.html#background-details-hints-tips-and-caveats)
comment on: http://stackoverflow.com/q/51878833
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51808101
tagged with: opencv
has title: How to detect location of text in natural scene using OpenCV Python?
type: Question
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/51850763
tagged with: python
tagged with: computer-vision
tagged with: ocr
type: UnansweredQuestion
has body: I'm trying to do a racing bib recognition system. So far I have reduced the region of interest into the torso area where the racing bib is usually located. This is the output that I currently have: image showing the result image after applying preprocessing techniques and canny edge I am only interested in the racing bib number. I know I have to use stroke width transform but currently I'm stuck at the localization of the racing bib part. Any ideas?

http://stackoverflow.com/q/51825987
has answer: http://stackoverflow.com/a/51826021
answer count: 1
accepted answer: http://stackoverflow.com/a/51826021
score: 0
tagged with: object-detection
has title: Training a model - Redundant Pictures from Different Angles
tagged with: classification
tagged with: python
type: AnsweredQuestion
tagged with: tensorflow
has body: I want to create my own Tensorflow model for a set images. This set would consist of approximately 50 different classifications to choose from. Would there be any benefit/harm to training a model on the same classification image but say from a different view angle? For example, I want to classify a type of frog. I have pictures from the front, side, and back of the same frog. Should I only use the picture from the front, all, or other?
type: Question

http://stackoverflow.com/q/51845668
has body: Hello im trying to run python script inside virtualenv from php but i cannot do it as well. I wanna insert a Social network in my input php and i wanna get link in my php page My php code and script python are in different folders This is my php code: Search Yahoo link <?php if (isset($_POST['Search'])) { $item=$_POST['social_network']; #$tmp = exec("python php_python.py $item"); This line it works if python script isnt in Virtual environment (Outside) $tmp = exec("cd C:/Users/admin/Desktop/python venv\scripts\activate.bat python yahoo.py $item"); echo $tmp; } ?> Python code: from selenium import webdriver import time, sys social_network = int(sys.argv[1]) # will receive values like: Facebook, Instagram, twitter, etc driver= webdriver.Chrome() driver.get('https://espanol.yahoo.com/?p=us') #Search Social Network driver.find_element_by_xpath('//*[@id="uh-search-box"]').send_keys(social_network) driver.find_element_by_xpath('//*[@id="uh-search-button"]').click() time.sleep(5) link = driver.find_element_by_xpath('//*[@id="web"]/ol/li[2]/div/div[1]/div/span[1]').text print(link) driver.quit()
tagged with: selenium
type: Question
has comment: http://stackoverflow.com/comment/90645025
has comment: http://stackoverflow.com/comment/90645546
has comment: http://stackoverflow.com/comment/90695408
score: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
tagged with: php
has comment: http://stackoverflow.com/comment/90711342
has title: How to run python script inside virtualenv from PHP post
has comment: http://stackoverflow.com/comment/90709994
answer count: 0

http://stackoverflow.com/q/51943622
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51943717
score: 1
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/51943717
downvote count: 0
has body: I want to loop trough a local folder with a couple thousand text files, remove the stop-words, and save the files in a sub-folder. My code loops through all files, but writes all text files in ONE new file. I need the files separated - as they where, and with the exact same filename, just without the stop-words. What am I doing wrong? import io from nltk.corpus import stopwords from nltk.tokenize import word_tokenize import glob import os import codecs stop_words = set(stopwords.words('english')) for afile in glob.glob("*.txt"): file1 = codecs.open(afile, encoding='utf-8') line = file1.read() words = word_tokenize(line) words_without_stop_words = [word for word in words if word not in stop_words] new_words = " ".join(words_without_stop_words).strip() appendFile = open('subfolder/file1.txt','w', encoding='utf-8') appendFile.write(new_words) appendFile.close() I see that the filename(s) will be "file1" (line 11) - I just can't get my head around glob (if glob is even the solution?).
has answer: http://stackoverflow.com/a/51943831
tagged with: glob
accepted answer: http://stackoverflow.com/a/51943831
favorite count: 0
tagged with: python-3.x
has title: Loop through files and save them separately
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/90836952

http://stackoverflow.com/comment/90622854
score: 0
comment on: http://stackoverflow.com/q/51818566
type: QuestionComment
type: Comment
has text: @user2906838 well I think so, I was following the tutorial that I mention above.

http://stackoverflow.com/a/51918644
has comment: http://stackoverflow.com/comment/90787367
answers question: http://stackoverflow.com/q/51917091
has comment: http://stackoverflow.com/comment/90792593
accepted answer of: http://stackoverflow.com/q/51917091
score: 2
has body: The main issue with your code is that for all the MovingRectangles in movingrects3, you were updating them using the update2 method, instead of the update3 method. The update2 method only increments the x value, which moves the rectangle horizontally, instead of vertically. However, the update3 method does increment the y value, which will move the rectangles vertically. To fix this problem: First, I, of course, changed the line movingrect3.update2() to movingrect3.update3(). Then, I created screen_width, and screen_height variables, at the top of the script, which we can use for collision detection in the update3 method. Lastly, I changed the collision detection code so that the rectangle will collide off of the bottom and top walls. To do this, I checked if the self.top was less than 20 (the height of the walls), or if the self.bottom was greater than screen_height minus 20. Remember that the point (0, 0) is at the top-left, in pygame. Here is the fixed code: import pygame import sys pygame.init() pygame.display.set_caption("My Game") screen_width, screen_height = 1200, 600 screen = pygame.display.set_mode((screen_width, screen_height)) clock = pygame.time.Clock() BLUE = pygame.Color('dodgerblue3') ORANGE = pygame.Color('sienna3') BLACK = (0, 0, 0) WHITE = (255,255,255) RED = (255, 0, 0) GREEN = (13, 255, 0) YELLOW = (0, 255, 20) BRIGHT_YELLOW = (255, 255, 20) class MovingRect(pygame.Rect): def __init__(self, x, y, w, h, vel): # Calling the __init__ method of the parent class super().__init__(x, y, w, h) self.vel = vel def update(self): self.x += self.vel # Moving if self.right &gt; 600 or self.left &lt; 320: # If it's not in this area self.vel = -self.vel # Inverting the direction def update2(self): self.x += self.vel if self.right &gt; 1180 or self.left &lt; 620: self.vel = -self.vel def update3(self): self.y += self.vel if self.top &lt; 20 or self.bottom &gt; screen_height-20: self.vel = -self.vel def quit_game(): pygame.quit() sys.exit() def text_objects(text,…
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90787294
type: Answer
has comment: http://stackoverflow.com/comment/90791405
upvote count: 2
has comment: http://stackoverflow.com/comment/90787423

http://stackoverflow.com/a/51915926
answers question: http://stackoverflow.com/q/51915453
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/90782500
has comment: http://stackoverflow.com/comment/90785176
has comment: http://stackoverflow.com/comment/90783823
type: AcceptedAnswer
has body: I was able to do that using json and urllib modules import json import urllib.request request = urllib.request.Request('https://rbwm-api.hsbc.com.hk/pws-hk-hase-fsm-papi-prod-proxy/v1/Funds/U44437?targetCurrency=&amp;isPIFund=N%27') resp = urllib.request.urlopen(request) data = json.loads(resp.read()) mi=data['mainInformation'] print(mi['fundCode'], mi['fundName'])
accepted answer of: http://stackoverflow.com/q/51915453

http://stackoverflow.com/comment/90820085
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51934871
score: 0
has text: If you have cuda I recommend taking a look at https://developer.nvidia.com/how-to-cuda-python. That way you don't have to write a wrapper to C/C++

http://stackoverflow.com/comment/90611592
has text: The 3 plot one won't work for the reason I stated. How do I go about updating the data of an existing plot?
comment on: http://stackoverflow.com/q/51828192
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90644433
type: QuestionComment
comment on: http://stackoverflow.com/q/51845385
type: Comment
has text: Oh! Whoops. I see what you mean. It should be def self-replace: No parens. I'm in favor of context and effort. :) But wasn't my example complete? In the sentence: "This article was written by AUTHOR, who is solely responsible for its content." (No quotes in the actual text of course) I want to replace the string AUTHOR with the content of author --and let's say that's Bob Jones. I am looking for a more unit-economical way than s = s.replace('AUTHOR', author)
score: 0

http://stackoverflow.com/q/51942698
linked to: http://stackoverflow.com/q/734598
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90835049
has comment: http://stackoverflow.com/comment/90834860
score: 1
linked to: http://stackoverflow.com/q/11907163
possible better answer: http://stackoverflow.com/a/51942721
upvote count: 1
has answer: http://stackoverflow.com/a/51943118
has answer: http://stackoverflow.com/a/51942721
type: Question
has comment: http://stackoverflow.com/comment/90835199
tagged with: kill
linked to: http://stackoverflow.com/q/1728330
linked to: http://stackoverflow.com/q/12978013
has title: Kill a batch file containing the python script within
tagged with: batch-file
answer count: 2
has body: I have a problem. I need to kill the batch file using the python script residing within the same batch file. The batch file has abc.py script as the first one along with other scripts. So I need to kill the batch file so that others don't get executed. Here is what I have tried: for proc in psutil.process_iter(): if proc.name() == "python.exe" and len(proc.cmdline()) &gt; 1 and "abc.py" in proc.cmdline()[1]: proc.terminate() But this only kills the python script, not the batch file. Tried killing the pid with the same effect. os.system("taskkill /F /PID " + str(os.getpid())) Edit 1 The script checks for existence of another running script and then needs to terminate itself.
linked to: http://stackoverflow.com/q/9426045
accepted answer: http://stackoverflow.com/a/51943118
downvote count: 0
has comment: http://stackoverflow.com/comment/90835083
favorite count: 0

http://stackoverflow.com/q/51905337
tagged with: sqlalchemy
answer count: 1
has body: I created a table in postgresql by SqlAlchemy: my_table = Table('test_table', meta, Column('id', Integer,primary_key=True,unique=True), Column('value1', Integer), Column('value2', Integer) ) And I want to upsert this table by a dataframe like: id value1 value2 0 1 32.0 1 1 2 2.0 32 2 3 NaN 3 3 4 213.0 23 I tried my code to upsert it by on_conflict_do_update in SqlAlchemy as follows: insert_statement = sqlalchemy.dialects.postgresql.insert(my_table,).values(df.to_dict(orient='records')) upsert_statement = insert_statement.on_conflict_do_update( index_elements=['id'], set_= df.to_dict(orient='dict') ) conn.execute(upsert_statement) But show this error: (psycopg2.ProgrammingError) can't adapt type 'dict' My SqlAlchemy version is 1.2.10, and psycopg2 version is 2.7.5. Can someone help me?
has comment: http://stackoverflow.com/comment/90821192
has answer: http://stackoverflow.com/a/51935542
linked to: http://stackoverflow.com/q/23353732
upvote count: 4
type: AnsweredQuestion
downvote count: 0
favorite count: 0
tagged with: postgresql
type: Question
accepted answer: http://stackoverflow.com/a/51935542
tagged with: python
score: 4
has title: How to use pandas to do upsert in SqlAlchemy
tagged with: psycopg2

http://stackoverflow.com/a/51837712
has body: You have to specify the format as "%Y-%m-%dT%H:%M:%S.%fZ" while conversion In [11]: from datetime import datetime In [12]: out_format = "%Y-%m-%d" In [13]: input_format="%Y-%m-%dT%H:%M:%S.%fZ" In [14]: date_time_obj = datetime.strptime(time,input_format) In [15]: date_time_obj Out[15]: datetime.datetime(2016, 4, 15, 12, 24, 20, 707000) In [16]: date_time_str = date_time_obj.strftime(out_format) In [17]: date_time_str Out[17]: '2016-04-15'
upvote count: 3
score: 3
downvote count: 0
answers question: http://stackoverflow.com/q/51837462
type: Answer

http://stackoverflow.com/a/51883459
has comment: http://stackoverflow.com/comment/90727092
accepted answer of: http://stackoverflow.com/q/51883391
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51883391
has comment: http://stackoverflow.com/comment/90718793
type: Answer
score: 0
has body: Here is a code example that uses iteration and subprocess to do the work: import subprocess output = ['Gig 5/1', 'Gig 5/37', 'Gig 6/37', 'Gig 5/7', 'Gig 6/3', 'Gig 5/3'] for item in output: subprocess.call(('show', 'interface', item)) This is assuming these are system commands. If not you will have to replace subprocess with something more appropriate. Another way is to use a dictionary instead of a list: output = { 'Gig 5/1': None, 'Gig 5/37': None, 'Gig 6/37': None, 'Gig 5/7': None, 'Gig 6/3': None, 'Gig 5/3': None, } for key in output: output[key] = do_something_with(key) The output will be like: { 'Gig 5/1': "result for Gig 5/1", 'Gig 5/37': "result for Gig 5/37", } Or you can access it like: for interface, value in output.items(): print(interface, value)

http://stackoverflow.com/comment/90818101
comment on: http://stackoverflow.com/q/51933437
has text: Ok, I'll try that again. Since I screwed it up the first time, suggestions would be appreciated. It doesn't look like there is a shared library for Python so I need to do that first.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90645419
type: QuestionComment
type: Comment
has text: First, why are you not using a `with` statement for your output file, the way you are for your input file? That means you don’t close or flush the file, which is usually a bad thing.
comment on: http://stackoverflow.com/q/51845854
score: 0

http://stackoverflow.com/a/51860054
upvote count: 4
accepted answer of: http://stackoverflow.com/q/51859815
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 4
has comment: http://stackoverflow.com/comment/96247791
answers question: http://stackoverflow.com/q/51859815
has body: The way you are calling Concatenate Function is not correct. Concatenate expects one argument which specifies the axis of concatenation. What you are trying to achieve can be done using keras's functional API. just change the following code model = Concatenate([ model1, model2, model3, model4, model5, model6]) model.add(Dense(512, activation='relu')) model.add(Dropout(0.75)) model.add(Dense(1024, activation='relu')) model.add(Dropout(0.75)) model.add(Dense(40, activation='softmax')) to merged = Concatenate()([ model1.output, model2.output, model3.output, model4.output, model5.output, model6.output]) merged = Dense(512, activation='relu')(merged) merged = Dropout(0.75)(merged) merged = Dense(1024, activation='relu')(merged) merged = Dropout(0.75)(merged) merged = Dense(40, activation='softmax')(merged) model = Model(inputs=[model1.input, model2.input, model3.input, model4.input, model5.input, model6.input], outputs=merged) N.B Though it is not the question being asked, I've noticed that you have been using very large dropout rate( But this may depend on the problem you are trying to solve). 0.75 drop rate means you are dropping 75% of the neurons while training. Please consider using small drop rate because the model might not converge.

http://stackoverflow.com/comment/90684751
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51847801
has text: no I don't. in my case the app appeared on my desktop. I didn't use github.

http://stackoverflow.com/q/51878706
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/51878998
has body: I have a JSON file with multiple duplicate keys in the following format: "data": { "nameA": { "result": someInt, "timestamp": "someTime" }, "nameB": { "result": someInt, "timestamp": "someTime" }, "nameA": { "result": someInt, "timestamp": "someTime" }, "nameC": { "result": someInt, "timestamp": "someTime" } } I need to dynamically determine the number of instances of each key and print them out. What would be the best way to accomplish this for a JSON in this format?
favorite count: 0
has comment: http://stackoverflow.com/comment/90708983
linked to: http://stackoverflow.com/q/29321677
accepted answer: http://stackoverflow.com/a/51878998
has comment: http://stackoverflow.com/comment/90709380
has comment: http://stackoverflow.com/comment/90709027
upvote count: 2
tagged with: python
score: 2
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/json
has title: Counting duplicate JSON keys in python
has comment: http://stackoverflow.com/comment/90708718
type: Question
linked to: http://stackoverflow.com/q/14902299

http://stackoverflow.com/comment/90854377
score: 0
type: AnswerComment
has text: Oh for crying out loud...thanks.
type: Comment
comment on: http://stackoverflow.com/a/51951797

http://stackoverflow.com/a/51919707
has body: Pre-allocation is still possible. Read the size of the full file, then allocate memory for whatever object. Where do you save files? If performance takes a dive during a loop it's usually indicative of accessing an ever-growing container. Try writing all information in a pre-allocated array and then write all data entries at once in the *.csv, instead of opening the ever-growing *.csv file once every loop. This will fix the issue in this case. I'm assuming that results = label_image(image, graph, session, input_height=299, input_width=299, input_layer="Mul") does not open any container but works only on the input arguments.
score: 0
has comment: http://stackoverflow.com/comment/90789443
type: Answer
answers question: http://stackoverflow.com/q/51919344

http://stackoverflow.com/comment/90796010
comment on: http://stackoverflow.com/a/51922915
has text: That might be the cause! I'm using jquery .load('url to my view') to fill a modal that pops up in the main page so I think that you're right!! Thanks a million for helping me!
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/51878524
type: Answer
upvote count: 4
answers question: http://stackoverflow.com/q/51878265
downvote count: 0
score: 4
has comment: http://stackoverflow.com/comment/90709890
has body: You have to change the color of the QPalette::Button role: from PyQt5 import QtWidgets, QtGui class combodemo(QtWidgets.QWidget): def __init__(self, parent = None): super(combodemo, self).__init__(parent) layout = QtWidgets.QHBoxLayout(self) self.cb = QtWidgets.QComboBox() self.cb.addItems(["1", "2"]) pal = self.cb.palette() pal.setColor(QtGui.QPalette.Button, QtGui.QColor(255,255,255)) self.cb.setPalette(pal) layout.addWidget(self.cb) if __name__ == '__main__': import sys app = QtWidgets.QApplication(sys.argv) ex = combodemo() ex.show() sys.exit(app.exec_()) In Windows you need: app.setStyle("fusion")
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90709904
accepted answer of: http://stackoverflow.com/q/51878265

http://stackoverflow.com/q/51891481
has answer: http://stackoverflow.com/a/51892726
has answer: http://stackoverflow.com/a/51892432
tagged with: beautifulsoup
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/51892432
tagged with: python
linked to: http://stackoverflow.com/q/24923826
type: AnsweredQuestion
type: Question
has title: How to get text from this cede using BeautifulSoup?
has comment: http://stackoverflow.com/comment/90734096
has body: I need to get this text 'Please login again' using bs4 Please login again. I have tried this but didn't get anything: page.select('#msgDiv > font > xmp')
score: 0
has answer: http://stackoverflow.com/a/51892517
answer count: 3
accepted answer: http://stackoverflow.com/a/51892517

http://stackoverflow.com/a/51804474
accepted answer of: http://stackoverflow.com/q/51804454
answers question: http://stackoverflow.com/q/51804454
has comment: http://stackoverflow.com/comment/90565091
type: AcceptedAnswer
downvote count: 0
has body: w.bind('&lt;Return&gt;', initializeVars) Event bindings expect a function that takes an event argument as the first parameter. So while you use the initializeVars correctly as a button handler, you need to accept the event parameter for the bind to work. If you don’t need the event, you can also make it optional: def initializeVars(event = None): # ... print('initializing variables')
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/q/51848349
upvote count: 1
answer count: 1
favorite count: 0
tagged with: python
tagged with: dictionary
has title: creating a dictionary in Pandas using groupby
type: AnsweredQuestion
has body: I am trying to create a dictionary for the following dataset usin: id value 1 a 1 b 1 c 2 e 2 f 2 g 3 h 3 g 3 l The output should be like this {1: [a,b,c], 2:[e, f, g], 3: [h, g, l]} I know some references on how create dictionary, but none of them give such an output. Thank you.
downvote count: 0
score: 1
accepted answer: http://stackoverflow.com/a/51848384
type: Question
has answer: http://stackoverflow.com/a/51848384
tagged with: pandas

http://stackoverflow.com/q/51935550
has answer: http://stackoverflow.com/a/51975852
tagged with: gmm
downvote count: 0
linked to: http://stackoverflow.com/q/29095769
possible better answer: http://stackoverflow.com/a/51975852
has answer: http://stackoverflow.com/a/52482295
tagged with: scikit-learn
favorite count: 0
has comment: http://stackoverflow.com/comment/90831695
tagged with: python
has body: I am trying to generate a Universal Background Model (UBM) based on a huge array of extracted MFCC features but I keep getting aMemoryError when I am fitting my data to the model. Here is the relevant code section: files_features.shape (2469082, 56) gmm = GMM(n_components = 1024, n_iter = 512, covariance_type = 'full', n_init = 3) gmm.fit(features) Is there a way to solve this error or to decompose the processing of the data to avoid the memory error. I am quite new to this field and would appreciate any help I get. [Update] Unfortunately the answers mentioned in here do not solve my issue since the data_set is assumed to have low variance, whereas in my case: round(np.var(files_features), 3) 47.781 Incremental fitting is maybe a solution but scikit-learn does not have such a partial_fit for GMMs. I would appreciate any suggestions on how to tackle this, whether alternative libs suggestions, partial_fit reference implementations or processing the data batch by batch (which does not work in this case because GMM.fit() is memory-less) ?
has title: How to solve MemoryError in sklearn when fitting huge data to a GMM?
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52482295
score: 1
upvote count: 1
tagged with: memory
type: Question
answer count: 2

http://stackoverflow.com/a/51890857
has comment: http://stackoverflow.com/comment/90733068
answers question: http://stackoverflow.com/q/51890152
score: 4
type: Answer
upvote count: 4
has comment: http://stackoverflow.com/comment/90732869
downvote count: 0
has body: Your problem is you're updating memory when n is already in the memory. The whole process of your first rec(5) is: rec(5) = rec(3) + rec(4) = rec(1) + rec(2) + rec(4) = 1 + 1 + rec(2) + rec(3) Until here everything is correct. Then your method will calculate rec(2) where 2 is already in your memory, so your new value for rec(2) is 2. If you don't understand why, see here: def rec(n): if n in memory: value = n # ... memory[n] = value return value Then it calculates the value of rec(3), and 3 is also in memory, so rec(3) is now 3 Then rec(5) = 1 + 1 + 2 + 3 = 7 For the second time you run it, since 5 is in memory, so the output is 5. One possible solution: def rec(n): if n in memory: return memory[n] elif n == 1: value = 1 elif n == 2: value = 1 elif n &gt; 2: value = rec(n - 2) + rec(n - 1) memory[n] = value return value

http://stackoverflow.com/a/51951567
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51951181
has body: You should be iterating over the duration rather than directly comparing it to a number. You could do this. import pandas as pd df = pd.read_csv('file.csv', sep=';') def get_cost(df): t_zone = 720 max_rate = 5.5 rate = 0.0208 duration = df['t1'] ratecol = [] for i in duration: if i &lt; t_zone: if(i * rate) &gt;= max_rate: ratecol.append(max_rate) else: ratecol.append(i * rate) else: if i &gt;= 720: x = int(i/720) y = ((i%720) * rate) if y &gt;= max_rate: ratecol.append((x * max_rate) + max_rate) else: ratecol.append((x * max_rate) + y) return ratecol df['cost'] = get_cost(df) This code produces exact same result as the one posted before.
type: Answer
downvote count: 0

http://stackoverflow.com/q/51947810
answer count: 1
tagged with: python
type: UnansweredQuestion
tagged with: pyside2
has answer: http://stackoverflow.com/a/51948222
tagged with: qml
type: Question
tagged with: qvideofilterrunnable
has body: I am attempting to show a video feed while processing the image with OpenCV. I already have a script that does the image processing using OpenCV and Python, but attempting to add any filter to the VideoOutput results in a segmentation fault. The documentation only has examples for C++, but I have tried to replicate it exactly in Python. Here is my Python file (example.py): from PySide2.QtWidgets import QApplication from PySide2.QtQml import qmlRegisterType from PySide2.QtQuick import QQuickView from PySide2.QtMultimedia import QAbstractVideoFilter, QVideoFilterRunnable from PySide2.QtCore import QUrl class ExampleFilterRunnable(QVideoFilterRunnable): def run(self, frame, surfaceFormat, flags): return frame class ExampleFilter(QAbstractVideoFilter): def createFilterRunnable(self): return ExampleFilterRunnable() app = QApplication([]) qmlRegisterType(ExampleFilter, "ExampleFilter", 1, 0, "ExampleFilter") view = QQuickView() url = QUrl("example.qml") view.setSource(url) view.setResizeMode(view.SizeRootObjectToView) view.show() app.exec_() And the QML (example.qml): import QtQuick 2.0 import QtQuick.Controls 2.3 import QtMultimedia 5.8 import ExampleFilter 1.0 Rectangle { id: rectangle width: 800 height: 600 color: "black" ExampleFilter { id: filter } MediaPlayer { id: player source: "https://archive.org/download/Mario1_500/Mario1_500_LQ.avi" autoPlay: true } VideoOutput { id: videoOutput source: player filters: [filter] anchors.fill: parent } } I added debug output to try to understand what was happening, as no errors are printed beside "Segmentation fault (core dumped)". The segmentation fault occurs sometime after the ExampleFilterRunnable is instantiated in createFilterRunnable and before ExampleFilterRunnable::run is called. I have run it on different computers with different video cards, and with different types of videos and camera feeds, and the result is the same. If I comment out the filters: [filter] line in VideoOutput, the video plays.
score: 0
has title: QVideoFilterRunnable causes Segmentation Fault with PySide2

http://stackoverflow.com/comment/90708018
comment on: http://stackoverflow.com/q/51878358
score: 0
has text: Answering this will be extremely difficult without knowing what the data looks like. Can you include any of it?
type: Comment
type: QuestionComment

http://stackoverflow.com/a/63248615
answers question: http://stackoverflow.com/q/51912999
downvote count: 0
has body: I solved this by reopening cmd in administration mode, activating virtual env, and installing again. This was with Tensorflow 2.3.0 in a virtual environment.
type: Answer
has comment: http://stackoverflow.com/comment/111850113
score: 2
upvote count: 2

http://stackoverflow.com/comment/90661820
has text: Oh, I'm sorry, I checked my .YAML file and remove null fields, problem resolved. Thanks, my mistake :)
score: 1
comment on: http://stackoverflow.com/q/51854492
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/118599021
comment on: http://stackoverflow.com/a/67093272
has text: @MartinPrikryl SFTP is the abbreviation of SSH File Transfer Protocol, so basically if you have SFTP you have a Linux server, maybe you mean FTPS!
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/90789020
comment on: http://stackoverflow.com/a/51919380
type: AnswerComment
score: 0
type: Comment
has text: It gives me dtype('O') when I have done df.PLU.dtype

http://stackoverflow.com/comment/90816846
has text: No one can answer your question if you do not specify the expected output. NB : "extract everything as a text" is not a useful spec (xml IS text already).
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51932120
type: QuestionComment

http://stackoverflow.com/a/51869889
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90716346
has comment: http://stackoverflow.com/comment/90715950
type: Answer
has body: Renaming list to tensor_list since it's bad practice to use reserved keywords as variable names. tensor_list =[] for i,chunk in enumerate(tensor.chunk(100,dim=0)): output = hiddenlayer(chunk).squeeze() tensor_list.append(output) result = torch.reshape(torch.stack(tensor_list,0), (-1, 1)) result.size() should now return torch.Size([2500, 1])
answers question: http://stackoverflow.com/q/51851966
has comment: http://stackoverflow.com/comment/90715694
accepted answer of: http://stackoverflow.com/q/51851966

http://stackoverflow.com/a/51898231
upvote count: 1
has body: You can use a column coding which night it is using date of pandas datetime series. And then use this column for a groupby to compute your rolling mean per week: df.Time = pd.to_datetime(df.Time) df['night'] = (df.Time.dt.hour&gt;22) | (df.Time.dt.hour &lt; 6) df['date'] = df.Time.dt.date idx = (df.night) &amp; (df.Time.dt.hour&gt;22) df.loc[idx,'date'] = df.loc[idx,'date'].values + pd.DateOffset(1) df.date = pd.to_datetime(df.date) df['rolling_mean'] = np.nan df.loc[df.night,'rolling_mean'] = df.loc[df.night,'date'].apply(lambda x : df.loc[df.night &amp; df.date.between(x-pd.DateOffset(3),x+pd.DateOffset(3)),'Value'].mean()) df.drop(['night','date'],1,inplace = True) Time Value rolling_mean 1 2016-02-16 08:40:14.133000 12 NaN 2 2016-02-16 11:25:14.133000 4 NaN 3 2016-02-16 23:45:14.133000 8 8.000000 4 2016-03-16 08:40:14.002700 17 NaN 5 2016-03-16 23:45:14.133000 2 5.666667 6 2016-03-16 23:50:14.133000 6 5.666667 7 2016-03-16 23:55:14.133000 9 5.666667 8 2016-04-16 08:40:14.133000 10 NaN 9 2016-04-16 11:20:14.133000 2 NaN 10 2016-04-16 12:40:14.133000 7 NaN 11 2016-04-16 23:45:14.133000 5 5.000000 12 2016-05-16 08:40:14.002700 11 NaN 13 2016-05-16 23:40:14.133000 3 3.500000 14 2016-05-16 23:50:14.133000 4 3.500000 15 2016-06-16 08:40:14.002700 11 NaN 16 2016-06-16 10:30:14.002700 27 NaN 17 2016-06-16 23:25:14.133000 3 4.000000 18 2016-06-16 23:30:14.133000 5 4.000000 19 2016-07-16 08:40:14.002700 7 NaN 20 2016-07-16 11:15:14.002700 9 NaN 21 2016-07-16 23:45:14.133000 18 18.000000 It is a heavy way to do this and there is probably a more elegant and pythonic way to do it, but at least you have your output! EDIT: There must definitely be a better way to do it using pandas.DataFrame.rolling on a subdataframe only containing the night rows. See This question for example. Here is a suboptimal example: df['night'] = (df.Time.dt.hour&gt;22) | (df.Time.dt.hour &lt; 6) df['date'] = df.Time.dt.date idx = (df.night) &amp; (df.Time.dt.hour&gt;22) df.loc[idx,'date'] = df.loc[id…
has comment: http://stackoverflow.com/comment/90755126
accepted answer of: http://stackoverflow.com/q/51895572
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51895572
has comment: http://stackoverflow.com/comment/90802547
downvote count: 0
score: 1
type: Answer

http://stackoverflow.com/q/51828219
type: Question
score: 3
tagged with: python-dateutil
has answer: http://stackoverflow.com/a/51828344
has title: python strptime vs dateutil - recommended use
downvote count: 2
answer count: 2
favorite count: 0
has body: I need to convert between strings and datetime objects quite often - up until now i have always used strptime and strftime. I started working with the google calendar API where i recieve strings like this: '2018-03-17T09:00:00+01:00 It seems like i need to convert the +01:00 into 0100 for strptime which is a little annoying. While i dont have this issue with dateutil there are a few other inconveniences.Also i saw that the last update of dateutil was in 2016 which seems odd. So my question is which one would you recommend for adding and substracting dates and datetimes and switching between string and datetime obj? Also is dateutil still maintained or is it outdated? Thanks a lot! - Sally
has comment: http://stackoverflow.com/comment/90610820
upvote count: 5
has answer: http://stackoverflow.com/a/51828436
tagged with: python
has comment: http://stackoverflow.com/comment/90611003
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90610963

http://stackoverflow.com/q/51922350
has title: Web scraping into a dataframe. Getting error when adding a column
tagged with: pandas
score: 1
favorite count: 0
has body: My error: "list indices must be integers or slices, not list" I know that there are seemingly endless amounts of posts related to that error, but I've searched and can't figure it out. If there is a solution that I missed and will help me, please let me know. Anyways... I'm using pandas to web scrape stock information into a dataframe, then add two calculated columns to the end: to calculate the price another unrelated calc The issues I'm seeing is when I try to add the first calculated column (the last bit of code): # Dependencies from bs4 import BeautifulSoup import requests import pandas as pd url = 'http://www.dividend.com/dividend-stocks/preferred-dividend-stocks.php#stocks&amp;sort_name=Symbol&amp;sort_order=ASC&amp;page=1' tables = pd.read_html(url) tables type(tables) type(tables[0]) tables[0].head() tables['Perp Value'] = (1/(tables['Dividend Yield']/100))*tables['Annual Dividend'] tables[0].head() When I try to add the column 'Perp Value' I get the error. What do I need to add to be able to do my calc? For reference, the unformatted data looks like: \nDividend Yield\n \nCurrent Price\n \nAnnual Dividend\n \n52-Week High\n \ 0 8.04% $25.65 $2.06 25.98 1 7.61% $25.47 $1.94 25.95 2 6.66% $25.82 $1.72 28.80 3 7.47% $25.95 $1.94 26.87 4 5.78% $25.72 $1.49 28.99 5 8.06% $26.20 $2.11 26.00 6 7.72% $23.87 $1.84 0.00 7 7.75% $23.80 $1.84 0.00 8 7.80% $24.05 $1.88 0.00 9
has answer: http://stackoverflow.com/a/51922503
upvote count: 1
tagged with: python
type: AnsweredQuestion
type: Question
accepted answer: http://stackoverflow.com/a/51922503
downvote count: 0
answer count: 1
tagged with: calculated-columns

http://stackoverflow.com/comment/90767731
has text: The code won't run (on TF 1.8 or 1.9) since the given `optimizer` is not an `Optimizer`. Removing the `lambda:` solves that.
comment on: http://stackoverflow.com/q/51907813
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51913931
has comment: http://stackoverflow.com/comment/90778062
accepted answer: http://stackoverflow.com/a/51913949
type: Question
linked to: http://stackoverflow.com/q/12923264
has answer: http://stackoverflow.com/a/51913965
has comment: http://stackoverflow.com/comment/90777939
possible better answer: http://stackoverflow.com/a/51913950
has answer: http://stackoverflow.com/a/51913950
answer count: 3
has comment: http://stackoverflow.com/comment/90778033
has comment: http://stackoverflow.com/comment/90777995
favorite count: 0
has body: I have the following code: class Thing: def __init__(self): self.a = 30 self.b = 10 def sumit(self): return self.a + self.b giventhing = Thing print(giventhing.sumit/2) I get this error: TypeError: unsupported operand type(s) for /: 'function and 'int'
has answer: http://stackoverflow.com/a/51913949
score: 0
has comment: http://stackoverflow.com/comment/90777959
has comment: http://stackoverflow.com/comment/90777883
tagged with: python
type: AnsweredQuestion
upvote count: 2
downvote count: 2
has comment: http://stackoverflow.com/comment/90778020
has title: Why does this method not return a value?

http://stackoverflow.com/comment/90764050
type: Comment
comment on: http://stackoverflow.com/q/51906709
type: QuestionComment
has text: OK. But still get same "tensorflow.python.training.basic_session_run_hooks.NanLossDuringTrainingError: NaN loss during training." error.
score: 0

http://stackoverflow.com/comment/90625693
type: Comment
comment on: http://stackoverflow.com/a/51821910
has text: @iMath That said, https://stackoverflow.com/questions/5366100/pyinstaller-but-keeping-py-files-upgradeable looks relevant from the information you gave.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/132096680
score: 2
comment on: http://stackoverflow.com/a/64066439
has text: There seem to be some flaws in these performance comparisons. The first two measurements are not at least one sigma apart, and the last measurement is flawed because it also measures the `[[1]*1000]*1000` call which is probably slow and dominates the runtime.
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/90607090
type: AnswerComment
type: Comment
score: 1
comment on: http://stackoverflow.com/a/51826196
has text: @MrYouMath Is your .kv the same as mine?

http://stackoverflow.com/q/51861691
answer count: 2
has body: I have a list with 5 items [6,4,2,4,6] If I needed the list to be 10 items long, with the same sum and relative distribution it would look like [3,3,2,2,1,1,2,2,3,3] That's simple because with double the number of items I just split each item in the previous list in half. I'm trying to figure out a way make the first list any number of items long. Perhaps 3, 7, 12, 999... Obviously it will very often not be possible to do it perfectly (as in the simple example), I'm trying to get to a solution that provides a best fit.
score: 0
has answer: http://stackoverflow.com/a/51861775
has title: Transform a list into a list with greater or fewer items, maintaining the sum of list and relative difference between items
has answer: http://stackoverflow.com/a/51862471
accepted answer: http://stackoverflow.com/a/51862471
tagged with: python
has comment: http://stackoverflow.com/comment/90676169
possible better answer: http://stackoverflow.com/a/51861775
type: AnsweredQuestion
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/90676269

http://stackoverflow.com/q/51901676
upvote count: 22
has comment: http://stackoverflow.com/comment/90754628
answer count: 2
linked to: http://stackoverflow.com/q/13659042
has title: get the lists of functions used/called within a function in python
favorite count: 0
has comment: http://stackoverflow.com/comment/90754644
tagged with: python
has answer: http://stackoverflow.com/a/51904019
has comment: http://stackoverflow.com/comment/90754630
has comment: http://stackoverflow.com/comment/90754573
has comment: http://stackoverflow.com/comment/90754633
has comment: http://stackoverflow.com/comment/90758905
type: AnsweredQuestion
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/51903975
has comment: http://stackoverflow.com/comment/90766408
has answer: http://stackoverflow.com/a/51903975
downvote count: 1
type: Question
has body: Is there any tool/library through which the list of methods/functions called within another methods/functions can be listed? For example: If that tool or library runs for below method def calculate(a: int, b: int, operator: Operator): if operator == Operator.add: add(a, b) elif operator == Operator.subtract subtract(a, b) then it should return 1. add 2. subtract This question is almost same as this one but it's for Java. This is basically same as what PyCharm does for Find Usage. Thanks!
has comment: http://stackoverflow.com/comment/90759809
has comment: http://stackoverflow.com/comment/90755081
linked to: http://stackoverflow.com/q/12111717
accepted answer: http://stackoverflow.com/a/51904019
score: 21
has comment: http://stackoverflow.com/comment/90755015
has comment: http://stackoverflow.com/comment/90759321

http://stackoverflow.com/q/51933437
has body: I'm working on Ubuntu with Apache2, Python 3.6.1. I followed the directions here to set it up with Django and mod_wsgi: How To Serve Django Applications with Apache and mod_wsgi on Ubuntu 14.04 I've looked at a lot of similar questions and still can't get it to work. The Apache error log spews the "ImportError: No module named 'encodings' almost constantly. Here are the relevant settings in my Apache2 files: In 000-default.conf: WSGIDaemonProcess myproject python-home=/home/user/myproject/myprojectenv/ python-path=/home/user/myproject/myprojectenv/bin/python WSGIProcessGroup myproject WSGIScriptAlias / /home/user/myproject/myprojectenv/myproject/myproject/wsgi.py In apache2.conf: WSGIPythonPath /home/user/myproject/myprojectenv Note that, when I check sys.prefix it equals what I have in the WSGIPythonPath above. Yes, I've activated the virtual environment. For my environment variables, I have: PATH = /home/user/myproject/myprojectenv/bin:$PATH PYTHONPATH = /home/user/myproject/myprojectenv/bin:$PYTHONPATH PYTHONHOME = not set I've tried various combinations of the environment variables being set and not being set. None that I've tried have worked. When I followed the steps from the link above, I'm not sure that a new mod_wsgi was built that is for Python 3.6.1. I had tried (on another copy of my VM) to explicitly build a Python shared library and to build mod_wsgi with that. It failed miserably. I hesitate to go that route again unless I'm sure that's what I need to do. Any help is greatly appreciated.
has comment: http://stackoverflow.com/comment/90816995
has answer: http://stackoverflow.com/a/51952565
has comment: http://stackoverflow.com/comment/90818101
tagged with: wsgi
answer count: 1
tagged with: apache2
has comment: http://stackoverflow.com/comment/90817819
tagged with: python
has comment: http://stackoverflow.com/comment/90817049
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51952565
has comment: http://stackoverflow.com/comment/90848894
has title: Apache2 on Ubuntu gives Py_Initialize ImportError: No module named encodings
has comment: http://stackoverflow.com/comment/90817526
tagged with: django
has comment: http://stackoverflow.com/comment/90817627
has comment: http://stackoverflow.com/comment/90817385
type: Question
has comment: http://stackoverflow.com/comment/90851641
score: 0

http://stackoverflow.com/comment/90603346
has text: Nah! Just tried to run script on server and got 1.7 seconds. Just wonder why it work so slow if I launch it from my local machine
type: QuestionComment
comment on: http://stackoverflow.com/q/51821428
score: 0
type: Comment

http://stackoverflow.com/a/51877299
accepted answer of: http://stackoverflow.com/q/51877124
has comment: http://stackoverflow.com/comment/90705974
answers question: http://stackoverflow.com/q/51877124
has comment: http://stackoverflow.com/comment/90706095
has comment: http://stackoverflow.com/comment/90706064
type: Answer
has comment: http://stackoverflow.com/comment/90705991
upvote count: 16
has body: How about something like this from tkinter import * from tkinter import ttk from tkinter import filedialog gui = Tk() gui.geometry("400x400") gui.title("FC") def getFolderPath(): folder_selected = filedialog.askdirectory() folderPath.set(folder_selected) def doStuff(): folder = folderPath.get() print("Doing stuff with folder", folder) folderPath = StringVar() a = Label(gui ,text="Enter name") a.grid(row=0,column = 0) E = Entry(gui,textvariable=folderPath) E.grid(row=0,column=1) btnFind = ttk.Button(gui, text="Browse Folder",command=getFolderPath) btnFind.grid(row=0,column=2) c = ttk.Button(gui ,text="find", command=doStuff) c.grid(row=4,column=0) gui.mainloop() Summary: You were creating your widgets and using the layout grid on the same line. This is a bad idea. I've split it out so that you define the button and then do the layout on a new line I've added a Stringvar, this is a special tkinter variable that can be used to automatically update fields I've added two functions, one is called when you press the new browse button and will bring up the folder select dialog. I've added another for the "Find" button which you can use for what ever you want to do with the folder path. Consider: More descriptive naming. Note that I've called the new button btnFind rather than a single character like you have done for the other widgets. This will make debugging/understanding your code easier when you come back to look at it. EDIT: Since you want more than 1 of these folder select items, it is worth creating a class that contains all the properties and functions for selecting a folder. Here is an example from tkinter import * from tkinter import ttk from tkinter import filedialog gui = Tk() gui.geometry("400x400") gui.title("FC") class FolderSelect(Frame): def __init__(self,parent=None,folderDescription="",**kw): Frame.__init__(self,master=parent,**kw) self.folderPath = StringVar() self.lblName = Label(self, text=folderDescription) self.lblName.grid(row=0,column=0) self.entPa…
downvote count: 0
has comment: http://stackoverflow.com/comment/90706489
score: 16
type: AcceptedAnswer

http://stackoverflow.com/q/51886641
has comment: http://stackoverflow.com/comment/90730952
tagged with: textblob
downvote count: 0
favorite count: 0
type: UnansweredQuestion
has title: how to run textblob on localhost?
has comment: http://stackoverflow.com/comment/90730871
has comment: http://stackoverflow.com/comment/90728387
tagged with: python
score: 2
has comment: http://stackoverflow.com/comment/90731001
answer count: 0
upvote count: 2
tagged with: localhost
type: Question
has body: On my locat host , if i run simple print statement it works fine. but i want to use textblob for sentiment analysis. For this purpose, I am trying to run below code on my localhost but it's showing error. Code: #!C:\fname lname\AppData\Local\Programs\Python\Python37-32\python.exe from textblob.classifiers import NaiveBayesClassifier from textblob import TextBlob train = [ ('I love this sandwich.', 'pos'), ('This is an amazing place!', 'pos'), ('I feel very good about these beers.', 'pos'), ('This is my best work.', 'pos'), ("What an awesome view", 'pos'), ('I do not like this restaurant', 'neg'), ('I am tired of this stuff.', 'neg'), ("I can't deal with this", 'neg'), ('He is my sworn enemy!', 'neg'), ('My boss is horrible.', 'neg') ] test = [ ('The beer was good.', 'pos'), ('I do not enjoy my job', 'neg'), ("I ain't feeling dandy today.", 'neg'), ("I feel amazing!", 'pos'), ('Gary is a friend of mine.', 'pos'), ("I can't believe I'm doing this.", 'neg') ] cl = NaiveBayesClassifier(train) # Classify some text print(cl.classify("Their burgers are amazing.")) # "pos" print(cl.classify("I don't like their pizza.")) # "neg" # Classify a TextBlob blob = TextBlob("The beer was amazing. But the hangover was horrible. " "My boss was not pleased.", classifier=cl) print(blob) print(blob.classify()) for sentence in blob.sentences: print(sentence) print(sentence.classify()) # Compute accuracy print("Accuracy: {0}".format(cl.accuracy(test))) # Show 5 most informative features cl.show_informative_features(5) I feel problem is these statements. Not sure how to fix it. Not sure if i need to import any library and should place it location where script is placed. from textblob.classifiers import NaiveBayesClassifier from textblob import TextBlob Error appeared as : Server error! The server encountered an internal error and was unable to complete your request. Error message: End of script output before headers: nltk.py If you think this is a server error, please contact the webmaster.…
has comment: http://stackoverflow.com/comment/90752413

http://stackoverflow.com/comment/90571969
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51808229
score: 0
has text: Try uninstalling and then again installing pyqt5 and pyqt5-tools

http://stackoverflow.com/q/51853269
type: Question
accepted answer: http://stackoverflow.com/a/51853290
has title: How to copy a math output to clipboard in Python?
has body: I'm super new to Python so I'm wondering if someone can help me out or link me to an appropriate post that explains this? What I would like to do is 9999**9999 in Python Terminal, then copy the output directly to my clipboard or sent to a file. I tried in Batch using py 9999**9999 &gt;&gt;pythonoutput.txt but only got an error of python.exe: can't open file '9999**9999': [Errno 22] Invalid argument and not sure how I could make that work either. Any ideas? Cheers
score: 0
answer count: 3
tagged with: python
has answer: http://stackoverflow.com/a/51853290
has answer: http://stackoverflow.com/a/51853559
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51906936
has answer: http://stackoverflow.com/a/51906936

http://stackoverflow.com/comment/90752848
type: Comment
type: QuestionComment
score: 1
has text: I cannot run the code because of undefined variables, so it's not complete. "Minimal" must be understood as "not more than necessary".
comment on: http://stackoverflow.com/q/51900272

http://stackoverflow.com/q/51851956
has comment: http://stackoverflow.com/comment/90656950
has body: This question is similar to this one, but with a crucial difference - the solution to the linked question does not solve the issue when the dataframe is grouped into bins. The following code to boxplot the relative distribution of the bins of the 2 variables produces an error: import pandas as pd import seaborn as sns raw_data = {'regiment': ['Nighthawks', 'Nighthawks', 'Nighthawks', 'Nighthawks', 'Dragoons', 'Dragoons', 'Dragoons', 'Dragoons', 'Scouts', 'Scouts', 'Scouts', 'Scouts'], 'company': ['1st', '1st', '2nd', '2nd', '1st', '1st', '2nd', '2nd','1st', '1st', '2nd', '2nd'], 'name': ['Miller', 'Jacobson', 'Ali', 'Milner', 'Cooze', 'Jacon', 'Ryaner', 'Sone', 'Sloan', 'Piger', 'Riani', 'Ali'], 'preTestScore': [4, 24, 31, 2, 3, 4, 24, 31, 2, 3, 2, 3], 'postTestScore': [25, 94, 57, 62, 70, 25, 94, 57, 62, 70, 62, 70]} df = pd.DataFrame(raw_data, columns = ['regiment', 'company', 'name', 'preTestScore', 'postTestScore']) df1 = df.groupby(['regiment'])['preTestScore'].value_counts().unstack() df1.fillna(0, inplace=True) sns.boxplot(x='regiment', y='preTestScore', data=df1) --------------------------------------------------------------------------- ValueError Traceback (most recent call last) &lt;ipython-input-241-fc8036eb7d0b&gt; in &lt;module&gt;() ----&gt; 1 sns.boxplot(x='regiment', y='preTestScore', data=df1) ~\AppData\Local\Continuum\anaconda3\lib\site-packages\seaborn\categorical.py in boxplot(x, y, hue, data, order, hue_order, orient, color, palette, saturation, width, dodge, fliersize, linewidth, whis, notch, ax, **kwargs) 2209 plotter = _BoxPlotter(x, y, hue, data, order, hue_order, 2210 orient, color, palette, saturation, -&gt; 2211 width, dodge, fliersize, linewidth) 2212 2213 if ax is None: ~\AppData\Local\Continuum\anaconda3\lib\site-packages\seaborn\categorical.py in __init__(self, x, y, hue, data, order, hue_order, orient, color, palette, saturation, width, dodge, fliersize, linewidth) 439 width, dodge, fliersize, linewidth): 440 --&gt; 441 self.establi…
downvote count: 0
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/51854093
tagged with: pandas-groupby
tagged with: pandas
has title: Cannot access individual columns of a groupby object of a dataframe after binning it
tagged with: seaborn
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/90659619
has comment: http://stackoverflow.com/comment/90657012
tagged with: indexing
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51854093
score: 1
type: Question
linked to: http://stackoverflow.com/q/51838479

http://stackoverflow.com/q/51936574
tagged with: polar-coordinates
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52517178
downvote count: 0
score: 7
favorite count: 0
has title: How to plot scipy.hierarchy.dendrogram using polar coordinates?
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/52517639
tagged with: python
has answer: http://stackoverflow.com/a/52517639
tagged with: plot
has body: I'm trying to adapt the following resources to this question: Python conversion between coordinates https://matplotlib.org/gallery/pie_and_polar_charts/polar_scatter.html I can't seem to get the coordinates to transfer the dendrogram shape over to polar coordinates. Does anyone know how to do this? I know there is an implementation in networkx but that requires building a graph and then using pygraphviz backend to get the positions. Is there a way to convert dendrogram cartesian coordinates to polar coordinates with matplotlib and numpy? import requests from ast import literal_eval import matplotlib.pyplot as plt import numpy as np def read_url(url): r = requests.get(url) return r.text def cartesian_to_polar(x, y): rho = np.sqrt(x**2 + y**2) phi = np.arctan2(y, x) return(rho, phi) def plot_dendrogram(icoord,dcoord,figsize, polar=False): if polar: icoord, dcoord = cartesian_to_polar(icoord, dcoord) with plt.style.context("seaborn-white"): fig = plt.figure(figsize=figsize) ax = fig.add_subplot(111, polar=polar) for xs, ys in zip(icoord, dcoord): ax.plot(xs,ys, color="black") ax.set_title(f"Polar= {polar}", fontsize=15) # Load the dendrogram data string_data = read_url("https://pastebin.com/raw/f953qgdr").replace("\r","").replace("\n","").replace("\u200b\u200b","") # Convert it to a dictionary (a subset of the output from scipy.hierarchy.dendrogram) dendrogram_data = literal_eval(string_data) icoord = np.asarray(dendrogram_data["icoord"], dtype=float) dcoord = np.asarray(dendrogram_data["dcoord"], dtype=float) # Plot the cartesian version plot_dendrogram(icoord,dcoord, figsize=(8,3), polar=False) # Plot the polar version plot_dendrogram(icoord,dcoord, figsize=(5,5), polar=True) I just tried this and it's closer but still not correct: import matplotlib.transforms as mtransforms with plt.style.context("seaborn-white"): fig, ax = plt.subplots(figsize=(5,5)) for xs, ys in zip(icoord, dcoord): ax.plot(xs,ys, color="black",transform=trans_offset) ax_polar = plt.subplot(111, …
tagged with: cartesian-coordinates
linked to: http://stackoverflow.com/q/20924085
upvote count: 7
tagged with: dendrogram
has answer: http://stackoverflow.com/a/52517178
linked to: http://stackoverflow.com/q/5089030

http://stackoverflow.com/q/51860471
accepted answer: http://stackoverflow.com/a/51860748
has answer: http://stackoverflow.com/a/51860565
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/33747234
has answer: http://stackoverflow.com/a/51860584
has comment: http://stackoverflow.com/comment/90673660
downvote count: 1
type: Question
has body: I have a huge dictionary called Menu. Here's a snippet of it: Menu= { 'Salad': { 'salad': { 'PLU': '32', 'NAME': 'salad', } }, 'Dessert': { 'cookie': { 'PLU': '334', 'NAME': 'cookie ', } }, 'Appetizer': { 'extra sauce': { 'PLU': '61', 'NAME': 'extra sauce', }, "French Fries": { 'PLU': '23', 'NAME': "french fries", }, 'breadsticks': { 'PLU': '59', 'NAME': 'breadsticks', } } } I am trying to get the value of the key by looking for PLU For example: If I want 'PLU:59'. I want 'breadsticks' and 'Appetizer' to show up. So far I can only try fetching the data by manually searching for it. that is by print(menu['Salad']['salad']['PLU']) Any suggestions will help! Please feel free to ask me to clarify anything.
answer count: 8
has title: get value from key in dictionary
has comment: http://stackoverflow.com/comment/90673308
has answer: http://stackoverflow.com/a/51860590
has comment: http://stackoverflow.com/comment/90673295
has comment: http://stackoverflow.com/comment/90673548
possible better answer: http://stackoverflow.com/a/51860565
score: 0
has comment: http://stackoverflow.com/comment/90673328
upvote count: 1
has answer: http://stackoverflow.com/a/51860688
duplicate of: http://stackoverflow.com/q/33747234
has answer: http://stackoverflow.com/a/51860585
favorite count: 0
has answer: http://stackoverflow.com/a/51860607
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/51860978
has answer: http://stackoverflow.com/a/51860748

http://stackoverflow.com/q/51879679
favorite count: 0
has answer: http://stackoverflow.com/a/51879895
accepted answer: http://stackoverflow.com/a/51879895
upvote count: 2
tagged with: python
has answer: http://stackoverflow.com/a/51879885
score: 2
type: AnsweredQuestion
type: Question
answer count: 2
has title: Add column from one dataframe to muliheader dataframe in pandas
downvote count: 0
possible better answer: http://stackoverflow.com/a/51879885
tagged with: pandas
has body: In the following code how to merge the df2 to df3 to get an output like df4. df3 is a multiheader dataframe and in the final ouput i just need the first level of the header as show.how to achieve this &gt;&gt;&gt; df = pd.DataFrame({'Maths':[95,96,97,98] ,'Science': [91,92,93,94]}) &gt;&gt;&gt; df2=pd.DataFrame({'Languages': ['English','Hindi','French','Spanish']}) &gt;&gt;&gt; header = pd.MultiIndex.from_product([['Subjects'],['Maths', 'Science']]) &gt;&gt;&gt; df3 = pd.DataFrame(df.values.tolist(), columns=header) &gt;&gt;&gt; df3 Subjects Maths Science 0 95 91 1 96 92 2 97 93 3 98 94 &gt;&gt;&gt; df2 Languages 0 English 1 Hindi 2 French 3 Spanish Output df4 Subjects Languages Maths Science 0 95 91 English 1 96 92 Hindi 2 97 93 French 3 98 94 Spanish

http://stackoverflow.com/comment/90751346
has text: It seems you got it just right. However, you can avoid nested `with`'s in this case and put it just in a line of code, as I showed in my expansion to your answer.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51900098

http://stackoverflow.com/comment/90828664
has text: I was able to get the links using `link.get('href')` with that loop I suggested. Can you post your output so I can try it out?
comment on: http://stackoverflow.com/q/51939159
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/a/65301211
has body: Here I am considering you had done all the image processing and others. The recommended threshold (cv2.THRESH_OTSU)! mask = np.zeros(img.shape, dtype=img.dtype) cont = cv2.findContours(img_th, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) cont = cont[0] if len(cont) == 2 else cont[1] for c in cont: area = cv2.contourArea(c) if area < 500: cv2.drawContours(mask, [c], -1, (255, 255, 255), -1) print(mask.shape) mask = cv2.cvtColor(mask, cv2.COLOR_BGR2GRAY) # making it to 2D (removing the channel value) removed_border = cv2.bitwise_and(img, img, mask=mask) cv2.imshow("result", removed_border) cv2.waitKey() cv2.destroyAllWindows() If you have any problem with understanding the code please let me know. I m happy to help you out and if you like the answer please thumps up!!! :) Result:
score: 3
downvote count: 1
answers question: http://stackoverflow.com/q/51933300
type: Answer
upvote count: 4

http://stackoverflow.com/comment/90773559
comment on: http://stackoverflow.com/a/51910944
type: AnswerComment
score: 0
type: Comment
has text: What is the meaning of that gray value then? Why does white map to an intermediate gray value and not black? Does that help perceptually, or is there some other reasoning?

http://stackoverflow.com/q/51896674
has answer: http://stackoverflow.com/a/51897764
has body: I have a ODE system for odeint Python module: def equations(p, t, lmbds): return np.array([-p[0] * lmbds[0] + p[1] * lmbds[1], -p[1] * lmbds[1] - p[1] * lmbds[2] + p[0] * lmbds[0]]) This system corresponding to the Markov chain with two states three intensity. The system of equations can contain a different number of equations. Is it possible to generate them on the go, depending on the number of equation entered by the user?
has comment: http://stackoverflow.com/comment/90747228
downvote count: 0
has comment: http://stackoverflow.com/comment/90747266
answer count: 1
accepted answer: http://stackoverflow.com/a/51897764
favorite count: 0
tagged with: odeint
upvote count: 1
tagged with: python
has title: Dynamic generatation of equation system for odeint
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/90746083
tagged with: scipy
type: Question

http://stackoverflow.com/comment/90666644
comment on: http://stackoverflow.com/a/51856949
type: AnswerComment
score: 0
type: Comment
has text: I don't know what was the error but now it works ! Thanks. I'm afraid it might be rather slow for big dataframes (that's why I was first looking into a vectorized solution) but at least this is a working solution, unlike my attempts.

http://stackoverflow.com/q/51831346
has body: Using the googlemaps api, I'm trying to get the "gyms" near a certain location: After importing googlemaps api and typing my user key: client = googlemaps.Client(key) latlon = ' [atitude, longitude' nearby = client.places_nearby(latlon, keyword="gym", radius = 100) print (nearby) I'm getting the following error: Traceback (most recent call last): File "C:/Users/dd/PycharmProjects/untitled/venv/file.py", line 11, in &lt;module&gt; nearby = client.places_nearby(latlon, keyword="gym", radius = 100) File "C:\Users\dd\PycharmProjects\untitled\venv\lib\site-packages\googlemaps\client.py", line 365, in wrapper result = func(*args, **kwargs) File "C:\Users\dd\PycharmProjects\untitled\venv\lib\site-packages\googlemaps\places.py", line 249, in places_nearby rank_by=rank_by, type=type, page_token=page_token) File "C:\Users\dd\PycharmProjects\untitled\venv\lib\site-packages\googlemaps\places.py", line 342, in _places return client._request(url, params) File "C:\Users\dd\PycharmProjects\untitled\venv\lib\site-packages\googlemaps\client.py", line 270, in _request extract_body, requests_kwargs, post_json) File "C:\Users\dd\PycharmProjects\untitled\venv\lib\site-packages\googlemaps\client.py", line 270, in _request extract_body, requests_kwargs, post_json) File "C:\Users\dd\PycharmProjects\untitled\venv\lib\site-packages\googlemaps\client.py", line 270, in _request extract_body, requests_kwargs, post_json) [Previous line repeated 7 more times] File "C:\Users\dd\PycharmProjects\untitled\venv\lib\site-packages\googlemaps\client.py", line 210, in _request raise googlemaps.exceptions.Timeout() googlemaps.exceptions.Timeout
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90616956
answer count: 0
has comment: http://stackoverflow.com/comment/90617301
has title: Using googlemaps api, places_nearby to find locations nearby with a certain keyword
type: Question
has comment: http://stackoverflow.com/comment/90635917
tagged with: google-maps
score: 0

http://stackoverflow.com/comment/105482312
has text: @RoshanBagdiya how do you do a pip install inside a lambda before importing it??
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51859032
score: 1

http://stackoverflow.com/a/51900983
answers question: http://stackoverflow.com/q/51900695
type: Answer
has comment: http://stackoverflow.com/comment/90754608
has comment: http://stackoverflow.com/comment/90755002
has comment: http://stackoverflow.com/comment/93388507
has comment: http://stackoverflow.com/comment/90754915
has body: You can add them like below "python.autoComplete.preloadModules": ["numpy", "pandas", "matplotlib"], also, check the docs! :) https://code.visualstudio.com/docs/python/editing#_autocomplete-and-intellisense
has comment: http://stackoverflow.com/comment/90755756
score: 0
has comment: http://stackoverflow.com/comment/139114988

http://stackoverflow.com/a/55855273
score: 19
has body: Looks like the issue described in: https://github.com/keras-team/keras/pull/11847 and https://github.com/tensorflow/tensorflow/issues/27769 While the bug has yet to be fixed, the problem only occurs when there are both trainable and non-trainable weights in the model. If you do not need to train the model further, you can work around the problem by freezing all the weights prior to saving: from keras import models def freeze(model): """Freeze model weights in every layer.""" for layer in model.layers: layer.trainable = False if isinstance(layer, models.Model): freeze(layer)
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/123962431
accepted answer of: http://stackoverflow.com/q/51944836
answers question: http://stackoverflow.com/q/51944836
type: Answer
upvote count: 19
has comment: http://stackoverflow.com/comment/105727582

http://stackoverflow.com/comment/90756398
score: 1
comment on: http://stackoverflow.com/q/51898251
type: Comment
has text: The ClientKeyExchange does not necessarily uses the PreMasterSecret, it can uses other keys in case of not doing RSA authentication (see 7.4.7 of TLS 1.2 RFC), then it is Diffie-Hellman. So it all depends on the cipher suites negotiated between both parties. Note also that ClientKeyExchange and PreMasterSecret disappeared in TLS 1.3. In short I still think that disabling certificate validation will expose you to too many dangers. Instead use TLS-PSK if you dislike certificates, that will be cleaner.
type: QuestionComment

http://stackoverflow.com/a/51912026
has body: It is explained in the documentation under Indexing using str .str[index] notation indexes the string by position where as [index] will slice based on the index of the series. Using the example s = pd.Series(['A', 'B', 'C', 'Aaba', 'Baca', np.nan,'CABA', 'dog', 'cat']) s.str[3] returns the element at index 3 at each row 0 NaN 1 NaN 2 NaN 3 a 4 a 5 NaN 6 A 7 NaN 8 NaN Whereas s[3] returns 'Aaba'
type: Answer
score: 5
upvote count: 5
downvote count: 0
answers question: http://stackoverflow.com/q/51911933

http://stackoverflow.com/q/51901495
has title: Efficient way to concatenate and sort seasonal time series?
type: AnsweredQuestion
downvote count: 0
score: 1
type: Question
tagged with: numpy
has body: I have a number of numpy arrays, each represents a series of seasonal data. The frequency is year. The 1st array has all the sales value in the 1st week of year, from year 2014 to year 2018. The 2nd array has all the sales value in the 2nd week of year, from year 2014 to year 2018. ... The 52nd array has all the sales value in the 52nd week of year, from year 2014 to year 2018. The following example is kind of tricky as they are not strictly obtained by counting "week of year" and slicking. Rather, they are selected based on the remainder to 52 of a week's relative index to the beginning of time. But the idea is similar... They look like this. arr1 = array([[Timestamp('2014-01-04 00:00:00'), 138.52], [Timestamp('2015-01-03 00:00:00'), 25476.179999999997], [Timestamp('2016-01-02 00:00:00'), 87318.65000000001], [Timestamp('2016-12-31 00:00:00'), 194409.42], [Timestamp('2017-12-30 00:00:00'), 299190.06000000023]], dtype=object) arr2 = array([[Timestamp('2014-01-11 00:00:00'), 0.0], [Timestamp('2015-01-10 00:00:00'), 23848.57000000001], [Timestamp('2016-01-09 00:00:00'), 86814.12], [Timestamp('2017-01-07 00:00:00'), 202016.92], [Timestamp('2018-01-06 00:00:00'), 344430.36000000004]], dtype=object) Now I want to join them into a complete and sorted time series. So the indices will be [arr1.index[0], arr2.index[0], arr3.index[0], ... arr52.index[0], (here we begin a new year) arr1.index[1], arr2.index[1], ...]. The values will be [arr1.value[0], arr2.value[0], arr3.value[0], ... arr52.value[0], (here we begin a new year) arr1.value[1], arr2.value[1], ...]. One way I can think of is to first concatenate all the subseries into a full series, and then sort the series by index. But are there better ways to do this? Thanks! Background The problem came up when I was trying to implement the stl decomposition in Python and one step is to smooth every seasonal subseries independently, and then combine them together.
tagged with: time-series
has answer: http://stackoverflow.com/a/51901591
accepted answer: http://stackoverflow.com/a/51901591
tagged with: pandas
upvote count: 1
answer count: 1
favorite count: 0
tagged with: python

http://stackoverflow.com/q/51895784
score: 1
has body: I will want to retrieve different values ​from a chosen field. Let me explain: I have this class: class SchoolWebServices(models.Model): _name = 'ecole.webservices' name = fields.Char(string='Nom') code_produit = fields.Char(string='Produit') code_CDG = fields.Char(string='Centre de Gestion') code_Catalog = fields.Char(string='Catalogue Produits') I have this other class: class ResPartner_school(models.Model): _name = 'ecole.partner.school' _order = 'id desc' half_pension_name = fields.Many2one(comodel_name="ecole.webservices", string="Lieu") And I have a function who is in the class: ecole.partner.school @api.multi def create_compte_cantine(self): print "Inscription réussie" get_halfpension_name = self.half_pension_name.id if get_halfpension_name: code_Catalog = self.env['ecole.webservices'].code_Catalog I get the id of half_pension_name in my variable get_halfpension_name but I wish to recover the code_Catalog of the same recording too. How to do?
upvote count: 1
has title: retrieve values from the same record from a field odoo 10
type: Question
has answer: http://stackoverflow.com/a/51896736
tagged with: odoo
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51896736

http://stackoverflow.com/q/51903617
has comment: http://stackoverflow.com/comment/90758263
has comment: http://stackoverflow.com/comment/90758565
type: Question
has answer: http://stackoverflow.com/a/51903720
has comment: http://stackoverflow.com/comment/90758508
has comment: http://stackoverflow.com/comment/90758603
has comment: http://stackoverflow.com/comment/90758557
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/90758368
tagged with: membership
has comment: http://stackoverflow.com/comment/90758405
possible better answer: http://stackoverflow.com/a/51903674
has comment: http://stackoverflow.com/comment/90758455
has answer: http://stackoverflow.com/a/51903674
has comment: http://stackoverflow.com/comment/90758440
tagged with: python
has body: How can a check for list membership be inverted based on a boolean variable? I am looking for a way to simplify the following code: # variables: `is_allowed:boolean`, `action:string` and `allowed_actions:list of strings` if is_allowed: if action not in allowed_actions: print(r'{action} must be allowed!') else: if action in allowed_actions: print(r'{action} must NOT be allowed!') I feel there must be a way to avoid doing the check twice, once for in and another time for not in, but can't figure out a less verbose way.
has comment: http://stackoverflow.com/comment/90758390
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51903720
tagged with: list
has comment: http://stackoverflow.com/comment/90758638
has title: Python: how to invert list membership check based on boolean variable?

http://stackoverflow.com/q/51898409
accepted answer: http://stackoverflow.com/a/51898652
type: AnsweredQuestion
type: Question
has body: I am trying to access an Excel file in Python, but I'm getting the following error: FileNotFoundError: [Errno 2] No such file or directory: 'input/sales-feb-2014.xlsx' Could you please help me defining the path of the file? Python Code: from xlrd import open_workbook sheet = open_workbook('input/sales-feb-2014.xlsx').sheet_by_index(0) print (sheet.cell_value(3,0))
has title: Relative path of excel files, python
downvote count: 0
has answer: http://stackoverflow.com/a/51898652
answer count: 1
score: 1
favorite count: 0
tagged with: pycharm
tagged with: path
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/90747991

http://stackoverflow.com/comment/90781344
has text: @Mohit if you wish to specify a format that's not the default date settings - yes... However, it should be appearing... Neil - are you really, really sure you 1) didn't typo it, and 2) have checked the returned source to see if there's anything in that ` ` tag and if there is - check you haven't got some CSS that's marking it non visible?
score: 1
comment on: http://stackoverflow.com/q/51915646
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51816399
upvote count: 2
has comment: http://stackoverflow.com/comment/90587285
type: Answer
has comment: http://stackoverflow.com/comment/90587195
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/51815949
has comment: http://stackoverflow.com/comment/90587173
has body: First you need to know how lambda function works. Let me give you a simple example here a = lambda x,y: x+y If you do print(a) You will get output something like: &lt;function __main__.&lt;lambda&gt;(x, y)&gt; but if you pass parameters print(a(5,6)) you will get output as: 11 In your case you are doing x = 5 y =6 a = lambda x,y: x+y # You are defining a function here Above function won't take values of x,y. Those are local variables for that function. so it will obviously give output: &lt;function __main__.&lt;lambda&gt;(x, y)&gt;

http://stackoverflow.com/comment/90772997
comment on: http://stackoverflow.com/a/51910876
type: AnswerComment
score: 0
type: Comment
has text: @nicholishen I was not being sarcastic sorry you misunderstood.. I am lazy myself.

http://stackoverflow.com/comment/90625187
has text: If you feel this info is not sufficient, please do ask.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51835810

http://stackoverflow.com/a/51920635
has body: You can try using merge, sort_values, and fillna: new_df = (df1.merge(df2, on=['year','month','day'], how='outer') .sort_values(['year','month','day']) .fillna('')) &gt;&gt;&gt; new_df year month day min-temp mav-temp precipitation snow snow-cover 0 2017 12 13 13 25 0.04 0 0 1 2017 12 16 25 32 0.4 0.04 1 2 2017 12 25 34 56 3 2018 7 6 0 0 0
has comment: http://stackoverflow.com/comment/90791171
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51920606
upvote count: 2
accepted answer of: http://stackoverflow.com/q/51920606
score: 2
has comment: http://stackoverflow.com/comment/90791249

http://stackoverflow.com/comment/90850434
type: Comment
comment on: http://stackoverflow.com/a/51950218
score: 0
type: AnswerComment
has text: well pandas is on itself numpy no?

http://stackoverflow.com/q/51955809
has title: Attempts to parse string representation of list with ast.literal_eval or json.loads do not work
type: Question
tagged with: python-2.7
score: 0
answer count: 1
tagged with: string
favorite count: 0
has answer: http://stackoverflow.com/a/51955864
tagged with: python
has comment: http://stackoverflow.com/comment/90863469
has comment: http://stackoverflow.com/comment/90862188
has comment: http://stackoverflow.com/comment/90862217
has comment: http://stackoverflow.com/comment/90862182
has comment: http://stackoverflow.com/comment/90862596
type: UnansweredQuestion
upvote count: 1
has comment: http://stackoverflow.com/comment/90862243
has comment: http://stackoverflow.com/comment/90862271
downvote count: 1
has body: I have a list of list in a string format as: arg = '[[ABC, DEF], 10.10.10.10, 12345]' I like to convert it to a list of string objects as: ['[ABC, DEF]', '10.10.10.10', '12345'] I tried converting to a python object of list type using ast.literal_eval(arg) and json.loads(arg) but both these methods throws errors since the my "arg" consists of strings that cannot be evaluated. Is there a simpler way to achieve this?

http://stackoverflow.com/comment/90612074
type: AnswerComment
type: Comment
has text: Not sure why someone downvoted here. Seems a downvote to the other useful question was also applied.
comment on: http://stackoverflow.com/a/51827716
score: 0

http://stackoverflow.com/q/51809527
type: UnansweredQuestion
type: Question
tagged with: twisted
has title: How to pass arguments to reconectingclientfactory
score: 0
tagged with: autobahn
answer count: 1
tagged with: python
has body: I have some problems to passing argument to reconectingclientfactory: class MyClientFactory(WebSocketClientFactory, ReconnectingClientFactory): protocol = MyClientProtocol maxDelay=90 maxRetries=10000 def __init__(ver,cfg,*args,**kwargs): self.sysVer=ver self.sysCfg=cfg super().__init__(*args,**kwargs) def clientConnectionFailed(self, connector, reason): print("Client connection failed {0} to: {1} .. retrying ..".format(reason,connector)) self.retry(connector) def clientConnectionLost(self, connector, reason): print("Client connection lost {0} to {1} .. retrying ..".format(reason,connector)) self.retry(connector) and when i calling: factory = MyClientFactory('ws:/mywswebserver/websocket/', ver=sys_ver, cfg=sys_cfg,protocols={"wsprotocol"}) there is a error like: TypeError: __init__() got multiple values for argument 'cfg' Can anybody tell me what i'm dooing wrong?
has answer: http://stackoverflow.com/a/51812102

http://stackoverflow.com/q/51867748
has comment: http://stackoverflow.com/comment/90710462
tagged with: python
has title: Clear line to the right of the text displayed by progressbar.FormatCustomText (python)
has answer: http://stackoverflow.com/a/52859643
linked to: http://stackoverflow.com/q/566746
has answer: http://stackoverflow.com/a/51879440
type: Question
type: AnsweredQuestion
answer count: 2
has comment: http://stackoverflow.com/comment/90687371
possible better answer: http://stackoverflow.com/a/51879440
tagged with: progress-bar
has body: I am using progressbar2 with FormatCustomText. The text is parameterized (eg "%s") and the width of the string to display varies. Let's say on the first iteration, the substituted text is "AA." On the second iteration, the text is "B." progressbar displays BA on the second iteration instead of B. Is there a way to clear everything to the right of the cursor to the end of the line after B? Normally, this is done with control-K (chr(11)). Unfortunately, adding chr(11) to the end of the string given to FormatCustomText causes a newline character to be output for each iteration. Any other ideas?
accepted answer: http://stackoverflow.com/a/52859643
score: 0

http://stackoverflow.com/comment/97227115
comment on: http://stackoverflow.com/q/51817104
has text: how did you work this out?
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/a/51952914
has body: Your use of self.startButton.bind('&lt;Return&gt;', self.start) should work fine as long as compensate for the event that the bind will send to the function/method. Here is a simple example that will work with the enter key as long as the button has focus. import tkinter as tk root = tk.Tk() def do_something(event=None): print("did something!") btn = tk.Button(root, text="Do something", command=do_something) btn.pack() btn.bind("&lt;Return&gt;", do_something) #root.bind("&lt;Return&gt;", do_something) will work without the button having focus. root.mainloop()
accepted answer of: http://stackoverflow.com/q/51952761
downvote count: 0
answers question: http://stackoverflow.com/q/51952761
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/90860097
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90859964
type: Answer

http://stackoverflow.com/a/51954030
has comment: http://stackoverflow.com/comment/90859741
upvote count: 0
answers question: http://stackoverflow.com/q/51953728
has comment: http://stackoverflow.com/comment/90860595
downvote count: 3
has body: errors_log = set() try: page_element = chrome.find_element_by_link_text("Next Page") except Exception as e: errors_log.add(e) try: page_element = chrome.find_element_by_class_name("pager_next") except Exception as e1: errors_log.add(e1) To appease those in the comments, from my perspective of the question and the code provided, the code above amends how the try blocks are handled. The original code would check for both, the code I posted will only check for the class if the link text cannot be found. E.g. if the first element he wants to select by text is the same one he wants to select by class, then if the link text is present then it will not waste time checking if the alternative exists. Had those people in the comments been patient, they would have seen the explanation. Even if they just asked politely. For some reason people think it's their God given right to be rude to others on SO...
score: -3
type: Answer

http://stackoverflow.com/a/51834450
score: 0
has body: You save a simple checkpoint but then you are trying load it as a meta graph. This cannot work. There is a writeup on the TensorFlow website explaining the differences https://www.tensorflow.org/mobile/prepare_models#what_is_up_with_all_the_different_saved_file_formats There must be a file ending with .meta.
type: Answer
answers question: http://stackoverflow.com/q/51834353

http://stackoverflow.com/a/51880542
type: Answer
has comment: http://stackoverflow.com/comment/90798995
has comment: http://stackoverflow.com/comment/90736907
has comment: http://stackoverflow.com/comment/90799250
has body: The '/' for the href means that you need to request the root directory. Use the same domain name, but don't request a subdirectory.
has comment: http://stackoverflow.com/comment/90800072
has comment: http://stackoverflow.com/comment/90796119
has comment: http://stackoverflow.com/comment/90796175
answers question: http://stackoverflow.com/q/51871695
has comment: http://stackoverflow.com/comment/90745224
score: 0

http://stackoverflow.com/a/51913176
has comment: http://stackoverflow.com/comment/113904263
downvote count: 0
has comment: http://stackoverflow.com/comment/111885512
has body: I've figured out what I needed to do, in the Private Storage class, I forgot to put custom_domain = False originally left this line off, because I did not think I needed it however you absolutely do in order to generate signed urls automatically.
score: 7
has comment: http://stackoverflow.com/comment/113904567
upvote count: 7
type: Answer
has comment: http://stackoverflow.com/comment/95961606
answers question: http://stackoverflow.com/q/51913046

http://stackoverflow.com/q/51933681
accepted answer: http://stackoverflow.com/a/51933981
has body: I have a python module with definitions of constants. They look like so: 30KHZ = 0b000 125KHZ = 0b001 250KHZ = 0b010 1MHZ = 0b011 Obviously, these are not allowed names. One way of to deal with this is to prepend names with something. Names like _30KHZ look nice, but they mess with static analyzers. Names like S_30KHZ or F30KHZ are allowed, but they look awkward and the meaning of the S_ or F may be unclear. Another way is to rotate the name like so: KHZ30. But is doesn't look good either. How to name such constants to make their meaning obvious to the user?
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90817555
score: 0
has comment: http://stackoverflow.com/comment/90817534
tagged with: conventions
type: Question
has comment: http://stackoverflow.com/comment/90817726
has comment: http://stackoverflow.com/comment/90817643
has comment: http://stackoverflow.com/comment/90817771
answer count: 1
has answer: http://stackoverflow.com/a/51933981
has comment: http://stackoverflow.com/comment/90817459
has title: python declaration of constant beginning with number

http://stackoverflow.com/comment/90764104
score: 0
type: QuestionComment
has text: Oh. Right. I changed x_data to x_data=np.linspace(0, 1000, 1000) and the problem does not occur. Please add your last comment as answer, so I will be able to mark this as solution.
type: Comment
comment on: http://stackoverflow.com/q/51906709

http://stackoverflow.com/q/51846682
answer count: 3
has comment: http://stackoverflow.com/comment/90649589
has comment: http://stackoverflow.com/comment/106406050
favorite count: 0
type: UnansweredQuestion
tagged with: python
has title: Eager Execution - InternalError: Could not find valid device for node name: "Sqrt"
has body: With Eager Execution enabled the TensorFlow square-root function tf.sqrt() results in an InternalError. import tensorflow as tf # enable eager execution tf.enable_eager_execution() &gt; tf.pow(2,4) 'Out': &lt;tf.Tensor: id=48, shape=(), dtype=int32, numpy=16&gt; &gt; tf.sqrt(4) &gt;&gt;&gt; Traceback (most recent call last): File "&lt;ipython-input-21-5dc8e2f4780c&gt;", line 1, in &lt;module&gt; tf.sqrt(4) File "/Users/ekababisong/anaconda3/envs/py36_dl/lib/python3.6/site-packages/ tensorflow/python/ops/math_ops.py", line 365, in sqrt return gen_math_ops.sqrt(x, name=name) File "/Users/ekababisong/anaconda3/envs/py36_dl/lib/python3.6/site-packages/ tensorflow/python/ops/gen_math_ops.py", line 7795, in sqrt _six.raise_from(_core._status_to_exception(e.code, message), None) File "&lt;string&gt;", line 3, in raise_from InternalError: Could not find valid device for node name: "Sqrt" op: "Sqrt" input: "dummy_input" attr { key: "T" value { type: DT_INT32 } } [Op:Sqrt] name: Sqrt/
downvote count: 0
has answer: http://stackoverflow.com/a/57921276
has comment: http://stackoverflow.com/comment/97522103
has answer: http://stackoverflow.com/a/55065322
score: 19
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/60089909
has comment: http://stackoverflow.com/comment/106406381
has comment: http://stackoverflow.com/comment/96792534
upvote count: 19

http://stackoverflow.com/q/51852025
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/107434769
score: 0
tagged with: facebook-page
answer count: 2
has comment: http://stackoverflow.com/comment/90660939
has answer: http://stackoverflow.com/a/52124117
tagged with: facebook-graph-api
favorite count: 0
has answer: http://stackoverflow.com/a/51852887
tagged with: python
has title: How to publish on my own Facebook Page (graph-api) without creating an App on Facebook developer
tagged with: python-3.x
type: UnansweredQuestion
tagged with: facebook-permissions
has body: I have several Facebook pages, to manage them all (publish photo or generally post as the page), I've created a simple script in python which needs the Page ID and the Access Token. To get the Access Token I need to make a Facebook app. I'm able to publish on my facebook pages using the access token taken from https://developers.facebook.com/tools/explorer/. The problem is that if I don't set the app status to live, the post on the FB Page are not visible. If I change the app status to live, I no longer have the permission required to publish, because I need to submit the app for review, but the script that I created doesn't fall in any of the categories listed; i.e. Facebook Web Games, Website, iOS, etc. So my questions are: How do I make visible to the public the posts made by the app, leaving the app status as "In Development"? Is there a way to publish to a FB Page, without the need to create an app on FB?
upvote count: 1

http://stackoverflow.com/comment/90794231
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51922003
has text: Sorry for the late response. Generally, I generate the HTML by running my Python program via Vagrant in which the HTML template is generated as well as the Python file.
type: AnswerComment

http://stackoverflow.com/comment/90832836
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51923075
has text: any data pre-processing you did before the model? since, these are images, how have you tagged your data?

http://stackoverflow.com/a/51951931
answers question: http://stackoverflow.com/q/51951592
score: 1
has comment: http://stackoverflow.com/comment/90855045
has comment: http://stackoverflow.com/comment/90854924
upvote count: 1
has body: Seems pretty straightforward. I don't know what you mean by "all the x will be processed only once", but that doesn't sound possible. The function still has to be called separately for each parameter (Unless some black magician on SO can prove me wrong, which seems likely) from multiprocessing import Pool def f(x, param): ...do stuff... if __name__ == '__main__': params = [1,2,3,4,5,6,7,8] try: pool = Pool(8) pool.starmap(f, [(x,param) for param in params]) except SomeError: ...do error stuff... finally: pool.close() pool.join()
type: Answer
has comment: http://stackoverflow.com/comment/90856374
downvote count: 0

http://stackoverflow.com/comment/90677633
type: QuestionComment
score: 2
has text: Welcome! It looks like you want us to write some code for you. While many users are willing to produce code for a coder in distress, they usually only help when the poster has already tried to solve the problem on their own. A good way to demonstrate this effort is to include the code you've written so far, example input (if there is any), the expected output, and the output you actually get (console output, tracebacks, etc.). The more detail you provide, the more answers you are likely to receive. Check the [FAQ] and [ask].
comment on: http://stackoverflow.com/q/51862644
type: Comment

http://stackoverflow.com/comment/90779024
type: QuestionComment
has text: Ideally, you would use a CDN for bootstrap, otherwise a static url, not a relative one. For the gear png, that needs to be gotten as `url_for('static', 'images/gear.png')`
score: 0
comment on: http://stackoverflow.com/q/51914537
type: Comment

http://stackoverflow.com/q/51936136
has comment: http://stackoverflow.com/comment/90822551
has answer: http://stackoverflow.com/a/51936954
has body: Currently, I am working in python Textblob to generate the rating for review Text and by using polarity score I am able to get the polarity score (a float) between -1 to 1 for a text like below blob.sentiment.polarity Now I want the rating from 0 to 5 (integer). I am stuck with that how to make polarity score from -1 to 1 to 0 to 5 or any other better approach for doing this to generate the rating. Thanks in advance
type: Question
has comment: http://stackoverflow.com/comment/90822502
answer count: 2
score: 0
tagged with: sentiment-analysis
has title: How to use polarity score to give rating for review text in python
has answer: http://stackoverflow.com/a/51936336
tagged with: python
tagged with: python-3.x
type: UnansweredQuestion

http://stackoverflow.com/q/51926849
tagged with: pca
answer count: 0
downvote count: 0
score: 1
type: Question
has body: I've just learnt about PCA/SVD and I just wanted to make sure that I've implemented the coding correctly. I also have a little trouble understanding increasing latent dimensionality. Is this another dimension reduction model? Any guidance is much appreciated! Question: For the provided dataset, perform PCA and plot the captured variance with respect to increasing latent dimensionality. What is the minimum dimension that captures (a) at least 95% variance and (b) at least 98% variance? This is what I did: from sklearn.decomposition import PCA pca95 = PCA(n_components = 0.95) pca95.fit_transform(X) print('95% variance retained = {:1d} dimensions'.format(len(pca95.explained_variance_ratio_))) pca98 = PCA(n_components = 0.98) pca98.fit_transform(X) print('98% variance retained = {:1d} dimensions'.format(len(pca98.explained_variance_ratio_))) pca100 = PCA(n_components = 4613) pca100.fit_transform(X) fig = plt.figure plt.plot(pca100.explained_variance_ratio_.cumsum()) plt.xlabel('N Dimensions') plt.ylabel('Cumulative Variance Retained') plt.ylim([0,1.2]) plt.xlim([len(pca100.explained_variance_ratio_.cumsum()),0]) plt.grid()
upvote count: 1
favorite count: 0
type: UnansweredQuestion
has title: Dimensionality Reduction using PCA/SVD
tagged with: python

http://stackoverflow.com/comment/90999141
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51914774
type: AnswerComment
has text: `self.tc.Bind(wx.EVT_LEFT_DOWN, self.remove_find)` might improve your odds.

http://stackoverflow.com/a/52065560
has body: This is ok. Some services have redirects from user-friendly web-page to a zip-file. Sometimes it is implemented using HTTP status (301 or 302, see example below) or using page with meta tag that contains redirect like in your example. HTTP/1.1 302 Found Location: http://www.iana.org/domains/example/ aiohttp can handle first case - automatically (when allow_redirects = True by default). But in the second case library retrieves simple HTML and can't handle that automatically.
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/91146462
downvote count: 0
answers question: http://stackoverflow.com/q/51939714
type: Answer

http://stackoverflow.com/comment/90780057
type: AnswerComment
has text: here the complexity was because `print(type(response['Regions']))` gives ` `<class 'list'>` and `print(type(response['Regions']))` is `<class 'dict'>` and `print (type(response))` is `<class 'dict'>` so dictionary is also returned inside dictionary a list and another dictionary was being returned. So I was not able to understand.
comment on: http://stackoverflow.com/a/51914836
score: 0
type: Comment

http://stackoverflow.com/comment/90731817
type: AnswerComment
has text: Env was indeed Python 2.x thats why it didnt spill out any errors. Thanks for the prompt response!
type: Comment
score: 0
comment on: http://stackoverflow.com/a/51890059

http://stackoverflow.com/q/51834353
type: UnansweredQuestion
tagged with: python
upvote count: 3
linked to: http://stackoverflow.com/q/33759623
tagged with: machine-learning
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/51834450
score: 3
has body: I've looked at many questions regarding saving a trained neural network, including Tensorflow: how to save/restore a model? and https://cv-tricks.com/tensorflow-tutorial/save-restore-tensorflow-models-quick-complete-tutorial/ but none of them save a model without explicitly saving specific variables along with it, as in my case. Here is my case: # In session "sesh" saver = tf.train.Saver() saver.save(sesh,os.getcwd(),latest_filename= 'RNN_plasma.ckpt') Now, I quit the session and want to restore the model I just saved. How can I do this? When trying: import tensorflow as tf with tf.Session() as session1: #First let's load meta graph and restore weights saver = tf.train.import_meta_graph('RNN_plasma.ckpt')#error-line saver.restore(session1,tf.train.latest_checkpoint('./')) , the tf.train.import_meta_graph() call returns: raise IOError("Cannot parse file %s: %s." % (filename, str(e))) IOError: Cannot parse file RNN_plasma.ckpt: 1:1 : Message type "tensorflow.MetaGraphDef" has no field named "model_checkpoint_path".. Can anyone give any insight as to what is going on here, and how to solve it? (My version of TensorFlow doesn't come with tf.python.saved_model.simple_save(). (I have git_version 1.5.0))
has answer: http://stackoverflow.com/a/51834526
answer count: 2
downvote count: 0
has title: Restoring a TensorFlow Model Without Explicitly Saving Session Variables
favorite count: 0
has comment: http://stackoverflow.com/comment/90622547

http://stackoverflow.com/comment/90639823
has text: It would also help to know your file structure -- you can get an ASCII-art version by starting bash, and running `cd /home/medhub/MedHub` and then `tree`.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51842485

http://stackoverflow.com/a/51832771
has comment: http://stackoverflow.com/comment/135177765
accepted answer of: http://stackoverflow.com/q/51832672
answers question: http://stackoverflow.com/q/51832672
score: 6
type: Answer
upvote count: 6
has comment: http://stackoverflow.com/comment/90619720
has body: There's a Reddit thread on days360 for Pandas - here's the function that's posted there (seems to work with your example input): def days360(start_date, end_date, method_eu=False): start_day = start_date.day start_month = start_date.month start_year = start_date.year end_day = end_date.day end_month = end_date.month end_year = end_date.year if ( start_day == 31 or ( method_eu is False and start_month == 2 and ( start_day == 29 or ( start_day == 28 and start_date.is_leap_year is False ) ) ) ): start_day = 30 if end_day == 31: if method_eu is False and start_day != 30: end_day = 1 if end_month == 12: end_year += 1 end_month = 1 else: end_month += 1 else: end_day = 30 return ( end_day + end_month * 30 + end_year * 360 - start_day - start_month * 30 - start_year * 360) Testing on OP data: d1 = pd.to_datetime("2/2/2015") d2 = pd.to_datetime("1/1/2018") days360(d1, d2) # 1049
has comment: http://stackoverflow.com/comment/90619662
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/51942913
has comment: http://stackoverflow.com/comment/91162171
favorite count: 0
score: 8
upvote count: 9
tagged with: prediction
tagged with: python
has body: Following my answered question: R or Python - loop the test data - Prediction validation next 24 hours (96 values each day) I want to predict the next day using H2o Package. You can find detail explanation for my dataset in the same above link. The data dimension in H2o is different. So, after making the prediction, I want to calculate the MAPE I have to change training and testing data to H2o format train_h2o &lt;- as.h2o(train_data) test_h2o &lt;- as.h2o(test_data) mape_calc &lt;- function(sub_df) { pred &lt;- predict.glm(glm_model, sub_df) actual &lt;- sub_df$Ptot mape &lt;- 100 * mean(abs((actual - pred)/actual)) new_df &lt;- data.frame(date = sub_df$date[[1]], mape = mape) return(new_df) } # LIST OF ONE-ROW DATAFRAMES df_list &lt;- by(test_data, test_data$date, map_calc) # FINAL DATAFRAME final_df &lt;- do.call(rbind, df_list) The upper code works well for "Non-H2o" prediction validation for the day-ahead and it calculates the MAPE for every day. I tried to convert the H2o predicted model to normal format but according to to:https://stackoverflow.com/a/39221269/9341589, it is not possible. To make a prediction in H2O: for instance, let say we want to create a Random Forest Model y &lt;- "RealPtot" #target x &lt;- names(train_h2o) %&gt;% setdiff(y) #features rforest.model &lt;- h2o.randomForest(y=y, x=x, training_frame = train_h2o, ntrees = 2000, mtries = 3, max_depth = 4, seed = 1122) Then we can get the prediction for complete dataset as shown below. predict.rforest &lt;- as.data.frame(h2o.predict(rforest.model, test_h2o) But in my case I am trying to get one-day prediction using mape_calc NOTE: Any thoughts in R or Python will be appreciated. UPDATE2(reproducible example):** Following @Darren Cook steps: I provided a simpler example - Boston housing dataset. library(tidyverse) library(h2o) h2o.init(ip="localhost",port=54322,max_mem_size = "128g") data(Boston, package = "MASS") names(Boston) [1] "crim" "zn" "indus" "chas" "nox" "rm" "age" "dis" "rad" "tax" "pt…
accepted answer: http://stackoverflow.com/a/52071620
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/51804842
has title: Calculating MAPE in H2o: Error: Provided column type POSIXct is unknown
tagged with: loops
linked to: http://stackoverflow.com/q/43103022
type: Question
has answer: http://stackoverflow.com/a/52071620
possible better answer: http://stackoverflow.com/a/51957138
has answer: http://stackoverflow.com/a/51957138
tagged with: http://stackoverflow.com/tag/r
has answer: http://stackoverflow.com/a/54953188
answer count: 3
linked to: http://stackoverflow.com/q/39215243
tagged with: h2o
downvote count: 1

http://stackoverflow.com/q/51905712
has comment: http://stackoverflow.com/comment/90762237
has comment: http://stackoverflow.com/comment/90773319
has body: I got a model field object using field_object = MyModel._meta.get_field(field_name). How can I get the value (content) of the field object?
tagged with: django-models
type: Question
score: 65
has comment: http://stackoverflow.com/comment/90762258
has comment: http://stackoverflow.com/comment/90763215
possible better answer: http://stackoverflow.com/a/51905725
has comment: http://stackoverflow.com/comment/90762082
tagged with: python
has answer: http://stackoverflow.com/a/51905725
accepted answer: http://stackoverflow.com/a/51905746
answer count: 4
favorite count: 0
has answer: http://stackoverflow.com/a/51905751
has comment: http://stackoverflow.com/comment/90762096
upvote count: 65
downvote count: 0
has comment: http://stackoverflow.com/comment/90762013
has answer: http://stackoverflow.com/a/72301791
tagged with: django
has answer: http://stackoverflow.com/a/51905746
has comment: http://stackoverflow.com/comment/90761988
type: AnsweredQuestion
has title: How to get the value of a Django Model Field object
has comment: http://stackoverflow.com/comment/90762049

http://stackoverflow.com/q/51842125
has answer: http://stackoverflow.com/a/51843354
has comment: http://stackoverflow.com/comment/90638078
score: 2
has comment: http://stackoverflow.com/comment/90637752
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/90638179
favorite count: 0
has title: uninstalling pip3 on mac
has comment: http://stackoverflow.com/comment/90637288
has comment: http://stackoverflow.com/comment/90637763
upvote count: 2
has comment: http://stackoverflow.com/comment/90637572
type: UnansweredQuestion
has body: I am trying to get the installation right with python 3, pip and pip3. I am working on a mac and by default. I have Python 2.7.10 python -V Python 2.7.10 python3 -V Python 3.5.1 What is the correct order of installation commands to install python3 pip and pip3 so that both pip and pip3 can be linked to python3? This what I get when I try to see what versions I already have: $ pip -V -bash: /usr/local/bin/pip: No such file or directory $ pip3 -V pip 7.1.2 from /Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages (python 3.5) I need to get this right so that I can install numpy afterward because now with what I have above this is what I get: $ pip3 install numpy Collecting numpy Could not find a version that satisfies the requirement numpy (from versions: ) No matching distribution found for numpy
tagged with: pip
tagged with: python
type: Question
has comment: http://stackoverflow.com/comment/90637850

http://stackoverflow.com/q/51868606
tagged with: dialogflow-es
has body: First of all, I'm a noob with dialogflow and web services. I'm trying to integrate a dialogflow agent I just created and integrate it with my app on my local computer. I was able to get project_id and all other important information but no matter where I look, no one seems to talk about where they get session ids from. Here is the audio-to-text code that I'm using that was forked from api.ai github page: import os import dialogflow_v2 as dialogflow os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "My Google Credential" project_id = 'project id' session_id = "this i don't know where to get" audio_file_path = 'my wave file directory name' language_code = 'en' def detect_intent_audio(project_id, session_id, audio_file_path, language_code): """Returns the result of detect intent with an audio file as input. Using the same `session_id` between requests allows continuation of the conversaion.""" session_client = dialogflow.SessionsClient() # Note: hard coding audio_encoding and sample_rate_hertz for simplicity. audio_encoding = dialogflow.enums.AudioEncoding.AUDIO_ENCODING_LINEAR_16 sample_rate_hertz = 44100 session = session_client.session_path(project_id, session_id) print('Session path: {}\n'.format(session)) with open(audio_file_path, 'rb') as audio_file: input_audio = audio_file.read() audio_config = dialogflow.types.InputAudioConfig( audio_encoding=audio_encoding, language_code=language_code, sample_rate_hertz=sample_rate_hertz) query_input = dialogflow.types.QueryInput(audio_config=audio_config) response = session_client.detect_intent( session=session, query_input=query_input, input_audio=input_audio) print('=' * 20) print('Query text: {}'.format(response.query_result.query_text)) print('Detected intent: {} (confidence: {})\n'.format( response.query_result.intent.display_name, response.query_result.intent_detection_confidence)) print('Fulfillment text: {}\n'.format( response.query_result.fulfillment_text)) detect_intent_audio(project_id, session_id, audio_file_path, …
type: Question
score: 14
has title: dialogflow - how to get session id?
downvote count: 0
answer count: 1
favorite count: 0
tagged with: sessionid
tagged with: python
type: AnsweredQuestion
upvote count: 14
has answer: http://stackoverflow.com/a/52442234
accepted answer: http://stackoverflow.com/a/52442234

http://stackoverflow.com/q/51869859
tagged with: wav
downvote count: 0
favorite count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51871708
tagged with: sox
upvote count: 1
tagged with: python
has body: I know how to print the duration of the .wav file using sox at the Linux command. soxi -D input.wav So I used this syntax in python. subprocess.call(['soxi', '-D', input.wav]) But I'd like to save the duration(seconds) in a variable. How do I get it in a variable? +++++++++++ edit ++++++++++++++ using) wavduration = subprocess.call(['soxi', '-D', input.wav]) print(wavduration) output) 4.000000 0 This is not the right way to do it...
has comment: http://stackoverflow.com/comment/90691777
tagged with: audio
has title: Get duration of .wav from sox in python
score: 1
linked to: http://stackoverflow.com/q/2804543
type: Question
answer count: 1

http://stackoverflow.com/q/51916943
score: 1
type: Question
has body: Let's say I want to replace the whole strings that contain "arm","hay" and "Arm" character with a string called "Armenian" simultaneously. (For example: armenia-> Armenian, hayeren->Armenian etc.) Here is what I tired &gt; df[col] = df[col].apply(lambda x : 'Armenian' if ["Arm","hay","arm",] in x else x) And I get TypeError: 'in ' requires string as left operand, not list>
accepted answer: http://stackoverflow.com/a/51917002
downvote count: 0
has answer: http://stackoverflow.com/a/51916986
has answer: http://stackoverflow.com/a/51917137
tagged with: pandas
has answer: http://stackoverflow.com/a/51917075
possible better answer: http://stackoverflow.com/a/51916986
favorite count: 0
has title: Replace multiple strings simultaneously if it contains substring
tagged with: python-3.x
upvote count: 1
has answer: http://stackoverflow.com/a/51917002
tagged with: python
answer count: 4
type: AnsweredQuestion

http://stackoverflow.com/comment/90615754
score: 0
has text: @PerunSS is right. This is a good approach. You can always try to use * to import anything, like `from pytmp.test import *` but that will make debugging harder as you can accidentally create functions with the same name in different modules.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51830572

http://stackoverflow.com/q/51940907
answer count: 2
has answer: http://stackoverflow.com/a/51943893
downvote count: 0
has comment: http://stackoverflow.com/comment/90832909
accepted answer: http://stackoverflow.com/a/51943893
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/51943345
tagged with: selenium-webdriver
tagged with: xpath
type: AnsweredQuestion
score: 1
tagged with: selenium
upvote count: 1
possible better answer: http://stackoverflow.com/a/51943345
tagged with: webdriver
type: Question
has title: How to select the option File from menu as per the html provided?
has body: I'm trying to do automation and struck in the middle. Cannot able to select option from a submenu. Tried every solution from stack overflow and anything doesn't work. Attaching the code. This is the id i need to click so a drop down appears. That is from differant section and the code is, Screen File Printer (clear) Once i selected the ID arid_WIN_0_2000053, i need to select option as File. Thanks in advance.

http://stackoverflow.com/q/51842727
answer count: 0
score: 1
upvote count: 1
type: Question
downvote count: 0
has title: Use Cypher Bolt Statement Result Directly in py2neo
has body: I have been experimenting with the neo4j library in python, but would like to use some of the functionality provided by py2neo. Currently, I open the driver and session directly from GraphDatabase of neo4j.v1 and use session.run() to execute graph queries. These queries return a neo4j.v1.result.BoltStatementResult object. Rather than having to reformulate my queries to be run from py2neo, I want to convert the BoltStatementResult I already have to a form py2neo can process. How do I perform this conversion?
tagged with: neo4j
favorite count: 0
tagged with: py2neo
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/51850478
upvote count: 4
has title: How to mock an imported module with pytest
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51852198
tagged with: python-unittest
type: Question
downvote count: 2
tagged with: mocking
has answer: http://stackoverflow.com/a/51852198
answer count: 1
favorite count: 0
has body: Something similar has been asked before, but I'm struggling to get this to work. How do I mock an import module from another file I have one file: b.py (named to be consistent with the linked docs) import cv2 # module 'a' in the linked docs def get_video_frame(path): vidcap = cv2.VideoCapture(path) # `a.SomeClass` in the linked docs vidcap.isOpened() ... test_b.py import b import pytest # with pytest-mock installed def test_get_frame(mocker): mock_vidcap = mocker.Mock() mock_vidcap.isOpened.side_effect = AssertionError mock_cv2 = mocker.patch('cv2.VideoCapture') mock_cv2.return_value = mock_vidcap b.get_video_frame('foo') # Doesn't fail mock_vidcap.isOpened.assert_called() # fails I set the tests up like this because in where to patch it specifies that if In this case the class we want to patch is being looked up on the a module and so we have to patch a.SomeClass instead: @patch(‘a.SomeClass’) I've tried a few other combinations of patching, but it exhibits the same behavior, which suggests I'm not successfully patching the module. If the patch were to be applied b.get_video_frame('foo') would fail due to the side_effect; having assert_called fail, supports this. Edit in an effort to reduce the length of the question I left off the rest of get_video_frame. Unfortunitly, the parts left off we're the critical parts. The full function is: def get_video_frame(path): vidcap = cv2.VideoCapture(path) # `a.SomeClass` in the linked docs is_open = vidcap.isOpened() while True: is_open, frame = vidcap.read() if is_open: yield frame else: break
tagged with: python

escpos
tags question: http://stackoverflow.com/q/51898173
tag name: escpos
type: Tag

http://stackoverflow.com/comment/90794477
comment on: http://stackoverflow.com/q/51922283
type: Comment
type: QuestionComment
has text: Could you explain me please how `a = [66.25, 333, 333, 1, 1234.5]` is equal to `x='10 0 17 5'` ?
score: 0

pygobject
type: Tag
tag name: pygobject
tags question: http://stackoverflow.com/q/51819834

http://stackoverflow.com/q/51917992
tagged with: python
has body: I am trying to create login with google in Django login so when I create my 'Login with Google' it goes to google login page but on selecting Google account it shows an error, ModuleNotFoundError at /auth/complete/google-oauth2/ No module named 'social' My project urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('', include('pages.urls')), path('accounts/', include('django.contrib.auth.urls')), path('auth/', include(('social_django.urls', 'social_django'), namespace='social')), path('admin/', admin.site.urls), ] settings.py import os INSTALLED_APPS = [ #..., 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'social_django', 'django', ] MIDDLEWARE = [ #... #... ] ROOT_URLCONF = 'trydjango.urls' TEMPLATES = [ { 'BACKEND': '# ...', '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', # Google login 'social_django.context_processors.login_redirect', # Google Login ], }, }, ] DATABASES = { 'default': { # ... # ... } } AUTH_PASSWORD_VALIDATORS = [ # .... ] 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.google.GoogleOAuth', # 'social_core.backends.github.GithubOAuth2', # for Github authentication # 'social_core.backends.facebook.FacebookOAuth2', # for Facebook authentication 'django.contrib.auth.backends.ModelBackend', ) SOCIAL_AUTH_URL_NAMESPACE = 'social' SOCIAL_AUTH_PIPELINE = ( 'social.pipeline.social_auth.social_details', 'social.pipeline.social_au…
has title: Django Google Sign in ModuleNotFoundError at /auth/complete/google-oauth2/
type: AnsweredQuestion
score: 0
tagged with: oauth-2.0
type: Question
tagged with: django-socialauth
has comment: http://stackoverflow.com/comment/90795430
tagged with: google-signin
has answer: http://stackoverflow.com/a/51918582
answer count: 1
accepted answer: http://stackoverflow.com/a/51918582
tagged with: django

http://stackoverflow.com/a/51925072
has comment: http://stackoverflow.com/comment/90800060
answers question: http://stackoverflow.com/q/51924729
score: 0
has comment: http://stackoverflow.com/comment/90799952
type: Answer
has body: Nice effort. When you're stuck like this, it's a great time to exercise basic debugging and design principles. Scale down complexity: approach your code in small chunks and make sure each component is working before increasing complexity. Removing stop words and reading input lists are totally different tasks and can be broken down and debugged in discrete chunks. In terms of input, are the files being read as you planned? Instead of lists of words, you're getting a list of strings nested in a list with the file contents inside of it, which seems unintended. printing your new list reveals "stack overflow is awesome, don't you think?\n". Removing the .append and doing a direct assignment on new will ensure you're only dealing with a 1d list of strings. At this point, strings need breaking down into words. This can be a complex pattern matching task depending on what you define as a word. For now, I recommend keeping it simple and using split() to break on whitespace, but know that you may have dangling commas, periods and quotation marks that will impact your output. After settling your input routine, matters should be much clearer inside your remove_stop function, which was previously broken because it was crashing while attempting to remove strings from a list that didn't contain anything other than lists. An approach to this function I prefer is using a list comprehension for terse but readable syntax and a set for fast, almost instantaneous lookups. remove, for contrast, is a slow approach that looks through every element of the input list one at a time to find the item to remove on every iteration. Putting it all together, here's one approach: def remove_stop(text, stopwords): disallowed = set(stopwords) return [word for word in text if word not in disallowed] text = open("helpme.txt","r").read().split() stopwords = open("stopwords1.txt","r").read().split() print(remove_stop(text, stopwords)) Given sample texts: helpme.txt: stack overflow is awesome, don't y…

http://stackoverflow.com/comment/90792532
score: 0
type: Comment
has text: the original input from the post
comment on: http://stackoverflow.com/a/51914404
type: AnswerComment

http://stackoverflow.com/comment/90632811
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51839219
has text: You should also have `Anaconda Prompt` installed
type: Comment

http://stackoverflow.com/comment/90574349
comment on: http://stackoverflow.com/a/51808661
has text: I need while loop here, I am thinking about logic and I need while loop on score column condition. I need your help here.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/90727806
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51884648
type: Comment
has text: I had to assign 1.1 to the cells where I wanted the +1. Then I applied the custom format you suggested, which worked. Thanks!

http://stackoverflow.com/a/51883299
accepted answer of: http://stackoverflow.com/q/51882681
answers question: http://stackoverflow.com/q/51882681
upvote count: 1
type: AcceptedAnswer
has body: First you need to get your code in order. These lines y = sigm(x) E = 1/2*(ol1 - y)**2 dsig = sigm(x,True) dyE = y-ol1 need to happen inside the for loop, after x = syn0 + syn1 + b. Next, there are a few neural network items to address. Here is a technical description of backprop. The derivative of sigm(x) is sigm(x) * (1 - sigm(x)), or in your case, y * (1 - y), which as you have implemented is sigm(y,True). Your bias also needs to be updated as well. This is a critical part of the network and is a learned parameter. You could use: dtotalb = dyE*dsig*1 b = b - 0.01*dtotalb The multiply by 1 is unnecessary, but instructive. This is the derivative of the "net" term, which you called x, with respect to b, i.e. 1. You may have noticed that the update I gave for b uses a - instead of +. The very last line of this section in the link above shows this is necessary to make sure the updates go in the correct direction to minimize your error. Finally, consider the possible values your network can output. The final output y is the result of calling sigm(x). The values that y can take on are in the open interval (0,1). Your network however, is trying to learn the value of 6. The closest it can get is almost 1. So as you continue to iterate, the weights will continue to increase to try and increase the output value of the sigmoid. The weights will grow indefinitely. With all these changes, try making your target something in (0,1), e.g. 0.6. I am able to get the E to decrease to near 0 and your weights to converge when I make all these changes. Side note: In order for your network to learn a value of 6, you would need another layer of weights without an activation function. Alternatively, you could remove the activation function, but then you start to lose the neural network approach you are trying to learn.
type: Answer
has comment: http://stackoverflow.com/comment/90772635
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/90819765

http://stackoverflow.com/a/51947114
has comment: http://stackoverflow.com/comment/90843838
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51947042
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51947042
has body: This should work. It's effectively the same as yours but a bit more efficient. Doesn't use string concatenation + += (which are slow) but instead saves incomplete lines as a list. It then writes 2 spaces, each incomplete sentence joined by spaces and then a newline -- this simplifies it by only writing when a line is complete. temp = [] with open(path_in, "r") as f_in, open(path_out, "w") as f_out: for line in f_in: curr_line = line.strip() if curr_line: temp.append(curr_line) if curr_line.endswith('.'): # write our line f_out.write(' ') f_out.write(' '.join(temp)) f_out.write('\n') temp.clear() # reset temp outputs This is a sentence. So is this one. And this. This is the next line and some lines are like this.
type: Answer
has comment: http://stackoverflow.com/comment/90844191

http://stackoverflow.com/q/51844921
tagged with: django
has comment: http://stackoverflow.com/comment/90788919
type: Question
has comment: http://stackoverflow.com/comment/90790192
has comment: http://stackoverflow.com/comment/90790178
score: 0
has comment: http://stackoverflow.com/comment/90789239
has comment: http://stackoverflow.com/comment/90790011
tagged with: django-taggit
has comment: http://stackoverflow.com/comment/90732510
tagged with: python-3.x
tagged with: python
tagged with: selectize.js
answer count: 0
has comment: http://stackoverflow.com/comment/90756935
has comment: http://stackoverflow.com/comment/90760983
has body: I am using this https://github.com/chhantyal/taggit-selectize which uses django-taggit and selectize.js to add autocompletion of tags in my blog app. I have followed the instructions in the readme file and it works fine in admin. But when I am trying to use it in User form , it is not working. I have used this https://github.com/chhantyal/taggit-selectize/issues/17 to customize my form and have tried using the js and css file almost everywhere in my HTML template as suggested in the above post. But I am not able to get it. &lt;script type="text/javascript" src="/static/taggit_selectize/js/selectize.js"&gt;&lt;/script&gt; &lt;link href="/static/taggit_selectize/css/selectize.django.css" type="text/css" media="all" rel="stylesheet"/&gt; PS. I am also using Martor Django Editor which uses semantic.js (Mentioning it because it had conflict with few of my JS and bootstrap stuff.)
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90789173
has title: Use Taggit-Selectize in Django to autocomplete the tags in User Form outside the Admin

http://stackoverflow.com/comment/90719605
has text: What if the count column is different for the same 'class' value?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51883926

http://stackoverflow.com/a/51953901
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51953766
has body: It's about how layers are connected. The layers after the first layer are chained so their input shapes are equal to the output shape of the previous layer in a sequential model: model.layers[i].input_shape == model.layers[i-1].output_shape But what about the very first layer? Since the model cannot infer what the shape should be, it asks you to provide it. After the first input all the shapes can be calculated.
type: Answer
accepted answer of: http://stackoverflow.com/q/51953766
upvote count: 1
score: 1

http://stackoverflow.com/comment/90854719
score: 0
type: AnswerComment
has text: it really confused me, since I didnt convert returned json string to object but I can still access to fields.pro_section and pro_description to display them to dataTable columns. After I deserialization and Serialization I got expected returned json. but can not access [fields][employee][name]
type: Comment
comment on: http://stackoverflow.com/a/51936544

http://stackoverflow.com/comment/90844828
score: 0
type: Comment
type: QuestionComment
has text: Please post the definition (or and example of) `list_hosts`.
comment on: http://stackoverflow.com/q/51947255

http://stackoverflow.com/q/51882110
type: UnansweredQuestion
tagged with: python
tagged with: dictionary
has body: I need to get the key by the given tuple destino which I have to find in the list transformed into a dictionary: destinos = [("AF10", [("Lima","Peru"), ("San Jose","Costa Rica")]), ("AF11", [("San Jose","Costa Rica"), ("Costa de Panama","Panama")])] destino = ("Lima","Peru") # could be any given tuple on the destinos list destinos_dict = dict(destinos) # destinos converted into a dictionary for val in destinos_dict.values(): if val == destino: print destinos_dict.key(destino) else: print "Destino not found" # always print on the terminal the else statement, I want the if to be printed
type: Question
has answer: http://stackoverflow.com/a/51882363
has answer: http://stackoverflow.com/a/51882290
score: 0
answer count: 3
has title: How to find a tuple as value on a dictionary and get its key
has answer: http://stackoverflow.com/a/51882467
tagged with: tuples

http://stackoverflow.com/comment/90684592
score: 0
type: AnswerComment
has text: `excel_app`, as well as `read_path`, was taken from your original post. Similarly, saving can be handled as in your own post.
type: Comment
comment on: http://stackoverflow.com/a/51865646

http://stackoverflow.com/q/51878878
type: Question
tagged with: python
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/90710333
has answer: http://stackoverflow.com/a/51879515
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/72852
has title: error in relative path and absolute path in import
has body: I have following folder structure Tool -&gt; Tool folder have following three subfolders inputfiles outputfiles soucefiles sourcefiles have following files __init__.py main.py ParseLogFile.py Following are contents of ParseLogFile.py class ParseLogFile: # initialize file name def __init__(self, filename): self.filename = filename return def ParseLogFileFunc(self): print("ParseLogFileFunc called " + self.filename ) Following are contents of main.py from sourcefiles.ParseLogFile import ParseLogFile parseFile = ParseLogFile("logfile") parseFile.ParseLogFileFunc() If i use following then it is working from ParseLogFile import ParseLogFile parseFile = ParseLogFile("logfile") parseFile.ParseLogFileFunc() but I am trying to understand absolute and relative paths for import Question 1: When i gave absolute path like above i am getting followoing error from sourcefiles.ParseLogFile import ParseLogFile If i run above file i.e., main.py i am getting following error. ModuleNotFoundError: No module named 'sourcefiles' How do we rectify this error using abolute path? Question 2:If i use relative path from .ParseLogFile import ParseLogFile parseFile = ParseLogFile("logfile") parseFile.ParseLogFileFunc() If i run above file i.e., main.py i am getting following error. ModuleNotFoundError: No module named '__main__.ParseLogFile'; '__main__' is not a package Question 3: How do open a file by providing relate path in python for example in my case input file in "inputfiles" folder. I am new to python and trying to learn python in realistic way used in real projects. Kindly help. I am using python 3.x and spyder tool of anaconda for development
tagged with: python-3.x

http://stackoverflow.com/q/51938713
score: 0
tagged with: data-analysis
tagged with: pandas
has comment: http://stackoverflow.com/comment/90827542
tagged with: python
has body: I am trying to separate the column values separated by "," separator of a panda dataframe. The original data Original panda dataframe The desired output Desired output I have tried several ways. Explode/stack a Series of strings newdf['Month'] = newdf['Month'].apply(list) using the above code I am getting [j,a,n,,f,e,b] and then I have used pd.Dataframe({'Month':np.concatenate(newdf['Month'].values), 'cust.no':newdf['cust.no'].repeat(newdf['cust no.'].apply(len))}) The output is each letter is coming in separate rows. As a result, the row numbers are not matching with "cust no." and I am getting error. I know there are several functions available but I couldn't one that can efficiently break down the values.
has title: How to split column values of a panda data frame into rows separated by “,”
has answer: http://stackoverflow.com/a/51939251
linked to: http://stackoverflow.com/q/50082449
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51940694
tagged with: dataframe
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/90869019

http://stackoverflow.com/comment/90701348
type: Comment
type: QuestionComment
has text: It looks like your platform is `win_amd64`. Why did you download `grpcio` for `win32` then? I see `grpcio-1.14.1-cp36-cp36m-win_amd64.whl` on PyPI, you should install that instead.
score: 0
comment on: http://stackoverflow.com/q/51862083

http://stackoverflow.com/q/51840471
score: -1
has answer: http://stackoverflow.com/a/51840880
type: Question
tagged with: api
upvote count: 0
has comment: http://stackoverflow.com/comment/90634126
answer count: 1
favorite count: 0
has body: I need post some binary file to server by REST API. I'm using python requests lib for that. First of all I open the session for get cookies, and then execute POST request, but got 403 error. import requests url0 = "https://someUrl/api/v1" url1 = "https://someUrl/api/v1/Action()" headers = { 'X-CSRF-Token': "E8D648268586298FBB52900F85C13CDC", 'Authorization': "Basic User:Password_InBase64" } s = requests.Session() responce = s.get(url0, headers=headers) print("first request") print(responce.status_code) headers = { 'X-CSRF-Token': "E8D648268586298FBB52900F85C13CDC", } payload = "{\"BinaryFile\": \"fileInBinary\"}" response = s.post(url1, data=payload, headers=headers ) print("second request") print(response.status_code) print(response.headers) In response with 403 error I see no information, why the error has occurred. The console output you can see below first request 200 second request 403 {'X-CSRF-Token': 'Required', 'Content-Type': 'text/html;charset=utf-8', 'Content-Language': 'en', 'Content-Length': '762', 'Date': 'Tue, 14 Aug 2018 10:43:13 GMT', 'Server': 'SAP', 'Strict-Transport-Security': 'max- age=31536000; includeSubDomains; preload'}
tagged with: rest
tagged with: python
type: UnansweredQuestion
tagged with: python-requests
downvote count: 1
has title: Getting 403 forbidden for POST Request

http://stackoverflow.com/a/51894534
has comment: http://stackoverflow.com/comment/90743916
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/90740133
has body: This should do what you need. with open("C:\\my_folders_are_in_here\\brit-a-z.txt", 'r') as f: check_list = [x.strip() for x in f.readlines()] def anagram(word): for alpha in range(ord('a'), ord('z') + 1): newletter = chr(alpha) for line in check_list: word1_list = list(word + newletter) word1_list.sort() ref_list = list(line) ref_list.sort() if word1_list == ref_list: print(line) while True: inp = input() anagram(inp) I took advantage of the chr() and ord() built-in function to remove the long if that converts alpha into newletter.
score: 1
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51894182
answers question: http://stackoverflow.com/q/51894182
type: AcceptedAnswer

http://stackoverflow.com/a/51915996
answers question: http://stackoverflow.com/q/51915835
type: AcceptedAnswer
downvote count: 0
has body: I'm not sure if the object you are trying to reshape is a Tensor or numpy.ndarray. If it is a numpy.ndarray, you can use np.transpose. For example: import numpy as np a = np.zeros((299, 299, 3, 50)) print(a.shape) # (299, 299, 3, 50) H x W x C x M b = np.transpose(a, [3, 0, 1, 2]) print(b.shape) # (50, 299, 299, 3) If it is a Tensor, You can use tf.transpose to change the order of the dimension in exactly the same way as np.transpose. For example: import tensorflow as tf a = tf.zeros((299, 299, 3, 50), dtype=tf.int32) print(a.shape.as_list()) # [299, 299, 3, 50] b = tf.transpose(a, [3, 0, 1, 2]) print(b.shape.as_list()) # [50, 299, 299, 3]
accepted answer of: http://stackoverflow.com/q/51915835
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/q/51926426
has answer: http://stackoverflow.com/a/51927143
has title: Generate exponentially increasing list of numbers (from start to stop)
has comment: http://stackoverflow.com/comment/90806812
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/51926900
has comment: http://stackoverflow.com/comment/90802628
favorite count: 0
has comment: http://stackoverflow.com/comment/90806397
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90802814
upvote count: 1
tagged with: python
has body: I would like to generate a exponentially increasing list of numbers between a start and an end number. So for example I would to take: start_num = 700,000 end num = 750,000 num_steps = 100 and generate a list of 100 numbers roughly like so:[700000,700100,700250,700700.....746000,750000] I can do this for evenly spaced intervals with np.arange or even slightly exponentially increasing with np.logspace but the "sharpness" of the increase is not enough with this method. Ideally I could also control how sharp the increase in distance would be.\\ Thanks for your time.
tagged with: list
has answer: http://stackoverflow.com/a/51929177
has comment: http://stackoverflow.com/comment/90808765
downvote count: 1
type: Question

http://stackoverflow.com/q/51822078
linked to: http://stackoverflow.com/q/30103662
tagged with: python
has answer: http://stackoverflow.com/a/51822918
duplicate of: http://stackoverflow.com/q/30103662
tagged with: ftp
type: AnsweredQuestion
has title: How to Append to a file (FTP Python)
downvote count: 0
score: 1
type: Question
has body: I just wanted to ask how do you append a file when using the FTP library in python. I understand how to read/upload a file using FTP but how would i append to one. I was looking online and it montioned using a function called 'APPE' but im not sure how this works. This is what i have so far. ftp= FTP('some ip',a username','password') ftp.cwd('directory/direct/dir') ftp.storbinary('STOR atestfile.txt', open ('/home/pi/aFolder/afile1.txt', 'rb')) ftp.close() I would like to append the 'atestfile.txt' file. Thanks ~Neamus
upvote count: 1
answer count: 1
accepted answer: http://stackoverflow.com/a/51822918
favorite count: 0

http://stackoverflow.com/a/51925304
has comment: http://stackoverflow.com/comment/90800967
score: 0
answers question: http://stackoverflow.com/q/51925233
type: Answer
has body: Seems like you are trying to sort the list in descending order. If you need to keep the original list, you could do it using sorted() builtin function xlist = [('00:04:F2:FF:7A:1D', -88), ('4C:49:E3:64:9D:D6', -63), ('00:EC:0A:87:61:F8', -58), ('CC:9F:7A:99:0D:EA', -80)] ylist = sorted(xlist, key=lambda x: x[1], reverse=True) print(ylist) You also may sort the xlist inplace using list.sort() method: xlist.sort(key=lambda x: x[1], reverse=True) print(xlist)

http://stackoverflow.com/q/51941543
tagged with: server
has body: I have a .py script stored on my server. Lets assume the absolute path to this script being \\100.0.0.1\_projects\_topgun\_pipeline\scripts\bin\myscript.py to break a little an explain here I've created a script with the wonderful guidance of people here in my last topic, to copy and create directories based on a file name. However currently users my COPY and PASTE this .py file into the active directory and then run it using terminal / the python launcher. I would like to make this simpler so I am wondering if there is a way i can allow them to just go to the active directory they wish to run the script one and then just maybe right click invoke a CMD / Terminal menu that gives them options of scripts to run and they can press [1] which runs [myscript.py] To to list this down systematically: User browsers to a network folder they wish to run the script on They run terminal or cmd which lists all possible scripts to run They input a number based on the script they wish to run Script runs on active directory If this a complex task to answer I'm more than happy to accept guidance on how to run just the myscript.py on the active directory. Also worth noting is this is being built for both mac and windows but mainly windows for now. Thank you, hoping my question asking skills have improved from my last topic.
score: 0
has title: Running a python script that is stored on a server, on the current active directory
tagged with: macos
has answer: http://stackoverflow.com/a/51953324
type: UnansweredQuestion
tagged with: python
type: Question
has answer: http://stackoverflow.com/a/51942076
answer count: 2

http://stackoverflow.com/comment/90600762
type: Comment
comment on: http://stackoverflow.com/q/51822709
score: 0
type: QuestionComment
has text: You want `data_a['FC06'].dtypes`. The series is of course of type series, you want the type of the *data* in the series. But it seems you have some object column, presumably from some csv?

http://stackoverflow.com/q/51813140
type: AnsweredQuestion
type: Question
tagged with: python
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51813166
has answer: http://stackoverflow.com/a/51813173
upvote count: 3
has answer: http://stackoverflow.com/a/51813179
answer count: 3
has title: Dynamically compare list for common occurrences
downvote count: 1
possible better answer: http://stackoverflow.com/a/51813173
has body: I want to dynamically use sets to find common entires in lists. If I have a list of list that could contain any number of lists how can I go about find all the common occurrences in all the lists. I have thought about enumerating the list and storing each nested list in its own variable but then I am not sure how to compare all the individual lists. Example of List: l = [[1,2,3,4,], [3,6,4,2,1], [6,4,2,6,7,3]] I want to do something like this but dynamic so it can accept any number of lists: common = set(l[0]) &amp; set(l[1]) &amp; set(l[2])
accepted answer: http://stackoverflow.com/a/51813166
score: 2

http://stackoverflow.com/comment/90730680
type: Comment
comment on: http://stackoverflow.com/a/51869802
score: 0
type: AnswerComment
has text: @G_M Thanks for looking into this, your code works with my old carelessly copy-pasted `readout` string but doesn't seem to work with newer `readout` or real device.

http://stackoverflow.com/comment/90745267
comment on: http://stackoverflow.com/a/51885174
type: AnswerComment
score: 0
type: Comment
has text: Many thanks @curi0uz_k0d3r but its throwing me another error: `TypeError: object of type 'int' has no len()` at `File "python\lib\site-packages\Crypto\Cipher\AES.py", line 91, in _create_base_cipher if len(key) not in key_size`

http://stackoverflow.com/q/51816642
has body: I created a Custom user model from AbstractUserModel. I'm using django.contrib.auth.urls for simple login and logout functionalities including password_reset and When i'm still using the default user model of django, but its no longer working on my Custom user model. Is there a way to make this work for custom user model. (1146, "Table 'db.auth_user' doesn't exist") this is the error message i'm getting every time i login a sample account to my application. Thanks
has comment: http://stackoverflow.com/comment/90587566
has title: django.contrib.auth.urls is no longer working after creating a Custom User model
type: Question
has answer: http://stackoverflow.com/a/51817377
answer count: 1
score: 0
type: UnansweredQuestion
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/90587748

http://stackoverflow.com/a/51903098
downvote count: 0
answers question: http://stackoverflow.com/q/51902953
score: 1
has body: You have mainly two options: 1) Use extend: singleList.extend([rock, input('Size: '), int(input('Quantity: '))]) 2) Concatenate your list with another list: singleList += [rock, input('Size: '), int(input('Quantity: '))] They are quite close in performance: $ python -m timeit 'l = [1,2,3]; l.extend([4,5,6,7,8,9])' 1000000 loops, best of 3: 0.553 usec per loop $ python -m timeit 'l = [1,2,3]; l += [4,5,6,7,8,9]' 1000000 loops, best of 3: 0.493 usec per loop
upvote count: 1
type: Answer

http://stackoverflow.com/a/59842844
upvote count: 2
answers question: http://stackoverflow.com/q/51835312
downvote count: 0
has body: Try http://127.0.0.1:8000/postman/message/ if you're on localhost. It should resolve the issue.
type: Answer
score: 2

http://stackoverflow.com/q/51893868
has title: Vispy No module named 'vispy.visuals.text._sdf_cpu'
upvote count: 1
answer count: 1
accepted answer: http://stackoverflow.com/a/52043599
has body: I have downloaded vispy and installed all necessary dependencies (numpy pyqt and cython). I am now trying to run some of the examples and when I try to run chloropleth.py for instance I get the following traceback Traceback (most recent call last): File "/Users/xxx/Documents/vispy-master/examples/collections/chloropleth.py", line 11, in &lt;module&gt; from vispy.visuals.collections import PathCollection, PolygonCollection File "/Users/xxx/Documents/vispy-master/vispy/visuals/__init__.py", line 14, in &lt;module&gt; from .axis import AxisVisual # noqa File "/Users/xxx/Documents/vispy-master/vispy/visuals/axis.py", line 13, in &lt;module&gt; from .text import TextVisual File "/Users/xxx/Documents/vispy-master/vispy/visuals/text/__init__.py", line 7, in &lt;module&gt; from .text import TextVisual # noqa File "/Users/xxx/Documents/vispy-master/vispy/visuals/text/text.py", line 18, in &lt;module&gt; from ._sdf_cpu import _calc_distance_field ModuleNotFoundError: No module named 'vispy.visuals.text._sdf_cpu' I am using a MacbookPro 2017 with High Sierra and print(vispy.sys_info()) returns: Platform: Darwin-17.6.0-x86_64-i386-64bit Python: 3.7.0 (default, Jun 28 2018, 07:39:16) [Clang 4.0.1 (tags/RELEASE_401/final)] NumPy: 1.15.0 Backend: PyQt5 pyqt4: None pyqt5: ('PyQt5', '5.9.2', '5.9.6') pyside: None pyside2: None pyglet: None glfw: None sdl2: None wx: None egl: None osmesa: None _test: None GL version: '2.1 ATI-1.66.42' MAX_TEXTURE_SIZE: 16384 Extensions: 'GL_ARB_color_buffer_float GL_ARB_depth_buffer_float GL_ARB_depth_clamp GL_ARB_depth_texture GL_ARB_draw_buffers GL_ARB_draw_elements_base_vertex GL_ARB_draw_instanced GL_ARB_fragment_program GL_ARB_fragment_program_shadow GL_ARB_fragment_shader GL_ARB_framebuffer_object GL_ARB_framebuffer_sRGB GL_ARB_half_float_pixel GL_ARB_half_float_vertex GL_ARB_imaging GL_ARB_instanced_arrays GL_ARB_multisample GL_ARB_multitexture GL_ARB_occlusion_query GL_ARB_pixel_buffer_object GL_ARB_point_parameters GL_ARB_point_sprite GL_ARB…
favorite count: 0
has answer: http://stackoverflow.com/a/52043599
tagged with: python
type: AnsweredQuestion
tagged with: vispy
downvote count: 0
score: 1
tagged with: cython
type: Question

http://stackoverflow.com/q/51869699
tagged with: python-3.x
type: Question
tagged with: python
linked to: http://stackoverflow.com/q/36286894
has body: I have some codes like this: @zhihu.log_attr @zhihu.iter_factory('voters') def voters(x): from .People import People return People(x) But the IDE ... Imgur Image So I try this way: @zhihu.log_attr @zhihu.iter_factory('voters') def voters(x)-&gt;People: from .People import People return People(x) But it don't works. NameError: name 'People' is not defined
has comment: http://stackoverflow.com/comment/90714980
score: 0
has answer: http://stackoverflow.com/a/51869758
answer count: 1
type: UnansweredQuestion
has title: How to tell Sublime this function return will return that class in Python?
tagged with: sublimetext3

http://stackoverflow.com/comment/90690420
score: 1
has text: In `feed_dict={x: 3, y: 4.5}`, `x` and `y` are not string. They are `tf.placeholder` objects.
comment on: http://stackoverflow.com/q/51869401
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51837462
answer count: 6
upvote count: 10
possible better answer: http://stackoverflow.com/a/51837712
type: Question
has answer: http://stackoverflow.com/a/51837712
has comment: http://stackoverflow.com/comment/93371959
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/51837499
has answer: http://stackoverflow.com/a/51837510
has answer: http://stackoverflow.com/a/51837838
tagged with: strptime
tagged with: datetime
has answer: http://stackoverflow.com/a/51837754
tagged with: python
score: 10
has body: I am trying to the parse dates of the format '2016-04-15T12:24:20.707Z' in Python, tried strptime, doesn't work and I also tried django parse_datetime but it only returns none as the value
accepted answer: http://stackoverflow.com/a/51837838
has comment: http://stackoverflow.com/comment/90628128
has title: Custom date format parsing in python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/72503744
has comment: http://stackoverflow.com/comment/90628146

http://stackoverflow.com/comment/90620284
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51833145
type: AnswerComment
has text: ok, got it, I am super dumb this morning! Thanks for the heads up

http://stackoverflow.com/q/51822388
type: Question
has title: CodingBat Python make_chocolate code failing in "other tests"
has answer: http://stackoverflow.com/a/65439421
has comment: http://stackoverflow.com/comment/90598686
score: 0
has comment: http://stackoverflow.com/comment/90599203
upvote count: 1
has answer: http://stackoverflow.com/a/73268798
has answer: http://stackoverflow.com/a/75227501
accepted answer: http://stackoverflow.com/a/51822634
favorite count: 0
has answer: http://stackoverflow.com/a/70965729
possible better answer: http://stackoverflow.com/a/65439421
answer count: 5
has body: There is a coding problem on CodingBat.com (Logic-2 Python section) that asks for a function to determine how many small chocolate bars are used for a weight requirement. The question is as follows: We want make a package of goal kilos of chocolate. We have small bars (1 kilo each) and big bars (5 kilos each). Return the number of small bars to use, assuming we always use big bars before small bars. Return -1 if it can't be done. make_chocolate(4, 1, 9) → 4 make_chocolate(4, 1, 10) → -1 make_chocolate(4, 1, 7) → 2 I came up with this solution to the problem but it still fails in "other tests". Is there any problem that causes this? Code: def make_chocolate(small, big, goal): if (small + 5*big &lt; goal) or (goal % 5 &gt; small): return -1 elif small &gt;= goal: return small else: smallnum = 0 for i in range(1,big+1): if 5*i + small &gt;= goal: if 5*i &gt; goal: break smallnum = goal - 5*i return smallnum EDIT: I have managed to finish the problem thanks to Mariah Akinbi. I have updated the code as follows: def make_chocolate(small, big, goal): if (small + 5*big &lt; goal) or (goal % 5 &gt; small): return -1 elif 5 &lt;= goal: smallnum = 0 for i in range(1,big+1): if 5*i + small &gt;= goal: if 5*i &gt; goal: break smallnum = goal - 5*i return smallnum return goal
has comment: http://stackoverflow.com/comment/90598709
has answer: http://stackoverflow.com/a/51822634
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90598697
downvote count: 1

http://stackoverflow.com/a/51880613
accepted answer of: http://stackoverflow.com/q/51869854
type: Answer
has body: I think what you want is related to this post: https://math.stackexchange.com/questions/260096/find-the-coordinates-of-a-point-on-a-circle x = radius * np.sin(θ) y = radius * np.cos(θ) The radius is your y variable, and your θ must come from dividing a circle by the number of points in your dataset. theta = 360 / len(ydata) To verify the resulting point is really the correct distance away from the center (y) you can follow the formula sqr(x) + sqr(y) = sqr(r) and you'll see it's the correct distance at the correct angle. So the code looks something like this: import numpy as np import matplotlib.pyplot as plt from math import pi ydata = [10,11,12,13,16,13,12,11] #plt.plot(xdata, ydata) #plt.show() def wrap_around(radii): thetas = [i * (360 / len(radii)) for i in range(0, len(radii))] xs = [(radius * np.sin(np.deg2rad(theta))) for radius, theta in zip(radii, thetas)] ys = [(radius * np.cos(np.deg2rad(theta))) for radius, theta in zip(radii, thetas)] print(thetas, len(thetas)) print(xs, len(xs)) print(ys, len(ys)) return xs,ys x,y = wrap_around(ydata) plt.plot(x,y) plt.grid(True) plt.show()
answers question: http://stackoverflow.com/q/51869854
score: 0
type: AcceptedAnswer

http://stackoverflow.com/q/51925424
type: AnsweredQuestion
upvote count: 2
score: 1
downvote count: 1
has body: I need to tag certain words with lxml. Take this as an example, Please BOLD me, BOLD me too I need to find out all certain words, 'BOLD' here , and add tags to them. The result should be: Please BOLD me, BOLD me too It must use lxml, it is not only a regular expression problem. It needs some program calculation before tagging. More like this: s = 'Please BOLD me, BOLD me too' from lxml import etree et = etree.fromstring(s) for e in et.iter(): if 'BOLD' in e.text: **tag it** if 'BOLD' in e.tail: **tag it** I guess I need to create an element bold = etree.Element('b'); bold.text = 'BOLD' The problem is I don't know how to insert the above element bold gracefully.
type: Question
has title: python - lxml - How to tag words in texts gracefully?
has answer: http://stackoverflow.com/a/51925836
tagged with: lxml
answer count: 1
favorite count: 0
tagged with: http://stackoverflow.com/tag/xml
accepted answer: http://stackoverflow.com/a/51925836
tagged with: python

http://stackoverflow.com/q/51952860
tagged with: python
has comment: http://stackoverflow.com/comment/90856233
type: AnsweredQuestion
downvote count: 3
has title: I am getting an exception raised and I can't figure out why?
type: Question
upvote count: 0
has answer: http://stackoverflow.com/a/51952947
favorite count: 0
has comment: http://stackoverflow.com/comment/90857183
has comment: http://stackoverflow.com/comment/90856234
answer count: 1
tagged with: python-3.x
has body: def permutations(string, step = 0): # convert parameter to string in case we received something else try: if isinstance(string, str): # if we've gotten to the end, print the permutation if step == len(string): print "".join(string) # everything to the right of step has not been swapped yet for i in range(step, len(string)): # copy the string (store as array) string_copy = [character for character in string] # swap the current index with the step string_copy[step], string_copy[i] = string_copy[i], string_copy[step] # recurse on the portion of the string that has not been swapped yet (now it's index will begin with step + 1) permutations(string_copy, step + 1) else: raise Exception except Exception as error: print('Caught this error: string passed in paramater is not a string') permutations("abc", 0) Why is the exception being raised? Basically I want to prevent someone from passing a random object (that is not a string). So 123 or Vehicle() would fail. however I am getting an exception raised on a string (usually the second iteration of my recursive function)
score: -3
accepted answer: http://stackoverflow.com/a/51952947

http://stackoverflow.com/q/51803649
upvote count: 2
has body: I am iteratively processing some data as follows: Do some processing and generate the results as such ~~~timestamp1 a 0.3 b 0.2 c 0.4 Do some further processing, the results shall be ~~~timestamp1 timestamp2 a 0.3 b 0.2 0.3 c 0.4 d 0.1 Do some further processing, the results shall be ~~~timestamp1 timestamp2 timestamp3 a 0.3 0.1 b 0.2 0.3 c 0.4 d 0.1 e 0.5 f 0.2 g 0.6 That means, each step adds a new column. The row may also grow. The point is, in each column there would be only a part of the data having values. The others not, therefore SparseSeries seems be a fit data structure for this. === Question === The question is, how can such a SparseSeries be generated in a successive manner? Thanks! Note: At each time step there will be a new sequence generated, such as [('b', 0.3), ('d', 0.1)]. My goal is to store them in a unified data structure such as a SparseSerie.
tagged with: scipy
has comment: http://stackoverflow.com/comment/90563679
type: Question
has answer: http://stackoverflow.com/a/51809395
has comment: http://stackoverflow.com/comment/90563785
tagged with: pandas
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/90564852
favorite count: 0
accepted answer: http://stackoverflow.com/a/51809395
has comment: http://stackoverflow.com/comment/90563366
has comment: http://stackoverflow.com/comment/90568817
tagged with: python
score: 2
type: AnsweredQuestion
has title: python data structure with sparse series

http://stackoverflow.com/q/51833343
tagged with: python
has comment: http://stackoverflow.com/comment/90620602
score: 0
tagged with: pivot-table
answer count: 1
has body: I have a large data set on a CSV (Dataset). I want to create a pd.pivot_table to summarize the data by zip code, however, my data has lines that share the same zip code. df = pd.read_csv('15zpallagi.csv') df['A00100'] = df['A00100'].map('{:,.2f}'.format) df.pivot_table(values='A00100', index='zipcode', aggfunc='sum') When I run the code above to create a pivot_table, the value column includes several values, like if it was stacking on the sum with multiple values. However if run the following code, I get the same values, but in an understandable format. df.pivot_table(values='A00100', index='zipcode',columns='agi_stub', aggfunc='sum') How can I create a pivot table that just adds the column A00100 and gives me a total by zip code?
has title: Pandas Pivot_Table grouped values
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51833659
type: Question
tagged with: pandas

http://stackoverflow.com/q/51929349
favorite count: 0
has answer: http://stackoverflow.com/a/51929879
accepted answer: http://stackoverflow.com/a/51929879
tagged with: python
tagged with: http://stackoverflow.com/tag/xml
has body: I have an XML file which looks like this: <vlan-terse/> 0 ACRS-Dev2 Fri Jan 1 00:37:59 2010 Enabled static 0 2 vlan.15 (UP) <vlan-l3-interface-address>10.8.25.1/24</vlan-l3-interface-address> Port Mode 7 6 0 default Fri Jan 1 00:37:59 2010 Enabled static 0 3 vlan.11 (UP) <vlan-l3-interface-address>10.8.27.1/24</vlan-l3-interface-address> Port Mode 12 2 From this, I only want the and <vlan-l3-interface-address> tags which are to be parsed and saved in a dict/json like variable with it's format being: {'Vlan-Name' : vlan_name, 'Interface-Address' : interface_addr} and then add these dict/json for each element in a list of dicts/json. This is my code for parsing and insertion of the json in list: root = tree.getroot() nw_pool = [] nw_json = {} for child in root: for items in child: for item1 in items: if 'vlan-l3-interface-address' in item1.tag: interface_addr = item1.text nw_json['Interface-Address'] = interface_addr elif 'vlan-name' in item1.tag: vlan_name = item1.text nw_json['Vlan-Name'] = vlan_name nw_pool.append(nw_json) print(nw_pool) But when I print the nw_pool, it gives me an output where the json of the last element found is repeated instead of giving me distinct dicts for each element. Output: [{'Vlan-Name': 'default', 'Interface-Address': '10.8.27.1/24'}, {'Vlan-Name': 'default', 'Interface-Address': '10.8.27.1/24'}] Whereas my desired output is: [{'Vlan-Name': 'ACRS-Dev2', 'Interface-Address': '10.8.25.1/24'}, {'Vlan-Name': 'default', 'Interface-Address': '10.8.27.1/24'}] Can somebody help me with this? Thanks in advance.
has answer: http://stackoverflow.com/a/51930001
has title: How to parse and fetch only the desired XML elements from an XML file using python?
type: AnsweredQuestion
downvote count: 0
score: 1
tagged with: http://stackoverflow.com/tag/json
type: Question
answer count: 2
upvote count: 1
possible better answer: http://stackoverflow.com/a/51930001

http://stackoverflow.com/a/51920724
upvote count: 3
answers question: http://stackoverflow.com/q/51919175
type: Answer
has body: Load your sounds once in the global scope or in another module and then reuse them in your game. SHOOT_SOUND = pygame.mixer.Sound('sounds/shoot.wav') SHOOT_SOUND.set_volume(0.2) def fire_bullet(si_settings, screen, ship, bullets): """Fire a bullet, if limit not reached yet.""" if len(bullets) &lt; si_settings.bullets_allowed: new_bullet = Bullet(si_settings, screen, ship) bullets.add(new_bullet) SHOOT_SOUND.play()
score: 3
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51919175

regex
tags question: http://stackoverflow.com/q/51943961
tags question: http://stackoverflow.com/q/51844260
tags question: http://stackoverflow.com/q/51937351
tags question: http://stackoverflow.com/q/51934755
tags question: http://stackoverflow.com/q/51868573
tags question: http://stackoverflow.com/q/51882155
tags question: http://stackoverflow.com/q/51864326
tags question: http://stackoverflow.com/q/51869782
tags question: http://stackoverflow.com/q/51919641
tags question: http://stackoverflow.com/q/51861706
tags question: http://stackoverflow.com/q/51925843
tags question: http://stackoverflow.com/q/51888893
tags question: http://stackoverflow.com/q/51848113
tag name: regex
tags question: http://stackoverflow.com/q/51811316
tags question: http://stackoverflow.com/q/51887388
tags question: http://stackoverflow.com/q/51893787
tags question: http://stackoverflow.com/q/51899665
tags question: http://stackoverflow.com/q/51872721
tags question: http://stackoverflow.com/q/51833129
tags question: http://stackoverflow.com/q/51811914
tags question: http://stackoverflow.com/q/51905346
tags question: http://stackoverflow.com/q/51867868
tags question: http://stackoverflow.com/q/51932484
tags question: http://stackoverflow.com/q/51827564
tags question: http://stackoverflow.com/q/51856781
tags question: http://stackoverflow.com/q/51812972
tags question: http://stackoverflow.com/q/51888539
tags question: http://stackoverflow.com/q/51936276
tags question: http://stackoverflow.com/q/51859165
tags question: http://stackoverflow.com/q/51919931
tags question: http://stackoverflow.com/q/51831202
tags question: http://stackoverflow.com/q/51895217
tags question: http://stackoverflow.com/q/51906929
tags question: http://stackoverflow.com/q/51933210
tags question: http://stackoverflow.com/q/51823026
tags question: http://stackoverflow.com/q/51829190
tags question: http://stackoverflow.com/q/51939680
tags question: http://stackoverflow.com/q/51847520
tags question: http://stackoverflow.com/q/51934520
tags question: http://stackoverflow.com/q/51861390
tags question: http://stackoverflow.com/q/51902666
tags question: http://stackoverflow.com/q/51869683
tags question: http://stackoverflow.com/q/51801510
tags question: http://stackoverflow.com/q/51866274
tags question: http://stackoverflow.com/q/51955475
tags question: http://stackoverflow.com/q/51833930
tags question: http://stackoverflow.com/q/51946007
tags question: http://stackoverflow.com/q/51828826
tags question: http://stackoverflow.com/q/51920019
tags question: http://stackoverflow.com/q/51823655
tags question: http://stackoverflow.com/q/51916052
tags question: http://stackoverflow.com/q/51827710
tags question: http://stackoverflow.com/q/51817242
tags question: http://stackoverflow.com/q/51879956
tags question: http://stackoverflow.com/q/51913726
tags question: http://stackoverflow.com/q/51910396
tags question: http://stackoverflow.com/q/51858423
tags question: http://stackoverflow.com/q/51866330
tags question: http://stackoverflow.com/q/51862861
tags question: http://stackoverflow.com/q/51912763
tags question: http://stackoverflow.com/q/51875290
tags question: http://stackoverflow.com/q/51818807
tags question: http://stackoverflow.com/q/51825453
tags question: http://stackoverflow.com/q/51861625
tags question: http://stackoverflow.com/q/51841401
tags question: http://stackoverflow.com/q/51887141
tags question: http://stackoverflow.com/q/51918261
tags question: http://stackoverflow.com/q/51893013
tags question: http://stackoverflow.com/q/51886803
tags question: http://stackoverflow.com/q/51804462
tags question: http://stackoverflow.com/q/51880062
tags question: http://stackoverflow.com/q/51832038
tags question: http://stackoverflow.com/q/51886880
tags question: http://stackoverflow.com/q/51949457
tags question: http://stackoverflow.com/q/51817609
tags question: http://stackoverflow.com/q/51846057
tags question: http://stackoverflow.com/q/51897861
tags question: http://stackoverflow.com/q/51924271
tags question: http://stackoverflow.com/q/51843263

http://stackoverflow.com/q/51943811
tagged with: wordnet
has title: Does the lemmatization mechanism reduce the size of the corpus?
type: Question
has comment: http://stackoverflow.com/comment/90837814
tagged with: lemmatization
tagged with: nltk
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51978364
accepted answer: http://stackoverflow.com/a/51978364
upvote count: 3
tagged with: python-3.x
has body: Dear Community Members, During the pre-processing of data, after splitting the raw_data into tokens, I have used the popular WordNet Lemmatizer to generate the stems. I am performing experiments on a dataset that has 18953 tokens. My question is, does the lemmatization process reduce the size of corpus? I am confused, kindly help in this regard. Any help is appreciated!
tagged with: python
type: AnsweredQuestion
score: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/90837293

http://stackoverflow.com/q/51831829
has comment: http://stackoverflow.com/comment/90617811
upvote count: 1
has answer: http://stackoverflow.com/a/51831896
has body: For example, given a list of strings prices = ["US$200", "CA$80", "GA$500"], I am trying to only return ["US", "CA", "GA"]. Here is my code - what am I doing wrong? def get_country_codes(prices): prices = "" list = prices.split() list.remove("$") "".join(list) return list
type: Question
has comment: http://stackoverflow.com/comment/90617848
score: -1
has answer: http://stackoverflow.com/a/51831927
has comment: http://stackoverflow.com/comment/90617781
has answer: http://stackoverflow.com/a/51831863
has answer: http://stackoverflow.com/a/51831905
tagged with: string
favorite count: 0
tagged with: python
answer count: 4
has comment: http://stackoverflow.com/comment/90617796
tagged with: list
has title: Python: Removing characters from a string and then returning it
type: UnansweredQuestion
downvote count: 2

http://stackoverflow.com/q/51900315
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51978136
has title: Pymodbus TCP `read_holding_registers` returns stale/old data
tagged with: modbus
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/90833028
answer count: 1
tagged with: pymodbus
upvote count: 3
has comment: http://stackoverflow.com/comment/90906076
has comment: http://stackoverflow.com/comment/90760726
has comment: http://stackoverflow.com/comment/90896463
tagged with: modbus-tcp
accepted answer: http://stackoverflow.com/a/51978136
has comment: http://stackoverflow.com/comment/90833282
has body: I've started using pymodbus to read values from modbus to store in a database off site. I've been struggling with an issue that the value received in the response is not the same as the value I can see on the Jace. I've tried modbus-tk as well and I'm getting the same incorrect response, so it must be something in my Python code that is causing this issue. The readings retrieved from our legacy system (VB.Net) are the same as the outputs I see on the Jace. This is the simple function retrieving the data from modbus. We have 2 registers at 40160 and 40162 the first one is reading 366 which is correct and the 2nd one is reading 367 (This is the one I'm having the problem with). I've also seen the same issue with other registers where the reading does not update even though I can see on the Jace that the value has increased. # -*- coding: utf-8 -*- from __future__ import division, print_function, unicode_literals from pymodbus.client.sync import ModbusTcpClient from pymodbus.constants import Endian from pymodbus.payload import BinaryPayloadDecoder def get_modbus_register_data(ip_address, register, device, count=2): """ Retrieve modbus data. """ client = ModbusTcpClient(ip_address, timeout=10) client.connect() # Read registers response = client.read_holding_registers( address=register, # 40162 count=count, # 2 unit=device) # 4 decoder = BinaryPayloadDecoder.fromRegisters( registers=response.registers, byteorder=Endian.Big, wordorder=Endian.Little) value = decoder.decode_32bit_float() client.close() return value # 366 and it should be 367 Pymodbus debug logs DEBUG:pymodbus.transaction:Current transaction state - IDLE DEBUG:pymodbus.transaction:Running transaction 1 DEBUG:pymodbus.transaction:SEND: 0x0 0x1 0x0 0x0 0x0 0x6 0x4 0x3 0x0 0xa0 0x0 0x2 DEBUG:pymodbus.client.sync:New Transaction state 'SENDING' DEBUG:pymodbus.transaction:Changing transaction state from 'SENDING' to 'WAITING FOR REPLY' DEBUG:pymodbus.transaction:Changing transaction state from 'WAITING FOR REPLY'…
downvote count: 0
has comment: http://stackoverflow.com/comment/90825202
type: AnsweredQuestion
score: 3
favorite count: 0

beautifulsoup
tags question: http://stackoverflow.com/q/51939415
tags question: http://stackoverflow.com/q/51870338
tags question: http://stackoverflow.com/q/51899780
tags question: http://stackoverflow.com/q/51939902
tags question: http://stackoverflow.com/q/51836275
tags question: http://stackoverflow.com/q/51848530
tags question: http://stackoverflow.com/q/51863466
tags question: http://stackoverflow.com/q/51850632
tags question: http://stackoverflow.com/q/51837685
tags question: http://stackoverflow.com/q/51823336
tags question: http://stackoverflow.com/q/51886306
tags question: http://stackoverflow.com/q/51848623
tags question: http://stackoverflow.com/q/51895517
tags question: http://stackoverflow.com/q/51799523
tags question: http://stackoverflow.com/q/51929133
tags question: http://stackoverflow.com/q/51869675
tag name: beautifulsoup
tags question: http://stackoverflow.com/q/51941135
tags question: http://stackoverflow.com/q/51826131
tags question: http://stackoverflow.com/q/51844897
tags question: http://stackoverflow.com/q/51888181
tags question: http://stackoverflow.com/q/51847473
tags question: http://stackoverflow.com/q/51949091
tags question: http://stackoverflow.com/q/51839937
tags question: http://stackoverflow.com/q/51888615
tags question: http://stackoverflow.com/q/51850577
tags question: http://stackoverflow.com/q/51922936
tags question: http://stackoverflow.com/q/51816917
tags question: http://stackoverflow.com/q/51891481
tags question: http://stackoverflow.com/q/51914581
tags question: http://stackoverflow.com/q/51843569
tags question: http://stackoverflow.com/q/51832901
tags question: http://stackoverflow.com/q/51893567
tags question: http://stackoverflow.com/q/51921882
tags question: http://stackoverflow.com/q/51918768
tags question: http://stackoverflow.com/q/51895560
tags question: http://stackoverflow.com/q/51821475
tags question: http://stackoverflow.com/q/51812028
tags question: http://stackoverflow.com/q/51847199
tags question: http://stackoverflow.com/q/51915453
type: Tag
tags question: http://stackoverflow.com/q/51849020
tags question: http://stackoverflow.com/q/51941396
tags question: http://stackoverflow.com/q/51939159
tags question: http://stackoverflow.com/q/51802903
tags question: http://stackoverflow.com/q/51894849
tags question: http://stackoverflow.com/q/51900107
tags question: http://stackoverflow.com/q/51800216
tags question: http://stackoverflow.com/q/51865855
tags question: http://stackoverflow.com/q/51856980
tags question: http://stackoverflow.com/q/51804725
tags question: http://stackoverflow.com/q/51805950
tags question: http://stackoverflow.com/q/51902677
tags question: http://stackoverflow.com/q/51951583
tags question: http://stackoverflow.com/q/51938519
tags question: http://stackoverflow.com/q/51836884
tags question: http://stackoverflow.com/q/51846955
tags question: http://stackoverflow.com/q/51937148
tags question: http://stackoverflow.com/q/51931167
tags question: http://stackoverflow.com/q/51833649
tags question: http://stackoverflow.com/q/51846867
tags question: http://stackoverflow.com/q/51921221
tags question: http://stackoverflow.com/q/51905704
tags question: http://stackoverflow.com/q/51899594
tags question: http://stackoverflow.com/q/51907544
tags question: http://stackoverflow.com/q/51935973
tags question: http://stackoverflow.com/q/51854097
tags question: http://stackoverflow.com/q/51956543
tags question: http://stackoverflow.com/q/51911439
tags question: http://stackoverflow.com/q/51913514
tags question: http://stackoverflow.com/q/51865429
tags question: http://stackoverflow.com/q/51829893
tags question: http://stackoverflow.com/q/51852588
tags question: http://stackoverflow.com/q/51897756
tags question: http://stackoverflow.com/q/51801510
tags question: http://stackoverflow.com/q/51863989

http://stackoverflow.com/q/51841002
tagged with: bioinformatics
has body: I am trying to align hundreds of transcription factor binding site sequences to my reference sequence. For example in the sequence below, in bold are the two TF binding sites it maps to. CTGGCGCGTGATCAACTGGCCAATCATGGCATCTGTCATTGTGAGTATAACCTCACACCCGTACTTCTAAACACACAGACCAGCCTCATACTGTATGCATTATGTCAGGCAGG GAGGGATTCTGCCAGCAAAGCAGACGAGGGGATGTGCTGAGTCTCACAGACACTTTCCTGGATAAGACATGAATGCAGGCATGTCAGGAAGAGCAAGCAAACACGCTGTCC When I try to use the alignment function in snapgene, the output shows one site where the TF sequence is mapped to. However, when I manually ctrl+f to search for matches for my TF sequence, there are two sites (bold above) which match my sequence 100%, however it can only be automatically aligned or made into a feature by snapgene for the first matching site it comes across and does not do it for the second site. I was just wondering if there are any suggestions or platforms (E.g. python, R) to map multiple short sequences to a reference sequence, which has the capability to annotate all possible alignment sites on the reference sequence?
type: UnansweredQuestion
downvote count: 2
upvote count: 1
type: Question
score: -1
has answer: http://stackoverflow.com/a/51841418
answer count: 1
tagged with: alignment
tagged with: http://stackoverflow.com/tag/r
tagged with: python
has title: Map motifs back to multiple sites in a reference sequence
favorite count: 0
has comment: http://stackoverflow.com/comment/90636752

http://stackoverflow.com/comment/90706070
type: Comment
comment on: http://stackoverflow.com/a/51876017
type: AnswerComment
has text: thanks for answering! >yes, timeSource is same column as time stamp >yes "de" is "of" i reamoved it anyway as you sugested >yes "seconds" is "secs" i translated some words from spanish but i left some behind :( >yes, im replacing newer value with older one im editing the orignal post
score: 0

http://stackoverflow.com/comment/90796879
comment on: http://stackoverflow.com/q/51923655
type: QuestionComment
has text: @e4c5 it is not a field, it is a dictionary attribute with some information that must be populated to the database table related to the model
score: 0
type: Comment

http://stackoverflow.com/a/51967955
has comment: http://stackoverflow.com/comment/90898211
has body: If I understood correctly you have time series data and you want to crate batches of data with the same length by sampling from it? I think you can use Dataset for returning just one sample of data as it was initially intended by the PyTorch developers. You can stack them in the batch with your own _collate_fn function and pass it to the DataLoader class (_collate_fn is a callable which takes a list of samples and returns a batch, usually, for example, padding is done there). So you would not have a dependency of length (=batch size in your dataset class). I assume you want to preserve sequential order of your samples when you form a batch (given that you work with time series), you can write your own Sampler class (or use SequentialSampler already available in PyTorch). As a result, you will decouple your sample representation, forming them in a batch (_collate_fn in DataLoader) and sampling (Sampler class). Hope this helps.
accepted answer of: http://stackoverflow.com/q/51939022
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51939022
type: Answer
score: 3
upvote count: 3

http://stackoverflow.com/q/51807243
has comment: http://stackoverflow.com/comment/90569848
favorite count: 0
possible better answer: http://stackoverflow.com/a/51807314
has body: I've read some blogs and docs that when access an instance attribute obj.a: try accessing data descriptor (named a) in current class __dict__ and base class __dict__ find a in obj.__dict__ find non-data descriptor (named a) in current class __dict__ and base class __dict__ find attribute (named a) in current class __dict__ and base class __dict__ call __getattr__ if any raise AttributeError But I found that this searching rule does not match the behavior of below codes: class ADesc(object): def __init__(self, name): self._name = name def __get__(self, obj, objclass): print('get.....') return self._name + ' ' + str(obj) + ' ' + str(objclass) def __set__(self, obj, value): print('set.....') self._name = value class A(object): dd_1 = ADesc('dd_1 in A') class B(A): dd_1 = 'dd_1 in B' if __name__ == '__main__': print(A.__dict__) # {'dd_1': &lt;__main__.ADesc object at 0x10ed0d050&gt;, '__dict__': &lt;attribute '__dict__' of 'A' objects&gt;, '__module__': '__main__', '__weakref__': &lt;attribute '__weakref__' of 'A' objects&gt;, '__doc__': None} print(B.__dict__) # {'dd_1': 'dd_1 in B', '__module__': '__main__', '__doc__': None} b = B() print(b.dd_1) # dd_1 in B I think the last print(b.dd_1) will invoke the __get__ in ADesc, because according to the 1st rule, __dict__ of base class A contains the attribute dd_1 that we're accessing, so that data descriptor should be called. So is the above access rule wrong or any other magic involved here ?
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51807314
type: Question
answer count: 2
accepted answer: http://stackoverflow.com/a/51807354
score: 0
has answer: http://stackoverflow.com/a/51807354
upvote count: 1
downvote count: 1
tagged with: python
has title: python attribute access with data descriptor
tagged with: instance-variables

http://stackoverflow.com/q/51893809
type: Question
has answer: http://stackoverflow.com/a/51900816
has answer: http://stackoverflow.com/a/51900760
tagged with: google-cloud-dataflow
has body: I'm running a Google Dataflow pipeline job and its job ID is: 2018-08-17_03_35_19-3029795715446392897 The console says that it has adjusted my autoscaling from 3 to 1000 nodes based on the current rate of progress, but the job is still saying at 3 nodes only. I also haven't received any errors in the Google Cloud Console regarding quota limits, so I'm not sure why Dataflow isn't scaling my pipeline, despite it saying so. Thank you for the help!
score: 0
answer count: 2
tagged with: google-cloud-platform
type: UnansweredQuestion
tagged with: python
has title: Google Cloud Dataflow - Autoscaling not working

http://stackoverflow.com/q/51842593
has title: DataFrame does not work well with my for loop
type: Question
answer count: 2
score: 0
accepted answer: http://stackoverflow.com/a/51843783
tagged with: pandas
has body: My for loop doesn't work well as soon as I update my DataFrame (I am not a programmer. I am using python 2.7.15). my code is not efficient, but still should to work, so please do not change my loop, tell me how to change the DataFrame only. The downloaded DataFrame (from AlphaVantage) looks like this: Open High ... 8. split coefficient datetime 0 31.1100 31.3500 ... 1.0000 2018-07-23 1 31.2900 31.3100 ... 1.0000 2018-07-20 2 28.4800 29.1200 ... 1.0000 2018-07-26 3 28.8200 29.3350 ... 1.0000 2018-07-27 4 30.4500 30.9400 ... 1.0000 2018-07-24 As soon as I update to my DataFrame to looks like this: Open High Low Close AdjClose Volume datetime 2018-07-23 31.1100 31.3500 30.6000 30.8200 30.8200 6023310 2018-07-20 31.2900 31.3100 30.8450 31.1100 31.1100 5022452 2018-07-26 28.4800 29.1200 27.5500 28.9800 28.9800 10582061 2018-07-27 28.8200 29.3350 27.7050 28.1300 28.1300 8101362 2018-07-24 30.4500 30.9400 29.9650 30.1400 30.1400 5706941 As soon as run the program with my loop, I got this error: TypeError: cannot insert DatetimeIndex with incompatible label The relevant part of the code is: import requests import pandas as pd import numpy as np import json import datetime as dt import matplotlib as plt . . . df['datetime'] = pd.to_datetime(df['datetime']) df.set_index('datetime', inplace=True) df.sort_index(inplace=False) # extract the default columns df = df[columns] return df df = df_from_response(data) df.sort_index(ascending=True, inplace=False) # Current day on top data frame A=pd.DataFrame(df) print (A.head(5)) #3 Len=len(A) print (Len) # Upward and Downward movement calculation for Rw in range(Len-1): def adj(A): adj_N=float(A.iloc[Rw,4]) adj_O=float(A.iloc[Rw+1,4]) #print (adj_N,adj_O) if adj_N&gt;adj_O: x1=adj_N-adj_O x2=0 else: x1=0 x2=adj_O-adj_N A.at[Rw+1,'UpMv']=x1 A.at[Rw+1,'DownMv']=x1 adj(A) print (A.head()) When I change line df.set_index('datetime', inplace=True) to "False", the "for loop" works well, but the DataFrame is change, and the index "datetime" d…
possible better answer: http://stackoverflow.com/a/51842884
has answer: http://stackoverflow.com/a/51842884
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51843783

http://stackoverflow.com/comment/90723005
score: 0
type: Comment
type: QuestionComment
has text: Hi welcome to SO. Can you update your question with any error logs?
comment on: http://stackoverflow.com/q/51885734

http://stackoverflow.com/a/58485467
answers question: http://stackoverflow.com/q/51929131
type: Answer
score: 3
downvote count: 0
has body: I have researched for a trascription speed guarantee with no luck In this forum post (requires an aws account) a poster makes a benchmark with the following results: A 10 minute clip took about 5 minutes 40 minute clips take around 17 minutes a 2 hour file took 36 minutes What seems to be an official Amazon source states that "At this time, transcription speeds are better optimized for audio longer than 30 seconds. You'll start to see a better processing time to audio duration time ratio when the audio file length is about 2 minutes or longer. Having said, this we are working hard to enhance transcription speeds overall" I hope it helps researchers
upvote count: 3

http://stackoverflow.com/q/51899558
tagged with: raspberry-pi
downvote count: 0
answer count: 1
favorite count: 0
tagged with: google-cloud-platform
tagged with: environment-variables
has title: Setting environment variables for Google Cloud Text to Speech in Raspbian doesn't work
has body: I want to implement a text-to-speech function for my application using Python. However, I got this error after following a tutorial here https://cloud.google.com/text-to-speech/docs/reference/libraries. Traceback (most recent call last): File "tts.py", line 3, in &lt;module&gt; client = texttospeech.TextToSpeechClient() File "/usr/local/lib/python2.7/dist-packages/google/cloud/texttospeech_v1/gapic/text_to_speech_client.py", line 84, in __init__ scopes=self._DEFAULT_SCOPES, File "/usr/local/lib/python2.7/dist-packages/google/api_core/grpc_helpers.py", line 170, in create_channel credentials, _ = google.auth.default(scopes=scopes) File "/usr/local/lib/python2.7/dist-packages/google/auth/_default.py", line 306, in default raise exceptions.DefaultCredentialsError(_HELP_MESSAGE) google.auth.exceptions.DefaultCredentialsError: Could not automatically determine credentials. Please set GOOGLE_APPLICATION_CREDENTIALS or explicitly create credentials and re-run the application. For more information, please see https://developers.google.com/accounts/docs/application-default-credentials. I've set the environment variable (GOOGLE_APPLICATION_CREDENTIALS) using this command in Terminal and I am positive that my credentials are working as I've tested on other Google Cloud services. export GOOGLE_APPLICATION_CREDENTIALS="/home/pi/labs/test/google_credentials.json" Here are some of the things that I've done but didn't manage to work still Reinstalled google-cloud-texttospeech Making credentials permanent Ensure that my environment variables are set by using env &amp; set | grep GOOGLE_APPLICATION_CREDENTIALS on the terminal to check Restarted my raspberry pi
has answer: http://stackoverflow.com/a/51900236
tagged with: google-text-to-speech
upvote count: 1
tagged with: python
type: AnsweredQuestion
score: 1
accepted answer: http://stackoverflow.com/a/51900236
type: Question

http://stackoverflow.com/q/51887012
favorite count: 0
has comment: http://stackoverflow.com/comment/90725408
type: Question
has comment: http://stackoverflow.com/comment/90725402
tagged with: python
has answer: http://stackoverflow.com/a/51887130
has title: How to declare many variables?
has answer: http://stackoverflow.com/a/51887045
upvote count: 1
has comment: http://stackoverflow.com/comment/90725358
has answer: http://stackoverflow.com/a/51887134
has comment: http://stackoverflow.com/comment/90725395
has answer: http://stackoverflow.com/a/51887044
answer count: 5
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51887125
has body: Here is the letters: letters='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789' I made a list of it with this: chars=[] for i in letters: chars.append(i) So I have a chars list. I need to all variables=0 each one to declare. And I wrote that: for i in chars: chars[i]=0; But there is an error message, like this: Traceback (most recent call last): File "python", line 15, in &lt;module&gt; TypeError: list indices must be integers or slices, not str The question: How to declare these multiple variables?
has comment: http://stackoverflow.com/comment/90725379
downvote count: 0
score: 1

http://stackoverflow.com/q/51934942
tagged with: python
type: AnsweredQuestion
score: 1
upvote count: 1
tagged with: multi-index
type: Question
has title: Add column using groupby in multiindex Pandas
has body: I am trying to find the sum of a column based upon the groupby function. so in this example i want to find the sum of all the bar, baz, foo, and qux. the sum would be added to a new column at the end. i can get the results i need but i can not join it back to the dataframe. import numpy as np import pandas as pd arrays = [np.array(['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux']), np.array(['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two'])] np.random.seed(7) df = pd.DataFrame(np.random.randn(8, 4), index=arrays) results=df.groupby(level=[0]).sum(axis=1) col_names=results.columns.values hold=[] for i in col_names: hold.append('sum_'+str(i)) results.columns=hold df=pd.concat([df,results],axis=1) Desired result below. thanks for looking 0 1 2 3 sum_0 sum_1 sum_2 sum_3 bar one 1.69 (0.47) 0.03 0.41 0.90 (0.46) 0.03 (1.35) bar two (0.79) 0.00 (0.00) (1.75) 0.90 (0.46) 0.03 (1.35) baz one 1.02 0.60 (0.63) (0.17) 1.52 0.34 (0.87) (1.62) baz two 0.51 (0.26) (0.24) (1.45) 1.52 0.34 (0.87) (1.62) foo one 0.55 0.12 0.27 (1.53) 2.21 0.28 (0.11) 0.50 foo two 1.65 0.15 (0.39) 2.03 2.21 0.28 (0.11) 0.50 qux one (0.05) (1.45) (0.41) (2.29) 1.00 (1.87) (1.15) (1.22) qux two 1.05 (0.42) (0.74) 1.07 1.00 (1.87) (1.15) (1.22)
tagged with: dataframe
has answer: http://stackoverflow.com/a/51935011
tagged with: pandas
answer count: 1
accepted answer: http://stackoverflow.com/a/51935011
downvote count: 0
favorite count: 0

http://stackoverflow.com/q/51953819
score: -1
tagged with: function
upvote count: 0
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51953878
tagged with: python
has body: I was solving a question which asked me for an output for a given sequence of input. First input is 'N' which is number of days, second input is a sequence of N integers separated by a Space, Third is Q (number of test-cases) and from forth onward are two Integers(l and r, l &lt; r) separated by a space(Q times). Sample input: 5 65 615 16 516 651 5 45 65 63 5635 654 862 0 956 56 89 The output I need to generate is how many days are there when the profit is between l and r(both included), for each test case. Expected output for sample Input: 1 4 0 5 1 I have written this code in python 3. But it only works for the first test-case, and for all other cases it prints 0. def solve(N,profit,l,r): days = 0 for i in range(N): for perdayprofit in profit: if l &lt;= perdayprofit &lt;= r : days = days + 1 return days N = int(input()) profit = map(int,input().split(" ")) Q = int(input()) for i in range(Q): l,r = map(int,input().split(" ")) out = solve(N,profit,l,r) print(out) Can someone please explain me what have i done wrong? Or is there any other approach to this question? I think my solution should work. I am using Jupyterlab and python 3, if you need to know.
has comment: http://stackoverflow.com/comment/90857978
has comment: http://stackoverflow.com/comment/90857975
accepted answer: http://stackoverflow.com/a/51953878
downvote count: 1
has comment: http://stackoverflow.com/comment/90858088
has title: My Python loop in a function is not running again when i call it again from another point
type: Question
tagged with: debugging
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90858234

http://stackoverflow.com/comment/90719200
has text: @AsavPatel I added a possible example above
comment on: http://stackoverflow.com/q/51812883
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51942909
has title: Flask restplus SQL query output formatting
has comment: http://stackoverflow.com/comment/90835992
answer count: 0
type: Question
has comment: http://stackoverflow.com/comment/90835318
has body: Using sqlplus inside python to generate SQL output. Running this via flaskplus, the formatting is lost i.e. the characters like \n,\t are not getting rendered. Tried different ways to fix this but din't help. 'print' works but 'return' doesn't work fine. @api.route('/db-health-report') class runSqlQuery(Resource): def get(self): session = Popen(['sqlplus', '-S', connect_string], stdin=PIPE, stdout=PIPE, stderr=PIPE) session.stdin.write(sql_command) queryResult, errorMessage = session.communicate() #print(queryResult, file=sys.stderr) #return queryResult.decode('string_escape') return queryResult
has comment: http://stackoverflow.com/comment/90835774
tagged with: flask-restful
score: 0
tagged with: flask-restplus
tagged with: sqlplus
has comment: http://stackoverflow.com/comment/90836042
tagged with: flask
has comment: http://stackoverflow.com/comment/90835839
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/51928094
score: 1
upvote count: 1
has body: To view the screen, you'll need to use a different protocol. I recommend RDP, because it's already installed on Windows computers. You can use the rdpy module to do this. As for seeing what programs are running, there's probably some way to list currently running processes but I can't find it either.
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51926699

http://stackoverflow.com/comment/90862761
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51955649
has text: Note that `ssh` just concatenates all its arguments together into one command and invokes it in a remote shell. There is absolutely no difference whatsoever between `['ssh', 'pi@B', 'cat telemetry >telemetry.copy']` and `['ssh', 'pi@B', 'cat', 'telemetry', '>telemetry.copy']`.

http://stackoverflow.com/comment/90895949
comment on: http://stackoverflow.com/q/51939709
score: 0
type: Comment
type: QuestionComment
has text: @KendrickKesley here's the data of the body https://gist.github.com/Petesta/d1d0d18b0694923f29b97d747d22cff2. The `content-type` is `multipart/form-data`.

http://stackoverflow.com/q/51874840
answer count: 3
has answer: http://stackoverflow.com/a/51878887
favorite count: 0
accepted answer: http://stackoverflow.com/a/51878887
tagged with: python
has title: Polynomial Regression won't work
upvote count: 4
possible better answer: http://stackoverflow.com/a/51878028
type: AnsweredQuestion
downvote count: 0
tagged with: regression
has answer: http://stackoverflow.com/a/51880793
type: Question
has body: I have a bivariate polynomial regression problem. I got this example off the internet but I can't seem to get it to work for my data. As shown in image the predictions made are dreadful and I can't work out why. I tried the same code but with a lot more training data but this gave even worse predictions. I assume this model automatically feature scales. All of the independent variables are significant so i cant imagine it needs elimination. poor predicitons: import numpy as np import matplotlib.pyplot as plt import pandas as pd from sklearn.linear_model import LinearRegression # Fitting Ploynomial regression to the dataset from sklearn.preprocessing import PolynomialFeatures #X is the independent variable (bivariate in this case) X = np.array([[1.00000000e-01, 7.56500000e+00], [1.00000000e-01, 8.11100000e+00], [1.00000000e-01,8.69700000e+00], [1.00000000e-01,9.32600000e+00], [1.00000000e-01,1.00000000e+01], [1.00000000e-01,1.07200000e+01], [1.00000000e-01,1.15000000e+01], [1.00000000e-01,1.23300000e+01], [1.00000000e-01,1.32200000e+01], [1.00000000e-01,1.41700000e+01], [1.00000000e-01,1.52000000e+01], [1.00000000e-01,1.63000000e+01], [1.00000000e-01,1.74800000e+01], [1.00000000e-01,1.87400000e+01], [1.00000000e-01,2.00900000e+01], [1.00000000e-01,2.15400000e+01], [1.00000000e-01,2.31000000e+01], [1.00000000e-01,2.47700000e+01], [1.00000000e-01,2.65600000e+01], [1.00000000e-01,2.84800000e+01], [1.00000000e-01,3.05400000e+01], [1.00000000e-01,3.27500000e+01], [1.00000000e-01 , 3.51100000e+01], [1.00000000e-01 , 3.76500000e+01], [1.00000000e-01 , 4.03700000e+01], [1.00000000e-01 , 4.32900000e+01], [1.00000000e-01 , 4.64200000e+01], [1.00000000e-01 , 4.97700000e+01], [1.00000000e-01 , 5.33700000e+01], [1.00000000e-01 , 5.72200000e+01], [1.00000000e-01 , 6.13600000e+01], [1.00000000e-01 , 6.57900000e+01], [1.00000000e-01 , 7.05500000e+01], [1.00000000e-01 , 7.56500000e+01], [1.00000000e-01 , 8.11100000e+01], [1.00000000e-01 , 8.69700000e+01], [1.00000000e-01 , 9.32600000…
score: 4
has answer: http://stackoverflow.com/a/51878028
has comment: http://stackoverflow.com/comment/90708490

http://stackoverflow.com/a/51885174
has body: Actually AES key should be either 16, 24 or 32 bytes long. You are using the hexdigest of a sha256 hash as a key, which results in a 64 bytes string. Instead do the following: password = (hashlib.sha256((passwordMd5 + prelogin["v1"])).hexdigest() + prelogin["v2"]) passwordKey = hashlib.sha256(password).digest()
has comment: http://stackoverflow.com/comment/90751121
upvote count: 2
has comment: http://stackoverflow.com/comment/90722218
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90730180
has comment: http://stackoverflow.com/comment/90752303
accepted answer of: http://stackoverflow.com/q/51884553
has comment: http://stackoverflow.com/comment/90747897
type: Answer
has comment: http://stackoverflow.com/comment/90730722
answers question: http://stackoverflow.com/q/51884553
has comment: http://stackoverflow.com/comment/90722256
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/90748829
has comment: http://stackoverflow.com/comment/90745267

http://stackoverflow.com/q/51870964
has answer: http://stackoverflow.com/a/51871281
score: 1
accepted answer: http://stackoverflow.com/a/51871041
has comment: http://stackoverflow.com/comment/90693425
favorite count: 0
has comment: http://stackoverflow.com/comment/90693337
possible better answer: http://stackoverflow.com/a/51871281
has comment: http://stackoverflow.com/comment/90693388
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
upvote count: 2
has body: I have dictionary like: {0:'I', 3: 'Mr.', 5: 'Nevrekar', 8: 'JK', 14: 'Soham', 15: 'Sharma', 4: 'Akshay'} I want to return it the 1st combination of consecutive keys(minimum 2). In above case it's (3,4,5). so it would return a list: ['Mr.', 'Akshay', 'Nevrekar']. How can I achieve this? My Attempt: name=[] count = 0 for k,g in name_list.items(): if count == 0: temp =None if k-1 == temp: name.append(g) count+= 1 temp = k which is giving output as: ['Akshay', 'Nevrekar', 'Sharma']
has comment: http://stackoverflow.com/comment/90693672
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51871041
has comment: http://stackoverflow.com/comment/90693305
has title: Fetching values with consecutive keys from dictionary
has comment: http://stackoverflow.com/comment/90693444
has comment: http://stackoverflow.com/comment/90693334
linked to: http://stackoverflow.com/q/2361945
answer count: 2

sqlite
tags question: http://stackoverflow.com/q/51915345
tags question: http://stackoverflow.com/q/51863562
tags question: http://stackoverflow.com/q/51846572
tags question: http://stackoverflow.com/q/51823419
tags question: http://stackoverflow.com/q/51905324
tags question: http://stackoverflow.com/q/51846525
tags question: http://stackoverflow.com/q/51913076
type: Tag
tags question: http://stackoverflow.com/q/51914610
tags question: http://stackoverflow.com/q/51802854
tags question: http://stackoverflow.com/q/51825348
tags question: http://stackoverflow.com/q/51854801
tags question: http://stackoverflow.com/q/51878358
tags question: http://stackoverflow.com/q/51834809
tags question: http://stackoverflow.com/q/51900158
tags question: http://stackoverflow.com/q/51840455
tags question: http://stackoverflow.com/q/51887405
tags question: http://stackoverflow.com/q/51833649
tags question: http://stackoverflow.com/q/51936705
tags question: http://stackoverflow.com/q/51871550
tags question: http://stackoverflow.com/q/51945281
tags question: http://stackoverflow.com/q/51875063
tags question: http://stackoverflow.com/q/51847455
tags question: http://stackoverflow.com/q/51798993
tag name: sqlite
tags question: http://stackoverflow.com/q/51883383

http://stackoverflow.com/comment/90650592
comment on: http://stackoverflow.com/q/51848532
has text: I just checked type by doing `type(df.Id)`. I get ` pandas.core.series.Series`
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51904037
answer count: 1
has title: Extracting data within complex functions/loops using lists/arrays
has body: I have this block of code that does several things; I loops through files I have saved in a folder that are labeled 1-100. These files are all forecast files for a specific month (example june 2016). What this function does is read all the files and goes to previous files to conduct forecasts. I store all the values by different months. I want to see the totals for how accurate predictions were for "one month ago", "two months ago", etc. I am able to do this with the code, however I am having trouble extracting the exact values that contribute to this total using arrays/lists. The portion that does not have to do with arrays or lists work, but I am wondering how I can extract these specific numbers. I would want to use the append numbers (the list) for graphing purposes later, that is why I am extracting it, the # with ?'s indicate the list portion that does not seem to work import pandas as pd import csv def nmonthaccuracy(basefilenumber, n): basefileread = pd.read_csv(str(basefilenumber)+'.csv', encoding='Latin-1') basefilevalue = basefileread.loc[basefileread['Customer'].str.contains('Customer A', na=False), 'Jun-16\nQty'] nmonthread = pd.read_csv(str(basefilenumber-n)+'.csv', encoding = 'Latin-1') nmonthvalue = nmonthread.loc[nmonthread['Customer'].str.contains('Customer A', na=False), 'Jun-16\nQty'] return int(nmonthvalue)/int(basefilevalue) N = 12 total_by_month = [0] * N total_by_month_list [] * N #???? for basefilenumber in range(24,36): for n in range(N): total_by_month[n] += nmonthaccuracy(basefilenumber, n) total_by_month_list[n].append(nmonthaccuracy(basefilenumber,n)) #???? onetotal = total_by_month[1] twototal = total_by_month[2] #etc
tagged with: python
type: AnsweredQuestion
type: Question
has answer: http://stackoverflow.com/a/51904204
accepted answer: http://stackoverflow.com/a/51904204
score: 0
tagged with: http://stackoverflow.com/tag/csv

http://stackoverflow.com/q/51933362
tagged with: django
type: Question
has comment: http://stackoverflow.com/comment/90818872
has comment: http://stackoverflow.com/comment/90817702
score: 0
has title: Django: How do i extract the email ID of users on the admin page
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90817320
answer count: 0
has comment: http://stackoverflow.com/comment/90818987
has body: How do I extract the email ID of users from the Users columns? I've managed to make sure that the name of the users are extracted through the Users table. class Project(models.Model): STATUS_CHOICE = ( ('Project Manager', 'Project Manager'), ('Technician', 'Technician'), ('Tester', 'Tester') ) STATUS_CHOICE_1 = ( ('Work Assigned', 'Work Assigned'), ('Work in Progress', 'Work in Progress'), ('Testing', 'Testing'), ('Completed', 'Completed') ) project_name = models.CharField(max_length=100) project_description = models.CharField(max_length=100) Admin_Name = models.CharField(max_length=100) Admin_Mail_ID = models.EmailField(max_length=50) Project_Manager_1 = models.ForeignKey(User, on_delete=models.CASCADE, related_name="Project_Manager_1_users") Project_Manager_1_Mail_ID = models.EmailField(max_length=50) Project_Manager_2 = models.CharField(max_length=50, blank=True, null=True) Project_Manager_2_Mail_ID = models.EmailField(max_length=50, blank=True, null=True) Technician_1 = models.ForeignKey(User, on_delete=models.CASCADE, related_name="Technician_1_users") Technician_1_Mail_ID = models.EmailField(max_length=50) Technician_2 = models.CharField(max_length=50, blank=True, null=True) Technician_2_Mail_ID = models.EmailField(max_length=50, blank=True, null=True) Technician_3 = models.CharField(max_length=50, blank=True, null=True) Technician_3_Mail_ID = models.EmailField(max_length=50, blank=True, null=True) Tester_1 = models.CharField(max_length=50, blank=True, null=True) Tester_1_Mail_ID = models.EmailField(max_length=50, default='Example@gmail.com') Additional_User_1 = models.CharField(max_length=50, blank=True, null=True) Additional_User_1_Type = models.CharField(max_length=18, choices=STATUS_CHOICE, blank=True, null=True) Additional_User_1_Mail_ID = models.EmailField(max_length=50, blank=True, null=True) Additional_User_2 = models.CharField(max_length=18, blank=True, null=True) Additional_User_2_Type = models.CharField(max_length=18, choices=STATUS_CHOICE, blank=Tr…
tagged with: mysql

http://stackoverflow.com/a/51864411
downvote count: 0
upvote count: 3
answers question: http://stackoverflow.com/q/51864326
has body: Brutish. This only works if the whole string is either 'Number' or 'NUMBER'. It will not replace those within a larger string. And of course, it is limited to just those two words. df.replace(['Number', 'NUMBER'], 'NewWord') More Brute Force If it wasn't obvious enough, this is far inferior to @coldspeed's answer import re df.applymap(lambda x: re.sub('number', 'NewWord', x, flags=re.IGNORECASE)) Or with a cue from @coldspeed's answer df.applymap(lambda x: re.sub('(?i)number', 'NewWord', x))
type: Answer
score: 3

http://stackoverflow.com/a/51952963
type: Answer
answers question: http://stackoverflow.com/q/51940557
score: 0
accepted answer of: http://stackoverflow.com/q/51940557
type: AcceptedAnswer
has body: I solved my problem using this code: db_search_username = session.query(User.username, User.password).filter_by(username=username).first() Is there any problem?

http://stackoverflow.com/a/51904425
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51903204
has body: You can use a dictionary comprehension with a custom function. We calculate the union of dictionary keys via set(dct_01) | set(dct_02) and iterate over them. dct_01 = {'a': 1, 'b': 2, 'c': 3} dct_02 = {'a': 2, 'b': 1, 'c': 3, 'd': 4} def calc_val(d1, d2, k): val1 = d1.get(k, 0) val2 = d2.get(k, 0) if val1 == val2: return val1 return val1 + val2 res = {k: calc_val(dct_01, dct_02, k) for k in set(dct_01) | set(dct_02)} print(res) {'b': 3, 'a': 3, 'c': 3, 'd': 4}

http://stackoverflow.com/a/51823391
type: Answer
has comment: http://stackoverflow.com/comment/90606500
has comment: http://stackoverflow.com/comment/90601897
has body: The part len(qa['answers'][0]['text']) in your code throws the error because len() expects a string. You can verify yourself by typing len(3) in a python interpreter. Check your data whether the 'text' key in the array in qa['answers'] contains integer values somewhere. Or modify the piece of code if you actually want integers there. I ran the portion from the original code and data you provided and it parsed w/o throwing errors. Since you mention you use a 'similar' dataset I assume you or someone else modified the contents... (It would be helpful if you provided the original your dataset and your code)
accepted answer of: http://stackoverflow.com/q/51822269
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51822269

http://stackoverflow.com/comment/90803366
type: Comment
has text: @ani no, definitely - Django is not that dumb and the problem is common to all projects, so there are of course much better solutions, cf my answer.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51926025

http://stackoverflow.com/a/51835582
has comment: http://stackoverflow.com/comment/90644850
has comment: http://stackoverflow.com/comment/90625114
has comment: http://stackoverflow.com/comment/90626207
answers question: http://stackoverflow.com/q/51835552
has comment: http://stackoverflow.com/comment/90625443
has comment: http://stackoverflow.com/comment/90626273
has comment: http://stackoverflow.com/comment/90681984
has comment: http://stackoverflow.com/comment/90625637
has comment: http://stackoverflow.com/comment/90658912
downvote count: 0
has comment: http://stackoverflow.com/comment/90624913
has comment: http://stackoverflow.com/comment/90624848
type: Answer
has comment: http://stackoverflow.com/comment/90645040
has body: You can convert first 20 columns names to list: df_final.groupby(by=df_final.columns[:20].tolist(),as_index=False).sum()
has comment: http://stackoverflow.com/comment/90625535
score: 2
has comment: http://stackoverflow.com/comment/90682661
upvote count: 2

http://stackoverflow.com/a/51859020
answers question: http://stackoverflow.com/q/51858067
upvote count: 23
has comment: http://stackoverflow.com/comment/90671213
has body: Try converting it to an array first: test_tensor = torch.Tensor(test.values)
has comment: http://stackoverflow.com/comment/90718412
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/51858067
score: 23

machine-learning
tags question: http://stackoverflow.com/q/51816714
tags question: http://stackoverflow.com/q/51815777
tags question: http://stackoverflow.com/q/51888996
tags question: http://stackoverflow.com/q/51906274
tags question: http://stackoverflow.com/q/51927474
tags question: http://stackoverflow.com/q/51885739
tags question: http://stackoverflow.com/q/51928856
tags question: http://stackoverflow.com/q/51953917
tags question: http://stackoverflow.com/q/51896013
tags question: http://stackoverflow.com/q/51847306
tags question: http://stackoverflow.com/q/51833310
tags question: http://stackoverflow.com/q/51814619
tags question: http://stackoverflow.com/q/51903256
tags question: http://stackoverflow.com/q/51903086
tags question: http://stackoverflow.com/q/51936644
tags question: http://stackoverflow.com/q/51905524
tags question: http://stackoverflow.com/q/51913547
tags question: http://stackoverflow.com/q/51868299
tags question: http://stackoverflow.com/q/51841506
tags question: http://stackoverflow.com/q/51830558
tags question: http://stackoverflow.com/q/51858970
tags question: http://stackoverflow.com/q/51838518
tags question: http://stackoverflow.com/q/51915188
tags question: http://stackoverflow.com/q/51935097
tags question: http://stackoverflow.com/q/51883058
tag name: machine-learning
tags question: http://stackoverflow.com/q/51842242
tags question: http://stackoverflow.com/q/51838201
tags question: http://stackoverflow.com/q/51816639
tags question: http://stackoverflow.com/q/51837437
tags question: http://stackoverflow.com/q/51834353
tags question: http://stackoverflow.com/q/51809132
tags question: http://stackoverflow.com/q/51851802
tags question: http://stackoverflow.com/q/51869694
tags question: http://stackoverflow.com/q/51904818
tags question: http://stackoverflow.com/q/51911160
tags question: http://stackoverflow.com/q/51890883
tags question: http://stackoverflow.com/q/51911751
tags question: http://stackoverflow.com/q/51848429
tags question: http://stackoverflow.com/q/51804923
tags question: http://stackoverflow.com/q/51847654
type: Tag
tags question: http://stackoverflow.com/q/51921193
tags question: http://stackoverflow.com/q/51815297
tags question: http://stackoverflow.com/q/51902011
tags question: http://stackoverflow.com/q/51840826
tags question: http://stackoverflow.com/q/51887958
tags question: http://stackoverflow.com/q/51815299
tags question: http://stackoverflow.com/q/51912598
tags question: http://stackoverflow.com/q/51825576
tags question: http://stackoverflow.com/q/51915835
tags question: http://stackoverflow.com/q/51911416
tags question: http://stackoverflow.com/q/51853583
tags question: http://stackoverflow.com/q/51931607
tags question: http://stackoverflow.com/q/51884707
tags question: http://stackoverflow.com/q/51827602
tags question: http://stackoverflow.com/q/51855627
tags question: http://stackoverflow.com/q/51879667
tags question: http://stackoverflow.com/q/51816305
tags question: http://stackoverflow.com/q/51923048
tags question: http://stackoverflow.com/q/51937185
tags question: http://stackoverflow.com/q/51815699
tags question: http://stackoverflow.com/q/51884439
tags question: http://stackoverflow.com/q/51889255
tags question: http://stackoverflow.com/q/51874695
tags question: http://stackoverflow.com/q/51855092
tags question: http://stackoverflow.com/q/51829810
tags question: http://stackoverflow.com/q/51948262
tags question: http://stackoverflow.com/q/51812001
tags question: http://stackoverflow.com/q/51893642
tags question: http://stackoverflow.com/q/51827349
tags question: http://stackoverflow.com/q/51835124
tags question: http://stackoverflow.com/q/51815890
tags question: http://stackoverflow.com/q/51862411
tags question: http://stackoverflow.com/q/51799234
tags question: http://stackoverflow.com/q/51853429
tags question: http://stackoverflow.com/q/51851365
tags question: http://stackoverflow.com/q/51954691
tags question: http://stackoverflow.com/q/51841810
tags question: http://stackoverflow.com/q/51907340

http://stackoverflow.com/q/51805413
tagged with: dictionary
has comment: http://stackoverflow.com/comment/90566589
answer count: 3
accepted answer: http://stackoverflow.com/a/51805451
has answer: http://stackoverflow.com/a/51805469
type: AnsweredQuestion
downvote count: 0
has title: Python Programming - to modify a list item in a dictionary
type: Question
has comment: http://stackoverflow.com/comment/90566543
has comment: http://stackoverflow.com/comment/90566518
tagged with: python
score: 1
has comment: http://stackoverflow.com/comment/90566526
possible better answer: http://stackoverflow.com/a/51805434
favorite count: 0
has answer: http://stackoverflow.com/a/51805434
has body: Question: # Write a program to modify the email addresses in the records dictionary to reflect this change records = {57394: ['Suresh Datta', 'suresh@example.com'], 48539: ['ColetteBrowning', 'colette@example.com'], 58302: ['Skye Homsi','skye@example.com'], 48502: ['Hiroto Yamaguchi', 'hiroto@example.com'], 48291: ['Tobias Ledford', 'tobias@example.com'], 48293: ['Jin Xu', 'jin@example.com'], 23945: ['Joana Dias', 'joana@example.com'], 85823: ['Alton Derosa', 'alton@example.com']} I have iterated through the dictionary and created a new list with the values and split the email at @ and was able to change the the email from .com to .org. My approach was to join the changed email and change the values of the dictionary. However, I keep on getting a TypeError: sequence item 0: expected str instance, list found my code : lst2 = [] for value in records.values(): lst2.append(value[1].split('@')) for items in lst2: items[1] = 'examples.org' for items in lst2: ','.join(lst2)
has answer: http://stackoverflow.com/a/51805451
upvote count: 1

http://stackoverflow.com/a/51992486
upvote count: 1
has body: Do you want the points of all True elements of the mask, or do you just want a skeleton? If the former.. import skimage as ski from skimage import io import numpy as np mask = ski.io.imread('./mask.png')[:,:,0]/255 mask = mask.astype('bool') s0,s1 = mask.shape # dimensions of mask a0,a1 = np.arange(s0),np.arange(s1) # make two 1d coordinate arrays coords = np.array(np.meshgrid(a0,a1)).T # cartesian product into a coordinate matrix coords = coords[mask] # mask out the points of interest If the latter, you can get the start and end points (from left to right) of the object in the mask in a fast way with something like start_mat = np.stack((np.roll(mask,1,axis=1),mask),-1) start_mask = np.fromiter(map(lambda p: np.alltrue(p==np.array([False,True])),start_mat[mask]),dtype=bool) starts = coords[start_mask] end_mat = np.stack((np.roll(mask,-1,axis=1),mask),-1) end_mask = np.fromiter(map(lambda p: np.alltrue(p==np.array([False,True])),end_mat[mask]),dtype=bool) ends = coords[end_mask] This will give you a rough outline of the object. Outline points will be missing anywhere that the slope of the figure is 0. You may have to think of a vertical difference scheme for those areas. The same idea would work with np.roll(...,axis=0). You could just concatenate the unique points from rolling over rows to the points from rolling over columns to get the full outline. Averaging the correct pairs to get the skeleton isn't so easy. Here's a resultant outline. You can definitely make this faster than 0.4s:
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/51805471

http://stackoverflow.com/q/51945949
type: Question
has comment: http://stackoverflow.com/comment/90841322
has answer: http://stackoverflow.com/a/70226710
has comment: http://stackoverflow.com/comment/90841979
has comment: http://stackoverflow.com/comment/90841290
downvote count: 0
has answer: http://stackoverflow.com/a/51946355
answer count: 3
has comment: http://stackoverflow.com/comment/90841925
tagged with: pandas
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/90841452
has answer: http://stackoverflow.com/a/51946197
has title: Selecting every nth observation by groups pandas
upvote count: 1
has comment: http://stackoverflow.com/comment/90841760
has body: I have some code which generates a dataframe. I want to be able to select every nth based on a 'group' classification as in df1 and df2. import pandas as pd data = [['Orange',11], ['Orange',12], ['Orange',13], ['Orange',14] ['Orange',15], ['Orange',16], ['Orange',17], ['Orange',18], ['StrawBerry',22], ['StrawBerry',23], ['StrawBerry',24], ['StrawBerry',25], ['StrawBerry',26], ['StrawBerry',27]] df = pd.DataFrame(data,columns=['Fruit', 'Score']) df #Here I start from the 1st row and then move to the fourth and then #and so forth by Fruit. Output1data = [['Orange',11], ['Orange',14], ['Orange',17], ['StrawBerry',22], ['StrawBerry',25]] df1 = pd.DataFrame(Output1data,columns=['Fruit','Score']) df1 #Here I start from the second row onwards and then move to the fifth and #then eighth and so forth by Fruit Output2data = [['Orange',12], ['Orange',15], ['Orange',18], ['StrawBerry',23], ['StrawBerry',26]] df2 = pd.DataFrame(Output2data,columns=['Fruit','Score']) df2 Please let me know if there is a way to do this using the group classification because I need to select every nth row for a given starting point ? Thanks a lot in advance. Really appreciate this.
possible better answer: http://stackoverflow.com/a/51946197
accepted answer: http://stackoverflow.com/a/51946355
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90842098
score: 1

http://stackoverflow.com/a/51810690
has comment: http://stackoverflow.com/comment/90576539
answers question: http://stackoverflow.com/q/51807763
has body: There's a SOUNDEX algorithm that bins together similarly sounding English words. Used when the telephone sound quality was not as good as today. Probably still used somewhere today.
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/90576602

http://stackoverflow.com/comment/90727578
has text: Can a SerializerMethodField() be used to fetch lawyer from the email passed?
comment on: http://stackoverflow.com/a/51876264
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/90603096
has text: @teaglebuilt - Yeh the stripe API went through a pretty major change in the last few weeks so this is what is causing the disparity. Their docs are pretty comprehensive so to have it omitted would be very unusual. I guess my answer can be accepted as correct now? :)
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51809916

http://stackoverflow.com/q/51931938
has comment: http://stackoverflow.com/comment/90815048
type: Question
answer count: 1
has comment: http://stackoverflow.com/comment/90815348
has body: There's only a single line of code, and I won't bother you with the data as it is quite large. I have a list of all requirements for some software in allRequirements and a second list of those requirements for which a test case exists in requirementWithCoverage. I want to generate a list of those requirements with no test case coverage. Lots of websites and S.O questions give the answer as this : notCovered = list(set(allRequirements) - set(requirementWithCoverage)) However: len(set(allRequirements)) is 779 and len(set(requirementWithCoverage)) is 201, BUT len(set(notCovered)) is 650 Obviously, I am making a very basic mistake - but for the life of me I can't see it. What am I doing wrongly?
has answer: http://stackoverflow.com/a/51933155
accepted answer: http://stackoverflow.com/a/51933155
has title: Python find elements of list 1 which are not in list 2 - simple code not working
score: 0
linked to: http://stackoverflow.com/q/3462143
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90815452
tagged with: list
tagged with: comparison

http://stackoverflow.com/comment/90614092
comment on: http://stackoverflow.com/a/51829618
score: 0
type: AnswerComment
type: Comment
has text: @NChauhan No it doesn't. "Your capture group is your entire expression, so you don't really need a capture group at all; just take the parentheses off the patterns, and use the whole `group()` rather than `group(1)`."

http://stackoverflow.com/a/51824346
accepted answer of: http://stackoverflow.com/q/51823023
type: Answer
answers question: http://stackoverflow.com/q/51823023
score: 2
upvote count: 2
has body: If the aim is to add another column to the data, the number of rows should stay unchanged. In the code below I added one further column to the data (consisting of number 50 to 150). import numpy as np import matplotlib.pyplot as plt lst_keys_ordered = [] dict_quotes = {} def main(): rows = ['bid 5','bid 4','bid 3','bid 2','bid 1','ask 1','ask 2','ask 3','ask 4','ask 5'] colors = ['red','crimson','indianred','lightcoral','lightsalmon','greenyellow','lawngreen','limegreen','green','darkgreen'] value_increment = 100 size_ratio = 50 """ this config works """ price = [55,55.5,55.2,55.9,60.3,60.3] price2 = [55.5,56,55.7,56.5,60.8,61,9] data = [[100,200,100,200,100,50],[20,200,50,100,50,60],[100,100,50,50,300,70],[400,50,100,50,50,80],[80,120,40,60,100,90]] data2 = [[100,200,100,200,100,110],[20,200,50,100,50,120],[100,100,50,50,300,130],[400,50,100,50,50,140],[80,120,40,60,100,150]] columns = ('09:30:01', '09:30:02', '09:30:03', '09:30:04', '09:30:05', '09:30:06') for i,row in enumerate(data): for j,item in enumerate(row): data[i][j] = float(data[i][j])/size_ratio for i,row in enumerate(data2): for j,item in enumerate(row): data2[i][j] = float(data2[i][j])/size_ratio n_rows = len(data) index = np.arange(len(columns)) + 0.3 bar_width = 0.4 # Initialize the vertical-offset for the stacked bar chart. y_offset = np.zeros(len(columns)) # Plot bars and create text labels for the table cell_text = [] for row in range(n_rows): print n_rows , index, data[row], bar_width, colors[row] plt.bar(index, data[row], bar_width, bottom=y_offset, color=colors[row],edgecolor="black") y_offset = y_offset + data[row] cell_text.append(['{0}'.format(x * size_ratio) for x in y_offset]) for row in range(n_rows): plt.bar(index, data2[row], bar_width, bottom=y_offset, color=colors[row + n_rows],edgecolor="black") y_offset = y_offset + data2[row] cell_text.append(['{0}'.format(x * size_ratio) for x in y_offset]) # Reverse colors and text labels to display the last value at the top. colors = colors[::-…
has comment: http://stackoverflow.com/comment/90603357
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/51951533
tagged with: python
answer count: 4
tagged with: node.js
possible better answer: http://stackoverflow.com/a/51951623
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51951614
has answer: http://stackoverflow.com/a/51951623
type: Question
has answer: http://stackoverflow.com/a/51962894
tagged with: javascript
has answer: http://stackoverflow.com/a/51951717
has comment: http://stackoverflow.com/comment/90853392
has body: I am transitioning a project from Python to Node.js - everything has been going fine up until this point. I have a function that is supposed to convert the amount of EXP someone has into a level. I have attempted to rewrite the working function from Python into Node.js but the functions return completely different answers and I can't figure out why. Python: def calculateLevel(exp): if exp &lt; 83: return 1 else: calcExp = 0 for level in range(1, 1000): diff = int(level + 300 * math.pow(2, float(level)/7)) calcExp += diff if exp &lt; calcExp//4: break return level Node.js: const _ = require("underscore"); // ... function calculateLevel(exp) { return new Promise((resolve, reject) =&gt; { if (exp &lt; 83) resolve(1); else { var calcExp = 0; for (var i in _.range(1, 1000)) { calcExp += parseInt(i + 300 * Math.pow(2, i/7)); if (exp &lt; Math.floor(calcExp/4)) { resolve(i); break; } } } }); } For example, calculateLevel(123456) in Python returns 51 (the correct answer), but await calculateLevel(123456); in Node.js returns 15 (the incorrect answer). Clearly there is something wrong in the Node.js version, but I can't figure out what it is. Any help is greatly appreciated. Thanks in advance.
has comment: http://stackoverflow.com/comment/90853516
score: 0
has title: Same function in Python and Node.js returns different results
has answer: http://stackoverflow.com/a/51951614

http://stackoverflow.com/comment/90608519
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51824521
has text: Still pandas could do better by guessing since the majority should win. But this is off topic in this context.

http://stackoverflow.com/a/51846978
score: 1
answers question: http://stackoverflow.com/q/51845017
has body: So it doesn't appear to be actually possible to do this inside the pandas.read_table() function. Below is posted the actual solution I ended up using to fix the problem: import re def get_headers(file, headerline, regexstring, exclude): # Get string of selected headerline with file.open() as f: for i, line in enumerate(f): if i == headerline-1: headerstring = line elif i &gt; headerline-1: break # Parse headerstring reglist = re.split(regexstring, headerstring) # Filter entries in reglist #filter out blank strs filteredlist = list(filter(None, reglist)) #filter out items in exclude list headerslist = [] if exclude: for entry in filteredlist: if not entry in exclude: headerslist.append(entry) return headerslist get_headers(filename, 3, r'(?:" ")|["\)\(]', ['\n']) Code explanation: get_headers(): Arguments, file is a file object that contains the header. headerline is the line number (starting at 1) that the header names exist. regexstring is the pattern that will be fed into re.split(). Highly recommended that you prepend a r to the regex pattern. exclude is a list of miscellaneous strings that you want to be removed from the headerlist. The regex pattern I used: First up we have the pipe (|) symbol. This was done to separate both the "normal" split method (which is the " ") and the other stuff that needs to be rid of (namely the parenthesis). Starting with the first group: (?:" "). We have the (...) since we want to match those characters in order. The " " is what we want to match as the stuff to split around. The ?: basically says to not capture the contents of the group. This is important/useful as otherwise re.split() will keep any groups as a separate item. See re.split() in documentation. The second group is simply the other characters. Without them, the first and last items would be '("Time Step' and 'flow-time)\n'. Note that this causes \n to be treated as a separate entry to the list. This is why we use the exclude argument to fix that up after the fact.
downvote count: 0
type: Answer
upvote count: 1

http://stackoverflow.com/a/51907040
has comment: http://stackoverflow.com/comment/90765219
type: Answer
downvote count: 1
has comment: http://stackoverflow.com/comment/90764457
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51906909
score: 0
has body: Editing the answer as requsted: Source: How do you import a file in python with spaces in the name?. Importing single function from a module with spaces in name without using importlib is simply impossible, since your only weapon here is __import__. Your only option is to import the whole module and only keep functions you like. But it still imports the whole module. Important notice Getting rid of spaces and other non-alphanumeric symbols from module names is strongly recommended. Example File 1.py def foo(): print("Foonction.") def spam(): print("Get out!") main.py globals()["foo"] = getattr(__import__("File 1"),"foo")
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51906909

http://stackoverflow.com/comment/90599024
score: 0
has text: can you also poste the error message ?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51822269

http://stackoverflow.com/a/51861925
type: AcceptedAnswer
type: Answer
has body: You have: runProg.StartInfo.Arguments = @"/c py " +botFilePath +" --config_path=" + configFilePath + " --config_index=username_" + index.ToString(); /C carries out the command and then terminates /K carries out the command but remains Try using /K instead: runProg.StartInfo.Arguments = @"/K py " +botFilePath +" --config_path=" + configFilePath + " --config_index=username_" + index.ToString();
accepted answer of: http://stackoverflow.com/q/51861821
answers question: http://stackoverflow.com/q/51861821
score: 0

http://stackoverflow.com/q/51944378
has answer: http://stackoverflow.com/a/69927282
favorite count: 0
tagged with: data-visualization
has body: I'm trying to plot some values respect to the time using a line plot with Bokeh. My issue came when I tried to add a hover that shows the concrete value at some point of the plot. I want to show a value, time data (it works fine), but I think a yyyy-mm-dd is imprecise for my purpose, so I want to redefine that pattern to add hours and minutes. My code is something like that (you can download as a notebook here): from datetime import datetime, timedelta from bokeh.plotting import figure, show from bokeh.models import HoverTool import pandas as pd import numpy as np today = datetime.today() date_range = pd.date_range(today, today + timedelta(days=1), freq=timedelta(minutes=15)) values = np.random.randint(-10, 10, size=len(date_range)).cumsum() data = pd.DataFrame({'date': date_range, 'value': values}) hover = HoverTool(tooltips=[('value', '@value'), ('date', '@date{%F}')], formatters={'date': 'datetime'}) plt = figure(x_axis_type='datetime', tools=[hover]) plt.line(x='date', y='value', source=data) show(plt) The output is like that: So my question is as follows: Can anyone explain me how to modify the datetime format pattern on the hover?
has answer: http://stackoverflow.com/a/51944537
upvote count: 1
tagged with: python
tagged with: plot
tagged with: hover
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51944537
has title: How can I set custom datetime pattern on Bokeh hover formatter?
score: 1
tagged with: bokeh
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/69927282
downvote count: 0

http://stackoverflow.com/q/51897667
tagged with: python
has comment: http://stackoverflow.com/comment/90746569
tagged with: vim
tagged with: editor
upvote count: 3
has comment: http://stackoverflow.com/comment/90749346
downvote count: 2
has comment: http://stackoverflow.com/comment/90767430
has body: I'm struggling to find on the internet how editors like vim, nano or emacs display its content. By using the subprocess module of python, I have found there is nothing written to stdout or stderr by vim. So how does vim display its content? Also, is it even possible to capture the output by an editor like vim with a python script? (I'm only asking about the concept, not to write the program for me.) EDIT: To give more context about my question, I'm trying to operate vim by using python3.7's subprocess module, meaning I have read access to STDOUT and STDERR streams and write access to STDIN stream bound to vim. vim is just an example here, it could be programs like nano or less or emacs etc.
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90746916
has title: How does vim display its content
has comment: http://stackoverflow.com/comment/90746939
answer count: 0
score: 1
has comment: http://stackoverflow.com/comment/90746309
favorite count: 0
has comment: http://stackoverflow.com/comment/90749572
has comment: http://stackoverflow.com/comment/90749503
tagged with: terminal
type: Question
has comment: http://stackoverflow.com/comment/90746451

http://stackoverflow.com/q/51946944
has answer: http://stackoverflow.com/a/51947240
type: Question
answer count: 1
has title: Pandas - aggregate over inconsistent values types (string vs list)
tagged with: pandas-groupby
tagged with: pandas
has comment: http://stackoverflow.com/comment/90844157
upvote count: 1
has body: Given the following DataFrame, I try to aggregate over columns 'A' and 'C'. for 'A', count unique appearances of the strings, and for 'C', sum the values. Problem arises when some of the samples in 'A' are actually lists of those strings. Here's a simplified example: df = pd.DataFrame({'ID': [1, 1, 1, 1, 1, 2, 2, 2], 'A' : ['a', 'a', 'a', 'b', ['b', 'c', 'd'], 'a', 'a', ['a', 'b', 'c']], 'C' : [1, 2, 15, 5, 13, 6, 7, 1]}) df Out[100]: ID A C 0 1 a 1 1 1 a 2 2 1 a 15 3 1 b 5 4 1 [b, c, d] 13 5 2 a 6 6 2 a 7 7 2 [a, b, c] 1 aggs = {'A' : lambda x: x.nunique(dropna=True), 'C' : 'sum'} # This will result an error: TypeError: unhashable type: 'list' agg_df = df.groupby('ID').agg(aggs) I'd like the following output: print(agg_df) A C ID 1 4 36 2 3 14 Which resulted because for 'ID' = 1 we had 'a', 'b', 'c' and 'd' and for 'ID' = 2, we had 'a', 'b', 'c'.
favorite count: 0
has comment: http://stackoverflow.com/comment/90844105
has comment: http://stackoverflow.com/comment/90843592
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90843750
tagged with: python
linked to: http://stackoverflow.com/q/51751138
has comment: http://stackoverflow.com/comment/90843900
downvote count: 0
score: 1
tagged with: dataframe

http://stackoverflow.com/a/51812345
downvote count: 0
answers question: http://stackoverflow.com/q/51812323
has body: In python 3.6+ you can do it by prefixing the string with f, and putting the variable in curly brackets. For earlier python version there have been various ways of doing it, look up string formatting message = f"The slope is {m}" plt.text(message) (by the way, gradient is usually called slope when referring to single variable linear equation)
type: Answer
score: 3
upvote count: 3

http://stackoverflow.com/q/51952446
score: 3
upvote count: 3
type: Question
accepted answer: http://stackoverflow.com/a/51953106
answer count: 2
has answer: http://stackoverflow.com/a/51952635
downvote count: 0
has title: Pandas, how to take the pd.Dataframe as a argument in functions
tagged with: scikit-learn
possible better answer: http://stackoverflow.com/a/51952635
tagged with: pandas
favorite count: 0
has answer: http://stackoverflow.com/a/51953106
has body: Actually, to simplify the code, instead of writing two similar part codes, I decide to use a function with Dataframe as arguments. Like following: from sklearn.neighbors import KNeighborsRegressor from sklearn.metrics import mean_squared_error train_one = split_one test_one = split_two train_two = split_two test_two = split_one def train_predict(train_arg, predict_arg): knn = KNeighborsRegressor() knn.fit(train_arg['accommodates'], train_arg['price']) predict = knn.predict(predict_arg['accommodates']) rmse = numpy.sqrt(mean_squared_error(predict_arg['price'], predict)) return rmse iteration_one_rmse = train_predict(train_one, test_one) iteration_two_rmse = train_predict(train_two, test_two) avg_rmse = numpy.mean(iteration_one_rmse, iteration_two_rmse) Maybe the arguments in the function definition block are inappropriate. However, I can not figure it out. Thanks for any hints. With the error notice like that: ValueErrorTraceback (most recent call last) &lt;ipython-input-1-f3f78fcf6758&gt; in &lt;module&gt;() 14 return rmse 15 ---&gt; 16 iteration_one_rmse = train_predict(train_one, test_one) 17 iteration_two_rmse = train_predict(train_two, test_two) 18 &lt;ipython-input-1-f3f78fcf6758&gt; in train_predict(train_arg, predict_arg) 9 def train_predict(train_arg, predict_arg): 10 knn = KNeighborsRegressor() ---&gt; 11 knn.fit(train_arg['accommodates'], train_arg['price']) 12 predict = knn.predict(predict_arg['accommodates']) 13 rmse = numpy.sqrt(mean_squared_error(predict_arg['price'], predict)) /dataquest/system/env/python3/lib/python3.4/site-packages/sklearn/neighbors/base.py in fit(self, X, y) 739 """ 740 if not isinstance(X, (KDTree, BallTree)): --&gt; 741 X, y = check_X_y(X, y, "csr", multi_output=True) 742 self._y = y 743 return self._fit(X) /dataquest/system/env/python3/lib/python3.4/site-packages/sklearn/utils/validation.py in check_X_y(X, y, accept_sparse, dtype, order, copy, force_all_finite, ensure_2d, allow_nd, multi_output, ensure_min_samples, ensure_min_fe…
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/90679566
type: AnswerComment
type: Comment
has text: On what Ansible version does this code run correctly?
comment on: http://stackoverflow.com/a/51862404
score: 0

http://stackoverflow.com/comment/90810906
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51929592
has text: @brunodesthuilliers Added a short clearification and a link with further usage and documentation.
score: 0

http://stackoverflow.com/comment/90731352
has text: The median is around 3,5 days or so. So yes. I'd like to see the distribution around the y- axis. i know that i will get only one boxplot, but the distrbution shown cant be real.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51876290
score: 0

http://stackoverflow.com/q/51935063
tagged with: python
has body: I have a data frame like the following: test = pd.DataFrame({'ID':[4, 5, 6, 6, 6, 7, 7, 7], 'val1':['one', 'one', 'two', 'two', 'three', np.nan, 'seven', 'seven'], 'val2':['hi', 'bye', 'hola', 'hola', 'hola', 'ciao', 'ciao', 'namaste'], 'val3':[3, 3, 4, np.nan, 4, 5, 5, 6]}) test ID val1 val2 val3 0 4 one hi 3.0 1 5 one bye 3.0 2 6 two hola 4.0 3 6 two hola NaN 4 6 three hola 4.0 5 7 NaN ciao 5.0 6 7 seven ciao 5.0 7 7 seven namaste 6.0 Each ID has some measured values, with some IDs being done in triplicate. If there is any disagreement between the replicate IDs for a specific column, then I want the new data frame to have an NaN for that value. If there is an NaN already present for one value (consider it not measured), but the other two for that replicate sample match, then I want that agreement to be present in the final data frame. If there is disagreement between the two where values are present, then NaN. I was thinking of using pandas groupby then aggregate for this, but I wasn't sure of how to do the logic for the aggregate function. Essentially the output I am looking for is like: pd.DataFrame({'ID':[4, 5, 6, 7], 'val1':['one', 'one', np.nan, 'seven'], 'val2':['hi', 'bye', 'hola', np.nan], 'val3':[3, 3, 4, np.nan]}) ID val1 val2 val3 0 4 one hi 3.0 1 5 one bye 3.0 2 6 NaN hola 4.0 3 7 seven NaN NaN Could you suggest how to do this? Thanks! Jack
type: Question
score: 9
answer count: 2
upvote count: 9
has title: Group by and aggregate columns but create NaN if values do not match
downvote count: 0
has answer: http://stackoverflow.com/a/51935139
tagged with: pandas
has answer: http://stackoverflow.com/a/51935149
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion

http://stackoverflow.com/comment/90707386
type: QuestionComment
comment on: http://stackoverflow.com/q/51877700
has text: @roganjosh Honestly, I don't think my code is bad (i.e. infinite loop or something like this). Maybe a drawback is that I concatenate pandas dataframes in a loop which is not a good idea... : https://stackoverflow.com/questions/36489576/why-does-concatenation-of-dataframes-get-exponentially-slower
score: 0
type: Comment

http://stackoverflow.com/comment/102181716
has text: @zixuan The name of your sheet. Make it whatever you want.
type: Comment
comment on: http://stackoverflow.com/a/51828911
type: AnswerComment
score: 0

http://stackoverflow.com/a/51826027
answers question: http://stackoverflow.com/q/51809979
downvote count: 0
type: Answer
has body: At least for importing the .edf-file into a pandas DF, you can use the following package by Niklas Wilming: https://github.com/nwilming/pyedfread/tree/master/pyedfread This should already take care of saccades and fixations - have a look at the readme. Once they're in the data frame, you can apply whatever analysis you want to it.
score: 3
upvote count: 3

http://stackoverflow.com/a/51951549
type: Answer
has comment: http://stackoverflow.com/comment/90856666
upvote count: 0
has comment: http://stackoverflow.com/comment/90864363
downvote count: 2
answers question: http://stackoverflow.com/q/51951429
score: -2
has comment: http://stackoverflow.com/comment/90863974
has body: Usually you want to overwrite the value rather than throwing an error. If you want to have a dictionary that protects itself from overwriting values then create a new clase that wrap the Dictionary class and throw an error if any value is overwritten.

http://stackoverflow.com/comment/90629365
comment on: http://stackoverflow.com/a/51837151
score: 0
type: Comment
has text: rows = soup.find_all('tr') is this ryt to find all tr tag ?
type: AnswerComment

http://stackoverflow.com/comment/90610082
has text: What you're doing is telling Python to interpret its standard input as the main script, and then passing the contents of `folder_a/file_a` as that input.
type: Comment
comment on: http://stackoverflow.com/q/51827824
score: 0
type: QuestionComment

http://stackoverflow.com/a/51846520
type: Answer
answers question: http://stackoverflow.com/q/51846274
has comment: http://stackoverflow.com/comment/90653658
has comment: http://stackoverflow.com/comment/90675342
has body: You can try doing easy_install pip==18.0
score: 0

http://stackoverflow.com/a/51999973
answers question: http://stackoverflow.com/q/51856575
type: Answer
has body: You can try to use blur filter here You can try to use Dilate after Erode.
score: 0

http://stackoverflow.com/comment/90736263
has text: consider we start with 1 easy task and 2 two hard tasks, the easy one gets released first and splits into 50 new easy tasks, but we don't reach them before we're done with the remaining 2 hard tasks (no matter how many threads we have).
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51883938
type: Comment

http://stackoverflow.com/comment/90711962
comment on: http://stackoverflow.com/q/51880196
type: Comment
type: QuestionComment
score: 1
has text: @PoojaRastogi Read the link I've shared. It explains this behavior

http://stackoverflow.com/comment/90831975
type: Comment
type: QuestionComment
has text: What have you tried? What happened?
comment on: http://stackoverflow.com/q/51941135
score: 0

http://stackoverflow.com/q/51908141
has answer: http://stackoverflow.com/a/51908244
downvote count: 0
has title: Print floating point number with a set number of significant digits (non-scientific)
tagged with: python
has body: I want to print floating point numbers with a set number of significant (i.e. non-zero) digits, but avoid the scientific notation (e). So, for example, the number 0.000000002343245345 should be printed as 0.000000002343 (and not 2.343e-09) I know how to define number of significant digits with an e notation: &gt;&gt;&gt;print('{:.3e}'.format(0.000000002343245345)) 2.343e-09 And how to print a set number of decimal places without e-notation: &gt;&gt;&gt;print('{:.12f}'.format(0.000000002343245345)) 0.000000002343 but not how to combine the two. is there any simple way of doing so?
favorite count: 0
upvote count: 3
has answer: http://stackoverflow.com/a/51908245
type: Question
type: AnsweredQuestion
score: 3
tagged with: format
possible better answer: http://stackoverflow.com/a/51908244
answer count: 2
accepted answer: http://stackoverflow.com/a/51908245

http://stackoverflow.com/comment/90614282
type: Comment
comment on: http://stackoverflow.com/q/51829622
has text: Take a look at [QGroupBox](http://doc.qt.io/qt-5/qgroupbox.html). I believe it is exactly what you are looking for.
score: 0
type: QuestionComment

http://stackoverflow.com/a/51864871
score: 1
answers question: http://stackoverflow.com/q/51864792
has body: You're only checking until the first line that doesn't match: searchphrase = raw_input("Please provide Your user ID:") searchfile = open("Librarybooks.txt","r") for line in searchfile: if searchphrase in line: # &lt;== if it matches, then print and go to next line.. print line else: # &lt;== if id doesn't match, exit the for loop print "User not identified or invalid entry, please restart program" break try something like this instead: for line in searchfile: if searchphrase in line: # &lt;== if matches, then print the line and break out of the for loop print line break else: # &lt;== if the for loop finished without breaking, then the searchphrase was not in the file print "User not identified or invalid entry, please restart program" this uses the else clause on the for-loop. A simple way to debug these kinds of issues is to print out interesting variables before (and after) something changes. E.g.: for line in searchfile: print "LINE: [%s]" % line # I put it inside [] to check if there are any spaces at the end. that way you can verify that your assumptions are correct. Your IDE might have a debugger that lets you set breakpoints and inspect variables in a pretty visual user interface.
accepted answer of: http://stackoverflow.com/q/51864792
type: AcceptedAnswer
upvote count: 1
type: Answer
downvote count: 0

http://stackoverflow.com/comment/90666022
has text: Thank you very much for the answer! This seems very promising, but I'll have to wait until I get home. To pick your brain a bit more: I've seen the `TimeDistributed` wrapper being used for the Dense layer. How does that differ from wrapping the LSTM layer? Many thanks!
comment on: http://stackoverflow.com/a/51856855
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/51860232
has comment: http://stackoverflow.com/comment/90673117
has comment: http://stackoverflow.com/comment/90672903
upvote count: 1
has comment: http://stackoverflow.com/comment/90673343
has body: Use a combination of .str.contains and .loc publications.loc[publications.title.str.contains(search_term), ['title', 'publication_ID']] Just be careful, because if your title is 'nightlife' and someone searches for 'night' this will return a match. If that's not your desired behavior then you may need .str.split instead. As jpp points out, str.contains is case sensitive. One simple fix is to just ensure everything is lowercase. title_mask = publications.title.str.lower().str.contains(search_term.lower()) pmids = publications.loc[title_mask, ['title', 'publication_ID']] now Lord, LoRD, lord and all other permutations will return a valid match, and your original DataFrame has the capitalization unchanged.
score: 1
has comment: http://stackoverflow.com/comment/90672883
answers question: http://stackoverflow.com/q/51859857
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51859857
type: Answer
has comment: http://stackoverflow.com/comment/90672866

http://stackoverflow.com/comment/90768828
type: Comment
has text: Can you please be more specific about your expected behaviour? It's not that unclear as in other questions. But better be explicit to avoid misunderstandings.
comment on: http://stackoverflow.com/q/51909312
score: 0
type: QuestionComment

http://stackoverflow.com/comment/90587025
comment on: http://stackoverflow.com/a/51815721
score: 0
type: AnswerComment
type: Comment
has text: NameError: global name 'FileExistsError' is not defined

http://stackoverflow.com/comment/90792925
has text: @ricecrispie Just writing a recursive solution for you!
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51921563
type: AnswerComment

http://stackoverflow.com/q/51831169
tagged with: function
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/90616553
favorite count: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/90617054
tagged with: python
has body: As the question states, I'm trying to learn how to run a function on each element belonging to a column within a DataFrame without having to define that column directly. The point is that I would like to be able to enter any given set of DataFrame and find each element within each column that fulfills a particular condition. The sample that I've included illustrates what I'm trying to do. I know the below doesn't work and I thought that writing def fun(dataframe[column]) would do the trick but the syntax is incorrect, unfortunately. Basically, the reason for this is that I have multiple sets of data where I'd like to locate each element that is above a set threshold. Thanks a lot in advance! df=pd.DataFrame(np.random.randint(0,100,size=(3, 3)), columns=list('ABC')) def fun(dataframe): for column in dataframe: def fun(column): mean= sum(column)/len(column) print (mean) for element in column: if element &lt; mean*1.1: element = 0 print (element) fun(df)
type: UnansweredQuestion
has title: Function within a function involving each column of a DataFrame in Python
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51832371
score: 1
tagged with: dataframe
has comment: http://stackoverflow.com/comment/90616775

http://stackoverflow.com/comment/90770243
score: 0
comment on: http://stackoverflow.com/q/51910031
type: Comment
has text: @ wwii, sorry I'll edit the post.
type: QuestionComment

http://stackoverflow.com/q/51938436
has body: For first: I am total beginner with Python. I just need to automate adding mp3 files to my shop. All of them are inside one catalog. Filename will be a Product Name, and file duration will be a Description of that product. I've wrote a simple Python script which reading all mp3 filenames from catalog and just printing them out. It looks like this: import os filenames = next(os.walk("./", topdown=True))[2] i = 0 while i &lt; len(filenames): print(filenames[i].replace(".mp3", "")) i += 1 It works great but now I need to read duration of all *.mp3 files from the same catalog. I found library called Mutagen. I can easily get duration of one file using this library but I can't read duration of files from whole catalog. Code for reading length of single mp3 file: from mutagen.mp3 import MP3 audio = MP3("example.mp3") print audio.info.length Do you have any idea on how to read duration of all *.mp3 files inside one catalog and print them out?
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/61665377
has answer: http://stackoverflow.com/a/51938495
score: 1
tagged with: duration
tagged with: http://stackoverflow.com/tag/mp3
type: Question
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/90827089
has comment: http://stackoverflow.com/comment/90827188
possible better answer: http://stackoverflow.com/a/61665377
tagged with: python
has title: Getting duration of all mp3 files inside catalog.
favorite count: 0
has comment: http://stackoverflow.com/comment/90827284
accepted answer: http://stackoverflow.com/a/51938495
has comment: http://stackoverflow.com/comment/90827650
has comment: http://stackoverflow.com/comment/90827560
upvote count: 1

http://stackoverflow.com/a/51867172
has body: Since you provide no code, I'll just give you some ideas without any final code. If you want more details, show more work of your own. It seems that you need to compare the values of consecutive tuples. You also have nothing to compare before the first tuple or after the last tuple, but if you add tuples denoting empty item and depth 0 you can do all comparisons. So in your loop, get two consecutive tuples using zip with lists that are one off from each other. You can add guard tuples at the beginning and at the end to show depth zero, and if their values are empty strings those values will not show in your result. So you loop can be for tuple1, tuple2 in zip([('', 0)] + lst, lst + [('', 0)]: The first time through the loop, tuple1 will be the guard tuple ('', 0) and tuple2 will be the first tuple in the list. The last time through the loop, tuple1 will be the last tuple in the list and tuple2 will be the guard tuple ('', 0). Every other time, tuple1 is a tuple in your list and tuple2 is the next tuple in your list. Then when comparing tuples, add left or right parentheses depending on the difference between the depths. Those zero depths enable the beginning and the closing parentheses. After the parenthesis, add the item in the second (later) tuple. You can add spaces here if you like for and and or. Can you finish from here?
has comment: http://stackoverflow.com/comment/90686808
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/51867052
downvote count: 0
type: Answer

event-handling
tag name: event-handling
tags question: http://stackoverflow.com/q/51860960
type: Tag

http://stackoverflow.com/comment/90815542
score: 0
type: AnswerComment
has text: How would a copy operation look like?
comment on: http://stackoverflow.com/a/51932722
type: Comment

http://stackoverflow.com/comment/90565703
comment on: http://stackoverflow.com/a/51804963
type: Comment
score: 0
type: AnswerComment
has text: @MonicaHeddneck I've heard default value, but I don't know if that is the official name for it.

http://stackoverflow.com/comment/90557651
type: Comment
comment on: http://stackoverflow.com/a/51799790
has text: Assuming the design you've suggested, this syntax: outputs=[output, output2] , ensures that each training step on model, will result in another training step on NewModel (where you've suggested to put it in)?
score: 0
type: AnswerComment

http://stackoverflow.com/comment/90641321
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51843914
has text: Thanks! One more question about this one: if I do not use the "ax[0, 0].set_xticks(range(4))" the it "forgets" to use the first tick and it works for example with ax[0, 0].set_xticklabels([-999, 2, 64, 77, 89]) where the -999 is ignored why is that? The set_xticklabels documentation does not comment on it ...

http://stackoverflow.com/q/51926983
type: Question
possible better answer: http://stackoverflow.com/a/51927202
has answer: http://stackoverflow.com/a/51927202
has answer: http://stackoverflow.com/a/51927204
has comment: http://stackoverflow.com/comment/90804084
has comment: http://stackoverflow.com/comment/90803883
score: 0
has answer: http://stackoverflow.com/a/51927292
has answer: http://stackoverflow.com/a/51927130
has comment: http://stackoverflow.com/comment/90804060
has body: I want to change csv name (in this case Example.csv) to a specific name: date time name. I have a library called from datetime import datetime This is my sentence to create a cvsFile: with open('Example.csv', 'w') as csvFile: I want that my output to be: 20180820.csv 20180821.csv 20180822.csv ... etc And if I run more that one time in the same day, I want that my output to be: 20180820.csv (First time that I run the script) 20180821(2).csv (Second time run) ... etc
answer count: 5
has comment: http://stackoverflow.com/comment/90804363
tagged with: http://stackoverflow.com/tag/csv
tagged with: datetime
tagged with: python
has comment: http://stackoverflow.com/comment/90803820
has title: Change CSV name to CSV date time python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90803569
has answer: http://stackoverflow.com/a/51927353
accepted answer: http://stackoverflow.com/a/51927130

http://stackoverflow.com/a/51822929
answers question: http://stackoverflow.com/q/51821540
has comment: http://stackoverflow.com/comment/90804756
has comment: http://stackoverflow.com/comment/90804616
has comment: http://stackoverflow.com/comment/90804468
has comment: http://stackoverflow.com/comment/90804559
has comment: http://stackoverflow.com/comment/90601254
has comment: http://stackoverflow.com/comment/90804730
has comment: http://stackoverflow.com/comment/90601237
has comment: http://stackoverflow.com/comment/90804858
downvote count: 0
has comment: http://stackoverflow.com/comment/90601046
has body: There exist a multitude of n-dimensional convolution functions in scipy.ndimage and astropy. Let's see if we can use any of them. First we need some data to compare against. So let's span up the input space: d0, d1 = np.array(A.shape) + np.array(B.shape) - 1 input_space = np.array(np.meshgrid(np.arange(d0), np.arange(d1))).T.reshape(-1, 2) # array([[0, 0], # [0, 1], # [0, 2], # [0, 3], # [0, 4], # [0, 5], # [0, 6], # [1, 0], # [1, 1], # ... # [4, 5], # [4, 6]]) and calculate your convolution over this space: out = np.zeros((d0, d1)) for K in input_space: out[tuple(K)] = conv(A, B, K + 1) out # array([[ 2., 10., 19., 24., 30., 20., 21.], # [ 17., 36., 71., 81., 112., 53., 72.], # [ 32., 27., 108., 74., 121., 79., 51.], # [ 19., 46., 79., 99., 111., 67., 81.], # [ 35., 39., 113., 76., 93., 33., 27.]]) Okay, now that we know what values to expect, lets see if we can get scipy and astropy to give us the same values: import scipy.signal scipy.signal.convolve2d(A, B) # only 2D! # array([[ 2., 10., 19., 24., 30., 20., 21.], # [ 17., 36., 71., 81., 112., 53., 72.], # [ 32., 27., 108., 74., 121., 79., 51.], # [ 19., 46., 79., 99., 111., 67., 81.], # [ 35., 39., 113., 76., 93., 33., 27.]]) import astropy.convolution astropy.convolution.convolve_fft( np.pad(A, pad_width=((1, 0), (1, 1)), mode='constant'), B, normalize_kernel=False ) # array([[ 2., 10., 19., 24., 30., 20., 21.], # [ 17., 36., 71., 81., 112., 53., 72.], # [ 32., 27., 108., 74., 121., 79., 51.], # [ 19., 46., 79., 99., 111., 67., 81.], # [ 35., 39., 113., 76., 93., 33., 27.]]) astropy.convolution.convolve( np.pad(A, pad_width=((1, 0), (1, 1)), mode='constant'), np.pad(B, pad_width=((0, 1), (0, 0)), mode='constant'), normalize_kernel=False ) # array([[ 2., 10., 19., 24., 30., 20., 21.], # [ 17., 36., 71., 81., 112., 53., 72.], # [ 32., 27., 108., 74., 121., 79., 51.], # [ 19., 46., 79., 99., 111., 67., 81.], # [ 35., 39., 113., 76., 93., 33., 27.]]) import scipy scipy.ndimage.filters.convolve( np.pad(A, pad_width=…
has comment: http://stackoverflow.com/comment/90600088
has comment: http://stackoverflow.com/comment/90805198
type: Answer
has comment: http://stackoverflow.com/comment/90805026
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/90804161
has comment: http://stackoverflow.com/comment/90804357
has comment: http://stackoverflow.com/comment/90804935
has comment: http://stackoverflow.com/comment/90600937

http://stackoverflow.com/tag/json
tags question: http://stackoverflow.com/q/51895839
tags question: http://stackoverflow.com/q/51848558
tags question: http://stackoverflow.com/q/51911674
tags question: http://stackoverflow.com/q/51816284
tags question: http://stackoverflow.com/q/51801528
tags question: http://stackoverflow.com/q/51884563
tags question: http://stackoverflow.com/q/51891858
tags question: http://stackoverflow.com/q/51916321
tags question: http://stackoverflow.com/q/51936785
tags question: http://stackoverflow.com/q/51876466
tags question: http://stackoverflow.com/q/51907546
tags question: http://stackoverflow.com/q/51853545
tags question: http://stackoverflow.com/q/51850163
tags question: http://stackoverflow.com/q/51878213
tags question: http://stackoverflow.com/q/51896680
tags question: http://stackoverflow.com/q/51804004
tags question: http://stackoverflow.com/q/51955605
tags question: http://stackoverflow.com/q/51955245
tags question: http://stackoverflow.com/q/51844487
tags question: http://stackoverflow.com/q/51915537
tags question: http://stackoverflow.com/q/51892415
tags question: http://stackoverflow.com/q/51859531
tags question: http://stackoverflow.com/q/51913744
tags question: http://stackoverflow.com/q/51878706
tags question: http://stackoverflow.com/q/51849318
tags question: http://stackoverflow.com/q/51925830
tags question: http://stackoverflow.com/q/51953082
tags question: http://stackoverflow.com/q/51862688
tags question: http://stackoverflow.com/q/51913496
tags question: http://stackoverflow.com/q/51827757
tags question: http://stackoverflow.com/q/51941227
tags question: http://stackoverflow.com/q/51937684
tags question: http://stackoverflow.com/q/51841653
tags question: http://stackoverflow.com/q/51847896
tags question: http://stackoverflow.com/q/51827820
tags question: http://stackoverflow.com/q/51825935
tags question: http://stackoverflow.com/q/51823590
tags question: http://stackoverflow.com/q/51800895
type: Tag
tags question: http://stackoverflow.com/q/51824502
tags question: http://stackoverflow.com/q/51910889
tags question: http://stackoverflow.com/q/51853462
tags question: http://stackoverflow.com/q/51896094
tags question: http://stackoverflow.com/q/51881794
tags question: http://stackoverflow.com/q/51894583
tags question: http://stackoverflow.com/q/51887104
tags question: http://stackoverflow.com/q/51919698
tags question: http://stackoverflow.com/q/51950730
tags question: http://stackoverflow.com/q/51936017
tags question: http://stackoverflow.com/q/51953452
tags question: http://stackoverflow.com/q/51945976
tags question: http://stackoverflow.com/q/51814121
tags question: http://stackoverflow.com/q/51927954
tags question: http://stackoverflow.com/q/51849851
tags question: http://stackoverflow.com/q/51806845
tags question: http://stackoverflow.com/q/51882304
tags question: http://stackoverflow.com/q/51920961
tags question: http://stackoverflow.com/q/51937252
tags question: http://stackoverflow.com/q/51873151
tags question: http://stackoverflow.com/q/51801510
tag name: json
tags question: http://stackoverflow.com/q/51922259
tags question: http://stackoverflow.com/q/51814497
tags question: http://stackoverflow.com/q/51861119
tags question: http://stackoverflow.com/q/51914505
tags question: http://stackoverflow.com/q/51903413
tags question: http://stackoverflow.com/q/51822269
tags question: http://stackoverflow.com/q/51822251
tags question: http://stackoverflow.com/q/51923876
tags question: http://stackoverflow.com/q/51916917
tags question: http://stackoverflow.com/q/51914326
tags question: http://stackoverflow.com/q/51840587
tags question: http://stackoverflow.com/q/51826053
tags question: http://stackoverflow.com/q/51949976
tags question: http://stackoverflow.com/q/51852007
tags question: http://stackoverflow.com/q/51821908
tags question: http://stackoverflow.com/q/51860742
tags question: http://stackoverflow.com/q/51836076
tags question: http://stackoverflow.com/q/51953659
tags question: http://stackoverflow.com/q/51873988

http://stackoverflow.com/comment/90857609
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51941101
type: Comment
has text: Could it be that ROSLIB.ServiceRequest? ? ?

http://stackoverflow.com/a/51903187
answers question: http://stackoverflow.com/q/51903096
upvote count: 1
score: 1
has body: You should be able to do df = xl.parse("products", names = headers)
has comment: http://stackoverflow.com/comment/91039355
downvote count: 0
type: Answer

http://stackoverflow.com/q/51865332
type: Question
has comment: http://stackoverflow.com/comment/90682913
score: -1
linked to: http://stackoverflow.com/q/13961140
tagged with: syntax-error
upvote count: 0
tagged with: newline
has answer: http://stackoverflow.com/a/51865379
duplicate of: http://stackoverflow.com/q/13961140
answer count: 1
favorite count: 0
has title: unexpected character after line continuation character when opening file in command line
tagged with: python
type: UnansweredQuestion
has body: I have just started learning python and make a python file called "helloworld.py" and store it inside a file called "python py" on the desktop, but this keep poping out whenever I am trying to open it in command line like this: Can someone tell me what's wrong?
downvote count: 1

http://stackoverflow.com/a/51897733
upvote count: 6
type: Answer
has comment: http://stackoverflow.com/comment/90747763
answers question: http://stackoverflow.com/q/51897638
score: 6
downvote count: 0
has body: The issue tells you that the Series returned by your operation holds no intrinsic truth value. Indeed, the operation will always return something and you have to chose what you actually want: if any of the returned values is true, meaning there exists an element in df which is in ['12','09'] if all of the returned values are true, meaning all elements in df are in ['12','09'] if the returned Series contains any element, meaning not empty So: if not df.loc[df['state_code'].isin(['12','09'])].empty: or if df.loc[df['state_code'].isin(['12','09'])].any(): or if df.loc[df['state_code'].isin(['12','09'])].all(): Check out the documentation For more help, provide a minimal working example of your code

http://stackoverflow.com/comment/90789560
comment on: http://stackoverflow.com/q/51918990
score: 0
type: QuestionComment
type: Comment
has text: @Novel: Then the sample code is too complex and hardly the minimal amount to reproduce the error. The fact that the OP isn't following the PEP 8 coding guidelines doesn't help things either.

http://stackoverflow.com/q/51829462
has body: I am creating a clustermap of a list of 529 genes. For some reason not all the genes in the index of the dataframe are being displayed in the clustermap. I've attached an image showing the issue. Any help would be much appreciated. def create_heatmap(dataframe, title): import seaborn as sns import matplotlib.pyplot as pyplot sns_plot = sns.clustermap(dataframe,mask=False,row_cluster=True,linewidth=.05, linecolor="grey",col_cluster=False,standard_scale=0 ,cmap="Greys",square=True,figsize=(12,(.2*(len(dataframe.index))))) sns_plot.savefig("{}.png".format(title)) return sns_plot
tagged with: seaborn
type: AnsweredQuestion
score: 17
upvote count: 17
type: Question
downvote count: 0
has answer: http://stackoverflow.com/a/51829979
has title: Seaborn clustermap not displaying all row annotations
answer count: 1
tagged with: python
favorite count: 0
tagged with: heatmap
accepted answer: http://stackoverflow.com/a/51829979

http://stackoverflow.com/q/51813335
has answer: http://stackoverflow.com/a/51813730
tagged with: python
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51813515
has answer: http://stackoverflow.com/a/51813550
has answer: http://stackoverflow.com/a/51814157
has answer: http://stackoverflow.com/a/51813515
has comment: http://stackoverflow.com/comment/90582263
type: Question
has comment: http://stackoverflow.com/comment/90581746
accepted answer: http://stackoverflow.com/a/51814157
answer count: 6
has title: Vectorized indexing numpy arrays in pandas Series with Boolean numpy arrays in pandas Series
has answer: http://stackoverflow.com/a/51814666
upvote count: 4
tagged with: numpy
has answer: http://stackoverflow.com/a/51813417
has body: The following reproducible code produces an example data set that mimics my data on a much smaller scale. import numpy as np import pandas as pd np.random.seed(142536) df = pd.DataFrame({ "vals": list(np.arange(12).reshape(3,4)), "idx" : list(np.random.choice([True, False], 12).reshape(3,4))}) df idx vals 0 [False, True, True, False] [0, 1, 2, 3] 1 [True, True, False, True] [4, 5, 6, 7] 2 [False, True, False, False] [8, 9, 10, 11] The following reproducible code returns the results I want, but is very inefficient for large data sets. How would I do this more efficiently? sel = [] for i in range(len(df.vals)): sel.append(df.vals[i][df.idx[i]]) df['sel'] = sel df idx vals sel 0 [False, True, True, False] [0, 1, 2, 3] [1, 2] 1 [True, True, False, True] [4, 5, 6, 7] [4, 5, 7] 2 [False, True, False, False] [8, 9, 10, 11] [9] I have tried np.apply_along_axis(), np.where(), df.apply(), and df.transform(), but can't get any of them to work for this case without errors.
downvote count: 0
score: 4
favorite count: 0
tagged with: pandas

http://stackoverflow.com/q/51955466
upvote count: 1
tagged with: timeit
has answer: http://stackoverflow.com/a/51956821
score: -1
has comment: http://stackoverflow.com/comment/90861500
has body: I've noticed that results change rapidly between running timeit with the regular arugments and timeit with the argument number=1. Here is the example that I found. import sympy as sp import numpy as np var = (sp.Symbol("x"), sp.Symbol("y"), sp.Symbol("z")) x,y,z = var[0], var[1], var[2] monos = np.array([1, z, y, x, z**2, y*z, y**2, x*z, x*y, x**2, z**3, y*z**2, y**2*z, y**3, x*z**2, x*y*z, x*y**2, x**2*z, x**2*y, x**3, z**4, y*z**3, y**2*z**2, y**3*z, y**4, x*z**3, x*y*z**2, x*y**2*z, x*y**3, x**2*z**2, x**2*y*z, x**2*y**2, x**3*z, x**3*y, x**4]) f = sp.lambdify(var, monos) import testit timeit.timeit("(f(2,3,4))", setup="from __main__ import f") #returns 2.0760600566864014 timeit.timeit("(f(2,3,4))", setup="from __main__ import f", number=1) #returns 1.5974044799804688e-05 I'm using python2 version 2.7.12 and sympy version 1.2. What is going on here?
type: Question
tagged with: numpy
tagged with: sympy
answer count: 1
has title: Inconsistency between timieit with number and timeit without a number
tagged with: python
favorite count: 0
type: UnansweredQuestion
downvote count: 2

twilio
tag name: twilio
tags question: http://stackoverflow.com/q/51878976
tags question: http://stackoverflow.com/q/51835215
type: Tag
tags question: http://stackoverflow.com/q/51850441

http://stackoverflow.com/q/51920887
has body: I have the following situation in python 2.7: class A(object): def __init__(self, a): self._a = a class B(object): def __init__(self, b): self._b = b class C(A, B): def __init__(self): # How to init A with 'foo' and B with 'bar'? It should also be noted that one of the parent classes, say A, is a library class and the solution should preferably assume it is set in stone; While the other class B is mine and could be freely changed. What is the correct way to initialize both parent classes correctly? Thanks!
duplicate of: http://stackoverflow.com/q/3277367
accepted answer: http://stackoverflow.com/a/51920922
tagged with: python
type: AnsweredQuestion
downvote count: 2
upvote count: 1
duplicate of: http://stackoverflow.com/q/9575409
type: Question
score: -1
has answer: http://stackoverflow.com/a/51920922
tagged with: python-2.7
has title: multiple inheritance, give both parents' constructors an argument
answer count: 1
tagged with: multiple-inheritance
linked to: http://stackoverflow.com/q/3277367
favorite count: 0

http://stackoverflow.com/comment/90836258
type: Comment
comment on: http://stackoverflow.com/q/51943308
score: 1
has text: This is almost certainly a duplicate of an existing question with a good answer; we just need to find it for you.
type: QuestionComment

http://stackoverflow.com/comment/90700696
type: QuestionComment
comment on: http://stackoverflow.com/q/51873465
has text: well that's just a wheel file being installed from a remote location. Please read my question again.
score: 0
type: Comment

http://stackoverflow.com/a/51904399
type: Answer
accepted answer of: http://stackoverflow.com/q/51903911
has body: The answer depends on the calling conventions of the ABI of the C compiler used to compile your Python. It sounds like you're on x86-64 Windows.1 If so, your system is built around the Microsoft x64 ABI. And if not, that still makes for a good example, so let's pretend you are. Slightly oversimplified,2 the calling conventions for that ABI work like this: The first four arguments are stored in registers RCX, RDX, R8, and R9. Any additional arguments are pushed onto the stack. So, your c_uint arguments get stored in the low 32 bits of RCX and RDX, respectively, while the high 32 bits of each of those registers gets cleared to 0. The add function goes to add RCX and RDX as unsigned 64-bit ints, and the result is exactly what you'd expect; everything works.3 But imagine you were on a different platform, with a different ABI. In fact, your imagination doesn't have to go very far; if you run a 32-bit program on the same Windows machine, you get the Microsoft IA-32 ABI instead of Microsoft x64. That ABI has three different calling conventions, and that _cdecl in your declaration now selects one of the three, which works like this: Push everything on the stack. OK, now c_uint and size_t both happen to be 32 bits, but let's do the same thing with c_ushort. Your Python code pushes two 16-bit values onto the stack. add tries to use the both of your values—as in x | (y&lt;&lt;32)—as its x parameter, and then whatever happens to be next to it on the stack as its y parameter. So, what you get back is garbage. And it can get even worse. What if you'd used _stdcall? In the Microsoft x64 ABI that does nothing, but in the Windows IA-32 ABI, it specifies the same parameter passing order as _cdecl, but stack cleanup by the callee rather than the caller. So, after generating your garbage for you, add goes to clean up the stack, and it's expecting a different size than what you gave it, and… well, actually, I think in this specific case you get away with it because the parameter area of…
upvote count: 1
answers question: http://stackoverflow.com/q/51903911
score: 1
has comment: http://stackoverflow.com/comment/90819984
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/51882486
tagged with: python-2.7
score: 0
answer count: 1
tagged with: python
has answer: http://stackoverflow.com/a/51882666
has title: Share variable between threads in python threadpool
type: UnansweredQuestion
tagged with: multithreading
has body: I have code like this: from multiprocessing import Pool def do_stuff(idx): for i in items[idx:idx+20]: # do stuff with idx items = # a huge nested list pool = Pool(5) pool.map(do_stuff, range(0, len(items), 20)) pool.close() pool.join() The issue is that threadpool does not share items but rather does create copy for each thread, which is an issue since list is huge and it hogs memory. Is there a way to implement this in a way that items would be shared? found some examples with global that work in basic thread library but that does not seem to apply for multiprocessing lib. Thanks!
tagged with: multiprocessing
tagged with: threadpool
linked to: http://stackoverflow.com/q/659865
type: Question

http://stackoverflow.com/comment/90650563
comment on: http://stackoverflow.com/q/51824991
has text: @VivekKumar yes I am sure. To test this bug, I return the data given to the function from the function to the notebook and process using the same commands that would usually be in the function. The only explanation I can come up with is that the pandas dataframe changes when the data is returned.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/90604177
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51824213
has text: its to find all possible combinations of test and train with the test set having data belonging to 2 values of x in every iteration. i will try the suggestions provided below.
score: 0

memoization
type: Tag
tags question: http://stackoverflow.com/q/51910978
tags question: http://stackoverflow.com/q/51831733
tag name: memoization
tags question: http://stackoverflow.com/q/51863982

http://stackoverflow.com/comment/90809317
score: 0
comment on: http://stackoverflow.com/q/51929798
has text: What is saxon exactly? Is it a part of string in the cells in column D? Or do you want all values from column D?
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51921769
has comment: http://stackoverflow.com/comment/90882409
type: Answer
has body: Here is a solution using an 1D interpolation to compute the inverse of the F(h) function. Because non standard root finding method is used, the error is not controlled, and the discretization grid have to be chosen with care. However, the interpolated inverse function can be directly computed over an array. note: the definition of F is modified, the problem is now Solve h for F(h) = TR import numpy as np from scipy.interpolate import interp1d import matplotlib.pylab as plt # The function to inverse: t = 10 alfa = 1.1*10**(-7) k = 0.18 T1 = 20 Tpow = 100 def F(h): A = np.exp(h**2*alfa*t/k**2) B = h**3*2/(3*np.sqrt(3))*(alfa*t)**(3/2)/k**3 return -(Tpow-T1)*( 1 - A + B ) # Interpolation h_eval = np.linspace(40, 100, 50) # critical step: define the discretization grid F_inverse = interp1d( F(h_eval), h_eval, kind='cubic', bounds_error=True ) # Some random data: TR = np.array([[13, 10, 13, 13, 13], [ 9, 11, 10, 12, 9], [13, 13, 10, 10, 13], [12, 11, 12, 9, 11], [11, 13, 13, 11, 13]]) # Compute the array h for a given array TR h = F_inverse(TR) print(h) # Graph to verify the interpolation plt.plot(h_eval, F(h_eval), '.-', label='discretized F(h)'); plt.plot(h.ravel(), TR.ravel(), 'or', label='interpolated values') plt.xlabel('h'); plt.ylabel('F(h) or TR'); plt.legend(); With the other function, the following lines are changed: from scipy.special import erf def F(h): return (Tpow-T1)*(1-np.exp((h**2*alfa*t)/k**2)*(1.0-erf(h*np.sqrt(alfa*t)/k))) # Interpolation h_eval = np.linspace(15, 35, 50) # the range is changed
has comment: http://stackoverflow.com/comment/90876165
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/90876308
has comment: http://stackoverflow.com/comment/90880494
answers question: http://stackoverflow.com/q/51920645
has comment: http://stackoverflow.com/comment/90874775
has comment: http://stackoverflow.com/comment/90883324
upvote count: 1
has comment: http://stackoverflow.com/comment/90872825
has comment: http://stackoverflow.com/comment/90875836

http://stackoverflow.com/q/51921782
tagged with: recursion
score: 0
has comment: http://stackoverflow.com/comment/90793577
has comment: http://stackoverflow.com/comment/90793231
answer count: 0
type: UnansweredQuestion
tagged with: binary-tree
has body: def delete(self,data): if self.root!=None: self._delete(data,self.root) def _delete(self,data,cur): if cur!=None: if cur.data==data: if cur.left==None and cur.right==None: cur=None else: print("Wait") else: self._delete(data,cur.left) self._delete(data,cur.right) I am using recursion in the code to delete the leaf node from a tree but putting cur=None is not doing anything it prints the the node when I view it again.
has title: I can't remove the data from the tree node it just shows when I view it again
has comment: http://stackoverflow.com/comment/90793218
tagged with: python-3.x
type: Question
tagged with: python

http://stackoverflow.com/q/51851198
has title: opencv set camera resolution windows vrs linux
tagged with: python
upvote count: 3
has answer: http://stackoverflow.com/a/52130912
type: UnansweredQuestion
type: Question
tagged with: opencv
score: 3
tagged with: image-resizing
has answer: http://stackoverflow.com/a/54728999
has answer: http://stackoverflow.com/a/52021832
answer count: 3
downvote count: 0
favorite count: 0
has body: Questions that are variations of this occur, but not this error situation. This codeworks on Linux, it Fails on windows10 OpenCV 3.4.2, 64bit -Python 3.6 - installed via "pip3 install opencv-python" It fails on Windows with the error message below. If I remove the 'cv2.set()' for the horz and virt size it works, without problem but the resolution is not what I want My goal is to change from the default image size to the LARGER size. v=3.4.2 Camera H=480, W=640 Camera H=480, W=640 [ WARN:0] videoio(MSMF): OnReadSample() is called with error status: -1072875855 [ WARN:0] videoio(MSMF): async ReadSample() call is failed with error status: -1072875855 [ WARN:1] videoio(MSMF): can't grab frame. Error: -1072875855 [ WARN:1] videoio(MSMF): can't grab frame. Error: -2147483638 This is the Python code import cv2 print("v=%s" % cv2.__version__) cap = cv2.VideoCapture(0, cv2.) h = cap.get( cv2.CAP_PROP_FRAME_HEIGHT ) w = cap.get( cv2.CAP_PROP_FRAME_WIDTH ) print("Camera H=%d, W=%d" % (h,w) ) # If I remove these two lines it works but is stuck at 640x480 cap.set( cv2.CAP_PROP_FRAME_HEIGHT, 10000 ) cap.set( cv2.CAP_PROP_FRAME_WIDTH, 10000 ) h = cap.get( cv2.CAP_PROP_FRAME_HEIGHT ) w = cap.get( cv2.CAP_PROP_FRAME_WIDTH ) print("Camera H=%d, W=%d" % (h,w) ) while(True): if cv2.waitKey(1) &amp; 0xFF == ord('q'): break ret, frame = cap.read() if ret: cv2.imshow('frame',frame) cap.release() cv2.destroyAllWindows()

http://stackoverflow.com/q/51943487
type: Question
score: 3
has body: I am trying to apply a filter to an existing Excel file, and export it to another Excel file. I would like to extract rows that only contain the value 16, then export the table to another excel file (as shown in the picture below). I have tried reading the openpyxl documentation multiple times and googling for solutions but I still can't make my code work. I have also attached the code and files below import openpyxl # Is use to create a reference of the Excel to wb wb1 = openpyxl.load_workbook('test_data.xlsx') wb2 = openpyxl.load_workbook('test_data_2.xlsx') # Refrence the workbook to the worksheets sh1 = wb1["data_set_1"] sh2 = wb2["Sheet1"] sh1.auto_filter.ref = "A:A" sh1.auto_filter.add_filter_column(0, ["16"]) sh1.auto_filter.add_sort_condition("B2:D6") sh1_row_number = sh1.max_row sh1_col_number = sh1.max_column rangeSelected = [] for i in range(1, sh1_row_number+1, 1): rowSelected = [] for j in range(1, sh1_col_number+1, 1): rowSelected.append(sh1.cell(row = i, column = j)) rangeSelected.append(rowSelected) del rowSelected for i in range(1, sh1_row_number+1, 1): for j in range(1, sh1_col_number+1, 1): sh2.cell(row = i, column = j).value = rangeSelected[i-1][j-1].value wb1.save("test_data.xlsx") wb2.save("test_data_2.xlsx") The pictures shows what should be the desire result
upvote count: 3
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/51944098
accepted answer: http://stackoverflow.com/a/51944098
favorite count: 0
has title: How to filter column data using openpyxl
tagged with: python
type: AnsweredQuestion
tagged with: openpyxl

http://stackoverflow.com/a/51910297
score: 0
has body: inventory = {847502: ['APPLES 1LB', 1.99, 50], 847283: ['OLIVE OIL', 10.99, 100], 839529: ['TOMATOS 1LB', 1.29, 25], 483946: ['MILK 1/2G', 3.45, 35], 493402: ['FLOUR 5LB', 2.99, 40], 485034: ['BELL PEPPERS 1LB', 1.35, 28], 828391: ['WHITE TUNA', 1.69, 100], 449023: ['CHEESE 1/2LB', 4.99, 15]} while True: try: upc_input = int(input('Enter a UPC number: ')) break except Exception: print("Oops! That was no valid number. Try again...") if upc_input in inventory.keys(): description = input('Enter a, item description: ') unit_price = float(input('Enter the unit price: ')) quantity = int(input('Enter th quantity: ')) print('Inventory Updating') inventory[upc_input] = [description,unit_price,quantity] if upc_input not in inventory.keys(): description = input('Enter a, item description: ') unit_price = float(input('Enter the unit price: ')) quantity = int(input('Enter th quantity: ')) print('Adding new inventory') inventory[upc_input] = [description,unit_price,quantity] print() print(inventory) Here! I checked your code and found the following, a) you mispelled "Exception" and b) there is a logic mistake. You ask first for the number and then use the statement try. You MUST have the input INSIDE the try statement, otherwise your program is trying nothing Check in my code I have the input statement inside the try:, and if everything goes right, then it will move on to asking for the other inputs and setting them up depending wether the reference number is/isnt in the list
has comment: http://stackoverflow.com/comment/90770759
type: Answer
accepted answer of: http://stackoverflow.com/q/51910031
answers question: http://stackoverflow.com/q/51910031
type: AcceptedAnswer

http://stackoverflow.com/comment/90661148
type: QuestionComment
has text: @KevinFang https://www.codefellows.org/blog/implementing-a-singly-linked-list-in-python/
type: Comment
comment on: http://stackoverflow.com/q/51853732
score: 0

http://stackoverflow.com/comment/90629777
type: Comment
comment on: http://stackoverflow.com/q/51838301
type: QuestionComment
has text: What is `item`, how does it relate to `i` in the `for` loop? You have tuples, so `i[-1]` or `i[2]` is the dictionary in each item in the list, you want to address *that reference* if you want to do anything with the dictionary.
score: 0

http://stackoverflow.com/a/51930351
upvote count: 2
answers question: http://stackoverflow.com/q/51928856
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 2
has body: You get this error because your training &amp; test data are not of the same kind: while you train in your initial X_train set: classifier.fit(X_train, y_train) you are trying to get predictions from a dataset which has undergone count vectorization &amp; tf-idf transormations first: predicted = classifier.predict(test_tfidf) It is puzzling why you choose to do so, why you nevertheless compute train_counts and train_tfidf (you don't seem to actually use them anywhere), and why you are also trying to redefine predicted as classifier.predict(X_test) immediately afterwards. Normally, changing your training line to classifier.fit(train_tfidf, y_train) and getting rid of your second predicted definition should work OK...
accepted answer of: http://stackoverflow.com/q/51928856

timezone
tags question: http://stackoverflow.com/q/51800165
type: Tag
tags question: http://stackoverflow.com/q/51843395
tag name: timezone
tags question: http://stackoverflow.com/q/51913210

pygame
tags question: http://stackoverflow.com/q/51875030
tags question: http://stackoverflow.com/q/51833699
tags question: http://stackoverflow.com/q/51848277
tags question: http://stackoverflow.com/q/51807787
tags question: http://stackoverflow.com/q/51860173
tags question: http://stackoverflow.com/q/51803098
tags question: http://stackoverflow.com/q/51818293
tags question: http://stackoverflow.com/q/51813744
tags question: http://stackoverflow.com/q/51918568
tags question: http://stackoverflow.com/q/51948446
tags question: http://stackoverflow.com/q/51867937
tags question: http://stackoverflow.com/q/51863302
tags question: http://stackoverflow.com/q/51901008
tags question: http://stackoverflow.com/q/51803264
tags question: http://stackoverflow.com/q/51810316
tags question: http://stackoverflow.com/q/51832118
tags question: http://stackoverflow.com/q/51893904
tags question: http://stackoverflow.com/q/51810828
tags question: http://stackoverflow.com/q/51832141
tags question: http://stackoverflow.com/q/51892263
tags question: http://stackoverflow.com/q/51883484
tags question: http://stackoverflow.com/q/51817123
tags question: http://stackoverflow.com/q/51803236
tags question: http://stackoverflow.com/q/51948688
tags question: http://stackoverflow.com/q/51956370
tags question: http://stackoverflow.com/q/51917091
tag name: pygame
tags question: http://stackoverflow.com/q/51840164
tags question: http://stackoverflow.com/q/51818613
tags question: http://stackoverflow.com/q/51939544
tags question: http://stackoverflow.com/q/51861781
tags question: http://stackoverflow.com/q/51886457
tags question: http://stackoverflow.com/q/51878667
tags question: http://stackoverflow.com/q/51838175
tags question: http://stackoverflow.com/q/51804863
tags question: http://stackoverflow.com/q/51878957
tags question: http://stackoverflow.com/q/51857329
tags question: http://stackoverflow.com/q/51898865
tags question: http://stackoverflow.com/q/51837006
tags question: http://stackoverflow.com/q/51813378
tags question: http://stackoverflow.com/q/51810381
tags question: http://stackoverflow.com/q/51814910
tags question: http://stackoverflow.com/q/51811946
tags question: http://stackoverflow.com/q/51943574
tags question: http://stackoverflow.com/q/51924485
type: Tag
tags question: http://stackoverflow.com/q/51919175

http://stackoverflow.com/comment/90828822
type: QuestionComment
has text: Ahh it worked. I had HREF capitalized. Any idea how to follow the links?
type: Comment
comment on: http://stackoverflow.com/q/51939159
score: 0

http://stackoverflow.com/comment/90707407
score: 0
type: Comment
type: QuestionComment
has text: well I only posted as image because I wasn't allowed to paste into the body of the message
comment on: http://stackoverflow.com/q/51874297

http://stackoverflow.com/comment/90872825
type: AnswerComment
has text: thanks a lot - it works perfect with that equation but when I try to use `(Tpow-T1)*(1-exp((h**2*alfa*t)/k**2)*(1.0-erf(h*sqrt(alfa*t)/k)))` instead of `-(Tpow-T1)*( 1 - A + B )` an error occurs: `AttributeError: 'ImmutableDenseNDimArray' object has no attribute 'extract_multiplicatively'`
score: 0
comment on: http://stackoverflow.com/a/51921769
type: Comment

http://stackoverflow.com/comment/90785396
type: QuestionComment
has text: I think you need to show what you are doing with those variables inside the nested function.
comment on: http://stackoverflow.com/q/51917757
score: 0
type: Comment

http://stackoverflow.com/comment/90798886
type: Comment
comment on: http://stackoverflow.com/q/51924253
type: QuestionComment
score: 0
has text: Opening in something else does not work I believe that it is being logged wrong and I have no clue how to fix that @HaR

http://stackoverflow.com/q/51843816
tagged with: amazon-web-services
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/90646456
has comment: http://stackoverflow.com/comment/90682281
has comment: http://stackoverflow.com/comment/90682245
tagged with: python
has comment: http://stackoverflow.com/comment/90644280
has comment: http://stackoverflow.com/comment/92831267
has comment: http://stackoverflow.com/comment/90645794
has body: I have created a neptune instance in aws. How can I connect to it now? I tried the the example given in the documentation locally from my laptop. from gremlin_python.structure.graph import Graph from gremlin_python.driver.driver_remote_connection import DriverRemoteConnection graph = Graph() g = graph.traversal().withRemote(DriverRemoteConnection('ws://my_endpoint:8182/gremlin','g')) print(g.V().limit(2).toList()) But I get Timeout exception with the following stacktrace File "/home/cegprakash/.virtualenvs/cegprakash-6Wq6Rd61/lib/python3.5/site-packages/gremlin_python/driver/driver_remote_connection.py", line 45, in __init__ password=password) File "/home/cegprakash/.virtualenvs/cegprakash-6Wq6Rd61/lib/python3.5/site-packages/gremlin_python/driver/client.py", line 76, in __init__ self._fill_pool() File "/home/cegprakash/.virtualenvs/cegprakash-6Wq6Rd61/lib/python3.5/site-packages/gremlin_python/driver/client.py", line 88, in _fill_pool conn = self._get_connection() File "/home/cegprakash/.virtualenvs/cegprakash-6Wq6Rd61/lib/python3.5/site-packages/gremlin_python/driver/client.py", line 101, in _get_connection self._transport_factory, self._executor, self._pool) File "/home/cegprakash/.virtualenvs/cegprakash-6Wq6Rd61/lib/python3.5/site-packages/gremlin_python/driver/connection.py", line 40, in __init__ self.connect() File "/home/cegprakash/.virtualenvs/cegprakash-6Wq6Rd61/lib/python3.5/site-packages/gremlin_python/driver/connection.py", line 46, in connect self._transport.connect(self._url) File "/home/cegprakash/.virtualenvs/cegprakash-6Wq6Rd61/lib/python3.5/site-packages/gremlin_python/driver/tornado/transport.py", line 33, in connect lambda: websocket.websocket_connect(url)) File "/home/cegprakash/.virtualenvs/cegprakash-6Wq6Rd61/lib/python3.5/site-packages/tornado/ioloop.py", line 458, in run_sync return future_cell[0].result() File "/home/cegprakash/.virtualenvs/cegprakash-6Wq6Rd61/lib/python3.5/site-packages/tornado/concurrent.py", line 238, in result raise_exc…
has comment: http://stackoverflow.com/comment/99805750
answer count: 3
upvote count: 7
tagged with: amazon-neptune
has title: Python - Connecting to AWS Neptune
has comment: http://stackoverflow.com/comment/90646333
linked to: http://stackoverflow.com/q/49088195
has answer: http://stackoverflow.com/a/56823934
has answer: http://stackoverflow.com/a/61585771
tagged with: graph-databases
has comment: http://stackoverflow.com/comment/91379367
has answer: http://stackoverflow.com/a/52847775
downvote count: 0
has comment: http://stackoverflow.com/comment/90702715
type: UnansweredQuestion
score: 7

http://stackoverflow.com/comment/90646949
comment on: http://stackoverflow.com/q/51846763
type: Comment
has text: `f` is an integer from your `range` and `f[1]` is the syntax for indexing. It's not clear to me what you expect the code to do instead.
score: 2
type: QuestionComment

http://stackoverflow.com/a/51899777
has body: The problem is here: else: next(h) print() next() gets the next item of an iterator. Since h is an int, it can't be iterated over. You don't need to use next() in a for loop, because for loops iterate without other code (h will increase each time the loop is run).
answers question: http://stackoverflow.com/q/51899662
type: Answer
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/a/51864900
upvote count: 1
score: 1
downvote count: 0
has body: This issue here is I had two python interpreters installed on the computer. I deleted the one where matplotlib was not present and the issue is now cleared.
answers question: http://stackoverflow.com/q/51863208
type: Answer

http://stackoverflow.com/a/51935790
has comment: http://stackoverflow.com/comment/90823324
has comment: http://stackoverflow.com/comment/90821847
type: AcceptedAnswer
downvote count: 0
score: 1
has body: Try: o ={ "events":[{"id": item, "name": "blah%s" %(index + 1)} for index, item in enumerate(array)], "name": "bla" } print(o) # {'events': [{'id': 'a', 'name': 'blah1'}, {'id': 'b', 'name': 'blah2'}, {'id': 'c', 'name': 'blah3'}], 'name': 'bla'}
type: Answer
answers question: http://stackoverflow.com/q/51935750
accepted answer of: http://stackoverflow.com/q/51935750
upvote count: 1

http://stackoverflow.com/comment/90770416
type: Comment
comment on: http://stackoverflow.com/q/51901907
score: 0
type: QuestionComment
has text: Please ask one question; you are asking 3. Also, for each please describe clearly what you are trying to achieve what you have tried and what does not work as desired.

http://stackoverflow.com/q/51836370
has comment: http://stackoverflow.com/comment/90627106
answer count: 0
upvote count: 3
type: UnansweredQuestion
has title: Python flask stop asyncio loops
has body: I try to create a Flask rest API with some asyncio loops behind working. I was testing it and I can see every time I got a loop.create_task() and the task start running its like flask server stop it. He is my code: async def hello_world(sc): await asyncio.sleep(sc) print("Hello World!",sc) loop = asyncio.get_event_loop() loop.create_task(hello_world(2)) loop.create_task(hello_world(4)) loop.create_task(hello_world(5)) loop.create_task(hello_world(1)) loop.create_task(hello_world(9)) print("fffffffffffffffffffff") api.start_server() And I got the following result: python main.py fffffffffffffffffffff * Serving Flask app "api" (lazy loading) [...] And i expected something like this: python main.py fffffffffffffffffffff * Serving Flask app "api" (lazy loading) [...] Hello World! 1 Hello World! 2 Hello World! 4 Hello World! 5 Hello World! 9 Edit More precise example that I got: import asyncio async def hello_world(sc): await asyncio.sleep(sc) print("Hello World!",sc) async def timer(): times = 0 while True: await asyncio.sleep(1) print(times) times +=1 loop = asyncio.get_event_loop() loop.create_task(timer()) loop.run_until_complete(asyncio.gather( hello_world(3), hello_world(2), hello_world(4), hello_world(5), )) print("fffffffffffffffffffff") api.start_server() That I got: λ python main.py 0 Hello World! 2 1 Hello World! 3 2 Hello World! 4 3 Hello World! 5 4 fffffffffffffffffffff * Serving Flask app "api" (lazy loading) * Environment: production WARNING: Do not use the development server in a production environment. Use a production WSGI server instead. * Debug mode: on 0 Hello World! 2 1 Hello World! 3 2 Hello World! 4 3 Hello World! 5 4 fffffffffffffffffffff Why stop print timer() function?
type: Question
score: 3
has comment: http://stackoverflow.com/comment/90629007
downvote count: 0
tagged with: flask
has comment: http://stackoverflow.com/comment/90626688
favorite count: 0
tagged with: python-asyncio
tagged with: python

ctypes
tags question: http://stackoverflow.com/q/51824794
tags question: http://stackoverflow.com/q/51881146
tags question: http://stackoverflow.com/q/51862518
tags question: http://stackoverflow.com/q/51845092
tags question: http://stackoverflow.com/q/51936490
tags question: http://stackoverflow.com/q/51867365
tag name: ctypes
type: Tag
tags question: http://stackoverflow.com/q/51899452
tags question: http://stackoverflow.com/q/51933309
tags question: http://stackoverflow.com/q/51955406
tags question: http://stackoverflow.com/q/51903911
tags question: http://stackoverflow.com/q/51872499
tags question: http://stackoverflow.com/q/51828692
tags question: http://stackoverflow.com/q/51852310
tags question: http://stackoverflow.com/q/51867653

http://stackoverflow.com/q/51888433
tagged with: python
linked to: http://stackoverflow.com/q/35491274
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/35491274
has answer: http://stackoverflow.com/a/51888455
has body: I have following pandas series 0 [1, 11283, 1, 5] 1 [2, 5, 1, 1] 2 [6, 33, 21, 2] 3 [11283, 1, 5, 1] 4 [8430, 1, 2, 2] 5 [2, 1, 1, 1] I need to right this to csv. But I need each item in a list as separate column. For example: In fist row, 1, 11283, 1, 5 should be separate column
type: Question
score: 0
has title: Pandas series flatten array to csv
tagged with: pandas
answer count: 1

http://stackoverflow.com/q/51829362
has comment: http://stackoverflow.com/comment/90613289
has comment: http://stackoverflow.com/comment/90613346
tagged with: tkinter
tagged with: python
has answer: http://stackoverflow.com/a/51829877
accepted answer: http://stackoverflow.com/a/51829877
tagged with: object
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90613734
type: Question
score: 0
has body: I'm trying to understand how Python classes work to be able to follow the four pillars of OOP. I'm trying to set up a Controller class that will set up some UI classes and respond to input. Currently the Controller class inits a frame which inits some Buttons. The controller passes a click(x,y) function to the UI classes to listen to clicks. That part is currently working, but I can't seem to figure out how the controller class can access it's subclass to do changes to the UI. Here's the code I got so far. My problem is that the Click(x,y) function in Controller cannot seem to find the "game" object created in main. Controller.py: from GameFrame import GameFrame global game def click(x, y): global game print("%s %s" %(x,y)) game.changeColor(x, y) if __name__ == '__main__': global game game = GameFrame("title", click) pass GameFrame.py: from GameButtons import GameButtons from tkinter import * class GameFrame(object): global gameButtons def __init__(self, params, click): frame = Tk() gameButtons= GameButtons(frame,click) frame.mainloop() def changeColor(self, x, y): gameButtons.buttons[x][y].configure(bg = "green") GameButtons.py: from tkinter import * class GameButtons(object): global buttons buttons = [[0 for x in range(8)]for x in range(8)] def __init__(self, frame, click): for x in range(8): for y in range(8): b = Button(frame, text = " x ", command = lambda row = x, col = y: click(row, col)) b.grid(row = x, column = y) global buttons buttons[x][y] = b Clicking a button correctly outputs the row/column from the click(x,y) function but then gives me a NameError: name 'game' is not defined when trying to run game.changeColor(x,y) Would greatly appreciate any help to fix this, or any explanation why what I'm trying to achieve is a bad idea in the first place.
answer count: 1
has comment: http://stackoverflow.com/comment/90613522
tagged with: global
has comment: http://stackoverflow.com/comment/90613173
has title: Trying to set up global object, but getting NameError object is not defined when trying to access subclass from another file
has comment: http://stackoverflow.com/comment/90614173

amazon-web-services
tags question: http://stackoverflow.com/q/51843755
tags question: http://stackoverflow.com/q/51802002
tags question: http://stackoverflow.com/q/51898575
tags question: http://stackoverflow.com/q/51801353
tags question: http://stackoverflow.com/q/51929131
tags question: http://stackoverflow.com/q/51848398
tags question: http://stackoverflow.com/q/51801942
tags question: http://stackoverflow.com/q/51828304
tags question: http://stackoverflow.com/q/51863155
tags question: http://stackoverflow.com/q/51879904
tags question: http://stackoverflow.com/q/51950417
tags question: http://stackoverflow.com/q/51843816
tags question: http://stackoverflow.com/q/51837210
tags question: http://stackoverflow.com/q/51828454
type: Tag
tag name: amazon-web-services
tags question: http://stackoverflow.com/q/51930111
tags question: http://stackoverflow.com/q/51817865
tags question: http://stackoverflow.com/q/51945353
tags question: http://stackoverflow.com/q/51947006
tags question: http://stackoverflow.com/q/51951753
tags question: http://stackoverflow.com/q/51885291
tags question: http://stackoverflow.com/q/51852782
tags question: http://stackoverflow.com/q/51838602
tags question: http://stackoverflow.com/q/51870479
tags question: http://stackoverflow.com/q/51865887
tags question: http://stackoverflow.com/q/51805464
tags question: http://stackoverflow.com/q/51954052
tags question: http://stackoverflow.com/q/51943378
tags question: http://stackoverflow.com/q/51875676
tags question: http://stackoverflow.com/q/51914646
tags question: http://stackoverflow.com/q/51935082
tags question: http://stackoverflow.com/q/51834857
tags question: http://stackoverflow.com/q/51848045
tags question: http://stackoverflow.com/q/51863827
tags question: http://stackoverflow.com/q/51859032
tags question: http://stackoverflow.com/q/51911088
tags question: http://stackoverflow.com/q/51824459
tags question: http://stackoverflow.com/q/51915335
tags question: http://stackoverflow.com/q/51893481
tags question: http://stackoverflow.com/q/51818413
tags question: http://stackoverflow.com/q/51932084

http://stackoverflow.com/q/51810333
has title: TreeView not working in Python Gtk3
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/51812481
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/51812481
tagged with: gtk3
favorite count: 0
tagged with: python-3.x
tagged with: gtktreeview
tagged with: python
has body: So I have a GTk structure like: Window()> Grid()> Label() + ScrolledWindow()> TreeView() + Box()> Button() Everything works fine except th Scrolled Window is not Displayed correctly as seen below. I believe i am doing something wrong with the positioning or something. I tried playing around with the positioning numbers but can't make it work. My Code is: import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk index = None #Global variable holding the index of the final chosen subtitle class window(Gtk.Window): def __init__(self,data): Gtk.Window.__init__(self, title="SubseekerV7 R&D") self.set_border_width(5) self.set_default_size(200, 400) self.grid = Gtk.Grid() self.grid.set_column_homogeneous(True) self.grid.set_rowndex = None heading_text = Gtk.Label() heading_text.set_markup(' Choose Subtitle below \n\nSelect a subtitle and press Download\n') scrolled_window = Gtk.ScrolledWindow() scrolled_window.set_border_width(5) scrolled_window.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC) self.data_list_store = Gtk.ListStore(str,str,str, str) for item in data:self.data_list_store.append(list(item[:4])) self.data_tree_view = Gtk.TreeView(self.data_list_store) for i, col_title in enumerate(["Serial","Name", "Language", "Score",]): renderer = Gtk.CellRendererText() column = Gtk.TreeViewColumn(col_title, renderer, text=i) self.data_tree_view.append_column(column) scrolled_window.add_with_viewport(self.data_tree_view); buttons_box = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL,spacing=10) #Button Declarations self.submit_button = Gtk.Button(label="Download") self.submit_button.connect("clicked", self.select_handle) self.cancel_button = Gtk.Button(label="Cancel") self.cancel_button.connect("clicked", lambda x:self.destroy()) #Adding buttons to button box buttons_box.pack_start(self.submit_button, True , True , 0) buttons_box.pack_start(self.cancel_button, True , True , 0) self.grid.attach(heading_text, 0, 0, 4, 1) self.grid.attach(scrolled_win…
score: 2
type: AnsweredQuestion

http://stackoverflow.com/a/51912244
has body: For question 2, I'd require the prices in the new group (or service) form to be set. You can use a required drop down field, that is populated with a query of prices. A sketch of the group form may exemplify the point: class groupForm(forms.ModelForm): price = forms.ModelChoiceField(queryset=None, empty_label=None, required=True) ... def __init__(self, *args, **kwargs): super(groupForm, self).__init__(*args, **kwargs) self.fields['price'].queryset = self.instance.price_set.all()
type: Answer
answers question: http://stackoverflow.com/q/51910667
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51910667
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/51913841
has comment: http://stackoverflow.com/comment/90777701
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90777735
accepted answer: http://stackoverflow.com/a/51913879
tagged with: dataframe
has comment: http://stackoverflow.com/comment/90777698
tagged with: pandas
tagged with: function
linked to: http://stackoverflow.com/q/51914247
has title: Defining a function for changing column values and creating new datasets
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/90777720
has body: I am trying to define a function where it will take a dataframe and change values in a column to create multiple new dataframes. As an example, from df1 looking like: df1: class colB colC 0 1 1b 1c 1 2 2b 2c 2 3 3b 3c 3 4 4b 4c 4 5 5b 5c I am trying to create multiple binary classes to implement one-vs-all classification. So the function would create... df2: class colB colC 0 1 1b 1c 1 -1 2b 2c 2 -1 3b 3c 3 -1 4b 4c 4 -1 5b 5c df3: class colB colC 0 -1 1b 1c 1 1 2b 2c 2 -1 3b 3c 3 -1 4b 4c 4 -1 5b 5c df4: class colB colC 0 -1 1b 1c 1 -1 2b 2c 2 1 3b 3c 3 -1 4b 4c 4 -1 5b 5c and so on. All the unique values are an incremental value ranging from 1 to 120. Any thoughts? Thanks
tagged with: python
has answer: http://stackoverflow.com/a/51913879
score: 1
tagged with: classification
has comment: http://stackoverflow.com/comment/90777681
upvote count: 1

http://stackoverflow.com/a/51900527
type: Answer
upvote count: 0
score: -1
has body: You can use a breadth-first search: from collections import deque, defaultdict class Tree: def __init__(self, **kwargs): self.__dict__ = {i:kwargs.get(i) for i in ['left', 'right', 'value']} def __contains__(self, _val): if self.value != _val and self.left is None and self.right is None: return False return True if self.value == _val else any([_val in [[], self.left][self.left is not None], _val in [[], self.right][self.right is not None]]) def __lookup(self, _val, _depth = 0): if self.value == _val: return _depth return getattr(self, 'left' if _val in self.left else 'right').__lookup(_val, _depth+1) def __getitem__(self, _val): return self.__lookup(_val) def bfs(_head): _d = deque([_head]) _seen = [] _last = None _final_result = defaultdict(list) while _d: _current = _d.popleft() if _current.value not in _seen: _seen.append(_current.value) _r = list(filter(None, [getattr(_current, i, None) for i in ['left', 'right']])) _d.extend(_r) _final_result[_head[_current.value]].append(_current.value) marker = iter(range(len(_final_result))) return [i[::-1] if next(marker)%2 else i for _, i in sorted(_final_result.items(), key=lambda x:x[0])] When constructing the same tree in the example from the link in the question, the output is: t = Tree(value=3, left=Tree(value=9), right=Tree(value=20, left=Tree(value=15), right=Tree(value=7))) print(bfs(t)) Output: [[3], [20, 9], [15, 7]] This solution uses the breadth-first search to traverse the tree horizontally. However, since a (complete) binary tree has two children, only two values will be added to the queue. Therefore, in order to determine the current tree level the search has reached, a method to find the depth of a particular value has to be implemented in the tree (__getitem__ and __lookup).
downvote count: 1
answers question: http://stackoverflow.com/q/51889381

http://stackoverflow.com/q/51807560
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90574102
has comment: http://stackoverflow.com/comment/90570778
has comment: http://stackoverflow.com/comment/90572922
tagged with: math
has title: Simple DFT Coefficients => Amplitude/Frequencies => Plot
linked to: http://stackoverflow.com/q/4364823
has body: Im trying on DFT and FFT in Python with numpy and pyplot. My Sample Vector is x = np.array([1,2,4,3] The DFT coefficients for that vector are K = [10+0j, -3+1j, 0+0j, -3-1j] so basically we have 10, -3+i, 0 and -3-1i as DFT coefficients. My problem now is to get a combination of sin and cos to fit all 4 points. Let's assume we have a sample Rate of 1hz. This is my code : from matplotlib import pyplot as plt import numpy as np x = np.array([1,2,4,3]) fft = np.fft.fft(x) space = np.linspace(0,4,50) values = np.array([1,2,3,4]) cos0 = fft[0].real * np.cos(0 * space) cos1 = fft[1].real * np.cos(1/4 * np.pi * space) sin1 = fft[1].imag * np.sin(1/4 * np.pi * space) res = cos0 + cos1 + sin1 plt.scatter(values, x, label="original") plt.plot(space, cos0, label="cos0") plt.plot(space, cos1, label="cos1") plt.plot(space, sin1, label="sin1") plt.plot(space, res, label="combined") plt.legend() As result i get the plot: (source: heeser-it.de) Why isnt the final curve hitting any point? I would appreciate your help. Thanks! EDIT: N = 1000 dataPoints = np.linspace(0, np.pi, N) function = np.sin(dataPoints) fft = np.fft.fft(function) F = np.zeros((N,)) for i in range(0, N): F[i] = (2 * np.pi * i) / N F_sin = np.zeros((N,N)) F_cos = np.zeros((N,N)) res = 0 for i in range(0, N): F_sin[i] = fft[i].imag / 500 * np.sin(dataPoints * F[i]) F_cos[i] = fft[i].real / 500* np.cos(dataPoints * F[i]) res = res + F_sin[i] + F_cos[i] plt.plot(dataPoints, function) plt.plot(dataPoints, res) my plot looks like: (source: heeser-it.de) where do i fail?
has comment: http://stackoverflow.com/comment/90570329
type: Question
tagged with: numpy
answer count: 2
has comment: http://stackoverflow.com/comment/90570474
has answer: http://stackoverflow.com/a/51809286
tagged with: fft
has comment: http://stackoverflow.com/comment/90570762
has comment: http://stackoverflow.com/comment/90572206
score: 0
has comment: http://stackoverflow.com/comment/90571012
tagged with: python
has comment: http://stackoverflow.com/comment/90573213
has comment: http://stackoverflow.com/comment/90570895
tagged with: dft
has answer: http://stackoverflow.com/a/51807936

http://stackoverflow.com/a/55065322
upvote count: 25
has comment: http://stackoverflow.com/comment/110738362
type: Answer
has body: I got a similar error when trying to pass an image through a convolutional filter. Turns out it was solved as P-Gn said, simply by convert it to float. x = tf.cast(x, tf.float32)
score: 25
downvote count: 0
has comment: http://stackoverflow.com/comment/110913624
answers question: http://stackoverflow.com/q/51846682

http://stackoverflow.com/q/51846183
has answer: http://stackoverflow.com/a/51846665
tagged with: python
has body: I want to list related categories saved on a db field called "related" my code def category(request, slug): related = Article.objects.filter(slug__icontains=slug).values('related').first() return render(request,'category.html',{'related':related} y try with: option 1: In case of a return, a None on related I assign only the category Article.objects.filter(Q(slug__icontains=slug) | Q(category__icontains=slug)) option 2: if related is None: related = Article.objects.filter(category__icontains=slug).values('category').first() else: related = related.get('related').split(',') error: 'NoneType' object has no attribute 'get' In my DB I checked with the following query: SELECT * FROM `article` WHERE slug like '%internet%' And I get 0 records, so the error is coherent But I don't see how to assign in that case SELECT * FROM `article` WHERE category like '%internet%' where I have 22 results model: class Article(models.Model): category = models.CharField(max_length=2000, blank=True, null=True) related = models.CharField(max_length=2000, blank=True, null=True) text = models.CharField(max_length=2000, blank=True, null=True) slug= models.SlugField(max_length=255, unique=True) class Meta: managed = False db_table = 'article' def __str__(self): return u'%s %s %s %s' % (self.categoria,self.related, self.text, self.slug) option 3: Article.objects.filter(Q(slug__icontains=slug) | Q(category__icontains=slug)).values_list("related", flat=True).distinct() error too many values to unpack (expected 2) error line 37 with this: relateds = related.get('related').split(',') all the process: def category(request, slug): related = Article.objects.filter(Q(slug__icontains=slug) | Q(category__icontains=slug)).values('related').distinct() temp=[] for x in relateds: temp.append(x.replace(" ","-").replace("é","e")) relateds=temp
has answer: http://stackoverflow.com/a/51846384
has comment: http://stackoverflow.com/comment/90648475
type: UnansweredQuestion
tagged with: django
has title: How to fix error 500 from query None?
type: Question
has comment: http://stackoverflow.com/comment/90648336
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/90647996

http://stackoverflow.com/q/51876706
has body: I am trying to pass parameters using Ajax and Django 1.11 and getting the error Not Found: /enquiry/followup_alter/.Here is the code. Error: Not Found: /enquiry/followup_alter/ Ajax: $(document).ready(function () { $(".remove").click(function () { $(this).parents('tr').hide(); var a_href = $(this).attr('href'); $.ajax({ type:"GET", url:"/enquiry/followup_alter/", data:"id=" +a_href, success: function (response) { alert(response) } }); }); }) enquiry/urls.py: url(r'^followup_alter/id=(?P&lt;id&gt;[\d]+)/$', views.followup_alter), views.py: def followup_alter(request,id): get = Followup.objects.get(id = id) get.status = 1 get.save() return HttpResponse('Entry Removed') Please help!
has answer: http://stackoverflow.com/a/51881084
type: Question
has comment: http://stackoverflow.com/comment/90713524
accepted answer: http://stackoverflow.com/a/51881084
tagged with: javascript
tagged with: jquery
tagged with: ajax
has title: django Ajax GET url Not Found
downvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/90729242
tagged with: django
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/90713661
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/90729228

http://stackoverflow.com/comment/90779446
comment on: http://stackoverflow.com/q/51914767
score: 0
has text: Mentioning C++ does not make it a C++ question. Please tag only with what is most relevant to your post. If you click on the tags and visit their wiki pages, there will usually be useful documentation there to help you decide if the tag is appropriate.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90862569
score: 0
type: Comment
type: QuestionComment
has text: Hi, thank you very much. Yes, you are right, I should have used sql2 as a string, it was fine in my code, but I really forget that comma in cursor.execute function, if I type: cursor.execute(sql2, (first_name, second_name,)) it works fine.
comment on: http://stackoverflow.com/q/51939466

http://stackoverflow.com/a/51907466
score: 3
answers question: http://stackoverflow.com/q/51907224
has body: If you print response.css('.listing.listing-search.listing-data').extract() you will why are you getting that error, .extract() actually returns a list of str/unicode items, if you want to use css/xpath on returned list items, please do not use extract() so it will return you objects of Selector class. See below code, container = response.css('.listing.listing-search.listing-data') for items in container: bname = items.css('listing-name::text').extract() item = YpauItem() item['Business_Name'] = bname yield item
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51907224
type: Answer
upvote count: 3

http://stackoverflow.com/comment/90824278
type: QuestionComment
comment on: http://stackoverflow.com/q/51936437
score: 0
has text: @Mint find the code attached.
type: Comment

http://stackoverflow.com/q/51921926
has comment: http://stackoverflow.com/comment/90793691
has comment: http://stackoverflow.com/comment/90793773
accepted answer: http://stackoverflow.com/a/51922050
has comment: http://stackoverflow.com/comment/90793611
answer count: 2
has comment: http://stackoverflow.com/comment/90793599
possible better answer: http://stackoverflow.com/a/51921980
has comment: http://stackoverflow.com/comment/90794611
has comment: http://stackoverflow.com/comment/90793748
score: 0
has answer: http://stackoverflow.com/a/51922050
upvote count: 1
has answer: http://stackoverflow.com/a/51921980
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/90793590
has comment: http://stackoverflow.com/comment/90793594
has title: Convert strings into a list of integer
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
tagged with: list
has body: I need to vectorise a bunch of words and I'm searching the faster way to do it. Let's say I've the string "blahbla", it uses 4 different letters ["a", "b", "h", "l"]. I create a translation table {'a': 0, 'b': 1, 'h': 2, 'l': 3} (it will remains the same for all my words.) My goal is to convert this word to obtains: [1, 3, 0, 2, 1, 3, 0] I can do this: word = "blahbla" symbols = ["a", "b", "h", "l"] trans_table = {s: i for i, s in enumerate(symbols)} word = [trans_table[letter] for letter in word] But do you know a faster way ? Edit Has I said before, the table will remain the same, I've in reality the following table which is computed before processing all my words: symbols = [' ', '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', 'à', 'â', 'ç', 'è', 'é', 'ê', 'î', 'ï', 'ô', 'û', 'ü'] Which will stays the same for every word. Sorry if it was not clear.
type: Question

http://stackoverflow.com/comment/90725764
comment on: http://stackoverflow.com/a/51851866
type: AnswerComment
score: 0
has text: @DebanjanB- Sure, I will do
type: Comment

http://stackoverflow.com/a/51826335
type: Answer
upvote count: 3
answers question: http://stackoverflow.com/q/51826234
score: 3
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51826234
has body: You should using agg df.groupby('ID')['Var1','Var2'].agg(lambda x : x.values.tolist()) Out[576]: Var1 Var2 ID alpha [1, 2] [10, 10] bravo [3, 3] [12, 13] charlie [5, 5] [10, 11]

http://stackoverflow.com/a/51849341
accepted answer of: http://stackoverflow.com/q/51824443
score: 3
type: AcceptedAnswer
has body: atom is a library (not the popular editor) on top of which enaml is built. It basically provides low-memory footprint Python object and implements the observer pattern which allows to get notified when the value of an attribute change. When installing enaml pip should pull atom automatically. Atom currently lacks documentation but the basics are covered in the examples (https://github.com/nucleic/atom). Best Matthieu
downvote count: 0
answers question: http://stackoverflow.com/q/51824443
type: Answer
has comment: http://stackoverflow.com/comment/90655570
upvote count: 3

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

http://stackoverflow.com/comment/90696759
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51872534
has text: that's a strange way or running python code, please try running your code through terminal . Like doing `python nltk.py`
score: 0

http://stackoverflow.com/q/51943028
has answer: http://stackoverflow.com/a/51943790
tagged with: python
has title: "for" inside list/Zip
accepted answer: http://stackoverflow.com/a/51943790
upvote count: 1
downvote count: 1
type: Question
type: AnsweredQuestion
has body: In this code import random import numpy as np class Network(object): def __init__(self, sizes): """The list ``sizes`` contains the number of neurons in the respective layers of the network. For example, if the list was [2, 3, 1] then it would be a three-layer network, with the first layer containing 2 neurons, the second layer 3 neurons, and the third layer 1 neuron. The biases and weights for the network are initialized randomly, using a Gaussian distribution with mean 0, and variance 1. Note that the first layer is assumed to be an input layer, and by convention we won't set any biases for those neurons, since biases are only ever used in computing the outputs from later layers.""" self.num_layers = len(sizes) self.sizes = sizes self.biases = [np.random.randn(y, 1) for y in sizes[1:]] self.weights = [np.random.randn(y, x) for x, y in zip(sizes[:-1], sizes[1:])] def feedforward(self, a): """Return the output of the network if ``a`` is input.""" for b, w in zip(self.biases, self.weights): a = sigmoid(np.dot(w, a)+b) return a NN=Network([3,2,1]) i dont understand : self.biases = [np.random.randn(y, 1) for y in sizes[1:]] if NN.sizes[1:] is [2,1] then what is y?? the same for the next line self.weights = [np.random.randn(y, x) for x, y in zip(sizes[:-1], sizes[1:])] i dont understand either x nor how zip works here
score: 0
answer count: 1
favorite count: 0

http://stackoverflow.com/q/51915167
answer count: 1
has answer: http://stackoverflow.com/a/52167181
has body: I've created an application (Python 3.6) with cx_Freeze and when ran as a Python command or even the executable works totally fine. But if I make the application auto-boot on windows 10 (by creating shortcut in shell:startup) the log file it would create or write to raises PermissionError. I tried to create a workaround by checking if the file is locked, just add an increment number to the end of the file. This also works, if I manually make a log file read only, it will create the next one and so on. But with auto boot it raises RecursionError, so it has probably absolutely no way to write to the disk. Is there anyway without giving the application Run as administrator to be able to handle the magic of creating a log file when booting up? :)
tagged with: cx-freeze
score: 0
tagged with: boot
has title: cx_Freeze created executable has no write permission on boot
tagged with: windows-10
tagged with: permissions
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/13184414
type: Question

http://stackoverflow.com/q/51919772
has answer: http://stackoverflow.com/a/51919911
score: -3
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51919904
downvote count: 3
has body: How could I get this in the programm below?: dict_cars {1 : {'Mercedes':'E500'}},{ 2 : {'Ford' : 'Focus'}},{ 3 {'Toyota' : 'Celica'}} My current programm is not working and I don't know how to fix it :( dict_cars = {} attributes = {} car_number = input ('Insert car number: ') car_brand = input ('Insert car brand: ') car_model = input ('Insert car model: ') while car_number != 'end': dict_cars[car_number] = attributes dict_cars[car_number][car_brand] = car_model car_number = input ('Insert car number: ') car_brand = input ('Insert car brand: ') car_model = input ('Insert car model: ') Instead what I want, I get: Insert car number: 1 Insert car brand: Mercedes Insert car model: E500 Insert car number: 2 Insert car brand: Ford Insert car model: Focus Insert car number: 3 Insert car brand: Toyota Insert car model: Celica Insert car number: end Insert car brand: Insert car model: &gt;&gt;&gt; dict_cars {'1': {'Mercedes': 'E500', 'Ford': 'Focus', 'Toyota': 'Celica'}, '2'{'Mercedes': 'E500', 'Ford': 'Focus', 'Toyota': 'Celica'}, '3': {'Mercedes': 'E500', 'Ford': 'Focus', 'Toyota': 'Celica'}}
has answer: http://stackoverflow.com/a/51920232
has comment: http://stackoverflow.com/comment/90789461
type: Question
answer count: 3
upvote count: 0
has title: Dictionaries into dictionary python 3.7 windows
has answer: http://stackoverflow.com/a/51919904
favorite count: 0
possible better answer: http://stackoverflow.com/a/51919911

http://stackoverflow.com/comment/90607598
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/51825728
has text: In [4]: response.xpath('//li[ ./a[@class="curr"] ]/following-sibling::li[1]/a/@href').extract() Out[4]: []
score: 0

numeric
tags question: http://stackoverflow.com/q/51810762
tag name: numeric
type: Tag

http://stackoverflow.com/comment/90558573
type: Comment
type: QuestionComment
score: 0
has text: Sorry, my bad I'll edit
comment on: http://stackoverflow.com/q/51801126

http://stackoverflow.com/a/51901214
score: 1
accepted answer of: http://stackoverflow.com/q/51895999
answers question: http://stackoverflow.com/q/51895999
has body: It bothers about the shape because you will probably want to connect another layer to it. And its feature dimension will be the basis for the next layer to create its own weights. A layer can't have a variable size weight matrix, thus, it can't have a variable size feature input.
upvote count: 1
type: AcceptedAnswer
type: Answer
downvote count: 0

http://stackoverflow.com/comment/90721744
type: Comment
type: QuestionComment
has text: So we can assume that the array is always sorted in ascending order?
comment on: http://stackoverflow.com/q/51885086
score: 0

http://stackoverflow.com/comment/90655735
type: AnswerComment
has text: This is the best solution ;) + 1
type: Comment
comment on: http://stackoverflow.com/a/51851350
score: 0

data-fitting
tags question: http://stackoverflow.com/q/51813857
tags question: http://stackoverflow.com/q/51900396
type: Tag
tag name: data-fitting

http://stackoverflow.com/comment/90705317
type: Comment
has text: I have try to covert it by `str` method, like this `[i.update({"created": str(i.get("created"))}) for i in data]`, and it's works. Thank you for remind!
type: AnswerComment
comment on: http://stackoverflow.com/a/51877094
score: 0

http://stackoverflow.com/a/51876712
has body: Your insert method seems fine. The problems seems to be that you initialize self.head as an empty Node() but never update that node's data. Adding a repr method to Node as def __repr__(self): return "(%r, %r)" % (self.data, self.next) we see that after appending or inserting the numbers from range(10), the result looks like this: (None, (0, (1, (2, (3, (4, (5, (6, (7, (8, (9, None))))))))))) (9, (8, (7, (6, (5, (4, (3, (2, (1, (0, (None, None))))))))))) Instead, you should initialize self.head as None and add an accordant check to append: def __init__(self): self.head = None def append(self,data): if self.head is None: self.head = Node(data) else: cur = self.head while cur.next is not None: cur = cur.next cur.next = Node(data) Then, the result looks like this: (0, (1, (2, (3, (4, (5, (6, (7, (8, (9, None)))))))))) (9, (8, (7, (6, (5, (4, (3, (2, (1, (0, None)))))))))) You also have to adapt your display method as it skips the first element in the list, which is probably why you did not notice the bug for append. def display(self): node_elements = [] cur = self.head while cur is not None: node_elements.append(cur.data) cur = cur.next print(node_elements)
type: Answer
answers question: http://stackoverflow.com/q/51875669
upvote count: 1
type: AcceptedAnswer
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/51875669

http://stackoverflow.com/q/51953391
tagged with: python-multiprocessing
tagged with: multiprocessing
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51954301
has title: Does lock.acquire blocks processes in non critical section
tagged with: python
answer count: 1
accepted answer: http://stackoverflow.com/a/51954301
score: 0
has body: Maybe I didn't read the docs that well, but I didn't find more information about how lock's or rlock's aquire work ... does it block all processes no matter what statements those processes are on (even if they are on no critical sections).. or does it block only the processes trying to access the critical section Thank you !

http://stackoverflow.com/q/51940797
has answer: http://stackoverflow.com/a/51940878
type: AnsweredQuestion
type: Question
score: 0
linked to: http://stackoverflow.com/q/17157272
has body: I am learning 8.6. bisect — Array bisection algorithm, bisect.bisect_left(a, x, lo=0, hi=len(a)) has default values of lo=0, hi=len(a), When I checked the source code and found that hi=len(a) is not set as default directly, def bisect_right(a, x, lo=0, hi=None): if lo &lt; 0: raise ValueError('lo must be non-negative') if hi is None: hi = len(a) while lo &lt; hi: mid = (lo+hi)//2 if x &lt; a[mid]: hi = mid else: lo = mid+1 return lo It's achieved by a if check None. What's the benefit do extra checking than set it as default straightly?
has title: high=None advantage over high=len(a) in bisect.bisect_left
answer count: 1
duplicate of: http://stackoverflow.com/q/17157272
has comment: http://stackoverflow.com/comment/90831595
has comment: http://stackoverflow.com/comment/90831410
tagged with: python
accepted answer: http://stackoverflow.com/a/51940878
has comment: http://stackoverflow.com/comment/90831482

http://stackoverflow.com/comment/90653658
has text: This worked, in a way, given cgohlke's comment, I managed to install both pip and setuptools with `python -m easy_install pip==18.0` Now I can use pip, however, I still get the error of the question everytime I try to install something with pip
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51846520
type: Comment

http://stackoverflow.com/q/51844209
score: 0
answer count: 3
has comment: http://stackoverflow.com/comment/90641781
accepted answer: http://stackoverflow.com/a/51844305
has answer: http://stackoverflow.com/a/51844368
has answer: http://stackoverflow.com/a/51844305
has comment: http://stackoverflow.com/comment/90641821
tagged with: python
type: AnsweredQuestion
tagged with: list
tagged with: set
has answer: http://stackoverflow.com/a/51844279
type: Question
has title: Python set() and list() functions together
has body: Looking through some python code I encountered this line: x = list(set(range(height)) - set(array)) where array is just an int array. It's guaranteed that array's len is less than height. Could someone please explain me how does it work? Thanks!
possible better answer: http://stackoverflow.com/a/51844279

http://stackoverflow.com/comment/90725118
comment on: http://stackoverflow.com/q/51886842
has text: [`os.system`](https://docs.python.org/3/library/os.html#os.system) just returns an exit code—just the number 0 if it worked, some other number if there was an error. Is that really what you want? If not, do what the docs say and [use the `subprocess` module instead](https://docs.python.org/3/library/subprocess.html#subprocess-replacements).
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51842675
has comment: http://stackoverflow.com/comment/90720096
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90768681
answers question: http://stackoverflow.com/q/51829810
has comment: http://stackoverflow.com/comment/90773577
type: Answer
accepted answer of: http://stackoverflow.com/q/51829810
has comment: http://stackoverflow.com/comment/90732461
has comment: http://stackoverflow.com/comment/90771818
downvote count: 0
has comment: http://stackoverflow.com/comment/90768315
score: 1
has body: The problem is in the input shape of Input layer. An embedding layer accepts a sequence of integers as input which corresponds to words indices in a sentence. Since here the number of words in sentences is not fixed, therefore you must set the input shape of Input layer as (None,). I think you are mistaking it with the case that we don't have an Embedding layer in our model and therefore the input shape of the model is (timesteps, n_features) to make it compatible with LSTM layer. Update: You need to pass the decoder_inputs to the Embedding layer first and then pass the resulting output tensor to the decoder_lstm layer like this: decoder_inputs = model.input[1] # (Input(shape=(None,))) # pass the inputs to the embedding layer decoder_embedding = model.get_layer(name='dec_embedding')(decoder_inputs) # ... decoder_lstm = model.get_layer(name='dec_lstm') # dec_lstm decoder_outputs, state_h, state_c = decoder_lstm(decoder_embedding, ...) Update 2: In training time, when creating the decoder_lstm layer you need to set return_state=True: decoder_lstm, _, _ = LSTM(latent_dim, return_sequences=True, return_state=True, name='dec_lstm')(decoder_embedding, initial_state=encoder_states)
has comment: http://stackoverflow.com/comment/90756256
has comment: http://stackoverflow.com/comment/90771540
has comment: http://stackoverflow.com/comment/90771732
has comment: http://stackoverflow.com/comment/90764332
has comment: http://stackoverflow.com/comment/90735399
has comment: http://stackoverflow.com/comment/90771811
upvote count: 1

http://stackoverflow.com/q/51799650
has answer: http://stackoverflow.com/a/51800552
has comment: http://stackoverflow.com/comment/90557230
tagged with: python
upvote count: 4
type: AnsweredQuestion
type: Question
score: 3
has title: Python How to use DataFrame output in email body as Text
accepted answer: http://stackoverflow.com/a/51800577
tagged with: win32com
has answer: http://stackoverflow.com/a/51800577
answer count: 3
tagged with: pandas
possible better answer: http://stackoverflow.com/a/59896987
tagged with: email
downvote count: 1
has answer: http://stackoverflow.com/a/59896987
has body: I have a output of a dataframe Df , I am able to send it in mail as an attachment, but not able to print Df value in message body. Please advise to print my Df value in email body so I won't have to add attachment. import win32com.client as win32 outlook = win32.Dispatch('outlook.application') mail = outlook.CreateItem(0) mail.To = 'abc@xyg.com' mail.Subject = 'Madsaage Subject' mail.Body = 'print(Df)' mail.HTMLBody = 'Please Find Attached' # This field is optional # To attach a file to the email (optional): mail.Attachments.Add('C:/XYZ/transport.csv') mail.Send()
favorite count: 0

http://stackoverflow.com/q/51813308
tagged with: percentage
tagged with: random
type: AnsweredQuestion
score: 3
downvote count: 0
has answer: http://stackoverflow.com/a/51813455
possible better answer: http://stackoverflow.com/a/51813670
has title: Python Random choice with 'percentage'
has answer: http://stackoverflow.com/a/51813670
favorite count: 0
type: Question
tagged with: python
tagged with: dictionary
has body: Foreword It looks like it is a duplicate of few stackoverflow question but my situation is (probably) slightly unique. My situation I have a dictionary. The key is a string and the value is an integer. I want the python script to randomly choose N number of keys. The value is how likely it is to be chosen. The higher the key's value is, the higher the chance the key will be randomly chosen. My solution So using some other StackOverflow post and the power of the internet I managed to solve it using Weighted Random. DICT_VAR= {'best':308281009, 'good':7066325, 'meh':26884, 'bad':71, 'terrible':16, 'never':0} list_var = [] for i in DICT_VAR.keys(): list_var.extend([i]*DICT_VAR[i]) print random.sample(list_var, 2) # get 2 random choice I suppose The issue (the catch) As you may notice, the value in the dictionary can be incredibly big (It can be unlimitedly big) and it can also be as small as 0 (zero is smallest, there is no negative number). Running this code (with a little bigger numbers) resulted in my computer to freeze and be unresponsive until I hard reset it. My question How should I deal with the situation? Is there any other way of randomly choosing that is suitable for my situation since Weighted Random is the worst possible solution to this current case.
tagged with: biginteger
accepted answer: http://stackoverflow.com/a/51813455
upvote count: 3
answer count: 2

http://stackoverflow.com/q/51809922
has answer: http://stackoverflow.com/a/51809955
tagged with: python-3.7
type: Question
tagged with: python
tagged with: pycharm
score: 0
has body: Whenever I click run in pycharm, it returns the following error: "D:\Python\python.exe: can't find '__main__' module in 'D:/Python projects/Projects' Process finished with exit code 1" the images below are my pycharm settings, Please help me, sos! img1 run error img2 project interpreter setting img3 project structure setting img4 debugs configuration setting
answer count: 1
type: UnansweredQuestion
has title: pycharm, p3.6 running error :"D:\Python\python.exe: can't find '__main__' module in 'D:/Python projects/Projects'

azure-blob-storage
tags question: http://stackoverflow.com/q/51865769
tag name: azure-blob-storage
type: Tag

http://stackoverflow.com/a/51860194
type: Answer
answers question: http://stackoverflow.com/q/51860084
has body: I would suggest using dash. This link gives an example of making an editable plot similar to your requirements.
score: 0

http://stackoverflow.com/q/51940556
has comment: http://stackoverflow.com/comment/90831559
tagged with: finite-field
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/90833507
type: Question
has body: I'm using the gf256 library to do galois field math, and I have it in a numpy matrix. Though when calling np.linalg.inv() with it, it throws an error. That's the summary, here's the details: import numpy as np from gf256 import GF256 as gf npgf = np.vectorize(gf) arr = np.identity(4, np.uint8) * 10 gfarr = npgf(arr) After all this, gfarr looks like this array([[GF256(0b00001010), GF256(0b00000000), GF256(0b00000000), GF256(0b00000000)], [GF256(0b00000000), GF256(0b00001010), GF256(0b00000000), GF256(0b00000000)], [GF256(0b00000000), GF256(0b00000000), GF256(0b00001010), GF256(0b00000000)], [GF256(0b00000000), GF256(0b00000000), GF256(0b00000000), GF256(0b00001010)]], dtype=object) And np.linalg.inv(gfarr) throws this error Traceback (most recent call last): File "&lt;pyshell#152&gt;", line 1, in &lt;module&gt; np.linalg.inv(gfarr) File "[python3.6]\lib\site-packages\numpy\linalg\linalg.py", line 528, in inv ainv = _umath_linalg.inv(a, signature=signature, extobj=extobj) TypeError: No loop matching the specified signature and casting was found for ufunc inv The matrix is definitely invertable, and the GF256 class supports all the usual operators. Is it possible to make this work with numpy?
tagged with: numpy
answer count: 1
downvote count: 0
favorite count: 0
tagged with: galois-field
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90831543
tagged with: python
has answer: http://stackoverflow.com/a/68747748
has title: Numpy matrix inversion with objects

http://stackoverflow.com/a/51931154
downvote count: 0
has body: it seems that hummingbird environments (default spark environments) in specific have an old and outdated version of the lib preinstalled. I will open a ticket to upgrade the version of the lib on Hummingbird.
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/51906172
score: 1
accepted answer of: http://stackoverflow.com/q/51906172
type: AcceptedAnswer

http://stackoverflow.com/a/51801781
has comment: http://stackoverflow.com/comment/90608023
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90566107
has comment: http://stackoverflow.com/comment/93265265
type: Answer
has comment: http://stackoverflow.com/comment/90573912
has body: When using App Engine Standard with python 3.7, none of the google.xxx libraries are available. You have to build your own, or use standard Python libraries. This goes for: auth, users, images, search, mail, taskqueue, memcache, urlfetch, deferred, etc., and even the ndb datastore interface. For datastore, you use google-cloud-datastore or some 3rd party. For others, you use a standard Python library, e.g.: google.auth => rauth, google.appengine.api.memcache => python-memcached Read more here: https://cloud.google.com/appengine/docs/standard/python3/python-differences That page recommends Google Identity Platform or Firebase Authentication to do authorization.
has comment: http://stackoverflow.com/comment/90573791
accepted answer of: http://stackoverflow.com/q/51799366
upvote count: 2
answers question: http://stackoverflow.com/q/51799366
score: 2

http://stackoverflow.com/a/51918154
answers question: http://stackoverflow.com/q/51918136
has comment: http://stackoverflow.com/comment/90789016
type: Answer
has comment: http://stackoverflow.com/comment/90786288
has body: You can't use - in an attribute or variable name. Perhaps you mean normalized_losses?
score: 0

http://stackoverflow.com/q/51930384
has comment: http://stackoverflow.com/comment/90810866
favorite count: 0
has answer: http://stackoverflow.com/a/58877574
has comment: http://stackoverflow.com/comment/93029124
has comment: http://stackoverflow.com/comment/90819331
tagged with: in-place
tagged with: python
has comment: http://stackoverflow.com/comment/90811450
linked to: http://stackoverflow.com/q/29318459
score: 8
downvote count: 0
type: UnansweredQuestion
has body: I want to operate on numpy arrays to use their indexing, and I want to include the 0-dimensional case. Now I came across a strange situation, where a type conversion appears, if I don't use in-place multiplication: In [1]: import numpy as np In [2]: x = 1.*np.array(1.) In [3]: y = np.array(1.) In [4]: y *= 1. In [5]: x Out[5]: 1.0 In [6]: y Out[6]: array(1.) In [7]: type(x) Out[7]: numpy.float64 In [8]: type(y) Out[8]: numpy.ndarray Why is the type of x different to y? I know, that the inplace operations are differently implemented and they don't create a copy of the array, but I don't get the point, why the type is changed, if I multiply a 0d-array with a float? It works for 1d-arrays: In [1]: import numpy as np In [2]: x = np.array(1.) In [3]: y = np.array([1.]) In [4]: 1.*x Out[4]: 1.0 In [5]: 1.*y Out[5]: array([1.]) In [7]: type(1.*x) Out[7]: numpy.float64 In [8]: type(1.*y) Out[8]: numpy.ndarray I think, that's strange... Now I run into the following problem, where I would have to treat 0d-array separately: In [1]: import numpy as np In [2]: x = np.array(1.) In [3]: y = np.array(1.)*1. In [4]: x[x&gt;0] Out[4]: array([1.]) In [5]: y[y&gt;0] Out[5]: array([1.]) In [6]: x[x&gt;0] = 2. In [7]: y[y&gt;0] = 2. --------------------------------------------------------------------------- TypeError Traceback (most recent call last) &lt;ipython-input-7-5f9c5b138fc0&gt; in &lt;module&gt;() ----&gt; 1 y[y&gt;0] = 2. TypeError: 'numpy.float64' object does not support item assignment
has title: Numpy: strange different behavior of inplace and explicit operation
linked to: http://stackoverflow.com/q/773030
upvote count: 8
type: Question
tagged with: numpy
tagged with: numpy-ndarray
answer count: 1
tagged with: arrays
has comment: http://stackoverflow.com/comment/90810851
has comment: http://stackoverflow.com/comment/90810808

http://stackoverflow.com/a/51950144
answers question: http://stackoverflow.com/q/51948688
has body: Your param is named aliens_number (plural) but you're trying to use it as alien_number (singular). def create_alien(ai_settings, screen, aliens, aliens_number): # ... alien.x = alien_width + 2 * alien_width * alien_number
type: Answer
accepted answer of: http://stackoverflow.com/q/51948688
has comment: http://stackoverflow.com/comment/90850245
type: AcceptedAnswer
score: 0

http://stackoverflow.com/q/51906522
tagged with: python
upvote count: 0
has answer: http://stackoverflow.com/a/51906625
has comment: http://stackoverflow.com/comment/90763482
type: Question
score: -2
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/90763623
has comment: http://stackoverflow.com/comment/90763587
has comment: http://stackoverflow.com/comment/90763455
downvote count: 2
answer count: 1
has comment: http://stackoverflow.com/comment/90763479
favorite count: 0
has comment: http://stackoverflow.com/comment/90763498
has comment: http://stackoverflow.com/comment/90763563
has title: Python pyplot syntax error
has body: def Prediction2(): df = TCTDBt df = df.sort_values('time') print df plt.figure(figsize = (18,9)) plt.plot(range(df.shape[0]),(df['price']) plt.xticks(range(0,df.shape[0],100),(df['time'].loc[::100],rotation=45) plt.xlabel('time',fontsize=18) plt.ylabel('Price',fontsize=18) plt.show() Hey guys im getting a syntax error on the 7th line but have tried changing about every thing i can think of anyone see whats wrong? def Prediction2(): df = TCTDBt df = df.sort_values('time') print df plt.figure(figsize = (18,9)) plt.plot(range(df.shape[0]),(df['price'])) plt.xticks(range(0,df.shape[0],100),(df['time'].loc[::100],rotation=45)) plt.xlabel('time',fontsize=18) plt.ylabel('Price',fontsize=18) plt.show() think i applied your fixed still getting the syntax error
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90763519

http://stackoverflow.com/q/51949481
tagged with: widget
score: 1
has title: Cross Domain Widget Issue -- Python, PHP, Chrome, JavaScript
type: Question
tagged with: javascript
tagged with: jquery
tagged with: cross-domain
upvote count: 1
favorite count: 0
answer count: 0
downvote count: 0
has body: This should be a rather straight forward widget with the usual HTML js/div plugin code, but the issue here is that it won't display the echoed PHP code (output would be plain html on callback from the Python file in /cgi-bin/) within Chrome (the browser I'm testing on). When I run the python code below from the BASH shell it displays the echoed PHP code as plain HTML, but it is not displaying anything when I run the Plugin/HTML code below from within Chrome. cgi.force_redirect = 0 is set within php.ini, so that shouldn't be the issue. Chrome previously threw an error for the PHP code callback due to cgi-bin / php security, but it isn't throwing that error any more with that set in php.ini. No errors are showing up in Chrome when I run it now, but it just isn't displaying any of the HTML code that should be coming from the PHP echoed code (that should be displayed from the Python callback). There aren't any callback issues as it displays the JSONP when its set to display just a plain string through Python (non-PHP output). So, it's confirmed that it is working to display data across domains. I don't know Python very well at all, so that could be the issue here. It's a perplexing issue for me and I put in few days trying to figure this all out before coming here to the experts! Here is the Plugin/HTML code (included on a third party domain (cross domain), not example.com): Here is the JavaScript Code (widget.js): (function() { // Localize jQuery variable var jQuery; /******** Load jQuery if not present *********/ if (window.jQuery === undefined) { var script_tag = document.createElement('script'); script_tag.setAttribute("type","text/javascript"); script_tag.setAttribute("src", "https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"); if (script_tag.readyState) { script_tag.onreadystatechange = function () { // For old versions of IE if (this.readyState == 'complete' || this.readyState == 'loaded') { scriptLoadHandler(); } }; } else { script_tag.onload = sc…
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/78727608
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/51887784
upvote count: 1
type: Answer
has body: To get this to work for me on Windows 10, behind a corporate proxy, and specifically in the Windows Subsystem for Linux (WSL) using Ubuntu I had to not only set the proxy parameter in the session.get call (as the accepted answer here describes), but I had to additionally set the SSL context. Otherwise, an incorrect CA bundle would be used resulting in an SSL Certificate Verify Failed error. For example: import aiohttp import ssl url = 'https://example.com' proxy_url = 'http://&lt;user&gt;:&lt;pass&gt;@&lt;proxy&gt;:&lt;port&gt;' path_to_cafile = '/etc/ssl/certs/ca-certificates.crt' ssl_ctx = ssl.create_default_context(cafile=path_to_cafile) async with aiohttp.ClientSession() as session: async with session.get(url, proxy=proxy_url, ssl=ssl_ctx)

http://stackoverflow.com/comment/90827357
has text: I do indeed have a writer.save()
type: Comment
comment on: http://stackoverflow.com/q/51938509
score: 0
type: QuestionComment

http://stackoverflow.com/q/51822269
has comment: http://stackoverflow.com/comment/90598471
has comment: http://stackoverflow.com/comment/90598405
accepted answer: http://stackoverflow.com/a/51823391
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90599024
has title: Type Error while using for loop in list of dictionaries in Python
tagged with: parsing
type: Question
has comment: http://stackoverflow.com/comment/90599518
tagged with: python
tagged with: dictionary
has body: I'm getting an error while using that structure on Python 3.6 while parsing data from a json file: for topic in data: cqas = [{'context': paragraph['context'], 'id': qa['id'], 'question': qa['question'], 'answer': qa['answers'][0]['text'], 'answer_start': qa['answers'][0]['answer_start'], 'answer_end': qa['answers'][0]['answer_start'] + \ len(qa['answers'][0]['text']) - 1, 'topic': topic['title'] } for paragraph in topic['paragraphs'] for qa in paragraph['qas']] I couldn't find a documentation about using for loops in list of dicts as mentioned above. I want to learn it because I'm also getting an error message when using that structure: Dataset: https://raw.githubusercontent.com/YerevaNN/R-NET-in-Keras/master/data/dev-v1.1.json
tagged with: list
has answer: http://stackoverflow.com/a/51823391
score: 0
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/90598602
has comment: http://stackoverflow.com/comment/90600335
answer count: 1

http://stackoverflow.com/comment/90610864
type: QuestionComment
score: 1
has text: As a side note (this isn't the problem you're asking about, but it is a problem you need to fix), the `grid` method returns `None`, so your variables `logo`, `button`, etc. aren't `Label`, `Button`, etc. objects, they're just all `None`. If you want to store a widget in a variable for later, you have to assign the widget to the variable, then call `grid` on the variable, as two separate statements.
comment on: http://stackoverflow.com/q/51828078
type: Comment

countvectorizer
type: Tag
tags question: http://stackoverflow.com/q/51884050
tag name: countvectorizer
tags question: http://stackoverflow.com/q/51873851

http://stackoverflow.com/comment/90709426
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51878966
has text: Seems like you want to replace _number_ with _1_? If so simply go with `url1.replace('number', number)`. If that's not your intention, please refine your question.

http://stackoverflow.com/comment/90720593
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51884373
type: Comment
has text: Thanks! This is close, but I need more than one group clustered, such as 1 &2 or 2 & 3. Another alternative would be TimeSeriesSplit, but that is essentially would you are proposing.

http://stackoverflow.com/comment/92078284
comment on: http://stackoverflow.com/a/52459266
has text: Then you just need to add an argument to the middleware the param. I will update the answer.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/51905730
type: Answer
downvote count: 0
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/90762072
answers question: http://stackoverflow.com/q/51905686
type: AcceptedAnswer
has body: plt.plot returns an matplotlib.AxesSubplot object or an array of them, depending on what you're plotting. If you're running that command in an interactive environment, and don't want its output dumped to output when run, you can either assign to a dummy variable or suppress with a semi-colon, but the latter isn't really pythonic. If you're running a script, it makes no difference, because nothing is printed to stdout unless explicitly printed.
accepted answer of: http://stackoverflow.com/q/51905686

http://stackoverflow.com/comment/90774132
score: 0
type: Comment
type: QuestionComment
has text: Not quite sure what the issue could be. Maybe open a new question, someone else will figure it out?
comment on: http://stackoverflow.com/q/51906709

http://stackoverflow.com/a/51954741
downvote count: 0
score: 1
has body: Abarnet pointed out one fix however in Tkinter it might be better to inherit from the Tkinter class Tk to start you GUI. Take this example. A much smaller amount of code and produces the same results desired. import tkinter as tk class MyGUI(tk.Tk): def __init__(self, colour): tk.Tk.__init__(self) self.geometry('300x100') self.title('Login') tk.Label(self, fg=colour, text="Sample Text", width=45, pady=10).grid(row=0, column=0) tk.Button(self, text="Retry", command=self.do_something, height=2, width=18).grid(row=1, column=0) def do_something(self): print('ok') MyGUI("Blue").mainloop() Results:
answers question: http://stackoverflow.com/q/51954359
upvote count: 1
type: Answer

http://stackoverflow.com/q/51899618
answer count: 0
score: 1
upvote count: 1
has body: My teacher told me that purchase_list=my_list is passing by reference/address. For example: my_list = ['pen' , 'pencil' , 'cell phone' , 'axiom team' , 'panacloud' ] purchase_list = my_list my_list.append('x') print(my_list) print(purchase_list) gives the following output ['pen', 'pencil', 'cell phone', 'axiom team', 'panacloud', 'x'] ['pen', 'pencil', 'cell phone', 'axiom team', 'panacloud', 'x'] then why is that when i do the following: my_list = ['pen' , 'pencil' , 'cell phone' , 'axiom team' , 'panacloud' ] purchase_list = my_list my_list=["Naufil"] print(my_list) print(purchase_list) gives me output: ['Naufil'] ['pen', 'pencil', 'cell phone', 'axiom team', 'panacloud'] and doesn't ['Naufil'] ['Naufil']
type: Question
has title: Why making changes in a passed by reference list doesn't make changes in the other list
linked to: http://stackoverflow.com/q/8463907
has comment: http://stackoverflow.com/comment/90750881
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/90750272
has comment: http://stackoverflow.com/comment/90750401
has comment: http://stackoverflow.com/comment/90762598
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/29926485
has comment: http://stackoverflow.com/comment/90762940
duplicate of: http://stackoverflow.com/q/8463907
has comment: http://stackoverflow.com/comment/90750969
tagged with: python
has comment: http://stackoverflow.com/comment/90903496
tagged with: pass-by-reference
tagged with: list

http://stackoverflow.com/q/51889225
has body: I have a sample list of strings: my_list = ['hello','this','is','a','sample','list', 'thanks', 'for', 'help'] And I want to club every three elements together, like: new_list = ['hello this is', 'a sample list', 'thanks for help']
tagged with: string-concatenation
score: 0
has answer: http://stackoverflow.com/a/51889320
has answer: http://stackoverflow.com/a/51889257
has answer: http://stackoverflow.com/a/51889342
answer count: 4
tagged with: python-3.x
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51889428
tagged with: python
has title: How to club certain parts of list: Python
tagged with: list
linked to: http://stackoverflow.com/q/2233204
type: Question

http://stackoverflow.com/comment/90913041
has text: Thanks for this
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/51938735

http://stackoverflow.com/comment/90782436
type: Comment
type: QuestionComment
has text: @Aran-Fey I've been stuck on this for two days before I came here, all I know is I have an unsorted list and a sorted list, I need to check each element of the unsorted list against the sorted list and return a new list with the elements that matched using a binary search.
score: 0
comment on: http://stackoverflow.com/q/51916029

http://stackoverflow.com/a/51870857
answers question: http://stackoverflow.com/q/51870662
score: 5
type: AcceptedAnswer
has body: You are encountering a Connection Error from the requests library(pygerrit2 is dependent on requests) - it is occurring because your connection is timing out. To avoid this I recommend using a library like backoff. Backoff will catch this connection Error and retry establishing the connection. This is done easily with a decorator and an import. from requests.auth import HTTPDigestAuth from pygerrit2 import GerritRestAPI, HTTPBasicAuth import backoff import requests @backoff.on_exception(backoff.expo, requests.exceptions.ConnectionError, max_time=10) def makeGerritAPICall(): auth = HTTPBasicAuth('user', 'password') rest = GerritRestAPI(url='https://xxx.xx.xxx.xxx.com/', auth = auth) changes = rest.get("changes/?q=is:open&amp;q=is:close&amp;q=all&amp;o=DETAILED_ACCOUNTS&amp;o=ALL_REVISIONS&amp;o=ALL_COMMITS&amp;o=ALL_FILES&amp;o=MESSAGES", headers={'Content-Type': 'application/json'}) The following function will retry making any request that encounters a ConnectionError for 10 seconds before failing and raising a ConnectionError. I would recommend visiting the backoff git README docs as they contain tons of useful info about backoff.
has comment: http://stackoverflow.com/comment/112493650
upvote count: 5
type: Answer
accepted answer of: http://stackoverflow.com/q/51870662
downvote count: 0

http://stackoverflow.com/comment/90781695
has text: Those differences are statistically insignificant
comment on: http://stackoverflow.com/q/51915690
type: Comment
type: QuestionComment
score: 6

http://stackoverflow.com/a/51884548
type: Answer
score: 2
answers question: http://stackoverflow.com/q/51884416
has body: To answer the question in the title, no. sys.stdout, the stream print writes to, is usually line buffered though (though that shouldn't matter in this case, as print writes a newline character (unless told not to)), and is shared between threads and subprocesses (unless explicitly unshared). Without knowing more about the code around this, it's hard to say more. (Who knows, maybe you have a background thread somewhere in there that sneakily changes submission.id?) EDIT: The new information in the original post, namely that print('Submission being evaluated:', submission.id) is being printed, not print(submission.id) is critical. Each argument of a print() call is printed atomically, but if two processes or threads are print()ing simultaneously, let's say print('a', 'b'), it's entirely possible that you get a a b b instead of a b a b.
upvote count: 2
has comment: http://stackoverflow.com/comment/90721461
downvote count: 0
has comment: http://stackoverflow.com/comment/90720728

http://stackoverflow.com/a/51857856
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 3
accepted answer of: http://stackoverflow.com/q/51857815
score: 3
answers question: http://stackoverflow.com/q/51857815
has body: Make the attributes into a list and iterate through it: for attr in ['a', 'b', 'c', 'd']: try: result = getattr(o, attr) except AttributeError: # Try the next one continue break else: raise ValueError("No attribute found") Apparently, the list can also be constructed dynamically.

http://stackoverflow.com/q/51915741
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/51915965
tagged with: python
tagged with: lambda
has answer: http://stackoverflow.com/a/51915965
tagged with: tkinter
type: Question
has comment: http://stackoverflow.com/comment/90781789
type: AnsweredQuestion
has title: Why tkinter-buttons do all disable?
has body: I am following a beginner's Python guide book and I am stuck with one particular task with tkinter. I've followed the code from the book but it still does not seem to work properly: The purpose is to make a guessing game where buttons are pressed two times. If the user finds two same symbols after guessing two times in a row, those buttons/symbols are disabled and stay visible. In other case, they are hidden and guessing starts again. Problem is: After pressing the buttons they all stay visible. Please see attachment. Screenshot of outcome For doing this code I am using Jupyter Notebook 5.5.0 which has worked well with other exercises in the book. I was wondering if it is about the notebook (also the graphics look different here than in the book) I am using or just a bug in the code? Thanks in advance! import random import time from tkinter import Tk, Button, DISABLED def show_symbol(x, y): global first global previousX, previousY buttons[x, y]["text"] = button_symbols[x, y] buttons[x, y].update_idletasks() if first: previousX = x previousY = y first = False elif previousX != x or previousY != y: if buttons[previousX, previousY]["text"] != buttons[previousX, previousY]["text"]: time.sleep(0.5) buttons[previousX, previousY]["text"] = "" buttons[x, y]["text"] = "" else: buttons[previousX, previousY]["command"] = DISABLED buttons[x, y]["command"] = DISABLED first = True root = Tk() root.title("Find a pair") root.geometry("500x500") root.resizable(width=False, height=False) buttons = {} first = True previousX = 0 previousY = 0 button_symbols = {} symbols = [u"✂", u"✂", u"✅", u"✅", u"✈", u"✈", u"✉", u"✉", u"✊", u"✊", u"✋", u"✋", u"✌", u"✌", u"✏", u"✏", u"✒", u"✒", u"✔", u"✔", u"✖", u"✖", u"✨", u"✨"] random.shuffle(symbols) for x in range(6): for y in range(4): button = Button(command=lambda x=x, y=y: show_symbol(x, y), width=3, height=3) button.grid(column=x, row=y) buttons[x, y] = button button_symbols[x, y] = symbols.pop() root.mainloop()

http://stackoverflow.com/comment/90617115
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51821919
score: 0
has text: Are you stuck on the "Exchange the key for an access token and send a notification" step?

http://stackoverflow.com/comment/90814071
has text: Possible duplicate of [Programmatically get current Ipython notebook cell output?](https://stackoverflow.com/questions/27952428/programmatically-get-current-ipython-notebook-cell-output)
comment on: http://stackoverflow.com/q/51931874
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51818413
answer count: 1
tagged with: amazon-web-services
has comment: http://stackoverflow.com/comment/90596607
tagged with: snapshot
has comment: http://stackoverflow.com/comment/90598347
tagged with: python
has body: I have piece of code for source and destination regions. I managed to have a reponse with all snapshot data but I can't manage to filter the response just to "SnapshotId" and copying it. import boto3 REGIONS = ['eu-central-1', 'eu-west-3'] SOURCEREG = boto3.client('ec2', region_name='eu-central-1') DISTREG = boto3.client('ec2', region_name='eu-west-3') response = SOURCEREG.describe_snapshots() print(response) In this case I receive a json response looking like {'OwnerId': 'xxxxxxx', 'StartTime': datetime.xxxxxxxx, 'SnapshotId': 'snap-xxxxxxxxxx", etc .....}. How can i filter this output and copy the snapshots?
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51822407
has comment: http://stackoverflow.com/comment/90599032
type: Question
has title: Copying AWS Snapshots using boto3
tagged with: boto3
accepted answer: http://stackoverflow.com/a/51822407
score: 0

http://stackoverflow.com/comment/90836102
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51932604
has text: Your solution is fantastic, just one more question, how can I print in the template the machine utilized in the previous cycle? I'll do an example in the question. thankyou

http://stackoverflow.com/comment/90594350
has text: What is the value of `url`?
score: 0
comment on: http://stackoverflow.com/q/51820281
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90618778
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51824191
has text: I would try binding the `self.display_warning_voice` to the `on_open` event from the `Popup`.
score: 0

http://stackoverflow.com/comment/115905356
has text: In the result of openssl command, CN = Common name, O = Organization, OU = Organization Unit, L = Locality, C = Country, S = State, ref link https://docs.oracle.com/cd/E24191_01/common/tutorials/authz_cert_attributes.html
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/64835339
score: 0

http://stackoverflow.com/comment/90577938
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51811060
has text: Can you share your Dockerfile and the `setup.sh` script? This fragment of a Compose file on its own isn't a [mcve]. To me the `volumes: [/usr/src/app]` line looks strange (and will cause Docker to overwrite whatever's in the image with an implicit volume, which could be a source of differences).
score: 0

http://stackoverflow.com/a/51841029
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/51840328
has body: First of all, for more information on python internal floating point arithmetic read this. Because your example uses the same values (Rounding 2.675 and getting 2.67 but you expect 2.68), you maybe already read this document. Now I try to answer some of your questions: Q: Is it possible to create code that checks...? A: Yes, but you need to use some other arithmetic than float. In your case if you want to check why the value is rounded down you can view the float representation of the value with the decimal module. You write "79.705 should have one according to the results, but it doesn't truly." That is not correct: &gt;&gt;&gt; from decimal import Decimal &gt;&gt;&gt; t = 79.695 &gt;&gt;&gt; print (Decimal(t)) 79.69499999999999317878973670303821563720703125 As you can see, the internal float representation differs from the decimal value, because python already rounds if you use something like 'print' on those values. This module can also be used for decimal floating point arithmetic if the 'normal' binary floating point arithmetic is not good enough. The question is, why do you want a list with such numbers? Because most of the time, the representation error is no problem at all. There are only some cases where you have to think about that problem.
downvote count: 0
type: Answer

http://stackoverflow.com/q/51839409
answer count: 1
favorite count: 0
tagged with: tkinter
has comment: http://stackoverflow.com/comment/90638218
has body: In my code I have got it to work by adding up the amount of drinks I want to buy however when trying to add code so that if they type yes into the takeaway entry box it will add 5% on to the total. I have added it within a def using an if statement however it doesn't seem to be registering that that define exists. I added a print('hi') after it and even that doesn't show up. I'm quite new to python and after looking quite a lot i don't know what to do. Also i know that my code is probably really badly organised and messy but I don't know how to fix this. Any help would be greatly appreciated. Here is my entire code its not too long the main problem is the def Takeaway() does not register when running the program. from tkinter import* import random import time import datetime root=Tk() root.geometry("1600x8000") root.title("Cafe au Lait") Tops=Frame(root, width=1600,relief=SUNKEN) Tops.pack(side=TOP) f1=Frame(root,width=800,height=700,relief=SUNKEN) f1.pack(side=LEFT) localtime=time.asctime(time.localtime(time.time())) lblInfo=Label(Tops,font=('helvetica',50,'bold'),text="Cafe au Lait ",fg="Black",bd=10,anchor='w') lblInfo.grid(row=0,column=0) lblInfo=Label(Tops,font=('arial',20,'bold'),text=localtime,fg="Steel Blue",bd=10,anchor='w') lblInfo.grid(row=1,column=0) def Ref(): x=random.randint(10908,500876) randomRef=str(x) rand.set(randomRef) if (Latte.get()==""): CoL=0 else: CoL=float(Latte.get()) if (Iced.get()==""): CoI=0 else: CoI=float(Iced.get()) if (FlatWhite.get()==""): CoFW=0 else: CoFW=float(FlatWhite.get()) if (DoubleExpresso.get()==""): CoDE=0 else: CoDE=float(DoubleExpresso.get()) if (Cappacuino.get()==""): CoC=0 else: CoC=float(Cappacuino.get()) if (Expresso.get()==""): CoE=0 else: CoE=float(Expresso.get()) CostofLatte =CoL * 3.5 CostofIced =CoI * 2.5 CostofFlatWhite =CoFW* 3.75 CostofDoubleExpresso =CoDE * 4.25 CostofCappacuino =CoC* 3.75 CostofExpresso =CoE * 3 CostofMeal= "$", str('%.2f' % (CostofLatte+CostofIced+CostofFlatWhite+CostofDoubleExpresso+Co…
has comment: http://stackoverflow.com/comment/90638147
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/90637239
has comment: http://stackoverflow.com/comment/90637370
type: AnsweredQuestion
score: 1
has title: I am very stuck in how to add takeaway option as define isn't working
has answer: http://stackoverflow.com/a/51843257
type: Question
has comment: http://stackoverflow.com/comment/90638100
has comment: http://stackoverflow.com/comment/90637024
downvote count: 0
accepted answer: http://stackoverflow.com/a/51843257

http://stackoverflow.com/a/51861341
has comment: http://stackoverflow.com/comment/90675101
has body: The problem occurs because at the time when MySubclass.say() is called, the global symbol MySubclass no longer refers to what's defined in your code as 'class MySubclass'. It is an instance of WrapperClass, which isn't in any way related to MySubclass. If you are using Python3, you can get around this by NOT passing any arguments to 'super', like this: super().say(x.upper()) I don't really know why you use the specific construct that you have, but it does look strange that a sub-class of MyClass that defines 'say()' - and has itself a 'say()' method in the source code would have to end up as something that does not have that method - which is the case in your code. Note you could change the class WrapperClass line to make it read class WrapperClass(cls): this will make your wrapper a sub-class of the one you just decorated. This doesn't help with your super(SubClass, self) call - you still need to remove the args (which is OK only on Python3), but at least an instance created as x=MySubclass() would have a 'say' method, as one would expect at first glance. EDIT: I've come up with a way around this, but it really looks odd and has the disadvantage of making the 'wrapped' class know that it is being wrapped (and it becomes reliant on that, making it unusable if you remove the decorator): def class_decorator(cls): class WrapperClass(object): def make_instance(self): i = cls() i._wrapped = cls return i return WrapperClass class MyClass(object): def say(self, x): print(x) @class_decorator class MySubclass(MyClass): def say(self, x): super(self._wrapped, self).say(x.upper()) # make_instance returns inst of the original class, non-decorated i = MySubclass().make_instance() i.say('hello') In essence, _wrapped saves a class reference as it was at declaration time, consistent with using the regular super(this_class_name, self) builtin call.
downvote count: 0
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51860397

http://stackoverflow.com/a/56733962
answers question: http://stackoverflow.com/q/51821537
downvote count: 0
type: Answer
score: 5
upvote count: 5
has body: I had a similar issue, but with different architecture. As people suggested, it's important not to mix keras with tensorflow.keras, so try swapping code like: from keras.preprocessing import image from keras.models import Model from keras.layers import Dense, GlobalAveragePooling2D from keras import backend as K to: from tensorflow.keras.preprocessing import image from tensorflow.keras.models import Model from tensorflow.keras.layers import Dense, GlobalAveragePooling2D from tensorflow.keras import backend as K Also make sure, you don't use keras.something inside your code (not only imports) as well, hope it helps : ) Also, I used Keras 2.2.4 with tensorflow 1.10.0

centroid
tags question: http://stackoverflow.com/q/51916239
type: Tag
tag name: centroid

http://stackoverflow.com/a/51938897
has comment: http://stackoverflow.com/comment/90850539
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/51821919
downvote count: 0
has comment: http://stackoverflow.com/comment/90873550
score: 1
has body: Try this: import io import json import requests from google.oauth2 import service_account import google.auth.transport.requests PATH_TO_SERVICE_ACCOUNT = 'path/to/json/service/account' REQUIRED_SCOPE = 'https://www.googleapis.com/auth/actions.fulfillment.conversation' # Get access token with io.open(PATH_TO_SERVICE_ACCOUNT, 'r', encoding='utf-8') as json_fi: credentials_info = json.load(json_fi) credentials = service_account.Credentials.from_service_account_info( credentials_info, scopes=[REQUIRED_SCOPE]) request = google.auth.transport.requests.Request() credentials.refresh(request) headers = { 'Authorization': 'Bearer: ' + credentials.token } payload = {'customPushMessage': { 'userNotification': { 'title': '&lt;NOTIFICATION_TITLE&gt;', }, 'target': { 'userId': '&lt;USER_ID&gt;', 'intent': '&lt;INTENT&gt;', # Expects a IETF BCP-47 language code (i.e. en-US) 'locale': '&lt;LOCALE&gt;' }, } } r = requests.get('https://actions.googleapis.com/v2/conversations:send', json=payload, headers=headers) print(str(r.status_code) + ': ' + r.text)
has comment: http://stackoverflow.com/comment/90850645

matplotlib
tags question: http://stackoverflow.com/q/51906756
tags question: http://stackoverflow.com/q/51939224
tags question: http://stackoverflow.com/q/51898101
tags question: http://stackoverflow.com/q/51834448
tags question: http://stackoverflow.com/q/51866626
tags question: http://stackoverflow.com/q/51914837
tags question: http://stackoverflow.com/q/51945430
tags question: http://stackoverflow.com/q/51928455
tags question: http://stackoverflow.com/q/51900874
tags question: http://stackoverflow.com/q/51856572
tags question: http://stackoverflow.com/q/51952608
tags question: http://stackoverflow.com/q/51801143
tags question: http://stackoverflow.com/q/51868644
tags question: http://stackoverflow.com/q/51899112
tags question: http://stackoverflow.com/q/51902156
tags question: http://stackoverflow.com/q/51925135
tags question: http://stackoverflow.com/q/51862593
tags question: http://stackoverflow.com/q/51861787
tags question: http://stackoverflow.com/q/51827536
tags question: http://stackoverflow.com/q/51844984
tags question: http://stackoverflow.com/q/51806090
tags question: http://stackoverflow.com/q/51859000
tags question: http://stackoverflow.com/q/51900272
tags question: http://stackoverflow.com/q/51810492
tags question: http://stackoverflow.com/q/51876166
tags question: http://stackoverflow.com/q/51849978
tag name: matplotlib
tags question: http://stackoverflow.com/q/51941029
tags question: http://stackoverflow.com/q/51940997
tags question: http://stackoverflow.com/q/51809886
tags question: http://stackoverflow.com/q/51897361
tags question: http://stackoverflow.com/q/51872583
tags question: http://stackoverflow.com/q/51865607
tags question: http://stackoverflow.com/q/51935960
tags question: http://stackoverflow.com/q/51919113
tags question: http://stackoverflow.com/q/51906131
tags question: http://stackoverflow.com/q/51847488
tags question: http://stackoverflow.com/q/51874832
tags question: http://stackoverflow.com/q/51937267
tags question: http://stackoverflow.com/q/51897979
tags question: http://stackoverflow.com/q/51849219
tags question: http://stackoverflow.com/q/51949185
tags question: http://stackoverflow.com/q/51909503
tags question: http://stackoverflow.com/q/51910697
tags question: http://stackoverflow.com/q/51816869
tags question: http://stackoverflow.com/q/51821793
tags question: http://stackoverflow.com/q/51871873
tags question: http://stackoverflow.com/q/51885703
tags question: http://stackoverflow.com/q/51890625
tags question: http://stackoverflow.com/q/51823023
tags question: http://stackoverflow.com/q/51941038
tags question: http://stackoverflow.com/q/51824174
tags question: http://stackoverflow.com/q/51900185
tags question: http://stackoverflow.com/q/51831634
tags question: http://stackoverflow.com/q/51824188
tags question: http://stackoverflow.com/q/51809017
tags question: http://stackoverflow.com/q/51890425
tags question: http://stackoverflow.com/q/51937381
tags question: http://stackoverflow.com/q/51850421
tags question: http://stackoverflow.com/q/51919953
tags question: http://stackoverflow.com/q/51798943
tags question: http://stackoverflow.com/q/51871420
tags question: http://stackoverflow.com/q/51943095
tags question: http://stackoverflow.com/q/51940509
tags question: http://stackoverflow.com/q/51904191
tags question: http://stackoverflow.com/q/51828205
tags question: http://stackoverflow.com/q/51870028
tags question: http://stackoverflow.com/q/51868613
tags question: http://stackoverflow.com/q/51849871
tags question: http://stackoverflow.com/q/51843313
tags question: http://stackoverflow.com/q/51850537
tags question: http://stackoverflow.com/q/51848454
tags question: http://stackoverflow.com/q/51807875
tags question: http://stackoverflow.com/q/51910306
tags question: http://stackoverflow.com/q/51840390
tags question: http://stackoverflow.com/q/51945745
tags question: http://stackoverflow.com/q/51840708
tags question: http://stackoverflow.com/q/51868628
tags question: http://stackoverflow.com/q/51841679
tags question: http://stackoverflow.com/q/51871426

http://stackoverflow.com/comment/90844284
comment on: http://stackoverflow.com/a/51947122
has text: Thank you for your efforts. I managed to accomplish the task with overriding the `__init__` method and manipulate the fields. But neither that nor your proposal looks very elegant and is obfuscating.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/90595251
comment on: http://stackoverflow.com/q/51818387
type: Comment
score: 0
has text: So this would be the right way to do it? https://pastebin.com/6UPvzWSd
type: QuestionComment

http://stackoverflow.com/comment/90759008
comment on: http://stackoverflow.com/q/51901250
score: 0
type: Comment
type: QuestionComment
has text: Please format your code examples with Markdown as described [here](https://stackoverflow.com/editing-help).

http://stackoverflow.com/q/51907340
tagged with: machine-learning
upvote count: 1
tagged with: scipy
type: Question
has answer: http://stackoverflow.com/a/51938187
downvote count: 0
answer count: 1
tagged with: scikit-learn
tagged with: kdtree
favorite count: 0
has title: Finding Kneighbors in sklearn using KDtree with multiple target variables with multiple search criteria
has body: Lets say this is my simple KD tree alogrithm that I am implementing def Test(): features = np.random.random((10, 2)) X = np.array(features[0:2]) print(X) tree = KDTree(features, leaf_size=40) indic = tree.query_radius(X, r= 0.1) counter = 0 for i in indic: a = (features[i]) np.savetxt('file{}.txt'.format(counter), a, fmt='%s') counter += 1 yield i tree = Test() [X for X in tree] Here I am saving text file for each neighbor elements of that each target position and this work quite fine. Are there any tricks that I can use different search criteria for each target points without creating a separate tree query again and again? For example, lets say I want to use one variable X = np.array(features[0] with r = 0.1 and another variable Y = np.array(features[1] with r = 0.5 Right now, I can think only like this way indic1 = tree.query_radius(X, r= 0.1) indic2 = tree.query_radius(Y, r= 0.5) Is there a way that I can combine these two and make a one tree query?
tagged with: python
accepted answer: http://stackoverflow.com/a/51938187
type: AnsweredQuestion
score: 1

http://stackoverflow.com/comment/90764140
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51894013
type: Comment
has text: Thanks a lot! I upvoted your answer, but I found the last answer most suitable, hence i accepted it.

http://stackoverflow.com/q/51806090
tagged with: wxpython
has answer: http://stackoverflow.com/a/51808452
accepted answer: http://stackoverflow.com/a/51808452
tagged with: python
type: AnsweredQuestion
has title: How to add a marker on wx slider?
type: Question
has body: I am developing a python GUI script which required a function to be plotted. I need my plot to vary in real time when I vary certain parameters in the slider. That's not a problem and I successfully implemented those with both wx slider and matplotlib slider. What I failed to do is to add a "marker" to the slider. Often a particular value of parameter is more interesting than others and we want to "highlight" that value on the slider for our users. What I have in my mind is something like the red vertical line in matplotlib slider which indicates the initial value: , but I failed to find any relevant functions to change its location after the slider's creation. We have a drop down list showing different configurations and the value of interest changes with the configurations. I would like my marker to update its location automatically when a new configuration is set. I would like to ask if it is possible to change that red vertical line in matplotlib slider? If not, are there alternatives in either wxpython or matplotlib that allows me to highlight the value of interest and update its location according to a drop down list?
tagged with: matplotlib
tagged with: wxwidgets
score: 0
answer count: 1

http://stackoverflow.com/a/51864122
accepted answer of: http://stackoverflow.com/q/51863993
has body: Use concat with the keys and names arguments: pd.concat([A, B], keys=[0, 1], names=['Idx0']) The resulting output: Col Idx0 Idx1 Idx2 0 0 0 A 1 B 1 0 C 1 D 1 0 0 E 1 F 1 0 G 1 H
type: Answer
upvote count: 2
score: 2
answers question: http://stackoverflow.com/q/51863993
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/51834222
tagged with: python
score: 2
has comment: http://stackoverflow.com/comment/90629180
has comment: http://stackoverflow.com/comment/90622436
tagged with: virtualenvwrapper
has body: I am running python3 on Linux Mint, and am trying to set up VirtualEnvWrapper. I have both virtualenv and virtualenvwrapper installed: Running sudo pip3 install virtualenv, returns Requirement already satisfied: virtualenv in ./.local/lib/python3.5/site-packages (15.1.0) Running sudo pip3 install virtualenvwrapper, returns Requirement already satisfied: virtualenvwrapper in /usr/local/lib/python3.5/dist-packages (4.8.2) virtualenv is in /home/username/.local/bin/virtualenv virtualenvwrapper.sh is in /usr/local/bin/virtualenvwrapper.sh My .bash_profile looks like: source ~/.profile export WORKON_HOME=~/Envs export PROJECT_HOME=$HOME/Devel export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3 export VIRTUALENVWRAPPER_VIRTUALENV=/usr/local/bin/virtualenv source /usr/local/bin/virtualenvwrapper.sh When I run source ~/.bash_profile and then mkvirtualenv TestEnv, I return the following error: bash: /usr/local/bin/virtualenv: /usr/bin/python: bad interpreter: No such file or directory I think this is an issue with my .bash_profile and the location of the virtualenv vs virtualenvwrapper files. Is anyone able to help me correct my bash_profile to resolve this. I have tried various solutions offered on other threads, but none have helped. Many thanks Addition: This is a selection of the contents of my /usr/bin directory (i.e. ls). I'm not sure why python is in red but it is neither a file nor a directory
type: Question
has title: Virtualenvwrapper - correct set up of .bash_profile
has comment: http://stackoverflow.com/comment/90651692
tagged with: virtualenv
has comment: http://stackoverflow.com/comment/90622599
upvote count: 3
tagged with: linux
answer count: 1
downvote count: 1
tagged with: unix
favorite count: 0
has answer: http://stackoverflow.com/a/51834424
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90652538
has comment: http://stackoverflow.com/comment/90658178
has comment: http://stackoverflow.com/comment/90652763

selenium-webdriver
tags question: http://stackoverflow.com/q/51815106
tags question: http://stackoverflow.com/q/51898157
tags question: http://stackoverflow.com/q/51811762
tags question: http://stackoverflow.com/q/51900046
tags question: http://stackoverflow.com/q/51940907
tags question: http://stackoverflow.com/q/51824211
tags question: http://stackoverflow.com/q/51870889
tags question: http://stackoverflow.com/q/51901267
tags question: http://stackoverflow.com/q/51881388
tags question: http://stackoverflow.com/q/51850011
tags question: http://stackoverflow.com/q/51953062
tags question: http://stackoverflow.com/q/51937046
tags question: http://stackoverflow.com/q/51888636
tags question: http://stackoverflow.com/q/51955896
tags question: http://stackoverflow.com/q/51930973
tags question: http://stackoverflow.com/q/51846188
tags question: http://stackoverflow.com/q/51878000
tags question: http://stackoverflow.com/q/51808255
tags question: http://stackoverflow.com/q/51915039
tag name: selenium-webdriver
tags question: http://stackoverflow.com/q/51921415
tags question: http://stackoverflow.com/q/51832019
tags question: http://stackoverflow.com/q/51818889
tags question: http://stackoverflow.com/q/51806436
tags question: http://stackoverflow.com/q/51805184
tags question: http://stackoverflow.com/q/51818982
tags question: http://stackoverflow.com/q/51812302
type: Tag
tags question: http://stackoverflow.com/q/51887473
tags question: http://stackoverflow.com/q/51942665
tags question: http://stackoverflow.com/q/51927757
tags question: http://stackoverflow.com/q/51928064
tags question: http://stackoverflow.com/q/51802268
tags question: http://stackoverflow.com/q/51836487
tags question: http://stackoverflow.com/q/51933804
tags question: http://stackoverflow.com/q/51904896
tags question: http://stackoverflow.com/q/51881644
tags question: http://stackoverflow.com/q/51911954
tags question: http://stackoverflow.com/q/51919033
tags question: http://stackoverflow.com/q/51837901

django-generic-views
type: Tag
tag name: django-generic-views
tags question: http://stackoverflow.com/q/51947018

http://stackoverflow.com/q/51902666
accepted answer: http://stackoverflow.com/a/51902780
has comment: http://stackoverflow.com/comment/90756874
has comment: http://stackoverflow.com/comment/90757059
has comment: http://stackoverflow.com/comment/90757076
has comment: http://stackoverflow.com/comment/90756682
has comment: http://stackoverflow.com/comment/90756939
has title: Extract time from string in format %I:%M %p
answer count: 1
has body: I have the following string '10:26 PM - words are here' and would like the following extracted 10:26 PM Sometimes the string is also in the format of '09:26 AM words are here' where the dash is no longer present. I had the following code re.split(r'[-](?=[ ])', regex_str)[0] But once the dash is no longer present it breaks. Bare in mind the time can also be 9:26PM and doesn't have to be 09:26PM
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/90756650
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/90758613
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90756546
score: 1
has comment: http://stackoverflow.com/comment/90757101
has answer: http://stackoverflow.com/a/51902780
upvote count: 1
type: Question

http://stackoverflow.com/comment/90838906
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51944403
has text: Well, it doesnt complain about the missing options. I was getting the same error as you but it went away after I installed clang-3.5. I didnt have clang installed before, so installing clang must have modified gcc. Could try uninstalling clang and re-installing it. It was just to get rid of the missing options error. Am not trying to do what you are doing.

http://stackoverflow.com/comment/90857286
score: 0
has text: The project was originally created as a Django project without a virtual environment (on Windows originally - I'm transferring it to Linux). The Django project has two main things under it - the browser interface and a TKinter GUI which includes a server daemon. When I made the virtual env, I copied what existed into the myprojectenv folder.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51953349

http://stackoverflow.com/q/51853149
tagged with: excel
type: Question
has comment: http://stackoverflow.com/comment/90658867
has comment: http://stackoverflow.com/comment/90659167
has comment: http://stackoverflow.com/comment/90658824
score: -1
upvote count: 0
answer count: 1
tagged with: vba
has comment: http://stackoverflow.com/comment/90658990
favorite count: 0
has comment: http://stackoverflow.com/comment/90661035
has comment: http://stackoverflow.com/comment/90658917
has body: I scrapped data and exported as csv files. For simplicity, the data look like below (I intentionally put arbitrary variables to just illustrate an example): id var1 var2 var3 ... A 10 14 355 ... B 35 56 22 ... C 95 22 222 ... D 44 55 222 ... Since I collected the data daily, I saved my file name as city_20180814_result.csv For example, if I collected the data in NYC at Aug 14th 2018, the corresponding file name is NYC_20180814_result.csv Here, I want to add a new column, the date variable, into each csv file. The desired example is going to be like the one below. To be specific, I want to add a date (YYYYMMDD as a format) column to each csv file and the values are going to be the date when the data were collected. For example, the below example csv file was generated on Aug 14th 2018, then the updated data will look like below: id date var1 var2 var3 ... A 20180814 10 14 355 ... B 20180814 35 56 22 ... C 20180814 95 22 222 ... D 20180814 44 55 222 ... The conventional way to do this is to open every csv file and manually add a new column, assign a corresponding date to all the rows, and repeat this step for all csv files. But there are too many to get this done. Is there any way to do this efficiently? Since I saved file names including the date, it would be a good idea to use this if it's possible. Any help/codes (by using python again or excel macro) would be appreciated.
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
has title: how to add a new column without opening a csv file
tagged with: python
has comment: http://stackoverflow.com/comment/90658845
has answer: http://stackoverflow.com/a/51853379
downvote count: 1

http://stackoverflow.com/comment/90720892
score: 0
type: AnswerComment
type: Comment
has text: What's the dtype of 3_mo?
comment on: http://stackoverflow.com/a/51884450

http://stackoverflow.com/comment/90796764
has text: Thanks, only just learning dictionaries.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51923190

http://stackoverflow.com/q/51911742
has comment: http://stackoverflow.com/comment/90773595
type: Question
has comment: http://stackoverflow.com/comment/90774360
has comment: http://stackoverflow.com/comment/90774093
answer count: 2
has answer: http://stackoverflow.com/a/51911800
downvote count: 0
has comment: http://stackoverflow.com/comment/90774136
favorite count: 0
has title: Python Request Headers Cookies Issue
has answer: http://stackoverflow.com/a/51911858
tagged with: python
has body: I am trying to scrape this page, but am having problems with the cookies using the below code: SelectProxy.select_proxy() local_proxy = SelectProxy.global_proxy session = requests.Session() session.proxies = {local_proxy} cookies = session.cookies url = movie_url 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-GB,en-US;q=0.9,en;q=0.8', 'Cache-Control': 'max-age=0', 'Connection': 'keep-alive', 'Cookie': cookies, 'Host': 'www.sky.com', 'If-Modified-Since': 'Sat, 18 Aug 2018 14:45:31 GMT', 'Upgrade-Insecure-Requests': '1', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36' } r = session.get(url, headers=headers) The error I am getting is as so: Traceback (most recent call last): File "G:\Python27\Kodi\Sky Q Movies Scraper.py", line 33, in &lt;module&gt; class sky_movies: File "G:\Python27\Kodi\Sky Q Movies Scraper.py", line 90, in sky_movies r = session.get(url, headers=headers) File "G:\Python27\lib\site-packages\requests\sessions.py", line 488, in get return self.request('GET', url, **kwargs) File "G:\Python27\lib\site-packages\requests\sessions.py", line 461, in request prep = self.prepare_request(req) File "G:\Python27\lib\site-packages\requests\sessions.py", line 394, in prepare_request hooks=merge_hooks(request.hooks, self.hooks), File "G:\Python27\lib\site-packages\requests\models.py", line 295, in prepare self.prepare_headers(headers) File "G:\Python27\lib\site-packages\requests\models.py", line 409, in prepare_headers check_header_validity(header) File "G:\Python27\lib\site-packages\requests\utils.py", line 800, in check_header_validity "not %s" % (value, type(value))) InvalidHeader: Header value &lt;RequestsCookieJar[]&gt; must be of type str or bytes, not &lt;class 'requests.cookies.RequestsCookieJar'&gt; Can anyone advise what I am doing wrong? Thanks
tagged with: cookies
type: UnansweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/90774176
upvote count: 1
tagged with: python-requests

http://stackoverflow.com/comment/90613167
type: Comment
comment on: http://stackoverflow.com/a/51825728
has text: @jacksmith Please post HTML source fragment from a *second* page
score: 0
type: AnswerComment

http://stackoverflow.com/comment/98703858
type: Comment
comment on: http://stackoverflow.com/a/51846025
score: 1
type: AnswerComment
has text: Dropping back in to say that it was indeed a whitespace issue, and removing the spacing worked, so this does do what I had hoped

http://stackoverflow.com/a/51887570
downvote count: 0
answers question: http://stackoverflow.com/q/51887426
has comment: http://stackoverflow.com/comment/90750720
has body: You can use the built-in function exec to define a function dynamically: def _create_multiInput_fcn(vector_fcn,var_list): exec(''' def g({0}): return vector_fcn([{0}]) '''.format(','.join(var_list)), globals(), locals()) return g g = _create_multiInput_fcn(f,var_list)
accepted answer of: http://stackoverflow.com/q/51887426
has comment: http://stackoverflow.com/comment/90727471
type: Answer
has comment: http://stackoverflow.com/comment/90757995
has comment: http://stackoverflow.com/comment/90819516
has comment: http://stackoverflow.com/comment/90750271
upvote count: 2
has comment: http://stackoverflow.com/comment/90727311
has comment: http://stackoverflow.com/comment/90751046
has comment: http://stackoverflow.com/comment/90750119
score: 2
type: AcceptedAnswer

http://stackoverflow.com/comment/90701548
has text: Your question needs a **[mcve]**. I suggest you set up a couple of dataframes and your desired output indicating your logic in various scenarios.
comment on: http://stackoverflow.com/q/51875012
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90693425
comment on: http://stackoverflow.com/q/51870964
has text: @PraysonDaniel For above input that;s it. It should not return anything after that(Ideally break the loop).
type: QuestionComment
score: 0
type: Comment

http://stackoverflow.com/q/51898404
tagged with: mongodb-query
favorite count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
has title: PyMongo Aggregation for Query Filters?
has answer: http://stackoverflow.com/a/53092807
score: 1
has body: So I'm finding questions similar but not quite answering what I'm looking for. If this is a duplicate; feel free to point me to the appropriate place. I have a collection which is a "source of truth" for some pretty large documents. I would like to do some pre-filtering using the query engine before I get to my primary analytics. Query 1: Retrieve only documents where document.financials.entrycount $gte 4. So basically in a document I have a subdocument for financials. I want to use this as a filter. I only want to return documents where the number of entries there is greater than 4. Query 2: Be able to do math and compare that to a number for retrieval. For example: (totalAssets + totalCash) / (totalDebt + totalLiabilities) &lt; .5 where those numbers are in a sub document. Finally be able to combine that together. Below is an example document projected down to only include quarterly financials. { "symbol": "AAWW", "quarterly_financials": { "2017-09-30": { "cashChange": -106467000, "cashFlow": 82299000, "costOfRevenue": 439135000, "currentAssets": 449776000, "currentCash": 176280000, "currentDebt": 196509000, "grossProfit": 96613000, "netIncome": -24162000, "operatingExpense": 43690000, "operatingGainsLosses": 378000, "operatingIncome": 52923000, "operatingRevenue": 535748000, "researchAndDevelopment": None, "shareholderEquity": 1575169000, "totalAssets": 4687302000, "totalCash": 175926000, "totalDebt": 2105344000, "totalLiabilities": None, "totalRevenue": 535748000 }, "2017-12-31": { "cashChange": 115584000, "cashFlow": 136613000, "costOfRevenue": 474565000, "currentAssets": 587586000, "currentCash": 291864000, "currentDebt": 218013000, "grossProfit": 153387000, "netIncome": 209448000, "operatingExpense": 46628000, "operatingGainsLosses": -95000, "operatingIncome": 106759000, "operatingRevenue": 627952000, "researchAndDevelopment": None, "shareholderEquity": 1789856000, "totalAssets": 4955462000, "totalCash": 294413000, "totalDebt": 2226999000, "totalLiabilities":…
tagged with: pymongo
type: Question
tagged with: mongodb
downvote count: 0
answer count: 1
tagged with: aggregation-framework

http://stackoverflow.com/q/51895326
has body: I would like to use the connection and cursor classes inside a custom made class. I would also like to inherit all the methods associated with the connection and cursor classes. I have done some research on it and found docs and this question related to my problem. I have some code that is working partly. i.e I can insert and update the database. However, I cannot select from the database because doing so returns none even when the row is in the database. Here is my code from datetime import datetime, timedelta import psycopg2 import psycopg2.extensions class DataBase(): """A class used to create tables in the database. Inherits from psycopg2.extensions.connection in order to gain access to the cursor, commit, close, and many other features from the pyscopg module. """ def __init__(self): self.my_connection = psycopg2.connect(database="public", user="public", password="general", host="127.0.0.1", port="5432") self.my_cursor = self.my_connection.cursor() def query_database(self, sql_statement, *args): return self.my_cursor.execute(sql_statement, *args) def commit_query(self): return self.my_connection.commit() def fetch_one(self, sql_statement, *args): result = self.query_database(sql_statement, *args) if result is None: return False return result.fetchone() def fetch_all(self, sql_statement, *args): result = self.query_database(sql_statement, *args) if result is None: return False return result.fetchall() def __del__(self): self.my_cursor.close() self.my_connection.close() ############################################################################ class CreateTables(DataBase): def create_user_table(self): """Helper function used to create the user_table""" sql_statement = '''CREATE TABLE IF NOT EXISTS USERS (ID SERIAL PRIMARY KEY, FIRSTNAME TEXT NOT NULL, LASTNAME TEXT NOT NULL, USERNAME TEXT NOT NULL UNIQUE, EMAIL TEXT NOT NULL UNIQUE, PASSWORD TEXT NOT NULL, DATETIMEREGISTERED TIMESTAMP NOT NULL);''' user_table = DataBase.query_database(self, sql_statement) DataB…
upvote count: 2
linked to: http://stackoverflow.com/q/18780591
answer count: 1
accepted answer: http://stackoverflow.com/a/51895597
favorite count: 0
tagged with: python
tagged with: psycopg2
has answer: http://stackoverflow.com/a/51895597
score: 2
type: AnsweredQuestion
downvote count: 0
has title: Connection and Cursor inside a class in psycopg2
type: Question

http://stackoverflow.com/comment/90762049
has text: This way you will get the unbound Field. To receive a value you need to get the Field bound to an instance. Which is usually done by: `MyModel.objects.get(some_query).field_name` or similar.
comment on: http://stackoverflow.com/q/51905712
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/comment/90826699
type: Comment
type: QuestionComment
score: 3
comment on: http://stackoverflow.com/q/51937772
has text: Import at all. If the module with the subclass is never loaded, then the python interpreter can't know that a subclass exists.

http://stackoverflow.com/comment/90643517
comment on: http://stackoverflow.com/a/51844275
score: 0
type: AnswerComment
type: Comment
has text: Yes I did and actually because it's just for learning purposes I even tried to convert it into a text file but it didn't work also

http://stackoverflow.com/comment/90740936
score: 0
has text: @RoadRunner That is not helpful. If you replace `check_output` with `Popen()` you will need to reimplement the rest of `check_output()`. Most people who try manage to botch it because `Popen()` is a hard beast to tame.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51893520

http://stackoverflow.com/comment/90650009
comment on: http://stackoverflow.com/q/51848288
type: Comment
type: QuestionComment
has text: That is a type-hint, not a default argument, I'm pretty sure.
score: 2

http://stackoverflow.com/a/51849964
answers question: http://stackoverflow.com/q/51849794
score: 3
has comment: http://stackoverflow.com/comment/90673216
accepted answer of: http://stackoverflow.com/q/51849794
has comment: http://stackoverflow.com/comment/90671036
upvote count: 3
has body: If I understand you correctly you should try something line that: np.savez('{}.npz'.format(list(a.keys())[0])). This will set a filename to a first key in a given dictionary. The error that you get is correct since you are trying to set a.keys() to be the value of a['xarray'] which is an expression. Moreover, to my very best knowledge python will not allow that. Edit: I am just after the lecture of what np.savez function does and I misunderstood you. So the correct thing (if I am correct now) is to do this: kwargs = {key: a[key] for key in a.keys()} np.savez('test.npz', **kwargs) Please try and say if this is what you want :) Edit 2: For having only first key: kwargs = {key: a[key] for key in [list(a.keys())[0]]} np.savez('test.npz', **kwargs)
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/comment/90596149
comment on: http://stackoverflow.com/a/51820230
type: AnswerComment
score: 0
type: Comment
has text: as far as i know, you can't. It'll end up causing a RunTimeError

http://stackoverflow.com/q/51840681
accepted answer: http://stackoverflow.com/a/51894917
answer count: 2
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/90732341
has body: I have written a Datadog Agent check in Python following the instructions on this page: https://docs.datadoghq.com/developers/agent_checks/. The agent check is supposed to read all files in a specified network folder and then send certain metrics to Datadog. The folder to be read is specified like this in the Yaml file: init_config: taskResultLocation: "Z:/TaskResults" This is the code used to read the folder, it is Python 2.7 because that is required by Datadog task_result_location = self.init_config.get('taskResultLocation') # Loop through all the XML files in the specified folder for file in os.listdir(task_result_location): If I just run the Python script in my IDE everything works correctly. When the check is added to the Datadog Agent Manager on the same machine that the IDE is on and the check is run an error is thrown in the Datadog Agent Manager Log saying: 2018-08-14 14:33:26 EEST | ERROR | (runner.go:277 in work) | Error running check TaskResultErrorReader: [{"message": "[Error 3] The system cannot find the path specified: 'Z:/TaskResults/.'", "traceback": "Traceback (most recent call last):\n File \"C:\Program Files\Datadog\Datadog Agent\embedded\lib\site-packages\datadog_checks\checks\base.py\", line 294, in run\n self.check(copy.deepcopy(self.instances[0]))\n File \"c:\programdata\datadog\checks.d\TaskResultErrorReader.py\", line 42, in check\n for file in os.listdir(task_result_location):\nWindowsError: [Error 3] The system cannot find the path specified: 'Z:/TaskResults/.'\n"}] I have tried specifying the folder location in multiple ways with single and double quotes, forward and back slashes and double slashes but the same error is thrown. Would anyone know if this is a Yaml syntax error or some sort of issue with Datadog or the Python?
has answer: http://stackoverflow.com/a/51894917
type: Question
tagged with: datadog
type: AnsweredQuestion
has title: Datadog Agent check cannot find the path specified
possible better answer: http://stackoverflow.com/a/51841340
has answer: http://stackoverflow.com/a/51841340
tagged with: python-2.7

http://stackoverflow.com/comment/90803015
type: AnswerComment
score: 0
type: Comment
has text: seems to me like the same problem just with the tensorflow module. just install that, too.
comment on: http://stackoverflow.com/a/51926168

http://stackoverflow.com/comment/90730974
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51889212
type: Comment
has text: How can I get URL in `data-original` not in `src`? ` `

http://stackoverflow.com/comment/90576678
comment on: http://stackoverflow.com/q/51810649
type: QuestionComment
type: Comment
score: 0
has text: I see there is a white space at this line 24: `print(key + ", " + str(value[1]) )` probably this is causing you problem submitting the code. Please replace this line with `print(key + ", " + str(value[1]))`. It may work.

http://stackoverflow.com/comment/90573601
has text: there's already a function that will do that just as easily : `dateimte.datetime.strptime`, why would you want to subclass Date when the functionality is already there? if that is the only reason for you to subclass then subclassing is meaningless
score: 0
comment on: http://stackoverflow.com/q/51808566
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90690507
type: Comment
has text: Thank you so much. Is this the only way? I will use it and you are great help.
type: AnswerComment
comment on: http://stackoverflow.com/a/51868975
score: 0

http://stackoverflow.com/comment/90822481
comment on: http://stackoverflow.com/a/51935358
type: AnswerComment
score: 0
type: Comment
has text: is the installation that i originally followed was intended for the v2 dev version?

google-cloud-functions
tag name: google-cloud-functions
tags question: http://stackoverflow.com/q/51856282
type: Tag
tags question: http://stackoverflow.com/q/51839083

http://stackoverflow.com/comment/90682775
comment on: http://stackoverflow.com/a/51849244
type: Comment
has text: As you stated in the original question: `does reverse support list/dict arguments` - yes it does. Passing your `replace_parameters` as `kwargs` is just fine. `Reverse` does support this parameter and understands what to do. The problem is inside `replace_parameters` - it contains placeholders instead of values. Which do not match your regex. That's it.
score: 0
type: AnswerComment

http://stackoverflow.com/a/51873511
has comment: http://stackoverflow.com/comment/90702503
answers question: http://stackoverflow.com/q/51873036
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: Use a dictionary with colors and explicitly state which color to use for which group. For example: color_dict = {1: 'r', 2:'b', 3: 'g'} And adding the colors when plotting: ax.plot(group.Day, group.Aprop, marker='o', linestyle='', ms=3, label=name, color=color_dict[name] )
upvote count: 1
has comment: http://stackoverflow.com/comment/90704209
score: 1
accepted answer of: http://stackoverflow.com/q/51873036

http://stackoverflow.com/comment/90660970
type: Comment
score: 0
comment on: http://stackoverflow.com/a/51845731
type: AnswerComment
has text: thanks a lot. I updated the code including import pandas.

http://stackoverflow.com/q/51952393
tagged with: raspberry-pi
tagged with: vba
has body: I am trying to run a python script located inside my Raspberry Pi from my Excel. For example a simple 2 button excel page where you write the pause time between each run to a excel box, press the first button and the script runs. When you want it to stop, just press the second one. First I started trying out the command prompt of windows 10 with built-in ssh. I created ssh keys from my laptop to the raspberry so there is no password asking. C:\Users\xx&gt;ssh pi@192.168.x.xx /home/pi/Temp_Codes/Script_Manual.py Writing to database... Write Complete C:\Users\xx&gt; This works perfectly and I know that the ssh connection is fine. For the Excel part I am trying to use the shell method but there are some problems. Sub RunScript() Dim PID As Variant PID = Shell("ssh pi@192.168.x.x /home/pi/Temp_Codes/Script_Manual.py", vbHide) End Sub This gives me a "Run-time error '53': File not found". I assume it is trying to find the script inside my computer instead of the raspberry pi. I tried different combinations but it is always the same error.
has comment: http://stackoverflow.com/comment/90857057
has comment: http://stackoverflow.com/comment/90885733
tagged with: ssh
tagged with: python
has comment: http://stackoverflow.com/comment/90885302
has comment: http://stackoverflow.com/comment/90882194
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90885810
has title: Using Excel VBA to remotely run a code inside Raspberry Pi
tagged with: excel
type: Question
score: 0

http://stackoverflow.com/q/51909407
has comment: http://stackoverflow.com/comment/90768885
answer count: 0
type: UnansweredQuestion
has body: Snippet of main.kv &lt;PositionSelection&gt;: name: 'PositionSelection' # pos_sel_button: sel_button id: sel_button_id GridLayout: rows:2 padding: 5 spacing: 5 Button: id: position_button text: 'Position' After created the button (id: position_button) in kv I will add a list of buttons in python, but I need to modify from python file the text (defined as 'Position') suddenly without any action on it. Has someone any idea?
type: Question
has comment: http://stackoverflow.com/comment/90771224
tagged with: kivy
tagged with: kivy-language
score: 0
tagged with: python
has title: Modify from python of kivy dropdown button text

http://stackoverflow.com/q/51863837
has answer: http://stackoverflow.com/a/51863917
has answer: http://stackoverflow.com/a/51864019
accepted answer: http://stackoverflow.com/a/51863917
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/90679760
type: Question
score: 3
has answer: http://stackoverflow.com/a/51863897
possible better answer: http://stackoverflow.com/a/51864019
upvote count: 3
answer count: 3
tagged with: pandas
favorite count: 0
has body: I have a pandas data frame with column that contain house numbers and a suffix. The house number and suffix are seperated by a '-' although many suffixes also contain a '-'. I have tried this: df house_nr(x): y = x['house_nr'].split('-', maxsplit = 1) return y df['suffix'] = df.apply(house_nr, axis=1) Got the following error: KeyError: ('house_nr', 'occurred at index 0') After some other attempts I've got this working: df2 = pd.DataFrame(df['house_nr'].str.split('-',1).tolist(),columns = ['house-number','suffix']) And then I join the dataframe but I don't think this solution is very nice or pythonic.
has title: Split column on first occurence of '-'
tagged with: python

http://stackoverflow.com/a/54785962
answers question: http://stackoverflow.com/q/51893564
has body: following method can be used to get driver with a proxy def get_driver(PROXY): firefox_capabilities = webdriver.DesiredCapabilities.FIREFOX firefox_capabilities['proxy'] = {"proxyType": "MANUAL", "httpProxy": PROXY, "ftpProxy": PROXY, "sslProxy": PROXY } fp = webdriver.FirefoxProfile() options = Options() options.add_argument("--headless") fp.update_preferences() driver = webdriver.Firefox(firefox_options=options,capabilities=firefox_capabilities, executable_path=geckodriver_path,firefox_profile=fp) driver.set_window_size(2400,1980) return driver
score: 0
type: Answer

http://stackoverflow.com/q/51932026
has comment: http://stackoverflow.com/comment/90814126
type: UnansweredQuestion
tagged with: python
has body: I have a string str="TMOUT=1800; export TMOUT" I want to extract only TMOUT=1800 from above string, but 1800 is not constant it can be any integer value. For example TMOUT=18 or TMOUT=201 etc. I'm very new to regular expression. I tried using code below re.search("TMOUT=\d",str). It is not working. Please help
has comment: http://stackoverflow.com/comment/90815899
type: Question
has comment: http://stackoverflow.com/comment/90815973
has title: search substring + integer from a string in python using regular expression
has answer: http://stackoverflow.com/a/51932056
score: 0
answer count: 1

http://stackoverflow.com/comment/90573989
comment on: http://stackoverflow.com/q/51808891
type: Comment
type: QuestionComment
has text: The comments happen to reference Knuth's The Art of Computer Programming, Vol. 2, which is an excellent place to look for such things. 4.3.2 is the chapter on arbitrary precision integer modulus.
score: 1

http://stackoverflow.com/comment/90819580
type: Comment
score: 1
comment on: http://stackoverflow.com/q/51934451
has text: @jonrsharpe Regardless of whether it works or not, this question needs a lot of clarification before it's a decent question anywhere.
type: QuestionComment

http://stackoverflow.com/comment/90651228
has text: The calling function will raise the same exception you caught in the callable, and you'll have the opportunity to handle it from that function, or to print an error. To understand this, think of a convenience store purchase where the cashier made the incorrect change for your purchase. The customer raises an IncorrectChangeException, but the cashier cannot do anything about it because she can't open the register. She `raise`s the exception to the manager, who will get the IncorrectChangeException. The manager can then open the drawer with their key, apologize, etc. Same concept applies.
type: Comment
comment on: http://stackoverflow.com/a/51848633
score: 0
type: AnswerComment

http://stackoverflow.com/comment/90692165
has text: Can you provide a html tag which are you looking for?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51870338

http://stackoverflow.com/q/51859000
has answer: http://stackoverflow.com/a/51859823
type: Question
has answer: http://stackoverflow.com/a/51890825
has comment: http://stackoverflow.com/comment/90674710
linked to: http://stackoverflow.com/q/51761926
downvote count: 0
has comment: http://stackoverflow.com/comment/90732724
possible better answer: http://stackoverflow.com/a/51890825
has title: Regional settings conflicting with Matplotlib for Python Visualizations in Power BI
answer count: 3
tagged with: powerbi
accepted answer: http://stackoverflow.com/a/51859823
has answer: http://stackoverflow.com/a/52077531
favorite count: 0
has comment: http://stackoverflow.com/comment/90671528
has comment: http://stackoverflow.com/comment/90672575
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/90679558
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/51856488
linked to: http://stackoverflow.com/q/8271564
score: 1
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/90671089
has body: The challenge: How can you prevent Matplotlib from using commas in figure arguments like matplotlib.pyplot.figure(figsize=(3,75,3,5)) without changing your locale settings (and still use commas as decimal separators for the rest of your system)? The details: From the questions and answers in the posts What is the best data format and setup for a time series in a Python Visualization in Power BI? and What setup do you need for Python Visualizations in Power BI? Any particular matplotlib package versions or system settings?, it seems that many european Power BI users will face a few issues when it comes to Python Visualizations in Power BI. This is because regional settings and using comma as a decimal separator raises an issue in matplotlib. In order to avoid the errors matplotlib.pyplot.figure(figsize=(3,75,3,52)) and TypeError: from_bounds() takes 4 positional arguments but 6 were given when you're setting up a Python Visualization, it seems that you would have to: Use non-european regional settings for you entire system, or tell matplotlib to ignore regional settings when setting up a figure. At least to me, It would be unthinkable to use another regional setting and decimal separator than ",". As far as I know, that would mess up the numerous other reports what we've set up in Power BI. So I guess we're stuck with option 2. In the post Matplotlib : Comma separated number format for axis, one of the answers shows how this can be done using: import locale locale.setlocale(locale.LC_ALL, "deu_deu") import matplotlib as mpl mpl.rcParams['axes.formatter.use_locale'] = True But it doesn't seem to work in Power BI. I've tried with this simple dataset: A,B 1,11 2,19 3,18 4,19 5,18 6,12 7,12 8,19 9,13 10,19 And this script: #Locale settings import locale locale.setlocale(locale.LC_ALL, "deu_deu") import matplotlib as plt plt.rcParams['axes.formatter.use_locale'] = True # Plot import matplotlib.pyplot as plt plt.plot(dataset['A'], dataset['B']) plt.show() But still no succ…

http://stackoverflow.com/a/51910110
answers question: http://stackoverflow.com/q/51904251
downvote count: 0
score: 1
has body: Make sure that comprehensive_ngrams is a list of unique words. I.e.: assert len(set(comprehensive_ngrams)) == len(comprehensive_ngrams)
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51904251
type: Answer

http://stackoverflow.com/q/51953016
type: AnsweredQuestion
type: Question
has answer: http://stackoverflow.com/a/51953357
tagged with: javascript
accepted answer: http://stackoverflow.com/a/51953357
tagged with: flask
has body: The problem I am having is the page is not being rendered. It just returns to the default index.html and not response.html I have created a flask app using python on the back end and javascript/jquery/ajax on the front end. However whenever I try to return a view in the template I get no errors (either in the console or in the cmd window) and the page doesnt render. Any help with this would be appreciated. Here is the code: here is index.html Local Sales Scraper Home About Contact Price Range sort lowest to highest price submit Search Ebay Search Craigslist Search Letgo search results: here is response.html Flask app and app.py from scraper import scrape from flask import Flask, render_template, jsonify, make_response, request import json app = Flask(__name__) @app.route("/") def index(): return render_template('index.html') @app.route("/parse_data", methods=['POST']) def parse_data(): data = request.get_json() #print data #search = json.loads(search) scrapedData = json.dumps(scrape(data)) #entries = jsonify({'name' : entries}) #print scrapedData return render_template('index.html', data= scrapedData) if __name__ == "__main__": app.run(debug=True, host='0.0.0.0', port=5000)
score: 0
answer count: 1
tagged with: jquery
tagged with: ajax
has title: Not getting any errors but page not rendering with render_template in my flask app
tagged with: python

http://stackoverflow.com/q/51913822
has body: my code for a random number guesser looks like so: if answer == 'n' and 'N': print 'I hope to see you next time, %s' % user exit() However, if I input 'N', the console blanks out and exits instead of printing the statement. 'n' works still tho and the 'Y' and 'y' statement works perfect. So I am not sure what is going on here with the 'N', but probably something simple I am overlooking. Thanks
duplicate of: http://stackoverflow.com/q/18195322
type: AnsweredQuestion
tagged with: pycharm
has answer: http://stackoverflow.com/a/51913844
linked to: http://stackoverflow.com/q/15112125
accepted answer: http://stackoverflow.com/a/51913844
type: Question
possible better answer: http://stackoverflow.com/a/51913847
has comment: http://stackoverflow.com/comment/90777742
has title: If And not taking second input
has comment: http://stackoverflow.com/comment/90777771
linked to: http://stackoverflow.com/q/18195322
has comment: http://stackoverflow.com/comment/90777687
score: 0
has answer: http://stackoverflow.com/a/51913860
has answer: http://stackoverflow.com/a/51913854
duplicate of: http://stackoverflow.com/q/15112125
has answer: http://stackoverflow.com/a/51913847
tagged with: python
answer count: 4

http://stackoverflow.com/comment/90638316
comment on: http://stackoverflow.com/q/51842612
score: 0
type: QuestionComment
has text: Are you sure that the file you are trying to write to is not opened in any other application?
type: Comment

http://stackoverflow.com/comment/90835634
score: 0
type: Comment
has text: But then the solution you mentioned above maybe not the right solution because one of my friend who is using the same RPA solution tool doesn't have the"MachineLevelUser..." file, but CAN OPEN THE CHROME through the RPA solution tool.
comment on: http://stackoverflow.com/a/51942613
type: AnswerComment

http://stackoverflow.com/comment/90735395
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/51889417
has text: You can use `subprocess` to run processes in the background. Perhaps then you will need to revert to `Popen()` though. Running multiple processes in parallel and polling for when one of them produces output is challenging. And you are reinventing existing tools anyway - search for `multiping` and `fping`.

http://stackoverflow.com/comment/90754691
type: QuestionComment
comment on: http://stackoverflow.com/q/51901655
score: 0
has text: @ArashHatami I'm just running `python manage.py collectstatic --noinput`, which automatically should provide default permissions, no? Is there something else I need to do?
type: Comment

http://stackoverflow.com/q/51939096
tagged with: syntax
type: UnansweredQuestion
type: Question
has body: I have been working on this text based adventure game using Python. This may be a simple fix, but I am unable to see it. When I add another EVENT in my code, it gives me an INVALID SYNTAX error. For example, when I added EVENT_DOOR2, I get an invalid syntax error, specifically on, door = colored_input():. Below is a snippet of my otherwise long code. Any insight would be helpful! Thank you! def main(): import sys from colorama import init init() init(autoreset=True) from colorama import Fore, Back, Style def run_event(event): text, choices = event text_lines = text.split("\n") for line in text_lines: print(Style.BRIGHT + line) print() choices = choices.strip() choices_lines = choices.split("\n") for num, line in enumerate(choices_lines): print(Fore.GREEN + Style.BRIGHT + str(num + 1) + ". " + line) print() def colored_input(): return input(Fore.YELLOW + Style.BRIGHT + "&gt; ") print ("") print ("") print (Fore.YELLOW + Style.BRIGHT + " WELCOME TO THE MAZE ") print ("") print ("") print ("You have found yourself stuck within a dark room, inside this room are 5 doors.. Your only way out..") print ("") print ("Do you want to enter door 1,2,3,4, or 5?") print ("") EVENT_DOOR1 = (""" Theres an alien eating what appears to be a human arm, though its so damaged it's hard to be sure. There is a knife next to the alien. what do you want to do? """, """ Go for the knife Attack alien before it notices you """) EVENT_DOOR2 = ("""You seem to have entered a different world. Objects and natural elements seem to be alive, grass attempts to wrap around your ankles. Ahead lies a sword, within what seems to be a large venus fly trap. What should you do? """,""" Run through this world as fast as you can. Attempt to grab the sword. Explore Further.""") door = colored_input() if door == "1": run_event(EVENT_DOOR1) elif door == "2": run_event(EVENT_DOOR2) EVENT_ALIEN = (""" You approach the knife slowly, While the alien is distracted. You finally reach the knife, but as you look up, the a…
tagged with: adventure
score: 0
tagged with: linux
tagged with: events
tagged with: python
has title: Invalid Syntax, Text Based Adventure game. Python (linux)
has comment: http://stackoverflow.com/comment/90828667
has comment: http://stackoverflow.com/comment/90828532
answer count: 0
has comment: http://stackoverflow.com/comment/90828311

http://stackoverflow.com/comment/90578476
has text: @StivenG, you're welcome. Consider to upvote and/or accept my answer if it was useful for you.
comment on: http://stackoverflow.com/a/51809030
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/51897447
has comment: http://stackoverflow.com/comment/90746004
type: Answer
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/90746100
answers question: http://stackoverflow.com/q/51897361
has comment: http://stackoverflow.com/comment/90746014
has body: tkinter is used as a UI processing backend for matplotlib. It should be shipped with python but might not be on your system for various reasons. Chances are you you have agg, (should ship with ubuntu) which you can use instead. import matplotlib matplotlib.use('agg') import matplotlib.pyplot as plt You can of course still use tkinter if you install it on your box. If you prefer that for some reason I can let you know but it requires sudo.
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90745918
has comment: http://stackoverflow.com/comment/90746252
accepted answer of: http://stackoverflow.com/q/51897361

http://stackoverflow.com/comment/90802568
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51926494
has text: Please add a minimal version of your network's code, too.
score: 0

http://stackoverflow.com/comment/90869019
type: QuestionComment
comment on: http://stackoverflow.com/q/51938713
score: 0
has text: The below link has solved my problem. Very very useful. https://stackoverflow.com/questions/50082449/splitting-multiple-columns-on-a-delimiter-into-rows-in-pandas-dataframe
type: Comment

http://stackoverflow.com/q/51811154
upvote count: 10
has comment: http://stackoverflow.com/comment/90578101
has answer: http://stackoverflow.com/a/76658515
favorite count: 0
tagged with: pytorch
has body: def save_checkpoint(state, is_best, filename='checkpoint.pth.tar'): torch.save(state, filename) if is_best: shutil.copyfile(filename, 'model_best.pth.tar') save_checkpoint({ 'epoch': epoch + 1, 'arch': args.arch, 'state_dict': model.state_dict(), 'best_prec1': best_prec1, 'optimizer': optimizer.state_dict() }, is_best) I am saving my model like this. How can I load back the model so that I can use it in other places, like cnn visualization? This is how I am loading the model now: torch.load('model_best.pth.tar') But when I do this, I get this error: AttributeError: 'dict' object has no attribute 'eval' What am I missing here??? EDIT: I want to use the model that I trained to visualize the filters and grads. I am using this repo to make the vis. I replaced line 179 with torch.load('model_best.pth.tar')
type: UnansweredQuestion
tagged with: python
tagged with: conv-neural-network
has comment: http://stackoverflow.com/comment/90577608
has comment: http://stackoverflow.com/comment/90578051
has comment: http://stackoverflow.com/comment/90577515
has comment: http://stackoverflow.com/comment/90578305
type: Question
has comment: http://stackoverflow.com/comment/90578287
answer count: 2
has title: load a pretrained model pytorch - dict object has no attribute eval
downvote count: 0
score: 10
has comment: http://stackoverflow.com/comment/90578268
has answer: http://stackoverflow.com/a/51812173
has comment: http://stackoverflow.com/comment/90578036
tagged with: deep-learning
has comment: http://stackoverflow.com/comment/90577601

http://stackoverflow.com/comment/90649776
type: AnswerComment
comment on: http://stackoverflow.com/a/51846132
score: 0
type: Comment
has text: Would you know how to loop this function so that it goes through and performs this action for every neighborhood, then put the single row data frames together? I have tried putting a for loop around the function, but it just prints out the list of neighborhood names I have.

http://stackoverflow.com/a/51817892
has body: You can use pattern: epms\[[^]]+\]\[[^]]+\] epms Match literal substring. \[ Match a [. [^]]+ Negated character set. Anything other than a ]. \] Match a ]. \[ Match a [. [^]]+ Negated character set. Anything other than a ]. \] Match a ]. In Python: import re mystring = "variable = epms[something][something]" if re.search(r'epms\[[^]]+\]\[[^]]+\]',mystring): print (mystring)
answers question: http://stackoverflow.com/q/51817609
accepted answer of: http://stackoverflow.com/q/51817609
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/90601943

http://stackoverflow.com/a/51962894
type: Answer
score: 0
has body: Just adding my opinion as you already have an accepted answer. Although you convert a Python code block to Javascript, I feel you don't really have to use the same syntaxes and method names. For an example, if we take the following code block in Python and JS; Python: def calculateLevel(exp): if exp &lt; 83: return 1 else: calcExp = 0 for level in range(1, 1000): diff = int(level + 300 * math.pow(2, float(level)/7)) calcExp += diff if exp &lt; calcExp//4: break return level Note: Here it uses for level in range(1, 1000):. The same thing can be done by using a while loop as well. So it could look something like: level = 0 while level &lt;= 1000: diff = int(level + 300 * math.pow(2, float(level)/7)) calcExp += diff if exp &lt; calcExp//4: break return level But looping over a for in range() in Python is more efficient than using a while loop. If I run a simple benchmark, I could see the following results. for in range() : 55 function calls in 0.000 seconds while: 1650 function calls in 0.001 seconds Although this is the case with Python, it's quite different in Javascript (and in your approach which uses underscore's range() function.) Although the function names look similar, it doesn't mean they have same performance as in Python. In fact, looping over _.range() is much slower than looping over a while loop. If you look at some benchmark results, you would see something like this: Using _.range(1, 1000): 67.67% slower https://jsbench.me/b2jl4vvgnw/1 So with all that, I think it's better to write this using a while loop, and with a slight modification, I would write it as: function calculateLevel(exp) { var level = 1; if (exp &gt; 83){ var calcExp = 0; while(level &lt;= 1000){ calcExp += parseInt(level + 300 * Math.pow(2, level/7)); if (exp &lt; Math.floor(calcExp/4)) break; level++; } } return level; } Hope it helps!!
answers question: http://stackoverflow.com/q/51951533

http://stackoverflow.com/comment/90809835
type: AnswerComment
type: Comment
has text: @iMath Looked deeper. This is a bug.
comment on: http://stackoverflow.com/a/51821910
score: 1

http://stackoverflow.com/q/51907281
type: Question
has comment: http://stackoverflow.com/comment/92361442
tagged with: anaconda
score: 4
has comment: http://stackoverflow.com/comment/92803087
has comment: http://stackoverflow.com/comment/100544774
has comment: http://stackoverflow.com/comment/99617220
has comment: http://stackoverflow.com/comment/92807533
has body: I'm new to python. I'm using Pycharm 2018.2 and the latest version of Anaconda. My operating system is windows 10. After solving all problems with installing textract on windows 10, I got a positive installation result from the anaconda prompt. Additionally, I have imported the Project Interpreter from \continuum\anaconda3\python.exe. I want to extract text from large .pdf files and save it to .txt files. I have tried using the test_pdf.py files from textract, but they didn't work. Here is the end code (own translation from German): "textract" is wrong written or can't be found So I tried my own, following the textract page. But it doesn't work either: Here's my code: import textract text = textract.process('pfad/large.pdf') Results: C:\Users\raz\AppData\Local\Continuum\anaconda3\python.exe "C:/Users/raz/Google Drive/FOM/Master/Master/NurText/Testo.py" Traceback (most recent call last): File "C:\Users\raz\AppData\Local\Continuum\anaconda3\lib\site-packages\textract-1.6.1-py3.6.egg\textract\parsers\utils.py", line 85, in run stdout=subprocess.PIPE, stderr=subprocess.PIPE, File "C:\Users\raz\AppData\Local\Continuum\anaconda3\lib\subprocess.py", line 709, in init restore_signals, start_new_session) File "C:\Users\raz\AppData\Local\Continuum\anaconda3\lib\subprocess.py", line 997, in _execute_child startupinfo) FileNotFoundError: [WinError 2] Das System kann die angegebene Datei nicht finden During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:/Users/raz/Google Drive/FOM/Master/Master/NurText/Testo.py", line 2, in text = textract.process('pfad/large.pdf') File "C:\Users\raz\AppData\Local\Continuum\anaconda3\lib\site-packages\textract-1.6.1-py3.6.egg\textract\parsers_init_.py", line 77, in process return parser.process(filename, encoding, **kwargs) File "C:\Users\raz\AppData\Local\Continuum\anaconda3\lib\site-packages\textract-1.6.1-py3.6.egg\textract\parsers\utils.py", line 46, in process byte_string = self.extra…
favorite count: 0
type: UnansweredQuestion
has title: Why can't I read pdf files using python textract?
tagged with: python
upvote count: 4
tagged with: text-extraction
answer count: 0
downvote count: 0

http://stackoverflow.com/q/51823655
type: Question
has title: How can I modify this regex pattern so that once it finds a match it returns the whole sentence, not just the words it matched?
score: 3
has comment: http://stackoverflow.com/comment/90603704
has comment: http://stackoverflow.com/comment/90601635
upvote count: 4
has comment: http://stackoverflow.com/comment/90601755
has comment: http://stackoverflow.com/comment/90603967
accepted answer: http://stackoverflow.com/a/51823979
has answer: http://stackoverflow.com/a/51825294
favorite count: 0
answer count: 5
tagged with: python
tagged with: regex
possible better answer: http://stackoverflow.com/a/51823822
has answer: http://stackoverflow.com/a/51823932
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51823822
has body: As the title explains this regex pattern basically checks the description variable for matching word combinations within set, eg: set = ["oak", "wood"] then if it finds those 2 words within a 5 word spacing it will return those words. However, I need it to return the matching sentence. So if for example the description was: description = "...would be a lovely addition to any home. This lovely oak hard wood table comes in a variety of sizes. Another great reason to consider..." instead of just returning the matching words I want it to return the entire sentence that contains the keywords. This is what I'm working with at the moment which obviously just returns the matching set pair. re.findall(r"\b(?:(%s)\W+(?:\w+\W+){0,5}?(%s)|(%s)\W+(?:\w+\W+){0,5}?(%s))\b" % (set[0], set[1], set[1], set[0]), description) I'm also aware that I believe this pattern will look beyond a single sentence for a match and as such you might get a case where it finds a match over 2 different sentences. If possible I'd also like to find a way that restricts matches to only be possible within the same sentence. I'd appreciate any help I can get with this. EDIT: Just to clarify my desired output is: "This lovely oak hard wood table comes in a variety of sizes." As this is the sentence which contains the matching keyword pair. Thanks!
has answer: http://stackoverflow.com/a/51825439
has answer: http://stackoverflow.com/a/51823979
downvote count: 1

http://stackoverflow.com/comment/90591085
score: 0
type: Comment
type: QuestionComment
has text: @neverwalkaloner - What I do see is that the `my_api` function doesn't appear in the paths django searches while the other view functions in the same class do appear in this list.
comment on: http://stackoverflow.com/q/51818252

http://stackoverflow.com/comment/90589705
type: Comment
has text: Is there a chance, that the 'Zip' function would convert the List into a Tuple?
comment on: http://stackoverflow.com/a/51802436
type: AnswerComment
score: 0

http://stackoverflow.com/a/51888871
answers question: http://stackoverflow.com/q/51888539
score: 0
type: AcceptedAnswer
has body: txt=["30330036.jpg","1-30330036.jpg","1-30330036-1.jpg","1-30330036A.jpg"] regex=r"([\d+]-)?(\d+)(\w+)?(-[\d+])?.jpg" result=[re.search(regex,s).group(2) for s in txt] print(result) Output: ['30330036', '30330036', '30330036', '30330036']
accepted answer of: http://stackoverflow.com/q/51888539
has comment: http://stackoverflow.com/comment/90729323
type: Answer
has comment: http://stackoverflow.com/comment/90729930
has comment: http://stackoverflow.com/comment/90729013

http://stackoverflow.com/comment/90637529
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51835244
has text: This could work, but it also introduces some white space between the plots which seems like a waste of space.

http://stackoverflow.com/a/51941119
has comment: http://stackoverflow.com/comment/94356707
answers question: http://stackoverflow.com/q/51941013
upvote count: 2
has body: this is a common mistake for css selectors where the spaces are very important for the actual result of the selector. 'h1 a ::text' That says to get text from all inner elements below a, but what you need is: 'h1 a::text' That says to only get the text element from the a tag
type: Answer
score: 2
downvote count: 0

http://stackoverflow.com/comment/90756406
type: Comment
has text: Sorry, yes I tried that and still get the same error
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51902067

heatmap
tags question: http://stackoverflow.com/q/51953965
tags question: http://stackoverflow.com/q/51876744
tags question: http://stackoverflow.com/q/51865766
tags question: http://stackoverflow.com/q/51823126
type: Tag
tags question: http://stackoverflow.com/q/51798720
tags question: http://stackoverflow.com/q/51829462
tags question: http://stackoverflow.com/q/51824174
tag name: heatmap

http://stackoverflow.com/comment/90672675
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51853563
has text: Check the answer I posted above, that's what I ended up with after messing around with it for a little while. Works just like I imagined it! Your help is much appreciated!

http://stackoverflow.com/q/51827374
score: 2
type: AnsweredQuestion
upvote count: 2
possible better answer: http://stackoverflow.com/a/51827600
type: Question
has body: I'm trying to practice python because I'm starting yr 12 soon. I created a quiz game but when i get the question right it always says that it's wrong print("Welcome to the math quiz game!") for i in range(0,10): operators = ['+','-','*','/'] import random num1 = random.randint(1,10) num2 = random.randint(1,10) randop = random.choice(operators) question = input("What is %d %s %d: " % (num1,randop,num2)) if randop == "+": answer = num1 + num2 elif randop == "-": answer = num1 - num2 elif randop == "*": answer = num1 * num2 elif randop == "/": answer = num1 / num2 if question == answer: print("\nCorrect") elif question != answer: print("Incorrect or Invalid")
has answer: http://stackoverflow.com/a/51827520
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/90609319
favorite count: 0
has comment: http://stackoverflow.com/comment/90609047
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90609098
accepted answer: http://stackoverflow.com/a/51827520
has comment: http://stackoverflow.com/comment/90615936
tagged with: python
has answer: http://stackoverflow.com/a/51827600
has title: Python Quiz Game Logic Error

http://stackoverflow.com/comment/90842928
has text: Put `skiprows=1,` in your code instead of `skiprows=0,`. OR try replacing `file.txt` in my code to `v10.txt` and re-run it
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51945803

http://stackoverflow.com/comment/90717069
comment on: http://stackoverflow.com/q/51882644
has text: @tgikal Okay, it looks like I have to 'Edit with IDLE' options (probably one 64 bit and one 32). Not sure how that happened. Should I just uninstall one and keep the other?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90557424
type: AnswerComment
has text: Thank you very much. Pandas solved the problem but now i don't know how to acces single row of those that were selected in the first step. It selected rows 2,4,6 becasue they have ABC product, but now I'd like to get individualy to rows 2, 4, 6 and assigns cells that they contain to variables. Do you have any idea how to approach this step?
type: Comment
score: 0
comment on: http://stackoverflow.com/a/51800385

http://stackoverflow.com/q/51892710
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/63374349
tagged with: pip
tagged with: python
has body: I tried to pip install using proxy, the proxy setting is correct because it works for npm install . what i tried is as below shown but got error message. any idea will be more than welcome! set http_proxy=http://&lt;username&gt;:&lt;password&gt;@&lt;proxy_server&gt;:&lt;port&gt; set https_proxy=https://&lt;username&gt;:&lt;password&gt;@&lt;proxy_server&gt;:&lt;port&gt; pip install Flask Collecting Flask Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', OSError('Tunnel connection failed: 407 Proxy Authentication Required'))': /simple/flask/ Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', OSError('Tunnel connection failed: 407 Proxy Authentication Required'))': /simple/flask/ Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', OSError('Tunnel connection failed: 407 Proxy Authentication Required'))': /simple/flask/ Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', OSError('Tunnel connection failed: 407 Proxy Authentication Required'))': /simple/flask/ Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', OSError('Tunnel connection failed: 407 Proxy Authentication Required'))': /simple/flask/ Could not find a version that satisfies the requirement Flask (from versions: ) No matching distribution found for Flask
answer count: 4
linked to: http://stackoverflow.com/q/14149422
has title: pip install package via proxy
type: Question
upvote count: 9
has answer: http://stackoverflow.com/a/51893057
downvote count: 0
linked to: http://stackoverflow.com/q/43473041
favorite count: 0
has comment: http://stackoverflow.com/comment/90741655
has answer: http://stackoverflow.com/a/75560272
score: 9
has answer: http://stackoverflow.com/a/51893002

http://stackoverflow.com/comment/90748616
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51898761
has text: Do you want every combo? `Sam-Mall` `Sam-Place` `Sam-Thing` etc?
type: Comment

http://stackoverflow.com/a/51867059
answers question: http://stackoverflow.com/q/51867012
type: Answer
upvote count: 6
accepted answer of: http://stackoverflow.com/q/51867012
has body: Using np.trim_zeros: Trim the leading and/or trailing zeros from a 1-D array or sequence. out = pd.DataFrame([np.trim_zeros(i) for i in df.values], index=df.index) out.columns = df.columns[:len(out.columns)] c1 c2 c3 c4 c5 c6 c7 index 1 1 2 3 4.0 5.0 NaN NaN 2 1 2 3 4.0 5.0 NaN NaN 3 1 2 3 NaN NaN NaN NaN 4 1 2 3 4.0 NaN NaN NaN 5 1 2 3 4.0 5.0 6.0 7.0 6 1 0 0 4.0 NaN NaN NaN
score: 6
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/51830558
has answer: http://stackoverflow.com/a/51834513
tagged with: scikit-learn
favorite count: 0
type: UnansweredQuestion
has title: Does sklearn LogisticRegressionCV use all data for final model
linked to: http://stackoverflow.com/q/44036193
tagged with: python
linked to: http://stackoverflow.com/q/49455806
has body: I was wondering how the final model (i.e. decision boundary) of LogisticRegressionCV in sklearn was calculated. So say I have some Xdata and ylabels such that Xdata # shape of this is (n_samples,n_features) ylabels # shape of this is (n_samples,), and it is binary and now I run from sklearn.linear_model import LogisticRegressionCV clf = LogisticRegressionCV(Cs=[1.0],cv=5) clf.fit(Xdata,ylabels) This is looking at just one regularization parameter and 5 folds in the CV. So clf.scores_ will be a dictionary with one key with a value that is an array with shape (n_folds,1). With these five folds you can get a better idea of how the model performs. However, I'm confused about what you get from clf.coef_ (and I'm assuming the parameters in clf.coef_ are the ones used in clf.predict). I have a few options I think it could be: The parameters in clf.coef_ are from training the model on all the data The parameters in clf.coef_ are from the best scoring fold The parameters in clf.coef_ are averaged across the folds in some way. I imagine this is a duplicate question, but for the life of me I can't find a straightforward answer online, in the sklearn documentation, or in the source code for LogisticRegressionCV. Some relevant posts I found are: GridSearchCV final model scikit-learn LogisticRegressionCV: best coefficients Using cross validation and AUC-ROC for a logistic regression model in sklearn Evaluating Logistic regression with cross validation
tagged with: machine-learning
upvote count: 10
downvote count: 1
linked to: http://stackoverflow.com/q/49562046
score: 9
type: Question
has answer: http://stackoverflow.com/a/71959964
has answer: http://stackoverflow.com/a/51830686
tagged with: cross-validation
linked to: http://stackoverflow.com/q/39163354
answer count: 3

http://stackoverflow.com/q/51824191
has title: Python kivy text to speech and Popup in parallel
answer count: 1
has comment: http://stackoverflow.com/comment/90618778
tagged with: python
tagged with: kivy
tagged with: parallel-processing
type: AnsweredQuestion
has body: I am trying to implement a warning which is using text to speech and a visual warning as popup which should disappear after few seconds. I am using kivy for the user interface. At the moment the code is running with the popup and the voice warning, but the problem is, that the voice warning starts first (I would rather like the popup warning to be first) and I additionally would like both processes to start at the same time. I was not able to solve this issue using multiprocessing.Process(target.display_warning_popup).start() and multiprocessing.Process(target.display_warning_voice).start(). Followed by multiprocessing.Process(target.display_warning_popup).join() and multiprocessing.Process(target.display_warning_voice).join(). This is a snippet of the code that I am using. # imports import pyttsx3 # for text to speech from kivy.uix.popup import Popup from kivy.uix.label import Label from kivy.clock import Clock class MainApp(App): engine = pyttsx3.init() # function for displaying popup def display_warning_popup(): content = Label(text="Please reduce the temperature.") content.color = (1, 1, 1, 1) popup = Popup(title="Warning", content=content, size_hint=(None, None), size=(350, 150)) popup.open() Clock.schedule_once(popup.dismiss, 2) # function for text to speech def display_warning_voice(self): self.engine.say("Temperature is too high") self.engine.runAndWait() # function for warning def warning(self, is_temperature_too_high): if is_temperatrue_too_high: self.display_warning_popup() self.display_warning_voice()
score: 0
has answer: http://stackoverflow.com/a/51844491
type: Question
has comment: http://stackoverflow.com/comment/90623558
accepted answer: http://stackoverflow.com/a/51844491
tagged with: function

http://stackoverflow.com/q/51895560
has comment: http://stackoverflow.com/comment/90742098
possible better answer: http://stackoverflow.com/a/51913256
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51895901
score: 0
tagged with: web-scraping
has body: I have the following page: http://greyhoundbet.racingpost.com/#card/race_id=1632746&amp;r_date=2018-08-17&amp;tab=form It contains a series of information organized in "tables". I need to "extract" that information (rows and columns) to manipulate the info later. Knowing that I'm a newbie, i tried to do it with bs4 with python but I wasn't successful. What would you recomend ? 1) Should I use a program language that would allow me to read the text from the page (which one should I use ? what sould I look for?) and then manipulate it ? 2) Can I get the text manually (ctrl+c) and send it to python somehow ? How would you get the info from the page in the easiest way to later work with the data ? Thank you all and I'm sorry if this is a dumb question. I've been struggling with that for the past week. Regards, P. EDIT: I was thinking in use an object oriented approach to separate every greyhound and to study each number. Maybe its better to do it in C# ?
type: Question
answer count: 2
tagged with: text-parsing
accepted answer: http://stackoverflow.com/a/51895901
has answer: http://stackoverflow.com/a/51913256
tagged with: parsing
tagged with: beautifulsoup
has comment: http://stackoverflow.com/comment/90741863
has title: How to extract text from this specific page ? Unable to do so with bs4+python

http://stackoverflow.com/q/51838785
linked to: http://stackoverflow.com/q/7277072
type: Question
score: -5
has title: Add range of numbers to each element in a list
answer count: 2
has body: I would like to add numbers to the end of each string in a list. Example: a = ['a', 'b', 'c'] b = list(range(0, 3)) Expected result: c = ['a0', 'a1', 'a2', 'b0', 'b1', 'b2', 'c0', 'c1', 'c2']
has comment: http://stackoverflow.com/comment/90630591
favorite count: 0
has answer: http://stackoverflow.com/a/51838847
tagged with: python
has answer: http://stackoverflow.com/a/51839057
duplicate of: http://stackoverflow.com/q/7277072
upvote count: 0
downvote count: 5
type: UnansweredQuestion

http://stackoverflow.com/a/51890025
accepted answer of: http://stackoverflow.com/q/51888661
type: Answer
upvote count: 4
downvote count: 0
has body: Do a morphological closing (explanation) to fill those tiny gaps, to complete the circles. Then fill the resulting binary image. Code : from skimage import io from skimage.morphology import binary_closing, disk import scipy.ndimage as nd import matplotlib.pyplot as plt # Read image, binarize I = io.imread("FillHoles.png") bwI =I[:,:,1] &gt; 0 fig=plt.figure(figsize=(24, 8)) # Original image fig.add_subplot(1,3,1) plt.imshow(bwI, cmap='gray') # Dilate -&gt; Erode. You might not want to use a disk in this case, # more asymmetric structuring elements might work better strel = disk(4) I_closed = binary_closing(bwI, strel) # Closed image fig.add_subplot(1,3,2) plt.imshow(I_closed, cmap='gray') I_closed_filled = nd.morphology.binary_fill_holes(I_closed) # Filled image fig.add_subplot(1,3,3) plt.imshow(I_closed_filled, cmap='gray') Result : Note how the segmentation trash has melded to your object on the lower right and the small cape on the lower part of the middle object has been closed. You might want to continue with an morphological erosion or opening after this. EDIT: Long response to comments below The disk(4) was just the example I used to produce the results seen in the image. You will need to find a suitable value yourself. Too big of a value will lead to small objects being melded into bigger objects near them, like on the right side cluster in the image. It will also close gaps between objects, whether you want it or not. Too small of a value will lead to the algorithm failing to complete the circles, so the filling operation will then fail. Morphological erosion will erase a structuring element sized zone from the borders of the objects. Morphological opening is the inverse operation of closing, so instead of dilate->erode it will do erode->dilate. The net effect of opening is that all objects and capes smaller than the structuring element will vanish. If you do it after filling then the large objects will stay relatively the same. Ideally it should remove a l…
has comment: http://stackoverflow.com/comment/90747494
score: 4
has comment: http://stackoverflow.com/comment/90747557
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51888661
has comment: http://stackoverflow.com/comment/90747335

http://stackoverflow.com/q/51918091
has comment: http://stackoverflow.com/comment/90787892
has comment: http://stackoverflow.com/comment/90786078
has body: for a subject I am implementing the Hill Cipher example from wikipedia using numpy. My code so far is below: import numpy as np msg = np.array([0, 2, 19]) # CAT key = np.matrix([ [6, 24, 1], [13, 16, 10], [20, 17, 15] ]) ciphertext = np.mod(np.dot(key, msg), 26) # [5, 8, 13] # POH # And here things go wrong invKey = key.I invKey2 = np.linalg.inv(key) # same as key.I Until line 10 ("ciphertext") things work as they should. np.mod(np.dot(key, msg), 26) returns [15, 14, 7], as specified in the article. But when I try to do a matrix inverse I get drastically different results than I expected. The article suggests that the key matrix inverse should return this: [[8, 21, 21], [5, 8, 12], [10, 21, 8]] But instead this is returned: [[ 0.15873016 -0.77777778 0.50793651] [ 0.01133787 0.15873016 -0.10657596] [-0.2244898 0.85714286 -0.48979592]] Now, I can understand from various questions on this site that numpy.linalg.inv() has a problem with floating point precision. But these results are so different from the expected that there must be more going on right? I am new to numpy. Please help me understand what is going on here and how I can alleviate the problem, so the key matrix is inverted as the article specifies. Thank you for your time.
tagged with: python
has answer: http://stackoverflow.com/a/51919127
has comment: http://stackoverflow.com/comment/90786160
score: 0
answer count: 1
has title: incorrect Matrix inverse result
type: UnansweredQuestion
tagged with: numpy
tagged with: security
has comment: http://stackoverflow.com/comment/90786165
linked to: http://stackoverflow.com/q/4287721
has comment: http://stackoverflow.com/comment/90786912
type: Question

http://stackoverflow.com/q/51799320
tagged with: permutation
has title: Python permutations for array of elements with specific repetitions
favorite count: 0
has answer: http://stackoverflow.com/a/51799461
linked to: http://stackoverflow.com/q/6284396
has answer: http://stackoverflow.com/a/51800721
accepted answer: http://stackoverflow.com/a/51800721
tagged with: python
possible better answer: http://stackoverflow.com/a/51799461
answer count: 4
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51799703
score: 1
has comment: http://stackoverflow.com/comment/90557508
has answer: http://stackoverflow.com/a/51800242
type: Question
tagged with: combinations
has comment: http://stackoverflow.com/comment/90556144
has body: How would I compute permutations of an array of elements, each repeated for a certain number of times within the permutation, in the fastest possible way? For example: elements = [0, 1] repetitions = [2, 3] I want it to return the 10 unique permutations: [(0, 0, 1, 1, 1), (0, 1, 0, 1, 1), (1, 0, 1, 0, 1) ....]
duplicate of: http://stackoverflow.com/q/6284396
upvote count: 2
downvote count: 1

http://stackoverflow.com/a/51842431
downvote count: 0
score: 2
type: Answer
upvote count: 2
has comment: http://stackoverflow.com/comment/90638070
has comment: http://stackoverflow.com/comment/90637953
has body: Use .days Ex: from datetime import date import random earlier_date = date(2017, 6, random.randint(1, 25)) later_date = date(2017, 6, random.randint(earlier_date.day + 1, 28)) days_between= (later_date- earlier_date).days #Update! print("There are", days_between, "days between", earlier_date, "and", later_date)
answers question: http://stackoverflow.com/q/51842381

http://stackoverflow.com/comment/90647013
score: 0
has text: @Fian I am aware of the ping_timeout feature, the event still isn't being triggered. socketio = SocketIO(ping_interval=2, ping_timeout=4) This is my current configuration, which means the disconnect event should be fired 4 seconds after the client disconnects. However, the disconnect even is not fired after 4 seconds. In fact, as far as I can tell, it is never fired (I have tried waiting 10 minutes for it).
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51831141

http://stackoverflow.com/q/51868735
tagged with: pyautogui
answer count: 2
has body: I am trying to get pyautogui to copy a number, then turn that number into a variable. Here is my code that is trying to achieve that but it just returns "none". How do I fix this? I want it to copy the number then turn test1 into that number amount. pyautogui.mouseDown() pyautogui.moveRel(100, 0) #####FIND DOLLAR AMOUNT MOVE pyautogui.mouseUp() pyautogui.hotkey('ctrl', 'c') test1 = pyautogui.hotkey('ctrl', 'v') print(test1)
downvote count: 0
has answer: http://stackoverflow.com/a/56455749
favorite count: 0
has title: How to have pyautogui turn a hotkey into a variable
tagged with: python
score: 2
upvote count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51868975
type: Question

http://stackoverflow.com/a/51936496
upvote count: 1
score: 1
has body: You can break this down into simpler problems, which I assume exist in networkx. Let E and V be the number of edges and vertices in your original graph respectively. Let F be the number of vertices that must be in your cycle (3 in your example: nodes 1, 2 and 4). From now on, I'll refer to them as cycle vertices. Algorithm: Compute the distance between each cycle vertex. If you use Dijkstra's algorithm, it's O(E + V log V) for each cycle vertex, so O(FE + FV log V) in total. Solve the travelling salesman problem over the cycle vertices using the edge weights from step 1, which will cost O(F!). There are approximate algorithms with much better time complexity if this becomes a significant bottleneck. Total cost is O(max(FE, FVlogV, F!)). It is likely that the F! term will dominate.
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90831528
accepted answer of: http://stackoverflow.com/q/51933464
downvote count: 0
answers question: http://stackoverflow.com/q/51933464
type: Answer

http://stackoverflow.com/comment/90717131
type: QuestionComment
has text: I'd check here, https://stackoverflow.com/questions/39015410/windows-python-64-32-bit-versions-and-pip, for installing 32 vs 64
comment on: http://stackoverflow.com/q/51882644
score: 0
type: Comment

http://stackoverflow.com/comment/90576969
has text: @jezrael in this way it would convert to `Timestamp`, and pyplot doesnt seem to understand this format.
score: 0
comment on: http://stackoverflow.com/q/51810888
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51876056
downvote count: 0
type: Answer
has body: I guess you could use csv...? The syntax is pretty straightforward: &gt;&gt;&gt; import csv &gt;&gt;&gt; with open('eggs.csv', 'rb') as csvfile: ... spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|') ... for row in spamreader: ... print ', '.join(row) Spam, Spam, Spam, Spam, Spam, Baked Beans Spam, Lovely Spam, Wonderful Spam Using this approach, I'd just read 30MB at a time, and spool out the read contents to another csv. Given you have the vector contents in row, you'll be able to ascertain the per-row size, and determine how many rows make ~30MB, so hopefully this will get you started. Also, given the constraint about c2, you might end up opening up several csv's so that each csv will contain its respective c2 grouping. Each row is a vector, so in the example you gave, that would appear to be the second element.
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/51875916

http://stackoverflow.com/comment/90866935
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51954792
has text: @eryksun But again, this code is never going to `join` again if any exception happens, so that's not going to be a problem, right? Obviously polling has other problems, as I explained in my answer, but the OP seems to be happy with those problems, so the question is whether there's an additional one that I didn't warn him about.
type: AnswerComment

http://stackoverflow.com/comment/122989167
type: Comment
comment on: http://stackoverflow.com/a/51824838
score: 0
type: AnswerComment
has text: Using module name `pycryptodomex` worked for me! thanks.

http://stackoverflow.com/comment/90748076
has text: Visit docopt.org website. It's a python package designed specifically for -arg while running python scripts from cmd
comment on: http://stackoverflow.com/q/51898042
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90727652
has text: If i remove the first print.. i didn’t see anything on my screen.
comment on: http://stackoverflow.com/q/51888134
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51937806
has comment: http://stackoverflow.com/comment/90828571
has title: Pandas - Binary Matrix and String Data (how to stack string data / new line?)
has answer: http://stackoverflow.com/a/51955932
has answer: http://stackoverflow.com/a/52411184
accepted answer: http://stackoverflow.com/a/52411184
has comment: http://stackoverflow.com/comment/90827974
score: 0
answer count: 3
tagged with: pandas
has comment: http://stackoverflow.com/comment/90828184
has comment: http://stackoverflow.com/comment/90830476
has comment: http://stackoverflow.com/comment/90827415
has comment: http://stackoverflow.com/comment/90851866
tagged with: python
has comment: http://stackoverflow.com/comment/90851021
has comment: http://stackoverflow.com/comment/90826891
type: AnsweredQuestion
has body: I am trying to generate a particularly structured dataframe, but i cant seem to "stack" the data. My sample raw data: # raw data df = pd.DataFrame({'Name':['name1', 'name2', 'name3', 'name1', 'name2', 'name3', 'name1', 'name2', 'name3' ], 'Year':['freshman','sophomore','freshman', 'freshman','sophomore','freshman', 'freshman','sophomore','freshman'], 'Rotation':['ERJD','PEDI','MAM','PEDI', 'ERJD','PEDI','MAM','ERJD','ABD'], 'Week1':[1,1,1,0,0,0,0,0,0], 'Week2':[0,0,0,1,1,1,0,0,0], 'Week3':[0,0,0,0,0,0,1,1,1], 'Week4':[1,0,0,0,0,0,0,1,1] }) df = df'Name','Year','Rotation','Week1','Week2','Week3','Week4' Which looks like: Name Year Rotation Week1 Week2 Week3 Week4 0 name1 freshman ERJD 1 0 0 1 1 name2 sophomore PEDI 1 0 0 0 2 name3 freshman MAM 1 0 0 0 3 name1 freshman PEDI 0 1 0 0 4 name2 sophomore ERJD 0 1 0 0 5 name3 freshman PEDI 0 1 0 0 6 name1 freshman MAM 0 0 1 0 7 name2 sophomore ERJD 0 0 1 1 8 name3 freshman ABD 0 0 1 1 I reshape the dataframe: #Reshape Table + Filtering df = pd.melt(df, id_vars=['Name','Year','Rotation'], value_vars=list(df.columns[3:]), var_name='Week', value_name='Sum of Value') df = df.loc[df['Sum of Value'] == 1].reset_index() df.pop('index') Which Generates: Name Year Rotation Week Sum of Value 0 name1 freshman ERJD Week1 1 1 name2 sophomore PEDI Week1 1 2 name3 freshman MAM Week1 1 3 name1 freshman PEDI Week2 1 4 name2 sophomore ERJD Week2 1 5 name3 freshman PEDI Week2 1 6 name1 freshman MAM Week3 1 7 name2 sophomore ERJD Week3 1 8 name3 freshman ABD Week3 1 9 name1 freshman ERJD Week4 1 10 name2 sophomore ERJD Week4 1 11 name3 freshman ABD Week4 1 I create a pivot table: #Create Pivot pivot = df.pivot_table(index=['Rotation','Year'], columns='Week', values='Name', aggfunc=lambda x: ' '.join(x)) pivot = pivot.reindex(weeks, axis=1) # Change order of Columns pivot Which generates: Week1 Week2 Week3 Week4 Rotation Year ABD freshman None None name3 name3 ERJD freshman name1 None None name1 sophomore None name2 name2 name2 MAM freshman…
possible better answer: http://stackoverflow.com/a/51951676
has answer: http://stackoverflow.com/a/51951676
type: Question

http://stackoverflow.com/comment/90830481
has text: Mate, you should Google. Use `roll.split('d')`. For more on the subject, check here - https://docs.python.org/3.7/library/stdtypes.html#str.split This is not a question that should appear on StackOverflow.
type: Comment
comment on: http://stackoverflow.com/q/51940291
score: 0
type: QuestionComment

http://stackoverflow.com/comment/90589201
type: QuestionComment
comment on: http://stackoverflow.com/q/51817384
score: 0
has text: Uhhh maybe because `current_section`'s supposed to be `'AM'` instead of `'PM'` (as it is in your code) ?
type: Comment

gmail
type: Tag
tags question: http://stackoverflow.com/q/51944861
tags question: http://stackoverflow.com/q/51857925
tags question: http://stackoverflow.com/q/51907836
tags question: http://stackoverflow.com/q/51805184
tag name: gmail

http://stackoverflow.com/comment/90652592
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51834424
score: 1
has text: python is in red because it is/was a symbolic link to another file. Do a `ls -lsa /usr/bin/python*`. It should show you to which file it was supposed to link

http://stackoverflow.com/comment/90830773
comment on: http://stackoverflow.com/a/51940321
score: 0
type: AnswerComment
type: Comment
has text: @JonasByström If you can solve the recurrence relation in terms of `i`, you can make some improvements to your loop and maybe apply numpy to it.

http://stackoverflow.com/a/51955178
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90861311
answers question: http://stackoverflow.com/q/51954912
score: 0
has body: The problem is that your are wrapping amf between brackets df=[amf] making it a list of arrays, change it to df=amf, for instance: data = [np.array([6.685, 6.84, 7.0, 7.16, 7.33, 7.51, 7.70])] result = pd.DataFrame(data=data) print(result.shape) returns: (1, 7) that is 1 column and 7 rows, however: data = np.array([6.685, 6.84, 7.0, 7.16, 7.33, 7.51, 7.70]) result = pd.DataFrame(data=data) print(result.shape) returns (7, 1), also you need to set the columns of the DataFrame: import numpy as np import pandas as pd data = np.array([6.685, 6.84, 7.0, 7.16, 7.33, 7.51, 7.70]) result = pd.DataFrame(data=data, columns=['amf']) print(result) Output: amf 0 1 1 2 2 3 3 4 4 5 5 6
has comment: http://stackoverflow.com/comment/90863520
type: Answer
has comment: http://stackoverflow.com/comment/90862779
accepted answer of: http://stackoverflow.com/q/51954912

http://stackoverflow.com/a/51863185
has comment: http://stackoverflow.com/comment/90689297
answers question: http://stackoverflow.com/q/51862994
type: Answer
accepted answer of: http://stackoverflow.com/q/51862994
score: 2
downvote count: 0
has body: First, let’s write this with a loop, which is more pythonic and also probably easier for a novice to understand: def count(nums): res = 0 for num in nums: res = 1 + res return res def sum(nums): res = 0 for num in nums: res = num + res return res The same one-word difference in the + operation. But now, hopefully you can understand why it’s different. The first one starts with 0, and adds 1 to that, once per element. The second one starts with 0, and adds the element to that, once per element. The recursive code is doing basically the same thing, except a bit more complicated. What it’s actually doing is pushing each element onto a stack, then starting with 0, then popping the stack until it’s empty, adding 1 or the element (respectively) for each element popped off the stack.1 But pushing a bunch of elements onto a stack and popping them off gives you the same elements, just in reverse. And adding 1 once per element, or adding up all of the elements, does the same thing counting backward as counting forward. If you still don't understand, you should try stepping through the calls. Normally I'd suggest using an interactive visualizer, like Python Tutor, but since this problem seems specifically designed to make you think functionally, let's do it that way. Imagine that function calls in Python were just a matter of substituting in the arguments for the parameters.2 So: count([1,2,3]) = 0 if len([1,2,3]) == 0 else 1 + count([2,3]) = 1 + count([2,3]) = 1 + (0 if len([2,3]) == 0 else 1 + count([3])) = 1 + (1 + count([3])) = 1 + (1 + (0 if len([3]) == 0 else 1 + count([]))) = 1 + (1 + (1 + count([]))) = 1 + (1 + (1 + (0 if len([]) == 0 else 1 + count([]))))) = 1 + (1 + (1 + (0))) = 1 + (1 + (1)) = 1 + (2) = 3 sum([5,10,1]) = 0 if len([5,10,1]) == 0 else 5 + count([10,1]) = 5 + count([10,1]) = 5 + (0 if len([10,1]) == 0 else 10 + count([1])) = 5 + (10 + count([3])) = 5 + (10 + (0 if len([3]) == 0 else 1 + count([]))) = 5 + (10 + (1 + count([]))) = 5 + (10 + (1 + (0 if le…
upvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/q/51812245
has body: I am trying to match the keys in two dictionaries (one nested) and if they match, add a value to the inner dictionary of the nested dictionary. The code I am using is: dict_z ={} for key, value in full_dict.items(): match_name_full_1 = key[:-3] match_name_full_2 = key[:-4] for key_path, value_path in paths_dict.items(): if match_name_full_1 == key_path or match_name_full_2 == key_path: dict_z.update({key: value, 'path' : value_path}) print(dict_z) The output I get however is 'Key': {x: 1, y: 1}, z: 1 When I would like: 'Key': {x: 1, y: 1, z: 1} Any help is greatly appreciated.
score: 1
type: Question
has title: Matching keys of two dictionaries (one nested) then adding value to inner nested dictionary
has answer: http://stackoverflow.com/a/51812877
accepted answer: http://stackoverflow.com/a/51812877
has comment: http://stackoverflow.com/comment/90580485
upvote count: 1
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/90579411
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/comment/90653913
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51850166
has text: Are you sure the php script has permissions to access the files under `/home/pi`? If the php script is run by Apache, then its user/group is most likely `www-data` or `http`.
type: Comment

http://stackoverflow.com/a/51882201
type: AcceptedAnswer
downvote count: 0
score: 4
has comment: http://stackoverflow.com/comment/90720165
type: Answer
answers question: http://stackoverflow.com/q/51881958
has body: A Python float is a fully-featured object, which knows its type (so it has methods) and can be garbage collected and so on. In CPython (the Python implementation you’re probably using), this works by storing a pointer to the type object (8 bytes) and a reference count (8 more bytes) along with the actual IEEE float64 value (8 more bytes), so it’s at least 24 bytes long. A list just stores references to Python objects. So, a list of a half million floats will take a bit over 4MB for the list itself (storing all those references), plus all those referenced float objects will take another 12MB in total. An array.array doesn’t store float objects, it just stores the bits of the IEEE float64 value (8 bytes), and then creates those float objects on the fly whenever you ask for one with, e.g., arr[0]. This makes it a lot smaller—the whole thing only takes 4MB in memory—but also slower.1 And of course you aren’t even storing an array of IEEE float64 (that’s d, not f), but float32. Half a million of those takes 2MB. If you want the best of both worlds, the third-party library NumPy can store the bits the same way array.array does, and it can do calculations on those bits without having to create and destroy float objects all over the place, so it’s both smaller and faster. So, when you ask for the size of an array of 500K f floats, that’s 2MB, because it stores only the 500K native IEEE float32 values (plus a few dozen bytes of fixed overhead). But when you loop over that array, counting the size of each member, you’re actually creating 24-byte float objects on the fly. The total size of all of those temporary objects is 12MB. But they’re temporary—as soon as you check the size of each one, you forget about it, it becomes garbage and gets cleaned up, and the same 24 bytes can be reused for the next one. As for why Task Manager shows your memory go up by 3MB: Almost every program works by having a heap of memory, allocating out of that heap, and only asking the OS for more me…
has comment: http://stackoverflow.com/comment/90750655
has comment: http://stackoverflow.com/comment/90750582
has comment: http://stackoverflow.com/comment/90750322
accepted answer of: http://stackoverflow.com/q/51881958
upvote count: 4

http://stackoverflow.com/comment/90646595
has text: Multiprocessing (including via `concurrent.futures`) passes data between processes by pickling it, passing the pickle over an IPC pipe or queue, then unpickling on the other side. If you try this with an `mmap.mmap` you get an exception. If you try it with a `np.memmap` I’m not sure what happens, but my suspicion is that it pickles the array with all of its data, sends that, and unpickles it, so instead of getting an array mapping the same file, you end up with a copy of the array in newly-allocated memory. Which would explain exactly what you’re seeing.
comment on: http://stackoverflow.com/q/51844679
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51955417
has comment: http://stackoverflow.com/comment/90862519
has title: Triggering a task in Airflow with the CLI run command
type: Question
has comment: http://stackoverflow.com/comment/90899446
tagged with: airflow
has comment: http://stackoverflow.com/comment/90894641
has comment: http://stackoverflow.com/comment/90893801
has comment: http://stackoverflow.com/comment/90863810
has comment: http://stackoverflow.com/comment/91443557
answer count: 1
has comment: http://stackoverflow.com/comment/90893745
has comment: http://stackoverflow.com/comment/90898914
favorite count: 0
has answer: http://stackoverflow.com/a/52247885
has body: How do I trigger a specific task in an Airflow (v1.8.1) DAG using the run command from the CLI? DAG dag = DAG( 'test_run', default_args=default_args, schedule_interval=SCHEDULE_INTERVAL, catchup=False ) one = BashOperator( task_id='one', bash_command='echo 1', dag=dag, ) two = BashOperator( task_id='two', bash_command='echo 2', dag=dag, ) one.set_downstream(two) Command airflow run -i -I -f test_run two 2018-08-21T18:59:51 I've tried the -i, -I and -f commands without any luck and without error. I've also tried -A for ignoring all dependencies, but that fails telling me there is no execution date in the command. If I run the same command but specify task one, I can see that successfully show in the task instance list, but I cannot seem to run task two while completely ignoring task one. Actual output when attempting to run two. datauser@ubuntu-xenial:/home/vagrant$ AIRFLOW_HOME=~/code/dataprocessing/ /virtualenvs/dataprocessing/bin/airflow run -i -I -f test_run two 2018-08-21T18:59:51 /virtualenvs/dataprocessing/lib/python3.5/site-packages/psycopg2/__init__.py:144: UserWarning: The psycopg2 wheel package will be renamed from release 2.8; in order to keep installing from binary please use "pip install psycopg2-binary" instead. For details see: &lt;http://initd.org/psycopg/docs/install.html#binary-install-from-pypi&gt;. """) [2018-08-21 19:11:51,538] {__init__.py:57} INFO - Using executor CeleryExecutor [2018-08-21 19:11:51,624] {driver.py:120} INFO - Generating grammar tables from /usr/lib/python3.5/lib2to3/Grammar.txt [2018-08-21 19:11:51,650] {driver.py:120} INFO - Generating grammar tables from /usr/lib/python3.5/lib2to3/PatternGrammar.txt Sending to executor. INFO:root:The key logs/test_run/two/2018-08-21T18:59:51 now contains 101162 bytes And digging into the logs, I can see: [2018-08-21 19:13:49,796] {base_task_runner.py:95} INFO - Subtask: [2018-08-21 19:13:49,795] {models.py:1122} INFO - Dependencies not met for &lt;TaskInstance: test_run.two 2018-08-21 18:59…
has comment: http://stackoverflow.com/comment/90862382
upvote count: 3
accepted answer: http://stackoverflow.com/a/52247885
tagged with: python
downvote count: 1
score: 2
type: AnsweredQuestion

http://stackoverflow.com/comment/90759717
comment on: http://stackoverflow.com/q/51900158
type: Comment
type: QuestionComment
has text: @RomanKonoval to dumb it down, i am just trying to compare the stock column for each row every time i request the api.
score: 0

http://stackoverflow.com/comment/132751650
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51831540
type: Comment
has text: In PyCharm 2022.2.4 the option in that menu now reads "Allow parallel run"

http://stackoverflow.com/q/51863721
has comment: http://stackoverflow.com/comment/90679646
has comment: http://stackoverflow.com/comment/90680057
has comment: http://stackoverflow.com/comment/90690698
tagged with: unit-testing
type: Question
has body: I'm writing a test suite in Pytest. I have a fixture that looks something like this: import pytest @pytest.fixture(scope="session", params=["cpu", "gpu"]) def device(request): return request.param This is because I want my code to work identically on both CPUs and GPUs. (This fact is technically not relevant to my question, but I wanted to give a practical example of my use case.) All other fixtures representing device-independent code depend on device, like so: @pytest.fixture(scope="session") def data(device): return LoadData(path, device) So far so good. Any test that uses load_data is called twice: def test_data_is_loaded(data): assert data.success But here's my problem: What if I want to compare the output of two different parametrizations of the same fixture? def test_devices_load_same_amount_of_data(data_cpu, data_gpu): assert len(data_cpu) == len(data_gpu) def test_gpu_is_faster_than_cpu(data_cpu, data_gpu): cpu_start = time.time() data_cpu.process() cpu_duration = time.time() - cpu_start gpu_start = time.time() data_gpu.process() gpu_duration = time.time() - gpu_start assert gpu_duration &lt; cpu_duration I'd like to be able to do something like that without splitting data into multiple fixtures; I tried that already, but it made my test code error-prone and hard to change (because there was a lot of useless duplication). It's okay if I have to write new fixtures, hooks, or markers. They just have to be for the purpose of reducing code duplication instead of adding it. It's also okay if there's a third-party plugin that does this.
has title: Running a test with two invocations of the same fixture (but with different parameters)?
downvote count: 0
has comment: http://stackoverflow.com/comment/90679863
favorite count: 0
has comment: http://stackoverflow.com/comment/90680608
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90679587
tagged with: python
score: 2
answer count: 0
tagged with: pytest
upvote count: 2

pyspark
tags question: http://stackoverflow.com/q/51824736
tags question: http://stackoverflow.com/q/51915908
tags question: http://stackoverflow.com/q/51943378
tags question: http://stackoverflow.com/q/51869402
tags question: http://stackoverflow.com/q/51934098
tags question: http://stackoverflow.com/q/51820994
tags question: http://stackoverflow.com/q/51844508
tags question: http://stackoverflow.com/q/51819357
tags question: http://stackoverflow.com/q/51880774
tags question: http://stackoverflow.com/q/51955607
tags question: http://stackoverflow.com/q/51943419
tags question: http://stackoverflow.com/q/51824082
tags question: http://stackoverflow.com/q/51830697
tags question: http://stackoverflow.com/q/51893884
tags question: http://stackoverflow.com/q/51842746
type: Tag
tags question: http://stackoverflow.com/q/51930995
tags question: http://stackoverflow.com/q/51952535
tags question: http://stackoverflow.com/q/51844940
tags question: http://stackoverflow.com/q/51856733
tags question: http://stackoverflow.com/q/51829501
tags question: http://stackoverflow.com/q/51853704
tags question: http://stackoverflow.com/q/51877778
tags question: http://stackoverflow.com/q/51910651
tags question: http://stackoverflow.com/q/51939204
tags question: http://stackoverflow.com/q/51846050
tags question: http://stackoverflow.com/q/51921244
tag name: pyspark
tags question: http://stackoverflow.com/q/51923086
tags question: http://stackoverflow.com/q/51848149
tags question: http://stackoverflow.com/q/51944665
tags question: http://stackoverflow.com/q/51894698
tags question: http://stackoverflow.com/q/51853349
tags question: http://stackoverflow.com/q/51831874

http://stackoverflow.com/comment/90755813
comment on: http://stackoverflow.com/q/51902156
type: Comment
type: QuestionComment
has text: any other known libray @DYZ ?
score: 0

http://stackoverflow.com/q/51924271
has answer: http://stackoverflow.com/a/51924346
type: Question
has body: I am using Python Paramiko module to sftp into one of my servers. I did a list_dir() to get all of the files in the folder. Out of the folder I'd like to use regex to find the matching pattern and then printout the entire string. List_dir will list a list of the XML files with this format LOG_MMDDYYYY_HHMM.XML LOG_07202018_2018 --&gt; this is for the date 07/20/2018 at the time 20:18 Id like to use regex to file all the XML files for that particular date and store them to a list or a variable. I can then pass this variable to Paramiko to get the file. for log in file_list: regex_pattern = 'POSLog_' + date + '*' if (re.search(regex_pattern, log) != None): matchObject = re.findall(regex_pattern, log) print(matchObject) the code above just prints: ['Log_07202018'] I want it to store the entire string Log_07202018_20:18.XML to a variable. How would I go about doing this? Thank you
tagged with: paramiko
score: 0
answer count: 2
upvote count: 1
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51924326
type: UnansweredQuestion
tagged with: python
tagged with: regex
has title: Python Regex with Paramiko

http://stackoverflow.com/comment/90562249
score: 1
type: AnswerComment
has text: thank you again for your help dear. you are really humble and awesome
comment on: http://stackoverflow.com/a/51802828
type: Comment

http://stackoverflow.com/comment/90642351
type: QuestionComment
comment on: http://stackoverflow.com/q/51843974
score: 1
has text: And yes, you can pass arbitrary command line arguments with `Popen`. Read the documentation on the `subprocess` module for the details, or feel free to ask that as a separate question on Stack Overflow
type: Comment

http://stackoverflow.com/comment/90560094
type: AnswerComment
has text: `seek` itself is almost certainly O(1), because any further work can (and should) be delayed until a read or write actually *needs* the new file position. No sense doing an O(N) operation if the next operation on the file is a close.
type: Comment
comment on: http://stackoverflow.com/a/51801243
score: 0

http://stackoverflow.com/comment/90741690
score: 0
type: AnswerComment
has text: at the beginning try this but the behavior is not appropriate, because if at least 1 is fulfilled the bottom is shown and I want the condition (necessary) to be when the 3 conditions are strictly met this hidden the example button (if status_inv == 2 and validate_cheque = = false and pay = = True then the answer is {invisible})
type: Comment
comment on: http://stackoverflow.com/a/51888515

http://stackoverflow.com/a/51875373
has comment: http://stackoverflow.com/comment/90803220
has body: You can make START_DA: part of a positive lookahead expression instead: ^_info:(\n|.)*(?=START_DA:)
has comment: http://stackoverflow.com/comment/90702776
has comment: http://stackoverflow.com/comment/90703767
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51875290
has comment: http://stackoverflow.com/comment/90704322
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/51875290
has comment: http://stackoverflow.com/comment/90803577
upvote count: 2

http://stackoverflow.com/q/51955195
has comment: http://stackoverflow.com/comment/90861176
upvote count: 2
answer count: 1
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/xlsx
tagged with: python
has comment: http://stackoverflow.com/comment/90861261
score: 2
has title: Corrupt xlsx file created by xlsxwriter
has body: I have the following code to create an .xlsx file with xlsxwriter: workbook = xlsxwriter.Workbook(file_path) workbook.encoding='utf-8' df_report = pd.DataFrame(columns=['name', 'other', 'days', 'id', 'type', 'call_type', 'role', 'breach']) df_report = pd.concat([df_report, rpt1[rpt1['name'] == clientName]]) df_report.sort_values(by = ['breach'], inplace = True, ascending = False) df_report = df_report'other', 'days', 'id', 'role','breach' worksheet = workbook.add_worksheet('RPT_001_Q') worksheet.insert_image('A1', 'logo.png', {'x_scale': 0.25, 'y_scale': 0.25}) merge_format = workbook.add_format({ 'bold': 1, 'border': 2, 'align': 'center', 'valign': 'vcenter', 'fg_color': 'white'}) worksheet.merge_range('A1:C5', '', merge_format) merge_format.set_border_color('green') bold = workbook.add_format({'bold': 1}) worksheet.write('A6', 'Report Date:', bold) worksheet.write('B6', self.date, bold) worksheet.write('A7', 'Report Name:', bold) worksheet.write('B7', 'RPT_001_Q ', bold) worksheet.write('A8', 'Begin Date:', bold) worksheet.write('B8', start, bold) worksheet.write('A9', 'End Date:', bold) worksheet.write('B9', end, bold) worksheet.write('A10', 'Entity:', bold) worksheet.write('B10', client, bold) worksheet.write('A11', 'Type:', bold) worksheet.write('B11', 'Type A', bold) worksheet.write('A12', 'Call Type:', bold) worksheet.write('B12', 'Type D', bold) if len(df_report) == 0: worksheet.write('A13', 'No Data found for this Report in the time constraint given', bold) else: table = 'A13:E' + str(len(df_report) + 13) data = df_report.values.tolist() worksheet.add_table(table, {'data' : data, 'style': 'Table Style Medium 1', 'columns' : [ {'header' : 'other'}, {'header' : 'days'}, {'header' : 'id'}, {'header' : 'role'}, {'header':'breach'},]}) workbook.close() The output file gives this error upon opening in Excel: Excel cannot open the file 'rpt.xlsx' because the file format or file extention is not valid When trying to read the excel file back into python (using p…
has comment: http://stackoverflow.com/comment/90860923
downvote count: 0
has comment: http://stackoverflow.com/comment/90861331
tagged with: xlsxwriter
has answer: http://stackoverflow.com/a/51988905
type: Question
has comment: http://stackoverflow.com/comment/90861645
has comment: http://stackoverflow.com/comment/90866722
tagged with: python-3.6

http://stackoverflow.com/a/51916695
answers question: http://stackoverflow.com/q/51916525
downvote count: 0
has comment: http://stackoverflow.com/comment/90783609
type: AcceptedAnswer
has body: Use loops! If I understand you correctly, the following should work, import networkx as nx import matplotlib.pyplot as plt import pandas as pd df = pd.DataFrame({'a': [1, 1, 0, 0], 'b': [0, 1, 1, 0], 'c': [0, 0, 1, 1]}) product = df.T.dot(df) graph = nx.Graph() for column in df.columns: graph.add_node(column, weight=product[column][column]) for row_label, values in product.iterrows(): for column_label, value in values.iteritems(): if row_label != column_label: graph.add_edge(row_label, column_label, range=value) nx.draw_networkx(graph) plt.show() Which yields,
type: Answer
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51916525

http://stackoverflow.com/comment/90651415
comment on: http://stackoverflow.com/a/51849067
type: Comment
score: 1
has text: I was checking my project euler solutions to see something like `n //= 2`. In python 2 the code would have been correct, though
type: AnswerComment

http://stackoverflow.com/q/51873988
has answer: http://stackoverflow.com/a/51898299
has comment: http://stackoverflow.com/comment/90815785
has comment: http://stackoverflow.com/comment/90816667
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/91027458
has comment: http://stackoverflow.com/comment/91066800
has comment: http://stackoverflow.com/comment/90700510
tagged with: python
has comment: http://stackoverflow.com/comment/90848017
has comment: http://stackoverflow.com/comment/90703679
has comment: http://stackoverflow.com/comment/91056270
score: -1
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51898299
has comment: http://stackoverflow.com/comment/90709702
tagged with: http://stackoverflow.com/tag/json
downvote count: 2
has comment: http://stackoverflow.com/comment/90814722
upvote count: 1
has body: I have to create a script in Python, which allows me to replace strings in a json file. This file contains patent information, for example: { "US-8163793-B2": { "publication_date": "20120424", "priority_date": "20090420", "family_id": "42261969", "country_code": "US", "ipc_code": "C07D417/14", "cpc_code": "C07D471/04", "assignee_name": "Hoffman-La Roche Inc.", "title": "Proline derivatives", "abstract": "The invention relates to a compound of formula (I) wherein A, R 1 -R 6 are as defined in the description and in the claims. The compound of formula (I) can be used as a medicament." } However, there are about 15,000 entries. To normalize this document, before performing word embedding, I use software which includes tags in the terms found. The output looks like this: "Row_1" : { "COMPANY": [ { "hitCount": 1, "sourceTitle": "", "sourceID": "", "docTitle": "", "docID": "Row_1", "hitID": "COMP642", "name": "Roche", "frag_vector_array": [ "16#Hoffman-La {!Roche!} Inc." ], "totnosyns": 1, "goodSynCount": 1, "nonambigsyns": 1, "score": 1, "hit_loc_vector": [ 16 ], "word_pos_array": [ 2 ], "exact_string": "16#90-95", "exact_array": [ { "fls": [ 16, 90, 95 ] } ], "entityType": "COMPANY", "realSynList": [ "Roche" ], "dictSynList": [ "roche" ], "kvp": { "entityType": "COMPANY" }, "rejected": false, "entityMeta": { "_ext_name": "Wikipedia", "_ext_uri": "http://en.wikipedia.org/wiki/Roche", "_termite_id": "TCP000392" }, "section_vector": [ 8 ], "dependencyMet": true, "fuzzyMatches": 0, "sectionMeta": { "8": "assignee_name|" } } ] } This output is also a json file and would be used as a dictionary. What I need is to replace the terms "name", for example "Roche", with the "hitID", like "COMP642", every time that this term appears in the Patents file. I very very new in Python, so any help or reading recommendation will be of great help. Thank you! EDIT What a tried so far: with open(file, "rb") as datafile: json_data = json.loads(datafile.read().decode("utf-8")) # type: object fo…
type: Question
has comment: http://stackoverflow.com/comment/90730987
linked to: http://stackoverflow.com/q/9452108
has comment: http://stackoverflow.com/comment/90815362
has comment: http://stackoverflow.com/comment/90845739
has title: Python: compare two json files and replace similar strings

http://stackoverflow.com/q/51953394
favorite count: 0
tagged with: python-3.x
has body: I am trying to use list comprehension to print only strings that contain a substring .pdf. Here is the line of code causing the syntax error. list_of_files = [x if ".pdf" in x for x in list_of_files] The list list_of_files contains .pdf and .docx files for reference. They are gathered using os.listdir. This for loop works fine but I would much rather use list comprehension. for x in list_of_files: if ".pdf" in x: print(x) Thank you for any help!
tagged with: python
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51953448
score: 1
has answer: http://stackoverflow.com/a/51953448
has answer: http://stackoverflow.com/a/51953644
type: Question
has comment: http://stackoverflow.com/comment/90857193
has title: List Comprehension Syntax Error
has comment: http://stackoverflow.com/comment/90857113
has comment: http://stackoverflow.com/comment/90857222
tagged with: list-comprehension
upvote count: 2
answer count: 3
has comment: http://stackoverflow.com/comment/90857217
downvote count: 1
has comment: http://stackoverflow.com/comment/90857504
has answer: http://stackoverflow.com/a/51953450
accepted answer: http://stackoverflow.com/a/51953450
has comment: http://stackoverflow.com/comment/90857313

http://stackoverflow.com/q/51836076
tagged with: http://stackoverflow.com/tag/json
tagged with: python-unicode
type: Question
has title: Reading from excel sheet and writing exact characters to the json file
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/51836117
accepted answer: http://stackoverflow.com/a/52205913
has body: I have an excel sheet and I am reading from it and writing the values read to a json file. But the problem is the characters are not written as they are. For example: If the text is "Молба", it is written as "\u041b\u0438\u0447\u043d\u0430" in unicode or something. Code I am using to write to file is with open('data.json', 'w') as file: str = json.dumps(json_list, indent=4) file.write(str) file.close() json_list has list of objects. Any suggestions to solve this issue would be helpful.
has answer: http://stackoverflow.com/a/52205913
tagged with: python
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51836117

http://stackoverflow.com/a/51822510
has comment: http://stackoverflow.com/comment/90600327
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51822411
has comment: http://stackoverflow.com/comment/90600340
has comment: http://stackoverflow.com/comment/90636446
score: 6
type: Answer
upvote count: 6
has comment: http://stackoverflow.com/comment/90599051
has body: You are looking for the not in operator. def vowel_count(foo): count = 0 for i in foo.lower(): if i not in 'aeiou': count += 1 return count or more simply: def vowel_count(foo): return sum(i not in 'aeiou' for i in foo.lower()) # True == 1, False == 0
has comment: http://stackoverflow.com/comment/90625383
has comment: http://stackoverflow.com/comment/90599050
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51822411

http://stackoverflow.com/q/51940853
has comment: http://stackoverflow.com/comment/90831614
has body: I have a pandas dataframe with time-series data in 1-min intervals. Is there a pythonic way to slice my data for every 15 min like this? a=pd.DataFrame(index=pd.date_range('2017-01-01 00:04','2017-01-01 01:04',freq='1T')) a['data']=np.arange(61) for i in range(0,len(a),15): print a[i:i+15] Is there any built in function for this in pandas?
tagged with: python
has title: Slicing window on pandas dataframe
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51940964
score: 1
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/90831635
tagged with: pandas
has answer: http://stackoverflow.com/a/51940964
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/90857737
comment on: http://stackoverflow.com/q/51953630
has text: You already have `total` and `total_by_month_list` ... why do you need these additional `...total` and `...totallist` variables anyway?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/107798550
has text: I have followed the steps laid out here but when I reach step 12(changing the formula bar to access different datasets) I get the following error: "Formula.Firewall: Query 'Table1' (step 'Run Python script') references other queries or steps, so it may not directly access a data source. Please rebuild this data combination.". Is there a workaround for this?
score: 2
comment on: http://stackoverflow.com/a/51947461
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/90762266
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51903913
type: Comment
has text: @abarnert you're right by saying you should avoid to make typos, but your solution makes the dict get generated every time you run the code, even though it's just a very much static dictionary that can be defined and will never be touched by the application. It would make much more sense to define it statically instead of programmatically.

http://stackoverflow.com/q/51875114
tagged with: opencv
has comment: http://stackoverflow.com/comment/90703016
accepted answer: http://stackoverflow.com/a/51876455
upvote count: 12
has answer: http://stackoverflow.com/a/55747862
downvote count: 0
has title: Triangle Filling in opencv
possible better answer: http://stackoverflow.com/a/55747862
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90704640
tagged with: ellipse
favorite count: 0
has answer: http://stackoverflow.com/a/51876455
tagged with: geometry
type: Question
has body: We have Rectangle fillings , circle and ellipse filling in opencv, but can anyone say how to fill a triangle in an image using opencv ,python.
score: 12
answer count: 2
tagged with: python

http://stackoverflow.com/comment/90751512
has text: @Jean-FrançoisFabre Thanks for your wonderful help. I need one more help on that. After the completing the above said two steps, Finally I want output should print first 20 characters(including space) Ex ['my name alan coming from london southeast'] should be printed ['my name alan coming from londo']. Kindly answer it will great help for me.
comment on: http://stackoverflow.com/a/51802291
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/51920231
has title: Queue in Python
answer count: 2
downvote count: 1
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
has body: I am an PHP developer, i've never used python before, now i'm implementing am SMS system on our project, it's already working, but as i dont like python i've just made a little script with some information i collected over the web and i call this script using an php, the python script is #!/usr/bin/python import urllib, sys import serial import time for arg in sys.argv: if arg == "-t": recipient = sys.argv[2] # numero elif arg == "-m": message = sys.argv[4] # mensagem phone = serial.Serial("/dev/serial0", 9600, timeout=5) try: time.sleep(0.2) phone.write(b'ATZ\r') time.sleep(0.12) phone.write(b'AT+CMGF=1\r') time.sleep(0.12) phone.write(b'AT+CMGS="' + recipient.encode() + b'"\r') time.sleep(0.12) phone.write(message.encode() + b"\r") time.sleep(0.12) phone.write(bytes([26])) time.sleep(0.12) finally: phone.close() print('OK') And i call it passing the vars on php like: $recipient = "+5511anyphonenumber"; $message = "'Estou fazendo um teste'"; $command = "python3 teste2.py -t $recipient -m $message"; exec($command); The only problem is that i need the script to run only once per 3 seconds, so if it is called once and is called again 2 seconds after, i need the second call to be queued until 3 seconds has been passed from the last call, is there any easy way to do this? Please take in count that i'm not familiar with python.
has answer: http://stackoverflow.com/a/51920432
tagged with: python
upvote count: 0
has answer: http://stackoverflow.com/a/51920270
type: Question
has comment: http://stackoverflow.com/comment/90790270
score: -1

http://stackoverflow.com/q/51910798
score: 0
has answer: http://stackoverflow.com/a/51912184
tagged with: pandas
answer count: 1
tagged with: python
has body: I used the following two lines of code to calculate the value of a formula and save the result as a new column in the same dataframe. The formula multiplies the value of each column of a dataframe (df_H) by a value from a dictionary (H) and add up these values (of a single row) and divide them by the sum of all the values of the dictionary and save the result in the same row of the new column (df_H["COI"]). H = {'G1_H':9.5438, 'G2_H':3.921565, 'G3_H':2.939454} df_H['COI'] = pd.Series(((df_H.G1 * H['G1_H']) + (df_H.G3 *H['G3_H']) + ...)/(H['G1_H']+H['G3_H']+...), index=df_H.index) Now I want to re-write the same code so that it loops through all the columns and do the same. The number of columns and the items of a dictionary is changing based on the simulation, however, the number of columns is always equal to the number of dictionary items ).
has title: Looping through each column of a dataframe applying a function and save the result as a new column
accepted answer: http://stackoverflow.com/a/51912184
type: AnsweredQuestion
type: Question
tagged with: dataframe
tagged with: apply

http://stackoverflow.com/q/51943782
tagged with: python
favorite count: 0
score: 2
upvote count: 2
type: UnansweredQuestion
type: Question
has body: Icons for various states of QPushbutton etc. How do set the icon for a QPushButton or QToolbutton for when it is off and for when it is toggled. btn1 = QPushButton("Test") icon1 = QIcon("normal.png") icon2 = QIcon("toggled.png") # set the icon for when btn1.toggled returns True # and when btn1.toggled returns False Creating a QPushbutton with three states I want to create a qpushbutton that can have three states. I am using the button in a media player I am creating. These are the states I want the button to have: normal (repeat off) toggled state 1 (repeat all) toggled state 2 (repeat one) Upon research I've realised I may have to override QAbstractButton.nextCheckState. The trouble is that the is no signature for the method in the documentation. I therefore have no idea on how to override it or even if the is a state property to set or modify. Any help will be appreciated.
has title: Change the icon of QPushbutton or QToolbutton
answer count: 2
tagged with: pyqt
has comment: http://stackoverflow.com/comment/90838852
has answer: http://stackoverflow.com/a/51947134
has answer: http://stackoverflow.com/a/51945812
downvote count: 0

http://stackoverflow.com/comment/90656836
type: Comment
has text: These timings don't demonstrate much, the dictionary is so small and you are timing a single loop, that they, again, are probably dominated by the method-call and noise due to your computer's other processes.
comment on: http://stackoverflow.com/a/51851976
type: AnswerComment
score: 0

http://stackoverflow.com/comment/90763339
comment on: http://stackoverflow.com/a/51906400
has text: @TechieBoy101: It's polynomial features, not monomial features. There's nothing restricting it to only one variable at a time.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/90681456
comment on: http://stackoverflow.com/q/51864540
score: 0
type: QuestionComment
type: Comment
has text: please consider marking it as answer :)

http://stackoverflow.com/comment/90812816
comment on: http://stackoverflow.com/a/51929310
has text: To be honest, I am struggling a bit to implement the above, although I theoretically understand what needs to be fixed. If you could provide an example of the refactored label_image and read_tensor_from_image_file would be very much appreciated.
score: 0
type: Comment
type: AnswerComment

soa
type: Tag
tag name: soa
tags question: http://stackoverflow.com/q/51924312

http://stackoverflow.com/comment/90761522
type: QuestionComment
comment on: http://stackoverflow.com/q/51887958
has text: @lintang Would initializations affect a saved model? If so, how can I check for that?
type: Comment
score: 0

http://stackoverflow.com/a/51857313
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51857239
accepted answer of: http://stackoverflow.com/q/51857239
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90670399
type: Answer
has body: Use a list, to save each item: items = [] for orderItem in xmlFormatter(ekmSingleOrderRequest(str(list(out.values())[0])), "C:/Users/user/Desktop/test2.xml").iter('{http://publicapi.ekmpowershop.com/}OrderItem'): out2 = {} #here we can the quantity of order items print("this is an order item") for child in orderItem: if child.tag in tags2: out2[child.tag.split('}',1)[1]] = child.text items.append(out2)

http://stackoverflow.com/q/51823123
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90603793
has comment: http://stackoverflow.com/comment/90601712
has answer: http://stackoverflow.com/a/52430239
score: 1
has title: Run import.class simultaneously and still being able to talk with them (put/get)
type: Question
accepted answer: http://stackoverflow.com/a/52430239
has body: I've been searching and searching on Google/Stackoverflow for the problem I'm having with asyncio,multiprocessing and other stuff I've tried. And my wish is to have someone to help me setting this up. But scenario is in .py file I want to load multiple modules with its class. And they all ends with 'mi6.CMOD()' which is the class I've imported from 'importlib'. What I want for this project is how I talk with the 'multiprocessing.thread()'. I would like you know how I can put stuff in those classes being imported. Like if the list['name'] = mi6.CMOD and I want to edit the variable in the by calling list['name'].value = 1 And also I want to grab information from there. My project is on GitHub and I would love to have someone helping me getting this to work. Github:kuzeyron. I'm somehow new to this so kind answers are very welcomed! Google/Stackoverflow haven't given me anything else than how to retrieve information. Not changing values and stuff like that. Thank you for reading this!
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/90630513
favorite count: 0
tagged with: python-3.x
upvote count: 1
has comment: http://stackoverflow.com/comment/90631144
tagged with: python

http://stackoverflow.com/q/51945110
type: AnsweredQuestion
score: -2
accepted answer: http://stackoverflow.com/a/51945241
has body: I have to read an Excel file Using python. By the time I use xl = pd.ExcelFile("abc.xlsx") The column values which had hyperlink assigned to it becomes a simple number without any hyperlink. Is there any way that I can retain the Hyperlink? Details below.
type: Question
linked to: http://stackoverflow.com/q/35325799
tagged with: pandas
upvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/90839858
tagged with: python
linked to: http://stackoverflow.com/q/16676727
has title: Read Excel file which has one of the column as Hyperlink through python
downvote count: 2
has comment: http://stackoverflow.com/comment/90839792
tagged with: excel
has answer: http://stackoverflow.com/a/51945241

http://stackoverflow.com/q/51933668
has comment: http://stackoverflow.com/comment/90817522
has comment: http://stackoverflow.com/comment/90817377
has answer: http://stackoverflow.com/a/51933916
has comment: http://stackoverflow.com/comment/90817384
tagged with: python
answer count: 4
favorite count: 0
has title: How do you access JSON subdata with Python
has comment: http://stackoverflow.com/comment/90817448
has body: I'm working with some JSON data with Python. Basically I have the following JSON data { "users": [ { "name": "John Doe", "prefix": "[Test Account]", "rank": "10" }, { "name": "Jane Doe", "prefix": "[Test Account]", "rank": "10" } ] } I have a loop that successfully loops through the users in Python. for x in data["users"]: if username == data["users"]["name"]: print("true") I want to get just the name value. In JS you'd do it like this data.users[x].name But how do you do it in Python. I've tried stuff like data["users"][x]["name"] and data["users"[x]]["name"] Both throw errors. Any help is greatly appreciated.
has comment: http://stackoverflow.com/comment/90817709
linked to: http://stackoverflow.com/q/38347855
accepted answer: http://stackoverflow.com/a/51933916
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90817490
score: 3
upvote count: 3
has answer: http://stackoverflow.com/a/51934008
type: Question
possible better answer: http://stackoverflow.com/a/51933781
has answer: http://stackoverflow.com/a/51934000
has answer: http://stackoverflow.com/a/51933781
downvote count: 0

http://stackoverflow.com/a/51827630
type: Answer
has comment: http://stackoverflow.com/comment/90626700
has comment: http://stackoverflow.com/comment/90626309
answers question: http://stackoverflow.com/q/51826607
has body: You're importing the image using Pillow. Pillow has no attribute 'shape'. Instead, try img = cv2.imread("test.jpg") This should fix all the issues.
accepted answer of: http://stackoverflow.com/q/51826607
score: 0
type: AcceptedAnswer

http://stackoverflow.com/q/51884416
type: Question
has body: I'm using praw to get new submissions from reddit: for submission in submissions: print('Submission being evaluated:', submission.id) p = Process(target = evaluate, args = (submission.id, lock)) p.start() When using this code I sometimes get ids that link to older submissions. So I changed my script to check if the submissions are new: for submission in submissions: if ((time.time()-submission.created) &lt; 15): #if submission is new lock.acquire() print('Submission being evaluated:', submission.id) lock.release() p = Process(target = evaluate, args = (submission.id, lock)) p.start() else: lock.acquire() print("Submission "+submission.id+" was older than 15 seconds") lock.release() But for an extended period of time the else part didn't get executed even though I got a fair amount of old submission ids with the previous script. So my question is, when I run print(submission.id) is it running in the background when the subprocess is created, maybe causing a problem and changing the value of submission.id or is it just some coincidence that with the second script I got no old submissions? Thanks in advance!
score: 1
has comment: http://stackoverflow.com/comment/90720500
has comment: http://stackoverflow.com/comment/90721389
has comment: http://stackoverflow.com/comment/90720493
has answer: http://stackoverflow.com/a/51884556
answer count: 2
favorite count: 0
has title: Does the "print" function run in a new subprocess or something similar?
has comment: http://stackoverflow.com/comment/90720481
tagged with: python
upvote count: 2
has answer: http://stackoverflow.com/a/51884548
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90721098
has comment: http://stackoverflow.com/comment/90720887
has comment: http://stackoverflow.com/comment/90720648
downvote count: 1
tagged with: multiprocessing

http://stackoverflow.com/q/51940525
accepted answer: http://stackoverflow.com/a/51940770
linked to: http://stackoverflow.com/q/13857
score: 0
has title: Tkinter Commands: Function arguments in lambdas?
answer count: 1
tagged with: button
linked to: http://stackoverflow.com/q/3431676
linked to: http://stackoverflow.com/q/19837486
tagged with: python
tagged with: lambda
has answer: http://stackoverflow.com/a/51940770
type: AnsweredQuestion
tagged with: tkinter
has comment: http://stackoverflow.com/comment/105769682
type: Question
has body: My program has a lambda as a command for a tkinter object inside a loop. I want the lambda to pass an argument for a function where the function will make some changes according to the argument. for cat in self.t_m_scope: print(cat) self.t_m_scopeObj[cat] = [tk.Checkbutton(self, text = cat, command = lambda: self.t_m_checkUpdate(cat)), []] if self.t_m_scopeVars[cat][0]: self.t_m_scopeObj[cat][0].toggle() self.t_m_scopeObj[cat][0].grid(row = 5, column = colNum, padx = (10,10), pady = (2,5), sticky = tk.W) Whenever I try to run this, it always passes in the last iteration of cat because of some weird nature in tkinter commands. Instead, I want it so that the argument matches exactly whatever iteration it was at when the lambda was defined. I don't want the argument to change just because I clicked the check button after its iteration. Here is the function that the lambda calls. def t_m_checkUpdate(self, cat): self.t_m_scopeVars[cat][0] = not self.t_m_scopeVars[cat][0] for subcat in range(len(self.t_m_scopeVars[cat][1])): if self.t_m_scopeVars[cat][0] != self.t_m_scopeVars[cat][1][subcat]: self.t_m_scopeVars[cat][1][subcat] = not self.t_m_scopeVars[cat][1][subcat] self.t_m_scopeObj[cat][1][subcat].toggle() As some context to what this program is, I am trying to have a bunch of checkbuttons toggle on and off in response to a click on a main checkbutton. The only way I know which checkbuttons to toggle (since I have many) is to pass an argument to a function using lambda. I do understand that I could just find the value of the current iteration using if/elif/else and pass a string instead of a variable but I seriously don't want to do that because it's just not scalable. If it helps, the text for my checkbutton and the argument I want to pass is one and the same. Is there any workaround so I can preserve the current iteration without Tkinter going all wonky?
tagged with: for-loop

http://stackoverflow.com/q/51820745
accepted answer: http://stackoverflow.com/a/51821008
has body: I'm importing data from API using multithreathing as: def importdata(data, auth_token): # # --- Get data from Keros API -- hed = {'Authorization': 'Bearer ' + auth_token, 'Accept': 'application/json'} urlApi = 'http://...&amp;offset=0&amp;limit=1' responsedata = requests.get(urlApi, data=data, headers=hed, verify=False) if responsedata.ok: num_of_records = int(math.ceil(responsedata.json()['total'])) value_limit = 249 # Number of records per page. num_of_pages = num_of_records / value_limit print num_of_records print num_of_pages pages = [i for i in range(0, num_of_pages-1)] #pages = [i for i in range(0, 3)] datarALL = [] with ThreadPoolExecutor(max_workers=num_of_pages) as executor: futh = [(executor.submit(getdata, page, hed, value_limit)) for page in pages] for data in as_completed(futh): datarALL = datarALL + data.result() return datarALL else: return None def getdata(page,hed,limit): is_valid = True value_offset = page * limit value_limit = limit #limit of records allowed per page datarALL = [] url = 'http://...&amp;offset={0}&amp;limit={1}'.format(value_offset,value_limit) responsedata = requests.get(url, data=data, headers=hed, verify=False) if responsedata.status_code == 200: #200 for successful call responsedata = responsedata.text jsondata = json.loads(responsedata) if "results" in jsondata: if jsondata["results"]: datarALL = datarALL + jsondata["results"] print "page {} finished".format(page) return datarALL When I set: pages = [i for i in range(0, 3)] it works with no problems. But when I try pages = [i for i in range(0, num_of_pages-1)] It generate this error: page 317 finished page 240 finished page 15 finished page 12 finished page 350 finished page 16 finished page 288 finished page 18 finished page 17 finished Traceback (most recent call last): File "/home/ubuntu/scripts/import.py", line 84, in importdata datarALL = datarALL + data.result() File "/usr/local/lib/python2.7/dist-packages/concurrent/futures/_base.py", line 455, in result return self.__g…
score: 3
answer count: 1
downvote count: 0
favorite count: 0
linked to: http://stackoverflow.com/q/1434451
tagged with: python
has answer: http://stackoverflow.com/a/51821008
has title: requests.exceptions.ChunkedEncodingError connection broken
type: AnsweredQuestion
upvote count: 3
tagged with: multithreading
type: Question

permissions
tag name: permissions
tags question: http://stackoverflow.com/q/51915167
type: Tag
tags question: http://stackoverflow.com/q/51804042
tags question: http://stackoverflow.com/q/51847159
tags question: http://stackoverflow.com/q/51865841
tags question: http://stackoverflow.com/q/51936437

http://stackoverflow.com/a/51836649
accepted answer of: http://stackoverflow.com/q/51836535
type: AcceptedAnswer
has body: This solution affect all views: Surely you can supply your custom exception handler: Custom exception handling from rest_framework.views import exception_handler from rest_framework import status def custom_exception_handler(exc, context): # Call REST framework's default exception handler first, # to get the standard error response. response = exception_handler(exc, context) # Now add the HTTP status code to the response. if response.status_code == status.HTTP_404_NOT_FOUND: response.data['custom_field'] = 'some_custom_value' return response Sure you can skip default rest_framework.views.exception_handler and make it completely raw. Note: remember to mention your handler in django.conf.settings.REST_FRAMEWORK['EXCEPTION_HANDLER'] Solution for specific view: from rest_framework.response import Response # rest of the imports class ProjectDetails(mixins.RetrieveModelMixin, mixins.UpdateModelMixin, generics.GenericAPIView): queryset = Project.objects.all() def handle_exception(self, exc): if isinstance(exc, Http404): return Response({'data': 'your custom response'}, status=status.HTTP_404_NOT_FOUND) return super(ProjectDetails, self).handle_exception(exc)
upvote count: 10
type: Answer
has comment: http://stackoverflow.com/comment/90626928
downvote count: 0
has comment: http://stackoverflow.com/comment/90626670
has comment: http://stackoverflow.com/comment/90626715
answers question: http://stackoverflow.com/q/51836535
score: 10

enaml
tags question: http://stackoverflow.com/q/51824443
tag name: enaml
type: Tag

http://stackoverflow.com/comment/90590535
type: Comment
type: QuestionComment
has text: You probably have a duff jpg, you should print the file name and test just that specific file
score: 0
comment on: http://stackoverflow.com/q/51818302

http://stackoverflow.com/q/51882005
tagged with: python
has title: Django/Celery - AttributeError: module 'novopagemento' has no attribute 'celery'
has body: When I try to execute the command celery -A novopagamento worker -l info I receive the following error: Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/celery/app/utils.py", line 365, in find_app found = sym.app AttributeError: module 'novopagamento' has no attribute 'app' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/bin/celery", line 11, in &lt;module&gt; sys.exit(main()) File "/usr/local/lib/python3.6/site-packages/celery/__main__.py", line 16, in main _main() File "/usr/local/lib/python3.6/site-packages/celery/bin/celery.py", line 322, in main cmd.execute_from_commandline(argv) File "/usr/local/lib/python3.6/site-packages/celery/bin/celery.py", line 496, in execute_from_commandline super(CeleryCommand, self).execute_from_commandline(argv))) File "/usr/local/lib/python3.6/site-packages/celery/bin/base.py", line 273, in execute_from_commandline argv = self.setup_app_from_commandline(argv) File "/usr/local/lib/python3.6/site-packages/celery/bin/base.py", line 479, in setup_app_from_commandline self.app = self.find_app(app) File "/usr/local/lib/python3.6/site-packages/celery/bin/base.py", line 501, in find_app return find_app(app, symbol_by_name=self.symbol_by_name) File "/usr/local/lib/python3.6/site-packages/celery/app/utils.py", line 370, in find_app found = sym.celery AttributeError: module 'novopagemento' has no attribute 'celery' My project's structure: novopagamento ├──novopagamento | ├──__init__.py | ├──settings.py | └──celery.py ├──api | └──tasks.py My celery file: from __future__ import absolute_import, unicode_literals import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'novopagemento.settings') app = Celery('novopagemento') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) My task file: from…
has comment: http://stackoverflow.com/comment/102607328
score: 0
answer count: 3
tagged with: celery
has comment: http://stackoverflow.com/comment/90715816
has answer: http://stackoverflow.com/a/51883333
tagged with: docker
has comment: http://stackoverflow.com/comment/90718236
linked to: http://stackoverflow.com/q/13555386
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51895272
possible better answer: http://stackoverflow.com/a/51882152
accepted answer: http://stackoverflow.com/a/51883333
has answer: http://stackoverflow.com/a/51882152
type: Question
has comment: http://stackoverflow.com/comment/90717010
tagged with: django

http://stackoverflow.com/q/51896866
answer count: 0
downvote count: 0
score: 1
type: Question
tagged with: ipython
tagged with: cd
upvote count: 1
has comment: http://stackoverflow.com/comment/90744598
tagged with: shell
has body: I get the error: UsageError: Line magic function `%cd..` not found. when running my python code that i usually run from Jupyter Notebook through a shell command. I use %cd and %ls all the time in Jupiter notebooks and do not get why i can not run it from shell. I both tried: python test.py and ipython test.py this is the relevant part of my code: import csv import matplotlib.pyplot as plt from PIL import Image import numpy as np import pandas as pd import sys import os import IPython from scipy.misc import imread import matplotlib.cbook as cbook if sys.version_info[0] &lt; 3: from StringIO import StringIO else: from io import StringIO def main(): script = sys.argv[0] map_name = sys.argv[1] callPenalty() def callPenalty(): %cd standalone-penalty os.system("octave-cli penalty.m map_bit.bmp 50 1 1 150 150") %cd.. main() Does anyone know how to solve that?
favorite count: 0
has comment: http://stackoverflow.com/comment/90747781
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90744608
tagged with: python
has title: UsageError: Line magic function `%cd..` not found
tagged with: jupyter-notebook

http://stackoverflow.com/q/51812884
tagged with: lstm
upvote count: 2
tagged with: deep-learning
has title: When there are some zeros in input vector, run the biLstm model will get a 'floating error 8'
favorite count: 0
type: UnansweredQuestion
tagged with: python
score: 2
answer count: 0
downvote count: 0
tagged with: tensorflow
type: Question
has body: I do the padding process by myself, so there some 0 values in 'debate', 'reason', 'claim' or 'warrant'. Put into the BiLSTM architecture will get the 'floating error 8' without any other reminder. This error means some numbers divide by 0 or the index is out of range. but in the model, there shouldn't be any number divided by 0. Here is the code: debate = tf.placeholder(tf.float32,[None,48,300]) reason = tf.placeholder(tf.float32,[None,48,300]) claim = tf.placeholder(tf.float32,[None,48,300]) warrant = tf.placeholder(tfenter code here.float32,[None,48,300]) y = tf.placeholder(tf.float32,[None,2]) n_hidden = 300 w = weight_variable([n_hidden,2]) b = bias_variable([2]) def bilstm(x, weights, biases): lstm_f = tf.contrib.rnn.LSTMCell(n_hidden, forget_bias = 1.0) lstm_b = tf.contrib.rnn.LSTMCell(n_hidden, forget_bias = 1.0) (alloutputs, output_states) = tf.nn.bidirectional_dynamic_rnn(lstm_f, lstm_b, x, dtype = tf.float32) (outputs, state) = output_states (output_state_fw, output_state_bw) = state return tf.matmul(tf.add(output_state_fw, output_state_bw), weights) + biases final_representation = tf.concat([debate,reason,claim,warrant],1) prediction = bilstm(final_representation,w,b) cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y,logits=prediction)) train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy) When I put the same input into the normal RNN architecture, it could work. Here is the RNN code which could run. def RNN(X,weights,biases): lstm_cell = tf.nn.rnn_cell.LSTMCell(n_hidden,use_peepholes=True) #final_state[0] cell state #final_state[1] hidden_state outputs,final_state = tf.nn.dynamic_rnn(lstm_cell,X,dtype=tf.float32) results = tf.nn.softmax(tf.matmul(final_state[1],weights)+biases) return results Could anyone tell me what happened? Did I misunderstand biLSTM model? There should not be any number divided by 0 in biLSTM! Thanks in advance.

http://stackoverflow.com/comment/90809745
score: 0
type: Comment
type: QuestionComment
has text: What are `u` and `v` in your example? I mean what are their values.
comment on: http://stackoverflow.com/q/51929545

http://stackoverflow.com/q/51856948
downvote count: 1
has comment: http://stackoverflow.com/comment/90666120
favorite count: 0
has answer: http://stackoverflow.com/a/51857015
tagged with: return
possible better answer: http://stackoverflow.com/a/51857161
tagged with: python
answer count: 4
type: Question
has comment: http://stackoverflow.com/comment/90666258
type: AnsweredQuestion
has title: What does 'Return' do exactly, and where and when should I use it?
accepted answer: http://stackoverflow.com/a/51857241
has answer: http://stackoverflow.com/a/51857161
has comment: http://stackoverflow.com/comment/90666210
has answer: http://stackoverflow.com/a/51857261
has body: What's the difference between where I put the 'return'? It gives me a different answer and I'm really confused. Correct: def grades_sum(scores): total=0 for i in scores: total+=i return total print (total) grades_sum(grades) and a wrong answer: def grades_sum(scores): total=0 for i in scores: total+=i return total print (total) grades_sum(grades) Also, why does including a return in this variance function give me the wrong answer: def grades_variance(scores): average=grades_average(scores) variance=0 for score in scores: variance+=(average-score)**2 return variance/len(scores) print (grades_variance(grades)) whereas this is correct: def grades_variance(scores): average=grades_average(scores) variance=0 for score in scores: variance+=(average-score)**2 print (grades_variance(grades))
score: 0
has answer: http://stackoverflow.com/a/51857241
tagged with: for-loop
upvote count: 1

http://stackoverflow.com/q/51849511
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90652366
score: 1
has answer: http://stackoverflow.com/a/51851337
has answer: http://stackoverflow.com/a/51874728
downvote count: 1
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/90652283
answer count: 3
has comment: http://stackoverflow.com/comment/90652289
has body: I have a ndarray with dimensions (720,100,100). This ndarray represents all the months within 60 years, this means that it is possible to group them by 12 months per year. 720 represents the months from the year 1958 to 2017 (including 1958), while (100, 100) represent rows and columns with data. Thus, the first twelve ndarray belong to 1958, the second pack of twelve belong to 1959 and so on.Worth to mention is that some of the "cells" in these rows and columns are empty. Thus, the ndarray is saved as a masked array (not a problem as all of the data it's like this). The problem I am experiencing is this: how can I iterate through this ndarray and "pack" all january, february, march and so on together? So, the new ndarray will have the same shape (720,100,100) but the first 12 arrays will belong to January, the next 12 to February and so on, of all years. I do not add a code because it is a complete thrash for this operation.
has title: Iterate through ndarray in Python
has comment: http://stackoverflow.com/comment/90654046
has answer: http://stackoverflow.com/a/51849662
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90652785
tagged with: multidimensional-array
upvote count: 2

http://stackoverflow.com/q/51866356
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51866392
tagged with: arguments
tagged with: python
has body: I have a chain of tasks that a celery worker runs. When a task is finished the chain carries forward the result of that task to the next task as a (positional) argument. Each task has it's own arguments + *args to handle the carried forward arguments. The problem is that I want to use keyword argument for the arguments of the task but those carried forward arguments are just positional arguments. The following code is just a simple example to show my problem without use of celery chains: def test_func(data1,*args): print(data1, '\t', args) def b(): return {'data2':'b'} test_func(data1='a', b()) I know that this generates "SyntaxError: positional argument follows keyword argument" because the first argument is using the argument name whereas the second one doesn't. If I know how to properly return the result of function b() then my problem will be solved. That is, to return the result of b() in a way that b() is considered as a keyword argument when calling test_func(data1='a', b()) UPDATE: It turned out celery chains carry over the results of each task to the first argument of the next task in the chain, not the last argument. This was my bad as I was new to celery chains. Therefore, I just switched the place of positional and keyword arguments in the function's header and my problem was solved as bellow: def test_func(data1, data2): print(data1, '\t', data2) def b(): return 'b' test_func(b(),data2='a') As Python allows to have a keyword argument after a positional argument, everything turned out to be smoothly running. Thanks to @MatiasCicero and @C.Nivs for their answers.
has title: Python celery task canvas: SyntaxError: positional argument follows keyword argument
tagged with: celery
type: Question
tagged with: celery-canvas
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/51866477
tagged with: python-3.x

http://stackoverflow.com/comment/90815882
has text: It still indicates that the bot is not in the voice channel. As suggested I wrote ```@client.command(name = "check", pass_context = True) async def check(ctx): server = ctx.message.server if client.is_voice_connected(server): print("Yes") else: print("No")``` And I continue to get that the bot in not in the channel
type: AnswerComment
comment on: http://stackoverflow.com/a/51922255
score: 0
type: Comment

http://stackoverflow.com/comment/90596239
type: QuestionComment
has text: I need to write a python package that will export the notebook automatically and save it in a specific location
comment on: http://stackoverflow.com/q/51820891
score: 0
type: Comment

http://stackoverflow.com/comment/90759232
comment on: http://stackoverflow.com/q/51903109
has text: what happens when you use `echo "$var"` (note the dbl-quotes surrounding `$var` ;-) ) Good luck.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51897243
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/51897407
has comment: http://stackoverflow.com/comment/90746177
has comment: http://stackoverflow.com/comment/90746927
type: Question
has body: I am new to python. Base class/python file(Base.py). SESSION_ID = "" def m1(): print "SESSION_ID in base: ",SESSION_ID Derived class(Derived.py) from Base import * class Derived(): def m2(self): global SESSION_ID SESSION_ID = 10 print "SESSION_ID in derived: ", SESSION_ID def main(): c2 = Derived() c2.m2() m1() if __name__ == "__main__": main() When I execute Derived.py file below is the output: SESSION_ID in derived: 10 SESSION_ID in base: I want the value which is set in m2() to be reflected in m1(). So the expected output is: SESSION_ID in derived: 10 SESSION_ID in base: 10 Can you please help?
possible better answer: http://stackoverflow.com/a/51897407
has title: Base class variable does not store value which is set by Derived class
downvote count: 0
has answer: http://stackoverflow.com/a/51897696
answer count: 3
has comment: http://stackoverflow.com/comment/90749422
tagged with: python-2.x
favorite count: 0
has answer: http://stackoverflow.com/a/51897368
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/51897368

http://stackoverflow.com/comment/90709360
has text: Can you please post stack trace so that we know where is code facing error.
comment on: http://stackoverflow.com/q/51860759
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90786270
type: Comment
score: 0
comment on: http://stackoverflow.com/a/51918171
type: AnswerComment
has text: ValueError Traceback (most recent call last) <ipython-input-61-4ee2085f959e> in <module>() ----> 1 df["normalized-losses"]=df["normalized-losses"].astype(float) ~\Anaconda3\lib\site-packages\pandas\util\_decorators.py in wrapper(*args, **kwargs)

http://stackoverflow.com/a/51867274
answers question: http://stackoverflow.com/q/51865461
type: Answer
has body: Your code seems a bit mixed up, as there are 2 app routes for index and both contain a post request. Try something like the following, I have no access to all your code so this is untested, please adjust where needed. I'm sure you get the idea: @app.route("/", methods = ["GET" , "POST"]) def index(): if request.method == "POST: if request.form.post['action'] == 'Append': note = request.form.get("note") notes.append(note) if request.form.post['action'] == 'Delete': number = request.form.get("number") notes.remove(notes[number]) return render_template("index.html" , notes = notes) in your html put the buttons in the right places something like this: &lt;input type ="submit" name="action" value="Append"&gt; &lt;input type ="submit" name="action" value="Delete"&gt;
score: 0

http://stackoverflow.com/a/51948532
accepted answer of: http://stackoverflow.com/q/51937823
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90856282
has comment: http://stackoverflow.com/comment/90853296
downvote count: 0
answers question: http://stackoverflow.com/q/51937823
has comment: http://stackoverflow.com/comment/90852878
type: Answer
has comment: http://stackoverflow.com/comment/90888822
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/90851997
has body: I don't know about your exact problem, but I had a problem similar to yours, and I fixed it with: query = [] if location: query.append(obj.location==location) I will query this list of queries with obj.query.filter(*query).all() Where in above examples, obj is the name of a model you have created. How is this help? this will allow you to fill in the variables you have dynamically and each query has its own conditions. you can use ==, !=, &lt;=, etc. note you should use filter and not filter_by then you can as many operators as you like. you can read link1 and link2 for documents on how to query sqlalchemy. edit: name = request.args.get("name") address = request.args.get("address") age = request.args.get("address") query = [] if name: query.append(Myobject.name==name) if address: query.append(Myobject.address==name) if age: query.append(Myobject.age &gt;= age) # look how we select people with age over the provided number! query_result = Myobject.query.filter(*query).all() if's will help you when there is no value provided by the user. this way you are not including those queries in your main query. with use of get, if these values are not provided by the user, they will be None and respected query won't be added to the query list.
has comment: http://stackoverflow.com/comment/90853046

http://stackoverflow.com/a/51802690
score: -1
downvote count: 1
has comment: http://stackoverflow.com/comment/123387222
has comment: http://stackoverflow.com/comment/90690438
type: Answer
has body: ec2 = boto3.client('ec2', region_name='us-east-1') for rds_security_group in ec2.describe_security_groups()['SecurityGroups']: if rds_security_group['GroupName'] == 'testgroup': print(rds_security_group['GroupId']) return (rds_security_group['GroupId']) else: rds_security_group_name = ec2.create_security_group( GroupName='testgroup', Description='rds-security-group', VpcId='vpc-12345') client.authorize_security_group_ingress( CidrIp=10.10.10.10/11, IpProtocol='tcp', FromPort=90, ToPort=90, GroupId=rds_security_group_name['GroupId']) print(rds_security_group_name['GroupId']) return(rds_security_group_name['GroupId']) I did find answer to my question with slight change in the existing code its self
upvote count: 0
answers question: http://stackoverflow.com/q/51801942

http://stackoverflow.com/q/51950472
has comment: http://stackoverflow.com/comment/90925944
upvote count: 2
has body: I am taking an excel spreadsheet, loading into a Pandas Dataframe then appending the data frame to an Oracle table. Any potentially sensitive data is starred. import os import pandas as pd import cx_Oracle from tkinter import Tk from tkinter.filedialog import askopenfilename from sqlalchemy import create_engine #Gets excel file and writes to dataframe Tk().withdraw() filename = askopenfilename() xl = pd.ExcelFile(filename) print(xl.sheet_names) ws = input('Type a sheet name to load: \n') dFrame = xl.parse(ws) #create engine connection engine = create_engine('oracle+cx_oracle://*********') print("Engine created") with engine.begin() as conn: conn.execute("DELETE FROM table") print("Delete from executed") #Write dataframe to table dFrame.to_sql('table',con=engine, if_exists='append', index=False) print("Data frame appended to table") However, I get error TypeError: expecting string or bytes object (full trace below), I believe this means there is a column in the dataframe which does not match the existing table type. If that is the case, how can I find which section of the dataframe is causing a problem? Traceback (most recent call last): File "C:\Users\*****\Documents\CD\Test.py", line 26, in &lt;module&gt; dFrame.to_sql('table',con=engine, if_exists='append', index=False) File "C:\Users\*****\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pandas\core\generic.py", line 2130, in to_sql dtype=dtype) File "C:\Users\*****\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pandas\io\sql.py", line 450, in to_sql chunksize=chunksize, dtype=dtype) File "C:\Users\******\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pandas\io\sql.py", line 1127, in to_sql table.insert(chunksize) File "C:\Users\******\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pandas\io\sql.py", line 641, in insert self._execute_insert(conn, keys, chunk_iter) File "C:\Users\******\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pandas\io\sql.py", …
answer count: 1
has comment: http://stackoverflow.com/comment/90864369
has comment: http://stackoverflow.com/comment/91111585
has answer: http://stackoverflow.com/a/57782741
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90874778
tagged with: pandas
score: 2
tagged with: cx-oracle
downvote count: 0
has comment: http://stackoverflow.com/comment/90974866
favorite count: 0
tagged with: python-3.x
type: Question
tagged with: oracle-database
has title: Expecting string or bytes object
has comment: http://stackoverflow.com/comment/91057450
tagged with: python
has comment: http://stackoverflow.com/comment/90956146

http://stackoverflow.com/a/51926385
downvote count: 0
has comment: http://stackoverflow.com/comment/90802575
has comment: http://stackoverflow.com/comment/90802348
has comment: http://stackoverflow.com/comment/90802492
answers question: http://stackoverflow.com/q/51925947
has comment: http://stackoverflow.com/comment/90802667
has comment: http://stackoverflow.com/comment/90802236
upvote count: 2
has comment: http://stackoverflow.com/comment/90802267
has body: Looks like you have created the file C:\Python27\pyo.py. So instead of the actual pyo module getting imported, your file gets imported. Rename the file C:\Python27\pyo.py and any pyc file (C:\Python27\pyo.pyc) associated with it and try again
has comment: http://stackoverflow.com/comment/90803051
type: Answer
score: 2

http://stackoverflow.com/q/51890074
type: UnansweredQuestion
tagged with: urllib
type: Question
score: 0
has comment: http://stackoverflow.com/comment/90731271
has comment: http://stackoverflow.com/comment/90731586
has body: Currently, I'm using Flask with Python 3. For sample purposes, here is a dropbox link In order to fetch the file and save it, I'm doing the following. urllib.request.urlretrieve("https://www.dropbox.com/s/w1h6vw2st3wvtfb/Sample_List.xlsx?dl=0", "Sample_List.xlsx") The file is saved successfully to my project's root directory, however there is a problem. When I try to open the file, I get this error. What am I doing wrong over here? Also, is there a way to get the file name and extension from the URL itself? Example, filename = Sample_List and extension = xlsx...something like this.
has comment: http://stackoverflow.com/comment/90731826
has title: Unable to open saved excel file using urllib.request.urlretrieve (Sample link mentioned )
tagged with: python
answer count: 0

http://stackoverflow.com/a/51828724
has comment: http://stackoverflow.com/comment/90611937
has comment: http://stackoverflow.com/comment/90612026
has comment: http://stackoverflow.com/comment/90612005
downvote count: 0
has body: You wrote in your view: for Destination in boards: # ... This means that Python sees Destination as a local variable, a local variable that you use before it is assigned. You can rename the variable in the loop to solve the problem, but actually you can make it more elegant and faster here by using .values_list(..): from django.http import HttpResponse from .models import Destination def index(request): response_html = '&lt;br&gt;'.join( Destination.objects.values_list('destinationtext', flat=True) ) return HttpResponse(response_html) Nevertheless, I'm still not convinced that this solves the matter, since the destinationtext could contain HTML, which then will mix up in the response. Usually it is better to use templates.
score: 1
answers question: http://stackoverflow.com/q/51828667
type: Answer
has comment: http://stackoverflow.com/comment/90611895
upvote count: 1
has comment: http://stackoverflow.com/comment/90612110

http://stackoverflow.com/q/51950162
downvote count: 1
has answer: http://stackoverflow.com/a/51950400
type: AnsweredQuestion
tagged with: list
upvote count: 3
has title: How do I build multiple list automatically
accepted answer: http://stackoverflow.com/a/51950400
tagged with: dataframe
has comment: http://stackoverflow.com/comment/90851159
tagged with: loops
type: Question
score: 2
has answer: http://stackoverflow.com/a/51950221
has comment: http://stackoverflow.com/comment/90850804
answer count: 3
tagged with: pandas
possible better answer: http://stackoverflow.com/a/51950221
has answer: http://stackoverflow.com/a/51950303
favorite count: 0
has body: I have hundereds of dataframe, let say the name is df1,..., df250, I need to build list by a column of those dataframe. Usually I did manually, but today data is to much, and to prone to mistakes Here's what I did list1 = df1['customer_id'].tolist() list2 = df2['customer_id'].tolist() .. list250 = df250['customer_id'].tolist() This is so manual, can we make this in easier way?
tagged with: python

http://stackoverflow.com/comment/90724625
type: QuestionComment
has text: What I mean to say is a single loop with a single iteration in the loop. If you see the count the iteration count is four. I was trying to do this in a single iteration.
comment on: http://stackoverflow.com/q/51886499
score: 0
type: Comment

http://stackoverflow.com/a/51876554
score: 1
has comment: http://stackoverflow.com/comment/90704390
upvote count: 1
has body: You don't need to call self.initiate_overlap_dict(self), you only need to call self.initiate_overlap_dict(). i.e. remove the self argument You can read more here https://pythontips.com/2013/08/07/the-self-variable-in-python-explained/
accepted answer of: http://stackoverflow.com/q/51876378
answers question: http://stackoverflow.com/q/51876378
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/comment/90896508
score: 0
type: Comment
has text: Try adding **print("Recieved input")** after the line check() in the while loop. Then check if it prints Recieved input when you switch GPIO23 to high. Let me know what happens.
comment on: http://stackoverflow.com/a/51946010
type: AnswerComment

http://stackoverflow.com/a/51880764
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/135977857
has body: One way to avoid doing the union is the following: Create a list of columns to compare: to_compare Next select the id column and use pyspark.sql.functions.when to compare the columns. For those with a mismatch, build an array of structs with 3 fields: (Actual_value, Expected_value, Field) for each column in to_compare Explode the temp array column and drop the nulls Finally select the id and use col.* to expand the values from the struct into columns. Code: StructType to store the mismatched fields. import pyspark.sql.functions as f # these are the fields you want to compare to_compare = [c for c in df_Actual.columns if c != "id"] df_new = df_cobined.select( "id", f.array([ f.when( f.col(c) != f.col("Expected_"+c), f.struct( f.col(c).alias("Actual_value"), f.col("Expected_"+c).alias("Expected_value"), f.lit(c).alias("Field") ) ).alias(c) for c in to_compare ]).alias("temp") )\ .select("id", f.explode("temp"))\ .dropna()\ .select("id", "col.*") df_new.show() #+---+------------+--------------+-----+ #| id|Actual_value|Expected_value|Field| #+---+------------+--------------+-----+ #| 7| CLAIR| CLARE| name| #| 10| London| Londn| City| #| 3| Sam| SAM| name| #+---+------------+--------------+-----+
upvote count: 5
has comment: http://stackoverflow.com/comment/90714011
score: 5
answers question: http://stackoverflow.com/q/51877778

http://stackoverflow.com/comment/110635104
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51916430
type: Comment
has text: Also, `return repr(obj)` will work if `__repr__` is defined in the model class.

http://stackoverflow.com/q/51833501
score: 5
has comment: http://stackoverflow.com/comment/93905330
has answer: http://stackoverflow.com/a/69040715
tagged with: python
has answer: http://stackoverflow.com/a/52545501
favorite count: 0
tagged with: python-3.x
upvote count: 5
type: UnansweredQuestion
tagged with: django
downvote count: 0
tagged with: geodjango
has comment: http://stackoverflow.com/comment/119313108
has body: Im trying to use Django with Geodjango, I followed all documentation steps, but still got this error when trying to make migrations: OSError: [WinError 127] : The specified procedure could not be found The models.py is correct, I'm using from geodjango site, and this is my settings.py import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'ci3qd6ti+d+#-4pae7d*)^8nmmgb2j@cacivgt8rdvsngu2$mj' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.gis', 'world', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'geodjango.urls' 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', ], }, }, ] WSGI_APPLICATION = 'geodjango.wsgi.application' # Database # https://docs.djangoproject.com/en/2.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql'…
has title: OSError in Geodjango: [WinError 127] : The specified procedure could not be found
type: Question
answer count: 2

http://stackoverflow.com/q/51932231
score: 1
tagged with: virtualenv
favorite count: 0
has title: No module named error but pip freeze shows module is instealled in virtualenv
type: Question
upvote count: 1
tagged with: python
answer count: 1
has body: I'm currently writing a Flask app using virtual env. When I try and run some of my python files I am getting: ImportError: No module named &lt;module&gt; In this case, the module I am trying to use is 'Click'. If I do a pip freeze or a pip list inside the virtual env, I can see the module listed there. I'm inside my virtual env when I'm trying to run the .py file too. How come pip freeze/list can find the module but my .py program cannot? Could it also be an issue with my .wsgi file?
has answer: http://stackoverflow.com/a/51933173
type: UnansweredQuestion
tagged with: flask
downvote count: 0

mne-python
type: Tag
tags question: http://stackoverflow.com/q/51869713
tag name: mne-python

http://stackoverflow.com/comment/90637250
comment on: http://stackoverflow.com/q/51841679
type: QuestionComment
type: Comment
has text: Alternatively, you can also just use `'-b'` in your plot command where `b` is for blue color and `-` is for line.
score: 0

http://stackoverflow.com/comment/90800663
has text: The process is once started in the beginning (init function of class "Main") and runs for the remainder of the program. New script are then passed through a process queue and a thread is started within the process for each script, which run as long as the script runs. The reason why the scripts all run in the same process and I don't just spawn a process for every script is, that they also need to share variables between each other and I don't want to have another queue to do that.
type: QuestionComment
comment on: http://stackoverflow.com/q/51859562
type: Comment
score: 0

http://stackoverflow.com/q/51837413
has comment: http://stackoverflow.com/comment/90628403
type: Question
has comment: http://stackoverflow.com/comment/90628395
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/51837877
has title: split big matrix into multiple smaller ones - difficulties
has comment: http://stackoverflow.com/comment/90628569
has answer: http://stackoverflow.com/a/51837584
has body: I have a 32*32 matrix and I want to break it into 4 8x8 matrixes. Here's how I try to make a smaller matrix for top-left part of the big one (pix is a 32x32 matrix). A = [[0]*mat_size]*mat_size for i in range(mat_ size): for j in range(mat_size): A[i][j] = pix[i, j] So, pix has the following values for top-left part: 198 197 194 194 197 192 189 196 199 199 198 198 199 195 195 145 200 200 201 200 200 204 131 18 201 201 199 201 203 192 57 56 201 200 198 200 207 171 41 141 200 200 198 199 208 160 38 146 198 198 198 198 206 157 39 129 198 197 197 199 209 157 38 77 But when I print(A) after the loop, all the rows of A equal to the last row of pix. So it's 8 rows of 198 197 197 199 209 157 38 77 I know I can use A = pix[:8, :8], but I prefer to use loop for some purpose. I wonder why that loop solution doesn't gives me correct result.
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/240178
tagged with: python
has comment: http://stackoverflow.com/comment/90628475
has comment: http://stackoverflow.com/comment/90628329

http://stackoverflow.com/comment/90684967
score: 0
type: QuestionComment
has text: So the array is inside a dataframe or it is numpy array prior to being appended to the dataframe? Also what do you want your end output to look like? How many columns in the end?
type: Comment
comment on: http://stackoverflow.com/q/51866152

http://stackoverflow.com/comment/90728270
type: QuestionComment
comment on: http://stackoverflow.com/q/51888381
score: 0
has text: I think you should start with a formal definition of what you mean by "out of order".
type: Comment

http://stackoverflow.com/a/51890010
has body: In case the JSON decoding fails, r.json() raises an exception. For example, if the response gets a 204 (No Content), or if the response contains invalid JSON, attempting r.json() raises ValueError: No JSON object could be decoded. It should be noted that the success of the call to r.json() does not indicate the success of the response. Some servers may return a JSON object in a failed response (e.g. error details with HTTP 500). Such JSON will be decoded and returned. To check that a request is successful, use r.raise_for_status() or check r.status_code is what you expect. so check your status code if it is 200 then it should parse the json if it is 204 then there is a problem with URL. check it using print(r.status_code) for more info refer this link
downvote count: 0
has comment: http://stackoverflow.com/comment/90736426
has comment: http://stackoverflow.com/comment/90736468
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51889745

http://stackoverflow.com/comment/90753360
comment on: http://stackoverflow.com/a/51900207
type: Comment
score: 0
type: AnswerComment
has text: Were you not getting that error before? I intended my answer to be code for you to run after performing the `add`, so I don't see how it could cause an error in a previous statement.

http://stackoverflow.com/comment/90589394
score: 0
comment on: http://stackoverflow.com/a/51816282
type: Comment
type: AnswerComment
has text: I got that part. So does `clf.predict(X)` provide the same result as `cross_val_predict`? I want to get the predicted values as well but when I apply 10-fold cross validation and try to print out the values, it gives a large number of values unlike in `cross_val_predict`.

http://stackoverflow.com/a/51815008
has body: This is because your form doesn't contain action, i.e. where should the POST call be made with the user credentials. Try following change in home.html: Welcome to my website {% csrf_token %} {{ form }} Submit
has comment: http://stackoverflow.com/comment/90584493
downvote count: 0
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/90584570
score: 1
has comment: http://stackoverflow.com/comment/90584682
answers question: http://stackoverflow.com/q/51814971

http://stackoverflow.com/a/51903662
downvote count: 1
upvote count: 0
answers question: http://stackoverflow.com/q/51903414
has body: I found another sollution which works pretty fine even if the enum iss more complex or consists of multiple datatypes. # coding=utf-8 # Written in python 3.7 # pandas==0.23.4 from enum import unique, Enum import pandas as pd class Complex: name: str type: str def __init__(self, name: str, type: str): self.name = name self.type = type def __str__(self) -&gt; str: return self.name @unique class DEMO(str, Enum): FIRST = Complex("Hello", "Siebzig") SECOND = Complex("World", "Zehn") df = pd.DataFrame() df[DEMO.FIRST] = pd.Series([1, 2]) df[DEMO.SECOND] = pd.Series([1, 2]) print(df.to_json()) will produce the output {"Hello":{"0":1,"1":2},"World":{"0":1,"1":2}} The important change was that I added str as super before Enum. This is even pretty simple to use with dynamic typed ENUM contents, as long as these have a string representation (def __str__(self) -&gt; str:). The Enum class will automatically check the string serialization of all the members to check if those are unique whithout the need to overwrite __hash__(self)
type: Answer
score: -1

http://stackoverflow.com/comment/90711356
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51862351
type: AnswerComment
has text: That makes sense. Is there any way to connect the front end validators to the model validators?

http://stackoverflow.com/q/51902451
has comment: http://stackoverflow.com/comment/90758403
has answer: http://stackoverflow.com/a/52152773
tagged with: python
score: 2
tagged with: tkinter
downvote count: 3
type: Question
upvote count: 5
has title: How to enable and disable Frame instead of individual widgets in Python Tkinter
has comment: http://stackoverflow.com/comment/90756233
has comment: http://stackoverflow.com/comment/90758414
has body: I have an application where I have to enable all the widgets on current window after I click on a radio button. Initially, when I start my application, I have two radio buttons in frame1 and I have to disable all other widgets (like buttons, entries) which are placed in frame2, and whenever I click on radio_button1 it all the widgets should be enabled. In this code, when I click on radio_button1, it activates all widgets. Is there a better approach I can develop, so that it disables and enables the whole frame instead of enabling and disabling each individual widget? Below is my current code: from tkinter import * from tkinter import simpledialog class Gui: def __init__(self, parent, **kw): self.parent = parent self.top = Toplevel(self.parent) self.frame1= Frame(self.top,width= 450,height =550) self.frame1.grid(row=0) self.frame2 = Frame(self.top, width=450, height=550) self.frame2.grid(row=1) self.radio1=Radiobutton(self.frame1,text='radio_button1',value=1,command=self.enable_window) self.radio2=Radiobutton(self.frame1,text='radio_button2',value=2) self.label1 = Label(self.frame2, text='Label1:', width=15, background='white', justify=CENTER, font='-weight bold') self.label2 = Label(self.frame2, text='Lable2:', width=15, background='white', justify=CENTER, font='-weight bold') self.b=Button(self.frame2,text='save',state=DISABLED) self.c = Button(self.frame2, text='cancel',state=DISABLED) self.radio1.grid(row=0,column=0,sticky='W') self.radio2.grid(row=0,column=1,padx=50,sticky='W') self.label1.grid(padx=10, pady=5, row=0, column=0, sticky='E') self.label2.grid(padx=10, pady=5, row=1, column=0, sticky='E') self.b.grid(row=3,column=0) self.c.grid(row=3, column=1) self.entry1_Var = StringVar() self.entry2_Var = StringVar() self.entry1 = Entry(self.frame2, width=15, background='white', textvariable=self.entry1_Var,state='disable', font='-weight bold') self.entry2 = Entry(self.frame2, width=15, background='white', textvariable=self.entry2_Var,state='disable', font='-weig…
has comment: http://stackoverflow.com/comment/90756282
answer count: 1
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/a/51879660
downvote count: 0
has comment: http://stackoverflow.com/comment/90711008
answers question: http://stackoverflow.com/q/51879374
accepted answer of: http://stackoverflow.com/q/51879374
upvote count: 3
type: AcceptedAnswer
type: Answer
has body: The any doesn't "belong to" the if - it's not special syntax, but a regular function: &gt;&gt;&gt; any([True, False]) True &gt;&gt;&gt; any([False, False]) False It returns True if and only if at least one of the list elements can be considered "true". Your second list will be non-empty, and a non-empty list is considered "true". Since any is a function, you can also apply it to the second list: if any(items in allbox[i].text for items in list1) and any(items1 in allbox[i].text for items1 in list2):
score: 3

mfcc
type: Tag
tag name: mfcc
tags question: http://stackoverflow.com/q/51826044

http://stackoverflow.com/comment/90641156
score: 0
type: AnswerComment
type: Comment
has text: Sorry! It has been a while since the last time i asked a question in here. Thanks :)
comment on: http://stackoverflow.com/a/51842189

http://stackoverflow.com/a/60905860
answers question: http://stackoverflow.com/q/51866213
score: 0
type: Answer
has body: This is actually a very interesting problem which I am running into now. I have a repo with two branches in very active development and I need to switch back and forth quite often. The branches have different compiled code (Fortran &amp; C) versions which means that every time I git checkout &lt;branch&gt; I need to recompile code. Not optimal to say the least. I would like to have two conda environments, with a different branch installed in each env. I would like to have two python kernels running, one started from each conda env and be able to test (run code) in both without doing switching branches (only the window I work in). What I ended up doing is cloning the repo twice under separate testing directories, both separate from the main repo's main dev dir, checking out different branches in each directory and installing each in a separate conda environment. As long as I don't touch the master branch in each of those testing directories, I will be able to push upstream and merge when I am ready.

http://stackoverflow.com/comment/90798299
score: 0
type: Comment
type: QuestionComment
has text: I printed it and it gave me numbers assigned for the letter such as a being 1 and b being 2 and so on and so forth but when I open the file to save to it is still giving me the same random characters as the picture @HaR
comment on: http://stackoverflow.com/q/51924253

http://stackoverflow.com/comment/90864393
comment on: http://stackoverflow.com/a/51956223
score: 0
type: AnswerComment
has text: I think the phrase "abusing mutable arguments" is a bit misleading and unclear.
type: Comment

http://stackoverflow.com/comment/90861732
has text: docs: *The binary representation is also the **native format used internally in Qt**, and is very efficient and fast to convert to and from.* Saying that it is internal means that you can change from version to version without prior notice, so there is no single way to do it, it is similar to what happens with QDataStream.
comment on: http://stackoverflow.com/q/51955605
score: 2
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/90741153
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51895280
has text: Try setting `wordlist=["some_string1", "some_other'string"]`, and then try your list comprehension.

http://stackoverflow.com/comment/90696272
score: 1
has text: This looks like a good solution, but it could be better if you explain what you are doing in a few words.
type: AnswerComment
comment on: http://stackoverflow.com/a/51869802
type: Comment

http://stackoverflow.com/a/51855880
upvote count: 1
has comment: http://stackoverflow.com/comment/90922524
has body: In answer to your main question, there are disadvantages in using any single measure of grey. It depends on what you want from your image. For example, if you have colored text on white background, if you want to make the text stand out you can use the minimum of the r, g, b values as your measure. But if you have black text on a colored background, you can use the maximum of the values for the same result. In my software I offer the option of max, min or median value for the user to choose. The results on continuous tone images are also illuminating. In response to comments asking for more details, the code for a pixel is below (without any defensive measures). int Ind0[3] = {0, 1, 2}; //all equal int Ind1[3] = {2, 1, 0}; // top, mid ,bot from mask... int Ind2[3] = {1, 0, 2}; int Ind3[3] = {1, 2, 0}; int Ind4[3] = {0, 2, 1}; int Ind5[3] = {2, 0, 1}; int Ind6[3] = {0, 1, 2}; int Ind7[3] = {-1, -1, -1}; // not possible int *Inds[8] = {Ind0, Ind1, Ind2, Ind3, Ind4, Ind5, Ind6, Ind7}; void grecolor(unsigned char *rgb, int bri, unsigned char *grey) { //pick out bot, mid or top according to bri flag int r = rgb[0]; int g = rgb[1]; int b = rgb[2]; int mask = 0; mask |= (r &gt; g); mask &lt;&lt;= 1; mask |= (g &gt; b); mask &lt;&lt;= 1; mask |= (b &gt; r); grey[0] = rgb[Inds[mask][2 - bri]]; // 2, 1, 0 give bot, mid, top }
has comment: http://stackoverflow.com/comment/90883753
type: Answer
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/90922865
answers question: http://stackoverflow.com/q/51818193
has comment: http://stackoverflow.com/comment/90967762

http://stackoverflow.com/comment/90660003
comment on: http://stackoverflow.com/a/51849537
score: 0
type: AnswerComment
has text: Thank you for responding I will try this
type: Comment

http://stackoverflow.com/a/51825671
has body: Set the parameter min_periods to 1 df['roll_speed'] = df.groupby('leg').speed.rolling(5, min_periods = 1).mean()\ .round(1).reset_index(drop = True) leg speed roll_speed 0 1 10 10.0 1 1 11 10.5 2 1 12 11.0 3 1 13 11.5 4 1 12 11.6 5 1 15 12.6 6 1 19 14.2 7 1 12 14.2 8 2 10 10.0 9 2 10 10.0 10 2 12 10.7 11 2 15 11.8 12 2 19 13.2 13 2 11 13.4
answers question: http://stackoverflow.com/q/51825513
downvote count: 0
score: 7
upvote count: 7
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51825513
type: Answer

http://stackoverflow.com/comment/90652580
score: 0
has text: With `kwargs` attempt error message should differ. What is it?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51848082

http://stackoverflow.com/comment/90923212
score: 1
type: Comment
has text: beautiful, I forgot to change that as well.
comment on: http://stackoverflow.com/a/51980769
type: AnswerComment

http://stackoverflow.com/comment/90583752
type: QuestionComment
has text: Hey sraw, I've fixed the example and clarified the intent of workflow
comment on: http://stackoverflow.com/q/51805642
score: 0
type: Comment

http://stackoverflow.com/q/51891451
has answer: http://stackoverflow.com/a/51892947
type: UnansweredQuestion
tagged with: authentication
type: Question
tagged with: certificate
score: 4
upvote count: 4
answer count: 2
downvote count: 0
has title: python certificate based authentication in REST request
favorite count: 0
has body: I tried to send a REST request in python with a certificate based authentication to a given server that is providing the REST api's but after hours of searching and trying I think I need help. I have a signed certificate from the mentioned server and the key for that cert. The Server itselfs does also provide a certificate for https. I tried the library httplib.HTTPSConnection: import httplib import urllib clientCert = "client.crt" clientKey = "client.key" serverCert = 'server.crt' serverApi = "/api/getExample" serverHost = "restapi.example.com" serverPort = 443 requestMethod = "POST" params = urllib.urlencode({'someId': 'myId'}) headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "application/json"} conn = httplib.HTTPSConnection(serverHost, serverPort, key_file=clientKey, cert_file=clientCert) conn.request(requestMethod, serverApi, params, headers) response = conn.getresponse() conn.getresponse() conn.close() I get ssl.SSLError: SSL: CERTIFICATE_VERIFY_FAILED Is it possible to get a cert based auth running with that library?
tagged with: rest
tagged with: python
has answer: http://stackoverflow.com/a/76713544

http://stackoverflow.com/q/51943838
favorite count: 0
type: UnansweredQuestion
has title: No feedback when I run the crawler
tagged with: python
upvote count: 0
tagged with: web-crawler
type: Question
score: -1
has body: import requests from requests.exceptions import RequestException import re def get_one_page(url): try: headers = { 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) ' 'Chrome/48.0.2564.116 Safari/537.36' } response = requests.get(url, headers=headers) if response.status_code == 200: return response.text return None except RequestException: return None def parse_one_page(html): pattern = re.compile('&lt;dd&gt;.*?board-index.*?&gt;(.*?)&lt;/i&gt;.*?src="(.*?)".*?name.*?a.*?&gt;(.*?)&lt;/ a&gt;.*?star.*?&gt;(.*?)&lt;/p&gt;' '.*?releasetime.*?(.*?)&lt;/p&gt;.*?integer.*?&gt;(.*?)&lt;/i&gt;.*?fraction.*?&gt;(.*?)&lt;/i&gt;.*?&lt;/dd&gt;', re.S) items = re.findall(pattern, html) return items def main(): url = 'https://maoyan.com/board/4' html = get_one_page(url) print(parse_one_page(html)) if __name__ == '__main__': main() Just following the tutorial,but nothing back.I didn't find that there was a error,but it happened. Can anyone tell me what is wrong with my program?
has answer: http://stackoverflow.com/a/51944461
answer count: 1
downvote count: 1

http://stackoverflow.com/comment/90625216
type: AnswerComment
has text: You shouldn't really use assert statements for this kind of thing, as they are for debugging: https://docs.python.org/3/reference/simple_stmts.html#the-assert-statement
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51835801

http://stackoverflow.com/comment/90842520
type: QuestionComment
has text: Can you plot it vertically i/o horizontally?
comment on: http://stackoverflow.com/q/51945411
score: 0
type: Comment

http://stackoverflow.com/comment/97952893
score: 0
type: Comment
has text: @rafael did you find a way of doing this via flask-wtf forms? I know you went with a form in Dash using dcc.components as I saw your thread on plotly forum but I was wondering if you know how to do it this way as decribed in your question because I need the same thing. Thanks
type: AnswerComment
comment on: http://stackoverflow.com/a/51840057

http://stackoverflow.com/a/51816840
answers question: http://stackoverflow.com/q/51816284
has body: Something like this will flatten a dict structure containing dicts, lists and tuples into a flat dict. The json_data blob is an excerpt from the data you posted. import json import collections json_data = """ {"additionalLocaleInfos":[],"approved":false,"approvedBy":null,"approvedOn":null,"catalogId":4,"code":"611","createdOn":"2018-03-24 09:39","customsCode":null,"deletedOn":null,"id":1,"invariantName":"Leisure Ali Baba Trousers","isPermanent":false,"locale":null,"madeIn":null,"manufacturer":{"createdOn":"2018-02-23 18:20","deletedOn":null,"id":1,"invariantName":"Unknown","updatedOn":"2018-02-23 18:20"},"onNoStockShowComingSoon":false,"season":"","updatedOn":"2018-03-24 09:39","variants":[{"assets":[{"fileName":"mu/2016/05/16/leisure-ali-baba-trousers-32956-0.jpg","id":1,"mediaType":{"baseFilePath":"Catalog","id":7,"name":"Product Main Image"},"sortOrder":0},{"fileName":"080113/3638.jpg","id":2,"mediaType":{"baseFilePath":"Catalog","id":8,"name":"Product Additional Image"},"sortOrder":0},{"fileName":"mu/2016/05/16/leisure-ali-baba-trousers-32956-1.jpg","id":3,"mediaType":{"baseFilePath":"Catalog","id":8,"name":"Product Additional Image"},"sortOrder":0},{"fileName":"mu/2015/07/21/leisure-ali-baba-trousers-13730-0.jpg","id":4,"mediaType":{"baseFilePath":"Catalog","id":8,"name":"Product Additional Image"},"sortOrder":0},{"fileName":"mu/2016/05/16/leisure-ali-baba-trousers-32956-2.jpg","id":5,"mediaType":{"baseFilePath":"Catalog","id":8,"name":"Product Additional Image"},"sortOrder":0},{"fileName":"mu/2015/07/29/leisure-ali-baba-trousers-13853-0.jpg","id":6,"mediaType":{"baseFilePath":"Catalog","id":8,"name":"Product Additional Image"},"sortOrder":0}],"attributes":[{"attribute":{"code":"COL","cultureNeutralName":"Color","id":1,"useAsFilter":false},"code":"BLACK","groupId":0,"id":3,"invariantValue":"BLACK","locale":null,"sortOrder":0,"valueLocale":null},{"attribute":{"code":"SZ","cultureNeutralName":"Size","id":2,"useAsFilter":false},"code":"ONE SIZE","groupId":0,"id":7…
score: 1
accepted answer of: http://stackoverflow.com/q/51816284
upvote count: 1
has comment: http://stackoverflow.com/comment/90590944
has comment: http://stackoverflow.com/comment/90589414
has comment: http://stackoverflow.com/comment/90591171
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90588236
downvote count: 0
type: Answer

http://stackoverflow.com/comment/90694178
has text: consider using a `multiprocessing.Manager()` object to store your results (create a fake `list` object from it). then maybe you have to sort the data and write it back
comment on: http://stackoverflow.com/q/51871322
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/51891257
downvote count: 6
has answer: http://stackoverflow.com/a/51902026
type: Question
has answer: http://stackoverflow.com/a/56435059
upvote count: 0
has answer: http://stackoverflow.com/a/51892005
has comment: http://stackoverflow.com/comment/90733595
answer count: 3
has body: Develop a Python method that for any integer amount in the range from 24 to 1000 returns a list consisting of numbers 5 and 7 only, such that their sum is equal to amount. For example, change(28) may return [7, 7, 7, 7], while change(49) may return [7, 7, 7, 7, 7, 7, 7] or [5, 5, 5, 5, 5, 5, 5, 7, 7] or [7, 5, 5, 5, 5, 5, 5, 5, 7] i tried : def change(amount): if amount == 24: return [5, 5, 7, 7] change(24) print (amount) but i think there is more efficient way to do the trick.. any help?
score: -6
favorite count: 0
has comment: http://stackoverflow.com/comment/90733752
type: UnansweredQuestion
has title: Python method for any integer returns a list consisting of numbers 5 and 7 only
tagged with: python

http://stackoverflow.com/comment/90737702
comment on: http://stackoverflow.com/a/51891937
has text: Thank you for introducing me to the concept of Structured arrays. Exactly what I needed. :)
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/90826729
type: QuestionComment
has text: I was looking for how to deal with sub_dict entry.
comment on: http://stackoverflow.com/q/51937684
score: 0
type: Comment

http://stackoverflow.com/q/51827749
score: 0
has comment: http://stackoverflow.com/comment/90610527
has title: Find the index of max value in a 3D array and store as 2D array
tagged with: python
answer count: 0
type: UnansweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/90610292
tagged with: numpy
has comment: http://stackoverflow.com/comment/90610514
has comment: http://stackoverflow.com/comment/90609835
has comment: http://stackoverflow.com/comment/90609943
has body: I have a 3D array of shape 7x10000x10000 . The first dimension of the array is a vector of length 7. I want to create a 2D array, of shape 10000x10000, that has the the index of max element in the vector. I tried doing it using loops but it s very slow because of the size of the array. Is there any better way of doing it , like flatten, find max in each vector and reshape? for i in range(0,7): for j in range(0,10000): for k in range(0,10000): vector = myarray[:,j,k] m = np.argmax(vector) img[j,k] = m

http://stackoverflow.com/comment/90817341
type: AnswerComment
has text: Is the difference in the method the key is distributed (meaning, it's certificate pinning if it's distributed through some other, secure channel, rather than provided on first use by the device)?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51899978

http://stackoverflow.com/q/51938519
has body: I'm trying to use the following list comprehension to retrieve the title attribute of a BeautifulSoup object. [i.find(class_ = 'turnstileLink')['title'] for i in soup_obj.find_all(class_ = 'jobtitle')] However it's failing because the first element doesn't have a title object. [i for i in soup_obj.find_all(class_ = 'jobtitle')][0] Nanny, Babysitter, Daycare Worker, Childcare Worker But the remaining elements do contain that attribute. [i for i in soup_obj.find_all(class_ = 'jobtitle')][1] Babysitter/Kids Klub Therefore when I grab an element individually that's not element 0, this seems to work FYI: here is the script that created soup_obj import requests from bs4 import BeautifulSoup from collections import Counter import pandas as pd url = 'https://www.indeed.com/jobs?q=babysitter&l=Austin,+TX&sort=date&limit=10&radius=25' page = requests.get(url) soup_obj = BeautifulSoup(page.text, 'html.parser') Apologies if any of this is difficult to digest, I'm still a relative newbie to BeautifulSoup and python in general. Can provide more detail if needed
tagged with: beautifulsoup
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51938598
has comment: http://stackoverflow.com/comment/90827253
tagged with: python
has comment: http://stackoverflow.com/comment/90827267
type: Question
has comment: http://stackoverflow.com/comment/90827222
score: 0
answer count: 1
has title: Using BeautifulSoup to ignore certain elements in a list

http://stackoverflow.com/a/51946871
has comment: http://stackoverflow.com/comment/90843102
type: Answer
answers question: http://stackoverflow.com/q/51946815
has body: Better is create dictionary of DataFrames: d = {'{}_{}'.format(k[1], k[0]):v for k, v in df.groupby(['ID','Product_Name'])} print (d) {'MS_1': ID Date Product_Name transaction 0 1 01-01-2018 MS 234 1 1 01-02-2018 MS 2345 2 1 02-02-2018 MS 234, 'HSD_2': ID Date Product_Name transaction 3 2 01-01-2018 HSD 2312 4 2 02-02-2018 HSD 2234, 'MS_3': ID Date Product_Name transaction 5 3 01-01-2018 MS 2123 6 3 02-02-2018 MS 345} And for select use: print (d['MS_1']) ID Date Product_Name transaction 0 1 01-01-2018 MS 234 1 1 01-02-2018 MS 2345 2 1 02-02-2018 MS 234 print (d['HSD_2']) ID Date Product_Name transaction 3 2 01-01-2018 HSD 2312 4 2 02-02-2018 HSD 2234 EDIT: @jpp suggestion for create keys by tuples: d = dict(tuple(df.groupby(['ID','Product_Name']))) print (d) {(1, 'MS'): ID Date Product_Name transaction 0 1 01-01-2018 MS 234 1 1 01-02-2018 MS 2345 2 1 02-02-2018 MS 234, (2, 'HSD'): ID Date Product_Name transaction 3 2 01-01-2018 HSD 2312 4 2 02-02-2018 HSD 2234, (3, 'MS'): ID Date Product_Name transaction 5 3 01-01-2018 MS 2123 6 3 02-02-2018 MS 345} print (d[(1, 'MS')]) ID Date Product_Name transaction 0 1 01-01-2018 MS 234 1 1 01-02-2018 MS 2345 2 1 02-02-2018 MS 234 print (d[(2, 'HSD')]) ID Date Product_Name transaction 3 2 01-01-2018 HSD 2312 4 2 02-02-2018 HSD 2234 And for convert back to big DataFrame with all subDataFrames use concat: df = pd.concat(dict(tuple(df.groupby(['ID','Product_Name'])))).reset_index(drop=True) print (df) ID Date Product_Name transaction 0 1 01-01-2018 MS 234 1 1 01-02-2018 MS 2345 2 1 02-02-2018 MS 234 3 2 01-01-2018 HSD 2312 4 2 02-02-2018 HSD 2234 5 3 01-01-2018 MS 2123 6 3 02-02-2018 MS 345
upvote count: 2
accepted answer of: http://stackoverflow.com/q/51946815
score: 2
has comment: http://stackoverflow.com/comment/90843171
has comment: http://stackoverflow.com/comment/90843456
has comment: http://stackoverflow.com/comment/90843195
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90843305
has comment: http://stackoverflow.com/comment/90843379
has comment: http://stackoverflow.com/comment/90843272

http://stackoverflow.com/q/51889049
tagged with: patch
score: 4
tagged with: python
favorite count: 0
has title: Unable to Mock class that inherits from another class (which creates/uses singleton object)
tagged with: unit-testing
accepted answer: http://stackoverflow.com/a/51894669
type: AnsweredQuestion
type: Question
upvote count: 4
has answer: http://stackoverflow.com/a/51894669
has body: I have three classes and one unittest case: 1) A.py: class A(object): def __new__(cls): """ Overriding the __new__ method to make the A a singleTon class :return: cls.instance """ if not hasattr(cls, 'instance') or not cls.instance: cls.instance = super(A, cls).__new__(cls) return cls.instance def execute(): print("class A") return "Coming from class A" 2) B.py: from A import A class B(object): def __init__(self): """ Initialize and declare any members/methods that can be passed over class that inherit this class """ self.a = A() self.name = Name() def run(self): pass class Name: def __init__(self): self.test_dict = {} 3) C.py from B import B class C(B): def __init__(self): super(C, self).__init__() self.result = None def run(self): self.result = self.A.execute() return self.result 4) test.py import unittest from unittest.mock import patch from A import A from B import B from C import C class TestMethods(unittest.TestCase): @patch('A.A') def test_basic(self, MockA): a = MockA() a.execute.return_value = "Testing code" c = C() result = c.run() self.assertEqual(result,"Testing code") if __name__ == '__main__': unittest.main() while executing test.py, I am getting following error: ERROR: test_basic (main.TestMethods) Traceback (most recent call last): File "C:\Users\davinder\AppData\Local\Continuum\Anaconda3\lib\unittest\mock.py", line 1179, in patched return func(*args, **keywargs) File "C:/Users/davinder/PythonCodes/Test Framework/test.py", line 14, in test_basic c = C() File "C:\Users\davinder\PythonCodes\Test Framework\C.py", line 5, in __init__ super(C, self).__init__() File "C:\Users\davinder\PythonCodes\Test Framework\B.py", line 8, in __init__ self.a = A() File "C:\Users\davinder\PythonCodes\Test Framework\A.py", line 8, in __new__ cls.instance = super(A, cls).__new__(cls) TypeError: super() argument 1 must be type, not MagicMock ---------------------------------------------------------------------- Ran 1 tests in 0.018s FAILED (errors=1) I want to test run() fr…
tagged with: mocking
answer count: 1
downvote count: 0

http://stackoverflow.com/a/51846624
type: Answer
has comment: http://stackoverflow.com/comment/90649394
score: 0
answers question: http://stackoverflow.com/q/51846525
has body: You are missing a comma on the end of line 20. c.execute("INSERT INTO customerProfiles (firstname, lastname, stocknumber, emailaddress, cellphone, housephone, workphone, leaseorbuy) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", (firstname, lastname, stocknumber, emailaddress, phonenum1, phonenum2, phonenum3, leaseorbuy)) (Because you were continuing the rest of the c.execute() block on the next line.)

http://stackoverflow.com/a/51947171
upvote count: 7
answers question: http://stackoverflow.com/q/51946571
score: 5
type: Answer
has body: The dataclasses.py is the module which provides decorator and functions for generating regular class methods by using of the field annotations. Which means that after processing class, the user defined fields shall be formed using PEP 526 Syntax of Variable annotations. The module annotations is accessible as __annotations__. According to the Runtime effects of type annotations the annotated types is accessible via __annotations__ attribute or by usage of the typing.get_type_hints, the last one the recommended. Please see some code samples below: from typing import Dict, ClassVar, get_type_hints from dataclasses import dataclass @dataclass class Starship: hitpoints: int = 50 get_type_hints(Starship) // {'hitpoints': int} Starship.__annotations__ // {'hitpoints': int} dataclasses.__annotations__ // The annotations of the dataclasses module. get_type_hints(get_type_hints)
downvote count: 2

http://stackoverflow.com/comment/90618907
comment on: http://stackoverflow.com/q/51832141
score: 0
has text: The error is quite clear, and the way forward is to read the doc for the function you are incorrectly using.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51808962
type: Answer
answers question: http://stackoverflow.com/q/51807056
has body: Users also have a User.default_avatar attribute. If you compare that to User.avatar, you should be able to filter out the users for which those match. @bot.command() async def userlist(ctx): for user in ctx.guild.members: if user.avater != user.default_avater: print (user.name+"#"+user.discriminator) This is assuming that your real problem isn't that you're looping through all the members again inside the else. Try this variation of your solution: @bot.command() async def userlist(ctx): for user in ctx.guild.members: if user.avatar: print (user.name+"#"+user.discriminator)
has comment: http://stackoverflow.com/comment/118470688
accepted answer of: http://stackoverflow.com/q/51807056
type: AcceptedAnswer
score: 0

http://stackoverflow.com/a/51832123
has comment: http://stackoverflow.com/comment/90618671
upvote count: 9
answers question: http://stackoverflow.com/q/51831733
score: 9
type: AcceptedAnswer
downvote count: 0
has body: The problem is that you've applied a decorator designed for functions to a class. The result is not a class, but a function that wraps up a call to the class. This causes a number of problems (e.g., as pointed out by Aran-Fey in the comments, you can't isinstance(feat, mystery), because mystery). But the particular problem you care about is that you can't pickle instances of inaccessible classes. In fact, that's basically what the error message is telling you: PicklingError: Can't pickle &lt;class '__main__.mystery'&gt;: it's not the same object as __main__.mystery Your feat thinks its type is __main__.mystery, but that isn't a type at all, it's the function returned by the decorator that wraps that type. The easy way to fix this would be to find a class decorator meant that does what you want. It might be called something like flyweight instead of memoize, but I'm sure plenty of examples exist. But you can build a flyweight class by just memoizing the constructor, instead of memoizing the class: class mystery: @funcy.memoize def __new__(cls, num): return super().__new__(cls) def __init__(self, num): self.num = num … although you probably want to move the initialization into the constructor in that case. Otherwise, calling mystery(1) and then mystery(1) will return the same object as before, but also reinitialize it with self.num = 1, which is at best wasteful, and at worst incorrect. So: class mystery: @funcy.memoize def __new__(cls, num): self = super().__new__(cls) self.num = num return self And now: &gt;&gt;&gt; feat = mystery(1) &gt;&gt;&gt; feat &lt;__main__.mystery at 0x10eeb1278&gt; &gt;&gt;&gt; mystery(2) &lt;__main__.mystery at 0x10eeb2c18&gt; &gt;&gt;&gt; mystery(1) &lt;__main__.mystery at 0x10eeb1278&gt; And, because the type of feat is now a class that's accessible under the module-global name mystery, pickle will have no problem with it at all: &gt;&gt;&gt; pickle.dumps(feat) b'\x80\x03c__main__\nmystery\nq\x00)\x81q\x01}q\x02X\x03\x00\x00\x00numq\x03K…
type: Answer
accepted answer of: http://stackoverflow.com/q/51831733

http://stackoverflow.com/comment/90778342
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51887725
has text: Dear @TC Zhang, Unfortunately, I appreciate your effort. Please I am still getting all values Non_Break

http://stackoverflow.com/q/51903109
upvote count: 0
has title: How to handle \r\n from command output in python or bash
has comment: http://stackoverflow.com/comment/90758223
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90757394
score: -3
tagged with: python
has answer: http://stackoverflow.com/a/51904606
has comment: http://stackoverflow.com/comment/90757330
has comment: http://stackoverflow.com/comment/90757535
type: Question
answer count: 2
tagged with: newline
has body: I am running a simple bash script var=$(script.sh) the output of script.sh is of the form: \r\n 123 ok Now when I do: echo $var it returns \r\n. It has not captured the 123 and ok. I want var to get the entire output. In python I tried the same thing using: bashCommand = ./myscript.sh process = Popen(bashCommand.split(), stdout=subprocess.PIPE) output, error = process.communicate() print("Output", output) but even here print output prints \r\n How to capture the entire stdout? Update: here's my bash script xyz.sh: #! /bin/sh set -x ./myscript.elf parm1 parm2 |{ while IFS= read -r line do echo "$line" done } Heres the output of ./xyz.sh: + ./myscript.elf parm1 parm2 + IFS= + read -r line &gt;123 OK &gt;+ echo $'\r' + IFS= + read -r line Here is the output if just run the command on ./myscript.elf parm1 parm2 line: ./myscript.elf parm1 parm2 &gt;123 OK &gt;
has comment: http://stackoverflow.com/comment/90757274
has comment: http://stackoverflow.com/comment/90759232
tagged with: bash
downvote count: 3
has answer: http://stackoverflow.com/a/51905616
tagged with: shell
favorite count: 0

http://stackoverflow.com/a/68244128
has comment: http://stackoverflow.com/comment/128447286
answers question: http://stackoverflow.com/q/51928807
type: AcceptedAnswer
downvote count: 1
has body: I had the same error as you but my problem was that I did not properly installed ImageMagick : in the installation wizard you need to check "install legacy utilities". So I reinstalled it, checked this box and it worked. Here is a screenshot of the page I am talking about :
type: Answer
upvote count: 27
score: 26
accepted answer of: http://stackoverflow.com/q/51928807

http://stackoverflow.com/a/51876319
type: Answer
upvote count: 3
score: 3
answers question: http://stackoverflow.com/q/51875174
downvote count: 0
has body: Python's arguments passing works the same for all objects - the original object is passed (not "a copy of", not "a reference to", not "a pointer to" - it IS the object itself that is passed), regardless of the object's type, whether it's mutable or not etc. These objects are then bound to their matching parameter's names as local variables. The difference you observe is actually the result of the difference between to totally distinct operations: rebinding a (local) name and mutating an object. Since parameters are local variables (local names actually) rebinding a parameter in your function's body only make this name point to another object, and does not impact the original argument (except for decreasing the reference counter). So obviously this has absolutely no effect outside the function itself. Now when you mutate one of your argument, since you are working on the very object you passed to the function, those changes are, very obviously, visible outside the function. Here: def external_1(instance_var, instance_list, instance_str, instance_tuple, instance_dict): # this one rebinds the local name `instance_var` # to a new `int` object. Doesn't affect the object # previously bound to `instance_var` instance_var += 1 # those three statement mutate `instance_list`, # so the effect is visible outside the function del instance_list[0] del instance_list[0] instance_list[0] = 15 # this one rebinds the local name `instance_str` # to the literal string "Bar". Same as for `instance_var` instance_str = "Bar" # this one creates a list from `instance_tuple`, # mutate this list, and discard it. IOW it eats a # couple processor cycles for nothing. list(instance_tuple)[0] = 15 # and this one mutates `instance_dict` so the # effect is visible outside the function instance_dict.update({"one": 15}) And here: def external_2(instance): # this one mutates `instance` - it's actually # syntactic sugar for # `instance.__setattr__("my_var", instance.__getattribute__("my_var") + 1))` inst…

multidimensional-array
tags question: http://stackoverflow.com/q/51949826
tags question: http://stackoverflow.com/q/51888101
tags question: http://stackoverflow.com/q/51815087
tags question: http://stackoverflow.com/q/51876012
type: Tag
tags question: http://stackoverflow.com/q/51880271
tags question: http://stackoverflow.com/q/51870897
tags question: http://stackoverflow.com/q/51849511
tags question: http://stackoverflow.com/q/51843254
tags question: http://stackoverflow.com/q/51851016
tag name: multidimensional-array
tags question: http://stackoverflow.com/q/51810407

http://stackoverflow.com/comment/90683952
score: 0
type: Comment
type: QuestionComment
has text: In your edited question, what is that `session`? If whatever library it comes from has some way to wait for something to finish, that's what you want to do. But without any idea of what library that is, it's impossible to give you a more detailed suggestion.
comment on: http://stackoverflow.com/q/51865326

http://stackoverflow.com/comment/90567919
type: QuestionComment
has text: Then it is duplicate. Stacking is done by output of one network is input of other instead of placeholders. And loading is described [here](https://stackoverflow.com/a/51018846/7443104)
comment on: http://stackoverflow.com/q/51804688
score: 0
type: Comment

http://stackoverflow.com/comment/90761494
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51905428
has text: Sure, But isn't `z` a list in both scenarios?

http://stackoverflow.com/q/51884098
has answer: http://stackoverflow.com/a/51884197
tagged with: python
has title: Messed up my pip and python installs
has comment: http://stackoverflow.com/comment/90719905
type: UnansweredQuestion
score: 1
upvote count: 1
tagged with: pip
has answer: http://stackoverflow.com/a/57872364
has body: Working with linux mint, I went to install a package yesterday with pip. user@mycomp ~ $ pip install bitmex-ws The program 'pip' is currently not installed. You can install it by typing: sudo apt install python-pip Ok, installing pip jason@speedylinux ~ $ sudo apt install python-pip And it appears to complete fine. Trying again... jason@speedylinux ~ $ pip install bitmex-ws Collecting bitmex-ws Downloading https://files.pythonhosted.org/packages/f0/5c/6ea7f43b49cf46b0d1552abd6ab89aae4f74641ebca2d836c52737300ea1/bitmex-ws-0.3.1.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; ImportError: No module named setuptools You are using pip version 8.1.1, however version 18.0 is available. You should consider upgrading via the 'pip install --upgrade pip' command. Thinking it was a problem with that last error (but it looks like it was actually just that setuptools wasn't installed), just doing as it says... user@mycomp ~ $ pip install --upgrade pip Traceback (most recent call last): File "/usr/bin/pip", line 9, in &lt;module&gt; from pip import main ImportError: cannot import name main I was stumped at this point and did a bunch of googling and SO searching. Ended up doing this after: jason@speedylinux ~ $ curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py success. jason@speedylinux ~ $ python get-pip.py /tmp/tmpM7KfNh/pip.zip/pip/_vendor/requests/__init__.py:83: RequestsDependencyWarning: Old version of cryptography ([1, 2, 3]) may cause slowdown. Collecting pip Using cached https://files.pythonhosted.org/packages/5f/25/e52d3f31441505a5f3af41213346e5b6c221c9e086a166f3703d2ddaf940/pip-18.0-py2.py3-none-any.whl Installing collected packages: pip Found existing installation: pip 18.0 Uninstalling pip-18.0: Could not install packages due to an EnvironmentError: [Errno 13] Permission denied: '/usr/bin/pip3' Consider using the `--user` option or check the permissions. which seeme…
type: Question
answer count: 2
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/139313795
comment on: http://stackoverflow.com/a/51896790
type: AnswerComment
score: 0
type: Comment
has text: A possible problem with the cost function is that absolute value is non smooth. Accordingly a derivative-free method such as Nelder-Mead and Powel should be specified or an approximation of the abs function such as sqrt(x²+ε²) should be used. ε should be a small number such as 0.1

http://stackoverflow.com/comment/90853578
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51866319
has text: Thanks for the example. Unfortunately it doesn't boost my accuracy, but this could well be a fault in my data. I noticed a huge discrepancy in my `max_sequence_len` (198720) and `min_sequence_len` (3!!) so this is clearly a problem
type: AnswerComment

http://stackoverflow.com/comment/90741547
type: Comment
type: QuestionComment
has text: Thanks for ur replying. Please note that, `task` is created by the loop rather that asyncio module. Due to the doc, `task` created by loop can be used by the loop.See: https://docs.python.org/3/library/asyncio-eventloop.html#tasks .
comment on: http://stackoverflow.com/q/51894809
score: 0

http://stackoverflow.com/comment/90655478
type: AnswerComment
comment on: http://stackoverflow.com/a/51851165
score: 0
type: Comment
has text: Glad I could help!

http://stackoverflow.com/comment/90779667
score: 0
type: Comment
type: AnswerComment
has text: while trying things I did a print (response['Regions'][0]['Endpoint']) gives me some help to find the values I am looking I updated the question.
comment on: http://stackoverflow.com/a/51914836

http://stackoverflow.com/q/51888539
has comment: http://stackoverflow.com/comment/90728226
downvote count: 3
has title: i want to use regular expressions to change the filename like this
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/90728276
favorite count: 0
upvote count: 0
has body: i want to use regular expressions to change the filename like this 1-30330036.jpg change to 1-30330036 1-30330036-1.jpg change to 1-30330036 how can i write my regular expressions? i have solve this question!
score: -3
type: AnsweredQuestion
tagged with: filenames
type: Question
has answer: http://stackoverflow.com/a/51888871
accepted answer: http://stackoverflow.com/a/51888871
answer count: 1

http://stackoverflow.com/comment/90883826
comment on: http://stackoverflow.com/q/51945455
type: Comment
type: QuestionComment
has text: I understand the idea, the problem is I have no idea how to implement it. Also one-hot representation should probably be in a sparse format. There are > 1M tags.
score: 0

http://stackoverflow.com/q/51950533
has answer: http://stackoverflow.com/a/61139559
has body: Python 3 installation was working fine until yesterday. Then this happened today. Output from command prompt (Windows 10) when I type Python: Fatal Python error: init_sys_streams: can't initialize sys standard streams AttributeError: module 'io' has no attribute 'OpenWrapper' Current thread 0x00001204 (most recent call first): Googled and searched thoroughly for answers in previous questions nothing seems to be helping. Just in case if relevant, used Python 3 with VS code before this. Also tried uninstalling current Python (3.6.5) and reinstall latest Python (3.7.0) but error still persists.
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/72372036
upvote count: 15
has comment: http://stackoverflow.com/comment/90853338
has answer: http://stackoverflow.com/a/72663396
downvote count: 0
has comment: http://stackoverflow.com/comment/90853232
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/56283693
has answer: http://stackoverflow.com/a/77030925
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/90852513
answer count: 6
score: 15
has comment: http://stackoverflow.com/comment/90854368
has answer: http://stackoverflow.com/a/73045017
has comment: http://stackoverflow.com/comment/90854251
linked to: http://stackoverflow.com/q/26569828
has title: Fatal Python error: init_sys_streams: can't initialize sys standard streams AttributeError: module 'io' has no attribute 'OpenWrapper'
has comment: http://stackoverflow.com/comment/90854632

http://stackoverflow.com/comment/90779841
has text: I guess but you could say the same about the video file itself, I mean, it holds all the information about the frames...anyways, if you'd like to make a video using `cv2.VideoWriter()`, then yes, you need to scale and convert your array. `VideoWriter()` needs RGB images (not single-channel grayscale images like your `water_depth`) and needs them to be 8-bit. You can scale them appropriately between 0 and 255 with `cv2.normalize()` and then you can merge that into a three-channel image with `cv2.merge()`.
score: 3
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51914683

http://stackoverflow.com/q/51856138
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90664591
has comment: http://stackoverflow.com/comment/90664602
has body: I made a GUI in Python and i just wanted to know how can i import a C file into python so every time a button is clicked on my GUI, different methods in the C program will be executed. I tried the 'Python' method of importing: sys.path.insert(0, '/home/pi/Desktop/FTPclass.py') import FTPclass That worked for the python file i imported, but when I do the same for my c file, it complains saying my "testinc" module doesn't exist. Thanks for everyone help in advance. ~Neamus
score: 0
linked to: http://stackoverflow.com/q/9420673
has title: How to import a C file into python
has comment: http://stackoverflow.com/comment/90664560
type: Question
linked to: http://stackoverflow.com/q/145270
tagged with: http://stackoverflow.com/tag/c
duplicate of: http://stackoverflow.com/q/145270
has answer: http://stackoverflow.com/a/51856257
answer count: 1
has comment: http://stackoverflow.com/comment/90664521
accepted answer: http://stackoverflow.com/a/51856257
linked to: http://stackoverflow.com/q/89228

http://stackoverflow.com/a/51919290
type: Answer
downvote count: 0
has body: Just move your for loop for writing the bar values (plt.text) inside the previous for loop. The problem is that you write the bar values after plotting all the three bars and so, once you come out of the plotting for loop, the variable bars contains only the values of the gray bars (the LinkedIn data) and hence you see the values only on top of gray bars. I am just writing the necessary part below. rest code remains the same. for i in range(total_data): bars = plt.bar(classes_num - width / 2. + i / total_data * width, values[i], width=width / total_data, align="edge", animated=0.4) for rect in bars: height = rect.get_height() plt.text(rect.get_x() + rect.get_width()/2.0, height, '%d' % int(height), ha='center', va='bottom') Output
score: 5
has comment: http://stackoverflow.com/comment/90788387
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51919113
upvote count: 5
answers question: http://stackoverflow.com/q/51919113

http://stackoverflow.com/comment/90632391
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51838911
has text: @thebjorn yes I am.

http://stackoverflow.com/a/51903975
has comment: http://stackoverflow.com/comment/90795916
has body: Update: added compatibility for Python2.7 Tested and confirmed working with Python2.7, Python3.5 and Python3.6 Credit for pointing out dis goes to Patrick Haugh¹ Implementation (parsing of the dis output) is my own: Setup: import dis import sys from contextlib import contextmanager # setup test environment def a(_,__): pass def b(_,__,___): pass def c(_): pass def g(): pass d = 4 def test(flag): e = c if flag: a(a(b,c), [l for l in g(1, x=2)]) else: b(a, int(flag), c(e)) d = d + 1 def calculate(a, b, operator): if operator == Operator.add: add(a, b) elif operator == Operator.subtract: subtract(a, b) class Operator(object): add = "add" subtract = "subtract" Python 2/3 compatibility: class AttrDict(dict): def __init__(self, *args, **kwargs): super(AttrDict, self).__init__(*args, **kwargs) self.__dict__ = self @contextmanager # https://stackoverflow.com/a/12111817/2422125 def captureStdOut(output): stdout = sys.stdout sys.stdout = output try: yield finally: sys.stdout = stdout """ for Python &lt;3.4 """ def get_instructions(func): import StringIO out = StringIO.StringIO() with captureStdOut(out): dis.dis(func) return [AttrDict({ 'opname': i[16:36].strip(), 'arg': int(i[37:42].strip() or 0), 'argval': i[44:-1].strip() }) for i in out.getvalue().split("\n")] if sys.version_info &lt; (3, 4): dis.get_instructions = get_instructions import __builtin__ as builtin else: import builtins as builtin Code: def get_function_calls(func, built_ins=False): # the used instructions ins = list(dis.get_instructions(func))[::-1] # dict for function names (so they are unique) names = {} # go through call stack for i, inst in list(enumerate(ins))[::-1]: # find last CALL_FUNCTION if inst.opname[:13] == "CALL_FUNCTION": # function takes ins[i].arg number of arguments ep = i + inst.arg + (2 if inst.opname[13:16] == "_KW" else 1) # parse argument list (Python2) if inst.arg == 257: k = i+1 while k &lt; len(ins) and ins[k].opname != "BUILD_LIST": k += 1 ep = k-1 # LOAD that loaded this function e…
has comment: http://stackoverflow.com/comment/109008010
has comment: http://stackoverflow.com/comment/90798756
has comment: http://stackoverflow.com/comment/90821347
answers question: http://stackoverflow.com/q/51901676
type: Answer
has comment: http://stackoverflow.com/comment/90810158
has comment: http://stackoverflow.com/comment/90797818
score: 7
upvote count: 7
has comment: http://stackoverflow.com/comment/90812083
has comment: http://stackoverflow.com/comment/90798538
has comment: http://stackoverflow.com/comment/90819961
downvote count: 0
has comment: http://stackoverflow.com/comment/90811823

http://stackoverflow.com/q/51935610
tagged with: python
score: 2
downvote count: 0
has title: Converting a tuple to a datetime
tagged with: mysql
has body: I want to save dates and times into a mysql table and work with them later on. How to convert a tuple to a datetime to work with this value? from datetime import datetime, timedelta import mysql.connector mydb = mysql.connector.connect( host="localhost", user="**USER**", passwd="**PASSWORT**", database="**DATABASE"** ) # Table already created like this: # mycursor.execute("CREATE TABLE events2 (id INT AUTO_INCREMENT PRIMARYKEY, name VARCHAR(255), startdate DATETIME, enddate DATETIME, deadline INT, position INT, reminder INT)") name = "Testevent" startdate = datetime.now().strftime('%Y-%m-%d %H:%M:%S') enddate = datetime.now() + timedelta(days=14) deadline = 24 position = 25 reminder = 1 sql = "INSERT INTO events2 (name, startdate, enddate, deadline, position, reminder) VALUES (%s, %s, %s, %s, %s, %s)" val = (name, startdate, enddate, deadline, position, reminder) mycursor.execute(sql, val) mydb.commit() mycursor = mydb.cursor() mycursor.execute("SELECT startdate FROM events2 WHERE id = '7'") myresult = mycursor.fetchone() print(myresult) y = myresult + timedelta(days=14) Output: (datetime.datetime(2018, 8, 20, 18, 31, 42),) Traceback (most recent call last): File ".../Create_event.py", line 54, in &lt;module&gt; y = myresult + timedelta(days=14) TypeError: can only concatenate tuple (not "datetime.timedelta") to tuple
type: Question
upvote count: 2
answer count: 1
favorite count: 0
tagged with: tuples
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51935635
tagged with: datetime

http://stackoverflow.com/q/51804692
has answer: http://stackoverflow.com/a/57951416
tagged with: class
type: Question
has answer: http://stackoverflow.com/a/51804987
has comment: http://stackoverflow.com/comment/99947077
has answer: http://stackoverflow.com/a/56652444
possible better answer: http://stackoverflow.com/a/51804987
upvote count: 31
has body: Please excuse the novice question, but is Module just the same as saying model? That's what it sounds like, when the documentation says: Whenever you want a model more complex than a simple sequence of existing Modules you will need to define your model (as a custom Module subclass). Or... when they mention Module, are they referring to something more formal and computer-sciency, like a protocol / interface type thing?
tagged with: python
favorite count: 0
downvote count: 0
tagged with: pytorch
answer count: 5
has answer: http://stackoverflow.com/a/78893793
score: 31
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/43183244
has answer: http://stackoverflow.com/a/51808347
accepted answer: http://stackoverflow.com/a/51808347
has title: What exactly is the definition of a 'Module' in PyTorch?

http://stackoverflow.com/comment/90833691
type: QuestionComment
comment on: http://stackoverflow.com/q/51941827
type: Comment
score: 0
has text: Both answer to your question is "Yes", since the `result` inside your javascript is a json object, now you can do whatever you want. About the second question, the same thing, fetch all the data from your db, send it to Ajax, then you have the json.

http://stackoverflow.com/comment/90591278
has text: Check the question linked by @Aran-Fey and use `enumerate(days, 1)` to handle your offset.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51818670
score: 0

http://stackoverflow.com/comment/90630012
comment on: http://stackoverflow.com/a/51837838
has text: ValueError: time data "('2016-04-15T12:24:20.707Z',)" does not match format '%Y-%m-%dT%H:%M:%S.%fZ' is the error I am getting when I try the same thing, maybe because I am retrieving it from the database and not hardcoding it.
score: 1
type: AnswerComment
type: Comment

http://stackoverflow.com/q/51878761
answer count: 1
downvote count: 0
favorite count: 0
has title: Function from a field that works half Odoo 10
accepted answer: http://stackoverflow.com/a/51879483
upvote count: 1
tagged with: python
has body: I notice something, the message is displayed as soon as I activate the boolean in Odoo. I would like the "half_pension is on" message to appear only when I save my form. How can I do that? The save button is automatically included in Odoo cordially – My class : class ResPartner_school(models.Model): _name = 'ecole.partner.school' _order = 'id desc' half_pension = fields.Boolean(string='Restauration Scolaire', copy=False) My function : @api.onchange('half_pension') def synchroHalfPension(self): if self.half_pension: print "half_pension is on" else: print "half_pension is off" Thanks you for help ! EDIT : @api.multi def changed_half_pension(self): for record in self: if record.half_pension: print "half_pension is on" else: print "half_pension is off" @api.model def create(self, vals): record = super('ecole.partner.school', self).create(vals) record.changed_half_pension() return record @api.multi def write(self, vals): result = super('ecole.partner.school', self).write(vals) self.changed_half_pension() return result 'ecole.partner.school' is my current class
type: AnsweredQuestion
tagged with: odoo
score: 1
type: Question
has answer: http://stackoverflow.com/a/51879483

http://stackoverflow.com/q/51911160
type: Question
has title: ValueError: Mix type of y not allowed
score: -2
answer count: 1
has answer: http://stackoverflow.com/a/51912257
tagged with: scikit-learn
downvote count: 3
upvote count: 1
tagged with: python
tagged with: bayesian-networks
favorite count: 0
type: UnansweredQuestion
tagged with: machine-learning
has comment: http://stackoverflow.com/comment/90799330
has comment: http://stackoverflow.com/comment/90772435
has body: I have lottery data and I am trying to prediction with that. But I'm stuck with reshaping the data. My data is structured like that: 0,Week,Date,B1,B2,B3,B4,B5,B6 1,1140,15/08/2018,3,10,15,18,25,43 2,1139,11/08/2018,9,15,16,21,32,33 3,1139,11/08/2018,9,15,16,21,32,33 My Python code: dataset = pd.read_csv('son.csv') # fit a Naive Bayes model to the data model = GaussianNB() y = dataset.values[:,9].reshape(1143,-1143) X_train, X_test, y_train, y_test = train_test_split(dataset, y, test_size=0.2) model.fit(X_train, y_train) print(model) # make predictions expected = X_test predicted = model.predict(y_test) # summarize the fit of the model print(metrics.classification_report(expected, predicted)) print(metrics.confusion_matrix(expected, predicted)) However, I am getting this error: ValueError: Mix type of y not allowed, got types {'multiclass-multioutput', 'binary'} error. How I can fix this?

http://stackoverflow.com/q/51895244
score: 0
has comment: http://stackoverflow.com/comment/90741253
has comment: http://stackoverflow.com/comment/90741054
tagged with: python
accepted answer: http://stackoverflow.com/a/51895442
favorite count: 0
upvote count: 1
possible better answer: http://stackoverflow.com/a/51895567
downvote count: 1
has title: Optimizing Python algorithm
has answer: http://stackoverflow.com/a/51895567
type: AnsweredQuestion
tagged with: nltk
type: Question
has answer: http://stackoverflow.com/a/51895442
answer count: 2
has body: I am running my code off a 10yr old potato computer (i5 with 4GB RAM) and need to do a lot of language processing with NLTK. I cannot afford a new computer yet. I wrote a simple function (as part of a bigger program). Problem is, I do not know which is more efficient, requires less computing power and is quicker for processing overall? This snippet uses more variables: import nltk from nltk.tokenize import PunktSentenceTokenizer #Unsupervised machine learning tokenizer. #This is the custom tagger I created. To use it in future projects, simply import it from Learn_NLTK and call it in your project. def custom_tagger(training_file, target_file): tagged = [] training_text = open(training_file,"r") target_text = open(target_file,"r") custom_sent_tokenizer = PunktSentenceTokenizer(training_text.read()) #You need to train the tokenizer on sample data. tokenized = custom_sent_tokenizer.tokenize(target_text.read()) #Use the trained tokenizer to tag your target file. for i in tokenized: words = nltk.word_tokenize(i) tagging = nltk.pos_tag(words) tagged.append(tagging) training_text.close() #ALWAYS close opened files! This is why I have included the extra code to this function! target_text.close() #ALWAYS close opened files! This is why I have included the extra code to this function! return tagged Or is this more efficient? I actually prefer this: import nltk from nltk.tokenize import PunktSentenceTokenizer #Unsupervised machine learning tokenizer. #This is the custom tagger I created. To use it in future projects, simply import it from Learn_NLTK and call it in your project. def custom_tagger(training_file, target_file): tagged = [] training_text = open(training_file,"r") target_text = open(target_file,"r") #Use the trained tokenizer to tag your target file. for i in PunktSentenceTokenizer(training_text.read()).tokenize(target_text.read()): tagged.append(nltk.pos_tag(nltk.word_tokenize(i))) training_text.close() #ALWAYS close opened files! This is why I have included the ex…
tagged with: optimization

http://stackoverflow.com/a/51945965
has comment: http://stackoverflow.com/comment/90876859
score: 21
has comment: http://stackoverflow.com/comment/127493390
answers question: http://stackoverflow.com/q/51945601
upvote count: 21
has body: Cryptography is an actively developed library that provides cryptographic recipes and primitives. It supports Python 2.6-2.7, Python 3.3+ and PyPy. Installation $ pip install cryptography Example code using high level symmetric encryption recipe: from cryptography.fernet import Fernet key = Fernet.generate_key() cipher_suite = Fernet(key) cipher_text = cipher_suite.encrypt(b"A really secret message. Not for prying eyes.") plain_text = cipher_suite.decrypt(cipher_text)
has comment: http://stackoverflow.com/comment/113167998
has comment: http://stackoverflow.com/comment/90893263
downvote count: 0
has comment: http://stackoverflow.com/comment/90843173
has comment: http://stackoverflow.com/comment/90844347
type: Answer

http://stackoverflow.com/comment/90567187
comment on: http://stackoverflow.com/q/51805571
has text: In other words, your implementation is sort of halfway between push-down and push-up, and not doing either one of them right. I can't really explain how to fix it without completely rewriting it—and if you want that, you can just find any of the million example implementations online and copy that.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/90844256
comment on: http://stackoverflow.com/a/51944850
has text: Thank you for your answer. But I still have some doubts. I need the X_train, y_train, X_test, y_test sets to perform the code below: y_train_pred = clf_random.predict(X_train) train_accuracy = np.mean(y_train_pred.ravel() == y_train.ravel())*100 train_accuracy_list.append(train_accuracy) y_test_pred = clf_random.predict(X_test) test_accuracy = np.mean(y_test_pred.ravel() == y_test.ravel())*100 I understood that everything is done in the RandomizedSearchCV. But I need to predict the accuracy on test data set and on train dataset.
type: AnswerComment
score: 0
type: Comment

deserialization
type: Tag
tags question: http://stackoverflow.com/q/51922243
tag name: deserialization

http://stackoverflow.com/comment/90846372
type: Comment
comment on: http://stackoverflow.com/q/51948209
type: QuestionComment
has text: Try https://regex101.com/r/ziAOMw/3
score: 1

http://stackoverflow.com/q/51845732
has title: Apply a function to multiple dataframes, return multiple DF's as output
favorite count: 0
has body: I'm relatively new to python, but have been working on a pet project looking at housing markets. Effectively I have a series of files that I've read in and stored as variables with the raw format as follows: ** cityrentalprice1BR.columns Index([u'RegionName', u'State', u'Metro', u'CountyName', u'SizeRank', u'2010-02', u'2010-03', u'2010-04', u'2010-05', u'2010-06', ... u'2017-09', u'2017-10', u'2017-11', u'2017-12', u'2018-01', u'2018-02', u'2018-03', u'2018-04', u'2018-05', u'2018-06'], dtype='object', length=106)** The "wide" formatting is not particularly helpful for my exercise so I've used the melt function to have a better timeseries by city and the results are great on single dataframe: cityrentalprice1BR_melt = pd.melt(cityrentalprice1BR, id_vars=['RegionName', 'State', 'Metro', 'CountyName', 'SizeRank'], value_vars = dates, value_name = 'Value', var_name =['Date']) cityrentalprice1BR_melt['Date'] = pd.to_datetime(cityrentalprice1BR_melt['Date'], format='%Y-%m') My problem arises in that I have multiple files to import with the same formatting and I'd prefer to not manually melt each dataframe. One big caveat is I'd prefer to have the results pushed into new unique dataframes (i.e. in the example above cityrentalprice1BR > cityrentalprice1BR_melt). I've been working on this for a while and have created a list of dataframes and can apply the melt function to the entire list as follows, however it is missing my key goal of retaining separate dataframes (or column sets per dataframe if a merge function is more appropriate): Rental = [cityrentalprice1BR, cityrentalprice2BR, cityrentalprice3BR, cityrentalprice4BR, cityrentalprice5BR, cityrentalpriceCondo, cityrentalpriceDupTri] for size in Rental: transformrent = pd.melt(size, id_vars=['RegionName', 'State', 'Metro', 'CountyName', 'SizeRank'], value_vars = dates, value_name = 'Value', var_name =['Date']) Any guidance would be much appreciated.
tagged with: python
score: 2
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/51848712
accepted answer: http://stackoverflow.com/a/51848712
type: Question
upvote count: 2
tagged with: function
tagged with: dataframe
tagged with: pandas
answer count: 1

http://stackoverflow.com/comment/90598542
score: 0
type: Comment
type: QuestionComment
has text: How many different files are there ? Do you have the name of the files ('a.txt' ... etc) stored somewhere ?
comment on: http://stackoverflow.com/q/51819714

http://stackoverflow.com/comment/90819765
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51883299
type: Comment
has text: In general, it is difficult to know why particular weights take on particular values. The optimization could find many other weight and bias settings which would reduce the error to 0. The random initialization will affect which minimum is found. For your simple problem, `x` needs to be a slightly larger than 0 to get the target of 0.6. Since `w1` and `b` are both positive, `w2` compensates by being negative.

http://stackoverflow.com/q/51932125
has answer: http://stackoverflow.com/a/51932449
has comment: http://stackoverflow.com/comment/90814280
type: Question
has comment: http://stackoverflow.com/comment/90814430
has comment: http://stackoverflow.com/comment/90814292
has comment: http://stackoverflow.com/comment/90814444
score: 0
has comment: http://stackoverflow.com/comment/90814340
answer count: 2
has title: Receiving in one line a different number of return values under different conditions
type: UnansweredQuestion
tagged with: python
has body: Suppose I have a function that returns a different number of outputs under different conditions; for example def _fn(cond): .... if cond is 'A': return x, y else: return y And a way to get the outputs of _fn is as follows: if cond is 'A': x_out, y_out = _fn(cond) else: y_out = _fn(cond) My question is can I reduce the right above four lines into a single line?
has answer: http://stackoverflow.com/a/51932281

http://stackoverflow.com/q/51874486
has comment: http://stackoverflow.com/comment/98910632
accepted answer: http://stackoverflow.com/a/63455566
tagged with: intellisense
has answer: http://stackoverflow.com/a/76096817
type: Question
has answer: http://stackoverflow.com/a/62369278
tagged with: visual-studio-code
has comment: http://stackoverflow.com/comment/118433209
has comment: http://stackoverflow.com/comment/112831894
tagged with: code-completion
has answer: http://stackoverflow.com/a/73657497
has answer: http://stackoverflow.com/a/56140409
has answer: http://stackoverflow.com/a/77279719
downvote count: 0
has answer: http://stackoverflow.com/a/75931456
has comment: http://stackoverflow.com/comment/97931114
score: 193
answer count: 24
has answer: http://stackoverflow.com/a/79140653
possible better answer: http://stackoverflow.com/a/56140409
has answer: http://stackoverflow.com/a/77167671
has answer: http://stackoverflow.com/a/57838491
favorite count: 0
has answer: http://stackoverflow.com/a/68546787
has answer: http://stackoverflow.com/a/64302423
has answer: http://stackoverflow.com/a/67385104
upvote count: 193
has answer: http://stackoverflow.com/a/63455566
has answer: http://stackoverflow.com/a/74573543
has answer: http://stackoverflow.com/a/69509149
tagged with: python
has comment: http://stackoverflow.com/comment/97878122
has answer: http://stackoverflow.com/a/51875064
has answer: http://stackoverflow.com/a/74357705
has comment: http://stackoverflow.com/comment/112805948
has answer: http://stackoverflow.com/a/66429741
has comment: http://stackoverflow.com/comment/111479522
has body: Edit: Pylance seems to be much better at this and has so far resolved all problems with the previous Python language server from Microsoft. I'm using VS Code and it's wonderful is all areas but code completion, where it is usually just too slow to be of any use. This example shows how long intellisense took to to find a local variable, and this is only after it was prompted to do so after I hit ctrl+enter. I've not been able to find a solution to this as of yet, so I am here to ask if anyone else has had a similar issue and ask how they have overcome it.
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/66327040
has comment: http://stackoverflow.com/comment/98096678
has comment: http://stackoverflow.com/comment/123443398
has title: Visual Studio Code Intellisense is very slow - Is there anything I can do?
has answer: http://stackoverflow.com/a/73979105
has comment: http://stackoverflow.com/comment/112813214
has answer: http://stackoverflow.com/a/61410856
has answer: http://stackoverflow.com/a/76086731
has answer: http://stackoverflow.com/a/74406030
has comment: http://stackoverflow.com/comment/112815934
has answer: http://stackoverflow.com/a/69834732

http://stackoverflow.com/comment/90824074
has text: Do you have a dictionary of arrays? What are you actually trying to do. Show your hypothetical plotting code.
comment on: http://stackoverflow.com/q/51936781
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/90676569
comment on: http://stackoverflow.com/a/51860885
has text: Thanks @Wen this works well for the example given. How would this need to change to accept a list of lists with varying lengths? E.g list = [ [0,1,2], [3,4], [5], [6,7] ]
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/90594715
score: 0
has text: just usual calling of script using "python3 cli.py"
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51820398

http://stackoverflow.com/a/52071620
has comment: http://stackoverflow.com/comment/91330385
type: Answer
has comment: http://stackoverflow.com/comment/91217397
has comment: http://stackoverflow.com/comment/91219302
has comment: http://stackoverflow.com/comment/91222460
score: 10
answers question: http://stackoverflow.com/q/51942913
has comment: http://stackoverflow.com/comment/91219592
has body: H2O is running in a separate process to R (whether H2O is on the local server or in a distant data centre). The H2O data and the H2O models are kept in that H2O process, and cannot be seen by R. What dH &lt;- as.h2o(dR) does is copy an R data frame, dR, into H2O's memory space. The dH is then an R variable that describes the H2O data frame. I.e. it is a pointer, or a handle; it is not the data itself. What dR &lt;- as.data.frame(dH) does is copy the data from the H2O process's memory, into the R process's memory. (as.vector(dH) does the same for when dH describes a single column) So, the simplest way to modify your mape_calc(), assuming that sub_df is an R data frame, is to change the first two lines as follows: mape_calc &lt;- function(sub_df) { p &lt;- h2o.predict(rforest.model, as.h2o(sub_df)) pred &lt;- as.vector(p) actual &lt;- sub_df$Ptot mape &lt;- 100 * mean(abs((actual - pred)/actual)) new_df &lt;- data.frame(date = sub_df$date[[1]], mape = mape) return(new_df) } I.e. upload sub_df to H2O, and give that to h2o.predict(). Then use as.vector() to download the prediction that was made. This was relative to your original code. So keep the original version of this: # LIST OF ONE-ROW DATAFRAMES df_list &lt;- by(test_data, test_data$date, map_calc) I.e. don't use by() directly on test_h2o. UPDATE based on edited question: I made two changes to your example code. First, I removed the date column from sub_df. That was what was causing the error message. The second change was just to simplify the return type; not important, but you ended up with the date column duplicated, before. mape_calc &lt;- function(sub_df) { sub_df_minus_date &lt;- subset(sub_df, select=-c(date)) p &lt;- h2o.predict(my_gbm, as.h2o(sub_df_minus_date)) pred &lt;- as.vector(p) actual &lt;- sub_df$medv mape &lt;- 100 * mean(abs((actual - pred)/actual)) data.frame(mape = mape) } ASIDE: h2o.predict() is most efficient when working on a batch of data to make predictions on. Putting h2o.predict() insi…
accepted answer of: http://stackoverflow.com/q/51942913
has comment: http://stackoverflow.com/comment/91126270
has comment: http://stackoverflow.com/comment/91164140
has comment: http://stackoverflow.com/comment/91219356
upvote count: 10
has comment: http://stackoverflow.com/comment/91217407
has comment: http://stackoverflow.com/comment/91226101
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91135431
has comment: http://stackoverflow.com/comment/91126468
has comment: http://stackoverflow.com/comment/91851519
has comment: http://stackoverflow.com/comment/91213256
has comment: http://stackoverflow.com/comment/91230640

http://stackoverflow.com/comment/90883558
type: Comment
comment on: http://stackoverflow.com/a/51818451
score: 0
type: AnswerComment
has text: I know you were the first to answer, and I quite liked your answer, but simply put, the other answers just have more detail. Sorry :(

http://stackoverflow.com/a/51949812
has body: If I understand your question correctly, you are dealing with a non-stationary time series. This is a common problem in time series analysis, but there are ways to deal with non-stationary data or make it stationary (such as detrending). These operations are not trivial, and there are various approaches, mostly copied from more stats-oriented languages such as R (eg: https://www.statsmodels.org/dev/generated/statsmodels.tsa.tsatools.detrend.html). An LSTM can also deal with non-stationary data. See this answer for more helpful discussion.
answers question: http://stackoverflow.com/q/51949338
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/90856465

http://stackoverflow.com/q/51929554
score: 0
has comment: http://stackoverflow.com/comment/90809194
has body: im currently trying to login to my account at ds-exchange (https://app.ds-exchange.co.uk/#/login/signin) via Python (Dont ask why, im just testing what i can do with Paython currently since im learning it :P ) I've checked a bit how their login works with Fiddler: They do an empty post @ https://api.ds-exchange.co.uk/v1/get/ip/ They do post device_id, app_type, platform, app_version &amp; identifier which they've got from step 1. @ https://api.ds-exchange.co.uk/v1/device/register/ Now they post email, password(in sha256) and access_token @ https://api.ds-exchange.co.uk/v1/login/ I've rewrite it simply in Python: import re import json import requests from requests.packages.urllib3.exceptions import InsecureRequestWarning #disable ssl warning requests.packages.urllib3.disable_warnings(InsecureRequestWarning) payload = {} content = requests.post('https://api.ds-exchange.co.uk/v1/get/ip/', verify=False, params=payload) print(content.text) payload = {'device_id': '123123123123123', 'app_type': 'admin', 'platform': 'web', 'app_version': '2.0.1', 'identifier': '127.0.0.1'} content = requests.post('https://api.ds-exchange.co.uk/v1/device/register/', verify=False, params=payload) print(content.text) answer = json.loads(content.text) print(answer['data']['access_token']) accesstoken = answer['data']['access_token'] payload = {'email': 'dolemites@test.de', 'password': 'dolemites', 'access_token': accesstoken} content = requests.post('https://api.ds-exchange.co.uk/v1/login/', verify=False, params=payload) print(content.text) That are the answers i got from python script: Step 1: {"ts":1534762909,"success":true,"error":false,"data":{"ip_address":"::1"}} Step 2: {"ts":1534762911,"success":true,"error":false,"data":{"access_token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.[binary].aYAcdRmYdRPxYtylh17gYJKjXYKiRhWlWRg-JnmFYBw"}} Step 3: {"ts":1534762912,"success":false,"error":true,"error_msg":"Access Denied. Token not found","logout":true} The problem is that im getting a completly dif…
has comment: http://stackoverflow.com/comment/90809132
tagged with: python
tagged with: web
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51929854
tagged with: authentication
type: Question
has title: Login with Python into a Website
answer count: 1
has comment: http://stackoverflow.com/comment/90809261

http://stackoverflow.com/q/51917358
has body: I'm want to solve programming exercise no.3 in problem solving with algorithms and data structures using python ch.2. The exercise wants me to devise an experiment that compares the performance of the del operator on lists and dictionaries. My code is import timeit import random for i in range(10000,1000001,20000): t = timeit.Timer("del x[random.randrange(%d)]" % i, "from __main__ import random, x") x = list(range(i)) lst_time = t.timeit(number=1000) x = {j:None for j in range(i)} d_time = t.timeit(number=1000) print("%d,%10.3f,%10.3f" % (i, lst_time, d_time)) But it fails with an error message IndexError: list assignment index out of range. How can i fix the code to solve exercise no. 3?
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90784940
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/51917428
type: AnsweredQuestion
has title: How can I devise an experiment that compares the performance of the del operator on lists and dictionaries?
has comment: http://stackoverflow.com/comment/90784562
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/90784604
accepted answer: http://stackoverflow.com/a/51917428

http://stackoverflow.com/comment/90659079
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51852983
has text: Ok. This is just a computer security challenge competition held by a high school that is opened to public through online.
score: 0

http://stackoverflow.com/comment/90576838
comment on: http://stackoverflow.com/a/51810701
type: Comment
has text: You can try e.g. for the [cde] columns (i.e. [2:5] in slice notation) this: `df['first_nonzero_cde']=df.keys()[2+argmax((df.values!=0)[2:5],axis=1)]` . (For some reason, slicing `df.values` directly does not work for me.)
type: AnswerComment
score: 0

http://stackoverflow.com/comment/90653290
score: 0
type: AnswerComment
type: Comment
has text: You should delete /usr/bin/python first then re-create the symlink
comment on: http://stackoverflow.com/a/51834424

http://stackoverflow.com/a/51860610
has comment: http://stackoverflow.com/comment/90719660
has body: You can send a COPY command naming a file using execute(), and pass the filename using placeholders, but since it requires database superuser privileges, because it can read/write all files the server has access to, it's usually better to avoid it. I suppose the special methods exist for the COPY commands using STDIN and STDOUT for receiving and sending data, since execute() as specified in the DBAPI 2 spec does not support such. Also copy_expert() does support sending a custom COPY command, while using STDIN and STDOUT. It's handy for dealing with CSV, for example.
has comment: http://stackoverflow.com/comment/90717232
type: Answer
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/90716477
has comment: http://stackoverflow.com/comment/90714918
upvote count: 2
accepted answer of: http://stackoverflow.com/q/51858564
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90718849
answers question: http://stackoverflow.com/q/51858564

http://stackoverflow.com/comment/90998477
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51935601
has text: Just `mystery = funcy.memoize(_mystery)`
score: 0

http://stackoverflow.com/q/51843837
favorite count: 0
tagged with: python
tagged with: kernel
has comment: http://stackoverflow.com/comment/90641442
answer count: 0
downvote count: 0
type: UnansweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/90641271
has comment: http://stackoverflow.com/comment/90641741
type: Question
has body: I'm trying to understand user CPU time and system CPU time but still confused about the difference. I understood that system CPU time is time spent by kernel but can not find when CPU is used by kernel in my code. In [1]: import numpy as np ...: a = np.zeros((3000, 4000), dtype=np.int64) ...: b = np.zeros((3000, 4000), dtype=np.int64) ...: In [2]: %%time ...: b[:] = a[:] ...: CPU times: user 12 ms, sys: 24 ms, total: 36 ms Wall time: 38.5 ms Why copying value from array a to b does the CPU usage need to be by kernel? It is just a simple loop iterating each element of a and b which can be done in user mode, isn't it?
has title: Why CPU is used by kernel in simple for loop
upvote count: 1

http://stackoverflow.com/a/51811815
score: 1
has comment: http://stackoverflow.com/comment/90578774
has body: With a boolean vector of zero/non-zero, you can calculate the distance from a given index to the non-zero values using subtract(). That will give you the "hops", and idxmin() can locate the actual value. def get_closest(df, target): df["not_zero"] = df.ne(0) not_zero = pd.Series(df.index[df.not_zero]) dist = not_zero.subtract(target).abs() minidx = not_zero.loc[dist.idxmin()] steps = dist.min() if minidx &lt; target else -dist.min() print("Closest steps to non-zero:", steps) print("Closest non-zero value:", df.A[minidx]) get_closest(df, 5) # Closest steps to non-zero: 3 # Closest non-zero value: 15 get_closest(df, 7) # Closest steps to non-zero: -2 # Closest non-zero value: 5
downvote count: 0
answers question: http://stackoverflow.com/q/51811710
type: Answer
upvote count: 1

http://stackoverflow.com/q/51945803
has comment: http://stackoverflow.com/comment/90841030
has comment: http://stackoverflow.com/comment/90844571
has title: Python line chart from complicated txt data
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90842923
has comment: http://stackoverflow.com/comment/90844811
tagged with: python
has comment: http://stackoverflow.com/comment/90842686
has comment: http://stackoverflow.com/comment/90841321
tagged with: charts
has answer: http://stackoverflow.com/a/51946076
has comment: http://stackoverflow.com/comment/90843331
has comment: http://stackoverflow.com/comment/90844533
has body: I have a text file in the form: Time,secs AreaA,cm˛ AreaA,A˛ AreaB,cm˛ AreaB,A˛ PiA,mN/m S.Pot,mV Depth,mm T.A.,cm˛ 1.103000 342.385783 44.343862 -0.278713 NaN 0.060977 -2.867612 5.000000 2.233000 342.357189 44.340159 -0.278713 NaN 0.069688 -5.336944 5.000000 3.356000 342.128434 44.310532 -0.202736 NaN 0.087109 -8.045245 5.000000 4.488000 341.999759 44.293867 -0.202736 NaN 0.093643 0.318624 5.000000 I would like to create a linear graph for x data - AreA,cm and y data - PiA,mN/m. Unfortunately I am not able to skip the first line and the data will not load correctly. I'm trying this one: import numpy as np import matplotlib.pyplot as plt with open('v10.txt') as f: data = np.loadtxt(f, delimiter="\t", dtype='float',skiprows=0,) x = data[:, 1] y = data[:, 5] fig = plt.figure() fig.suptitle('') plt.xlabel('') plt.ylabel('') plt.plot(-x, -y, c='r', label='') leg = plt.legend() plt.show() Anyone can know how to do it? Thank you in advance!
type: Question
has answer: http://stackoverflow.com/a/51945966
has comment: http://stackoverflow.com/comment/90841341
answer count: 2
has comment: http://stackoverflow.com/comment/90844214
has comment: http://stackoverflow.com/comment/90843560
has comment: http://stackoverflow.com/comment/90842928
score: 0
has comment: http://stackoverflow.com/comment/90845407
has comment: http://stackoverflow.com/comment/90843113

http://stackoverflow.com/q/51854974
has title: Is there anyway to use the index in python numpy vectorize functions?
has body: The below example illustrates my problem: &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; l = lambda i, value: i*v &gt;&gt;&gt; y = np.vectorize(l) &gt;&gt;&gt; y(range(10)) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/local/lib/python3.6/site-packages/numpy/lib/function_base.py", line 2755, in __call__ return self._vectorize_call(func=func, args=vargs) File "/usr/local/lib/python3.6/site-packages/numpy/lib/function_base.py", line 2825, in _vectorize_call ufunc, otypes = self._get_ufunc_and_otypes(func=func, args=args) File "/usr/local/lib/python3.6/site-packages/numpy/lib/function_base.py", line 2785, in _get_ufunc_and_otypes outputs = func(*inputs) TypeError: &lt;lambda&gt;() missing 1 required positional argument: 'value' &gt;&gt;&gt; y(enumerate(range(10))) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/local/lib/python3.6/site-packages/numpy/lib/function_base.py", line 2755, in __call__ return self._vectorize_call(func=func, args=vargs) File "/usr/local/lib/python3.6/site-packages/numpy/lib/function_base.py", line 2825, in _vectorize_call ufunc, otypes = self._get_ufunc_and_otypes(func=func, args=args) File "/usr/local/lib/python3.6/site-packages/numpy/lib/function_base.py", line 2785, in _get_ufunc_and_otypes outputs = func(*inputs) TypeError: &lt;lambda&gt;() missing 1 required positional argument: 'value' Is there anything like fromiter that supports this, but is faster with large inputs, like vectorize?
tagged with: iterable
answer count: 2
has answer: http://stackoverflow.com/a/51855074
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/90662429
has comment: http://stackoverflow.com/comment/90682501
has comment: http://stackoverflow.com/comment/90667499
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90797175
tagged with: python
has answer: http://stackoverflow.com/a/51856295
score: 1
has comment: http://stackoverflow.com/comment/90797163
type: Question
upvote count: 2
tagged with: numpy

http://stackoverflow.com/q/51869115
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/html
tagged with: python
tagged with: css
favorite count: 0
has title: Bokeh plot update in notebook but not in static HTML
type: Question
upvote count: 2
tagged with: django
has body: This is the first time to ask a question here . I'm totally new to HTML , CSS , JavaScipt , Django , Python and Bokeh . I'm poor in English . And I'll appreciate for your help . I'm meeting a problem when I want to realize a simple function . There is 2 plots here . When I click the circle of the first plot , the circles not associated with in the second spot will be hidden . It's work in notebook . But when I add it into an HTML page . The second plot won't Change . I use Django+python to realize this function . And I use HTML component tag to add plots into an web page. I'm sorry that I'm not allow to put a picture here, but there are links. Here is the gif when it works in notebook . work in notebook And this is the gif when it's not work in static HTML . not work in HTML Here is the HTML code . test And here is the python code . from PIL.ImageQt import rgb from bokeh.embed import components from bokeh.layouts import column, widgetbox, layout from bokeh.models import Range1d, Title, Label, PrintfTickFormatter, NumeralTickFormatter, Axis, ColumnDataSource, \ ColorBar, LinearAxis, TapTool, CDSView, BooleanFilter, CustomJS, Slider, layouts, Select from bokeh.plotting import figure, Figure from bokeh.models import HoverTool from bokeh.layouts import column # Create your views here. from bokeh.resources import CDN from bokeh.transform import linear_cmap from django.shortcuts import render def test(request): data1 = {'time': [1, 2, 3, 4, 5, 6, 7], 'projectname': ["project1", "project2", "project3", "project4", "project5", "project6", "project7"], 'id': ['byq-1', 'byq-2', 'byq-3', 'byq-4', 'byq-5', 'byq-6', 'byq-7'], 'missingnumber0': [1, 2, 30, 22, 23, 5, 9], 'missingnumber1': [3, 4, 30, 12, 20, 1, 20], 'missingnumber': [4, 6, 60, 34, 43, 6, 29], 'holi': [0.10, -0.20, 0.30, -0.11, -0.32, 0.44, 0.05], 'lilo': [0.23, -0.21, 0.02, 0.03, 0.66, 0.31, 0.22], 'holo': [0.33, -0.41, 0.32, -0.08, 0.34, 0.7…
tagged with: bokeh
score: 2
answer count: 0
downvote count: 0

http://stackoverflow.com/a/51811102
has comment: http://stackoverflow.com/comment/90577250
accepted answer of: http://stackoverflow.com/q/51810888
answers question: http://stackoverflow.com/q/51810888
upvote count: 2
has comment: http://stackoverflow.com/comment/90577309
has comment: http://stackoverflow.com/comment/90577205
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90577425
type: Answer
has body: UPDATE (per comments) It seems like the confusion here is stemming from the fact that the call to plt.plot() takes positional x/y arguments instead of keyword arguments. In other words, the appropriate signature is: plt.plot(x, y) Or, alternately: plt.plot('x_label', 'y_label', data=obj) But not: plt.plot(x=x, y=y) There's a separate discussion of why this quirk of Pyplot exists here, also see ImportanceOfBeingErnest's comments below. Original This isn't really an answer, more of a demonstration that Pyplot doesn't have an issue with Pandas datetime data. I've added an extra row to df to make the plot clearer: import pandas as pd import matplotlib.pyplot as plt df = pd.DataFrame([[1433120400, "2015-06-01T09:00:00+08:00"], [1433130400, "2015-07-01T09:00:00+08:00"]], columns=["epoch", "strtime"]) df["usable_time"] = pd.to_datetime(df["strtime"]) df.dtypes epoch int64 strtime object usable_time datetime64[ns] dtype: object plt.plot(df.usable_time, df.epoch) pd.__version__ # '0.23.3' matplotlib.__version__ # '2.2.2'
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/90577300
has comment: http://stackoverflow.com/comment/90577602

http://stackoverflow.com/comment/90669054
type: AnswerComment
type: Comment
score: 0
has text: Thank you for your help! I've posted the contents of one of the files I'm trying to parse. If you have a chance to look at it I would greatly appreciate your help!
comment on: http://stackoverflow.com/a/51849777

http://stackoverflow.com/comment/90865448
score: 0
type: AnswerComment
type: Comment
has text: Also from what I can see PYTHONPATH is only used when running stuff from the terminal? I am indeed trying to run it locally, but always within spyder
comment on: http://stackoverflow.com/a/51954089

http://stackoverflow.com/a/51943831
score: 1
has comment: http://stackoverflow.com/comment/90837682
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51943622
type: Answer
has body: Quick Solution: import io from nltk.corpus import stopwords from nltk.tokenize import word_tokenize import glob import os import codecs stop_words = set(stopwords.words('english')) for afile in glob.glob("*.txt"): file1 = codecs.open(afile, encoding='utf-8') line = file1.read() words = word_tokenize(line) words_without_stop_words = [word for word in words if word not in stop_words] new_words = " ".join(words_without_stop_words).strip() subfolder = getSubfolder(afile) filename = getFilename(afile) appendFile = open('{}/{}.txt'.format(subfolder,filename),'w', encoding='utf-8') appendFile.write(new_words) appendFile.close() I've never worked with glob or codecs, i believe your problem lies in your last 3 lines of code. You use a constant string ('subfolder/file1.txt') as a final file target - that's why your results land in one file. I replaced the target path with two variables. These variables i get from the functions "getSubfolder()" and "getFilename()". You have to implement these functions in order to get the filename you need. If i understand your goal correct, your filename stays the same, just in a different folder. Then you can use this line: appendFile = open('{}/{}.txt'.format('mysubfolder',afile),'w', encoding='utf-8') Solution while learning: I would recommend you to take a look at https://github.com/inducer/pudb and follow the execution of every step of your loop. This way you will see and learn what python does, what variable has what value at a certain point in time, and so on.
upvote count: 1
has comment: http://stackoverflow.com/comment/90837749
answers question: http://stackoverflow.com/q/51943622

http://stackoverflow.com/comment/134918448
type: QuestionComment
has text: Hi. Does anyone know if this is available in Google Colab now?
comment on: http://stackoverflow.com/q/51940596
score: 0
type: Comment

http://stackoverflow.com/comment/90582417
has text: I prefer Jinja2. It provides more flexibility and speed. You can read about it in the [project's main page](http://jinja.pocoo.org).
comment on: http://stackoverflow.com/a/51813619
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/90767088
has text: Possible duplicate: https://stackoverflow.com/questions/492519/timeout-on-a-function-call
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51908424
score: 0

http://stackoverflow.com/a/51936514
score: 0
upvote count: 1
downvote count: 1
type: Answer
has body: You are adding references to the same list over and over. You see the result of the last shuffle mirrored in all instances.
answers question: http://stackoverflow.com/q/51936434

http://stackoverflow.com/q/51880258
tagged with: file
upvote count: 0
type: UnansweredQuestion
favorite count: 0
has comment: http://stackoverflow.com/comment/90712551
has title: I have some data in a text file, how should I parse the document that I will only get the value of 'isakm' and 'esp'?
type: Question
has answer: http://stackoverflow.com/a/51880326
has body: eth frames:27 bytes:5286 ip frames:27 bytes:5286 udp frames:11 bytes:2054 isakm frames:11 bytes:2054 esp frames:16 bytes:3232 I am writing a python script for it: data = open('data.txt','r') print(data.read())
score: -1
tagged with: python-3.x
answer count: 2
tagged with: python
downvote count: 1
has answer: http://stackoverflow.com/a/51880626
has comment: http://stackoverflow.com/comment/90712400

http://stackoverflow.com/comment/90704256
type: QuestionComment
has text: @roganjosh I have updated the codes that I had worked, Now question is fully complete, I appreciate your help.
comment on: http://stackoverflow.com/q/51875932
score: 0
type: Comment

http://stackoverflow.com/q/51827810
has title: Saving the plot using the dataframe plot function
duplicate of: http://stackoverflow.com/q/32219350
tagged with: plot
type: Question
duplicate of: http://stackoverflow.com/q/19555525
answer count: 2
tagged with: pandas
has answer: http://stackoverflow.com/a/51827871
has answer: http://stackoverflow.com/a/51827875
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/32219350
score: 0
has body: I'm using the data frame plot function to create the following plot: Using the following code: data.groupby(['age']).agg(np.size)['listener_id'].plot(kind='bar') How can I save this plot?

http://stackoverflow.com/q/51924803
tagged with: python
has title: Python: 'Deep create' keys in a dictionary?
tagged with: dictionary
score: 0
has comment: http://stackoverflow.com/comment/90824149
answer count: 0
type: UnansweredQuestion
has body: Being a Perl convert I'm wondering, if it is possible in Python to create more then one level of keys in a dictionary. In Perl, if I have an empty hash, I can e.g. write this: my %h; # emtpy hash $h{level1}{level2}{level3} = "something"; Do I really have to do the same thing in Python like this: h = {} # empty dictionary h['level1'] = {} h['level1']['level2'] = {} h['level1']['level2']['level3'] = "something" or is there a shortcut?
has comment: http://stackoverflow.com/comment/90799030
linked to: http://stackoverflow.com/q/651794
type: Question
duplicate of: http://stackoverflow.com/q/651794
has comment: http://stackoverflow.com/comment/90799386

http://stackoverflow.com/comment/90726494
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51887639
type: Comment
has text: do this first `curl https://bootstrap.pypa.io/get-pip.py | sudo python` then try to install again

http://stackoverflow.com/comment/90587087
score: 0
type: Comment
type: QuestionComment
has text: Make a sample input data that illustrates your problem when passed through your code. You don't need 10Gb data to show your point, a 20-line pared-down JSON should be enough. Also show what your desired output JSON would be. This will give you many more willing answerers.
comment on: http://stackoverflow.com/q/51816284

http://stackoverflow.com/comment/90837230
score: 1
type: AnswerComment
type: Comment
has text: Great! This worked. Class based views are new to me. Previous implementation of this app worked with views.Login, but i updated the Django version and seems like that was deprecated.
comment on: http://stackoverflow.com/a/51943715

http://stackoverflow.com/q/51908229
has answer: http://stackoverflow.com/a/51908554
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/51908764
has title: Selenium can't locate the element, a search button using xpath
possible better answer: http://stackoverflow.com/a/51908554
favorite count: 0
has body: I can't find a solution how this element cannot be found by using a selenium xpath. Other button on other websites always working just fine. Usually what I would normally do is, just open up a page and inspect the element and I would right click it and copy the xpath. Done. But this website, www.gsc.com.my (a malaysian cinema booking site). Seems not able to find the button. Is it protected by another security layer? Lets see the code below, from selenium import webdriver chromedriver_path = './chromedriver.exe' driver = webdriver.Chrome(chromedriver_path) driver.get('https://www.gsc.com.my') driver.find_element_by_xpath("""//*[@id="btnNext"]""").click() The error Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="btnNext"]"}
tagged with: python
tagged with: xpath
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51908436
tagged with: selenium
upvote count: 1
downvote count: 1
accepted answer: http://stackoverflow.com/a/51908436
type: Question

http://stackoverflow.com/q/51883796
has answer: http://stackoverflow.com/a/51883939
score: 0
has comment: http://stackoverflow.com/comment/90719245
tagged with: concatenation
tagged with: pandas
answer count: 1
type: UnansweredQuestion
tagged with: python
has title: What is the best way to do a pd.concat horizontally in pandas, matching on a column?
type: Question
has body: Example: Df1: ID, Variable_1, Variable_2 Df2: ID, Variable_1a, Variable_2a I want the resulting Df to be matched on ID values (which are identical), and have the following format: Df3: ID, Variable_1, Variable_2, Variable_1a, Variable_2a I tried: Df3 = pd.concat([Df1, Df2], axis=1, join='outer'), but it does not produce the desired result.

http://stackoverflow.com/comment/90725319
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51886956
has text: I don't think this is what he's after. Although it's hard to be sure, with an ambiguous question.
score: 1

http://stackoverflow.com/comment/90674906
score: 1
has text: @JasonR Did you read the note next to the documentation? It explains the 'weird' behaviour.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51861272

http://stackoverflow.com/comment/90655692
comment on: http://stackoverflow.com/q/51850525
has text: Anyway, your output doesn't look out of order. The reason it's messed up is that the newlines are showing up in the `recv` log as `\n` instead of as newlines (which is to be expected; it's a reasonable way to log `bytes`). But that doesn't change the fact that `read_all` isn't reading all that data and giving it to you to print out…
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51868631
accepted answer: http://stackoverflow.com/a/51868845
tagged with: tensorflow
type: Question
answer count: 1
tagged with: keras
score: 0
has title: Unable to create session in jupyter notebook for keras kfold validation code
has answer: http://stackoverflow.com/a/51868845
tagged with: jupyter-notebook
tagged with: python
has body: I wrote a code in jupyter notebook using keras/tensorflow. The code worked well when I ran it on my laptop that runs tensorflow on cpu but when I run the same code on my home computer that runs tensorflow on gpu I receive the message "failed to create session." I would like to keep using gpu if possible. I will include my code and the error below along with the output from the terminal. Code (I excluded other parts of the code that loads/ manipulate data): from sklearn.model_selection import StratifiedKFold l2_reg = 0.4 momentum = 0.99 seed = 5 def create_model_val(x_train, y_train, x_val, y_val, layers=[20, 20, 4], kernel_init ='he_uniform', bias_init ='he_uniform', batch_norm=True, dropout=True): model = Sequential() # layer 1 model.add(Dense(layers[0], input_dim=x_train.shape[1], W_regularizer=l2(l2_reg), kernel_initializer=kernel_init, bias_initializer=bias_init)) if batch_norm == True: model.add(BatchNormalization(axis=-1, momentum=momentum, center=True)) model.add(Activation(params['activation'])) if dropout == True: model.add(Dropout(params['dropout'])) # layer 2+ for layer in range(0, len(layers)-1): model.add(Dense(layers[layer+1], W_regularizer=l2(l2_reg), kernel_initializer=kernel_init, bias_initializer=bias_init)) if batch_norm == True: model.add(BatchNormalization(axis=-1, momentum=momentum, center=True)) model.add(Activation(params['activation'])) if dropout == True: model.add(Dropout(params['dropout'])) # Last layer model.add(Dense(layers[-1], activation=params['last_activation'], kernel_initializer=kernel_init, bias_initializer=bias_init)) model.compile(loss=params['losses'], optimizer=keras.optimizers.adam(lr=params['lr']), metrics=['accuracy']) model_output = {'model':model} return model_output def train_and_evaluate_model(model, x_train, y_train, x_val, y_val): history = model.fit(x_train, y_train, validation_data=[x_val, y_val], batch_size=params['batch_size'], epochs=params['epochs'],verbose=0) return history n_folds = 10 total_acc = [] skf = St…
type: AnsweredQuestion

http://stackoverflow.com/q/51840008
type: Question
has answer: http://stackoverflow.com/a/51843153
tagged with: dataframe
tagged with: memory
has comment: http://stackoverflow.com/comment/90632974
has title: Memory Error while Merging Dataframe in Python
answer count: 1
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90633123
score: 0
has body: I am new to Python and Data Processing. I was trying to process some data just like we use Vtool in excel. I was importing data from 2 excel files and then merge them and extract another excel. I was using pd.merge. However, I am getting memory error. df1 details: dtypes: float64(10), int64(1), object(10) memory usage: 1.0 MB df2 details: dtypes: object(6) memory usage: 579.2 KB Memory is not even that large. How do I get rid of this memory error? Here is the code: dff=pd.DataFrame(list(zip(NameList)),columns=['Name']) dff = pd.merge(dff,df2, how='left',left_on='Name', right_on='Name') #From 1st data sheet dff.drop(['A','B'], axis=1, inplace=True) dff = pd.merge(dff,df1, how='left',on='Name') #From 2nd datasheet dff.drop(['E','F'], axis=1, inplace=True) dff.index=dff.index+1 display(dff) All I get is the following error: MemoryError Solved I read individual excel files in different dataframes df1,df2 and df3 and after dropping certain properties to get rid off the Memory Error I merged them. dff = df2.merge(df1, how='left',on='Name') dff.drop(['A','B'], axis=1, inplace=True) dfff = dff.merge(df3, how='right',on='Name') dff.drop(['E','F'], axis=1, inplace=True)

http://stackoverflow.com/comment/90734885
comment on: http://stackoverflow.com/a/51890445
type: Comment
has text: requests.exceptions.SSLError: HTTPSConnectionPool(host='URL', port=443): Max retries exceeded with url: /info (Caused by SSLError(SSLError(0, u'unknown error (_ssl.c:2825)'),)) Thanks Dinesh, tried with the code you provided and got above response
score: 0
type: AnswerComment

http://stackoverflow.com/comment/90836591
type: QuestionComment
type: Comment
score: 0
has text: Have you tried `lock.locked()`?
comment on: http://stackoverflow.com/q/51943435

list
tags question: http://stackoverflow.com/q/51814497
type: Tag
tags question: http://stackoverflow.com/q/51851016
tags question: http://stackoverflow.com/q/51860703
tags question: http://stackoverflow.com/q/51918197
tags question: http://stackoverflow.com/q/51808662
tags question: http://stackoverflow.com/q/51849509
tags question: http://stackoverflow.com/q/51848856
tags question: http://stackoverflow.com/q/51828044
tags question: http://stackoverflow.com/q/51909914
tags question: http://stackoverflow.com/q/51877709
tags question: http://stackoverflow.com/q/51913946
tags question: http://stackoverflow.com/q/51900773
tags question: http://stackoverflow.com/q/51901920
tags question: http://stackoverflow.com/q/51831829
tags question: http://stackoverflow.com/q/51947087
tags question: http://stackoverflow.com/q/51866010
tags question: http://stackoverflow.com/q/51922751
tags question: http://stackoverflow.com/q/51931938
tags question: http://stackoverflow.com/q/51914198
tags question: http://stackoverflow.com/q/51924113
tags question: http://stackoverflow.com/q/51880868
tags question: http://stackoverflow.com/q/51953688
tags question: http://stackoverflow.com/q/51859841
tags question: http://stackoverflow.com/q/51833952
tags question: http://stackoverflow.com/q/51848354
tags question: http://stackoverflow.com/q/51852109
tags question: http://stackoverflow.com/q/51941019
tags question: http://stackoverflow.com/q/51938213
tags question: http://stackoverflow.com/q/51918444
tags question: http://stackoverflow.com/q/51873576
tags question: http://stackoverflow.com/q/51843855
tags question: http://stackoverflow.com/q/51898035
tags question: http://stackoverflow.com/q/51955245
tags question: http://stackoverflow.com/q/51813910
tags question: http://stackoverflow.com/q/51923874
tags question: http://stackoverflow.com/q/51884992
tag name: list
tags question: http://stackoverflow.com/q/51811937
tags question: http://stackoverflow.com/q/51834855
tags question: http://stackoverflow.com/q/51942648
tags question: http://stackoverflow.com/q/51878000
tags question: http://stackoverflow.com/q/51882756
tags question: http://stackoverflow.com/q/51815087
tags question: http://stackoverflow.com/q/51809437
tags question: http://stackoverflow.com/q/51946256
tags question: http://stackoverflow.com/q/51827820
tags question: http://stackoverflow.com/q/51929478
tags question: http://stackoverflow.com/q/51886874
tags question: http://stackoverflow.com/q/51926237
tags question: http://stackoverflow.com/q/51907844
tags question: http://stackoverflow.com/q/51882215
tags question: http://stackoverflow.com/q/51806318
tags question: http://stackoverflow.com/q/51906611
tags question: http://stackoverflow.com/q/51814155
tags question: http://stackoverflow.com/q/51818670
tags question: http://stackoverflow.com/q/51885942
tags question: http://stackoverflow.com/q/51898026
tags question: http://stackoverflow.com/q/51824502
tags question: http://stackoverflow.com/q/51865939
tags question: http://stackoverflow.com/q/51844034
tags question: http://stackoverflow.com/q/51933901
tags question: http://stackoverflow.com/q/51881734
tags question: http://stackoverflow.com/q/51816688
tags question: http://stackoverflow.com/q/51862620
tags question: http://stackoverflow.com/q/51933112
tags question: http://stackoverflow.com/q/51834311
tags question: http://stackoverflow.com/q/51940291
tags question: http://stackoverflow.com/q/51893702
tags question: http://stackoverflow.com/q/51899774
tags question: http://stackoverflow.com/q/51954938
tags question: http://stackoverflow.com/q/51909982
tags question: http://stackoverflow.com/q/51926426
tags question: http://stackoverflow.com/q/51928532
tags question: http://stackoverflow.com/q/51812672
tags question: http://stackoverflow.com/q/51804790
tags question: http://stackoverflow.com/q/51920942
tags question: http://stackoverflow.com/q/51809512
tags question: http://stackoverflow.com/q/51870897
tags question: http://stackoverflow.com/q/51923891

http://stackoverflow.com/comment/90637024
has text: One problem is you have 2 functions called Takeaway and one variable. This is most likely the issue and you should never name multiple objects the same thing.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51839409

http://stackoverflow.com/comment/90856485
type: QuestionComment
comment on: http://stackoverflow.com/q/51938729
score: 0
has text: @CharlieClark there's an excel file has 1 sheet, look like the above sample master dataframe. The workflow is to open Notes_111.xlsx, add a new sheet, then based of the file's name 111, it will extract only the code=111 in the master data frame, then paste code and city in that new sheet
type: Comment

http://stackoverflow.com/q/51948298
answer count: 2
tagged with: plotly-dash
downvote count: 0
has title: Plotly dash template similar to shinydashboard
favorite count: 0
score: 7
type: UnansweredQuestion
tagged with: python
upvote count: 7
has body: For R Shiny, there are multiple very useful templates to start building your dashboard. Best known is the shinydashboard package, which makes use of a Bootstrap 3 template. I'm looking for a similar template or example as a starting point for creating a Dash Dashboard. There are lots of examples on Dash webpage, but none of these have navigation on the left pane. Question: Is there a template for a Python Dash dashboard, which has navigation on the left pane and plots/filters in the right pane of the web page?
has answer: http://stackoverflow.com/a/67526422
has answer: http://stackoverflow.com/a/56328234
type: Question

http://stackoverflow.com/q/51811575
favorite count: 0
tagged with: python-3.x
type: Question
linked to: http://stackoverflow.com/q/45440900
tagged with: python
has body: I want to implement an asynchronous token bucket algorithm which manages when to run tasks (co-routines). Simply put, this would control the number of co-routines to run in any given timespan. I've tried this leaky bucket and semaphores but neither are quite true token bucket algorithms. The goal is to exhaust the bucket (i.e. run co-routines) if there is capacity to do so, otherwise wait just long enough before running the next routine. So what I've decided to do is to override the semaphore class to control how many co-routines I run in any time period like so: TokenSemaphore.py import datetime from asyncio.locks import Semaphore import asyncio import collections from math import floor class TokenSemaphore(Semaphore): """A Semaphore implementation. A semaphore manages an internal counter which is decremented by each acquire() call and incremented by each release() call. The counter can never go below zero; when acquire() finds that it is zero, it blocks, waiting until some other thread calls release(). Semaphores also support the context management protocol. The optional argument gives the initial value for the internal counter; it defaults to 1. If the value given is less than 0, ValueError is raised. """ def __init__(self, capacity=1, rate=1, loop=None): if capacity &lt; 0: raise ValueError("Semaphore initial value must be &gt;= 0") self._capacity = capacity self._rate = rate self._time_table = collections.deque(maxlen=self._capacity) super().__init__(value=capacity, loop=loop) @property def capacity(self): return self._capacity def _wake_up_next(self): while self._waiters: waiter = self._waiters.popleft() if not waiter.done(): waiter.set_result(None) return def has_capacity(self): if len(self._time_table) &lt; self._capacity: self._time_table.append(datetime.datetime.now()) return True tf = datetime.datetime.now() delta = (tf - self._time_table[0]).total_seconds() if delta &lt; self._rate: return False else: self._time_table.append(tf) return True def locked(se…
has comment: http://stackoverflow.com/comment/90578517
tagged with: semaphore
accepted answer: http://stackoverflow.com/a/51811834
upvote count: 1
answer count: 1
tagged with: async-await
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51811834
downvote count: 0
has title: Token Bucket Algorithm based async semaphore
score: 1

http://stackoverflow.com/q/51877958
upvote count: 1
answer count: 1
tagged with: discord
favorite count: 0
has body: I've tried the code below, but I get this error. I clearly do not have the correct attribute, but I cannot find it in the documentation. AttributeError: type object 'User' has no attribute 'mutual_guilds @bot.command() async def C(ctx): for user in bot.user.friends: if user.mutual_guilds == None: print ("Friend: " + user.name+"#"+user.discriminator)
tagged with: python
type: AnsweredQuestion
has title: List friends that share no mutual guilds, discord.py rewrite
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/51878947
accepted answer: http://stackoverflow.com/a/51878947
type: Question
tagged with: discord.py

http://stackoverflow.com/a/51799321
accepted answer of: http://stackoverflow.com/q/51799228
answers question: http://stackoverflow.com/q/51799228
score: 0
type: AcceptedAnswer
has body: I'm not sure which of the dimensions your actual number of inputs is, but the first dimension needs to be the same. But for example you need to have shapes: (68, 64, 4) and (68, 4, 64) or (64, 68, 4) and (64, 4, 68) or (4, 68, 64) and (4, 64, 68) etc.. But you have number of inputs 68 and 4, these need to match. You should checkout the examples given in the here in the docs.
type: Answer

http://stackoverflow.com/q/51840167
type: UnansweredQuestion
has title: how get the average of array extracted from several netcdf file with datetime,hour as an increment in the loop
type: Question
tagged with: netcdf4
downvote count: 0
favorite count: 0
has body: I have been working on radar data file with netcdf as file format, the file is structured such that within the year directory is the month directory and within it is the day directory, and within the day directory are the files with inconsistent time increment of scan. I want to get the hourly average reflectivity and is using the glob to scan through the directories and list the files and filter it with the second elevation volume scan of the horizontal reflectivity. below is the code i'm working on: import datetime as dt import glob import netCDF4 as nc import numpy as np startdate = dt.datetime(2015, 01, 01, 00, 00, 00) enddate = dt.datetime(2015, 01, 02, 00, 00, 00) interval = dt.timedelta(hours=1) ctr = 0 sub_hour_ave = np.zeros((360,240)) while startdate != enddate: for i in range(24): denominator = 0 hourly_files = glob.glob('C:\\Users\\User\\Documents\\sample\\Subic\\'+str(startdate.year)+'\\'+\ str(startdate.month).zfill(2)+'\\'+str(startdate.day).zfill(2)+'\\SUB-'+str(startdate.year)+''\ +str(startdate.month).zfill(2)+''+str(startdate.day).zfill(2)+ "-" + str(i).zfill(2) + '*-02-ZH.nc') for files in hourly_files: sub_nc = nc.Dataset(files) sub_data = np.array(sub_nc.variables['Filtered_Intensity(Horizontal)']) sub_data[sub_data = -99900] = np.isnan() sub_data += sub_data denominator += 1 sub_hour_ave = sub_data/denominator startdate += interval
tagged with: datetime
tagged with: python
score: 2
answer count: 0
upvote count: 2

kivy-language
type: Tag
tags question: http://stackoverflow.com/q/51893858
tags question: http://stackoverflow.com/q/51946012
tags question: http://stackoverflow.com/q/51913956
tags question: http://stackoverflow.com/q/51881192
tags question: http://stackoverflow.com/q/51839412
tags question: http://stackoverflow.com/q/51825739
tags question: http://stackoverflow.com/q/51911965
tags question: http://stackoverflow.com/q/51909537
tags question: http://stackoverflow.com/q/51909407
tags question: http://stackoverflow.com/q/51841278
tags question: http://stackoverflow.com/q/51861245
tags question: http://stackoverflow.com/q/51820515
tag name: kivy-language
tags question: http://stackoverflow.com/q/51833438
tags question: http://stackoverflow.com/q/51948295

http://stackoverflow.com/q/51954289
tagged with: mysql
upvote count: 1
type: Question
linked to: http://stackoverflow.com/q/18671
has title: How to transfer data in django from sqlite to mysql, so that all the data that is in the admin are preserved?
has body: How to transfer data in django from sqlite to mysql, so that all the data that is in the admin are preserved? I have a database with the same tables, where I can transfer all the data. I tried to do it the standard way throughpython manage.py loaddata datadump.json. The data in the tables was transferred but the admin panel got stuck. I use wagtail django admin. To be more clear, I need information and not the structure itself
tagged with: wagtail
tagged with: dump
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/51979053
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/90859140
type: UnansweredQuestion
score: 1

http://stackoverflow.com/comment/90599345
type: AnswerComment
comment on: http://stackoverflow.com/a/51822553
type: Comment
has text: It only makes the image shorter but there is still a problem with the width, changing the height of the image doesn't matter and it will still scan - but adjusting he width makes it unreadable.
score: 0

http://stackoverflow.com/comment/90642980
type: Comment
comment on: http://stackoverflow.com/a/51832487
has text: @DGav sort_values(by='name')
score: 0
type: AnswerComment

http://stackoverflow.com/comment/90712319
type: Comment
type: QuestionComment
has text: If you installed Python somewhere writable, its normal site-packages should be somewhere writable as well, which means you can just use `pip3 install spam` or `python3 -m pip install spam` (or however you normally run your Python, the same thing with `-m pip` as arguments).
score: 0
comment on: http://stackoverflow.com/q/51880013

http://stackoverflow.com/comment/90761643
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51905312
has text: I would like to use the key parameter since it would be more efficient when sorting. Besides the cmp_to_key function, writing up a class to provide the complex comparison logic is the only way to sort with the new approach?

http://stackoverflow.com/q/51926684
tagged with: matplotlib
type: Question
has answer: http://stackoverflow.com/a/65042232
favorite count: 0
has title: Plotting sum of two sinusoids in Python
possible better answer: http://stackoverflow.com/a/51926767
answer count: 5
tagged with: seaborn
score: 3
has body: I would like to plot sum of two sinusoidal in Python, like on attached screenshot. Could you please recommend how can i do it in matplotlib?
has answer: http://stackoverflow.com/a/51928241
has answer: http://stackoverflow.com/a/51926767
tagged with: python
tagged with: jupyter-notebook
has answer: http://stackoverflow.com/a/72174172
has comment: http://stackoverflow.com/comment/90803013
downvote count: 2
has answer: http://stackoverflow.com/a/51926873
tagged with: graph
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51928241
upvote count: 5

http://stackoverflow.com/q/51912155
has body: I am having some issue importing Tensorflow-CPU. When I import import tensorflow as tf, I get this error MYPC@MYPC-PC MINGW64 ~/Desktop $ python Python 3.5.4 (v3.5.4:3f56838, Aug 8 2017, 02:17:05) [MSC v.1900 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import tensorflow as tf Traceback (most recent call last): File "C:\Python\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 14, in swig_import_helper return importlib.import_module(mname) File "C:\Python\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "&lt;frozen importlib._bootstrap&gt;", line 985, in _gcd_import File "&lt;frozen importlib._bootstrap&gt;", line 968, in _find_and_load File "&lt;frozen importlib._bootstrap&gt;", line 957, in _find_and_load_unlocked File "&lt;frozen importlib._bootstrap&gt;", line 666, in _load_unlocked File "&lt;frozen importlib._bootstrap&gt;", line 577, in module_from_spec File "&lt;frozen importlib._bootstrap_external&gt;", line 938, in create_module File "&lt;frozen importlib._bootstrap&gt;", line 222, in _call_with_frames_removed ImportError: DLL load failed with error code -1073741795 During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Python\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 58, in &lt;module&gt; from tensorflow.python.pywrap_tensorflow_internal import * File "C:\Python\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 17, in &lt;module&gt; _pywrap_tensorflow_internal = swig_import_helper() File "C:\Python\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 16, in swig_import_helper return importlib.import_module('_pywrap_tensorflow_internal') File "C:\Python\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ImportError: No m…
duplicate of: http://stackoverflow.com/q/50430086
has answer: http://stackoverflow.com/a/51912591
has comment: http://stackoverflow.com/comment/90775233
tagged with: importerror
tagged with: python
has answer: http://stackoverflow.com/a/51912911
type: UnansweredQuestion
score: 0
has title: Tensorflow - ImportError: DLL load failed with error code -1073741795
tagged with: tensorflow
linked to: http://stackoverflow.com/q/50430086
type: Question
answer count: 2
tagged with: python-import
has comment: http://stackoverflow.com/comment/90775915

pycharm
tags question: http://stackoverflow.com/q/51800809
tags question: http://stackoverflow.com/q/51926667
tags question: http://stackoverflow.com/q/51843015
tags question: http://stackoverflow.com/q/51831152
tag name: pycharm
tags question: http://stackoverflow.com/q/51902595
tags question: http://stackoverflow.com/q/51859462
tags question: http://stackoverflow.com/q/51869263
tags question: http://stackoverflow.com/q/51951256
tags question: http://stackoverflow.com/q/51887405
tags question: http://stackoverflow.com/q/51837124
tags question: http://stackoverflow.com/q/51818271
tags question: http://stackoverflow.com/q/51874753
tags question: http://stackoverflow.com/q/51924836
tags question: http://stackoverflow.com/q/51809922
tags question: http://stackoverflow.com/q/51897338
tags question: http://stackoverflow.com/q/51877005
tags question: http://stackoverflow.com/q/51945478
tags question: http://stackoverflow.com/q/51919248
tags question: http://stackoverflow.com/q/51941576
tags question: http://stackoverflow.com/q/51898409
type: Tag
tags question: http://stackoverflow.com/q/51847580
tags question: http://stackoverflow.com/q/51950281
tags question: http://stackoverflow.com/q/51913822
tags question: http://stackoverflow.com/q/51862083
tags question: http://stackoverflow.com/q/51893567
tags question: http://stackoverflow.com/q/51830993
tags question: http://stackoverflow.com/q/51859529
tags question: http://stackoverflow.com/q/51889132
tags question: http://stackoverflow.com/q/51846229
tags question: http://stackoverflow.com/q/51918167

http://stackoverflow.com/comment/91326460
has text: Hey I'll get back to you on this, one of the issue would be still that I also have a version file, and that seems to be unreadable too. I might have to workaround on that if the log works in appdata.
comment on: http://stackoverflow.com/a/52167181
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/51851290
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/51850844
score: 2
has body: IIUC drop_duplicates df.sort_values('Percentage').drop_duplicates('Sample',keep='last') Out[1046]: Sample Percentage Attribute1 Attribute2 2 2_B 10.0 ccccc ddddd 0 1_A 12.3 xxxx yyyy
downvote count: 0

http://stackoverflow.com/comment/90609008
type: AnswerComment
type: Comment
has text: I can confirm that multiple instances of calc.exe can run simultaneously, and this issue happens even when no instances of it are running before it begins the process in windows 10.
score: 0
comment on: http://stackoverflow.com/a/51827332

http://stackoverflow.com/q/51811096
upvote count: 1
has comment: http://stackoverflow.com/comment/90577264
downvote count: 1
tagged with: iteration
favorite count: 0
has comment: http://stackoverflow.com/comment/90577298
has answer: http://stackoverflow.com/a/51811204
has comment: http://stackoverflow.com/comment/90577507
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has answer: http://stackoverflow.com/a/51811964
type: UnansweredQuestion
tagged with: loops
has title: My list is being over sliced when writing to CSV
has comment: http://stackoverflow.com/comment/90577196
type: Question
has body: I am trying to write to a CSV, but when I attempt to iterate while writing to a CSV (either using a for loop or via the writerows), my output not only slices my list, but also slices the strings within the list. Please help! code: import csv FileName= input("Enter the name of your master file here: ") if len(FileName)&lt;1: FileName="MasterCustomerList.csv" FileOpen=open(FileName) lst=list() count=0 for lines in FileOpen: count=count+1 lines=lines.rstrip() pieces=lines.split(',') if pieces[7]=="Yes": lst.append(pieces[2]+" "+pieces[1]+" "+pieces[0]) lst.sort() for items in lst: print(items) with open("CC_Customers.csv", "w", newline="") as DataFile: DataFileWriter = csv.writer(DataFile) DataFileWriter.writerows(lst) DataFile.close()
score: 0
answer count: 2

match
tags question: http://stackoverflow.com/q/51926237
tag name: match
type: Tag
tags question: http://stackoverflow.com/q/51875012

http://stackoverflow.com/a/51848498
upvote count: 1
has body: You could also convert the csv file to a list, truncate the list, and then convert the list to a numpy array and then use np.reshape.
has comment: http://stackoverflow.com/comment/90650561
score: 1
has comment: http://stackoverflow.com/comment/90650510
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51848406

http://stackoverflow.com/comment/90726308
type: AnswerComment
score: 0
type: Comment
has text: I'd also like to add that this is beautifully pythonic. very impressive, I am humbled!
comment on: http://stackoverflow.com/a/51887293

http://stackoverflow.com/comment/90625220
type: Comment
score: 0
has text: Still, I would be curious how one would do that in cython.
type: AnswerComment
comment on: http://stackoverflow.com/a/51829198

http://stackoverflow.com/q/51940769
downvote count: 2
upvote count: 1
tagged with: object
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91227919
score: -1
has comment: http://stackoverflow.com/comment/90831341
has body: If you use the sorted() method on a variable does it create a new object?
has title: Creating new objects in Python with different methods
type: Question
accepted answer: http://stackoverflow.com/a/51940820
has comment: http://stackoverflow.com/comment/90831332
tagged with: sorting
favorite count: 0
has answer: http://stackoverflow.com/a/51940820
answer count: 1
tagged with: python

http://stackoverflow.com/comment/90818016
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/51933981
type: Comment
has text: arguably even better `bitmaps = {30: 0b000, 125: 0b001, 250: 0b010, 1000: 0b011}` then you can just access using their value.

http://stackoverflow.com/comment/90837020
type: AnswerComment
score: 0
type: Comment
has text: Thanks for the script.. but this is not working.. the error is as below - Reason: Script does not have a variable named 'hook', Resolution: Add a global variable named 'hook' to the script that is instantiated to the class that implements ScriptHook interface
comment on: http://stackoverflow.com/a/51943072

directed-acyclic-graphs
type: Tag
tag name: directed-acyclic-graphs
tags question: http://stackoverflow.com/q/51881118

http://stackoverflow.com/q/51890834
upvote count: 2
score: 1
has comment: http://stackoverflow.com/comment/90732974
has comment: http://stackoverflow.com/comment/90732694
tagged with: file
downvote count: 1
has title: word counting in python in file with spaces in name
type: Question
has body: Here is my code fname = input("Enter file name: ") word=input("Enter word to be searched:") k = 0 with open(fname, 'r') as f: for line in f: words = line.split() for i in words: if(i==word): k=k+1 print("Occurrences of the word:") print(k) I am running it on windows if the file name is having spaces in it such as "some file xyz.txt" then upon running the above code I am getting error Enter file name: "some file xyz.txt" Enter word to be searched:cs Traceback (most recent call last): File "D:/folder1/folder2/folder3/some file xyz.txt", line 5, in &lt;module&gt; with open(fname, 'r') as f: OSError: [Errno 22] Invalid argument: '"some file xyz.txt"' &gt;&gt;&gt; How should I enter correct file name with spaces or the code itself is wrong?
has comment: http://stackoverflow.com/comment/90732882
has comment: http://stackoverflow.com/comment/90732738
has answer: http://stackoverflow.com/a/51891493
has comment: http://stackoverflow.com/comment/90732846
has comment: http://stackoverflow.com/comment/90732804
accepted answer: http://stackoverflow.com/a/51891493
answer count: 1
tagged with: string
favorite count: 0
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/a/62515158
has body: There are 4 methods which I'm aware of for plotting the scikit-learn decision tree: print text representation of the tree with sklearn.tree.export_text method plot with sklearn.tree.plot_tree method (matplotlib needed) plot with sklearn.tree.export_graphviz method (graphviz needed) plot with dtreeviz package (dtreeviz and graphviz needed) The simplest is to export to the text representation. The example decision tree will look like: |--- feature_2 &lt;= 2.45 | |--- class: 0 |--- feature_2 &gt; 2.45 | |--- feature_3 &lt;= 1.75 | | |--- feature_2 &lt;= 4.95 | | | |--- feature_3 &lt;= 1.65 | | | | |--- class: 1 | | | |--- feature_3 &gt; 1.65 | | | | |--- class: 2 | | |--- feature_2 &gt; 4.95 | | | |--- feature_3 &lt;= 1.55 | | | | |--- class: 2 | | | |--- feature_3 &gt; 1.55 | | | | |--- feature_0 &lt;= 6.95 | | | | | |--- class: 1 | | | | |--- feature_0 &gt; 6.95 | | | | | |--- class: 2 | |--- feature_3 &gt; 1.75 | | |--- feature_2 &lt;= 4.85 | | | |--- feature_1 &lt;= 3.10 | | | | |--- class: 2 | | | |--- feature_1 &gt; 3.10 | | | | |--- class: 1 | | |--- feature_2 &gt; 4.85 | | | |--- class: 2 Then if you have matplotlib installed, you can plot with sklearn.tree.plot_tree: tree.plot_tree(clf) # the clf is your decision tree model The example output is very similar to what you will get with export_graphviz: You can also try dtreeviz package. It will give you much more information. The example: You can find comparison of different visualization of sklearn decision tree with code snippets in this blog post: link.
answers question: http://stackoverflow.com/q/51912370
type: Answer
score: 0

http://stackoverflow.com/comment/90719244
comment on: http://stackoverflow.com/a/51867519
score: 0
has text: See my edit. Hopefully, this guides you in the right direction.
type: Comment
type: AnswerComment

mysql
tags question: http://stackoverflow.com/q/51897241
tags question: http://stackoverflow.com/q/51921187
tags question: http://stackoverflow.com/q/51896429
tags question: http://stackoverflow.com/q/51896131
tags question: http://stackoverflow.com/q/51934592
tags question: http://stackoverflow.com/q/51800323
tags question: http://stackoverflow.com/q/51840644
tag name: mysql
tags question: http://stackoverflow.com/q/51870699
tags question: http://stackoverflow.com/q/51954181
tags question: http://stackoverflow.com/q/51935610
tags question: http://stackoverflow.com/q/51933580
tags question: http://stackoverflow.com/q/51877093
tags question: http://stackoverflow.com/q/51925097
tags question: http://stackoverflow.com/q/51855083
tags question: http://stackoverflow.com/q/51927954
tags question: http://stackoverflow.com/q/51907237
tags question: http://stackoverflow.com/q/51927603
tags question: http://stackoverflow.com/q/51830831
tags question: http://stackoverflow.com/q/51800698
tags question: http://stackoverflow.com/q/51926303
tags question: http://stackoverflow.com/q/51861131
tags question: http://stackoverflow.com/q/51954289
tags question: http://stackoverflow.com/q/51804782
tags question: http://stackoverflow.com/q/51920779
tags question: http://stackoverflow.com/q/51841936
tags question: http://stackoverflow.com/q/51807348
tags question: http://stackoverflow.com/q/51943419
type: Tag
tags question: http://stackoverflow.com/q/51867550
tags question: http://stackoverflow.com/q/51809684
tags question: http://stackoverflow.com/q/51853649
tags question: http://stackoverflow.com/q/51846102
tags question: http://stackoverflow.com/q/51870141
tags question: http://stackoverflow.com/q/51800216
tags question: http://stackoverflow.com/q/51926091
tags question: http://stackoverflow.com/q/51897079
tags question: http://stackoverflow.com/q/51878786
tags question: http://stackoverflow.com/q/51880452
tags question: http://stackoverflow.com/q/51918829
tags question: http://stackoverflow.com/q/51798975
tags question: http://stackoverflow.com/q/51878594
tags question: http://stackoverflow.com/q/51802862
tags question: http://stackoverflow.com/q/51933362
tags question: http://stackoverflow.com/q/51879564
tags question: http://stackoverflow.com/q/51865334
tags question: http://stackoverflow.com/q/51947255
tags question: http://stackoverflow.com/q/51899652
tags question: http://stackoverflow.com/q/51897825
tags question: http://stackoverflow.com/q/51929835
tags question: http://stackoverflow.com/q/51851875
tags question: http://stackoverflow.com/q/51801925
tags question: http://stackoverflow.com/q/51935715
tags question: http://stackoverflow.com/q/51833328

http://stackoverflow.com/comment/90595172
type: Comment
comment on: http://stackoverflow.com/a/51820619
has text: Sorry. How do you do that?
score: 0
type: AnswerComment

http://stackoverflow.com/a/51930997
downvote count: 0
type: Answer
has body: The values in value column are not np.inf or -np.inf. Since you want to remove those very large values you can try this. Here you can use df.value[0] as your value which needs to be replaced. First replacing with 0: df.replace(df.value[0], 0) The Output looks like this: id kind value time 0 1 tmx2005-01 0.0 1 1 1 tmx2005-02 0.0 2 2 1 tmx2005-03 0.0 3 3 1 tmx2005-04 0.0 4 4 1 tmx2005-05 0.0 5 If you want to replace it with np.nan value then: df.replace(df.value[0], np.nan) Remove the null values using value column as a subset: df.dropna(subset=["value"], how="all")
upvote count: 2
accepted answer of: http://stackoverflow.com/q/51930898
has comment: http://stackoverflow.com/comment/90814914
answers question: http://stackoverflow.com/q/51930898
score: 2
type: AcceptedAnswer

http://stackoverflow.com/comment/90842268
type: QuestionComment
has text: First, do you know the algorithm?
comment on: http://stackoverflow.com/q/51946413
score: 0
type: Comment

http://stackoverflow.com/comment/90690605
has text: what about pytesseract?
score: 0
comment on: http://stackoverflow.com/q/51867834
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51809132
has comment: http://stackoverflow.com/comment/90630540
has comment: http://stackoverflow.com/comment/90636934
tagged with: machine-learning
tagged with: python
answer count: 1
has answer: http://stackoverflow.com/a/51844178
tagged with: tensorflow
score: 2
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/90641666
tagged with: keras
has comment: http://stackoverflow.com/comment/90600191
has title: How to restore a saved model with LSTM layers in Keras
tagged with: lstm
accepted answer: http://stackoverflow.com/a/51844178
type: Question
has comment: http://stackoverflow.com/comment/90611027
has comment: http://stackoverflow.com/comment/90630019
has body: I was following a tutorial to generate English text using LSTMs and using Shakespeare's works as a training file. This is the model I am using with reference to that- model = Sequential() model.add(LSTM(HIDDEN_DIM, input_shape=(None, VOCAB_SIZE), return_sequences=True)) model.add(Dropout(0.2)) for i in range(LAYER_NUM - 1): model.add(LSTM(HIDDEN_DIM, return_sequences=True)) model.add(TimeDistributed(Dense(VOCAB_SIZE))) model.add(Activation('softmax')) model.compile(loss="categorical_crossentropy", optimizer="rmsprop") After 30 epochs of training, I save the model using model.save('model.h5'). At this point, the model has learned the basic format and has learned a few words. However, when I try to load the model in a new program using load_model('model.h5') and try to generate some text, it ends up predicting completely random letters and symbols. This led me to think that the model weights are not being restored properly, since I encountered the same problem while storing only the model weights. So is there any alternative for storing and restoring trained models with LSTM layers? For reference, in order to generate the text, the function randomly generates a character and feeds it into the model to predict the next character. This is the function- def generate_text(model, length): ix = [np.random.randint(VOCAB_SIZE)] y_char = [ix_to_char[ix[-1]]] X = np.zeros((1, length, VOCAB_SIZE)) for i in range(length): X[0, i, :][ix[-1]] = 1 print(ix_to_char[ix[-1]], end="") ix = np.argmax(model.predict(X[:, :i+1, :])[0], 1) y_char.append(ix_to_char[ix[-1]]) return ('').join(y_char) EDIT The snippet of code for training- for nbepoch in range(1, 11): print('Epoch ', nbepoch) model.fit(X, y, batch_size=64, verbose=1, epochs=1) if nbepoch % 10 == 0: model.model.save('checkpoint_{}_epoch_{}.h5'.format(512, nbepoch)) generate_text(model, 50) print('\n\n\n') Where generate_text() is just a function to predict a new character, starting from a randomly generated character. After every…
favorite count: 0
has comment: http://stackoverflow.com/comment/90610225
upvote count: 2

http://stackoverflow.com/comment/90577583
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51811247
type: Comment
has text: @J.C.Rocamonde. `ast.literal_eval` is always safe and secure than using `eval`. Never, never use eval if you are not sure about the data source

http://stackoverflow.com/comment/90654161
type: QuestionComment
comment on: http://stackoverflow.com/q/51850421
has text: What happens if you use `df.plot(ax=ax, x_compat=True)`? Does this change anything?
score: 0
type: Comment

http://stackoverflow.com/comment/91555837
type: Comment
comment on: http://stackoverflow.com/a/51811364
type: AnswerComment
has text: @krishna I have yet to find a solution.
score: 0

http://stackoverflow.com/q/51914893
possible better answer: http://stackoverflow.com/a/51914964
downvote count: 0
has answer: http://stackoverflow.com/a/51914971
has answer: http://stackoverflow.com/a/51914964
favorite count: 0
tagged with: python-3.x
has title: How to make my modified pandas/numpy .where function adaptable to different sizes of a list parameter?
tagged with: python
linked to: http://stackoverflow.com/q/20528328
type: AnsweredQuestion
score: 1
accepted answer: http://stackoverflow.com/a/51914971
upvote count: 1
type: Question
tagged with: numpy
tagged with: function
has body: I want to create my own function that scans a number of user-specified columns in a dataframe, and that function will create a new variable and assign it as '1' if all the specified columns == 1, otherwise 0. In the following codes, I am accommodating if users are inputting exactly two columns to be scanned over. import numpy as np class Tagger: def __init__(self): pass def summing_all_tagger(self, df, tag_var_list, tag_value=1): # This tagger creates a tag='1' if all variables in tag_var_list equals to tag_value; otherwise='0' self.df = df self.tag_var_list = tag_var_list self.tag_value = tag_value self.df['temp'] = np.where((self.df[self.tag_var_list[0]]==self.tag_value) &amp; (self.df[self.tag_var_list[1]]==self.tag_value), 1, 0) return self.df_pin['temp'] Then I can call it in the main.py file: import pandas as pd import datetime import feature_tagger.feature_tagger as ft tagger_obj = ft.Tagger() df_pin['PIN_RX&amp;TIME_TAG'] = tagger_obj.summing_all_tagger(df_pin, tag_var_list=['PIN_RX_TAG', 'PIN_TIME_TAG'], tag_value=1) How can I modify it so users can enter as many column names for tag_var_list as they want? Such as df_pin['PIN_RX&amp;TIME_TAG'] = tagger_obj.summing_all_tagger(df_pin, tag_var_list=['PIN_RX_TAG', 'PIN_TIME_TAG', 'PIN_NAME_TAG'], tag_value=1) # or df_pin['PIN_RX&amp;TIME_TAG'] = tagger_obj.summing_all_tagger(df_pin, tag_var_list=['PIN_RX_TAG'], tag_value=1)
answer count: 2
tagged with: pandas

http://stackoverflow.com/comment/90650699
comment on: http://stackoverflow.com/a/51848539
score: 0
type: AnswerComment
has text: Okay, can you tell me what I'm doing wrong or please edit. That cans help me to understand your opinion.
type: Comment

http://stackoverflow.com/comment/90846866
comment on: http://stackoverflow.com/q/51948561
type: QuestionComment
has text: Did you try using Haversine Distance to compute distance between two Geo-Coordinates?
type: Comment
score: 1

http://stackoverflow.com/comment/90836568
score: 0
has text: Meanwhile, this isn't "attribute syntax". Attributes are things you access with `.`, like `self.x` or `np.sum` or `grad_h.shape`. This is _indexing_ syntax. Indexes are things you access with brackets, like `grad_h[0]` or `grad_h[0, 2]` or `grad_h[0:2, ..., 3]` or `grad_h[h < 0]`. (Technically, it's _subscripting_ syntax, which is used both for indexing and for key lookup, but nobody calls it that unless they're talking about implementing `__getitem__` methods or how the parser works…)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51943308

computer-vision
tags question: http://stackoverflow.com/q/51846195
tags question: http://stackoverflow.com/q/51886576
tags question: http://stackoverflow.com/q/51812001
tags question: http://stackoverflow.com/q/51798812
tags question: http://stackoverflow.com/q/51818763
tags question: http://stackoverflow.com/q/51887222
tags question: http://stackoverflow.com/q/51888661
tags question: http://stackoverflow.com/q/51841326
tags question: http://stackoverflow.com/q/51908166
tags question: http://stackoverflow.com/q/51866280
tags question: http://stackoverflow.com/q/51808101
tags question: http://stackoverflow.com/q/51933123
tags question: http://stackoverflow.com/q/51846933
tags question: http://stackoverflow.com/q/51857066
tags question: http://stackoverflow.com/q/51856575
type: Tag
tag name: computer-vision
tags question: http://stackoverflow.com/q/51828770

http://stackoverflow.com/q/51864688
has comment: http://stackoverflow.com/comment/90681617
type: Question
tagged with: recursion
has comment: http://stackoverflow.com/comment/90681728
has comment: http://stackoverflow.com/comment/90681571
has title: recursion repeats output - python 3
score: 0
has answer: http://stackoverflow.com/a/51864943
has comment: http://stackoverflow.com/comment/90681885
accepted answer: http://stackoverflow.com/a/51864943
answer count: 1
has body: I'm trying out recursion and am having trouble Here's the code: inputs = [] def ins(x,y,length): global inputs, j if [x,y] not in inputs: inputs.append([x,y]) if x is not length: ins(x+1,y,length) if y is not length: ins(x,y+1,length) j = 0 ins(0,0,12) but it seems to go over the same x,y combo multiple times and gives an inputs ends up being 10400599 items long instead of just 169
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/90711735
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51879904
score: 2
has text: Can you check if GPU is really utilized and how much % of it's used? Command `watch -n 1 nvidia-smi` Also do you use estimators API to train the model or feed_dict ?

http://stackoverflow.com/a/73135208
has body: After updating or trough fresh install anaconda-navigator stops running trough .lnk C:\Anaconda3\pythonw.exe C:\Anaconda3\cwp.py C:\Anaconda3 C:\Anaconda3\pythonw.exe C:\Anaconda3\Scripts\anaconda-navigator-script.py conda install anaconda=2022.05 break up anaconda-navigator 2.2.0-py39haa95532_0 --&gt; 2.1.4-py39haa95532_0 still broken anaconda-navigator 2.1.4-py39haa95532_0 --&gt; 2.1.2-py39haa95532_0 still broken anaconda-navigator 2.1.2-py39haa95532_0 --&gt; 2.1.1-py39_0 works and offer update to 2.2.0 and after update trough GUI break up again But is runable trough cmd promt anaconda-navigator
score: 0
answers question: http://stackoverflow.com/q/51849743
type: Answer

http://stackoverflow.com/a/51860590
answers question: http://stackoverflow.com/q/51860471
upvote count: 1
has body: Solution from pandas pd.DataFrame(Menu).stack().apply(pd.Series).loc[lambda x : x['PLU']=='59'] Out[143]: NAME PLU breadsticks Appetizer breadsticks 59
downvote count: 0
type: Answer
score: 1

http://stackoverflow.com/a/51847145
has body: Finally I have found the solution after debugging for atleast 1 week. The problem was access related issue. the SAP NW RFC SDK was installed in the path C:\nwrfcsdk\lib as per the documentation. link : Installation documentation But the user account under which the .NET Core API was running in the application pool of IIS didn't have any read/write access to this nwrfcsdk folder. Hence pyrfc was not able to import the DLL (SAPNWRFC.dll) when the python script was being called from the .NET Core API.I have provided read/write access to that particular account and the script is running fine now . I have followed the below steps to debug the diagnose the issue - I have used profiling with Procmon.exe from sysinternals to monitor w3wp.exe IIS worker process and python.exe after calling the API I have also used dependency walker to track the dependent dll. Hope this helps someone who is facing a similar type of issue.
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/51825708
accepted answer of: http://stackoverflow.com/q/51825708
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/90833159
score: 0
type: Comment
has text: Yes and remove 'workbook.save("saxons.xls")' and add it at the end.
type: AnswerComment
comment on: http://stackoverflow.com/a/51929982

http://stackoverflow.com/q/51800931
type: Question
upvote count: 2
tagged with: openpyxl
has body: I had a problem wit openpyxl but users Eric and H. Trizi solved it. Unfortunately there is another problem. They gave me solution how to select rows that contain certain product name (ABC in this case) but I have no idea how to access search results separately. This is Eric's code: from openpyxl import load_workbook wb = load_workbook("report.xlsx") ws = wb.active for row in ws.rows: if row[4].value == "ABC": for cell in row: print(cell.value, end=" ") print() And this is H. Trizi's: import pandas as pd df = pd.read_excel("path_to_excel_file") df_abc = df[df["Products"] == "ABC"] # this will only contain 2,4,6 rows They both work great when it comes to selecting ALL rows that contain "ABC" product but is there a way to access every single row (and then every cell in it) that contains ABC product name separately? What I want to achieve ist access every row that has product name ABC separately and then save its cells to variables. So step by step: 1.Find all rows with ABC product is in rows (2,4,6 in this case)- solved by Eric and H. Trizi 2.Get row 2 and break it down to cells that will be assigned to variables (name, surname, order number etc.) 3. Do the same for row 4 4. Do the same for row 6 5.etc. PS. Data is available in excel report
tagged with: python
tagged with: excel
accepted answer: http://stackoverflow.com/a/51800975
score: 2
downvote count: 0
tagged with: pandas
type: AnsweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/90558278
has comment: http://stackoverflow.com/comment/90558522
has title: How to access one row out of many founded
favorite count: 0
has answer: http://stackoverflow.com/a/51800975

http://stackoverflow.com/comment/90636042
type: AnswerComment
score: 0
type: Comment
has text: That would depend on your environment and set up, but I can't see why not. Though, why is it that you want a nosql database. You're extracting tabular data, so why use something that's designed for unstructured data. Won't a simple sql database not do the job?
comment on: http://stackoverflow.com/a/51840746

http://stackoverflow.com/a/58083051
type: Answer
answers question: http://stackoverflow.com/q/51865300
has body: You can also add global browser like so: def open_instagram(): try: # Connect chrome_options = webdriver.ChromeOptions() chrome_options.add_argument("--incognito") global browser # this will prevent the browser variable from being garbage collected browser = webdriver.Chrome('drivers/chromedriver.exe', chrome_options=chrome_options) browser.set_window_size(1800, 900) browser.get("https://www.instagram.com/accounts/login/?hl=de") browser.find_element(By.NAME, 'username').send_keys('MYEMAIL', Keys.TAB, 'MYPW', Keys.ENTER) except Exception as e: print (e, 'Instagram') open_instagram() Source
downvote count: 0
score: 8
upvote count: 8

http://stackoverflow.com/comment/91005572
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51985671
score: 0
has text: Got it now working. I put the solution to the original question. Thank you for your help!

http://stackoverflow.com/comment/90860953
type: Comment
comment on: http://stackoverflow.com/q/51955020
has text: A time string like `u'2018-04-29T23:00:00'` should be treated with caution. It has no timezone info, so you need to be certain about whether it's a local time, or a UTC time. And if it's local, make sure it's from your locality. ;)
score: 0
type: QuestionComment

http://stackoverflow.com/a/51935149
downvote count: 0
score: 7
has comment: http://stackoverflow.com/comment/90820395
has comment: http://stackoverflow.com/comment/90820640
has body: Using test.groupby('ID',as_index=False).agg(lambda x : x.mode()[0] if x.nunique()==1 else np.nan) Out[372]: ID val1 val2 val3 0 4 one hi 3.0 1 5 one bye 3.0 2 6 NaN hola 4.0 3 7 seven NaN NaN
has comment: http://stackoverflow.com/comment/90820409
upvote count: 7
has comment: http://stackoverflow.com/comment/90820701
answers question: http://stackoverflow.com/q/51935063
has comment: http://stackoverflow.com/comment/90820421
type: Answer
has comment: http://stackoverflow.com/comment/90820317
has comment: http://stackoverflow.com/comment/90820434

http://stackoverflow.com/a/51873287
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/90698937
has comment: http://stackoverflow.com/comment/90698390
has comment: http://stackoverflow.com/comment/90698705
has comment: http://stackoverflow.com/comment/90698752
has comment: http://stackoverflow.com/comment/90716076
has comment: http://stackoverflow.com/comment/90698697
has comment: http://stackoverflow.com/comment/90698043
score: 1
answers question: http://stackoverflow.com/q/51872533
has comment: http://stackoverflow.com/comment/90698479
has body: Considering that the input is Aug 15 17:32:50 abc lines.split(None, 3) is splitting it into 4 parts while you are assigning only 3 variable. Run the below code import subprocess from datetime import datetime import re month_abbr = {"jan": 1, "feb": 2, "mar": 3, "apr": 4, "may": 5, "jun": 6, "jul": 7, "aug": 8, "sep": 9, "oct": 10, "nov": 11, "dec": 12} def parse_date(lines): mon, day, tim, _ = lines.split(None, 3) # note the change date_string = "{:02} {:02} ".format(month_abbr[mon.lower()], int(day)) + tim try: return datetime.strptime(date_string, "%m %d %H:%M:%S") except ValueError as e: return datetime.strptime(date_string, "%m %d %H:%M:%S.%f") f = open("temp.txt") for lines in f: line = lines.strip() date_obj = re.search('(.*?\d\d:\d\d:\d\d)', line) if date_obj: date = date_obj.group(1) if date: val = parse_date(date) else: continue print val
has comment: http://stackoverflow.com/comment/90698382
downvote count: 0
has comment: http://stackoverflow.com/comment/90698112

http://stackoverflow.com/comment/90854841
comment on: http://stackoverflow.com/q/51952253
type: QuestionComment
type: Comment
has text: So you'd like to convert continuous time sequences to a single row?
score: 1

http://stackoverflow.com/comment/90609624
score: 0
comment on: http://stackoverflow.com/q/51827117
type: Comment
type: QuestionComment
has text: @abarnert I am doing automated testing of anti-malware system, and compiled a false positive signature for calc.exe, run the process, run the scan with my signature check that the process is marked as "malicious" than need to kill the process and do a rescan, so this is the whole story...

http://stackoverflow.com/comment/90679636
has text: I knew there had to be a simpler way. I'll give it a try. Thanks!
type: Comment
comment on: http://stackoverflow.com/a/51862870
score: 0
type: AnswerComment

http://stackoverflow.com/q/51865271
accepted answer: http://stackoverflow.com/a/51865487
has comment: http://stackoverflow.com/comment/90682994
downvote count: 0
answer count: 1
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/90682906
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/90682875
type: AnsweredQuestion
tagged with: dynamic
type: Question
has body: I want to be able to dynamically check and set an instances attribute values. The use-case is for a point-like class, where I want to have a custom 'set_value' method that checks for which value the client is trying to set, and then determines what to do from there. My goal is to have a method which allows the values (x, y) of the instance to be set once, and then disallows future assignments to those variables... effectively making them 'immutable'. I know that this does not technically make them immutable, I'm relying on the gentleman's agreement to not do funny stuff and mess around with it. I've trying messing around with the setattr method, to no avail, as it then won't allow the init to run in the first place. My class is shown below: class Node: """Represents the nodes as points with a position x, y.""" def __init__(self, x=0, y=0, x_state=0, y_state=0): """Create a new node at x, y""" self.x = x self.y = y if self.x != 0: self.x_state = 1 else: self.x_state = x_state if self.y != 0: self.y_state = 1 else: self.y_state = y_state # some other dunder methods here def set_value(self, attr, value): if self.[attr]_state == 0: self.[attr] = value self.[attr]_state = 1 else: raise NotImplementedError The method checks the appropriate 'state' variable and then assigns the x or y variable to the value given by the user if the 'state' is 0, and then gives the 'state' a value of 1, thereby rendering future value assignments useless. The confusion I have is with dynamically referencing the attributes. Is this possible? Thanks in advance for any assistance!
has comment: http://stackoverflow.com/comment/90683163
has answer: http://stackoverflow.com/a/51865487
has title: How do I dynamically check and set an instances variable values?

http://stackoverflow.com/comment/90858163
comment on: http://stackoverflow.com/a/51913162
score: 0
type: AnswerComment
has text: In that case what it means is : content is empty. which could be because when you are scrapping the website, there could be a case where "table:nth-child(2) a" is empty or does not exist. You can do an "if content.isempty()" check before "for" loop or you can try grabbing the element through something other than "table"nth-child"
type: Comment

http://stackoverflow.com/comment/90675463
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51861577
has text: I think the first is a list-comprehension and the second one is part of the lambda stuff python offers. I believe most people like list-comprehension more then lambda but I cant offer any technical details here.
score: 0

http://stackoverflow.com/q/51902011
downvote count: 0
has body: I'm just starting with Python and I'm having trouble understanding how I'm supposed to achieve the following goal (I'm a Java programmer). Here is the initial code: def compute_distances_two_loops(self, X): """ Compute the distance between each test point in X and each training point in self.X_train using a nested loop over both the training data and the test data. Inputs: - X: A numpy array of shape (num_test, D) containing test data. Returns: - dists: A numpy array of shape (num_test, num_train) where dists[i, j] is the Euclidean distance between the ith test point and the jth training point. """ num_test = X.shape[0] num_train = self.X_train.shape[0] dists = np.zeros((num_test, num_train)) for i in range(num_test): for j in range(num_train): ##################################################################### # TODO: # # Compute the l2 distance between the ith test point and the jth # # training point, and store the result in dists[i, j]. You should # # not use a loop over dimension. # ##################################################################### dists[i, j] = np.sum(np.square(X[i] - self.X_train[j])) ##################################################################### # END OF YOUR CODE # ##################################################################### return dists Here is the piece of code that is supposed to have one less nested loop while still outputing the same array: def compute_distances_one_loop(self, X): """ Compute the distance between each test point in X and each training point in self.X_train using a single loop over the test data. Input / Output: Same as compute_distances_two_loops """ num_test = X.shape[0] num_train = self.X_train.shape[0] dists = np.zeros((num_test, num_train)) for i in range(num_test): tmp = '%s %d' % ("\nfor i:", i) print(tmp) print(X[i]) print("end of X[i]") print(self.X_train[:]) # all the thing [[ ... ... ]] print(": before, i after") print(self.X_train[i]) # just a row print(self.X_train[i, :]) ##############…
has answer: http://stackoverflow.com/a/51902523
has title: Replacing a nested loop
type: AnsweredQuestion
score: 2
accepted answer: http://stackoverflow.com/a/51902523
favorite count: 0
tagged with: python-3.x
type: Question
upvote count: 2
tagged with: machine-learning
tagged with: python
answer count: 1
tagged with: numpy

http://stackoverflow.com/a/61605029
answers question: http://stackoverflow.com/q/51902824
type: Answer
has body: Neither of the suggested solutions work for keyboard layouts that isn't the standard US keyboard layout. The problem is that pyautogui doesn't really handle different keyboard layouts that well. Switching to standard US keyboard layout in your OS should solve any issues with special characters.
score: 0

http://stackoverflow.com/comment/90737847
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51880333
has text: You should be able to use `.apply` the same way when resampling. I've edited the answer.
score: 0

http://stackoverflow.com/q/51835305
downvote count: 2
type: Question
has body: As the title suggests... Is there a way to change the color of the text on a checkbox while the checkbox is checked, and then return to the default color when the checkbox is unchecked?
has answer: http://stackoverflow.com/a/51837475
score: 0
answer count: 1
favorite count: 0
tagged with: colors
has title: Python/Tkinter - Change the Text Color Of on a Checkbox, When Checkbox is Checked?
tagged with: python
tagged with: checkbox
accepted answer: http://stackoverflow.com/a/51837475
tagged with: text
type: AnsweredQuestion
tagged with: tkinter
upvote count: 2

http://stackoverflow.com/q/51928536
has title: Pandas data frames alignment with time gaps
accepted answer: http://stackoverflow.com/a/51948127
tagged with: dataframe
tagged with: gaps-in-data
has comment: http://stackoverflow.com/comment/90817370
tagged with: pandas
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90806599
type: Question
has answer: http://stackoverflow.com/a/51948127
tagged with: python
answer count: 1
has comment: http://stackoverflow.com/comment/90817242
has comment: http://stackoverflow.com/comment/90843574
has body: I have a problem trying to align two different pandas dataframes. Actually the time alignment works using: import pandas as pd import datetime import numpy as np import matplotlib.pyplot as plt d1 = np.random.random_integers(0,7000,[4000,1]) d2 = np.random.random_integers(0,7000,[2000,1]) dfA = pd.DataFrame(d1) dfB = pd.DataFrame(d2) dfA.columns = ['data1'] dfB.columns = ['data2'] dfA['time'] = pd.date_range('1970-01-01 00:01:00', periods=dfA.shape[0], freq='1S') dfB['time'] = pd.date_range('1970-01-01 00:00:00', periods=dfB.shape[0], freq='1S') dfA.set_index('time', inplace=True) dfB.set_index('time', inplace=True) dfA1 = dfA.between_time('00:00:00', '00:09:00') dfA2 = dfA.between_time('00:14:00', '00:16:00') dfB1 = dfB.between_time('00:00:00', '00:12:00') dfB2 = dfB.between_time('00:15:00', '00:16:00') df1 = pd.concat([dfA1, dfA2]) df2 = pd.concat([dfB1, dfB2]) df_aligned = df1.join(df2, how='outer').interpolate(method='time').resample('2S').mean().fillna(method='backfill') print(df_aligned.head()) df_aligned.plot() plt.plot(df_aligned['data1'].values) plt.plot(df_aligned['data2'].values) plt.show() However the two columns in df1 and df2 presents different time gaps and, as a result, I have new samples inside this gaps. My task is just retrieve actual data without fake samples coming from the gaps. Any suggestion? Thank you so much in advance.
tagged with: join
score: 0

http://stackoverflow.com/comment/90570956
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51807789
has text: @user3280146 I hope it is clear now that during adjustment process the values changed.

http://stackoverflow.com/q/51824170
has comment: http://stackoverflow.com/comment/90829005
has comment: http://stackoverflow.com/comment/90709190
score: 3
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/51939527
has body: In the past it seems bokeh had options to generate html files that work offline. Here is an older discussion that shows how to do it: https://groups.google.com/a/continuum.io/forum/#!topic/bokeh/Ts2P24YR0VU using the line: output_file(file_path, mode='inline') However, this seem not to work with the bokeh version I am using 0.12.10 When I try adding mode = 'inline' I am getting: TypeError: file_html() got an unexpected keyword argument 'mode' Looking at the new dcumentaion it makes sense: https://docs.bokeh.org/en/latest/docs/reference/embed.html#bokeh.embed.file_html Is it possible to get a short example of what to do to allow the html files to be viewed offline without running a local bokeh server? Hopefully the solution is trivial as before. Jacob
favorite count: 0
tagged with: offline
has comment: http://stackoverflow.com/comment/90706734
tagged with: http://stackoverflow.com/tag/html
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90753537
upvote count: 3
has title: Generating Bokeh html files that work offline
has comment: http://stackoverflow.com/comment/90606569
accepted answer: http://stackoverflow.com/a/51939527
tagged with: bokeh
type: Question

http://stackoverflow.com/a/51809065
type: Answer
score: 2
has body: Here is a solution using the maximum and minimum filters from ndimage: import numpy as np from scipy.ndimage import maximum_filter from scipy.ndimage import minimum_filter def max_minus_min(a, length, step=1): a = np.asarray(a) center = length//2 # shift the window to the right len_output = len(a)-length+1 # crop the output to keep only full windows max_a = maximum_filter(a, size=length, origin=-center, mode='nearest')[:len_output:step] min_a = minimum_filter(a, size=length, origin=-center, mode='nearest')[:len_output:step] return max_a - min_a print(max_minus_min([3,5,1,8,3,5,2,2], 2, 2)) # array([2, 7, 2, 0]) print(max_minus_min([3,5,1,8,3,5,2,2], 2, 1)) # array([2, 4, 7, 5, 2, 3, 0]) print(max_minus_min([0, 0, 0, 0, 1, 0, 0, 0], 4, 1)) # array([0, 1, 1, 1, 1]) print(max_minus_min([0, 0, 0, 0, 1, 0, 0, 0], 4, 3)) # array([0, 1])
answers question: http://stackoverflow.com/q/51808573
upvote count: 2
downvote count: 0

http://stackoverflow.com/q/51849673
tagged with: python
tagged with: generator
linked to: http://stackoverflow.com/q/25073064
upvote count: 0
has body: I am trying to combine this into one line - for x in set(l_rooms): if l_rooms.count(x) == 1: print(x) I tried: print(x for x in set(l_rooms) if l_rooms.count(x)== 1) but that only yields a generator object and doesn't actually print
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90654785
has comment: http://stackoverflow.com/comment/90652611
has title: How can I compound a if and for loop inside a print statement in Python
type: Question
score: -1
has answer: http://stackoverflow.com/a/51849694
duplicate of: http://stackoverflow.com/q/25073064
answer count: 1
downvote count: 1
favorite count: 0

http://stackoverflow.com/comment/90844076
comment on: http://stackoverflow.com/q/51947224
type: Comment
has text: Ah thanks, but I'm only interested in the binary values in positions of 'id' that match values from 'id2'. Thanks for your response!
score: 0
type: QuestionComment

http://stackoverflow.com/comment/90595072
type: QuestionComment
score: 1
has text: @jalazbe that statement is not correct. It depends on which version of Anaconda you install. As you can see [here](https://www.anaconda.com/download/) there is one download with a default python3 version and a different download with a default python2 version
comment on: http://stackoverflow.com/q/51819719
type: Comment

http://stackoverflow.com/q/51909757
possible better answer: http://stackoverflow.com/a/51909919
tagged with: append
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51909919
has body: I have this: I would like to achieve this using pandas:
accepted answer: http://stackoverflow.com/a/51909979
type: Question
tagged with: rows
has title: Insert rows based on values pandas dataframe
score: 0
answer count: 2
tagged with: pandas
tagged with: insert
has answer: http://stackoverflow.com/a/51909979
tagged with: python

http://stackoverflow.com/comment/90646660
comment on: http://stackoverflow.com/q/51846590
score: 0
type: Comment
type: QuestionComment
has text: Guys, before down voting, please read the question more carefully and do not propose wrong solutions.

http://stackoverflow.com/a/51862188
downvote count: 0
answers question: http://stackoverflow.com/q/51861904
has body: you can do it using str.split on df.A directly, with the parameter expand=True and then use values such as: df = pd.DataFrame({'A':['70 80 82','151 150 147']}) print (df.A.str.split(' ',expand=True).values) array([['70', '80', '82'], ['151', '150', '147']], dtype=object) with your method, if all the strings contain the same amount of numbers, you can still use np.stack to get the same result: print (np.stack(df.A.apply(lambda x: np.array(x.split(" "))).values)) EDIT: for the difference, not sure I can explain it good enough but I try. let's define arr1 = df.A.str.split(' ',expand=True).values arr2 = df.A.apply(lambda x: np.array(x.split(" "))).values First you can notice that the shape is not the same: print(arr1.shape) (2, 3) print(arr2.shape) (2,) so I would say one difference is that arr2 is a 1D array of elements that happens to be also 1D array. When you construct arr2 with values, it constructs a 1D array from the serie df.A.apply(lambda x: np.array(x.split(" "))) without looking at the type in this serie. For arr1, the difference is that df.A.str.split(' ',expand=True) is not a serie but a dataframe, so using values will construct an 2D array with a shape being (number of rows,nb of columns). In both case you use values, but actually having an array in a cell of a serie (as created in your method) will not create a 2D array. Then, if you want to access any element (such as the first row second element) you can do it by arr1[0,1] while arr2[0,1] will throw an error because this structure is not a 2D array, but arr2[0][1] gives the good answer because you access the second element [1] of the first 1D array [0] in arr2. I hope it gives some explanation.
type: Answer
has comment: http://stackoverflow.com/comment/90676824
has comment: http://stackoverflow.com/comment/90677369
score: 3
upvote count: 3
accepted answer of: http://stackoverflow.com/q/51861904
type: AcceptedAnswer

http://stackoverflow.com/q/51915962
downvote count: 1
has answer: http://stackoverflow.com/a/54837743
has body: I was wondering how I would go about allowing every server my bot is connected to, to set their own prefix. I am using the async version of dpy with Commands ext. I would assume you would store the prefix's and server name in a .json file, but I don't know how you would write them or check the file for them. Thanks
upvote count: 9
type: Question
answer count: 2
tagged with: discord.py
has answer: http://stackoverflow.com/a/51917443
tagged with: discord
has title: Per server prefixs
favorite count: 0
score: 8
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/90574447
comment on: http://stackoverflow.com/q/51809624
score: 0
type: Comment
type: QuestionComment
has text: @nuric `keras` has been part of core TF. except [`The tf.keras version in the latest TensorFlow release might not be the same as the latest keras version from PyPI.`](https://www.tensorflow.org/guide/keras#import_tfkeras)

http://stackoverflow.com/q/51806845
answer count: 1
has title: Scraping data from website graph with Python
tagged with: http://stackoverflow.com/tag/json
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90569143
type: Question
tagged with: python
score: 0
has comment: http://stackoverflow.com/comment/90569241
has answer: http://stackoverflow.com/a/51806994
has body: As an exercise, I am trying to scrape data from a dynamic graph using Python. The graph can be found at this link (let's say I want the data from the first one). Now, I was thinking of doing something like: src = 'https://marketchameleon.com/Overview/WFT/IV/#_ABSTRACT_RENDERER_ID_11' import json import urllib.request with urllib.request.urlopen(src) as url: data = url.read() reply = json.loads(data) However, I receive an error message on the last line of the code, saying: JSONDecodeError: Expecting value "data" is not empty, so I believe there is a problem with the format of the information within it. Does someone have an idea to solve this issue? Thanks!
has comment: http://stackoverflow.com/comment/90569179

http://stackoverflow.com/comment/106070415
score: 2
has text: Beautiful method.
type: AnswerComment
comment on: http://stackoverflow.com/a/56981871
type: Comment

http://stackoverflow.com/comment/95650631
type: QuestionComment
has text: @cowlicks - twine can be pointed at the folder to upload the package - see current answer
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51939257

http://stackoverflow.com/q/51872431
type: Question
tagged with: numpy
answer count: 2
tagged with: pandas
has answer: http://stackoverflow.com/a/51872666
downvote count: 0
favorite count: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/51872666
has title: pandas cumulative subtraction in a column
has comment: http://stackoverflow.com/comment/90696240
tagged with: python
possible better answer: http://stackoverflow.com/a/51872549
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/51872549
upvote count: 3
has body: I have a dataframe where I need to do a burndown starting from the baseline and subtracting all the values along, essentially I'm looking for an opposite of DataFrame().cumsum(0): In Use Baseline 3705.0 February 2018 0.0 March 2018 2.0 April 2018 15.0 May 2018 30.0 June 2018 14.0 July 2018 797.0 August 2018 1393.0 September 2018 86.0 October 2018 374.0 November 2018 21.0 December 2018 0.0 January 2019 0.0 February 2019 0.0 March 2019 0.0 April 2019 2.0 unknown 971.0 I cannot find a function to do or, or I'm not looking by the right tags / names. How can this be achieved?

http://stackoverflow.com/q/51834679
has body: I got the error message: Python 3.6.6 |Anaconda, Inc.| (default, Jun 28 2018, 17:14:51) [GCC 7.2.0] on linux Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import tensorflow as tf &gt;&gt;&gt; hello = tf.constant('Hello, TensorFlow!') &gt;&gt;&gt; sess = tf.Session() 2018-08-14 14:35:53.739970: I tensorflow/core/platform/cpu_feature_guard.cc:141] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 FMA 2018-08-14 14:35:53.948699: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:897] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero 2018-08-14 14:35:53.949210: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1405] Found device 0 with properties: name: Tesla K80 major: 3 minor: 7 memoryClockRate(GHz): 0.8755 pciBusID: 0000:00:05.0 totalMemory: 11.17GiB freeMemory: 11.11GiB 2018-08-14 14:35:53.949241: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1484] Adding visible gpu devices: 0 2018-08-14 14:35:53.949419: E tensorflow/core/common_runtime/direct_session.cc:158] Internal: cudaGetDevice() failed. Status: CUDA driver version is insufficient for CUDA runtime version Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/local/anaconda3/envs/tensorflow/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1494, in __init__ super(Session, self).__init__(target, graph, config=config) File "/usr/local/anaconda3/envs/tensorflow/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 626, in __init__ self._session = tf_session.TF_NewSession(self._graph._c_graph, opts) tensorflow.python.framework.errors_impl.InternalError: Failed to create session. Doing on the following environment. Tesla K80 GPU machine Ubuntu 16.04 CUDA 9.0 cudnn7=7.1.4.18 Python 3.6.6 tensorflow 1.10 Can someone please help me?
type: UnansweredQuestion
has title: tensorflow error. CUDA driver version is insufficient for CUDA runtime version
tagged with: tensorflow
has answer: http://stackoverflow.com/a/51834808
type: Question
downvote count: 2
answer count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/30820513
tagged with: python
upvote count: 4
tagged with: cuda
score: 2

http://stackoverflow.com/comment/90854485
type: Comment
type: QuestionComment
score: 3
has text: No, there isn't an easy way to do this. The `makemigrations` command creates migrations based on the models, not on the current database. You might be able to use `inspectdb` to create a `models.py` that matches your existing database, and use that to create your initial migration.
comment on: http://stackoverflow.com/q/51951919

http://stackoverflow.com/comment/90836072
type: Comment
has text: The init method for the class `Contact` 8 arguments. `firstname, middlename, lastname, nickname, title_photo, email, email2, email3`. While creating a Contact object inside your `test_add_contact_in_book_address` method you have passed just 4 out of these 8 arguments which is what the error message is complaining about in your screenshot
comment on: http://stackoverflow.com/q/51942665
score: 0
type: QuestionComment

http://stackoverflow.com/q/51902878
downvote count: 4
has answer: http://stackoverflow.com/a/51902981
upvote count: 0
has answer: http://stackoverflow.com/a/51902933
score: -4
has comment: http://stackoverflow.com/comment/90756921
type: AnsweredQuestion
favorite count: 0
accepted answer: http://stackoverflow.com/a/51902933
type: Question
answer count: 2
has title: How to communicate with Excel files via subprocess using python?
tagged with: python
tagged with: excel
tagged with: subprocess
has body: How do I change cells in an excel file with subprocess? So far, my code is: import subprocess ob =subprocess.Popen(['*Path to excel file*'], shell=True) ob.communicate('H2=test') But, it doesn't do anything! Any help would be appreciated
possible better answer: http://stackoverflow.com/a/51902981
tagged with: office365

http://stackoverflow.com/comment/90861311
comment on: http://stackoverflow.com/a/51955178
score: 0
type: AnswerComment
type: Comment
has text: Thank you! I think once I solve another problem I'm having that will work. I'll probably throw that column into an edit.

http://stackoverflow.com/comment/90717214
score: 0
type: Comment
type: QuestionComment
has text: There's definitely a good duplicate question with a great answer, but the short version is: `sorted(listodicts, key=operator.itemgetter('id'))`
comment on: http://stackoverflow.com/q/51882756

http://stackoverflow.com/a/51799016
score: 3
downvote count: 0
upvote count: 3
has body: Use the difference operator -: only_odd = odd - even
type: Answer
answers question: http://stackoverflow.com/q/51798955
has comment: http://stackoverflow.com/comment/90555479

http://stackoverflow.com/a/73352657
score: 147
downvote count: 1
upvote count: 148
has comment: http://stackoverflow.com/comment/134842823
has comment: http://stackoverflow.com/comment/136961266
type: Answer
answers question: http://stackoverflow.com/q/51845562
has body: As of v2022.8.13 of pipenv, the "old" lock -r functionality has been removed. Going forward, this should be accomplished with: pipenv requirements > requirements.txt

http://stackoverflow.com/q/51858427
type: Question
has body: For a small language I want to parse expressions of the form "X [Y,Z,V]" where X, Y, Z, V are natural numbers. Below is my attempt. from pyparsing import * class Y(): def __init__(self, ls): self.ls = ls def MakeCombinedList(tokens): print(len(tokens)) # prints 4 print(tokens) # [5, 1, 2, 3] clist = tokens[1] clist.append(tokens[0]) # 'int' attribute object has no attribute 'append' return clist def MakeIntList(tokens): nlist = tokens[0].split(",") ilist = [] for n in nlist: ilist.append(int(n)) return ilist def MakeY(tokens): Yobj = Y(tokens[0]) return Yobj LEFT_BRACK = Suppress(Literal("[")) RIGHT_BRACK = Suppress(Literal("]")) NATURAL = Word(nums).addParseAction(lambda n: int(n[0])) NATURAL_LIST = delimitedList(NATURAL, combine = True) NATURAL_VEC = LEFT_BRACK + NATURAL_LIST + RIGHT_BRACK NATURAL_VEC.addParseAction(MakeIntList) X = NATURAL + NATURAL_VEC X.addParseAction(MakeCombinedList) Y = X Y.addParseAction(MakeY) print(Y.parseString("5 [1,2,3]").ls) MakeIntList is supposed to transform a string such as "1,2,3" into the list [1,2,3]. MakeCombinedList is then supposed to append an integer to this list, but the tokens received by MakeCombinedList are not the single integer and the integer list created from MakeIntList, but a list of all the integers, as indicated by my comment. How can I make tokens[1] inside MakeCombinedList be the result of calling MakeIntList?
upvote count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/51869793
favorite count: 0
has title: Pyparsing parseaction and lists typerror
answer count: 1
tagged with: python
type: AnsweredQuestion
score: 1
accepted answer: http://stackoverflow.com/a/51869793
has comment: http://stackoverflow.com/comment/90669354
tagged with: pyparsing

http://stackoverflow.com/a/70711397
has comment: http://stackoverflow.com/comment/140040766
has body: My solution: add a value: int without any init to Mixin class: class MultiplicatorMixin: value: int def multiply(self, m: int) -&gt; int: return self.value * m class AdditionMixin: value: int def add(self, b: int) -&gt; int: return self.value + b class MyClass(MultiplicatorMixin, AdditionMixin): def __init__(self, value: int) -&gt; None: self.value = value instance = MyClass(10) print(instance.add(2)) print(instance.multiply(2))
answers question: http://stackoverflow.com/q/51930339
has comment: http://stackoverflow.com/comment/137040113
downvote count: 1
has comment: http://stackoverflow.com/comment/128757084
type: Answer
upvote count: 4
score: 3

google-oauth
type: Tag
tags question: http://stackoverflow.com/q/51881430
tags question: http://stackoverflow.com/q/51828397
tags question: http://stackoverflow.com/q/51912331
tag name: google-oauth

http://stackoverflow.com/a/51916006
has comment: http://stackoverflow.com/comment/90782893
has comment: http://stackoverflow.com/comment/90785214
score: 20
has comment: http://stackoverflow.com/comment/90791618
has comment: http://stackoverflow.com/comment/90785647
upvote count: 20
has comment: http://stackoverflow.com/comment/90799312
has comment: http://stackoverflow.com/comment/129260948
has comment: http://stackoverflow.com/comment/109668258
has comment: http://stackoverflow.com/comment/90797962
has comment: http://stackoverflow.com/comment/90800793
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/51915174
has comment: http://stackoverflow.com/comment/90782000
has comment: http://stackoverflow.com/comment/90791687
has body: Using py3-zmq (renamed py3-pyzmq before August 2022) package From my experience, python:3.6-alpine is not well suited for installing packages with C extensions because of missing Python headers. The alpine images already offer a Python 3.6 distribution and also a precompiled pyzmq package, so it's already sufficient to do: FROM alpine:edge RUN apk update && apk add py3-pyzmq CMD ["/bin/sh"] Check: $ docker run --rm -it my/alpine /bin/sh / # python3 -c "import zmq; print(zmq.__version__)" 17.1.0 This is the easiest and most reliable way to install pyzmq in an Alpine container. Building from source with pip install Alpine is not manylinux1-compatible, so any package containing C extensions must be built from source. This means you have to install the build tools first. Again, I'd use alpine image instead of python:3.6-alpine: FROM alpine:edge RUN apk update && apk add build-base libzmq musl-dev python3 python3-dev zeromq-dev RUN pip3 install pyzmq # reduce image size by cleaning up the build packages RUN apk del build-base musl-dev python3-dev zeromq-dev CMD ["/bin/sh"] Check: $ docker run --rm -it my/alpine /bin/sh / # python3 -c "import zmq; print(zmq.__version__)" 17.1.0 If you insist on python:3.6-alpine Beware that python:3.6-alpine does not install Python via apk, it has Python built from source and located under /usr/local. So when you inherit from python:3.6-alpine, install python3-dev and run pip install pyzmq, you'll end up with building pyzmq for Python 3.6.6 (coming from python:3.6-alpine) using header files from Python 3.6.4 (coming from apk add python3-dev). In general, this shouldn't be an issue (header files are incompatible only between major Python releases), but may become an issue in case the header files were adapted by the distro maintainer. Edit: exact steps to reproduce, with log $ docker image rm my/alpine:latest Untagged: my/alpine:latest Deleted: sha256:2e613cdc3c90c9d44b23d399bd44069217e5b31c1b4a8fc91e501c5226a4ef6a Deleted: sha256:d66ac6c9…
has comment: http://stackoverflow.com/comment/129260814
has comment: http://stackoverflow.com/comment/90799231

http://stackoverflow.com/comment/90765463
comment on: http://stackoverflow.com/q/51907546
type: Comment
has text: lol, {u'success': False, u'error': {u'info': u'Access Restricted - Your current Subscription Plan does not support this API Function.', u'code': 105, u'type': u'function_access_restricted'}} so I need to upgrade my plan i guess?...
score: 0
type: QuestionComment

gis
tags question: http://stackoverflow.com/q/51808969
tag name: gis
tags question: http://stackoverflow.com/q/51907699
type: Tag

http://stackoverflow.com/q/51862462
accepted answer: http://stackoverflow.com/a/51862719
has comment: http://stackoverflow.com/comment/90677421
has comment: http://stackoverflow.com/comment/90678153
favorite count: 0
has body: According to the documentation: Once an iterator’s __next__() method raises StopIteration, it must continue to do so on subsequent calls. Implementations that do not obey this property are deemed broken. However, for file-objects: &gt;&gt;&gt; f = open('test.txt') &gt;&gt;&gt; list(f) ['a\n', 'b\n', 'c\n', '\n'] &gt;&gt;&gt; next(f) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; StopIteration &gt;&gt;&gt; f.seek(0) 0 &gt;&gt;&gt; next(f) 'a\n' Are file-object iterators broken? Is this just one of those things that can't be fixed because it would break too much existing code that relies one it?
upvote count: 14
tagged with: python
has answer: http://stackoverflow.com/a/53069283
has comment: http://stackoverflow.com/comment/90677680
has title: Is the File-Object iterator "broken?"
has comment: http://stackoverflow.com/comment/90677332
has comment: http://stackoverflow.com/comment/90677528
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/53069283
score: 12
type: Question
tagged with: iterator
downvote count: 2
has answer: http://stackoverflow.com/a/51862719
answer count: 2

http://stackoverflow.com/comment/90752167
has text: @BryanOakley the toplevel just doesn't respond. I can click on the buttons but it doesn't do anything. The values in the textboxes don't get updated
comment on: http://stackoverflow.com/q/51899959
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90796916
type: QuestionComment
has text: Still no clue on what happened, same error here. :(
type: Comment
comment on: http://stackoverflow.com/q/51923086
score: 0

http://stackoverflow.com/comment/90845029
type: QuestionComment
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51947561
has text: @LaurenzAlbe with b_tree query is still very very slow and takes tens of minutes to perform

http://stackoverflow.com/q/51873354
has body: I have written the following code to import values from a csv file: directory = os.path.join("fileLocation") file = 'fileName.csv' filename = directory + file datafile = open(filename,'r') reader = csv.reader(datafile) data1 = [] for row in reader: data1.append(float(row[0])) resistance_values = np.array(data1) the .csv file has values that are structured as follows: 0 19,54091284 31,73614448 ... I would like the data imported in to python as a list of floats such as this: 0.0 19.54091284 31.73614448 ... Currently the values are being rounded to look like this: 0.0 19.0 31.0 ... How can I avoid this rounding issue?
has answer: http://stackoverflow.com/a/51874010
upvote count: 1
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/90698472
favorite count: 0
has answer: http://stackoverflow.com/a/51873523
accepted answer: http://stackoverflow.com/a/51873523
has title: excel.csv file rounding issue when importing to Python
tagged with: python
answer count: 4
has answer: http://stackoverflow.com/a/51873777
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51873642
downvote count: 0
score: 1
possible better answer: http://stackoverflow.com/a/51873777
type: Question
has comment: http://stackoverflow.com/comment/90698432

http://stackoverflow.com/q/51903394
score: -1
tagged with: logical-operators
tagged with: while-loop
has comment: http://stackoverflow.com/comment/90758439
answer count: 1
has comment: http://stackoverflow.com/comment/90758037
has comment: http://stackoverflow.com/comment/90757836
favorite count: 0
tagged with: python-3.x
downvote count: 2
has body: Code from "Think Like a Computer Scientist: Python" def find(astring, achar): ix = 0 found = False while ix &lt; len(astring) and not found: if astring[ix] == achar: found = True else: ix = ix + 1 if found: return ix else: return -1 I've run this through CodeLens in all variations of location of not and original value for found, but cannot wrap my head around the way Python handles its conditions in this form. Please point out where my train of thought goes wrong or what I miss: If found = False, then not found = True when found = True. The condition is set to not found so the loop will iterate. (I set the condition to found and it does not iterate. So while loops must only iterate for True values). Once achar is found in astring, found = True. What is the logic behind this closing the loop? Where is my misunderstanding of the use of not?
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/90758012
has comment: http://stackoverflow.com/comment/90757845
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90758227
type: Question
has title: Explanation of While Loop Using the Logical Operator "not"
has answer: http://stackoverflow.com/a/51903599
accepted answer: http://stackoverflow.com/a/51903599

encoder-decoder
type: Tag
tags question: http://stackoverflow.com/q/51847674
tag name: encoder-decoder

http://stackoverflow.com/comment/90777326
type: Comment
comment on: http://stackoverflow.com/a/51913618
has text: How do I fix the StringVar problem between the two roots
score: 0
type: AnswerComment

http://stackoverflow.com/q/51827474
score: 1
type: Question
has body: Hey guys I am currently having a problem where I am trying to do an import and I come across two problems within in my code where it says this: Skip loading non-existent .env file /notebooks/app/.env File "/notebooks/app/aime/predict/multimodal_aime_zeke_single_qs.py", line 35, in &lt;module&gt; from app.aime.keras.callback.lightweight_progress_bar import LightweightProgressBar File "/notebooks/app/aime/keras/callback/lightweight_progress_bar.py", line 5, in &lt;module&gt; from keras.callbacks import Callback ImportError: No module named 'keras' And I then use this command: pip list | grep -i keras To realize that I do have keras listed from the command: Keras (2.2.2) Keras-Applications (1.0.4) Keras-Preprocessing (1.0.2) Can someone help please? Thanks!
has answer: http://stackoverflow.com/a/54900550
tagged with: keras
linked to: http://stackoverflow.com/q/39930952
answer count: 2
upvote count: 1
has answer: http://stackoverflow.com/a/51827725
favorite count: 0
type: UnansweredQuestion
has title: ImportError: No module named 'keras' in Pycharm
has comment: http://stackoverflow.com/comment/90609258
tagged with: python
has comment: http://stackoverflow.com/comment/90610577
downvote count: 0

http://stackoverflow.com/comment/91078859
has text: I was troubleshooting a script that seemed to quit working when the hold calls were removed. Today the simple plot example worked until the problem script ran; then the simple script would print only the last .plot line.
score: 0
comment on: http://stackoverflow.com/q/51865607
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91227088
score: 0
type: QuestionComment
has text: Have you solved this issue? I just installed the GPU version (which upgraded TF to 1.10 from 1.8) and I get the DLL load failed error. I suspect that there is a problem with 1.10
comment on: http://stackoverflow.com/q/51924849
type: Comment

http://stackoverflow.com/comment/90805764
type: Comment
score: 3
comment on: http://stackoverflow.com/a/51927865
type: AnswerComment
has text: @tobias_k If we're going full pedant, `list` and `tuple` are classes whose instances are iterables ;)

http://stackoverflow.com/q/51934528
has answer: http://stackoverflow.com/a/77945591
linked to: http://stackoverflow.com/q/3701646
answer count: 6
has comment: http://stackoverflow.com/comment/90823174
has body: I have python versions 3.6.5_1 and 3.7.0installed via Homebrew. jupyter needs python3.6 for launching. It wouldn't start if I switch to python3.7. After launching, it fails to start the kernel with this error: File "/usr/local/Cellar/python/3.6.5_1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/subprocess.py", line 1344, in _execute_child raise child_exception_type(errno_num, err_msg, err_filename) FileNotFoundError: [Errno 2] No such file or directory: '/usr/local/opt/python/bin/python3.7': '/usr/local/opt/python/bin/python3.7' From what I understand, the kernel is looking for python3.7. My kernel list has just python3 $jupyter kernelspec list Available kernels: python3 /usr/local/etc/jupyter/kernels/python3 I looked at this link on github, but it wasn't helpful. How do I make jupyter and the kernel running on the same python version?
has answer: http://stackoverflow.com/a/68260362
has answer: http://stackoverflow.com/a/66761102
downvote count: 0
has comment: http://stackoverflow.com/comment/90819365
tagged with: kernel
tagged with: jupyter-notebook
favorite count: 0
has comment: http://stackoverflow.com/comment/120640220
has comment: http://stackoverflow.com/comment/90822110
has answer: http://stackoverflow.com/a/51937017
tagged with: python
score: 19
type: AnsweredQuestion
upvote count: 19
has answer: http://stackoverflow.com/a/54917829
accepted answer: http://stackoverflow.com/a/51937017
has comment: http://stackoverflow.com/comment/90819421
has title: Failed to start the kernel on jupyter notebook
type: Question
possible better answer: http://stackoverflow.com/a/54917829
has answer: http://stackoverflow.com/a/52988093
has comment: http://stackoverflow.com/comment/90819801

http://stackoverflow.com/a/51953059
has comment: http://stackoverflow.com/comment/90856479
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51953018
answers question: http://stackoverflow.com/q/51953018
upvote count: 2
has comment: http://stackoverflow.com/comment/90856499
type: Answer
has body: First note your input isn't syntactically correct Python. Once you have correctly defined a list of np.ndarray objects, you can use sum with a generator expression: L = [np.array([[1,2],[3,4],[5,6],[7,8],[9,10]]), np.array([[1,2],[1,2]]), np.array([[1,2,3,4,5],[3,4,5,6,7]]), np.array([1,2])] res = sum(i.sum() for i in L) # 104 In addition, never shadow built-ins, so don't name your variables list or sum. If one of your 2 dimensions are the same size across all your arrays, you can combine them into a single array and then use a vectorised method: L = [np.array([[1,2],[3,4],[5,6],[7,8],[9,10]]), np.array([[1,2],[1,2]]), np.array([[1,3],[2,4],[3,5],[4,6],[5,7]]), np.array([1,2])] res = np.vstack(L).sum() # 104
score: 2

http://stackoverflow.com/comment/90641456
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/51833758
score: 0
has text: Your description of `map` and `input` applies to Python 2, not Python 3 (which the OP is asking about).

http://stackoverflow.com/comment/90883753
type: AnswerComment
type: Comment
has text: This is just an attempt at indirectly self-promoting your own software.
score: 0
comment on: http://stackoverflow.com/a/51855880

http://stackoverflow.com/q/51929887
type: AnsweredQuestion
downvote count: 0
score: 1
has title: '<' not supported between instances of 'method' and 'method' - Python, Django
has answer: http://stackoverflow.com/a/51929973
accepted answer: http://stackoverflow.com/a/51929973
duplicate of: http://stackoverflow.com/q/75271187
has comment: http://stackoverflow.com/comment/90809560
has comment: http://stackoverflow.com/comment/90809709
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/90809637
upvote count: 1
has comment: http://stackoverflow.com/comment/90809773
linked to: http://stackoverflow.com/q/75271187
has comment: http://stackoverflow.com/comment/90809710
has answer: http://stackoverflow.com/a/51930205
favorite count: 0
has comment: http://stackoverflow.com/comment/90809406
tagged with: django
tagged with: python
possible better answer: http://stackoverflow.com/a/51930205
has body: I'm trying to do Winerama Recommender Tutorial . I met a error which I can't solve. When I try to go to the tab 'recommendation list' the browser returned the following error. Error Environment: Request Method: GET Request URL: http://127.0.0.1:8000/recommendation/ Django Version: 2.0.7 Python Version: 3.7.0 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'bootstrap3', 'reviews', 'registration'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "C:\Users\tymot\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py" in inner 35. response = get_response(request) File "C:\Users\tymot\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response 128. response = self.process_exception_by_middleware(e, request) File "C:\Users\tymot\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response 126. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\tymot\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view 21. return view_func(request, *args, **kwargs) File "C:\Users\tymot\Desktop\Cd-12.50-20.08\env\my_app\winerama\reviews\views.py" in user_recommendation_list 89. reverse=True Exception Type: TypeError at /recommendation/ Exception Value: '&lt;' not supported between instances of 'method' and 'method' I created everything according to the steps in the tutorial. File …

http://stackoverflow.com/comment/90756134
comment on: http://stackoverflow.com/q/51902100
score: 0
type: Comment
type: QuestionComment
has text: What are you really trying to do? This sort of sounds like you want to have multiple threads or coroutines, but strictly control their execution at a very low level. What rules would decide which thing gets to execute next?

http://stackoverflow.com/comment/90752418
type: QuestionComment
has text: If the script only uses a relative path to the file then the script will have to be run in the same directory as the target file
score: 0
comment on: http://stackoverflow.com/q/51900640
type: Comment

http://stackoverflow.com/a/51929370
has comment: http://stackoverflow.com/comment/90810764
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51929238
has comment: http://stackoverflow.com/comment/90811845
has comment: http://stackoverflow.com/comment/90811481
has body: You can convert to str and join with whitespace before passing to pd.to_datetime: df['datetime'] = pd.to_datetime(df['day'].astype(str) + ' ' + df['time'].astype(str)) print(df, df.dtypes, sep='\n') # day time datetime # 0 2018-01-01 15:00:00 2018-01-01 15:00:00 # 1 2015-12-30 05:00:00 2015-12-30 05:00:00 # day datetime64[ns] # time object # datetime datetime64[ns] # dtype: object Setup from datetime import datetime df = pd.DataFrame({'day': ['2018-01-01', '2015-12-30'], 'time': ['15:00', '05:00']}) df['day'] = pd.to_datetime(df['day']) df['time'] = df['time'].apply(lambda x: datetime.strptime(x, '%H:%M').time()) print(df['day'].dtype, type(df['time'].iloc[0]), sep='\n') # datetime64[ns] # &lt;class 'datetime.time'&gt; Complete example including seconds: import pandas as pd from io import StringIO x = StringIO(""" ActStartDateExecution ActStartTimeExecution 0 2016-02-17 11:00:00 10 2016-04-15 07:15:00 20 2016-06-10 10:30:00""") df = pd.read_csv(x, delim_whitespace=True) df['ActStartDateExecution'] = pd.to_datetime(df['ActStartDateExecution']) df['ActStartTimeExecution'] = df['ActStartTimeExecution'].apply(lambda x: datetime.strptime(x, '%H:%M:%S').time()) df['datetime'] = pd.to_datetime(df['ActStartDateExecution'].astype(str) + ' ' + df['ActStartTimeExecution'].astype(str)) print(df.dtypes) ActStartDateExecution datetime64[ns] ActStartTimeExecution object datetime datetime64[ns] dtype: object
downvote count: 0
has comment: http://stackoverflow.com/comment/90810816
has comment: http://stackoverflow.com/comment/90811501
type: Answer

http://stackoverflow.com/comment/90556241
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51799843
type: Comment
has text: the thing is tensorflow variable seems to be not iterative so I think you can enumerate each value in the variable

http://stackoverflow.com/comment/90635940
comment on: http://stackoverflow.com/a/51837932
score: 0
type: AnswerComment
has text: This is an answer that works, but I think there must be better solutions. One problem with my answer is that when I save the figure, I get a big white space in the saved plot (corresponding to the axes that I set their visibility to False) that I do not see in jupyter notebooks when I am running the code. If FacetGrid just plots the dataframe that I am giving it as the input (in this case ```X```), there would have been no problem anymore. There should be a way to do that.
type: Comment

http://stackoverflow.com/comment/90672903
comment on: http://stackoverflow.com/a/51860232
type: Comment
has text: @Py.rookie89 no need for a function using this method
score: 1
type: AnswerComment

http://stackoverflow.com/q/51945646
favorite count: 0
tagged with: dask
tagged with: pandas
tagged with: python
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/52137286
accepted answer: http://stackoverflow.com/a/52137286
type: Question
score: 1
has body: In pandas there is the between_time method however my dataset is too large for pandas, however doing a quick control f in the Dask api shows 4 mentions for between_time but no actual use of it. I just get a lovely: AttributeError: 'Series' object has no attribute 'between_time'. Does it actually exist? Is there a workaround?
upvote count: 1
has title: Dask Does between_time exist?
answer count: 1

http://stackoverflow.com/q/51946545
score: 0
has comment: http://stackoverflow.com/comment/90874157
accepted answer: http://stackoverflow.com/a/53706214
has title: how to store the dictionary in genism which has been created for the specific dataset?
tagged with: python
tagged with: dictionary
tagged with: lda
type: AnsweredQuestion
has body: How to store the dictionary in genism? Which has been created for a specific dataset for performing to LDA.i'm using mac os. This is my current code: dictionary=corpora.Dictionary(texts) dictionary.save(Macintosh_HD.Users.srinivasan(bin,'creation.dict'))
tagged with: topic-modeling
type: Question
has answer: http://stackoverflow.com/a/53706214
answer count: 1

http://stackoverflow.com/q/51893225
score: 3
upvote count: 3
has answer: http://stackoverflow.com/a/51893499
has title: How to store an array of users in django?
has comment: http://stackoverflow.com/comment/90737232
type: Question
has answer: http://stackoverflow.com/a/51893414
has body: I have a django model which is basically a group called Contexts.It contains some fields like name, description and a user.Below is the model defined class Contexts(models.Model): context_name = models.CharField(max_length=50) context_description = models.TextField() users = models.CharField(max_length=255, null=False) Currently there is only one user per Context.But I want to add more users to the same Context.So now I want to change the users field to an array field.By the way I am using django + postgres. So this is what I do class Contexts(models.Model): context_name = models.CharField(max_length=50) context_description = models.TextField() users = ArrayField(ArrayField(models.TextField())) But then how do I append users to the users field?This is what I do normally to add a context @csrf_exempt def context_operation(request): user_request = json.loads(request.body.decode('utf-8')) if request.method == "POST": try: if user_request.get("action") == "add": print("add") conv = Contexts.objects.create( context_name=user_request.get("context_name"), context_description=user_request.get("context_description"), users=user_request.get("user") ) except Exception as e: print("Context saving exception", e) return HttpResponse(0) return HttpResponse(1) But how do I append one user at a time to the users field in the same context (assuming same context name is passed)?
answer count: 2
downvote count: 0
linked to: http://stackoverflow.com/q/51810439
favorite count: 0
type: UnansweredQuestion
tagged with: django
tagged with: python

http://stackoverflow.com/comment/90782664
comment on: http://stackoverflow.com/q/51915908
score: 0
type: QuestionComment
type: Comment
has text: It works fine while sharing between same interpreters. Right now I want to share it between pyspark and python

http://stackoverflow.com/a/51942428
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/90834353
type: Answer
upvote count: 2
has body: You can pass custom colors to df.plot: df = pd.DataFrame({"lab":["A","B","C"], "val":[10,20,30]}) df.plot.bar(x="lab", y="val", rot=0, color = ["y","c","m"]) Result: Here is a LINK to the some more about the one-letter color abbreviations
answers question: http://stackoverflow.com/q/51942096

http://stackoverflow.com/comment/90677286
score: 1
has text: *whistle* +1 nice!
comment on: http://stackoverflow.com/a/51862471
type: AnswerComment
type: Comment

http://stackoverflow.com/q/51956476
has comment: http://stackoverflow.com/comment/91391783
type: Question
upvote count: 15
has comment: http://stackoverflow.com/comment/91473867
answer count: 1
tagged with: javascript
has comment: http://stackoverflow.com/comment/91523942
favorite count: 0
has body: I've created a JavaScript extension for my Jupyter Notebook that will plot some data for me. Right now I have the data hardcoded within the extension. My question: is there a way to access a data object that exists within the Notebook? For example, below is some sample code for an extension: define([ 'base/js/namespace' ], function( Jupyter ) { function test_second_extension() { var handler = function () { console.log( 'This is the current notebook application instance:', Jupyter.notebook ); var data = [{"x": 1, "y": 5}, {"x": 2, "y":12}, {"x": 3, "y": 27}]; console.log(data); }; var action = { icon: 'fa-comment-o', // a font-awesome class used on buttons, etc help : 'Print notebook instance', help_index : 'zz', handler : handler }; var prefix = 'test_second_extension'; var action_name = 'show-alert'; var full_action_name = Jupyter.actions.register(action, action_name, prefix); // returns 'my_extension:show-alert' Jupyter.toolbar.add_buttons_group([full_action_name]); } return { load_ipython_extension: test_second_extension }; }); And this is what I have in a Python3 Jupyter cell: import pandas as pd data = pd.read_json('[{"x": 1, "y": 5}, {"x": 2, "y":12}, {"x": 3, "y": 27}]') Is there a way to access the data object that is created in the Jupyter cell from within the extension, instead of hardcoding it?
tagged with: python
has comment: http://stackoverflow.com/comment/91473720
has answer: http://stackoverflow.com/a/52337409
has title: Access data object in Jupyter extension
tagged with: jupyter-notebook
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91330836
downvote count: 1
score: 14
linked to: http://stackoverflow.com/q/42773092

http://stackoverflow.com/a/51814479
score: -1
has body: I would recommend you use os.startfile. You have to import os then say I had a file in a directory path C:\Users\me\Videos Then I would do, os.startfile('C:\Users\me\Videos'). This is if you are on Windows, if you are not, don't include the 'C:\' in that. If you get a unicode error in the path, use double backslashes. os.startfile('C:\\Users\\me\\Videos')
has comment: http://stackoverflow.com/comment/90583598
has comment: http://stackoverflow.com/comment/90583616
downvote count: 1
has comment: http://stackoverflow.com/comment/90583582
type: Answer
upvote count: 0
answers question: http://stackoverflow.com/q/51814397

http://stackoverflow.com/comment/90619675
type: QuestionComment
comment on: http://stackoverflow.com/q/51831970
score: 1
has text: Should capitalize `Submit`, rather than `submit`?
type: Comment

relative-path
type: Tag
tag name: relative-path
tags question: http://stackoverflow.com/q/51910966

http://stackoverflow.com/q/51899207
tagged with: exe
has title: Pyinstaller - convert python to exe from Linux
tagged with: pyinstaller
has answer: http://stackoverflow.com/a/51899289
tagged with: python
accepted answer: http://stackoverflow.com/a/51899289
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90749420
type: Question
has body: I want to convert one .py file to .exe from Linux Ubuntu. I found pyinstaller for this. But when pyinstaller runs from Linux it makes file executable only for Linux and when pyinstaller runs from Windows it makes .exe file for Windows. I want to convert .exe file from Linux for Windows. So how can i make it? I need an instruction. P.S: if i cannot do it with pyinstaller, please write other tool.
answer count: 1
has comment: http://stackoverflow.com/comment/90749342
score: 0
has comment: http://stackoverflow.com/comment/90749373
tagged with: windows
has comment: http://stackoverflow.com/comment/90749439
linked to: http://stackoverflow.com/q/2950971

http://stackoverflow.com/a/51927526
downvote count: 0
type: Answer
upvote count: 6
accepted answer of: http://stackoverflow.com/q/51897756
score: 6
answers question: http://stackoverflow.com/q/51897756
has body: You are not getting that content because, when you execute the request, it is not present in the page. Yet. If you check the javascript code between the script tags, you can see it is generating the table dynamically. So, you receive the html code before that has happened, since requests is not a browser and won't execute the js, and you don't get to see the table. Now that you know why you can't see the table, your next problem is how to get the HTML produced after the javascript execution. Don't faint, it is feasible. You might find the solutions in this question interesting. Good luck
has comment: http://stackoverflow.com/comment/90805963
type: AcceptedAnswer

http://stackoverflow.com/a/51799303
has body: You could analyse the code in a python console (just execute python at the shell command line), and find some problems: First, an import is missing at the top of the code: import time, os Second, the db variable is not set, I guess this should be DB_NAME. A good practice in python is to concatenate strings by using %-formatting: dumpcmd = "mysqldump -h %s -u %s -p%s %s &gt; %s/%s.sql" % (DB_HOST,DB_USER,DB_USER_PASSWORD,DB_NAME,TODAYBACKUPPATH,DB_NAME,) Finally, as a hint, add print dumpcmd and test the command manually. Keep in mind that the path should be created first, or replace the / by - for the filename.
has comment: http://stackoverflow.com/comment/90555246
answers question: http://stackoverflow.com/q/51798975
score: 1
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/90555260
has comment: http://stackoverflow.com/comment/90556582
upvote count: 1

http://stackoverflow.com/q/51835552
has body: I have a dataframe with +60 columns. I need to group by two columns, and only need one column values summed. The problem is if I don't manually type the names of all the column labels in the groupby statement, columns not included will not appear in the output. Instead of something like this: df_final.groupby(by=['OrderNo','ItemSKU','CustName',.......'20th Column'],as_index=False).sum() I'd like to do something like this: df_final.groupby(by=[:20],as_index=False).sum() How can I do this and avoid typing all those column names? Here is a print of the column datatypes: &gt;&gt;&gt; print(df_final.dtypes) OrderNo float64 PledgeID int64 ReferrerID float64 FulfillmentStatus object FundingDate object PaymentMethod float64 Appearance object Name object Email object Amount object PlatformFee object PerkID float64 Perk object ShippingName object ShippingPhoneNumber object ShippingAddress object ShippingAddress2 object ShippingCity object ShippingState/Province object ShippingZip/PostalCode object ShippingCountry object ItemSKU object ArticleName object UPC float64 ArticleQty int64 dtype: object &gt;&gt;&gt;
has answer: http://stackoverflow.com/a/51835582
type: Question
tagged with: pandas
tagged with: python
favorite count: 0
has title: Group many columns by index instead of by label in a pandas Groupby statement
upvote count: 1
answer count: 1
tagged with: group-by
type: UnansweredQuestion
downvote count: 0
score: 1

http://stackoverflow.com/comment/90670697
has text: @C.Nivs I think the problem is only with installing flask, but I installed it. How to check that python executable pointing to the right site-packages?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51849725

http://stackoverflow.com/a/51878571
type: Answer
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/90768684
upvote count: 1
has body: def magic_zip(*lists): max_len = max(map(len, lists)) return zip(*([None] * (max_len - len(l)) + l for l in lists))
answers question: http://stackoverflow.com/q/51878354

forms
tags question: http://stackoverflow.com/q/51852574
type: Tag
tags question: http://stackoverflow.com/q/51826146
tags question: http://stackoverflow.com/q/51831995
tags question: http://stackoverflow.com/q/51803008
tag name: forms
tags question: http://stackoverflow.com/q/51804917
tags question: http://stackoverflow.com/q/51814971

http://stackoverflow.com/comment/90718593
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51883382
has text: can u give an example of what do you mean by switching .Which view you hitted first and then which one

http://stackoverflow.com/q/51854716
upvote count: 0
score: -2
answer count: 1
tagged with: token
favorite count: 0
has answer: http://stackoverflow.com/a/51854752
type: UnansweredQuestion
has title: how to create temporary tokens django
downvote count: 2
tagged with: django
tagged with: python
has body: I have found that we can make temporary tokens with this in Django : pip install Django-rest-framework-temporary-tokens but I don't know how to use this method. does anybody know how to use this or any other way to make temporary tokens in Django ??
type: Question

http://stackoverflow.com/comment/90644589
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51845385
has text: Yeah, I'm a newbie. def sel-replace(variable-name):

http://stackoverflow.com/comment/90800801
comment on: http://stackoverflow.com/q/51925284
score: 0
type: Comment
type: QuestionComment
has text: @needtobe added conf.py, but it doesn't have anything extraordinary. It's only classes with ready-to-send responses. It works properly with any other part of the project.

http://stackoverflow.com/comment/90709994
type: Comment
type: QuestionComment
has text: Yes, i did it with bat file... and .bat activate virtualenv and execute my script python
comment on: http://stackoverflow.com/q/51845668
score: 0

http://stackoverflow.com/comment/90705345
type: Comment
type: QuestionComment
has text: If you're attempting to check every single uppercase/lowercase possibility (i.e. brute force), you'll be banned by the servers due to a potential DoS threat much before you obtain the package you're looking for. If you can't have a reproducible pattern to check against, I'd suggest you to rethink the goals of your project.
score: 1
comment on: http://stackoverflow.com/q/51876852

http://stackoverflow.com/comment/90861624
comment on: http://stackoverflow.com/q/51955386
type: Comment
type: QuestionComment
score: 1
has text: You are correct, I will fix it. Thank you for catching it.

http://stackoverflow.com/comment/90684102
score: 3
comment on: http://stackoverflow.com/q/51865905
has text: This code does not run. It has syntax errors. E.g. `execut main:` is definitely not valid Python code. Please read [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) and modify your question accordingly.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90830833
type: Comment
has text: thanks that fixed it. seriously was going crazy. Just so I understand... is topic.id being compared to entry_id?
comment on: http://stackoverflow.com/a/51940461
score: 0
type: AnswerComment

http://stackoverflow.com/comment/90746673
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51897251
has text: I have to check 1 Linesegment against all the coastline-segments very often (+ 10^6 times). The coastline-segments do not change, but AB is altered and can not be collected in an array, because it is determined dynamically.

http://stackoverflow.com/q/51879628
has title: How to write 2 lists of items in 2 columns instead of 2 arrays?
answer count: 4
favorite count: 0
has body: I ran my code and got 2 lists like this: and what I need to do is put them in a .csv file. but I got an output that looks ugly like this: The correct one should be like this: So what should I do to solve that problem? code: from urllib.request import urlopen import urllib import re import csv def main(): html = urlopen("https://www.realestate.com.au/rent/with-1-bedroom-in-perth+-+greater+region%2c+wa/list-1?maxBeds=1&amp;source=location-search").read().decode('utf-8') csvfile=open('price.csv','w',newline='') #### check ##print(price(html)) ##print(postcode(html)) #### end check writer=csv.writer(csvfile) writer.writerow(['Postcode','Price']) data=[price(html),postcode(html)] writer.writerows(data) csvfile.close() def price(page): priceTextReg=re.compile(r"priceText\"&gt;(.+?)&lt;") priceText = re.findall(priceTextReg,page) p1=[] for i in range(20): ## we just need the first 20 items priceReg=re.compile(r"\d+") price=re.findall(priceReg,priceText[i]) p1.append(price[0]) return p1 def postcode(page): postcodeTextReg=re.compile(r"alt=.+?, WA (.+?)' title=") postcodeText=re.findall(postcodeTextReg,page) p2=[] for i in range(20): postcode=postcodeText[i] p2.append(postcode) return p2
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/51879704
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51879733
score: 1
has answer: http://stackoverflow.com/a/51879687
type: Question
has answer: http://stackoverflow.com/a/51879676
accepted answer: http://stackoverflow.com/a/51879704
possible better answer: http://stackoverflow.com/a/51879687
downvote count: 0

http://stackoverflow.com/comment/90683630
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51865372
has text: Yup that worked, and showed me that it was an unsupported format. Figured that these files are being opened with excel that I'd be able to take this approach.
score: 0

http://stackoverflow.com/comment/90938137
has text: sorry that was supposed to be des_content not content which is declared by getting the file from the file chooser of serialized text. Its in the open function.
comment on: http://stackoverflow.com/q/51922243
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51882540
tagged with: pandas
has title: How to access/split items in a column that contains a list
tagged with: python
accepted answer: http://stackoverflow.com/a/51882562
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51882589
has comment: http://stackoverflow.com/comment/90717082
has answer: http://stackoverflow.com/a/51882562
type: Question
has body: Let's say I received a dataset with a structure similar to this (I understand that this structure is not typical.) The following code is just to generate an example of a dataframe that looks like my data. tmp = pd.DataFrame( [ {'foo': 123, 'bar': [1, 2]}, {'foo': 456, 'bar': [1, 2]} ] ) foo item 0 123 [1, 2] 1 456 [1, 2] Is there an easy way to: access items in bar.. like df.bar[1], resulting in 2 ? (this clearly does not work) or split the bar column into something like bar.0, bar.1, etc.. Ideally, I would like to plot all items in bar[0] vs bar[1] Note the list in bar is not limited to 2 items and the number can vary a bit.
score: 0
possible better answer: http://stackoverflow.com/a/51882589
answer count: 2

http://stackoverflow.com/a/51948258
has comment: http://stackoverflow.com/comment/90846239
upvote count: 1
answers question: http://stackoverflow.com/q/51948191
has comment: http://stackoverflow.com/comment/90846140
type: Answer
has comment: http://stackoverflow.com/comment/90846512
score: -1
has body: Just download your image in your python directory and then copy it into the folder of your choice with shutil.copyfile() : from shutil import copyfile copyfile(src, dst)
downvote count: 2

http://stackoverflow.com/comment/90735466
score: 0
type: AnswerComment
has text: Tks for that fast response. Just implemented your fix and it works a dream. I'll go back to my model defn to do that naming change you advised. Tks again.
comment on: http://stackoverflow.com/a/51892254
type: Comment

http://stackoverflow.com/q/51864615
upvote count: 1
type: Question
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51864631
has title: Parsing a network address string
answer count: 1
downvote count: 0
favorite count: 0
tagged with: parsing
has answer: http://stackoverflow.com/a/51864631
tagged with: python
has body: I am using python 3.5 and have a network address string like the following: tcp://10.1.2.3:45678 I want to parse this string and extract the protocol, the ip address and the port number. I know I can do this very easily with a string split or regex, however I was wondering if there is a python package or module that does this. I am sure that there is a specification for these string which defines them, hence I am interested in a python module instead of using regex or string parsing.
score: 1

http://stackoverflow.com/q/51902001
has comment: http://stackoverflow.com/comment/90755212
type: Question
has comment: http://stackoverflow.com/comment/90756496
has comment: http://stackoverflow.com/comment/90755168
has comment: http://stackoverflow.com/comment/90758190
has comment: http://stackoverflow.com/comment/90758272
answer count: 1
has comment: http://stackoverflow.com/comment/90757596
score: 0
has comment: http://stackoverflow.com/comment/90759647
has body: I am uploading a file to a REST API with a Python 3 script via the windows command line. The filename is an argument passed in to the script. Everything works fine unless there is a space in the path name. i.e. c:\temp\myFolder\1.jpg works, but c:\temp\my Folder\1.jpg throws an error: raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) The code up until the error is as follows: def upload_photo(filename): f = open(filename, "rb") data = f.read() data_md5 = hashlib.md5(data).hexdigest() f.close() r = requests.put('https://upload.mysite.com/{}'.format(filename), data=data) response = json.loads(r.text) I'm not sure how to fix it. Thanks for the help. --Edit-- Full traceback c:\&gt;python test.py "c:/temp/my folder/1.jpg" Traceback (most recent call last): File "test.py", line 144, in &lt;module&gt; print(test(sys.argv[1])) File "test.py", line 132, in upload_photo response = json.loads(r.text) File "C:\Users\Default\AppData\Local\Programs\Python\Python37-32\lib\json\__init__.py", line 348, in loads return _default_decoder.decode(s) File "C:\Users\Default\AppData\Local\Programs\Python\Python37-32\lib\json\decoder.py", line 337, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "C:\Users\Default\Default\Local\Programs\Python\Python37-32\lib\json\decoder.py", line 355, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
has answer: http://stackoverflow.com/a/51902067
tagged with: python
has title: Python json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) with Spaces in path name
tagged with: python-3.x
type: UnansweredQuestion

where-clause
tags question: http://stackoverflow.com/q/51888197
tags question: http://stackoverflow.com/q/51814074
type: Tag
tags question: http://stackoverflow.com/q/51875755
tag name: where-clause

http://stackoverflow.com/q/51954820
tagged with: loops
downvote count: 1
type: Question
score: -1
has body: How to read and write all the file with *.txt extension in a loop. I would like to write output to same file name. My code: PWD1 = os.getcwd() f = open(PWD1+'/' +DirPath + ".txt", "r") g = open(PWD1+'/' +DirPath + ".txt", "w") for line in f: if line.strip(): g.write("\t".join(line.split()[2:]) + "\n") # removes first two columns from text file. A.close() f.close() g.close() text1.txt 2 33 /home/workspace/aba/abga 22 4 /home/home text2.txt 1 44 /home/workspace/aba/abga 24 5 /home/home desired output text1.txt /home/workspace/aba/abga /home/home text2.txt /home/workspace/aba/abga /home/home Please note that there are several .txt files in this directory. I would like to loop through all of them.
has comment: http://stackoverflow.com/comment/90860269
has comment: http://stackoverflow.com/comment/90860531
has title: python, read and write all the file with *.txt extension
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/90860319
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51954960
accepted answer: http://stackoverflow.com/a/51954960
upvote count: 0
has comment: http://stackoverflow.com/comment/90860344
linked to: http://stackoverflow.com/q/16208206
has comment: http://stackoverflow.com/comment/90860218

http://stackoverflow.com/comment/90861580
comment on: http://stackoverflow.com/a/51955485
type: Comment
has text: Thanks very much :)
score: 0
type: AnswerComment

http://stackoverflow.com/a/70770392
has body: This should solve your problem This is because the url is a https site instead of http. So it requires ssl verification using certificates. If you are working in your firms workstation, internal use sites will be accessible through the browser managed by your organization. The organization will have setup the certificates. Atleast these certificates are needed ROOT CA certificate Intermediate CA certificate Website ( domain ) certificate The browsers will have these certificates configured, but python will not. So you need to do some manual work to get it working. As Indranil suggests, using verify=False is not recommended. So download all the certificates as mentioned in the above link and follow the steps.
answers question: http://stackoverflow.com/q/51925384
downvote count: 2
type: Answer
score: 1
upvote count: 3

http://stackoverflow.com/a/51864058
type: Answer
has body: I have tested your code and it works perfectly fine in a Python webserver. I have started one with python -m http.server and placed an index.html in the same directory with some content before starting the server. and your code import time import urllib.request import io userurl='http://localhost:8000/index.html' def checksite(userurl): change=False u = urllib.request.urlopen(userurl) webContent1 = u.read() print(webContent1) time.sleep(15) u = urllib.request.urlopen(userurl) webContent2 = u.read() print(webContent2) if webContent1 == webContent2: print("Everything is normal") elif webContent1 !=webContent2: print("Warning, there has been a change to the webite!") change=True return change checksite(userurl) and output b' \n\t Hello \n\t \n\t\tTesting, Webcontent1 \n\t \n\t \n\n' b' \n\t Hello \n\t \n\t\tTesting, Webcontent2\n\t \n\t \n\n' Warning, there has been a change to the webite! [Finished in 17.5s] Your code is perfectly fine.
upvote count: 1
answers question: http://stackoverflow.com/q/51863740
downvote count: 0
score: 1

http://stackoverflow.com/q/51928038
type: Question
has comment: http://stackoverflow.com/comment/90805992
tagged with: max
linked to: http://stackoverflow.com/q/15741759
has comment: http://stackoverflow.com/comment/90805990
has comment: http://stackoverflow.com/comment/90806523
linked to: http://stackoverflow.com/q/17193850
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/90806307
has comment: http://stackoverflow.com/comment/90805832
answer count: 1
has answer: http://stackoverflow.com/a/51928670
has title: Filter column maximum value and respective row value pandas
has comment: http://stackoverflow.com/comment/90805933
type: UnansweredQuestion
tagged with: python
has body: I want to filter max value from 7th column and respective row (date and time) from bs4 import BeautifulSoup import pandas as pd import numpy as np import matplotlib.pyplot as plt #pd.set_option('display.max_columns', None) a = pd.read_html("D:\\abcd\New folder\PRTG Report AIRTEL-5PM to 9 PM 64-32768-32723.html", flavor='bs4',header=None) df0=a[0] df1=a[1] df2=a[2][https://i.sstatic.net/ZkbjT.png][1] df3=a[3] df=df0.append([df1,df2,df3]) df[df != 'Average'].iloc[:,[1,7]].dropna()
tagged with: dataframe

http://stackoverflow.com/comment/90802814
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51926426
has text: I don't think it's possible to have an exponential increase change when working between a fixed `start` and `end`. The problem is that you want different equations `y = Ab^x` but `A` and `b` are two variables dependent on `start` and `end` only. i.e. for any `start, end` you can always solve for the unique equation `y = f(x) = Ab^x` s.t. `f(0) = start` and `f(num_steps) = end`

http://stackoverflow.com/a/51913273
answers question: http://stackoverflow.com/q/51912284
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/90776824
upvote count: 3
downvote count: 1
has comment: http://stackoverflow.com/comment/90776951
has comment: http://stackoverflow.com/comment/90776994
has body: I doubt that you really do need, or want, to downgrade NumPy. But that's not what your question is really about. You want to know why pip is showing one thing and python is showing another, and what you can do about that. The reason you're seeing different things is that your pip doesn't go with your python. When you run python, that's your Python 2.7, and packages you import there come from your 2.7 library, at /usr/local/lib/python2.7/. When you run pip it's using your Python 3.4, and installing and looking for things in your Python 3.4's library, which is at /usr/local/lib/python3.4/. So, pip show numpy is showing you the version of NumPy your Python 3.4 has, which is completely independent of the version of NumPy your Python 2.7 has. If you didn't intend to use Python 2.7, the solution is to run Python 3.4 instead, usually just by using python3 instead of python. If you did intend to use Python 2.7, the solution is to use the pip that goes with it. You may have a command named pip2 or pip2.7 for this, but the safest way is to use python -m pip instead of pip. As a side note, given where your 3.4 NumPy is installed, it looks like you may have done something like apt-get python3-numpy or yum python-numpy or similar to install it, not pip install numpy. And probably something like apt-get python2-numpy to get the 2.7 version as well. If so, you may want to downgrade or upgrade it the same way you installed it in the first place, using your distro's package manager, instead of using pip. If not… then ignore this paragraph. If this all seems way too complicated, but you really do need to have both Python 2.7 and Python 3.4 around, there are two things you should consider: Always use virtual environments. Whenever possible, don't install anything globally; pick an environment to install it in. Whatever environment is active, python and pip will both be for that environment. Install the latest version of Anaconda, with the latest version of Python (3.7 as of today), th…
has comment: http://stackoverflow.com/comment/90776914

http://stackoverflow.com/comment/90756682
has text: Sorry Wiktor, only saw your comment once my answer was posted.
type: QuestionComment
comment on: http://stackoverflow.com/q/51902666
score: 0
type: Comment

http://stackoverflow.com/q/51907336
favorite count: 0
upvote count: 5
has title: When I set freq="W", why does the output become freq="W-Sun"?
tagged with: pandas
tagged with: datetime
tagged with: python
has answer: http://stackoverflow.com/a/51907408
accepted answer: http://stackoverflow.com/a/51907408
downvote count: 0
type: AnsweredQuestion
type: Question
score: 5
answer count: 1
has body: When I set freq="W", why does the output become freq="W-Sun"? import pandas as pd a=pd.date_range('10/10/2018', periods=10, freq="W") print(a)
tagged with: date-range

http://stackoverflow.com/q/51851070
tagged with: python
tagged with: montecarlo
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90655437
has comment: http://stackoverflow.com/comment/97607116
has body: I've recently been working on some code in python to simulate a 2 dimensional U(1) gauge theory using monte carlo methods. Essentially I have an n by n by 2 array (call it Link) of unitary complex numbers (their magnitude is one). I randomly select element of my Link array and propose a random change to the number at that site. I then compute the resulting change in the action that would occur due to that change. I then accept the change with a probability equal to min(1,exp(-dS)), where dS is the change in the action. The code for the iterator is as follows def iteration(j1,B0): global Link Staple = np.zeros((2),dtype=complex) for i0 in range(0,j1): x1 = np.random.randint(0,n) y1 = np.random.randint(0,n) u1 = np.random.randint(0,1) Linkrxp1 = np.roll(Link,-1, axis = 0) Linkrxn1 = np.roll(Link, 1, axis = 0) Linkrtp1 = np.roll(Link, -1, axis = 1) Linkrtn1 = np.roll(Link, 1, axis = 1) Linkrxp1tn1 = np.roll(np.roll(Link, -1, axis = 0),1, axis = 1) Linkrxn1tp1 = np.roll(np.roll(Link, 1, axis = 0),-1, axis = 1) Staple[0] = Linkrxp1[x1,y1,1]*Linkrtp1[x1,y1,0].conj()*Link[x1,y1,1].conj() + Linkrxp1tn1[x1,y1,1].conj()*Linkrtn1[x1,y1,0].conj()*Linkrtn1[x1,y1,1] Staple[1] = Linkrtp1[x1,y1,0]*Linkrxp1[x1,y1,1].conj()*Link[x1,y1,0].conj() + Linkrxn1tp1[x1,y1,0].conj()*Linkrxn1[x1,y1,1].conj()*Linkrxn1[x1,y1,0] uni = unitary() Linkprop = uni*Link[x1,y1,u1] dE3 = (Linkprop - Link[x1,y1,u1])*Staple[u1] dE1 = B0*np.real(dE3) d1 = np.random.binomial(1, np.minimum(np.exp(dE1),1)) d = np.random.uniform(low=0,high=1) if d1 &gt;= d: Link[x1,y1,u1] = Linkprop else: Link[x1,y1,u1] = Link[x1,y1,u1] At the beginning of program I call a routine called "randomize" to generate K random unitary complex numbers which have small imaginary parts and store them in an array called Cnum of length K. In the same routine I also go through my Link array and set each element to a random unitary complex number. The code is listed below. def randommatrix(): global Cnum global Link for i1 in range(0,K): C1 …
linked to: http://stackoverflow.com/q/32195525
type: Question
has title: Vectorizing a monte carlo simulation in python
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/51851714
has comment: http://stackoverflow.com/comment/90656131
has comment: http://stackoverflow.com/comment/90661212
accepted answer: http://stackoverflow.com/a/51851714
favorite count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/90655545
has comment: http://stackoverflow.com/comment/90664407

http://stackoverflow.com/a/51938462
has body: In python you can use the membership testing operator in. So instead of checking using loops you can combine your lists and check membership like so: if get_site_name in sites_2017 + sites_2018:
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51938385

http://stackoverflow.com/a/51917834
answers question: http://stackoverflow.com/q/51917662
has body: Perl uses a multi-phase compilation model. Subroutines are defined in an early phase before the actual run time, so no forward declarations are necessary. In contrast, Python executes function definitions at runtime. The variable which holds a function must be assigned (implicitly by the def) before it can be called as a function. If we translate these runtime semantics back to Perl, the code would look like: # at runtime: $test-&gt;(); my $test = \&amp;test; # at compile time: sub test { print 'here' } Note that the $test variable is accessed before it was declared and assigned.
type: Answer
downvote count: 0
score: 7
has comment: http://stackoverflow.com/comment/90791911
upvote count: 7

http://stackoverflow.com/comment/90788310
score: 1
type: QuestionComment
type: Comment
has text: Those `return`s mean anything after won't execute... so you'll never get to your update query anyway... it also seems to imply that `Medications_Bridge` should have a `total_quantity_sold` attribute as well... I think you need to have a good look at how to create a [mcve] here and spend a bit more time on your question...
comment on: http://stackoverflow.com/q/51918856

http://stackoverflow.com/q/51813624
type: UnansweredQuestion
tagged with: python
answer count: 0
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/90582515
tagged with: pip
type: Question
has comment: http://stackoverflow.com/comment/90582311
has comment: http://stackoverflow.com/comment/90595543
has title: Error installing pip packages
has body: I'm having a bit problem with pip, trying to install mopidy-Iris with command below: sudo pip install Mopidy-Iris This worked previously but after uninstall and reinstall I'm getting errors below: Collecting Mopidy-Iris Exception: Traceback (most recent call last): File "/usr/lib/python2.7/dist-packages/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/usr/lib/python2.7/dist-packages/pip/commands/install.py", line 353, in run wb.build(autobuilding=True) File "/usr/lib/python2.7/dist-packages/pip/wheel.py", line 749, in build self.requirement_set.prepare_files(self.finder) File "/usr/lib/python2.7/dist-packages/pip/req/req_set.py", line 380, in prepare_files ignore_dependencies=self.ignore_dependencies)) File "/usr/lib/python2.7/dist-packages/pip/req/req_set.py", line 554, in _prepare_file require_hashes File "/usr/lib/python2.7/dist-packages/pip/req/req_install.py", line 278, in populate_link self.link = finder.find_requirement(self, upgrade) File "/usr/lib/python2.7/dist-packages/pip/index.py", line 465, in find_requirement all_candidates = self.find_all_candidates(req.name) File "/usr/lib/python2.7/dist-packages/pip/index.py", line 423, in find_all_candidates for page in self._get_pages(url_locations, project_name): File "/usr/lib/python2.7/dist-packages/pip/index.py", line 568, in _get_pages page = self._get_page(location) File "/usr/lib/python2.7/dist-packages/pip/index.py", line 683, in _get_page return HTMLPage.get_page(link, session=self.session) File "/usr/lib/python2.7/dist-packages/pip/index.py", line 792, in get_page "Cache-Control": "max-age=600", File "/usr/share/python-wheels/requests-2.12.4-py2.py3-none-any.whl/requests/sessions.py", line 501, in get return self.request('GET', url, **kwargs) File "/usr/lib/python2.7/dist-packages/pip/download.py", line 386, in request return super(PipSession, self).request(method, url, *args, **kwargs) File "/usr/share/python-wheels/requests-2.12.4-py2.py3-none-any.whl/requests/sessions.py…
upvote count: 1
has comment: http://stackoverflow.com/comment/90582072
linked to: http://stackoverflow.com/q/37495375
favorite count: 0

web
tags question: http://stackoverflow.com/q/51890685
tags question: http://stackoverflow.com/q/51848174
tags question: http://stackoverflow.com/q/51848143
type: Tag
tags question: http://stackoverflow.com/q/51873093
tags question: http://stackoverflow.com/q/51929554
tags question: http://stackoverflow.com/q/51866785
tag name: web
tags question: http://stackoverflow.com/q/51870338

timeit
tag name: timeit
type: Tag
tags question: http://stackoverflow.com/q/51955466

http://stackoverflow.com/a/51831497
type: Answer
answers question: http://stackoverflow.com/q/51830638
has body: From the same blog post: call the users.list method to map user display names to User IDs. You'll need to consume the entire list, so you'll want to cache the mappings somewhere for your app to read and update.
score: 0

http://stackoverflow.com/a/51870300
upvote count: 2
accepted answer of: http://stackoverflow.com/q/51869915
has body: Give this a try: from random import randint index = randint(0, 100) key = "Some random string which comes on our way and we don't find the length" try: print('Index value: {}'.format(key[index])) except IndexError: print('No value found with index: {}'.format(index)) To answer your question, it is better to index a sequence of unknown length than to slice. In your code, key[__index__:__index__+1] is the same as key[__index__] except that indexing raises an IndexError if the index was not found, whereas slicing would return an empty string(or tuple, or list etc) if the slice wasn't found. Regardless, it is better to handle the case where the exception is raised, and at that point, you know the index was not found. This would also avoid the unnecessary if else statements in your code. I hope this helps!
answers question: http://stackoverflow.com/q/51869915
score: 2
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/comment/90661280
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51854444
has text: Is your script also named speedtest?
score: 0

http://stackoverflow.com/a/51904217
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/51903744
answers question: http://stackoverflow.com/q/51903744
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/90774778
has body: I would start by using a "spell check" function to get a list of all words in the corpus which are not spelled correctly. This will cut down the data set massively. Then you can brute-force the misspelled words using edit_distance against all the search tokens whose length is similar enough (say, within one or two characters of the same length). You can pre-compute a dict of the search tokens keyed by their length, so when you find a misspelled word like "portible" you can check its edit distance from all your search tokens having 7, 8, or 9 characters.

http://stackoverflow.com/comment/90786230
comment on: http://stackoverflow.com/q/51918024
score: 0
type: Comment
type: QuestionComment
has text: ideally it should be the true value of the amount of days of the month that lies between the start and end dates.

http://stackoverflow.com/comment/90847207
score: 0
type: Comment
type: QuestionComment
has text: I agree with L3viathan, but only for practical reasons. The people of earth have already computed this data upto staggering numbers, and lookup will trump computation. Though, the Sieve is always worth study :)
comment on: http://stackoverflow.com/q/51948635

http://stackoverflow.com/q/51850773
tagged with: arrays
tagged with: histogram
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90654974
score: 0
type: Question
has answer: http://stackoverflow.com/a/51850910
accepted answer: http://stackoverflow.com/a/51850910
has body: everyone. I created an histogram with by using an array with a size of 1x1000 and its values range from 0 to 99. I want to store histograms values as an int array. However, when I run the program I got the following results for the program(the numeric values are different for everyone since its random): (array([ 93., 101., 119., 91., 97., 110., 102., 111., 85., 91.]), array([ 0. , 9.9, 19.8, 29.7, 39.6, 49.5, 59.4, 69.3, 79.2, 89.1, 99. ]), ) I want to get a result like this: [ 93 101 119 91 97 110 102 111 85 91] Can you help? Also what kind of array I am getting as a result? It doesn't look like anything I have ever seen before import numpy as np import matplotlib.pyplot as plt x = np.random.randint(100, size=1000) y = plt.hist(x,10) print(y)
has title: Converting Histogram Values to Int Array in Python
answer count: 1

http://stackoverflow.com/q/51921882
type: Question
score: 0
answer count: 1
has body: I am using bs4 to get data from a website. I am using the select method to perform a CSS selection operation. But i can't extract the value i want. This is my code: data = bs4.BeautifulSoup(data.content,'lxml') html_PER = data.select('tr[title="Price to Earnings Ratio Basico"]')` this i what i get: [ PER Basico: 16,53639823662936 ] I would like to extract the 16.53 value. But I don't know how. I'm sure there is a easiest way to do this. But I'm new in web scraping and I don't know nothing about html.
has answer: http://stackoverflow.com/a/51921907
tagged with: beautifulsoup
has title: get specific data from bs4 element tag
tagged with: http://stackoverflow.com/tag/html
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51921907

http://stackoverflow.com/comment/90581727
type: AnswerComment
score: 1
type: Comment
comment on: http://stackoverflow.com/a/51813462
has text: Upvoted for inclusion of specific documentation, really helpful!

http://stackoverflow.com/comment/90647059
type: Comment
score: 1
has text: Exactly that! Moreover, it is stated in the Pandas [documentation](https://pandas.pydata.org/pandas-docs/stable/io.html), as I see it now, that _select will raise a ValueError if the query expression has an unknown variable reference. Usually this means that you are trying to select on a column that is not a data_column._ Additionally, instead of `data_columns=[ ...]` one can specify `data_columns=True` to index all columns and make them therefore available to filtering in `where` clause.
comment on: http://stackoverflow.com/a/51828825
type: AnswerComment

bayesian-networks
type: Tag
tags question: http://stackoverflow.com/q/51911160
tag name: bayesian-networks

http://stackoverflow.com/a/51942812
has body: For Python3 this helped: export JUPYTER_PATH=/Library/Frameworks/Python.framework/Versions/3.7/Resources/Python.app/Contents/MacOS/Python:$JUPYTER_PATH Thanks to https://stackoverflow.com/a/46180035/9881344
answers question: http://stackoverflow.com/q/51916265
type: AcceptedAnswer
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/51916265

http://stackoverflow.com/q/51841401
has title: Regex for removing all characters except A-z and deleting all words containing digits
type: Question
has body: My goal is to write a function that inputs a text and substitutes all characters except for latin alphabet (A-z) with whitespaces, plus it deletes all the words containing digits. Then it replaces all multiple whitespace with a single one. Example: ' hello, world! ho1hoho2ho, merry xmas!! ho1ho1 :))' -&gt; 'hello world merry xmas'. The Python function that implements this: def clean_text(text): text_valid = re.sub(u'[^A-z0-9]', ' ', text) return ' '.join(word for word in text_valid.split() if not re.search(r'\d', word)) Now I wonder if there is a single regular expression for this, maybe, so I could just write something like return ' '.join(re.findall(enter_my_magical_regex_here)) Or, maybe, there is another way to replace the code above with something faster (and, hopefully, shorter)?
has comment: http://stackoverflow.com/comment/90636121
has comment: http://stackoverflow.com/comment/90635835
tagged with: replace
score: 0
has answer: http://stackoverflow.com/a/51841783
has comment: http://stackoverflow.com/comment/90637247
accepted answer: http://stackoverflow.com/a/51841783
answer count: 2
has comment: http://stackoverflow.com/comment/90636066
has answer: http://stackoverflow.com/a/51841701
has comment: http://stackoverflow.com/comment/90657718
linked to: http://stackoverflow.com/q/29771901
has comment: http://stackoverflow.com/comment/90636397
tagged with: python
tagged with: regex
possible better answer: http://stackoverflow.com/a/51841701
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90635869

http://stackoverflow.com/q/51799030
upvote count: 2
tagged with: python
has answer: http://stackoverflow.com/a/51806554
score: 2
accepted answer: http://stackoverflow.com/a/51806554
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90565573
possible better answer: http://stackoverflow.com/a/51806685
has title: Is there any way to generate ELF BINARY using only python library?
has comment: http://stackoverflow.com/comment/90556180
type: Question
answer count: 2
tagged with: elf
downvote count: 0
has answer: http://stackoverflow.com/a/51806685
tagged with: assembly
has body: Is there any way to generate ELF binary using only the python library? I want to assemble the file below using python library. a.s : line 1 : .global _start line 2 : _start: line 3 : push _STRING1 line 4 : push _STRING2 line 5 : call printf line 6 : _STRING1: line 7 : .string "gogo" line 8 : _STRING2: line 9 : .string "%s" I've tried to use two python libraries keystone, and pwntool. However, they support only machine code byte emission corresponding to assembly command. (It didn't generate ELF binary consisting of elf header, section header,.. etc) Also, It doesn't support handling on external library info. (such as line 5) Q. I wanna generate a complete ELF BINARY a.out using python library. Is there any possible way to do that?
has comment: http://stackoverflow.com/comment/90554644
favorite count: 0
tagged with: binary

tkinter
tags question: http://stackoverflow.com/q/51849115
tags question: http://stackoverflow.com/q/51849581
tags question: http://stackoverflow.com/q/51822509
tags question: http://stackoverflow.com/q/51803339
tags question: http://stackoverflow.com/q/51907438
tags question: http://stackoverflow.com/q/51916597
tags question: http://stackoverflow.com/q/51915741
tags question: http://stackoverflow.com/q/51798963
tags question: http://stackoverflow.com/q/51857017
tags question: http://stackoverflow.com/q/51820398
tags question: http://stackoverflow.com/q/51852276
tags question: http://stackoverflow.com/q/51892070
tags question: http://stackoverflow.com/q/51930567
tags question: http://stackoverflow.com/q/51949976
tags question: http://stackoverflow.com/q/51856163
tags question: http://stackoverflow.com/q/51953821
tags question: http://stackoverflow.com/q/51877124
tags question: http://stackoverflow.com/q/51830722
tags question: http://stackoverflow.com/q/51871477
tag name: tkinter
tags question: http://stackoverflow.com/q/51802770
tags question: http://stackoverflow.com/q/51867429
tags question: http://stackoverflow.com/q/51847455
tags question: http://stackoverflow.com/q/51807934
tags question: http://stackoverflow.com/q/51800441
tags question: http://stackoverflow.com/q/51955487
tags question: http://stackoverflow.com/q/51842918
tags question: http://stackoverflow.com/q/51908541
tags question: http://stackoverflow.com/q/51940525
tags question: http://stackoverflow.com/q/51903504
tags question: http://stackoverflow.com/q/51855003
tags question: http://stackoverflow.com/q/51899959
tags question: http://stackoverflow.com/q/51857406
tags question: http://stackoverflow.com/q/51828078
tags question: http://stackoverflow.com/q/51941260
tags question: http://stackoverflow.com/q/51805901
tags question: http://stackoverflow.com/q/51941418
tags question: http://stackoverflow.com/q/51954359
tags question: http://stackoverflow.com/q/51804454
tags question: http://stackoverflow.com/q/51804001
tags question: http://stackoverflow.com/q/51847801
tags question: http://stackoverflow.com/q/51845416
tags question: http://stackoverflow.com/q/51822820
tags question: http://stackoverflow.com/q/51858788
tags question: http://stackoverflow.com/q/51926553
tags question: http://stackoverflow.com/q/51845368
tags question: http://stackoverflow.com/q/51884186
tags question: http://stackoverflow.com/q/51867579
tags question: http://stackoverflow.com/q/51913511
tags question: http://stackoverflow.com/q/51856051
tags question: http://stackoverflow.com/q/51802153
tags question: http://stackoverflow.com/q/51860316
tags question: http://stackoverflow.com/q/51804857
tags question: http://stackoverflow.com/q/51955138
tags question: http://stackoverflow.com/q/51908825
tags question: http://stackoverflow.com/q/51805940
tags question: http://stackoverflow.com/q/51913076
tags question: http://stackoverflow.com/q/51833888
tags question: http://stackoverflow.com/q/51897361
tags question: http://stackoverflow.com/q/51812575
tags question: http://stackoverflow.com/q/51835305
tags question: http://stackoverflow.com/q/51907656
tags question: http://stackoverflow.com/q/51818550
tags question: http://stackoverflow.com/q/51949536
tags question: http://stackoverflow.com/q/51916181
tags question: http://stackoverflow.com/q/51882804
tags question: http://stackoverflow.com/q/51874832
tags question: http://stackoverflow.com/q/51853581
tags question: http://stackoverflow.com/q/51858064
tags question: http://stackoverflow.com/q/51933809
tags question: http://stackoverflow.com/q/51825178
tags question: http://stackoverflow.com/q/51810743
tags question: http://stackoverflow.com/q/51915500
tags question: http://stackoverflow.com/q/51804862
tags question: http://stackoverflow.com/q/51819633
tags question: http://stackoverflow.com/q/51854801
tags question: http://stackoverflow.com/q/51820023
tags question: http://stackoverflow.com/q/51918990
tags question: http://stackoverflow.com/q/51829362
tags question: http://stackoverflow.com/q/51839409

http://stackoverflow.com/a/51862719
has comment: http://stackoverflow.com/comment/90677954
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51862462
has body: I think this is, if anything, a docs bug on that paragraph, not a bug in io objects. (And io object’s aren’t the only thing—most trivially, a csv.reader wrapper around a file is just as restartable as a file.) If you just use an iterator as an iterator, once it raises it will keep on raising. But if you call methods outside of the iterator protocol, you’re not really using it as an iterator anymore, but as something more than an iterator. And in that case, it seems legal and even idiomatic for the object to be “refillable” if it makes sense. As long as it never refills itself while it’s quacking as an iterator, only when it’s quacking as some other type that goes beyond that. In a similar situation in C++, the language committee might well declare that this breaks substitutability and therefore the iterator becomes invalid as an iterator once you call such a method on it, even if the language can’t enforce that. Or come up with a whole new protocol for refillable iterators. (Of course C++ iterators aren’t quite the same thing as Python iterators, but hopefully you get what I mean.) But in Python, practicality beats purity. I’m pretty sure Guido intended this behavior from the start, and that an object is allowed to do this and still be considered an iterator, and the core devs continue to intend it, and it’s just that nobody has thought about how to write something sufficiently rigorous to explain it accurately because nobody has asked. If you ask by filing a docs bug, I’ll bet that this paragraph gets a footnote, rather than the io and other refillable iterator objects being reclassified as not actually iterators.
score: 8
answers question: http://stackoverflow.com/q/51862462
type: Answer
has comment: http://stackoverflow.com/comment/138561102
has comment: http://stackoverflow.com/comment/90677975
downvote count: 1
upvote count: 9
has comment: http://stackoverflow.com/comment/138561079

http://stackoverflow.com/q/51899374
tagged with: machine-learning
tagged with: python
score: 3
has comment: http://stackoverflow.com/comment/90750329
has body: I am trying to predict a value each week. I have 4 months and the actual value goes near to zero on weekends but never negative. My polynomial regression model is predicting well for weekdays and goes to way negative when actual is near to zero. How to correct this? poly = PolynomialFeatures(degree=2) X_ = poly.fit_transform(X) predict_ = poly.fit_transform(predict) clf = linear_model.LinearRegression() clf.fit(X_, vector) print clf.predict(predict_)
tagged with: linear-regression
upvote count: 3
type: Question
has title: Negative predictions in polynomial regression
has answer: http://stackoverflow.com/a/55007777
has comment: http://stackoverflow.com/comment/90750250
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/90750406
favorite count: 0
has comment: http://stackoverflow.com/comment/90750494
type: UnansweredQuestion

http://stackoverflow.com/comment/90676645
type: Comment
has text: @RokoC.Buljan yes i am trying to do it in python. sorry about the confusion. i am trying to paste a snippet of the actual code if i can figure out the formatting in the comment section
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51861552

http://stackoverflow.com/comment/90580838
comment on: http://stackoverflow.com/q/51812028
has text: Could you provide us with the exact code you're using to scrape, and the exact page your scraping from? That would help us a lot with figuring out what the issue might be. I tried to find elements in the link you provided which match your scraping example, but couldn't find any.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/127384259
comment on: http://stackoverflow.com/a/70907644
score: 5
type: AnswerComment
type: Comment
has text: This is a much nicer answer than typing the individual "self" arguments, because typing `self` as the Protocol prevents you from accessing attributes on the Mixin class itself. (It is just the Protocol)

http://stackoverflow.com/comment/90574482
has text: `str.split` returns a new list... you want `a = a.split()`...
comment on: http://stackoverflow.com/q/51809743
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/a/51933029
has body: Following @stovfl's answer on How to get inner content as string using minidom from xml.dom? Perhaps this works for you? def getText(nodelist): # Iterate all Nodes aggregate TEXT_NODE rc = [] for node in nodelist: if node.nodeType == node.TEXT_NODE: rc.append(node.data) else: # Recursive rc.append(getText(node.childNodes)) return ''.join(rc) # Iterate &lt;sec..&gt;...&lt;/sec&gt; Node List for node in nodelist: print(getText(node.childNodes)) The output: Introduction This is a paragraph This is second paragraph List Item 1 List Item 2 List Item 3
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/90881289
answers question: http://stackoverflow.com/q/51932120
upvote count: 2
type: Answer

http://stackoverflow.com/q/51906709
has comment: http://stackoverflow.com/comment/90764164
has comment: http://stackoverflow.com/comment/90764025
has comment: http://stackoverflow.com/comment/90764050
has comment: http://stackoverflow.com/comment/90764104
tagged with: python
has comment: http://stackoverflow.com/comment/90764078
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51906923
has title: TensorFlow InvalidArgumentError/Value error occurs with small change of code
has body: The code: import numpy as np import tensorflow as tf import pandas as pd from sklearn.model_selection import train_test_split x_data = np.linspace(0, 1000000, 1000) y_true = np.sin(x_data) y_true += np.random.randn(len(x_data)) feature_columns = [tf.feature_column.numeric_column('x', shape=[1])] estimator = tf.estimator.DNNRegressor(feature_columns=feature_columns, hidden_units=[10,10,10], optimizer=lambda: tf.train.AdamOptimizer( learning_rate=0.1 )) X_train, X_test, y_train, y_test = train_test_split(x_data, y_true, test_size=0.3) input_function = tf.estimator.inputs.numpy_input_fn({'x': X_train},y_train, batch_size=8, num_epochs=None, shuffle=True) train_input_function = tf.estimator.inputs.numpy_input_fn({'x': X_train},y_train, batch_size=8, num_epochs=1000, shuffle=False) test_input_function = tf.estimator.inputs.numpy_input_fn({'x': X_test},y_test, batch_size=8, num_epochs=1000, shuffle=False) estimator.train(input_fn=input_function, steps=1000) train_metrics = estimator.evaluate(input_fn=train_input_function, steps=1000) test_metrics = estimator.evaluate(input_fn=test_input_function, steps=1000) print('TRAINING DATA METRICS') print(train_metrics) print() print('TEST DATA METRICS') print(test_metrics) print() Works very well. But if I change line y_true = np.sin(x_data) into y_true=tf.square(x_data), I get an error: Traceback (most recent call last): File "C:\Users\Admin\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\framework\ops.py", line 1576, in _create_c_op c_op = c_api.TF_FinishOperation(op_desc) tensorflow.python.framework.errors_impl.InvalidArgumentError: Shape must be rank 1 but is rank 2 for 'strided_slice' (op: 'StridedSlice') with input shapes: [1000], [1,700], [1,700], [1]. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:/Users/Admin/Documents/PycharmProjects/TF_API_2/api.py", line 21, in X_train, X_test, y_train, y_test = train_test_split(x_data, y_true, te…
has comment: http://stackoverflow.com/comment/90771478
has comment: http://stackoverflow.com/comment/90764371
has comment: http://stackoverflow.com/comment/90764177
accepted answer: http://stackoverflow.com/a/51906923
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/90764404
has comment: http://stackoverflow.com/comment/90764440
tagged with: neural-network
has comment: http://stackoverflow.com/comment/90764124
has comment: http://stackoverflow.com/comment/90770909
score: 0
has comment: http://stackoverflow.com/comment/90782323
tagged with: deep-learning
has comment: http://stackoverflow.com/comment/90774132
answer count: 1

http://stackoverflow.com/comment/90611939
has text: @WillemVanOnsem the error is `Destination` has no variable `objects`, which refers to the line `Destination.objects.all()`, two lines before the local variable with the same name is created.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51828715

http://stackoverflow.com/comment/90778818
has text: @pandachii so glad I could help ;)
comment on: http://stackoverflow.com/a/51914404
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/51898299
answers question: http://stackoverflow.com/q/51873988
type: Answer
has comment: http://stackoverflow.com/comment/90800198
accepted answer of: http://stackoverflow.com/q/51873988
has body: If I am following what you are after, I think you want to replace the "assignee_name" in your patents data with a corresponding "hitID" from your companies data based on the company data "name" being included somewhere in the patent data "assignee_name". A couple of loops should do the trick (though I am sure there is a more elegant approach). Of course, if you need something more sophisticated to determine if the "name" from the companies data is really a match for the "assignee_name" in the patents data, then you could add some regex, etc to this approach but this should get you pointed in the right direction. import json patents = json.loads("""{ "US-8163793-B2": { "publication_date": "20120424", "assignee_name": "Hoffman-La Roche Inc." }, "US-1234567-A1": { "publication_date": "20010101", "assignee_name": "ABC Inc." } }""") companies = json.loads("""{ "Row_1": { "COMPANY": [ { "hitID": "COMP642", "name": "Roche" } ] }, "Row_2": { "COMPANY": [ { "hitID": "COMP123", "name": "ABC" } ] } }""") # loop through companies data for company in companies.values(): company_id = company['COMPANY'][0]['hitID'] company_name = company['COMPANY'][0]['name'] # update patents where company "name" included in "assignee_name" for patent in patents.values(): if company_name in patent['assignee_name']: patent['assignee_name'] = company_id print(patents) # OUTPUT (use json.dump to write to file if needed) # # { # 'US-1234567-A1': {'assignee_name': 'COMP123', 'publication_date': '20010101'}, # 'US-8163793-B2': {'assignee_name': 'COMP642', 'publication_date': '20120424'} # }
score: 0
type: AcceptedAnswer

http://stackoverflow.com/q/51903209
has comment: http://stackoverflow.com/comment/90757482
answer count: 1
has comment: http://stackoverflow.com/comment/90822105
has comment: http://stackoverflow.com/comment/90821680
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90822171
tagged with: python
has comment: http://stackoverflow.com/comment/90759028
tagged with: pyside2
type: Question
has answer: http://stackoverflow.com/a/53979425
score: 0
has title: UI does not accept file drops
has body: What I want to do: I am trying to create a PySide2/PyQt window which accepts the files dropped on its UI and runs a function. Problem: UI is not accepting file drops and does not trigger any event function defined. What I have done so far: Below is the trimmed down code of my app where I am loading a .ui-file created in Qt-Designer to load the interface. window gets stored in self.window variable. self.window has setAcceptDrops(True). Event functions are also defined. -Code from PySide2 import QtUiTools from PySide2 import QtGui from PySide2 import QtCore from PySide2 import QtWidgets import os,sys kUiFilePath = os.path.join(os.path.dirname(__file__) , 'uiFile.ui') class LoadTool(QtWidgets.QMainWindow): def __init__(self, uiFilePath): self.window = None self.app = None self.loadUI(uiFilePath) self.window.setAcceptDrops(True) self.window.show() sys.exit(self.app.exec_()) def dropEvent(self, e): print e e.accept() def dragEnterEvent(self, e): print e e.accept() def dragMoveEvent(self, e): print e e.accept() def loadUI(self, uiFilePath): self.app = QtWidgets.QApplication(sys.argv) super(LoadTool, self).__init__() self.window = QtUiTools.QUiLoader().load(uiFilePath) LoadTool(kUiFilePath) UI file code <?xml version="1.0" encoding="UTF-8"?> ShellExport <x>0</x> <y>0</y> 399 520 false true Dialog <x>10</x> <y>10</y> 381 501 true Device Status <x>10</x> <y>30</y> 361 111 true Deploy Fbx <x>10</x> <y>50</y> 341 20 <x>270</x> <y>80</y> 75 23 Deploy fbx <x>10</x> <y>30</y> 47 13 Fbx path <x>20</x> <y>150</y> 201 91 <resources/> <connections/>

http://stackoverflow.com/a/51919000
has comment: http://stackoverflow.com/comment/90790328
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51916407
answers question: http://stackoverflow.com/q/51916407
has comment: http://stackoverflow.com/comment/90790425
type: Answer
score: 1
upvote count: 1
downvote count: 0
has body: Scapy has support for monitor mode, but it requires several things: Use the latest development scapy version. To download it, get https://github.com/secdev/scapy/archive/master.zip and install it via python setup.py install Use Npcap instead of Winpcap. You will need to uninstall Winpcap first (Winpcap has been abandoned, and Nmap took the project back). Download it at https://nmap.org/npcap/ Call sniff([...], monitor=True). It will be safer to specify the interface. You can print the list with IFACES.show() in scapy’s console. (Note: the interface name iface= argument allows full interface name. For instance “RaLink Adapter (R) Wi-Fi” as prompted by the previous command) The monitor argument is important, as it triggers new sniffing mechanics. Wireshark will also requires Npcap (Winpcap has no support for monitor mode) to sniff in monitor mode

http://stackoverflow.com/comment/90819212
score: 0
has text: @paul when i do this command, there is no output.
comment on: http://stackoverflow.com/q/51934098
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90640990
has text: Added goals per @Fildor
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51843254

http://stackoverflow.com/q/51897361
has body: I am getting the error "ImportError: No module named Tkinter" but don't know why. When I run my script I am getting this error but that is usually do to a library you are trying to use that you have not imported. I have searched and all of the posts I have found are directly related to someone ether messing up "Tkinter" with "tkinter" python 2 and 3, or have not imported the library the right way. I have ran this script from the command line on ubuntu 14.04, Spyder on the same Ubuntu box, and also on the Cloudera Data Science workbench and it worked fine. On all of these machines I have not imported the library and it works flawlessly. When I try to run it on my rhel 7 box I am getting the following error: root@rhel7_box:/home/user/4688_events_PC-Tags_last_7_days# python 4688_events_PC-Tags_last_7_days_NN_FromMergedHash.py Traceback (most recent call last): File "4688_events_PC-Tags_last_7_days_NN_FromMergedHash.py", line 5, in &lt;module&gt; import matplotlib.pyplot as plt File "/usr/lib64/python2.7/site-packages/matplotlib/pyplot.py", line 115, in &lt;module&gt; _backend_mod, new_figure_manager, draw_if_interactive, _show = pylab_setup() File "/usr/lib64/python2.7/site-packages/matplotlib/backends/__init__.py", line 62, in pylab_setup [backend_name], 0) File "/usr/lib64/python2.7/site-packages/matplotlib/backends/backend_tkagg.py", line 4, in &lt;module&gt; from . import tkagg # Paint image to Tk photo blitter extension. File "/usr/lib64/python2.7/site-packages/matplotlib/backends/tkagg.py", line 5, in &lt;module&gt; from six.moves import tkinter as Tk File "/usr/lib/python2.7/site-packages/six.py", line 203, in load_module mod = mod._resolve() File "/usr/lib/python2.7/site-packages/six.py", line 115, in _resolve return _import_module(self.mod) File "/usr/lib/python2.7/site-packages/six.py", line 82, in _import_module __import__(name) ImportError: No module named Tkinter It seems to be getting the error when it hits "import matplotlib.pyplot as plt". These are the…
has title: rhel7 matplotlib: "ImportError: No module named Tkinter"
tagged with: tkinter
type: AnsweredQuestion
tagged with: matplotlib
accepted answer: http://stackoverflow.com/a/51897447
has comment: http://stackoverflow.com/comment/90745707
type: Question
answer count: 1
has comment: http://stackoverflow.com/comment/90745673
has answer: http://stackoverflow.com/a/51897447
score: 0
tagged with: python

http://stackoverflow.com/a/58429182
score: 0
type: Answer
has body: The version with df - df.astype(int) does not work correctly for me, simply applying the same str.split without it does: def get_max_decimal_length(df): """Get the maximum length of the fractional part of the values or None if no values present.""" values = df.dropna() return None if values.empty else values.astype(str).str.split(".", expand=True)[1].str.len().max()
answers question: http://stackoverflow.com/q/51879063

http://stackoverflow.com/comment/90752661
type: QuestionComment
comment on: http://stackoverflow.com/q/51899594
score: 1
has text: You are trying to program several steps beyond your current ability. Again, please work through the appropriate tutorials to increase your ability. Stack Overflow is an archive of useful question-answer postings, *not* a general help site.
type: Comment

http://stackoverflow.com/comment/90611395
has text: I tried that and it did not fix the overlapping issue when data points are greater than 100, however, it did help some.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51828270
type: Comment

http://stackoverflow.com/a/51909073
answers question: http://stackoverflow.com/q/51907836
has comment: http://stackoverflow.com/comment/90769589
has body: 1) Why is sender = 'hk7206210@gmail.com' Your settings.EMAIL_HOST_USER is your email account, any emails will come out of this address so your sender is 'hk7206210@gmail.com' 2) Why is receiver = 'hk7206210@gmail.com' Because you wrote emailTo = [settings.EMAIL_HOST_USER] What are you trying to accomplish? If you want to send an email to what the user input in the form, it should be the opposite: emailFrom = settings.EMAIL_HOST_USER emailTo = [form.cleaned_data['email']]
score: 0
has comment: http://stackoverflow.com/comment/90772924
has comment: http://stackoverflow.com/comment/90772683
type: Answer
has comment: http://stackoverflow.com/comment/90770181
has comment: http://stackoverflow.com/comment/90772655
has comment: http://stackoverflow.com/comment/90768932

http://stackoverflow.com/q/51923974
type: AnsweredQuestion
has body: I have the two following files: datetime.py #! /usr/bin/python3.6 from PyQt5.QtCore import QDate, QTime, QDateTime, Qt now = QDate.currentDate() print(now) print(now.toString(Qt.ISODate)) print(now.toString(Qt.DefaultLocaleLongDate)) datetime = QDateTime.currentDateTime() print(datetime) print(datetime.toString()) time = QTime.currentTime() print(time) print(time.toString(Qt.DefaultLocaleLongDate)) print("\n") print("UTC Time: " + datetime.toUTC().toString(datetime.offsetFromUtc())) It was running fine at the beginning, however, upon running it after a couple of times, I'm getting this result: PyQt5.QtCore.QDate(2018, 8, 19) 2018-08-19 Sunday, August 19, 2018 PyQt5.QtCore.QDateTime(2018, 8, 19, 21, 47, 36, 885) Sun Aug 19 21:47:36 2018 PyQt5.QtCore.QTime(21, 47, 36, 885) 9:47:36 PM MDT UTC Time: Mon Aug 20 03:47:36 2018 GMT Segmentation fault (core dumped) The segmentation fault wasn't there at the beginning, it just started to pop up. Then I created a new file: daysto.py #! /usr/bin/python3.6 from PyQt5.QtCore import QDate xmas1 = QDate(2017, 12, 25) xmas2 = QDate(2018, 12, 25) daysToAnniversary1 = QDate(2018, 3, 3) daysToAnniversary2 = QDate(2019, 3, 3) now = QDate.currentDate() daysPassed = xmas1.daysTo(now) print(daysPassed) The result I'm seeing is: PyQt5.QtCore.QDate(2018, 8, 19) 2018-08-19 Sunday, August 19, 2018 PyQt5.QtCore.QDateTime(2018, 8, 19, 21, 47, 36, 885) Sun Aug 19 21:47:36 2018 PyQt5.QtCore.QTime(21, 47, 36, 885) 9:47:36 PM MDT UTC Time: Mon Aug 20 03:47:36 2018 GMT Segmentation fault (core dumped) So basically, I'm running two different files, but I still see the same output - which is weird because the second file is supposed to just give me a number. I copied the file to my home directory and it worked fine. However, as long as I'm in that directory, it's not working. I'm on Ubuntu 18 and my these files are chmod +xed. Why is this happening and how can I fix it?
tagged with: pyqt5
has comment: http://stackoverflow.com/comment/90797724
type: Question
has comment: http://stackoverflow.com/comment/90797470
score: 0
upvote count: 1
answer count: 1
downvote count: 1
has title: Two different files giving same output despite having different codes - PyQT5 and Python
favorite count: 0
has answer: http://stackoverflow.com/a/51924017
accepted answer: http://stackoverflow.com/a/51924017
tagged with: python

http://stackoverflow.com/comment/105304965
score: 3
comment on: http://stackoverflow.com/a/51861479
type: AnswerComment
has text: this means that you redoing it every time you recreate your virtual environment
type: Comment

http://stackoverflow.com/q/51803875
has answer: http://stackoverflow.com/a/51807807
tagged with: python-3.x
score: 2
upvote count: 2
type: Question
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51807807
has body: I am trying to calculate the average rating of a game and order by descending. In my models.py I have defined a hybrid property class Review(db.Model): id = db.Column(db.Integer, primary_key=True) rating = db.Column(db.Numeric(precision=2, scale=1), index=True) body = db.Column(db.String(140)) user_id = db.Column(db.Integer, db.ForeignKey('user.id')) game_id = db.Column(db.Integer, db.ForeignKey('game.id')) class Game(db.Model): id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(255), index=True, unique=True) reviews = db.relationship('Review', backref='game', lazy='dynamic') @hybrid_property def avg_rating(self): total_rating = 0 reviews = Review.query.filter_by(game_id=self.id).all() for review in reviews: total_rating += review.rating return total_rating / len(reviews) but when I try and query for the average rating in my routes.py games = Game.query.order_by(Game.avg_rating.desc()) I get this error AttributeError: 'decimal.Decimal' object has no attribute 'desc' I probably need to do something like this in my models.py but how? @avg_rating.expression def avg_rating(cls): # what to write here
tagged with: sqlalchemy
has title: define expression used when querying the model
answer count: 1
downvote count: 0
tagged with: flask
tagged with: flask-sqlalchemy
favorite count: 0
tagged with: python

http://stackoverflow.com/q/51832505
type: Question
has title: Android MediaPlayer Streaming YouTube audio stream unexpected LOUD static
tagged with: android-mediaplayer
tagged with: audio-streaming
has answer: http://stackoverflow.com/a/51891188
tagged with: youtube-dl
answer count: 1
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/51891188
tagged with: android
tagged with: python
has body: What I'm attempting: I'm using youtube-dl in a Python Daemon on a remote server to get a URL. That URL is fed into an Android App into a MediaPlayer instance. What is happening: Occasionally and unexpectedly the Media player will BLAST static and play at normal speed, sometimes it will blast static and play at 1.5 times speed. Here's a video of what happens. HEADPHONE WARNING YouTube Video Observations: If there is static it is for the whole song (it isn't intermittent). I've taken the URLs it provides and they play fine in a PC browser with no static. It happens on different phones, and it is not just my particular phone. It takes longer to start tracks that end up being staticy. Tracks that are staticy make my progress bar (seconds minutes display) just behave strangely. I've seen it count up and down in the first couple seconds, and there is the 1.5x speed I was talking about. MediaHTTPConnection throws alot of exceptions that I don't know how to handle. E/MediaHTTPConnectionEx: disconnecting E/MediaHTTPConnectionEx: RuntimeException: Unbalanced enter/exit mConnection.disconnect(); Below is the portion of my Python daemon that returns the URL ydl_opts = { 'skip_download':True, # We just want to extract the info 'format':'bestaudio', 'forceurl':True, 'ignoreerrors':True, 'youtube_include_dash_manifest':False, 'restrict_filenames':True, 'source_address':'10.1.0.38',#we have to set this to force ipv4 'logger': MyLogger() } def ytdl(self, url): url2 = "https://www.youtube.com/watch?v="+url ydl.download([url2]) Here's the (basically boilerplate) MediaPlayer public static Stack&lt;Track&gt; tracks = new Stack&lt;&gt;(); private static MediaPlayer mediaPlayer; private String mediaFile; private static int duration = 0; private AudioManager audioManager; private Boolean userPause = false; // Binder given to clients private final IBinder iBinder = new LocalBinder(); public static final String TAG = "Player"; @Override public IBinder onBind(Intent intent) { return iBinder; …
type: AnsweredQuestion
score: 1
upvote count: 1

http://stackoverflow.com/comment/90682928
comment on: http://stackoverflow.com/q/51862924
type: Comment
type: QuestionComment
has text: Ok, so you need to create an array that you can push() and pop() with, and when the user is happy, submits that array as a POST object to be collected by a view, then that view can update `bullet_list`. However, if you hard code `bullet_list` like this in your view rather than using a model and a method to delete object entries in a database you will always get the same `bullet_list` on a page refresh.
score: 1

http://stackoverflow.com/comment/90599845
has text: Thanks to the respondents above, and I'll take a closer look at your responses, there shouldn't be many questions
comment on: http://stackoverflow.com/q/51822701
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/comment/133125507
score: 5
type: Comment
has text: Try closing your IDE and Jupyter Notebooks
type: QuestionComment
comment on: http://stackoverflow.com/q/51912999

http://stackoverflow.com/comment/90632719
type: Comment
type: QuestionComment
score: 0
has text: Yes of course ! I added it to the post
comment on: http://stackoverflow.com/q/51839415

http://stackoverflow.com/comment/90691923
type: Comment
comment on: http://stackoverflow.com/q/51870095
score: 0
has text: I'm sorry I'm not sure what you mean, do you want to extract all confidence from the entities from this `dict` or looking if the api has an method to do the same?
type: QuestionComment

http://stackoverflow.com/a/51874823
upvote count: 1
downvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/90701479
has body: Inseted of using driver.find_element_by_xpath("//div[@class='fxg-field'][1]/input[@class='fxg-field__input-text']") try with driver.find_element_by_xpath(//input[@name="USER"])
has comment: http://stackoverflow.com/comment/90701169
answers question: http://stackoverflow.com/q/51873603
score: 0

http://stackoverflow.com/a/51951042
has body: I Cant test your code cause i dont have a token and i cant understand your API docs, but maybe you can input your second request in same scope of the first, so your second request will happens when the first finish and if the statuscode was 200. something like that, sory i cant test the code s3 = boto3.client('s3') domain = 'mydatabricks.cloud.databricks.com' tokenStr = 'token:tokenstr' response = requests.post('https://%s/api/2.0/clusters/start' % (domain), headers = {"Authorization": "Basic " + base64.standard_b64encode(tokenStr)}, json = {"cluster_id": "ddddd-sss23-2232323"}) if response.status_code == 200: response2 = requests.post('https://%s/api/2.0/jobs/run-now' % (domain), headers = {"Authorization": "Basic " + base64.standard_b64encode(tokenStr)}, json = {"job_id": 12345}) print(response2.statuscode)
score: -1
downvote count: 1
type: Answer
upvote count: 0
answers question: http://stackoverflow.com/q/51950417

http://stackoverflow.com/comment/90861394
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51951692
has text: I updated the question with some additional info.
score: 0

django-apps
tag name: django-apps
tags question: http://stackoverflow.com/q/51855147
type: Tag

http://stackoverflow.com/q/51861495
accepted answer: http://stackoverflow.com/a/51861699
possible better answer: http://stackoverflow.com/a/51861686
has body: I am getting used with datasets from the scikit-learn and I am currently using the iris dataset (dataset for classification of different species of iris). When I try to visualize the values describing the flowers features using print adding with this code: from sklearn.datasets import load_iris iris_dataset=load_iris() print("Keys of the iris dataset:\n".format(iris_dataset['feature_names'])) I just obtain this output from the console: Keys of the iris dataset: On the other hand, if I use the print function without "format" with this line: print("Keys of the iris dataset:\n",(iris_dataset['feature_names'])) I obtain at least an output: ('Keys of the iris dataset:\n', ['sepal length (cm)', 'sepal width (cm)', 'petal length (cm)', 'petal width (cm)']) This happens with every section of the dataset I try to display, it seems a problem with the function format(), does anyone have any suggestion for solving it and correctly visualize the formatted output?
has answer: http://stackoverflow.com/a/51861686
answer count: 2
tagged with: printing
downvote count: 0
tagged with: scikit-learn
favorite count: 0
has answer: http://stackoverflow.com/a/51861699
tagged with: python
type: AnsweredQuestion
has title: Print.format() function not working in Python
score: 1
upvote count: 1
type: Question

http://stackoverflow.com/comment/90576007
type: Comment
type: QuestionComment
has text: ...it would be a lot more straightforward to put the content you're writing onto a queue, and have a separate thread read from the queue, write to the sink, *and* flush. That way you aren't depending on any semantics that aren't well-documented.
comment on: http://stackoverflow.com/q/51810479
score: 0

http://stackoverflow.com/a/51815270
answers question: http://stackoverflow.com/q/51815249
upvote count: 7
downvote count: 0
has body: You can just do def is_this_5(x): return x == 5 as I assume you are trying to return a boolean, and == returns a boolean result.
type: Answer
score: 7

http://stackoverflow.com/q/51867876
has comment: http://stackoverflow.com/comment/90687797
has answer: http://stackoverflow.com/a/51869933
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/90688254
score: 0
has comment: http://stackoverflow.com/comment/90687913
has comment: http://stackoverflow.com/comment/90689557
answer count: 1
linked to: http://stackoverflow.com/q/43137288
tagged with: keras
has comment: http://stackoverflow.com/comment/90688119
has title: Keras - improve memory performance
has body: I am running a convolutional neural network on input set that is 5GB, and training output is same size, so total of 10GB of data. I am reserving about 50GB of memory, but still getting memory issues. I am using adam optimizer, my model fitting looks like this: cnn_model.fit(x_train,y_train, validation_data=(x_test,y_test), callbacks=[earlystopper], epochs=25) Any idea how I can improve the situation? Someone here https://github.com/tensorflow/tensorflow/issues/18736 says "Adam and RMSProp are problematic because they memorize historical gradients", any ideas how to address that?
tagged with: out-of-memory
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90687667
tagged with: conv-neural-network
has comment: http://stackoverflow.com/comment/90687888

http://stackoverflow.com/comment/91132582
score: 0
has text: Excellent - just worked for me on an 8 year old macbook pro with El Capitan installed
type: AnswerComment
comment on: http://stackoverflow.com/a/51925618
type: Comment

http://stackoverflow.com/comment/90625516
comment on: http://stackoverflow.com/a/51835492
type: AnswerComment
score: 0
has text: I have already tried this method. When we apply this method on series of dates then it gives us warning. like : Pass `tzinfos` argument in order to correctly return a timezone-aware datetime. You can see tzinfo is None. there should be something GMT or IST.
type: Comment

http://stackoverflow.com/comment/90672324
has text: yes, features always in sorted order
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51859917
score: 0

http://stackoverflow.com/comment/106258146
type: Comment
score: 1
type: AnswerComment
has text: This will cause the admin panel to use your views instead of the admin ones. Not a good solution because it skews the admin panel user experience.
comment on: http://stackoverflow.com/a/51861472

numpydoc
tag name: numpydoc
tags question: http://stackoverflow.com/q/51814010
type: Tag

http://stackoverflow.com/q/51815254
tagged with: visual-studio
has title: Deploying a SpaCY application in Flask using Docker
type: Question
has body: I have a SpaCY application written in Python Flask to detect Named Entities which is to be used as a service in tandem with another application. It was created as a Python app using Visual Studio and the virtual environment is Python Version (3.6). I deployed it on Azure as a windows VM and works great as is. Next step was to deploy using Docker. I created a Dockerfile, built an image and ran it. It does run and shows the url and port. But upon accessing any defined route I get a "This site cannot be reached". I am able to directly run the python project or through visual studio and have no problems which led me to believe that the problem is in my Dockerfile or my understanding of it. As a guide I started following Microsoft's Azure tutorial (https://learn.microsoft.com/en-us/azure/container-instances/container-instances-tutorial-prepare-app) and used the sample project : https://github.com/Azure-Samples/aci-helloworld and I was able to build a dockerfile and access its routes. Now it leads me to believe that either SpaCY, my dockerfile or some incompatibility between SpaCY and Docker is causing this. Any help on this would be greatly appreciate. If I am missing any information, I would be happy to add it. My project structure : SpaCYParser env runserver.py ( This will fire up the server ) SpaCYParser init.py parser.py runserver.py from SpaCYParser import app if __name__ == '__main__': app.run() init.py from flask import Flask app = Flask(__name__) parser.py from flask import request, jsonify, make_response from SpaCYParser import app import json, spacy from SpaCYParser import parserOutput from SpaCYParser import Entity from SpaCYParser import NEREntities @app.route('/') @app.route('/test') def ping(): print("hello world") return "HELLO WORLD" @app.route('/parse') def parse(): # NER Specific code. My Docker File : FROM tiangolo/uwsgi-nginx-flask:python3.6 LABEL Name=mparser Version=0.0.1 ENV LISTEN_PORT=5000 EXPOSE 5000 WORKDIR /mparser COPY . /mparser # Using pip:…
downvote count: 0
tagged with: flask
score: 4
tagged with: docker
has comment: http://stackoverflow.com/comment/119121947
has comment: http://stackoverflow.com/comment/92618236
favorite count: 0
tagged with: spacy
answer count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/120005645
upvote count: 4

http://stackoverflow.com/q/51828044
favorite count: 0
has comment: http://stackoverflow.com/comment/90610476
tagged with: python
tagged with: list
type: UnansweredQuestion
has title: Getting argument error while converting set to list
downvote count: 2
tagged with: set
upvote count: 7
has comment: http://stackoverflow.com/comment/90610494
type: Question
has body: I have a set that I am trying to convert to a list, but I get Error in argument: u'(different_aois)' ipdb&gt; l = list(different_aois) *** Error in argument: u'= list(different_aois)' ipdb&gt; type(different_aois) &lt;type 'set'&gt; ipdb&gt; list(different_aois) *** Error in argument: u'(different_aois)'
has comment: http://stackoverflow.com/comment/90610502
has comment: http://stackoverflow.com/comment/90610488
has answer: http://stackoverflow.com/a/51828091
score: 5
has comment: http://stackoverflow.com/comment/90611820
answer count: 1

http://stackoverflow.com/comment/90693373
score: 0
type: Comment
type: QuestionComment
has text: but as the loop goes on it will fail, for 6 >> 2 << 2
comment on: http://stackoverflow.com/q/51870848

http://stackoverflow.com/a/53098672
downvote count: 0
upvote count: 8
score: 8
answers question: http://stackoverflow.com/q/51943050
has comment: http://stackoverflow.com/comment/93610903
type: Answer
has comment: http://stackoverflow.com/comment/109425268
has body: I had similar issues, in my case I was missing the cuDNN library, which prevented dlib from compiling with CUDA instructions, although I had CUDA compiler and other drivers installed. The next part is to download dlib from this repo. Then run this command to install dlib with CUDA and AVX instructions, you do not need to manually compile it with CMake using make file: python setup.py install --yes USE_AVX_INSTRUCTIONS --yes DLIB_USE_CUDA Important part now is to read the log, if the python can actually find CUDA, cuDNN and can use CUDA compiler to compile the test project. These are the important lines: -- Found CUDA: /usr/local/cuda/bin/ (found suitable version "8.0", minimum required is "7.5") -- Looking for cuDNN install... -- Found cuDNN: /usr/local/cuda/lib64/libcudnn.so -- Building a CUDA test project to see if your compiler is compatible with CUDA... The second problem I was facing was related to CMake versions. The latest version had some known problems with cuda and dlib, so I had to install CMake 3.12.3 in order to make it work.

http://stackoverflow.com/comment/90813185
score: 1
has text: @ElyFialkoff I think `readlines()` is correct here, though it wouldn't be needed. Simply using `for line in f` would be more efficient and avoid storing the whole file in memory at once.
comment on: http://stackoverflow.com/q/51931582
type: Comment
type: QuestionComment

modelica
tag name: modelica
type: Tag
tags question: http://stackoverflow.com/q/51829373

http://stackoverflow.com/q/51851733
tagged with: tensorflow-datasets
tagged with: python
has answer: http://stackoverflow.com/a/51852973
tagged with: tensorflow
type: AnsweredQuestion
has body: I cannot get this code to work, where am I wrong? dataset = tf.data.Dataset.from_tensors(np.arange(8)) dataset = dataset.apply(tf.contrib.data.sliding_window_batch(window_size=4)) iterator = dataset.make_one_shot_iterator() element = iterator.get_next() with tf.Session() as sess: while True: try: print(sess.run(element)) except tf.errors.OutOfRangeError: print('end') break I would have expected [0,1,2,3],[1,2,3,4],... but instead I get nothing. EDIT: if I do print(dataset) before apply I get &lt;TensorDataset shapes: (8,), types: tf.int64&gt;, after apply I get &lt;_SlideDataset shapes: (?, 8), types: tf.int64&gt;, which is not what I expected: shouldn't the shape of _SlideDataset be (?, 4)?
accepted answer: http://stackoverflow.com/a/51852973
type: Question
score: 0
answer count: 1
has title: tensorflow dataset sliding window batch not working?

http://stackoverflow.com/comment/90660383
comment on: http://stackoverflow.com/q/51852983
has text: Hm, interesting. It doesn't produce any errors for me, so far I only get empty files. It seems like it's related to [Decode Hex String in Python 3](https://stackoverflow.com/questions/3283984/decode-hex-string-in-python-3), or [Convert(decode) hex string to ASCII or any other understandable format](https://stackoverflow.com/questions/29547104/convertdecode-hex-string-to-ascii-or-any-other-understandable-format), but I can't solve it yet, will keep trying and update with any success.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90636884
score: 0
type: Comment
type: QuestionComment
has text: Here you go! :)
comment on: http://stackoverflow.com/q/51840708

http://stackoverflow.com/comment/90813606
score: 0
comment on: http://stackoverflow.com/a/51903181
type: Comment
has text: Appreciated, but I was looking for a way to represent this relationship using the declarative relationship framework. It's easy enough to query query these things (I could even use the raw SQL I provided) but I am looking to make a bit more automatic.
type: AnswerComment

http://stackoverflow.com/q/51909250
score: 0
has answer: http://stackoverflow.com/a/51909274
answer count: 2
has comment: http://stackoverflow.com/comment/90768769
has body: I have written a program that uses Scapy. Python is able to import the scapy module perfectly but using sniff function of scapy requires running the program as administrator. However, running the program as sudo python3 &lt;program_name&gt; produces an import error, why is it so? Here is the import line : import scapy.all as scapy
has answer: http://stackoverflow.com/a/51910255
tagged with: sudoers
favorite count: 0
possible better answer: http://stackoverflow.com/a/51909274
tagged with: linux
tagged with: python
has comment: http://stackoverflow.com/comment/90768615
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51910255
upvote count: 1
downvote count: 1
has title: Import error in Python 3.6 with sudo?
type: Question
tagged with: ubuntu

django-rest-auth
tag name: django-rest-auth
type: Tag
tags question: http://stackoverflow.com/q/51822247

http://stackoverflow.com/q/51863740
has comment: http://stackoverflow.com/comment/90679780
tagged with: parsing
favorite count: 0
tagged with: python-3.x
upvote count: 2
type: UnansweredQuestion
has body: I built this function to tell me whether there have been changes to the website. I'm not sure if it works as I have tried it on a few websites that have not changed and it has given me the wrong output. Where is the issue and is there an issue at all? This is the code: I put the code into a function so that I could allow the user to input any site userurl=input("Please enter a valid url") def checksite(userurl): change=False import time import urllib.request import io u = urllib.request.urlopen(userurl) webContent1 = u.read() time.sleep(60) u = urllib.request.urlopen(userurl) webContent2 = u.read() if webContent1 == webContent2: print("Everything is normal") elif webContent1 !=webContent2: print("Warning, there has been a change to the webite!") change=True return change checksite(userurl)
tagged with: python
has answer: http://stackoverflow.com/a/51864058
score: 1
has comment: http://stackoverflow.com/comment/90679684
downvote count: 1
tagged with: urllib
type: Question
has answer: http://stackoverflow.com/a/51863905
has answer: http://stackoverflow.com/a/51863885
answer count: 3
tagged with: http://stackoverflow.com/tag/html
has title: How do i understand whether i am parsing the websites acurately?

http://stackoverflow.com/q/51910530
has comment: http://stackoverflow.com/comment/90771254
has comment: http://stackoverflow.com/comment/90772218
has body: I am trying to use python to get access to the inspect element code from a page that i have already open. I tried using selenium import selenium driver = selenium.webdriver.Chrome() driver.get("mywebsite") html = driver.execute_script("return document.documentElement.innerHTML;") It works, giving me the code, but it opens the a new chrome page. Thanks.
type: Question
score: 0
has title: How to get access to a page's "Inspect Element" code without opening a new page
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90771428
linked to: http://stackoverflow.com/q/16180428
tagged with: python
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/90690673
has text: print out `counts` and see if you are seeing the pairs you expect. It looks like you have picked up and extra `tuple` value. Which you shouldn't get with the above code.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51869123

http://stackoverflow.com/comment/90665541
type: Comment
has text: @Ian_De_Oliveira - Hmmm, why it is necessary? Do you need join all `10` together? Because if use `dataframes['ISCOGroups_en.csv']` it is like `df`, check it by `print (type(dataframes['ISCOGroups_en.csv'])`
type: AnswerComment
comment on: http://stackoverflow.com/a/51854783
score: 0

http://stackoverflow.com/comment/90822129
type: QuestionComment
type: Comment
has text: All: This is my first post, my apologies for missing out on some of the key parts you are asking about. I'm using Python 3. The code I have written is all over the place but the part that I am stuck on is how to have the name (John, Sally or Bill) be the key to a nested dictionary if I am pulling that name from an existing dictionary. In other words: How do I get Bill to be the key for {"Bill":{"Attribute": "hair_color", "Value": NULL"}
comment on: http://stackoverflow.com/q/51935940
score: 0

http://stackoverflow.com/comment/90974299
has text: I'd suggest using the new API instead
score: 0
comment on: http://stackoverflow.com/a/51911016
type: Comment
type: AnswerComment

http://stackoverflow.com/a/51831901
score: 13
answers question: http://stackoverflow.com/q/51831726
downvote count: 0
upvote count: 13
type: AcceptedAnswer
has body: The short answer to the question is: requests will close a connection in the case of any exception, including KeyboardInterrupt and SystemExit. A little digging into the requests source code reveals that requests.get ultimately calls the HTTPAdapter.send method (which is where all the magic happens). There are two ways in which a request might be made within the send method: chunked or not chunked. Which send we perform depends on the value of the request.body and the Content-Length header: chunked = not (request.body is None or 'Content-Length' in request.headers) In the case where the request body is None or the Content-Length is set, requests will make use of the high-level urlopen method of urllib3: if not chunked: resp = conn.urlopen( method=request.method, url=url, body=request.body, # ... ) The finally block of the urllib3.PoolManager.urlopen method has code that handles closing the connection in the case where the try block didn't execute successfully: clean_exit = False # ... try: # ... # Everything went great! clean_exit = True finally: if not clean_exit: # We hit some kind of exception, handled or otherwise. We need # to throw the connection away unless explicitly told not to. # Close the connection, set the variable to None, and make sure # we put the None back in the pool to avoid leaking it. conn = conn and conn.close() release_this_conn = True In the case where the response can be chunked, requests goes a bit lower level and uses the underlying low level connection provided by urllib3. In this case, requests still handles the exception, it does this with a try / except block that starts immediately after grabbing a connection, and finishes with: low_conn = conn._get_conn(timeout=DEFAULT_POOL_TIMEOUT) try: # ... except: # If we hit any problems here, clean up the connection. # Then, reraise so that we can handle the actual exception. low_conn.close() raise Interestingly the connection may not be closed if there are no errors, depending on how you have …
accepted answer of: http://stackoverflow.com/q/51831726
type: Answer

http://stackoverflow.com/comment/90744617
score: 0
type: Comment
type: QuestionComment
has text: How are you importing the data?
comment on: http://stackoverflow.com/q/51896429

http://stackoverflow.com/comment/130119459
type: AnswerComment
type: Comment
score: 1
has text: Cool. Thanks for clarifying that!
comment on: http://stackoverflow.com/a/70907644

http://stackoverflow.com/comment/90656464
type: QuestionComment
comment on: http://stackoverflow.com/q/51851723
has text: Possible duplicate of [Parallelize apply after pandas groupby](https://stackoverflow.com/questions/26187759/parallelize-apply-after-pandas-groupby)
score: 0
type: Comment

http://stackoverflow.com/comment/90756069
comment on: http://stackoverflow.com/q/51902453
score: 0
type: Comment
type: QuestionComment
has text: Please, present your code with proper indentation

http://stackoverflow.com/comment/90740713
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51894781
has text: Thanks for your explanation. Could you please explain what is "framerate of 20"?
type: AnswerComment

http://stackoverflow.com/comment/90835840
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51942904
has text: @PMende I did use `pyplot.subplot`, but not able to get the axes in sync. I also put in an edit in the question, where I show a way to do this, but the axes are not in order.
score: 0

http://stackoverflow.com/comment/90568005
has text: How the error occurred? While trying to create **`Contexts`** instance?
comment on: http://stackoverflow.com/q/51806240
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/104432807
score: 0
type: AnswerComment
has text: @jamesmartini please create a new question
type: Comment
comment on: http://stackoverflow.com/a/51949988

phrase
type: Tag
tag name: phrase
tags question: http://stackoverflow.com/q/51837249

http://stackoverflow.com/q/51946815
has body: I have following main dataframe in python ID Date Product_Name transaction 1 01-01-2018 MS 234 1 01-02-2018 MS 2345 1 02-02-2018 MS 234 2 01-01-2018 HSD 2312 2 02-02-2018 HSD 2234 3 01-01-2018 MS 2123 3 02-02-2018 MS 345 Now,I want to subset dataframes based on ID and Product_Name more of a dynamic nature. So from above dataframe it will create 3 dynamic dataframes(Based on unique values from ID and Product_Name columnns) with following subset filters and name it like MS_1,HSD_2,MS_3 ID = 1 and Product_Name = 'MS' ID = 2 and Product_Name = 'HSD' ID = 3 and Product_Name = 'MS' Is it possible to do it in pandas?
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/51946871
type: AnsweredQuestion
has title: how to get dynamic dataframes created in function in pandas
score: 1
upvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/51946871

http://stackoverflow.com/comment/90808007
has text: Indeed, I’m using a factory so the right object is created, but perhaps the dictionary where it looks could be built by a metaclass every time a new subtype is added? I wonderered if a good use of metaclasses was to create a constraint of how classes will have to look (its methods, for example) in order for it to function
comment on: http://stackoverflow.com/a/51928708
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/51941471
has body: tl;dr: Instead of doing item(row_selected)['values'], do item(row_selected, option='values'). I think this is actually a bug in tkinter, and the workaround is actually relying on another bug, so I filed both as b.p.o. #34447. But let's see what the tkinter experts over there say. Meanwhile, you hopefully want to understand why that makes a difference, right? If you look at the docs for item: Query or modify the options for the specified item. If no options are given, a dict with options/values for the item is returned. If option is specified then the value for that option is returned. Otherwise, sets the options to the corresponding values as given by kw. So, if you ask for the values option, you get the values option's value. But if you don't ask for anything, tkinter tries to get clever and give you a dict with all of the options. The problem is that, under the covers, tkinter is a wrapper around Tcl/Tk. In Tcl, everything is a string (it's more like, say, bash in this regard than Python); there's no difference between the number 123 and the string '123'. It's perfectly legal to store ints in TreeView items, but they get stored exactly the same way as strings. And what's returned by the Tcl code to get all of the options for an item is a Tcl list of Tcl key-value pairs where all of the values are Tcl strings. Tkinter has no idea which ones were supposed to be strings, and which were supposed to be ints.2 So it tries to guess: any string that can be converted to an int with the int constructor is an int, anything else is a string.1 And your string can be converted to an int3, so it is. Of course this is pretty hacky, but it usually does what you want, and it makes things more convenient when it does, and "pretty hacky but usually does what you want conveniently" is almost the definition of tkinter. However, I think it ought to recognize that, while '123_456' is a perfectly valid Python integer literal, it's not a string that could ever be created by Tcl for an inte…
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51941260
score: 4
accepted answer of: http://stackoverflow.com/q/51941260
upvote count: 4
type: AcceptedAnswer

http://stackoverflow.com/comment/131076044
type: Comment
comment on: http://stackoverflow.com/a/73413938
has text: sys.executable will give only the current folder where jupyter runed not the env_path as desribed in https://stackoverflow.com/questions/36539623/how-do-i-find-the-name-of-the-conda-environment-in-which-my-code-is-running
score: 0
type: AnswerComment

http://stackoverflow.com/a/51936578
has body: You don't do that in the model. The model is simply a table in a database, so there you just define that the fields start_date and end_date are of the type DateTimeField. You can find more info here: Django Models What you are trying to accomplish you ca do it in other part of Django, like in the view. There, when you get the dates inserted by the user, you can validate that start_date is in the future and end_date is after.
score: 0
answers question: http://stackoverflow.com/q/51936447
type: Answer

http://stackoverflow.com/a/51803106
score: 6
has body: Owing to its greater flexibility, there is more going on behind the scenes in the first version. After all, a if b else c is an expression with 3 possibly distinct input variables/expressions, while a or b is binary. You can disassemble the expressions to get a better idea: def a(x): return x if x else '' def b(x): return x or '' &gt;&gt;&gt; import dis &gt;&gt;&gt; dis.dis(a) 2 0 LOAD_FAST 0 (x) 2 POP_JUMP_IF_FALSE 8 4 LOAD_FAST 0 (x) 6 RETURN_VALUE &gt;&gt; 8 LOAD_CONST 1 ('') 10 RETURN_VALUE &gt;&gt;&gt; dis.dis(b) 2 0 LOAD_FAST 0 (x) 2 JUMP_IF_TRUE_OR_POP 6 4 LOAD_CONST 1 ('') &gt;&gt; 6 RETURN_VALUE
answers question: http://stackoverflow.com/q/51802974
upvote count: 7
downvote count: 1
type: Answer

http://stackoverflow.com/comment/90710728
comment on: http://stackoverflow.com/q/51879476
has text: @ChenA Sure, but I'm not sure how the exact naming of the inner directory is important. In django apps, for instance, it is customary to have a nested directory with the same name as the project.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51910876
has comment: http://stackoverflow.com/comment/90773254
has comment: http://stackoverflow.com/comment/90772670
has comment: http://stackoverflow.com/comment/90773536
has comment: http://stackoverflow.com/comment/90772688
accepted answer of: http://stackoverflow.com/q/51910563
has comment: http://stackoverflow.com/comment/90773934
has comment: http://stackoverflow.com/comment/90772651
has comment: http://stackoverflow.com/comment/90773134
has comment: http://stackoverflow.com/comment/90771943
has comment: http://stackoverflow.com/comment/90773443
answers question: http://stackoverflow.com/q/51910563
has comment: http://stackoverflow.com/comment/90772998
score: 0
has comment: http://stackoverflow.com/comment/90772906
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90772703
has body: You can use csv.DictReader to create a list of OrderedDicts from your data file. Then you can rearrange and transform your data to make the nested dictionary to meet your requirements. Here is an example using dictionary comprehension. import csv with open('text.csv') as f: reader = csv.DictReader(f) result = { int(d['KEY']):{k: int(v) if v.isdigit() else v for k, v in d.items() if k != 'KEY'} for d in reader if d['KEY'].isdigit()} print(result) EDIT: If all you need is the string values as posted in Tanmay's solution then this does the same with a lot less code. import csv from pprint import pprint with open('text.csv') as f: results = {d.pop('KEY'): dict(d) for d in csv.DictReader(f)} pprint(results) EDIT 2: casting values import csv from pprint import pprint import re def cast_dict(d: dict): def cast_value(value: str): if value.isdigit(): return int(value) elif re.match(r'^\d+\.\d+$', value): return float(value) return value return {k: cast_value(v) for k, v in d.items()} with open('text.csv') as f: results = {int(d.pop('KEY')): cast_dict(d) for d in csv.DictReader(f) if d.get['KEY'].isdigit()} pprint(results) pprint(results)
has comment: http://stackoverflow.com/comment/90772997
has comment: http://stackoverflow.com/comment/90772976
type: Answer
has comment: http://stackoverflow.com/comment/90772590

http://stackoverflow.com/a/51954032
score: 1
upvote count: 1
downvote count: 0
has body: Downloading the csv will make a copy to your local storage, a pro to this is that you could make in-place edits to the files if necessary and it will be faster on the back-end to access. Plus, since the copy is local you will not need an internet connection to play with the data. The obvious con is that over time you will use a lot of storage. Streaming has the obvious benefit of accessing the data remotely so you do not use up your own storage. Cons are that it is slower than accessing a downloaded file because it will rely on the speed of your internet, as well as it will constantly be using bandwidth to look at files. This just means that over time, if you run this program on multiple files at once the bandwidth will stack up quickly, and could make some other internet users angry. Reading the file directly from the S3 path will probably be your best bet. This will store the data as a pandas dataframe in memory and only access the data once (to store it). Then all further changes to the dataframe will be applied to the object in memory. The best method will depend on your downstream applications. I do not think downloading the csv file will ever be the most practical method, because your code is pointing to the s3 bucket. The only practical purpose of downloading the data would be to access it without internet (in which case you would download the file outside of the code and then access it from your local pc). Your code 2 and 3 are redundant. When you are streaming the data that is fine, but then you are loading it as a dataframe object anyway, which kind of defeats the purpose of reading the file as a stream. The amount of data in the dataframe will be the same because you're storing it eventually. I think METHOD 3, will be your best bet because it takes away that unnecessary redundancy.
answers question: http://stackoverflow.com/q/51953557
type: Answer

http://stackoverflow.com/comment/90593771
has text: [read this](https://docs.citrix.com/en-us/receiver/chrome/current-release/deploy.html)
comment on: http://stackoverflow.com/a/51819324
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/51871867
downvote count: 0
has body: The reason for this error is that set.union() expects one or more sets (ie set.union(oneset, anotherset, andathirdone)), not a list nor generator. The solution is to unpack your list or generator: &gt;&gt;&gt; set().union( *({n, 2*n} for n in range(5)) ) {0, 1, 2, 3, 4, 6, 8}
type: Answer
upvote count: 4
answers question: http://stackoverflow.com/q/51871836
accepted answer of: http://stackoverflow.com/q/51871836
score: 4
type: AcceptedAnswer

http://stackoverflow.com/a/51810679
upvote count: 1
has body: You could do something like this: import tkinter as tk # &lt;-- avoid star imports class Custom_RadioButton(tk.Frame): def __init__(self, master, *args, **kwargs): super().__init__(self, master, *args, **kwargs) self.canvas = tk.Canvas(self) # place a canvas into self (a Frame) self.canvas.pack(expand=True, fill=tk.BOTH) self.label = tk.Label(self.canvas, text='clickme') # place a label in self.canvas self.canvas.create_oval(.....) # draw a circle on self.canvas
has comment: http://stackoverflow.com/comment/90576329
has comment: http://stackoverflow.com/comment/90576313
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51810561
downvote count: 0
answers question: http://stackoverflow.com/q/51810561
type: Answer
score: 1

http://stackoverflow.com/comment/90607871
type: Comment
comment on: http://stackoverflow.com/q/51826721
score: 0
has text: Got it. Thanks for that
type: QuestionComment

http://stackoverflow.com/comment/90698903
comment on: http://stackoverflow.com/q/51873598
score: 0
has text: in this line of code `places = geograpy.get_place_context(text=text)` what is that `text` variable you are passing? is it defined else where? did you mean `places = geograpy.get_place_context(url=url)`?
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51899115
tagged with: defaultdict
upvote count: 3
has answer: http://stackoverflow.com/a/51899391
tagged with: python
tagged with: dictionary
favorite count: 0
has comment: http://stackoverflow.com/comment/90749848
has comment: http://stackoverflow.com/comment/90750311
type: UnansweredQuestion
has body: How to increment d['a']['b']['c'][1][2][3] if d is defaultdict of defaultdict without code dublication? from collections import defaultdict nested_dict_type = lambda: defaultdict(nested_dict_type) nested_dict = nested_dict_type() # incrementation if type(nested_dict['a']['b']['c']['d'][1][2][3][4][5][6]) != int: nested_dict['a']['b']['c']['d'][1][2][3][4][5][6] = 0 nested_dict['a']['b']['c']['d'][1][2][3][4][5][6] += 1 # ok, now it contains 1 Here we can see that we duplicated (in the code) a chain of keys 3 times. Question: Is it possible to write a function inc that will take nested_dict['a']['b']...[6] and do the same job as above? So: def inc(x): if type(x) != int: x = 0 x += 1 inc(nested_dict['a']['b']['c']['d'][1][2][3][4][5][6]) # ok, now it contains 1 Update (20 Aug 2018): There is still no answer to the question. It's clear that there are options "how to do what I want", but the question is straightforward: there is "value", we pass it to a function, function modifies it. It looks that it's not possible. Just a value, without any "additional keys", etc. If it is so, can we make an answer more generic? Notes: What is defaultdict of defaultdicts - SO. This question is not about "storing of integers in a defaultdict", so I'm not looking for a hierarchy of defaultdicts with an int type at the leaves. Assume that type (int in the examples) is known in advance / can be even parametrized (including the ability to perform += operator) - the question is how to dereference the object, pass it for modification and store back in the context of defaultdict of defaultdicts. Is the answer to this question related to the mutability? See example below: Example: def inc(x): x += 1 d = {'a': int(0)} inc(d['a']) # d['a'] == 0, immutable d = {'a': Int(0)} inc(d['a']) # d['a'] == 1, mutated Where Int is: class Int: def __init__(self, value): self.value = value def __add__(self, v): self.value += v return self def __repr__(self): return str(self.value)
has comment: http://stackoverflow.com/comment/90750231
has title: How to increment a value (in defaultdict of defaultdicts)?
linked to: http://stackoverflow.com/q/986006
downvote count: 4
tagged with: recursion
has comment: http://stackoverflow.com/comment/90749935
linked to: http://stackoverflow.com/q/19189274
score: -1
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/51899490

http://stackoverflow.com/q/51910169
downvote count: 0
favorite count: 0
tagged with: modbus
has title: python communication MODBUS TCP/IP raspberry pi and HMI - write value
upvote count: 2
type: UnansweredQuestion
tagged with: python
score: 2
tagged with: tcp
has answer: http://stackoverflow.com/a/51910938
type: Question
has body: I'm French student and i need your help in Python for my program. I've got a program in my rapsberry in Python which acquire datas from temperature and hygrometry sensors. I need to communicate these values to an Human Machine Interface supervisor by the MODBUS TCP/IP PROTOCOL to display and made some graphics of these values in my HMI The IP adress of the raspberry : 172.16.0.2 The IP adress of the HMI : 172.16.0.10 I think I need to use package like pyModbusTCP or things like that but I don't understand how to use it. Could you help me to understand how I made the communication between my Rpi and my HMI and for example how I could write the integer value 100 at the address index 1? Thanks for all! Antoine
tagged with: raspberry-pi
answer count: 1

http://stackoverflow.com/q/51879018
has answer: http://stackoverflow.com/a/51879675
accepted answer: http://stackoverflow.com/a/51879108
has body: I have a dataframe with a column that contains street intersections | Locations | -------------------------------- |W Madison Ave &amp; S Randall Blvd| |N Clemson St &amp; E Tower Ave | |E Thompson St &amp; S Garfield Ln | I'd like to remove the directional characters (N, S, E, W) as well as the suffixes of the streets (Blvd, St, Ave, etc...) so that my output looks like this | Locations | --------------------- |Madison &amp; Randall | |Clemson &amp; Tower | |Thompson &amp; Garfield| I can't do a str.replace() because it would be removing characters from the words I need to stay. I tried using lstrip() and rstrip() but that wouldn't fix the characters I'd like removed from the middle of the string. I also tried experimenting with Series.apply() banned = ['N', 'S', 'E', 'W', 'Ave', 'Blvd', 'St', 'Ln'] df["Locations"].apply(lambda x: [item for item in x if item not in banned]) But this essentially does a str.replace() and places everything in a list in the dataframe instead.
answer count: 4
has answer: http://stackoverflow.com/a/51879255
tagged with: pandas
type: AnsweredQuestion
score: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/90709561
favorite count: 0
possible better answer: http://stackoverflow.com/a/51879255
has answer: http://stackoverflow.com/a/51882760
type: Question
has answer: http://stackoverflow.com/a/51879108
tagged with: python
has comment: http://stackoverflow.com/comment/90710226
has title: Removing words/characters from string in dataframe cell?
upvote count: 3

http://stackoverflow.com/a/51856254
score: 1
has body: OR try the below code, using map: lod=[{0: 26}, {0: 36}, {1: 1}, {0: 215}, {1: 63}, {0: 215}] print(list(map(lambda x: list(x.keys())[0])))
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/51855360
downvote count: 0

http://stackoverflow.com/comment/90758443
score: 1
has text: Yeah, but. How long would it take to work out what this is doing if you came across it cold?
comment on: http://stackoverflow.com/a/51903720
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/90578759
score: 0
type: Comment
type: AnswerComment
has text: This helps but I now think I have an issue where I may need to lock `self._capacity`. The value of the capacity is getting added too much by each routine I think. 200 0:00:00.201525 0 Releasing Semaphore Successfully acquired the semaphore Successfully acquired the semaphore Successfully acquired the semaphore Successfully acquired the semaphore 200 0:00:00.698236 28 Releasing Semaphore 200 0:00:00.702178 29 Releasing Semaphore 200 0:00:00.704255 31 Releasing Semaphore 200 0:00:00.707803 36 Releasing Semaphore Main Coroutine All Workers Completed
comment on: http://stackoverflow.com/a/51811834

http://stackoverflow.com/comment/90769231
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51908642
has text: @SharvilMainkar how many possible values should you have? How should they be distributed in the interval?
score: 0

http://stackoverflow.com/tag/r
tags question: http://stackoverflow.com/q/51929945
tags question: http://stackoverflow.com/q/51934413
tags question: http://stackoverflow.com/q/51946413
tags question: http://stackoverflow.com/q/51897517
tags question: http://stackoverflow.com/q/51942913
tags question: http://stackoverflow.com/q/51867868
tags question: http://stackoverflow.com/q/51810759
tags question: http://stackoverflow.com/q/51903754
tags question: http://stackoverflow.com/q/51882272
tag name: r
tags question: http://stackoverflow.com/q/51908679
tags question: http://stackoverflow.com/q/51938097
tags question: http://stackoverflow.com/q/51929083
tags question: http://stackoverflow.com/q/51817345
type: Tag
tags question: http://stackoverflow.com/q/51804842
tags question: http://stackoverflow.com/q/51909715
tags question: http://stackoverflow.com/q/51841002
tags question: http://stackoverflow.com/q/51887163
tags question: http://stackoverflow.com/q/51858187
tags question: http://stackoverflow.com/q/51866330
tags question: http://stackoverflow.com/q/51813317
tags question: http://stackoverflow.com/q/51807632
tags question: http://stackoverflow.com/q/51878227

http://stackoverflow.com/q/51945421
has title: Why is variable not updated outside of loop?
type: Question
has answer: http://stackoverflow.com/a/51945801
has body: Can't figure out why the first key from the result is "abc" and not "c" as I'd expect. (I'm using Python 3.6.4) Data structure is weird because I removed not relevant keys and values. f = { 'replace' : { 'ab' : ''} } r = {} data = { 'abc' : 1, 'def' : 2, 'ghi' : 3, 'jkf' : 4, 'lmn' : 5 } for d in data: replaced = 'hello' for x in f['replace']: if x in d: replaced = d.replace(x, f['replace'][x]) print(replaced) else: replaced = d r.update( { replaced : data[d] } ) print(r)
score: 2
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/51945801
upvote count: 2
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/51857468
upvote count: 9
accepted answer: http://stackoverflow.com/a/51857546
has answer: http://stackoverflow.com/a/51857738
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90667142
has body: I've copied a large number of .jpg images from my Google Drive to Google Colab per Google Colab: how to read data from my google drive?: local_download_path = os.path.expanduser('~/data') try: os.makedirs(local_download_path) except: pass # 2. Auto-iterate using the query syntax # https://developers.google.com/drive/v2/web/search-parameters file_list = drive.ListFile( {'q': "'1SooKSw8M4ACbznKjnNrYvJ5wxuqJ-YCk' in parents"}).GetList() for f in file_list: # 3. Create &amp; download by id. print('title: %s, id: %s' % (f['title'], f['id'])) fname = os.path.join(local_download_path, f['title']) print('downloading to {}'.format(fname)) f_ = drive.CreateFile({'id': f['id']}) f_.GetContentFile(fname) This completed, so all the image files should be in a data folder. How do I actually access these files now? I'd like to loop through all files that are of type .jpg in the data folder.
downvote count: 0
possible better answer: http://stackoverflow.com/a/51857738
has answer: http://stackoverflow.com/a/57857176
has answer: http://stackoverflow.com/a/51857546
type: Question
has title: Google Colab: How to loop through images in a folder?
linked to: http://stackoverflow.com/q/48376580
score: 9
answer count: 3
favorite count: 0

http://stackoverflow.com/q/51812784
has title: Is it always possible to convert a class that implements the content manager into function that uses contextmanager decorator?
accepted answer: http://stackoverflow.com/a/51812833
type: Question
tagged with: python
answer count: 1
score: 0
has comment: http://stackoverflow.com/comment/90580508
has comment: http://stackoverflow.com/comment/90580524
has answer: http://stackoverflow.com/a/51812833
tagged with: contextmanager
has body: I have the following class that implements the context manager protocol: class Indenter: def __init__(self): self.level = 0 def __enter__(self): self.level += 1 return self def __exit__(self, exc_type, exc_val, exc_tb): self.level -= 1 def print(self, text): print('\t' * self.level + text) The following code: with Indenter() as indent: indent.print('bye!') with indent: indent.print('goodbye') with indent: indent.print('au revoir') indent.print('bye bye') produces the following output: bye! goodbye au revoir bye bye Now, I want to produce the same functionality, but instead of implementing a class, I want to use the contextmanager decorator. I have the following code so far: class Indenter: def __init__(self): self.level = 0 def print(self, text): print('\t' * self.level + text) @contextmanager def indenter(): try: i = Indenter() i.level += 1 yield i finally: i.level -= 1 However, I cannot produce the same output when I call: with indenter() as indent: indent.print('hi!') with indent: indent.print('hello') with indent: indent.print('bonjour') indent.print('hey') What am I doing wrong? Is it possible to achieve what I am doing with the class that implements the context manager with the function decorated by the contextmanager decorator? Main question: Is it possible to convert any class that implements the context manager protocol into a function that uses the contextmanager decorator? What are the limitations of each option? Are there cases in which one is better than the other?
type: AnsweredQuestion

http://stackoverflow.com/comment/90651534
type: Comment
score: 1
has text: @Aakib Well...You seemed to misunderstand the point of my answer and my _urge_ to not use Regex to match any datetime. Does the _solution_ you provided account for a file like `Weekly Score 99.99.9999 Report.csv` ? It's not a valid datetime but your solution would match it happily. Anyways, good luck!
type: AnswerComment
comment on: http://stackoverflow.com/a/51847759

http://stackoverflow.com/comment/90864250
comment on: http://stackoverflow.com/a/51923906
type: AnswerComment
has text: I don't think you read my question. The first thing I explain is that I'd already used `pip` and it did not work for me.
type: Comment
score: 2

http://stackoverflow.com/q/51902779
tagged with: python
upvote count: 6
type: AnsweredQuestion
tagged with: setuptools
accepted answer: http://stackoverflow.com/a/51903090
tagged with: pypi
type: Question
has comment: http://stackoverflow.com/comment/90770078
has body: I'm writing a setup.py file to install an OpenSource project using PyPi package. The thing is, this project requires to install as well outside apps (ghostscript, imagemagick, and tesseract). These apps have different ways to install depending on the platform (win, linux, or mac). I wrote a file that when I execute python setup.py install install all of it. The problem is when I load the tar and whl files on PyPi and I execute pip install Gap-ML it is just installing the modules but it is not installing these apps. Here the code on setup.py: """ setup Gap-ML Copyright, 2018(c), Andrew Ferlitsch Autor: David Molina @virtualdvid """ from setuptools import setup, find_packages from distutils.command.install import install import os, sys, platform import requests ##Install custom apps Ghostscript, Imagemagick, and Tesseract def install_apps(app_name, app_path, url): """ Install custom apps :param app_name: name of the app to install :param app_path: path on windows where the app should be installed :param url: url where the .exe file is located """ #extract the app_name.exe from the url app = url.split('/')[-1] #verify if the software is already installed on windows if os.path.exists(app_path): print('{} already installed'.format(app_name)) else: print('Download has started') #warning message to specify the correct path where to install the app if platform.architecture()[0] == '64bit': print('Please verify C:\\Program Files\\ is part of the path to install the app') else: print('Please verify C:\\Program Files (x86)\\ is part of the path to install the app') #download, install, and delete the app_name.exe r = requests.get(url, allow_redirects=True) open(app, 'wb').write(r.content) os.system(os.path.join(os.getcwd(),app)) os.remove(app) #verify pythonpath to execute the apps from terminal if app_path not in sys.path: sys.path.append(app_path) print('{} has been installed successful'.format(app_name)) def main(): #verify Operative System if sys.platform.startswith('win'):…
score: 6
has comment: http://stackoverflow.com/comment/90765267
has comment: http://stackoverflow.com/comment/134435004
has title: How to include .exe, apt-get and brew install files on a PyPi setup.py file
answer count: 1
downvote count: 0
linked to: http://stackoverflow.com/q/47042483
favorite count: 0
has comment: http://stackoverflow.com/comment/134435006
has comment: http://stackoverflow.com/comment/90765156
has answer: http://stackoverflow.com/a/51903090

http://stackoverflow.com/q/51839314
score: 0
has title: Posting data to a Django model via external python script
tagged with: python
type: UnansweredQuestion
tagged with: django
has comment: http://stackoverflow.com/comment/90631826
has comment: http://stackoverflow.com/comment/90631801
has answer: http://stackoverflow.com/a/51839530
has body: I have a python script that is printing data to a .csv every one minute. I want to instead save this data to a Django database over the internet. I have a basic Django based site running by following some tutorials. But I can only post data on my database by submitting online forms. I would like to do this automatically (from python script), then view the posted data. Would the best method be: Instead of printing the data, have the python program write mydata to a url. The url would be mywebsite.com/dataPost/mydata In Django mysite directory: mysite/urls.py would forward this url to datapost/urls.py dataPost/urls.py would point to dataPost/views.py dataPost/views.py would point to dataPost/models.py where mydata would be saved to database. Assuming this is a valid high level plan, can someone give me a rough idea of what the syntax would look like? Anything will help.
type: Question
answer count: 1

http://stackoverflow.com/comment/139940755
has text: That's the only solution I could find that works for me. Huge thanks. The only thing I had to change here is changing `python` with the executable of the actual python in the desired environment.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/75937125
type: Comment

http://stackoverflow.com/a/51918237
type: Answer
has comment: http://stackoverflow.com/comment/90787201
has comment: http://stackoverflow.com/comment/90787181
downvote count: 0
answers question: http://stackoverflow.com/q/51918214
score: 1
has comment: http://stackoverflow.com/comment/90787257
accepted answer of: http://stackoverflow.com/q/51918214
has comment: http://stackoverflow.com/comment/90787246
upvote count: 1
type: AcceptedAnswer
has body: Store the change made back into p[i] for i,x in enumerate(p): if x % 5 ==0 : p[i] = p[i] + 5 You can change it while asking for input itself : p=[] for i in range(5): num=int(input()) if(num%5==0): p.append(num+10) else: p.append(num) # input : 1 2 3 4 5 # p : 1 2 3 4 15

http://stackoverflow.com/a/51862088
has comment: http://stackoverflow.com/comment/90710020
upvote count: 5
downvote count: 0
has body: Once you install python-levenshtein, it's easy as: &gt;&gt;&gt; from Levenshtein import distance &gt;&gt;&gt; distance( 'hingry', 'hungry') 1 &gt;&gt;&gt; distance( 'hungre', 'hungry') 1 &gt;&gt;&gt; distance( 'hungr', 'hungry') 1 It automatically handles: added characters removed characters replaced characters The final code might look like this: &gt;&gt;&gt; words = ['asdfd', 'hingry', 'hungre', ' hangrr'] &gt;&gt;&gt; [w for w in words if distance( 'hungry', w) &lt; 2] ['hingry', 'hungre']
type: Answer
answers question: http://stackoverflow.com/q/51861706
score: 5

http://stackoverflow.com/q/51801187
favorite count: 0
has title: Calculate the mode whilst ignoring certain values
upvote count: 2
tagged with: python
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51801256
type: Question
tagged with: numpy
has body: How can I get the mode in numpy? With the caveat that I want to ignore certain values? For example; [[-1, 2, -1], [2, -1, -1], [2, 45, 1]] In the above the mode is -1 but I want to ignore all -1 values always so the mode should be 2 in the above example. I want to determine the mode and how many times it occurs (3 in the above example). My iterative function is below: def calc_mode(values, ignore_value=-1): if values.sum() == ignore_value * values.size: return -1 mode_map = {} for (x,y), value in np.ndenumerate(values): if (value &lt;= ignore_value): continue if not value in mode_map: mode_map[value] = 1 else: mode_map[value] += 1 if len(mode_map) &lt;= 0: return -1 mode = max(zip(mode_map.values(), mode_map.keys())) return mode[1]
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/51801256

http://stackoverflow.com/a/51873139
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51872451
answers question: http://stackoverflow.com/q/51872451
score: 0
type: Answer
has body: Possible duplicate of: Write text in particular font color in MS word using python-docx Using docx python library, how to apply color and font size simultaneously You would need to use the font property. from docx import Document document = Document() run = document.add_heading().add_run("TITLE") font = run.font font.color.rgb = RGBColor(0,0,0) document.save("test.docx") Please see the python-docx documentation.

http://stackoverflow.com/comment/90754455
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51900715
type: Comment
has text: Dont drag it Just Put the path file if you drage it is like you saying you want to open the file from the cmd

http://stackoverflow.com/q/51927347
tagged with: python
score: 2
has comment: http://stackoverflow.com/comment/91013427
upvote count: 2
has title: Q: ModuleNotFoundError: No module named 'matplotlib.pyplot', etc
has comment: http://stackoverflow.com/comment/91022359
type: Question
has comment: http://stackoverflow.com/comment/91016664
has answer: http://stackoverflow.com/a/52036285
has comment: http://stackoverflow.com/comment/90804586
tagged with: matplotlib
has body: there~ I tried to find the root cause of this issue on my computer here and there, however, I didn't get the right way to fix it. Could you help me? The following is my situation. OS : Windows7 Python : Installed by Anaconda3 full package(Python3.5.6) Whenever I try to import every attributes in the module, I got the error messeges. import matplotlib as mpl There was no error messege if I just imported 'matplotlib' as above. import matplotlib.pyplot as plt Traceback (most recent call last): File "&lt;ipython-input-52-a0d2faabd9e9&gt;", line 1, in &lt;module&gt; import matplotlib.pyplot as plt ModuleNotFoundError: No module named 'matplotlib.pyplot' But, when I imported 'matplotlib.pyplot', the messege was as above. It was very weird. The same situation goes on importing 'pandas'. import pandas as pd There was also no error messege. However, when I imported 'pandas.read_csv', I got the same error messege. import pandas as pd df = pd.read_csv("baby-names.csv") --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) &lt;ipython-input-4-6e6b54911d31&gt; in &lt;module&gt; import pandas as pd df = pd.read_csv("baby-names.csv") AttributeError: module 'pandas' has no attribute 'read_csv' I can't understand my situation. Check 1) No similar file names. There are no similar file name in my working directory, such as matplotlib, pandas, python files. Check 2) sys.path I'm using Spyder(Python 3.6 in Anaconda3) as an interpreter. import sys sys.path Out[35]: ['', 'd:\\ProgramData\\Anaconda3\\lib\\site-packages\\spyder', 'd:\\ProgramData\\Anaconda3\\python36.zip', 'd:\\ProgramData\\Anaconda3\\DLLs', 'd:\\ProgramData\\Anaconda3\\lib', 'd:\\ProgramData\\Anaconda3', 'd:\\ProgramData\\Anaconda3\\lib\\site-packages', 'd:\\ProgramData\\Anaconda3\\lib\\site-packages\\win32', 'd:\\ProgramData\\Anaconda3\\lib\\site-packages\\win32\\lib', 'd:\\ProgramData\\Anaconda3\\lib\\site-packages\\Pythonwin', 'd:\\ProgramData\\Anaco…
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/90804493
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91013404

http://stackoverflow.com/a/51858108
score: 0
accepted answer of: http://stackoverflow.com/q/51858011
answers question: http://stackoverflow.com/q/51858011
type: AcceptedAnswer
type: Answer
has body: You are appending list to the end of list and as you can see you get: [elem11, elem12, ..., elem1n, [elem21, elem22, ..., elem2m]] (list inside of list) You need to use extend instead of append to add all the elements of f1.readlines() fruit.extend(f1.readlines()) Source: https://developers.google.com/edu/python/lists

http://stackoverflow.com/comment/90793853
comment on: http://stackoverflow.com/a/51922003
type: Comment
score: 1
type: AnswerComment
has text: @Hegemon1984 How are you generating the HTML? You should post a new question. (Most likely, you just need to print the value directly from the dictionary, rather than the literal string `"school.state"`.)

http://stackoverflow.com/comment/99291820
type: QuestionComment
has text: In the link, if you look at the line `remainingSamples = total_samples % batch_size #confirm that this is greater than 0` - his answer depends on the number of samples not being divisible by the batch-size, which yours is for the train_set (39592 % 2 == 0). So from what you have posted, I see no reason why batches should be missing, or individual data-points not being able to fill a batch being missing. For your validation-set, you may have a single image not being used.
comment on: http://stackoverflow.com/q/51885739
score: 0
type: Comment

http://stackoverflow.com/comment/90694068
type: QuestionComment
has text: and how is that ??
score: 0
comment on: http://stackoverflow.com/q/51871042
type: Comment

http://stackoverflow.com/q/51913177
favorite count: 0
tagged with: python-3.x
has body: I have the following class which I made: import math class Point: """Two-Dimensional Point(x, y)""" def __init__(self, x=0, y=0): # Initialize the Point instance self.x = x self.y = y def __iter__(self): yield self.x yield self.y def __add__(self, other): addedx = self.x + other.x addedy = self.y + other.y return Point(addedx, addedy) def __mul__(self, other): mulx = self.x * other muly = self.y * other return Point(mulx, muly) def __rmul__(self, other): mulx = self.x * other muly = self.y * other return Point(mulx, muly) @classmethod def from_tuple(cls, tup): x, y = tup return cls(x, y) def loc_from_tuple(self, tup): self.x, self.y = tup @property def magnitude(self): # """Return the magnitude of vector from (0,0) to self.""" return math.sqrt(self.x ** 2 + self.y ** 2) def distance(self, self2): return math.sqrt((self2.x - self.x) ** 2 + (self2.y - self.y) ** 2) def __str__(self): return 'Point at ({}, {})'.format(self.x, self.y) def __repr__(self): return "Point(x={},y={})".format(self.x, self.y) I don't exactly know how to explain it but I basically want to be able to maintain a points id despite mathematical operations. For example: point1 = Point(2, 3) point2 = Point(4, 5) id1 = id(point1) point1 += point2 print(point1) Point(x=6, y=8) print(id1 == id(point1)) True print(point2) Point(x=4, y=5) Is there a reason this doesn't happen in my code. It says False during the id part in mine.
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90777029
downvote count: 1
has comment: http://stackoverflow.com/comment/90776521
type: Question
upvote count: 0
has answer: http://stackoverflow.com/a/51913501
has comment: http://stackoverflow.com/comment/90776579
has title: ID of object not being saved
has comment: http://stackoverflow.com/comment/90777878
has comment: http://stackoverflow.com/comment/90776603
has comment: http://stackoverflow.com/comment/90776745
answer count: 1
has comment: http://stackoverflow.com/comment/90776515
score: -1

http://stackoverflow.com/q/51825453
score: 0
has answer: http://stackoverflow.com/a/51937456
has title: python regex optional named groups
has answer: http://stackoverflow.com/a/52010886
possible better answer: http://stackoverflow.com/a/51969950
has comment: http://stackoverflow.com/comment/90606445
has answer: http://stackoverflow.com/a/51969950
favorite count: 0
has answer: http://stackoverflow.com/a/51826434
has answer: http://stackoverflow.com/a/51952898
tagged with: python
has comment: http://stackoverflow.com/comment/90822841
tagged with: regex
has answer: http://stackoverflow.com/a/51937066
tagged with: parsing
type: AnsweredQuestion
upvote count: 1
linked to: http://stackoverflow.com/q/22937618
has comment: http://stackoverflow.com/comment/90823001
downvote count: 1
has comment: http://stackoverflow.com/comment/90606876
type: Question
has comment: http://stackoverflow.com/comment/90606123
duplicate of: http://stackoverflow.com/q/22937618
has body: I'm looking for a clean way to extract some data from a string using regex and the python re module. Each line of the string is of the form key = value. There are only certain keys that I'm interested in, but for some strings these keys may be missing. I can think of a few ways to do this by iterating over the string line by line, or by using re.finditer(), but what I'd really like to do is use named groups and a single call to re.match(), to end with a dictionary of groups using .groupdict() method of the returned match object. I can do that using named groups when all the groups are present, but it seems that if I make groups optional then they don't get matched even when present. I'm probably missing something obvious, but is there a way to do this in a single regex or do I need a multistep process? import re # trying to extract 'type', 'count' and 'destinations'. # string1 has all keys and a single re.match works # string2 is missing 'count'... any suggestions? string1 = """ Name: default type = Route status = 0 count = 5 enabled = False start_time = 18:00:00 end_time = 00:00:00 destinations = default started = False """ string2 = """ Name: default type = Route status = 0 enabled = False start_time = 18:00:00 end_time = 00:00:00 destinations = default started = False """ pattern = re.compile(r"(?s).*type = (?P&lt;type&gt;\S*).*count = (?P&lt;count&gt;\S*).*destinations = (?P&lt;destinations&gt;\S*)") m1 = re.match(pattern,string1) # m1.groupdict() == {'type': 'Route', 'count': '5', 'destinations': 'default'} m2 = re.match(pattern,string2) # m2 == None
accepted answer: http://stackoverflow.com/a/51937066
answer count: 6
has comment: http://stackoverflow.com/comment/90606329

http://stackoverflow.com/a/51912614
type: Answer
accepted answer of: http://stackoverflow.com/q/51912598
downvote count: 1
answers question: http://stackoverflow.com/q/51912598
has comment: http://stackoverflow.com/comment/90775506
has body: Unindent lines from 19 to 21. Z = Z.reshape(xx1.shape) plt.contourf(xx1, xx2, Z, alpha=0.4, cmap=cmap), plt.xlim(xx1.min(), xx1.max()) plt.ylim(xx2.min(), xx2.max())
score: -1
has comment: http://stackoverflow.com/comment/90775573
upvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90775431

http://stackoverflow.com/comment/90605592
type: Comment
type: QuestionComment
has text: @MartijnPieters so how are you supposed to write a function that can work on multiple columns? that's the entire point of variables!
comment on: http://stackoverflow.com/q/51825348
score: 0

dayofweek
type: Tag
tags question: http://stackoverflow.com/q/51951223
tag name: dayofweek

http://stackoverflow.com/a/51828772
answers question: http://stackoverflow.com/q/51828518
upvote count: 11
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51828518
type: Answer
has body: Using pd.MultiIndex.from_arrays and groupby + cumcount. df.index = pd.MultiIndex.from_arrays( [df.index.get_level_values(0), df.groupby(level=0).cumcount()], names=['ID', 'Date']) df col1 col2 ID Date 1 0 4 6 1 8 5 2 4 7 3 3 3 2 0 7 8 1 5 9 2 8 4 This won't generalise to N levels, but there should be a df.index.set_levels equivalent I'm forgetting...
has comment: http://stackoverflow.com/comment/136388867
score: 11

http://stackoverflow.com/comment/90816271
type: QuestionComment
comment on: http://stackoverflow.com/q/51933046
type: Comment
has text: yes, but within each "trial" each node can be used only once. Imagine these are people being identified from different datasets. If A = B, then I can't match any more because A and B are already matched and C and D aren't connected. In a new trial though if I match A to C, then B can also match to D.
score: 0

http://stackoverflow.com/comment/90727549
type: Comment
type: QuestionComment
has text: Are you talking about argparse? https://docs.python.org/3/library/argparse.html
score: 0
comment on: http://stackoverflow.com/q/51888251

http://stackoverflow.com/q/51821166
has title: interger required to open file python
has answer: http://stackoverflow.com/a/51821308
accepted answer: http://stackoverflow.com/a/51821308
has comment: http://stackoverflow.com/comment/90596484
has comment: http://stackoverflow.com/comment/90596234
answer count: 1
has comment: http://stackoverflow.com/comment/90596159
duplicate of: http://stackoverflow.com/q/1046656
score: 0
linked to: http://stackoverflow.com/q/1046656
tagged with: python
tagged with: module
has comment: http://stackoverflow.com/comment/90596323
tagged with: python-3.x
has body: Okay so I need to do a file test for a program by creating/opening(if the file exists) and append some text to it to confirm that it works. Before I started adding in modules in the test went perfectly fine but once I finished putting in the modules and started working with the GUI with the Tkinter module now I get an error that an integer is required. There is a post about it but in there the person just messed up something with readline() which is not the case for me. I think it has to do with the JSON module or the fact that I added in #!/usr/bin/env python after the file test but I don't know. Here's my code #!/usr/bin/env python #shit to import from json import * from os import * from sys import * from numpy import * from datetime import * from tkinter import * #testing with open("test.txt","a") as file: file.read() file.write("The test has been completed \n") #GUI win = Tk() win.mainloop()
tagged with: file
type: Question
type: AnsweredQuestion

http://stackoverflow.com/comment/90636437
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51841653
has text: `json.loads(statusFile.read())` returns dictionary not int

http://stackoverflow.com/q/51888009
has comment: http://stackoverflow.com/comment/90737343
score: -1
has answer: http://stackoverflow.com/a/51896259
has comment: http://stackoverflow.com/comment/90737223
has title: Python program to get the value and unit of a person's height？
downvote count: 1
answer count: 1
has body: For example: From 170m I want to get number:170.0,unit m From 1.059米 I want to get number:1.059,unit m From 173cm I want to get number:173,unit cm From 1m40 I want to get number：1.40 unit m From 155センチ I want to get number:155 unit cm My code: value='170cm' value = re.findall('^\d*\.*\d*|', value) if len(value) &gt; 0: number = value[0] units = re.findall('m|cm', value) if len(units) &gt; 0: unit = units[0] But I think this it is not good.
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90736974
tagged with: python
upvote count: 0
has comment: http://stackoverflow.com/comment/90737386
has comment: http://stackoverflow.com/comment/90727169
type: Question

http://stackoverflow.com/a/51950391
has comment: http://stackoverflow.com/comment/90873995
accepted answer of: http://stackoverflow.com/q/51948753
has body: https://devcenter.heroku.com/articles/deploying-python The changes you make through heroku run bash are not sustained. Once you quit the bash the dyno is immediately terminated. I suggest you create a requirements.txt like pip freeze &gt; requirements.txt in the root folder or mention dependencies in Pipfile. Dependencies specified in Pipfile or requirements.txt are automatically installed when you deploy your application. Add this in your Pipfile [packages] django-crispy-forms = "*" django = "*" django-multiselectfield = "*"
has comment: http://stackoverflow.com/comment/90874075
type: Answer
has comment: http://stackoverflow.com/comment/90884320
has comment: http://stackoverflow.com/comment/90882911
has comment: http://stackoverflow.com/comment/90852250
has comment: http://stackoverflow.com/comment/90885071
score: 0
answers question: http://stackoverflow.com/q/51948753
has comment: http://stackoverflow.com/comment/90884793
type: AcceptedAnswer

http://stackoverflow.com/comment/90792572
comment on: http://stackoverflow.com/q/51921075
score: 0
has text: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/178311/discussion-between-raunaq-jain-and-tina).
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90784474
type: QuestionComment
has text: Additionally loop over the letters?
score: 0
comment on: http://stackoverflow.com/q/51917267
type: Comment

http://stackoverflow.com/q/51866330
tagged with: http://stackoverflow.com/tag/r
has comment: http://stackoverflow.com/comment/90685036
tagged with: pandas
upvote count: 1
tagged with: regex
favorite count: 0
answer count: 0
type: UnansweredQuestion
tagged with: python
has body: I'm pretty good with R and just starting out trying to teach myself python. I'm trying to replicate the following lines of code: regex &lt;- paste0("precip_pday_", 30:185, collapse = "|") dat$TAP &lt;- rowSums(dat[,grepl(regex, colnames(dat))])/1000 Basically just create a regular expression, and then take the row-wise sum of the variables with that match the regex. I suppose I could have as just as easily not collapsed the string and used %in%. I tried to replicate this in python, and the best I can do is a nested mess of for loops and if statements that takes 15 lines: import re import pandas as pd regex = re.compile("precip") idx = [] for i in range(0, len(list(df))-1, 1): name = list(df)[i] found = regex.findall(name) if len(found) &gt; 0: day = name.split("_")[2] if int(day) in range(30, 185, 1): idx.append(i) cols_I_want = df.iloc[:,idx] df["TAP"] = cols_I_want.sum(axis = 1)/1000 How could this be simplified? Made more efficient? Here's a fake dataset, to complete the MWE: fake_df &lt;- as.data.frame(matrix(rnorm(1000*365), nrow = 1000, ncol = 365)) colnames(fake_df) &lt;- paste0("precip_pday_", 1:365) write.csv("fake_df.csv") df &lt;- read.csv("fake_df.csv") and of course df = pd.read_csv("fake_df.csv") Here's what part of df looks like: ddd.iloc[[1,2,3],[1,2, 365] ] Out[58]: precip_pday_1 precip_pday_2 precip_pday_365 1 -1.189000 -0.825324 0.300221 2 -1.045318 -1.092792 1.098239 3 1.429858 0.919119 -0.643524 It has columns for each day of the year (and lots of others in my real dataset, but I can filter them out with the regex). The desired output is the sum of the values of days 30 through 185
has comment: http://stackoverflow.com/comment/90685166
has comment: http://stackoverflow.com/comment/90685008
score: 1
has comment: http://stackoverflow.com/comment/90685064
type: Question
has comment: http://stackoverflow.com/comment/90685117
has comment: http://stackoverflow.com/comment/90685124
downvote count: 0
has comment: http://stackoverflow.com/comment/90684979
has title: One-liner for creating a variable based on the sum of other variables defined in a regular expression?
has comment: http://stackoverflow.com/comment/90684868
has comment: http://stackoverflow.com/comment/90685198
has comment: http://stackoverflow.com/comment/90685202

http://stackoverflow.com/comment/90836665
has text: Ok you slightly changed the question I see. Does jpp's answer work for you?
type: AnswerComment
comment on: http://stackoverflow.com/a/51933949
type: Comment
score: 0

http://stackoverflow.com/a/51838777
upvote count: 1
has comment: http://stackoverflow.com/comment/90632867
has body: you should use iframe = driver.find_elements_by_tag_name('iframe')[0] driver.switch_to.frame(iframe) # your work to extract link driver.switch_to_default_content() for multiple url find_elements_by_tag_name will return an array. so use for loop iframe = driver.find_elements_by_tag_name('iframe') for i in iframe: driver.switch_to.frame(i) # your work to extract link driver.switch_to_default_content() to get only text use text = driver.find_element_by_tag_name('body').text after driver.switch_to.frame(i)
has comment: http://stackoverflow.com/comment/90635050
has comment: http://stackoverflow.com/comment/90631123
has comment: http://stackoverflow.com/comment/90631524
has comment: http://stackoverflow.com/comment/90631720
downvote count: 0
answers question: http://stackoverflow.com/q/51838630
has comment: http://stackoverflow.com/comment/90634189
has comment: http://stackoverflow.com/comment/90633481
type: Answer
score: 1

http://stackoverflow.com/comment/90703655
type: Comment
has text: That means an object got plotted. Now it needs rendering? `plt.show()` might do the trick..
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51873813

http://stackoverflow.com/q/51832920
tagged with: bash
answer count: 3
has body: i want to create a script in python, but having this error. Can please anyone help me. Traceback (most recent call last): File "./python_test.py", line 7, in &lt;module&gt; if i in range(1, 254): NameError: name 'i' is not defined ================================== #!/usr/bin/env python import os if i in range(1, 254): all=os.system("echo 10.11.1.i") print(all) ====================================== for ip in $(seq 1 254);do echo 10.11.1.$ip;done
possible better answer: http://stackoverflow.com/a/51832963
has title: Bash to python scripting
favorite count: 0
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51832952
upvote count: 0
accepted answer: http://stackoverflow.com/a/51832952
downvote count: 2
type: Question
score: -2
has answer: http://stackoverflow.com/a/51832963
has answer: http://stackoverflow.com/a/51832983

http://stackoverflow.com/a/51827990
has body: First of all, the derivative of a + b*x + c*x**2 is b + 2*c*x, not b + c*x. Second, we need to replace "positive" by "nonnegative", because optimization by its nature requires a closed region of allowable parameters. The expression b + 2*c*x is nonnegative for x&gt;0 if and only if b&gt;=0 and c&gt;=0. Hence, the problem is solved by providing suitable lower bounds on b and c to curve_fit, as shown below: import numpy as np from scipy.optimize import curve_fit x_data = [1, 2, 3, 4, 5] y_data = [2, 1, 2, 5, 9] def poly(x, a, b, c): return a + b*x + c*x**2 result = curve_fit(poly, x_data, y_data, bounds=((-np.inf, 0, 0), (np.inf, np.inf, np.inf))) print(result[0]) The result [2.70588235e-01 1.92685605e-15 3.20855615e-01] shows that b is effectively zero (it's being pushed against the constraint), so the fit is better expressed as y = 0.271 + 0.321 * x**2.
answers question: http://stackoverflow.com/q/51823688
score: 0
type: Answer

geography
type: Tag
tag name: geography
tags question: http://stackoverflow.com/q/51891538

http://stackoverflow.com/q/51921821
linked to: http://stackoverflow.com/q/31950331
answer count: 0
type: UnansweredQuestion
has title: Create new column inside loop
has comment: http://stackoverflow.com/comment/90793365
type: Question
has comment: http://stackoverflow.com/comment/90793425
score: 0
has comment: http://stackoverflow.com/comment/90793326
has comment: http://stackoverflow.com/comment/90793405
has body: I am trying to get the percentage change for value in dftemp['eps_mean_est'] from the first value in that column. I want to do that for each dftemp['per_end_date'] within each stock. Here's the code I have tried. This is a pandas dataframe. The error is KeyError: 'ticker' . What am I doing wrong? dftemp.set_index(['ticker','per_end_date'], inplace=True) for stock in dftemp['ticker'][0:]: for qtrDate in dftemp['per_end_date'][0:]: dftemp['pctchg'] = (dftemp['eps_mean_est'] - dftemp['eps_mean_est'][0]) /dftemp['eps_mean_est'][0]
tagged with: pandas
tagged with: python
has comment: http://stackoverflow.com/comment/90793424

http://stackoverflow.com/q/51822251
has title: Python KeyError JSON
upvote count: 1
has body: I am trying to get some specific data from a JSON file, but I get the following error: for item in data['perfil'][0]['regimes']: KeyError: 'regimes' This is my script, as you can see, I am trying to get Key regimes, because it has specific data, that others don't have: import json import matplotlib.pyplot as plt with open('backupperfil.json') as f: data = json.load(f) for item in data['perfil'][0]['regimes']: print(item['classificacao']) And this is a small copy of Json File: { "perfil":[ { "data": 1533815887, "kmh": 0, "rpm": 0.0, "pedal": 15.294117647058824 }, { "data": 1533815888, "kmh": 0 ,"rpm": 0.0 ,"pedal": 15.294117647058824 }, { "data": 1533815889, "kmh": 0 ,"rpm": 0.0 ,"pedal": 15.294117647058824 }, { "kmh": 0 ,"rpm": 834.75 ,"pedal": 14.117647058823529 }, { "regimes": [ { "kmh": 0, "rpm": 833.75, "pedal": 14.117647058823529, "regime_inferior_normal": 318, "regime_normal": 27, "regime_agressivo": 1, "regime_muito_agressivo": 0, "soma_regimes": 346, "classificacao": "Regime Inferior a Normal" } ] }, { "kmh": 0, "rpm": 827.5, "pedal": 14.117647058823529 } ] } How can I get the data inside of Key "regimes"?
favorite count: 0
has answer: http://stackoverflow.com/a/51822474
accepted answer: http://stackoverflow.com/a/51822474
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/51822459
has comment: http://stackoverflow.com/comment/90598476
type: Question
possible better answer: http://stackoverflow.com/a/51822459
tagged with: http://stackoverflow.com/tag/json
answer count: 2

http://stackoverflow.com/a/51916476
answers question: http://stackoverflow.com/q/51913511
has body: Your code has several problems. You are using &lt;var&gt;.get() to get the text in the entry but if you try printing its output then you will get the entry name, not the text. Use &lt;entry&gt;.get() to get the text. You are using open("&lt;file&gt;","w") whereas the mode w is used to rewrite the file. I will suggest you to use mode a which appends data automatically at the end of file. You are not closing your file after writing data. add is the name of function but you are making a button naming add. Similar with login. Give these buttons a different name. Your updated code is: from tkinter import * from tkinter import messagebox loginwin = Tk() loginwin.wm_title("Login") loginwin.geometry("225x75") win = Tk() win.wm_title("Password Manger") win.geometry("550x215") win.withdraw() u = StringVar() p = StringVar() a = StringVar() u1 = StringVar() p1 = StringVar() def login(): username1 = u.get() password1 = p.get() print(username1,password1) if username1 == "": if password1 == "": messagebox.showinfo("Login", "Login Complete") loginwin.withdraw() win.deiconify() else: messagebox.showinfo("Login", "Incorrect Password or Username") else: messagebox.showinfo("Login", "Incorrect Password or Username") def add(): account11 = str(account.get()) username22 = str(username1.get()) password22 = str(password1.get()) file = open("passwords.txt", "a") file.write("\n" + account11 + " " + username22 + " " + password22) file.close() Label(loginwin, text=" Username: ").grid(row=1, column=1) Label(loginwin, text=" Password: ").grid(row=2, column=1) Label(loginwin, text="Hint: Nothing").grid(row=3, column=2) Label(win, text=" Account: ").grid(row=1, column=1) Label(win, text=" Username: ").grid(row=2, column=1) Label(win, text=" Password: ").grid(row=3, column=1) username = Entry(loginwin, textvariable = u) username.grid(row=1, column=2) password = Entry(loginwin, textvariable = p, show = "*") password.grid(row=2, column=2) account = Entry(win, textvariable = a) account.grid(row=1, col…
score: 0
type: Answer

http://stackoverflow.com/q/51951692
has comment: http://stackoverflow.com/comment/90861394
upvote count: 1
tagged with: sqlalchemy
has comment: http://stackoverflow.com/comment/90864238
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90891212
has body: I have a sqlalchemy query that uses some window functions to implement lag() over a column. The backend is using Teradata if that matters. I am receiving a database error from that suggests to me that the parameter values are not being correctly substituted. If I run the bare query in the database, I get the exact same error. The tables are defined as extensions to the base class and reflected from the database in the usual way. The sqlalchemy code: name = 'some_column' query = self.session\ .query(func.min(getattr(table,name))\ .over(partition_by=over_attrs, order_by=getattr(table,name), rows=(1,1))) produces the following sql: SELECT min(my_table_1.my_date) OVER (PARTITION BY my_table_1.ban, my_table_1.location ORDER BY my_table_1.my_date ROWS BETWEEN ? FOLLOWING AND ? FOLLOWING) AS anon_1 FROM schema.my_table AS my_table_1 The error message I get is: (teradata.api.DatabaseError) (3707, "[42000] [Teradata] [ODBC Teradata Driver][Teradata Database] Syntax error, expected something like a name or a Unicode delimited identifier or an integer between the 'BETWEEN' keyword and '?'. ") [SQL: 'SELECT TOP 25 min(my_table_1.my_date) OVER (PARTITION BY my_table_1.ban, my_table_1.location ORDER BY my_table_1.my_date ROWS BETWEEN ? FOLLOWING AND ? FOLLOWING) AS anon_1 \n FROM schema.my_table AS my_table_1'] [parameters: (1, 1)] (Background on this error at: http://sqlalche.me/e/4xp6) If I run the query in database with the ? replaced with (1,1), the query runs fine. If I leave in the ? then it fails with the exact same error as the sqlalchemy version. Am I doing something wrong that would cause it to fail in this way or could this be a bug in sqlalchemy? Versions: SQLAlchemy 1.2.8 sqlalchemy-teradata 0.1.0.dev0 pyodbc 4.0.23 I'm using the Teradata Database ODBC driver v 16.10.
downvote count: 0
tagged with: teradata
score: 1
has comment: http://stackoverflow.com/comment/90860872
favorite count: 0
has title: SQLAlchemy Not Substituting Values into Query
type: Question
tagged with: python
answer count: 0

http://stackoverflow.com/q/51878594
type: UnansweredQuestion
score: 0
has body: I am looking to loop through 2 database servers to get a match for the query submitted through form(example.html) ie iterating the configuration value (app.config['MYSQL_HOST'] = db['mysql_host']). If no data is retrieved from first database server it needs to query with the second one. When I try to make a list to iterate through the mysql hosts, it shows me TypeError: list indices must be integers or slices, not str. Below is the work code when I set one database server in app.config['MYSQL_HOST'] = db['mysql_host']. db.yaml file contains the database server and configuration information. from flask import Flask, render_template, request from flask_mysqldb import MySQL import yaml import sys app = Flask(__name__) db = yaml.load(open('db.yaml')) app.config['MYSQL_USER'] = db['mysql_user'] app.config['MYSQL_PASSWORD'] = db['mysql_password'] app.config['MYSQL_DB'] = db['mysql_db'] mysql = MySQL(app) @app.route('/') def dashboard(): return render_template('dashboard.html') @app.route('/sdetails') def sdetails(): return render_template('s.html') @app.route('/s', methods = ['POST', 'GET']) def s(): dbhosts = yaml.load(open('yamlsample.yaml')) dbhosts = list(dbhosts) if request.method == 'POST': result = request.form sname = request.form["Name"] for i in dbhosts: app.config['MYSQL_HOST'] = i cur = mysql.connection.cursor() slist=cur.execute(slist=cur.execute("select * from table1 WHERE table1.name LIKE '{}'".format(sname)) sdetails=cur.fetchall() if sdetails != None: return render_template('results.html', sdetails=sdetails) else: continue # I thought continue will take me to the next dbhost. But not happening. if __name__ == '__main__': app.run(debug = True) I am making use of db.yaml only for database username,password and database server. db.yaml mysql_user: 'xxxx' mysql_password: 'xxxxx' mysql_db: 'xxxxx' I am making use of yamlsample.yaml for iterating over DB hosts only. yamlsample.yaml 192.168.1.10 192.168.1.11
upvote count: 1
downvote count: 1
type: Question
tagged with: mysql
tagged with: flask
favorite count: 0
has comment: http://stackoverflow.com/comment/90709557
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/90750033
has title: How to iterate through multiple database servers in Flask Mysqldb

http://stackoverflow.com/q/51879367
has comment: http://stackoverflow.com/comment/90710385
has comment: http://stackoverflow.com/comment/90730975
answer count: 1
has title: Combining identical values against a list of dictionaries in Python
has answer: http://stackoverflow.com/a/51880001
tagged with: python
has comment: http://stackoverflow.com/comment/90710661
score: 0
type: UnansweredQuestion
has body: I am building a table using python. The rows to the table are contained in a list of a dictionaries, like so: table = [{ 'User' : 'johndoe', 'Profile' : 'Production', 'Risk' : 'No MFA', 'Action': 'Disable account and notify user' }, { 'User' : 'janedoe', 'Profile' : 'Production', 'Risk' : 'Expired Password', 'Action': 'Reset password and notify user' }, { 'User' : 'cookiedoe', 'Profile' : 'Non-Production', 'Risk' : 'Expired key', 'Action': 'Delete old key and notify user' },] I run a function to build the row each time I detect a non-compliant condition. My goal is to combine rows where 'User' and 'Profile' are identical. For instance, if johndoe in Production also had an expired password, I want his dictionary to look thusly: { 'User' : 'johndoe', 'Profile' : 'Production', 'Risk' : 'No MFA, Expired password', Action: 'Disable account and notify user\n Reset password and notify user' } Each current row lives in a local dictionary called 'row'. This is how I'm trying to accomplish this now: for past_row in table: past_user = past_row['User'] row_user = row['User'] past_profile = past_row['Profile'] row_profile = row['Profile'] if past_user == row_user and past_profile == row_profile: past_row['Risk'] = "%s, %s" %(past_row['Risk'], row['Risk']) past_row['Action'] = "%s\n %s" %(past_row['Action'], row['Action']) My Python script just runs endlessly, without ever finishing. I feel like I'm examining my past rows inefficiently, and I'm fairly young in my Pythonic education. Googling in circles is just making my logic more convoluted. Can someone set me straight?
type: Question
has comment: http://stackoverflow.com/comment/90710495

http://stackoverflow.com/a/51959134
type: AcceptedAnswer
type: Answer
upvote count: 4
has body: This answer only works for Python 3.6+. If you have the option to upgrade to the most recent Python version, there are numerous reasons why you should and the following may be one of them. Python 3.6 introduced the __init_subclass__ hook that is exectued after a class is subclassed. class MusicFile: _register = {} def __init_subclass__(cls, **kwargs): if not hasattr(cls, 'extension'): raise ValueError(cls.__name__ + ' has no extension') MusicFile._register.update({e: cls for e in cls.extension}) @classmethod def get_class_by_extension(cls, ext): return cls._register.get(ext) Example class MP3(MusicFile): extension = ['mp3'] class MIDI(MusicFile): extension = ['midi'] MusicFile.get_class_by_extension('mp3') # &lt;class '__main__.MP3'&gt; MusicFile.get_class_by_extension('midi') # &lt;class '__main__.MIDI'&gt; Note that this is very similar to the factory approach suggested by bipll, but in a more straightforward and maintainable way.
downvote count: 0
answers question: http://stackoverflow.com/q/51923555
accepted answer of: http://stackoverflow.com/q/51923555
score: 4

http://stackoverflow.com/comment/90811906
type: Comment
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/51921431
has text: Maybe worth noting; should probably do it via SQL if possible since this can create unwanted behaviour if using pagination when fetching all posts. And thus only sorting a part of all the posts

http://stackoverflow.com/comment/90634681
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51807319
has text: few edits again...use `filename.name` instead of `filename` (updated the answer)
type: AnswerComment

http://stackoverflow.com/comment/90842551
type: QuestionComment
has text: @alex As of now, I have a command line program.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51945846

http://stackoverflow.com/a/51916864
type: Answer
answers question: http://stackoverflow.com/q/51880685
has body: w3lib.url.canonicalize_url works incorrectly in this webpage , and the above workaround that resp = response.replace(encoding='utf8', body=response.text.encode('utf8')) only work in scrapy shell so we can specify the canonicalize=True in spider like this: LinkExtractor(canonicalize=True) but in scrapy documents said,under normal circumstances, you’re using LinkExtractor to follow links it is more robust to keep the default canonicalize=False
score: 0

http://stackoverflow.com/a/51863322
upvote count: 1
type: AcceptedAnswer
type: Answer
downvote count: 0
score: 1
has body: Solution I don't have to delete python symbolic link in ~/miniconda/bin/, and instead, in the ~/.bashrc file, I need to change my conda path to export PATH=$PATH:/home/me/miniconda/bin After doing this, when I call python, it's actually executing the python program in /usr/bin/. conda command will execute ~/miniconda/bin/conda program.
answers question: http://stackoverflow.com/q/51862963
accepted answer of: http://stackoverflow.com/q/51862963

http://stackoverflow.com/comment/116233155
has text: Are/Were you on a Mac by any chance? Check out this answer on how to install certificates: https://stackoverflow.com/a/53310545/778533
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51925384
score: 0

http://stackoverflow.com/a/51862351
has comment: http://stackoverflow.com/comment/90677236
score: 4
downvote count: 0
has body: As you didn't configure the field with blank= True https://docs.djangoproject.com/es/2.1/ref/models/fields/#blank it is a required field, therefore it is rendered in the template as that, so the browser ask it to be filled. You have to add the attribute: telefono = models.CharField( max_length=15, validators=[phone_regex], verbose_name='Teléfono', blank=True ) Also you could, instead of create a field for regex, create a library with a function, so you could reuse it on other models. EDIT: Validators are not meant to be in the model definition, as it is a representation of a table, and a regex field is not a field of a table. You could create a folder with an __init__.py so it can be called from your apps root_folder/ myapp/ myvalidators/ __init__.py myvalidators.py In the myvalidators.py you create functions or constant with the validations you need: myvalidators.py REGEX_PATTERN_PHONE = your_regex MSG_PHONE_NOT_VALID = your_message In your models then add the validation pattern with RegexValidator from myvalidators import myvalidators ... telefono = models.CharField( max_length=15, validators=[phone_regex], verbose_name='Teléfono', blank=True, validators = [RegexValidator(myvalidators.REGEX_PATTERN_PHONE, myvalidators.MSG_PHONE_NOT_VALID)], ) ... With this approach you can reuse the regex on any app or project, and in different fields that have to be validated the same way.
type: Answer
has comment: http://stackoverflow.com/comment/90711356
upvote count: 4
answers question: http://stackoverflow.com/q/51862171
has comment: http://stackoverflow.com/comment/90681141
has comment: http://stackoverflow.com/comment/90681928
has comment: http://stackoverflow.com/comment/90751756

http://stackoverflow.com/q/51821131
has title: How to get a completely clean python environment with miniconda?
favorite count: 0
has body: I have tried: conda create --name Leaf python==3.6.5 And if I do conda list I can find: # packages in environment at /home/roychang/miniconda3/envs/Leaf: # # Name Version Build Channel ca-certificates 2018.03.07 0 certifi 2018.4.16 py36_0 libedit 3.1.20170329 h6b74fdf_2 libffi 3.2.1 hd88cf55_4 libgcc-ng 7.2.0 hdf63c60_3 libstdcxx-ng 7.2.0 hdf63c60_3 ncurses 6.1 hf484d3e_0 openssl 1.0.2o h14c3975_1 pip 10.0.1 py36_0 python 3.6.5 hc3d631a_2 readline 7.0 ha6073c6_4 setuptools 40.0.0 py36_0 sqlite 3.24.0 h84994c4_0 tk 8.6.7 hc745277_3 wheel 0.31.1 py36_0 xz 5.2.4 h14c3975_4 zlib 1.2.11 ha838bed_2 But if I try to run some script which use some package didn't in this list (like kivy). I think it shouldn't work, but it did! So does MiniConda auto fetch the package from the origin python root? How could I get a completely clean python environment with MiniConda? UPDATE: Seems that I didn't explain well, I had activated that environment and what I got after doing conda list was the result showing above. I could run this script when I activated the environment, although I didn't install kivy under this environment. I only installed kivy to the origin python before I installed MiniConda. from kivy.app import App from kivy.core.window import Window from kivy.uix.widget import Widget from kivy.uix.floatlayout import FloatLayout from kivy.uix.button import Button from kivy.uix.spinner import Spinner from kivy.uix.label import Label from kivy.uix.image import Image from kivy.uix.textinput import TextInput from kivy.graphics import Color, Ellipse, Line, Rectangle from kivy.lang import Builder And what else I found is if I try which python, it showed: (Leaf) roychang@ThinkPad-T480:~$ which python /home/roychang/miniconda3/bin/python After I deactivated the environment and did which python again I got the same result. Is this expected? I think it should use different python in different environment. conda list in default environment (I found Kivy isn't here): # Name Version Build Cha…
tagged with: python
score: 2
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90602371
type: Question
tagged with: miniconda
has comment: http://stackoverflow.com/comment/90657536
tagged with: conda
has answer: http://stackoverflow.com/a/51848141
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/90698978
has text: The issue of this solution: User will have to parse on his own each line. Better to use csv reader and specify dialect.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51873642
type: Comment

http://stackoverflow.com/q/51878330
has title: python search word in specific paragraph
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90708142
answer count: 0
has body: I have a files like DDDDMMYY.zip in multiple folders like below /test/abc/DDDDMMYY.zip /test/def/DDDDMMYY.zip These files will be configured in the application to process the data. Just wanted to check regularly whether all the sub directories files are configured to process.Application config looks like &lt;config name=abc&gt; Process &lt;DDDDMMYY.zip&gt; &lt;config name&gt; &lt;config name=def&gt; Process &lt;DDDDMMYY.zip&gt; &lt;config name&gt; Tried using regex but it gives results only for the available configs. Above mentioned is a example like this we have hundred's of config i wan to verify them all using script. Please don't mind if question is too long, asking this as I am new to python.
has comment: http://stackoverflow.com/comment/90731045
has comment: http://stackoverflow.com/comment/90708043
has comment: http://stackoverflow.com/comment/90707980
type: Question
has comment: http://stackoverflow.com/comment/90708181
has comment: http://stackoverflow.com/comment/90708016
has comment: http://stackoverflow.com/comment/90711929
has comment: http://stackoverflow.com/comment/90708633
score: 0

http://stackoverflow.com/comment/90674807
type: AnswerComment
has text: @Py.rookie89 you have `np.nan` values in the title column is my guess you can filter these out or make them blank strings
type: Comment
comment on: http://stackoverflow.com/a/51860492
score: 0

http://stackoverflow.com/comment/90577591
type: QuestionComment
comment on: http://stackoverflow.com/q/51811269
score: 0
has text: Could you tell the file path? and app structuring of the validator and the model?
type: Comment

oitnb
tag name: oitnb
tags question: http://stackoverflow.com/q/51854839
type: Tag

http://stackoverflow.com/comment/90708732
type: Comment
has text: Yeah, I'll usually do `import anceOfBeingErnst as me` every moring. :-P
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51877995

http://stackoverflow.com/comment/90794195
has text: @OlivierMelançon. I was thinking of doing a binary search on the start and end indices, but for a large enough input sets would be faster.
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/51918697
type: Comment

http://stackoverflow.com/q/51953636
has title: Python Flask app.run process does not quit
type: Question
tagged with: flask
score: 0
has comment: http://stackoverflow.com/comment/90857669
has comment: http://stackoverflow.com/comment/90858441
has comment: http://stackoverflow.com/comment/90858387
has comment: http://stackoverflow.com/comment/90857630
answer count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90865713
has comment: http://stackoverflow.com/comment/90857700
has body: I have a Python and Flask script as follows: app = Flask(__name__) @app.route("/myroute") def foo(): # do something # copy json results into file **output.json** # return output.json app.run(host='0.0.0.0',port=8080) after running the app (flask run) I hit my url and get the results in output.json as my http response. However, after I try to stop the flask run with a ctrl-c or ctrl-z, my URL still returns the output.json file content. I have cleared my browser cache. I then deleted the output.json file on the server and ran the url. Surprisingly, I still get the output.json result but there is no output.json file created on the server. This means my Flask job did not run and some other task is returning output.json results cached on the server. Can someone help me figure out what is going on and how to identify what task is responding with json results? Edited: I am using Linux Centos. I do not have any web servers and no other components are running. This is how I run my flask job: export FLASK_APP=myscript.py flask run

http://stackoverflow.com/comment/90832412
comment on: http://stackoverflow.com/q/51931394
type: QuestionComment
type: Comment
has text: I have posted the response I get. The console-consumer-* group id is created by `bin/kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic test --from-beginning`. which works normally. @AbhiskekN
score: 0

http://stackoverflow.com/comment/109729686
type: AnswerComment
score: 0
type: Comment
has text: use `model.get_booster().get_score(importance_type='weight')` to get importance of all features.
comment on: http://stackoverflow.com/a/51905976

http://stackoverflow.com/q/51880196
has answer: http://stackoverflow.com/a/51880305
has comment: http://stackoverflow.com/comment/90711889
type: Question
answer count: 2
linked to: http://stackoverflow.com/q/1132941
has body: Question regarding list in python: I have one program in that list are generating and assigning to a different variable but still getting the same output for two variable...Not able to understand the functionality. Code: def extendList (val, list=[]): list.append(val) return list list1 = extendList (10) list2 = extendList (123, []) list3 = extendList ('a') print list1, list2, list3
possible better answer: http://stackoverflow.com/a/51880305
has title: List variable concept in python
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/51880293
duplicate of: http://stackoverflow.com/q/1132941
favorite count: 0
has comment: http://stackoverflow.com/comment/90712262
tagged with: python
has comment: http://stackoverflow.com/comment/90712218
has comment: http://stackoverflow.com/comment/90711962
accepted answer: http://stackoverflow.com/a/51880293
upvote count: 1
has comment: http://stackoverflow.com/comment/90711940
has comment: http://stackoverflow.com/comment/90711941
type: AnsweredQuestion

http://stackoverflow.com/a/51888564
type: Answer
has comment: http://stackoverflow.com/comment/90728433
accepted answer of: http://stackoverflow.com/q/51888408
answers question: http://stackoverflow.com/q/51888408
has comment: http://stackoverflow.com/comment/90728450
score: 3
has body: If you have N bits in the fractional part then you just need to divide by 2N, since the stored bit pattern is actually the real value multiplied by 2N. Therefore with Q8.8 like in your case you'll have to divide by 256 For your 00000001.01000000 and 00000001.11000000 examples above: &gt;&gt;&gt; 0b0000000101000000/256.0 1.25 &gt;&gt;&gt; 0b0000000111000000/256.0 1.75
type: AcceptedAnswer
downvote count: 0
upvote count: 3

http://stackoverflow.com/comment/90775947
has text: Index 1 means 2nd column, if you want 1st column, then use 0
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51912909

http://stackoverflow.com/a/51830803
answers question: http://stackoverflow.com/q/51807060
accepted answer of: http://stackoverflow.com/q/51807060
score: 0
type: AcceptedAnswer
has body: Currently you can view the test output by clicking on the test results in the status bar or you can look at the code lenses on your tests. Otherwise adding such a view is an open feature request which you can leave a reaction on to vote up its priority.
type: Answer

http://stackoverflow.com/comment/90710170
score: 5
comment on: http://stackoverflow.com/q/51879374
type: Comment
type: QuestionComment
has text: Your question is unclear.

http://stackoverflow.com/q/51875333
type: Question
answer count: 2
has body: I have the following set up for which on session.query() SqlAlchemy returns stale data: Web application running on Flask with Gunicorn + supervisor. one of the services is composed in this way: app.py: @app.route('/api/generatepoinvoice', methods=["POST"]) @auth.login_required def generate_po_invoice(): try: po_id = request.json['po_id'] email = request.json['email'] return jsonify(response=POInvoiceGenerator.get_invoice(po_id, email)) except Exception as ex: app.logger.error("generate_po_invoice(): " + ex.message) in another folder i have the database related stuff: DatabaseModels (folder) |-->Model.py |-->Connection.py that's what is contained in the connection.py file: from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker, scoped_session from sqlalchemy.ext.declarative import declarative_base engine = create_engine(DB_BASE_URI, isolation_level="READ COMMITTED") Session = scoped_session(sessionmaker(bind=engine)) session = Session() Base = declarative_base() and thats an extract of the model.py file: from DatabaseModels.Connection import Base from sqlalchemy import Column, String, etc... class Po(Base): __tablename__ = 'PLC_PO' id = Column("POId", Integer, primary_key=True) code = Column("POCode", String(50)) etc... Then i have another file POInvoiceGenerator.py that contains the call to the database for fetching some data: import DatabaseModels.Connection as connection import DatabaseModels.model as model def get_invoice(po_code, email): try: po_code = po_code.strip() PLCConnection.session.expire_all() po = connection.session.query(model.Po).filter(model.Po.code == po_code).first() except Exception as ex: logger.error("get_invoice(): " + ex.message) in subsequent users calls to this service sometimes i start to get errors like: could not find data in the db for that specific code and so on. Like if the data are stale and so on. My first approach was to add isolation_level="READ COMMITTED" to the engine declaration and then to create a scope…
has comment: http://stackoverflow.com/comment/90802670
tagged with: flask
score: 0
has comment: http://stackoverflow.com/comment/90882509
has comment: http://stackoverflow.com/comment/90837821
tagged with: supervisord
has answer: http://stackoverflow.com/a/57443083
has comment: http://stackoverflow.com/comment/90803609
tagged with: gunicorn
tagged with: python
has answer: http://stackoverflow.com/a/51984088
accepted answer: http://stackoverflow.com/a/51984088
type: AnsweredQuestion
has title: Issue with Stale data Flask/SqlAlchemy
possible better answer: http://stackoverflow.com/a/57443083
has comment: http://stackoverflow.com/comment/90749068
tagged with: sqlalchemy

http://stackoverflow.com/comment/90576942
score: 0
has text: Can you edit your question and put it in there? It is really hard to read in a comment.
type: Comment
comment on: http://stackoverflow.com/q/51810944
type: QuestionComment

http://stackoverflow.com/comment/90819210
comment on: http://stackoverflow.com/a/51924347
type: AnswerComment
has text: That doesn't seem to be working. That was what I did the first time, and it did not work. I was inside a virtualenv, I ran "pip3 install gunicorn" and afterwards the gunicorn was not in the path.
score: 0
type: Comment

http://stackoverflow.com/comment/90813357
type: Comment
has text: It comes from standard python package for VS.I also thought about the debugger but it is slow even if I run scripts directly with python.exe, no VS shell or any other stuff
type: QuestionComment
comment on: http://stackoverflow.com/q/51931579
score: 0

http://stackoverflow.com/comment/90848703
type: Comment
has text: @papampi That's cool, but when you use other people's code verbatim you should give them attribution (mention their name). The bottom of every Stack Overflow page says "user contributions licensed under [cc by-sa 3.0](https://creativecommons.org/licenses/by-sa/3.0/) with attribution required". At a minimum, that means you're supposed to mention the code author's name, and Stack Overflow. Please see [Attribution Required](https://stackoverflow.blog/2009/06/25/attribution-required/) and [legal](https://stackoverflow.com/legal/terms-of-service#licensing) for further details.
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/51916202

http://stackoverflow.com/a/51865767
downvote count: 0
answers question: http://stackoverflow.com/q/51865705
score: 3
upvote count: 3
type: Answer
has body: You can use a merge for this: df2 = (df.merge(table.stack().reset_index(), left_on=['A','B'], right_on=['level_1', 'level_0']) .drop(['level_0', 'level_1'], 1) .rename(columns={0:'C'})) &gt;&gt;&gt; df2 A B C 0 High Blue 1 1 High Green 4 2 Low Red 9 3 Low Red 9 4 Middle Blue 2 5 Low Blue 3

http://stackoverflow.com/comment/90849599
has text: not in the model in the template
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51949293
score: 0

http://stackoverflow.com/q/51918063
downvote count: 0
score: 1
type: Question
has answer: http://stackoverflow.com/a/51918149
has body: I have a categorical variable (A,B,C) in my data frame. Then, I encoded it (made it numerical) in order to pass into a neural network. However, my final visualization graph shows me the encoded values for the categorical variables and I am having difficulties mapping it back to its original values. I used this command to encode my categorical variables (data type=object) into numerical values first: encoders = {} for x in df.columns: if df[x].dtypes=='object': le = preprocessing.LabelEncoder() df[x]=le.fit_transform(df[x].astype(str)) encoders[x] = le corr = df.corr() Then, I am decoding those using this code (right before the final visualization): for x, le in encoders.items(): df[x] = le.inverse_transform(df[x]) # Visualization: plotting categorical variables (A,B,C) in scatterplot using Seaborn. sns.lmplot(x="A", y="B", data=df, fit_reg=False, hue='C',legend=False) display() ...but the visualization STILL shows the encoded values instead of the categorical ones (see screenshot below). No mapping was done. Why?
upvote count: 1
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/90809908
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has title: Can’t inverse encoded categorical variables

http://stackoverflow.com/comment/90832947
type: Comment
has text: This also undoes the ordering by counts if not all items occur with the same frequency.
comment on: http://stackoverflow.com/a/51933949
type: AnswerComment
score: 0

http://stackoverflow.com/comment/90657129
type: AnswerComment
has text: You still generate the whole list which is inefficient
type: Comment
comment on: http://stackoverflow.com/a/51852202
score: 2

http://stackoverflow.com/comment/90708193
comment on: http://stackoverflow.com/a/51878310
score: 0
type: Comment
has text: Yes, It's working as you suggested. Thanks Ilia for help :)
type: AnswerComment

supervised-learning
type: Tag
tag name: supervised-learning
tags question: http://stackoverflow.com/q/51802063
tags question: http://stackoverflow.com/q/51831589
tags question: http://stackoverflow.com/q/51860895

http://stackoverflow.com/q/51815072
has comment: http://stackoverflow.com/comment/90587645
has body: I use Django cache.I know Redis is thead-safe. If BlockingConnectionPool is necessary, when I configure CACHE. What does BlockingConnectionPool do? When I need use BlockingConnectionPool?
possible better answer: http://stackoverflow.com/a/62485950
has title: Redis is thread safe , so why use `BlockingConnectionPool` in redis-py
answer count: 2
accepted answer: http://stackoverflow.com/a/51820995
has comment: http://stackoverflow.com/comment/90584763
has comment: http://stackoverflow.com/comment/90587938
favorite count: 0
tagged with: redis
has answer: http://stackoverflow.com/a/51820995
tagged with: python
upvote count: 4
has comment: http://stackoverflow.com/comment/90587668
has answer: http://stackoverflow.com/a/62485950
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/90586677
tagged with: django
has comment: http://stackoverflow.com/comment/90588318
type: Question
has comment: http://stackoverflow.com/comment/90586868
has comment: http://stackoverflow.com/comment/90587889
score: 4

http://stackoverflow.com/a/51870027
upvote count: 1
answers question: http://stackoverflow.com/q/51869854
type: Answer
has body: from math import pi ydata = [11,16,12,14,13,12,13,10] data_len = len(ydata) max_y = max(ydata) DESIRED_MAP_RADIUS = 100.0 new_data = {'x': [n * 2 * pi / data_len for n in range(data_len)] , 'y': [y/max_y*DESIRED_MAP_RADIUS for y in ydata] } print(new_data)
downvote count: 0
score: 1

dictionary
tags question: http://stackoverflow.com/q/51859917
tags question: http://stackoverflow.com/q/51832063
tags question: http://stackoverflow.com/q/51939437
tags question: http://stackoverflow.com/q/51876466
tags question: http://stackoverflow.com/q/51922869
tags question: http://stackoverflow.com/q/51860471
tags question: http://stackoverflow.com/q/51896284
tags question: http://stackoverflow.com/q/51800639
tags question: http://stackoverflow.com/q/51886761
tags question: http://stackoverflow.com/q/51805413
tags question: http://stackoverflow.com/q/51860378
tags question: http://stackoverflow.com/q/51842469
tags question: http://stackoverflow.com/q/51950730
tags question: http://stackoverflow.com/q/51955245
tags question: http://stackoverflow.com/q/51851937
tags question: http://stackoverflow.com/q/51910868
tags question: http://stackoverflow.com/q/51954976
tags question: http://stackoverflow.com/q/51809512
tags question: http://stackoverflow.com/q/51859531
tags question: http://stackoverflow.com/q/51920736
tags question: http://stackoverflow.com/q/51934897
tags question: http://stackoverflow.com/q/51802193
tags question: http://stackoverflow.com/q/51866680
tags question: http://stackoverflow.com/q/51911657
tags question: http://stackoverflow.com/q/51867176
tags question: http://stackoverflow.com/q/51931008
tags question: http://stackoverflow.com/q/51924803
tags question: http://stackoverflow.com/q/51935309
tags question: http://stackoverflow.com/q/51923190
tags question: http://stackoverflow.com/q/51872648
tags question: http://stackoverflow.com/q/51827820
tags question: http://stackoverflow.com/q/51800651
tags question: http://stackoverflow.com/q/51915286
tags question: http://stackoverflow.com/q/51818670
tags question: http://stackoverflow.com/q/51805075
tags question: http://stackoverflow.com/q/51816688
tags question: http://stackoverflow.com/q/51911383
tags question: http://stackoverflow.com/q/51822269
tags question: http://stackoverflow.com/q/51933112
tags question: http://stackoverflow.com/q/51923876
tags question: http://stackoverflow.com/q/51878605
tags question: http://stackoverflow.com/q/51865705
tags question: http://stackoverflow.com/q/51946545
tags question: http://stackoverflow.com/q/51843857
tags question: http://stackoverflow.com/q/51911734
tags question: http://stackoverflow.com/q/51923611
tags question: http://stackoverflow.com/q/51944387
tag name: dictionary
tags question: http://stackoverflow.com/q/51879872
tags question: http://stackoverflow.com/q/51922923
tags question: http://stackoverflow.com/q/51801164
tags question: http://stackoverflow.com/q/51871527
tags question: http://stackoverflow.com/q/51900624
tags question: http://stackoverflow.com/q/51812245
tags question: http://stackoverflow.com/q/51948664
tags question: http://stackoverflow.com/q/51856120
tags question: http://stackoverflow.com/q/51851867
tags question: http://stackoverflow.com/q/51876794
tags question: http://stackoverflow.com/q/51819999
tags question: http://stackoverflow.com/q/51921926
tags question: http://stackoverflow.com/q/51922259
tags question: http://stackoverflow.com/q/51886499
tags question: http://stackoverflow.com/q/51899115
tags question: http://stackoverflow.com/q/51855360
tags question: http://stackoverflow.com/q/51935940
tags question: http://stackoverflow.com/q/51814497
tags question: http://stackoverflow.com/q/51808970
tags question: http://stackoverflow.com/q/51917483
tags question: http://stackoverflow.com/q/51835930
tags question: http://stackoverflow.com/q/51888423
tags question: http://stackoverflow.com/q/51815313
tags question: http://stackoverflow.com/q/51824728
tags question: http://stackoverflow.com/q/51892798
tags question: http://stackoverflow.com/q/51901920
tags question: http://stackoverflow.com/q/51943561
tags question: http://stackoverflow.com/q/51897222
tags question: http://stackoverflow.com/q/51904941
tags question: http://stackoverflow.com/q/51870964
tags question: http://stackoverflow.com/q/51881503
tags question: http://stackoverflow.com/q/51846670

http://stackoverflow.com/q/51944909
has title: So I've made a Neural Network model for classifying dogs and cats with tensorflow keras, but it's accuracy isn't improving. Any suggestions?
tagged with: tensorflow
type: Question
has body: So I'm fairly new to this stuff and I have written some code, written below, where the model I made doesn't seem to be classifying the cats and dogs. Basically the data is a large collection of cat and dog pictures, starting with 12500 cats, and then 12500 dogs in that order. I just can't seem to work out why this isn't working. I have tried adjusting weights and batch size, but nothing works. Any suggestions? import tensorflow as tf from tensorflow import keras import numpy as np import cv2 import os import random import pickle #cat: 1, dog: 0 training_data_path = '/Path/to/folder/containing/images' IMG_SIZE = 100 training_data = [] def create_training_data(): counter = 0 for file in os.listdir(training_data_path): if 'cat' in str(file): label = 1 img_path = os.path.join(training_data_path, file) array = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE) new_array = cv2.resize(array, (IMG_SIZE, IMG_SIZE)) training_data.append([new_array, label]) print(counter) counter += 1 else: label = 0 img_path = os.path.join(training_data_path, file) print(img_path) print(label) array = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE) new_array = cv2.resize(array, (IMG_SIZE, IMG_SIZE)) training_data.append([new_array, label]) print(counter) counter += 1 random.shuffle(training_data) X = [] y = [] for point in training_data: X.append(point[0]) y.append(point[1]) X = np.array(X) y = np.array(y) pickle_out = open('X3.pickle', 'wb') pickle.dump(X, pickle_out) pickle_out.close() pickle_out = open('y3.pickle', 'wb') pickle.dump(y, pickle_out) pickle_out.close() def NN_model(): pickle_in = open('X3.pickle', 'rb') pickle_in_2 = open('y3.pickle', 'rb') batch_size = 1000 X = pickle.load(pickle_in) y = pickle.load(pickle_in_2) inputs = keras.Input(shape=(X.shape[1:])) f = keras.layers.Flatten()(inputs) predictions = keras.layers.Dense(2, activation=tf.nn.softmax)(f) model = keras.Model(inputs=inputs, outputs=predictions) model.compile(optimizer=tf.train.AdamOptimizer(learning_rate=0.1), loss='sparse_ca…
has answer: http://stackoverflow.com/a/51945095
tagged with: network-programming
answer count: 1
tagged with: keras
tagged with: python
accepted answer: http://stackoverflow.com/a/51945095
score: 0
type: AnsweredQuestion

http://stackoverflow.com/q/51937189
has title: learning python,sample file that's correct from a valid instructor.first time to deal with it,append & pop command do not work on my PC
type: Question
has comment: http://stackoverflow.com/comment/90824388
has body: a.append([1, 2]) print(a) NameError Traceback (most recent call last) in () ----> 1 a.append([1, 2]) 2 print(a) NameError: name 'a' is not defined &lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;
tagged with: python
linked to: http://stackoverflow.com/q/11007627
tagged with: python-3.x
answer count: 1
has answer: http://stackoverflow.com/a/51937448
downvote count: 5
upvote count: 0
score: -5
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90824610
favorite count: 0

http://stackoverflow.com/q/51946290
has comment: http://stackoverflow.com/comment/90841988
tagged with: oop
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51947373
score: -1
has comment: http://stackoverflow.com/comment/90841902
linked to: http://stackoverflow.com/q/4205130
answer count: 1
has comment: http://stackoverflow.com/comment/90842691
has title: Class initialization inside a function?
favorite count: 0
has body: I am trying to understand object oriented programming of python. In the following code when I omit class Dataset and pass statement from function read_data_set and try to create object without giving some argument - I get error that positional arguments a missing. But when I run this code without omitting anything it works fine even if I don't mention positional arguments while creating object. Why it doesn't raise error in this case? Can someone please guide me whats going on in the following code? Secondly I also want to know that when I mention class Dataset with a pass statement does it mean that I am creating a new class or does it mean I am just redefining this? class Dataset: def __init__(self,MC_sample,MC_label): self.__MC_sample = MC_sample self.__MC_label = MC_label def read_data_set(): class Dataset: pass data_sets = Dataset() #object created return data_sets
type: UnansweredQuestion
downvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/90842174
has comment: http://stackoverflow.com/comment/90844494

http://stackoverflow.com/comment/90860905
has text: If I use Button then the image will stretch to fit the button. Why do you think I did not just use Button to start with?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51954416
type: AnswerComment

http://stackoverflow.com/q/51804368
has body: so I have set up Django allauth on my Django project and connected to Instagram, when doing so I have now on my admin site Social accounts category with my account registers, all good so far on the lower page, I can see a field called extra data, how can I put it inside the normal Users database so I can use it to take how many followers I got out of the extra data? can I request the followers with the Token i have maybe?
answer count: 1
downvote count: 0
tagged with: django-jsonfield
tagged with: django-allauth
tagged with: python
favorite count: 0
type: UnansweredQuestion
tagged with: django
upvote count: 1
tagged with: django-database
type: Question
has answer: http://stackoverflow.com/a/51805154
score: 1
has title: Django allauth Social application extra data

http://stackoverflow.com/q/51828690
has comment: http://stackoverflow.com/comment/90611994
tagged with: python
type: AnsweredQuestion
upvote count: 1
has body: I am getting this error everytime i run this code using .format() Code: list_A = [1,2,3,4] #Declaring List_A with items 1,2,3,4 list_B = [6,7,8,9] #Declaring List_B with items 5,6,7,8 print("list_A is: {} and list_B is: {}".format(list_A, list_B)) #Prints list_A and list_B print("length of list_A is: {0} and length of list_B is: {1}".format(len(list_A), len(list_B)) #Prints length of list_A with list_B Output File "&lt;ipython-input-76-d54f829c5c52&gt;", line 5 print("length of list_A is: {0} and length of list_B is: {1}".format(len(list_A), len(list_B)) #Prints length of list_A with len() ^ SyntaxError: unexpected EOF while parsing
type: Question
score: -1
has title: unexpected EOF while parsing in Python 3?
has comment: http://stackoverflow.com/comment/90611905
answer count: 1
has answer: http://stackoverflow.com/a/51828704
accepted answer: http://stackoverflow.com/a/51828704
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90612042
downvote count: 2

http://stackoverflow.com/q/51845416
has title: Half of tkinter button border white?
tagged with: python
accepted answer: http://stackoverflow.com/a/51845496
score: 2
type: AnsweredQuestion
tagged with: tkinter
upvote count: 2
type: Question
has body: For some odd reason my tkinter button's border is half white half black, is this normal/fixable? I want the whole border to be black btn_Next1 = tk.Button(self, text="Next", command=lambda: controller.show_frame(PageOne)) btn_Next1.configure(font=buttonfont, fg='#ffffff', background='#00497a', highlightbackground='#3E4149', borderwidth=2)
has comment: http://stackoverflow.com/comment/90649973
has answer: http://stackoverflow.com/a/51845496
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/90645219
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/a/51866266
answers question: http://stackoverflow.com/q/51866091
has comment: http://stackoverflow.com/comment/90692143
has comment: http://stackoverflow.com/comment/90685119
score: 0
has comment: http://stackoverflow.com/comment/90684844
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90686684
type: Answer
has body: The reason for this is that the other_module.py was loaded before the logging system was configured and its logger is instantiated using default values. If you put the basicConfig call before import other_module the logging level will be as intended.
accepted answer of: http://stackoverflow.com/q/51866091

http://stackoverflow.com/q/51939518
upvote count: 2
has body: I am trying to parallelize lime framework on databricks , but not able to do so. I dont know how , how can i send every observation on different workers, if anyone could help. Ex plainer is coming from the lime framework. Code below : import lime import lime.lime_tabular explainer= lime.lime_tabular.LimeTabularExplainer(X_train,feature_names=train_columns, class_names=['look_forward_Repatha'],verbose=True, mode='regression') -------------------------------- def calculate_in_parallel(line): test_nparray = np.array(line) exp = explainer.explain_instance(test_nparray,xgb_model.predict, num_features=30) return exp.as_list() test_rdd = sc.parallelize(df_pred_X_test_skew_nohighcoll.values) test_rdd = test_rdd.map(calculate_in_parallel) test_rdd = test_rdd.collect()
tagged with: apache-spark
favorite count: 0
type: UnansweredQuestion
tagged with: python
has title: Parallelizing Lime in data bricks
tagged with: parallel-processing
score: 2
answer count: 0
downvote count: 0
tagged with: lime
type: Question

http://stackoverflow.com/q/51831958
has body: Assuming I have two models: from django.db import models class Parent(models.Model): pass class Child(models.Model): parent = models.ForeignKey(Parent, on_delete=models.CASCADE, related_name='children') active = models.BooleanField() How might I go about getting a query set of parents that have at least 1 active child? In other words, how would I get a query set of parents that excludes those without any active children? If using model properties in filters was feasible, this would be a trivial task, but that is not possible. This is also a simple operation using list comprehensions, but it's important here for the queryset to be the end result.
tagged with: model
has answer: http://stackoverflow.com/a/51833409
accepted answer: http://stackoverflow.com/a/51832144
tagged with: django
upvote count: 1
tagged with: python
type: AnsweredQuestion
has title: How to retrieve a queryset using any/exists/all logic across foreign key relationships in Django?
tagged with: filtering
score: 1
has answer: http://stackoverflow.com/a/51832144
type: Question
answer count: 2
downvote count: 0
possible better answer: http://stackoverflow.com/a/51833409
favorite count: 0
tagged with: foreign-keys

http://stackoverflow.com/comment/90577138
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51811009
has text: Right, pandas is smart enough to get the dtype right.

http://stackoverflow.com/comment/90862188
has text: That isn't a string representation of a valid list, what is `10.10.10.10` supposed to be
score: 9
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51955809

http://stackoverflow.com/comment/90741331
comment on: http://stackoverflow.com/a/51893057
type: AnswerComment
type: Comment
has text: You may add some documentation instead of pasting code without any details.
score: 2

http://stackoverflow.com/q/51845854
has comment: http://stackoverflow.com/comment/90645472
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90648044
downvote count: 2
has comment: http://stackoverflow.com/comment/90645419
type: Question
has body: I have the following code: import csv import operator import sys with open('countryInfo.csv','r', encoding='utf-8') as csvfile: reader = csv.DictReader(csvfile, delimiter='\t') result = sorted(reader, key = lambda d: float(d['population']),reverse = True) # for row in result: # print(row) # for row in result: # print(row['name'], row['capital'], row['population']) writer = csv.DictWriter(open('country_simple_info.csv', 'w', encoding='utf-8'), reader.fieldnames) #with open("country_simple_info.csv", "w", encoding='utf-8') as csvoutfile: writer.writeheader() writer.writerows(result) The goal of this code is to write a program that opens a countryInfo.csv file and extracts the country name, capital city and population from each row, then writes a new file named country_simple_info.csv with country, capital and population in each row, with the rows sorted by population size, largest first. The file has columns with other information such as continent, languages, etc. but the code should ignore those. In my code above, when I uncomment the print statements, the code can print the expected output - something in the following format: country,capital,population China,Beijing,1330044000 India,New Delhi,1173108018 United States,Washington,310232863 ....... However, I cannot get the file to be written. Any ideas? And also, I am not allowed to use pandas.
has title: Cannot write a file
has comment: http://stackoverflow.com/comment/90645113
upvote count: 0
score: -2
has answer: http://stackoverflow.com/a/51846089
has comment: http://stackoverflow.com/comment/90645519
answer count: 1
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/q/51940862
tagged with: datetime
tagged with: python
has answer: http://stackoverflow.com/a/51956651
has title: Parsing date string with multiple days
type: Question
tagged with: date
score: 0
has answer: http://stackoverflow.com/a/51941137
has answer: http://stackoverflow.com/a/51942939
has answer: http://stackoverflow.com/a/51959129
tagged with: parsing
has answer: http://stackoverflow.com/a/51941026
has comment: http://stackoverflow.com/comment/90831685
answer count: 5
type: UnansweredQuestion
has body: I have some dates that contain multiple days that I am trying to parse. It seems that the datetime.strptime function does not support regular expressions and thus I cannot get it to ignore one day at a time. Is there an easy solution to this that I am missing? Here are some examples: March 20 &amp; June 8, 2011 September 4 &amp; 27, 2010 February 15, December 5 &amp; 6, 2013 I know that each of these examples differ quite drastically, but I am hoping to get a solution for even one of them. An approach that can easily work across a wide range with some formatting parameter would be awesome. Additionally, there may be cases where the date is formatted differently which I assume should be easier to handle: 7/2/2011 &amp; 8/9/2011

http://stackoverflow.com/comment/90749422
has text: You `Derived` class doesn't derive from anything.
type: Comment
comment on: http://stackoverflow.com/q/51897243
type: QuestionComment
score: 0

http://stackoverflow.com/comment/90850062
has text: `pos_change` would be better as a dict of dicts (`pos_change = {'s' : {4: 'h', 6: 'k', 7: 'p', 10: 'r'}}`)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51949959
score: 1

http://stackoverflow.com/a/51892882
answers question: http://stackoverflow.com/q/51892824
score: 3
type: AcceptedAnswer
has body: If I understood you correctly, you can use: df1['value'] = np.where(df1['age'].isnull(), 1, '') Output: id age value 0 1 0.0 1 2 NaN 1 2 3 10.0 3 5 2.0
type: Answer
upvote count: 3
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51892824

http://stackoverflow.com/a/51915350
has comment: http://stackoverflow.com/comment/90781162
score: 0
has comment: http://stackoverflow.com/comment/90780806
has comment: http://stackoverflow.com/comment/90780859
answers question: http://stackoverflow.com/q/51915174
has comment: http://stackoverflow.com/comment/90780836
has comment: http://stackoverflow.com/comment/90781179
has comment: http://stackoverflow.com/comment/90781248
type: Answer
has comment: http://stackoverflow.com/comment/90780787
has body: Check if this works better with python 3.7, as mentioned in zeromq/pyzmq issue 1050 The .c files were generated with Cython. It would appear that Python 3.7 has changed its C API, such that the .c files are no longer compatible with Python 3.7. We'll need to wait for a Cython release that fixes support for unreleased Python before we can use it.

http://stackoverflow.com/comment/90711129
has text: Thanks! I think your problem lays in the double quote character, which has code `201c`, you should better use utf-8 coding.
type: QuestionComment
type: Comment
score: 1
comment on: http://stackoverflow.com/q/51877520

http://stackoverflow.com/comment/90623428
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51834649
score: 0
has text: Just ignore it. Let tools help you but not dominate you.

http://stackoverflow.com/q/51918197
has answer: http://stackoverflow.com/a/51918263
has title: Remove from list in python 3
has answer: http://stackoverflow.com/a/51918423
accepted answer: http://stackoverflow.com/a/51918286
favorite count: 0
has comment: http://stackoverflow.com/comment/90786173
tagged with: python
answer count: 4
has answer: http://stackoverflow.com/a/51918251
type: AnsweredQuestion
tagged with: list
upvote count: 2
score: 1
possible better answer: http://stackoverflow.com/a/51918251
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51918286
has body: I have a list that I have scraped from a website. I want to remove the links that are anchors for the various pages of the site, for example '/about/'. There are a number of them. Rather than make different loops that remove from the list, is there a way that I can build a code that looks at the text and if "http" (not just https like the data below has because what if the "s" is not there) is in the text then it would add it to the list? My list data is this: ['mailto:info@yourdomain.com', 'https://www.demodms.com/annuity/', 'https://www.demodms.com/annuity/', 'https://www.demodms.com/annuity/about/', 'https://www.demodms.com/annuity/services/', 'https://www.demodms.com/annuity/educational-courses/', 'https://www.demodms.com/annuity/events/', 'https://www.demodms.com/annuity/articles-and-downloads/', 'https://www.demodms.com/annuity/videos/', 'https://www.demodms.com/annuity/calculators/', 'https://www.demodms.com/annuity/news/', 'https://www.demodms.com/annuity/contact/', 'https://www.demodms.com/annuity/', 'https://www.demodms.com/annuity/about/', 'https://www.demodms.com/annuity/services/', 'https://www.demodms.com/annuity/educational-courses/', 'https://www.demodms.com/annuity/events/', 'https://www.demodms.com/annuity/articles-and-downloads/', 'https://www.demodms.com/annuity/videos/', 'https://www.demodms.com/annuity/calculators/', 'https://www.demodms.com/annuity/news/', 'https://www.demodms.com/annuity/contact/', '/events/', 'https://www.demodms.com/annuity/tips-for-back-to-school-season/', 'https://www.demodms.com/annuity/tips-for-back-to-school-season/', 'https://www.demodms.com/annuity/5-things-to-know-about-getting-life-insurance-for-your-child/', 'https://www.demodms.com/annuity/5-things-to-know-about-getting-life-insurance-for-your-child/', 'https://www.demodms.com/annuity/5-signs-you-need-to-up-your-life-insurance-coverage/', 'https://www.demodms.com/annuity/5-signs-you-need-to-up-your-life-insurance-coverage/', 'https://www.demodms.com/annuity/tips-…

http://stackoverflow.com/q/51933714
type: UnansweredQuestion
upvote count: 1
tagged with: python
downvote count: 1
has body: I am currently making a flask app. I cant get the javascript to update whenever I do a post request. It just stays the same. Here is the code I am focused on that is supposed to update whenever I do a post request: var jsonz =; var s = JSON.parse(jsonz); var i; for (i = 0; i < s.length; i++) { var para = document.createElement("p"); var node = document.createTextNode(s[i].product_name + "\n" + s[i].product_link); para.appendChild(node); var element = document.getElementById("div1"); element.appendChild(para); I am very new to javascript. I want to pass in "entries" from the back end and then have that json be displayed in the index.html. Someone please help. Here is the full code for index.html Flask app Home About Contact submit you searched: and here is app.py from scraper import scrape from flask import Flask, render_template, jsonify, make_response, request import json app = Flask(__name__) @app.route("/", methods=['GET', 'POST']) @app.route("/index", methods=['GET', 'POST']) def index(): if request.method == 'POST': search = request.get_json() search = json.dumps(search) search = json.loads(search) search = search['text'] print search #search = json.loads(search) entries = json.dumps(scrape(search)) return entries elif request.method == "GET": entries = json.dumps(scrape("cars")) return render_template('index.html', entries= entries) else: return render_template('index.html') if __name__ == "__main__": app.run(debug=True, host='0.0.0.0', port=5000) Again, I want the scraped data in the form of "entries" to be passed to the front end and displayed in the html. Thanks for any help! HERES WHAT I DID TO FINALLY GET IT WORKING Flask app Home About Contact submit search results: and app.py from scraper import scrape from flask import Flask, render_template, jsonify, make_response, request import json app = Flask(__name__) @app.route("/") def index(): return render_template('index.html') @app.route("/parse_data", methods=['POST']) def parse_data()…
type: Question
has comment: http://stackoverflow.com/comment/90822366
has title: How do I update the javascript in my index.html file?
tagged with: javascript
tagged with: jquery
tagged with: flask
tagged with: ajax
has comment: http://stackoverflow.com/comment/90822049
score: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/90821900
answer count: 0

http://stackoverflow.com/a/51926171
downvote count: 0
type: Answer
upvote count: 3
answers question: http://stackoverflow.com/q/51925956
score: 3
has comment: http://stackoverflow.com/comment/90802032
has body: Have you tried the Basic Authentication example from requests? &gt;&gt;&gt; from requests.auth import HTTPBasicAuth &gt;&gt;&gt; requests.get('https://api.github.com/user', auth=HTTPBasicAuth('user', 'pass')) &lt;Response [200]&gt;

http://stackoverflow.com/q/51897699
tagged with: statsmodels
has comment: http://stackoverflow.com/comment/90746433
type: Question
has comment: http://stackoverflow.com/comment/90759988
has title: how statsmodels linear regression model calculate out std error of coefficients?
tagged with: statistics
score: 0
has comment: http://stackoverflow.com/comment/90748924
has body: as you know, statsmodels can print out summary after OLS fit. Following picture will show its output. My question is: how statsmodels can calculate out std err for all the coefs? As i understand, std err describe mean deviation for values to its mean, but here, we can not know its mean, and even no other values(except the exact one value for each coef), so no way to calculate the std err... Can you give me some hint on how does this work and calculated out the std err value?
answer count: 0
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/51833107
answer count: 1
favorite count: 0
has body: UPDATE: I have a list of integers that represent bits values: bits = [1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1] len(bits) == 30 My question is how to add random bit padding so that the length of the bits is 32 and how to remove the padding? Same in the case when I have the length of bits, let say 20, how to add 4 bit padding so that it become 24 and how to remove back the 4 bit padding?
tagged with: python
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/90620249
has comment: http://stackoverflow.com/comment/90620351
has title: How to add and remove random bit padding in Python
type: Question
accepted answer: http://stackoverflow.com/a/51833145
has answer: http://stackoverflow.com/a/51833145
upvote count: 2
score: 0
downvote count: 2
tagged with: padding

http://stackoverflow.com/q/51814162
tagged with: matplotlib
tagged with: dataframe
tagged with: pandas
answer count: 1
has title: Prettifying Matplotlib Line Graph
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90583570
has comment: http://stackoverflow.com/comment/90583111
has answer: http://stackoverflow.com/a/51814660
tagged with: python
has comment: http://stackoverflow.com/comment/90583596
score: 0
has body: What I'm trying to achieve is a line graph of genres and their average score throughout history. X-axis = years, y-axis = score. genre_list is an array of the types of genres. for genre in genre_list: random_color = [np.random.random_sample(), np.random.random_sample(), np.random.random_sample()] plt.plot('release_year', 'vote_average', data=genre_df, marker='', markerfacecolor=random_color, markersize=1, color=random_color, linewidth=1, label = genre) plt.legend() plt.figure(figsize=(5,5)) Though what I end up with is quite ugly. Question 1) I've tried setting the figure size, but it seems to stay the same proportion. How do I configure this? Question 2) How do I set the line color to match the legend? Question 3) How do I configure the x and y axis so that they are more precise? (potentially the same question as #1) I appreciate any sort of input, thank you.
linked to: http://stackoverflow.com/q/12608788
type: Question
tagged with: graph

http://stackoverflow.com/comment/112130254
type: AnswerComment
type: Comment
score: 1
comment on: http://stackoverflow.com/a/51881060
has text: I would like to point out that this library is not really capable of creating tables as it appears based on the example. The table is here drawn as set of frames, each representing a cell. Furthermore, there's no flow control whatsoever, so without manual wrapping and manual size modifications, the table and contents do not communicate together at all. It could be still a good tool for some purposes, but might be a show stopper for many.

http://stackoverflow.com/q/51920827
tagged with: pandas
has answer: http://stackoverflow.com/a/51920852
accepted answer: http://stackoverflow.com/a/51920852
downvote count: 0
favorite count: 0
tagged with: python
type: AnsweredQuestion
has body: I have the following dataframe: U_ID Group Location Hours People Date 149 17 USA 2 2 2014-11-03 149 17 USA 2 1 2014-11-07 149 21 USA 3 2 2014-12-21 149 18 UK 1.5 1 2014-11-14 149 19 Spain 2 4 2014-11-21 Which I can rollup the number of hours with the following code snippet: def process_hours(hr_df): hr_df['Date'] = pd.to_datetime(hr_df['Date']) hr_df['Hours'] = pd.to_numeric(hr_df['Hours']) hr_df = (vol_df.groupby(['U_ID', 'Group', 'Location', 'People', pd.Grouper(key='Date', freq='MS')])['Hours'].sum().reset_index(level=[0, 1, 2, 3])) However this splits when the number of people differ: U_ID Group Location People Hours Date 2014-11-01 149 17 USA 1 2.0 2014-11-01 149 17 USA 2 2.0 2014-11-01 149 18 UK 1 1.5 2014-11-01 149 19 Spain 4 2.0 2014-12-01 149 21 USA 2 3.0 How do I take the max number of people when the grouping happens to result in this: U_ID Group Location People Hours Date 2014-11-01 149 17 USA 2 4.0 2014-11-01 149 18 UK 1 1.5 2014-11-01 149 19 Spain 4 2.0 2014-12-01 149 21 USA 2 3.0
score: 3
has answer: http://stackoverflow.com/a/51920866
upvote count: 3
type: Question
tagged with: dataframe
has title: How to take the max value of a series when using pandas Grouper?
answer count: 2
possible better answer: http://stackoverflow.com/a/51920866

http://stackoverflow.com/a/51903827
answers question: http://stackoverflow.com/q/51870699
has body: I ended up learning that just because I created an SSH connection, I still needed to set up an SSH Tunnel with port forwarding, so the script knows where to communicate. I made the assumption that the connection itself would tell the script where to look (when in reality the port forwarding tells it where to look and listen). So I was skipping a step. The final working script uses SSHTunnelForwarder from the sshtunnel library. import mysql.connector from datetime import date, datetime, timedelta from sshtunnel import SSHTunnelForwarder ssh_host = 'servername.net' ssh_port = 22 ssh_user = 'serveruser' ssh_key = "C:\\Users\\user\\ssh\\public key" ssh_remote_port = 3306 with SSHTunnelForwarder( (ssh_host, ssh_port), ssh_username=ssh_user, ssh_private_key=ssh_key, remote_bind_address=('127.0.0.1', ssh_remote_port) ) as server: cnx = mysql.connector.connect(user='username', password='password', database='analyst_db, host='localhost', port=server.local_bind_port) cur = cnx.cursor()
accepted answer of: http://stackoverflow.com/q/51870699
upvote count: 1
type: AcceptedAnswer
type: Answer
downvote count: 0
score: 1

mongodb
tags question: http://stackoverflow.com/q/51925468
tags question: http://stackoverflow.com/q/51945976
tags question: http://stackoverflow.com/q/51872613
tags question: http://stackoverflow.com/q/51848411
tags question: http://stackoverflow.com/q/51906514
tags question: http://stackoverflow.com/q/51898404
tags question: http://stackoverflow.com/q/51885715
tags question: http://stackoverflow.com/q/51879359
tags question: http://stackoverflow.com/q/51897517
tag name: mongodb
tags question: http://stackoverflow.com/q/51858168
tags question: http://stackoverflow.com/q/51888323
tags question: http://stackoverflow.com/q/51830805
type: Tag
tags question: http://stackoverflow.com/q/51834431
tags question: http://stackoverflow.com/q/51856567
tags question: http://stackoverflow.com/q/51897701
tags question: http://stackoverflow.com/q/51903663
tags question: http://stackoverflow.com/q/51862688
tags question: http://stackoverflow.com/q/51814146
tags question: http://stackoverflow.com/q/51804780
tags question: http://stackoverflow.com/q/51801883
tags question: http://stackoverflow.com/q/51825876
tags question: http://stackoverflow.com/q/51905306
tags question: http://stackoverflow.com/q/51847929
tags question: http://stackoverflow.com/q/51860786

http://stackoverflow.com/comment/90637418
score: 1
has text: You have a newline at the end of your string, which `int` chokes on. `list(raw_input(...).strip())` should work.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51842218

http://stackoverflow.com/comment/90684191
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51865989
type: AnswerComment
has text: I know its a bit much, but the behavior of `round` just feels so weird to me!

http://stackoverflow.com/a/51803118
answers question: http://stackoverflow.com/q/51802744
downvote count: 0
has comment: http://stackoverflow.com/comment/90565762
type: Answer
has comment: http://stackoverflow.com/comment/90562788
upvote count: 3
has body: Your problem has nothing to do with np.linspace. Neither does np.linspace has specific precision. You can try x = np.linspace(0, 10**(-10), num=10000) and see that it works fine. The problem is that you're running out of memory. Every time you divide the increment by 10, your array gets 10 times larger. There's nothing you can do about it. The only approach would be, instead of generating the whole a array in advance, to generate its elements in a loop. eg while increment &gt; 10**(-12): # start_timing for a in range(start, end, increment): b = 3*a - 2 # stop timing increment = increment / 10 Since built-in range seems to accept only integer step, and np.arange mentions that it does not work well with non-integer step, you could make your own range function. Take care that it must be a generator, otherwise you'll run out of memory def my_range(start, stop, step): current = start while current &lt; stop: current += step yield current
score: 3
has comment: http://stackoverflow.com/comment/90579479

http://stackoverflow.com/q/51935459
answer count: 2
tagged with: arrays
has answer: http://stackoverflow.com/a/71147951
has title: Finding standard deviations along x and y in 2D numpy array
favorite count: 0
has comment: http://stackoverflow.com/comment/90821998
has comment: http://stackoverflow.com/comment/90823350
tagged with: python
tagged with: python-3.x
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90821524
has answer: http://stackoverflow.com/a/51935557
has body: If I have a 2D numpy array composed of points (x, y) that give some value z(x, y) at each point, can I find the standard deviation along the x-axis and along the y-axis? I know that np.std(data) will simply find the standard deviation of the entire dataset, but that's not want I want. Also, adding in axis=0 or axis=1 computes the standard deviations along each axis for as many rows or columns that you have. If I just want one standard deviation along the y-axis, and another along the x-axis, can I find these in a dataset like this? From my understanding, standard deviations along x and y normally make sense when you have points x with values y(x). But I need some sigma_x and sigma_y for a 2D Gaussian fit I'm trying to do. Is this possible? Here is an oversimplified example, since my actual data is much larger. import numpy as np data = np.array([[1, 5, 0, 3], [3, 5, 1, 1], [41, 33, 9, 20], [11, 20, 4, 13]]) print(np.std(data)) #not what I want &gt;&gt;&gt; 11.78386 print(np.std(data, axis=0)) #this gives me as many results as there are rows/columns so it's not what I want &gt;&gt;&gt; [16.03 11.69 3.5 7.69] I'm not sure how the output corresponding to what I want would look like, since I'm not even sure if it's possible in a 2D array with shape > nx2. But I want to know if it's possible to compute a standard deviation along the x-axis, and one along the y-axis. I'm not even sure if this makes sense for a 2D array... But if it doesn't, I'm not sure what to input as my sigma_x and sigma_y for a 2D Gaussian fit.
downvote count: 1
has comment: http://stackoverflow.com/comment/90822345
score: 1
tagged with: standard-deviation
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/90821044

http://stackoverflow.com/comment/90829351
has text: That's unnecessary overhead. O(n) to hash all items in the list + O(1) to check membership. It's only ever going to be called once during runtime after initialization. `if site_name in sites1 + sites2:` is still more efficient and simpler. PEP20: "Simple is better than complex"
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51938432

http://stackoverflow.com/q/51844665
has comment: http://stackoverflow.com/comment/90862968
downvote count: 1
has body: I want to change the metadata of the pdf file using this code: from PyPDF2 import PdfFileReader, PdfFileWriter title = "Vice-présidence pour l'éducation" fin = open(filename, 'rb') reader = PdfFileReader(fin) writer = PdfFileWriter() writer.appendPagesFromReader(reader) metadata = reader.getDocumentInfo() metadata.update({'/Title':title}) writer.addMetadata(metadata) fout = open(filename, 'wb') writer.write(fout) fin.close() fout.close() It works fine if the title is in english(no accents) but when it has accents I get the following error: TypeError: createStringObject should have str or unicode arg How can I add a title with accent to the metadata ? Thank you
has comment: http://stackoverflow.com/comment/90872000
score: 3
type: Question
upvote count: 4
has comment: http://stackoverflow.com/comment/90801874
has comment: http://stackoverflow.com/comment/90872736
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/90681675
has comment: http://stackoverflow.com/comment/90872193
has comment: http://stackoverflow.com/comment/90959944
tagged with: http://stackoverflow.com/tag/pdf
has comment: http://stackoverflow.com/comment/90833986
tagged with: python
has answer: http://stackoverflow.com/a/52007487
has comment: http://stackoverflow.com/comment/90692583
has title: Add pdf metadata with accents in python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90872798

http://stackoverflow.com/a/51858090
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/90668358
has comment: http://stackoverflow.com/comment/90668274
accepted answer of: http://stackoverflow.com/q/51857406
upvote count: 2
answers question: http://stackoverflow.com/q/51857406
type: AcceptedAnswer
type: Answer
has body: You can insert a default value in the entry field; here is a little example that subclasses tk.Entry, that you can reuse in your own project: import tkinter as tk class EntryBoxWithNegativeDollarSign(tk.Entry): def __init__(self, master, *args, **kwargs): self.master = master super().__init__(self.master, *args, **kwargs) self.default = '-$' self.insert(0, self.default) self.pack() def set_default(self): self.delete('0',tk.END) self.insert(0, self.default) def get(self): value = - float(super().get()[2:]) self.set_default() print(value) return value root = tk.Tk() app = tk.Frame(root) app.pack() entry = EntryBoxWithNegativeDollarSign(app) tk.Button(app, text='get value', command=entry.get).pack() root.mainloop()

http://stackoverflow.com/comment/90800060
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51925072
has text: @JacquelynTan you can do that, sure, but you diminish functionality and reusability of `remove_stop`. It'd be more versatile if you could pass in any list whether from a text file of any name or not rather than having to be restricted to one specific text file.
type: Comment

google-bigquery
tags question: http://stackoverflow.com/q/51850473
tags question: http://stackoverflow.com/q/51920405
type: Tag
tags question: http://stackoverflow.com/q/51940352
tags question: http://stackoverflow.com/q/51824201
tag name: google-bigquery

http://stackoverflow.com/q/51859917
has comment: http://stackoverflow.com/comment/90672259
has comment: http://stackoverflow.com/comment/90672260
has answer: http://stackoverflow.com/a/51861094
has body: You are given a dictionary which is mapping of number and feature. Create a function to convert dictionary to a matrix without numpy or any similar package. Simply use basic python operations. Input Dictionary: { 11:['a','b','c'] 22:['c','d','e'] } output must be like this: [ ['tag','a','b','c','d','e'] [11,1,1,1,0,0] [22,0,0,1,1,1] ] I tried but cant so help
has comment: http://stackoverflow.com/comment/90672925
tagged with: function
answer count: 1
favorite count: 0
downvote count: 3
tagged with: matrix
tagged with: converters
score: -3
has comment: http://stackoverflow.com/comment/90672324
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/90672618
upvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90672133
type: Question
has title: How to create function to convert dictionary to a matrix without numpy or any similar package

http://stackoverflow.com/q/51930730
has comment: http://stackoverflow.com/comment/90811584
type: Question
has answer: http://stackoverflow.com/a/51931468
has answer: http://stackoverflow.com/a/51933651
tagged with: python
has body: On my machine I have python3.4 and a recently downloaded python3.6 installed, I would like to set python3.6 as my default python used in command prompt. I have removed the python34 path variable but my when I access python through the command prompt it still defaults to opening python3.4. I saw this question about access the non default python but that was for specific files. Since posting the question: I have also removed python34 from the system path variables. Typing where python in command prompt returns this: C:\&gt;where python C:\Python34\python.exe C:\Python36\python.exe Typing echo %PATH% returns C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\iCLS\;C:\Program Files\Intel\Intel(R) Management Engine Components\iCLS\;C:\ProgramData\Oracle\Java\javapath;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\Microsoft SQL Server\Client SDK\ODBC\130\Tools\Binn\;C:\Program Files (x86)\Microsoft SQL Server\140\Tools\Binn\;C:\Program Files (x86)\Microsoft SQL Server\140\DTS\Binn\;C:\Program Files (x86)\Microsoft SQL Server\140\Tools\Binn\ManagementStudio\;C:\Program Files\dotnet\;C:\Program Files\Microsoft SQL Server\130\Tools\Binn\;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files\Intel\WiFi\bin\;C:\Program Files\Common Files\Intel\WirelessCommon\;C:\Python34;;C:\WINDOWS\System32\OpenSSH\;C:\Python36\Scripts\;C:\Python36\;C:\Users\ME\AppData\Local\Microsoft\WindowsApps;C:\Program Files\Intel\WiFi\bin\;C:\Program Files\Common Files\Intel\WirelessCommon\; The accepted answer on the proposed duplicate states it is possible but you shouldn't do it, and doesn't give details on how to do it.
linked to: http://stackoverflow.com/q/24814724
possible better answer: http://stackoverflow.com/a/51933651
has comment: http://stackoverflow.com/comment/90811535
has comment: http://stackoverflow.com/comment/90811240
upvote count: 7
has comment: http://stackoverflow.com/comment/90812126
has comment: http://stackoverflow.com/comment/90811508
linked to: http://stackoverflow.com/q/5846167
has comment: http://stackoverflow.com/comment/90811888
accepted answer: http://stackoverflow.com/a/51931468
has answer: http://stackoverflow.com/a/51931339
has comment: http://stackoverflow.com/comment/90811612
has title: Change default python version for command prompt
has comment: http://stackoverflow.com/comment/90811458
answer count: 4
type: AnsweredQuestion
tagged with: environment-variables
has comment: http://stackoverflow.com/comment/90811800
downvote count: 0
score: 7
favorite count: 0
has answer: http://stackoverflow.com/a/66126428

serverless-framework
tag name: serverless-framework
tags question: http://stackoverflow.com/q/51939709
type: Tag

http://stackoverflow.com/q/51902595
score: -1
favorite count: 0
has title: How do I extract variables that repeat from an Excel Column using Python?
tagged with: pycharm
has comment: http://stackoverflow.com/comment/90756419
downvote count: 2
tagged with: openpyxl
upvote count: 1
tagged with: python
answer count: 1
has comment: http://stackoverflow.com/comment/90768893
has comment: http://stackoverflow.com/comment/90756791
has body: I'm a beginner at Python and I have a school proyect where I need to analyze an excel document with information. It has aproximately 7 columns and more than 1000 rows. Theres a column named "Materials" that starts at B13. It contains a code that we use to identify some materials. The material code looks like this -> 3A8356. There are different material codes in the same column they repeat a lot. I want to identify them and make a list with only one code, no repeating. Is there a way I can analyze the column and extract the codes that repeat so I can take them and make a new column with only one of each material codes? An example would be: 12 Materials 13 3A8356 14 3A8376 15 3A8356 16 3A8356 17 3A8346 18 3A8346 and transform it toosomething like this: 1 Materials 2 3A8346 3 3A8356 4 3A8376
has comment: http://stackoverflow.com/comment/90756500
has comment: http://stackoverflow.com/comment/90756631
has answer: http://stackoverflow.com/a/51902638
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90756440
type: Question
tagged with: xlrd
tagged with: pandas

http://stackoverflow.com/comment/90802492
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51926385
type: Comment
has text: @Sunitha there is a file named 'pyo' and it's type is a compiled python file, and I tried deleting it but when I ran my code, it said 'Traceback (most recent call last): File "C:\Python27\pyotest.py", line 1, in <module> from pyo import * ImportError: No module named pyo'

http://stackoverflow.com/a/51846024
type: Answer
score: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/90665283
upvote count: 3
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51838853
has body: Updated answer Okay, I managed to implement my own suggestion, but it was not trivial and still has quirks. Complicating factors were: Dash does not permit two callbacks to target the same Output There is no good way to track which Input or Event triggered your callback. Workarounds generally involve tracking the number of clicks per button (see https://github.com/plotly/dash-html-components/pull/37 as an example). Disabling a timer via disable=True or max_requests=0 appears to be permanent. Once I stopped a timer in this way, I could not restart it with either disable=False or max_requests=1000. Issues: In this solution, update_output_div() gets called twice -- but you can tell the difference between the two by measuring the number of button clicks to the previous count, so you can keep it from submitting your data twice. Timeouts of less than 100ms won't work. I had to split the delay timer for my method to work, so I chose 100 and (1000 * BUTTON_PRESS_LOCKOUT_SECONDS)-100 as the two timer durations. In principle, you could split them evenly half and half. I don't know if there are any problems with using a low timeout when working over the network (I did my testing on localhost). Inspiration drawn from: https://community.plot.ly/t/how-to-turn-off-interval-event/5565/3 https://github.com/plotly/dash-recipes/blob/master/toggle-interval.py import json import datetime import dash from dash.dependencies import Input, Output, State, Event import dash_core_components as dcc import dash_html_components as html BUTTON_PRESS_LOCKOUT_SECONDS = 10 # seconds app = dash.Dash() app.config['suppress_callback_exceptions']=True def serve_layout(): return html.Div([ dcc.Input(id='my-id', value='initial value', type="text"), html.Button('Submit', id='button'), html.Div( [ dcc.Interval(id='interval-component', disabled=True) , dcc.Interval(id='interval-sync-component', disabled=True) ] , id='interval-container' ), html.Div("", id='my-div'), html.Div(json.dumps({'n_clicks':0, 'n_previ…
answers question: http://stackoverflow.com/q/51838853

http://stackoverflow.com/comment/90812150
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51931065
has text: still, the implementation could have checked if `__dir__` is callable

http://stackoverflow.com/comment/90851569
type: AnswerComment
type: Comment
has text: It helped. Thank you!
comment on: http://stackoverflow.com/a/51950693
score: 1

http://stackoverflow.com/comment/90691813
type: Comment
type: QuestionComment
has text: No, this test case is random.
comment on: http://stackoverflow.com/q/51869907
score: 0

http://stackoverflow.com/comment/90745464
type: AnswerComment
comment on: http://stackoverflow.com/a/51896844
score: 0
type: Comment
has text: kind of strange. No I'm not/Don't have one

http://stackoverflow.com/a/52169940
answers question: http://stackoverflow.com/q/51949231
upvote count: 4
has comment: http://stackoverflow.com/comment/91541441
downvote count: 0
type: Answer
has body: I've used pypdfocr in the past to do this. It hasn't been updated recently though. From the README: pypdfocr filename.pdf --&gt; filename_ocr.pdf will be generated Read carefully the Install instructions for Windows. A more recent Python library is OCRmyPDF: https://github.com/jbarlow83/OCRmyPDF There is a Docker image for Windows
has comment: http://stackoverflow.com/comment/91290495
score: 4

http://stackoverflow.com/a/51953223
downvote count: 0
answers question: http://stackoverflow.com/q/51952333
score: 1
upvote count: 1
type: AcceptedAnswer
has body: Given the following dataframe: df = pd.DataFrame([['2018-04-10 00:00:00', 'AAA', 2018, 4, 1, 20, 10, 0, 'hd', 'pv'], ['2018-04-10 01:00:00', 'AAA', 2018, 4, 2, 10, 10, 10, 'fg', 'pv'], ['2018-04-10 00:00:00', 'BBB', 2018, 4, 1, 30, 20, 5, 'cv', 'er'], ['2018-04-10 01:00:00', 'BBB', 2018, 4, 2, 20, 20, 5, 'hd', 'fd'], ['2018-04-10 00:00:00', 'CCC', 2018, 4, 1, 20, 30, 10, 'cv', 'fd'], ['2018-04-10 01:00:00', 'CCC', 2018, 4, 2, 10, 10, 5, 'df', 'ee']], columns = ['Index','CITY','YEAR','MONTH','HOUR','TEMP','DP','CC','ASTR','BSTR']) And weights: weights = {"AAA" : 0.3, "BBB" : 0.4, "CCC" : 0.3} You can do the following: w_a = lambda x: np.average(x, weights=list(weights.values())) new = df.groupby('Index').agg({'TEMP': w_a, 'DP': w_a, 'CC': w_a}) new = new.join(df[df['CITY']=='BBB']'Index','YEAR','MONTH','HOUR','ASTR','BSTR'.set_index('Index'), on='Index') Which gives: TEMP DP CC YEAR MONTH HOUR ASTR BSTR Index 2018-04-10 00:00:00 24 20 5.0 2018 4 1 cv er 2018-04-10 01:00:00 14 14 6.5 2018 4 2 hd fd Note that this solution assumes that the keys in your weights dictionary are provided in the same order that the cities appear in the CITY column of your original df (i.e. sorted alphabetically).
type: Answer
has comment: http://stackoverflow.com/comment/90858575
accepted answer of: http://stackoverflow.com/q/51952333

http://stackoverflow.com/q/51831921
tagged with: stack
accepted answer: http://stackoverflow.com/a/51831973
tagged with: dataframe
has title: How to reverse the `unstack` method of a `DataFrame` in `pandas` back to original object?
type: Question
downvote count: 0
tagged with: pandas
answer count: 1
has answer: http://stackoverflow.com/a/51831973
favorite count: 0
tagged with: pivot-table
upvote count: 1
tagged with: python
has body: I want to convert a symmetric similarity matrix (pd.DataFrame) into an unstacked pd.Series with a pd.MultiIndex and then back into a pd.DataFrame Here is the code to get the symmetric pd.DataFrame and my attempt to reverse the operation. Am I supposed to use pivot? I want to end up with another pd.DataFrame called df_sqr_revert that is the same as the original df_sqr. Does anyone have any idea how to reverse this operation? data = {'sepal_length': {'sepal_length': 1.0, 'sepal_width': 0.44531537502467533, 'petal_length': 0.935877078652436, 'petal_width': 0.9089768166845817}, 'sepal_width': {'sepal_length': 0.44531537502467533, 'sepal_width': 1.0, 'petal_length': 0.2897419517994226, 'petal_width': 0.32172795519309727}, 'petal_length': {'sepal_length': 0.935877078652436, 'sepal_width': 0.2897419517994226, 'petal_length': 1.0, 'petal_width': 0.9813785485254833}, 'petal_width': {'sepal_length': 0.9089768166845817, 'sepal_width': 0.32172795519309727, 'petal_length': 0.9813785485254833, 'petal_width': 1.0}} df_sqr = pd.DataFrame(data) # petal_length petal_width sepal_length sepal_width # petal_length 1.000000 0.981379 0.935877 0.289742 # petal_width 0.981379 1.000000 0.908977 0.321728 # sepal_length 0.935877 0.908977 1.000000 0.445315 # sepal_width 0.289742 0.321728 0.445315 1.000000 Se_vertical = df_sqr.unstack() # petal_length petal_length 1.000000 # petal_width 0.981379 # sepal_length 0.935877 # sepal_width 0.289742 # petal_width petal_length 0.981379 # petal_width 1.000000 # sepal_length 0.908977 # sepal_width 0.321728 # sepal_length petal_length 0.935877 # petal_width 0.908977 # sepal_length 1.000000 # sepal_width 0.445315 # sepal_width petal_length 0.289742 # petal_width 0.321728 # sepal_length 0.445315 # sepal_width 1.000000 # dtype: float64 # df_sqr_revert = Se_vertical.stack() # AttributeError: 'Series' object has no attribute 'stack'
type: AnsweredQuestion
score: 1

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

http://stackoverflow.com/comment/90612646
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51824687
has text: Thanks a lot, Exactly what I was looking for.
type: AnswerComment

http://stackoverflow.com/comment/90687342
comment on: http://stackoverflow.com/q/51867653
has text: @xaxxon Why did the post that I'm linking to work? It was returning an array as well?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90754394
has text: I think you should write this logic in the *view*, not in the template. The expresiveness of Django templates has been restricted (deliberately) to avoid people writing such behavior in a template.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51901590

http://stackoverflow.com/comment/90801596
score: 1
type: Comment
comment on: http://stackoverflow.com/a/51925978
type: AnswerComment
has text: It works please upvote my question. I will tick the answer in 2 mins

http://stackoverflow.com/a/52021572
answers question: http://stackoverflow.com/q/51956181
score: 0
type: Answer
has body: This post here should work i believe to change keep_checkpoint_every_n_hours max_to_keep How to store best models checkpoints, not only newest 5, in Tensorflow Object Detection API? You can also refer official doc https://www.tensorflow.org/api_docs/python/tf/train/Saver

http://stackoverflow.com/q/51870848
has comment: http://stackoverflow.com/comment/90693361
has comment: http://stackoverflow.com/comment/90693407
accepted answer: http://stackoverflow.com/a/51870945
score: 0
has comment: http://stackoverflow.com/comment/90693314
has comment: http://stackoverflow.com/comment/90693093
answer count: 1
has comment: http://stackoverflow.com/comment/90693157
has body: I encountered such a function: import math import random def low_zeros(value): for i in xrange(1, 32): if value &gt;&gt; i &lt;&lt; i != value: break return i - 1 I googled but not found any useful material about value &gt;&gt; i &lt;&lt; i != value:
favorite count: 0
has title: the use of value >> i << i != value:
has comment: http://stackoverflow.com/comment/90693082
has comment: http://stackoverflow.com/comment/90693542
has comment: http://stackoverflow.com/comment/90693238
tagged with: python
has comment: http://stackoverflow.com/comment/90693138
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90693373
has answer: http://stackoverflow.com/a/51870945
upvote count: 3
downvote count: 3
type: Question

http://stackoverflow.com/q/51937913
type: Question
has comment: http://stackoverflow.com/comment/90930960
has comment: http://stackoverflow.com/comment/90861722
downvote count: 0
tagged with: configuration-files
favorite count: 0
has comment: http://stackoverflow.com/comment/90864838
has comment: http://stackoverflow.com/comment/90846134
tagged with: package
has title: Manage configuration files packaged in python modules
tagged with: python
score: 2
has comment: http://stackoverflow.com/comment/90826304
answer count: 0
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90898572
has body: What's the proper way to manage configuration files that are embedded in a python module. I have a python module (e.g. my_py_logger) that does a certain task (i.e. centralized logging). It's meant to be used by other python applications developed by the team. Once it is imported in a python application (e.g. my_py_app_a), developers are able to call a method in the logging module that init's the logging module. This method reads a config file. That config file is inside the my_py_logger package. When I call this method from another package, python is not able to find the config file because the root folder has changed from my_py_logger's root source folder to my_py_app_a's root source folder. my_py_logger __init__.py config/ default.conf init_logger.py my_py_app_a __init__.py app.py I tried to use importlib.import_module(__name__) in the my_py_logger module to get the absolute path of the main file in my_py_logger, so I can technically extract the parent directory from that string/path and concatenate "../config/default.conf" but this feels like a poor solution. I'm sure there is a better way to handle this situation. Maybe putting this as a config file is not the right solution, but I'm sure I'm not the first guy to try this in python. What would be the correct solution?

http://stackoverflow.com/comment/90752671
type: QuestionComment
score: 6
has text: `['a', 'b', 'c']` notation is not a list comprehension.
comment on: http://stackoverflow.com/q/51900773
type: Comment

http://stackoverflow.com/a/51824666
upvote count: 3
has body: You can iterate over your dictionary to access each bid. Ex: import requests url = 'https://api.binance.com/' urlWithSymbol = 'https://api.binance.com/api/v1/depth?symbol=' def getRecentTrades(symbol): response = requests.get(urlWithSymbol+symbol) data = response.json() print(type(data)) for bid in data["bids"]: print(bid) getRecentTrades('NPXSBTC') Output: &lt;type 'dict'&gt; [u'0.00000023', u'159089575.00000000', []] [u'0.00000022', u'187598715.00000000', []] [u'0.00000021', u'118040187.00000000', []] [u'0.00000020', u'168707413.00000000', []] [u'0.00000019', u'64558205.00000000', []] [u'0.00000018', u'63484191.00000000', []] [u'0.00000017', u'32063443.00000000', []] [u'0.00000016', u'40413788.00000000', []] [u'0.00000015', u'41686707.00000000', []] [u'0.00000014', u'16842512.00000000', []] [u'0.00000013', u'8228300.00000000', []] [u'0.00000012', u'3940729.00000000', []] [u'0.00000011', u'4739318.00000000', []] [u'0.00000010', u'5012270.00000000', []] [u'0.00000009', u'15746312.00000000', []] [u'0.00000008', u'2100806.00000000', []] [u'0.00000007', u'3053860.00000000', []] [u'0.00000006', u'13562956.00000000', []] [u'0.00000005', u'13869819.00000000', []] [u'0.00000004', u'18357472.00000000', []] [u'0.00000003', u'76777773.00000000', []] [u'0.00000002', u'7518568.00000000', []] [u'0.00000001', u'10500722.00000000', []]
downvote count: 0
answers question: http://stackoverflow.com/q/51824502
type: Answer
score: 3

http://stackoverflow.com/q/51856488
tagged with: python
type: AnsweredQuestion
score: 1
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51856863
linked to: http://stackoverflow.com/q/51761926
has title: What setup do you need for Python Visualizations in Power BI? Any particular matplotlib package versions or system settings?
tagged with: powerbi
has body: I keep getting the error TypeError: from_bounds() takes 4 positional arguments but 6 were given when trying to insert a Python Visualization in Power BI. Though it seems that Matplotlib is the problem here, I don't know if that is the root cause. My system: Windows 7, 64 bit Power BI august 2018 Python 3.6.6.0 Matplotlib 2.2.2 Pandas 0.23.4 I can't be 100% sure that this is in fact a version problem, but I can't think of anything else because I'm using the same dataset that was successfully used in the post What is the best data format for a time series in a Python Visualization in Power BI?. Data: Date,Value 2017-01-12,1 2017-01-13,4 2017-01-14,2 2017-01-15,4 2017-01-16,2 2017-01-17,2 2017-01-18,2 2017-01-19,5 2017-01-20,5 2017-01-21,5 2017-01-22,5 2017-01-23,6 2017-01-24,3 2017-01-25,6 2017-01-26,6 2017-01-27,5 2017-01-28,8 2017-01-29,4 2017-01-30,2 Code: import matplotlib.pyplot as plt plt.plot(dataset['Date'], dataset['Value']) plt.show() Error message screenshot: Edit 1 - The complete error message: Feedback Type: Frown (Error) Timestamp: 2018-08-15T09:58:44.0322850Z Local Time: 2018-08-15T11:58:44.0322850+02:00 Session ID: 85df81af-81bb-4f82-a7f4-062b315cb370 Release: August, 2018 Product Version: 2.61.5192.601 (18.08) (x64) Error Message: Python script error. Traceback (most recent call last): File "PythonScriptWrapper.PY", line 6, in matplotlib.pyplot.figure(figsize=(3,75,3,52777777777778)) File "C:\Users\userinfo\AppData\Local\Continuum\Anaconda3\lib\site-packages\matplotlib\pyplot.py", line 548, in figure **kwargs) File "C:\Users\userinfo\AppData\Local\Continuum\Anaconda3\lib\site-packages\matplotlib\backend_bases.py", line 160, in new_figure_manager fig = fig_cls(*args, **kwargs) File "C:\Users\userinfo\AppData\Local\Continuum\Anaconda3\lib\site-packages\matplotlib\figure.py", line 361, in init self.bbox_inches = Bbox.from_bounds(0, 0, *figsize) TypeError: from_bounds() takes 4 positional arguments but 6 were given OS Version: Microsoft Windows NT 6.1.760…
has comment: http://stackoverflow.com/comment/90665552
downvote count: 0
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/51856863
has comment: http://stackoverflow.com/comment/90665395

http://stackoverflow.com/comment/90583110
score: 0
comment on: http://stackoverflow.com/q/51814180
has text: Is `all_data` a numpy array or a python array?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90943416
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51944248
has text: Actually, I found out this approach does not work in the case `list_of_values` contains repeated values: the order is not guaranteed to be kept. Im sorry I had to unvote as answer
score: 0

http://stackoverflow.com/comment/90558390
score: 0
has text: It might be because you don't call mainloop on your window?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51798963

http://stackoverflow.com/a/51949943
score: 3
answers question: http://stackoverflow.com/q/51949681
downvote count: 0
type: Answer
upvote count: 3
has body: You can use collections.Counter on an iterable of 3-word groupings. The latter is constructed via a generator comprehension and list slicing. from collections import Counter three_words = (words[i:i+3] for i in range(len(words)-2)) counts = Counter(map(tuple, three_words)) wordscount = {' '.join(word): freq for word, freq in counts.items() if freq &gt; 1} print(wordscount) {'show makes me': 2} Notice we don't use str.join until the very end to avoid unnecessary repeated string operations. In addition, tuple conversion is required for Counter as dict keys must be hashable.

http://stackoverflow.com/q/51852686
upvote count: 0
has comment: http://stackoverflow.com/comment/90663248
favorite count: 0
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/51852723
score: -1
tagged with: openpyxl
accepted answer: http://stackoverflow.com/a/51852723
downvote count: 1
answer count: 1
tagged with: excel
linked to: http://stackoverflow.com/q/37478237
has title: How to get only the output of a formula with excel openpyxl python
has body: My code is: import openpyxl wb = openpyxl.load_workbook('C:\\xampp\\htdocs\\dad_app\\template\\template.xlsm') sheet = wb.get_active_sheet() sheet = wb.active sheet['A1:AP701'] = sheet['A1:AP701'].internal_value But it saves the formula too. How do I remove the formula and only get the output?
type: AnsweredQuestion

http://stackoverflow.com/q/51804600
score: -1
linked to: http://stackoverflow.com/q/14507591
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/90565088
upvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/51804630
has title: Python dict and enumerate usage
has answer: http://stackoverflow.com/a/51804625
duplicate of: http://stackoverflow.com/q/14507591
type: UnansweredQuestion
tagged with: python
downvote count: 1
has body: I am a little confused about a piece of python code in using dict: &gt;&gt;&gt; S = "ababcbacadefegdehijhklij" &gt;&gt;&gt; lindex = {c: i for i, c in enumerate(S)} &gt;&gt;&gt; lindex {'a': 8, 'c': 7, 'b': 5, 'e': 15, 'd': 14, 'g': 13, 'f': 11, 'i': 22, 'h': 19, 'k': 20, 'j': 23, 'l': 21} How to understand it the "{c: i for i, c in enumerate(S)}" ? Could anyone give me some explanations?

http://stackoverflow.com/comment/90682193
has text: @Dipankar Saha I just saw your comment and since it wasn't actually on my response I can't respond there. Could you please provide a formatted version of what you used to get the new errors and the traceback?
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51829264

http://stackoverflow.com/comment/90800295
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51917930
type: Comment
has text: @mzjn, yes. how to install `Sphinx search engine`?

http://stackoverflow.com/q/51832584
downvote count: 1
has title: Can anyone help me with this program?
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51832669
score: -1
accepted answer: http://stackoverflow.com/a/51832669
type: Question
upvote count: 0
has comment: http://stackoverflow.com/comment/90619840
favorite count: 0
has comment: http://stackoverflow.com/comment/90619147
has body: class student: def __init__(self,name,sub,mark): self.name=name self.sub=sub self.mark=mark def on_kv_board(self): if (self.mark&gt;=450): return True else:`enter code here` return False students=[] num_student=int(input("Enter the number of students appeared:")) for entries in range(0,num_student): name=input("Student name:") sub=input("Subject in which "+name+" got the highest mark:") mark=int(input("Total marks obtained/500:")) if student(name,sub,mark).on_kv_board() is True: a=(student(name,sub,mark)) students.append(a) print(students) Whenever I print the students[] list with two inputs it gives me an output [Student.student object at 0x03784790, Student.student object at 0x037D61B0]
answer count: 1
tagged with: python

http://stackoverflow.com/comment/90688336
has text: Thanks Mishra. The code works well! One more question. If there are many days contains 09:00~11:00, how can i check a specific day?
type: AnswerComment
comment on: http://stackoverflow.com/a/51838551
score: 0
type: Comment

http://stackoverflow.com/comment/90807337
comment on: http://stackoverflow.com/a/51926488
has text: This one is much faster and a very clever solution.
type: AnswerComment
type: Comment
score: 1

http://stackoverflow.com/a/51882268
has body: You can use validate method in the ObjectSerializer. class ObjectSerializer(serializers.ModelSerializer): status = StatusSerializer(read_only=True) class Meta: model = Object fields = ('obj_name', 'status',) def validate(self, attrs): validated_data = super().validate(attrs) status = self.initial_data.get('status') # Here assuming that None is not the valid value for status if status is not None: status_obj = Status.objects.filter(name=status) if not status_obj: raise serializer.ValidationError('Invalid Status') status_obj = status_obj[0] validated_data['status'] = status_obj return validated_data # Nothing special to be done in create/update since we are sending data # in validated_data which will directly sent to the instance. # def create(self, validated_data): # We do not want to create new statuses - only use existing ones # status = Status.objects.get(name=self.initial_data['status']) #return Object.objects.create(status=status, **validated_data) #def update(self, instance, validated_data): # instance.obj_name = validated_data.get('obj_name', instance.obj_name) # We do not want to create new statuses - only use existing ones # instance.status = Status.objects.get(name=self.initial_data['status']) if 'status' in self.initial_data else instance.status # return instance And if you can use different keys for write and read status, then you can modify ObjectSerializer like this: class ObjectSerializer(serializer.ModelSerializer): status = serializer.SlugRelatedField(slug_field='name', queryset=Status.objects.all(), write_only=True) status_data = StatusSerializer(read_only=True, source='status') class Meta: model = Object fields = ('obj_name', 'status', 'status_data') In this case, if you pass {'obj_name': 'ObjectName', 'status': 'StatusName'} data to serializer, the serializer will first check for the StatusName value in the name field of the provided queryset (In this case we are using all) and if not valid raises ValidationError. If valid, then saves the status i…
accepted answer of: http://stackoverflow.com/q/51879411
type: Answer
answers question: http://stackoverflow.com/q/51879411
has comment: http://stackoverflow.com/comment/90762003
upvote count: 1
has comment: http://stackoverflow.com/comment/90718427
score: 1
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/90648336
score: 0
type: Comment
type: QuestionComment
has text: and with that i have a blank page with 0 results, and the other categories that worked previously do not work now
comment on: http://stackoverflow.com/q/51846183

http://stackoverflow.com/comment/90714192
score: 0
type: AnswerComment
has text: Is there a way I can write a function or anything for that? My goal is to get a short and clean code, having a `try` block for every variable I need to check doesn't exactly achieve that.
comment on: http://stackoverflow.com/a/51881382
type: Comment

http://stackoverflow.com/comment/90737608
type: QuestionComment
has text: the problem was that the API I was calling would be disconnected with tasks pending and I was trying to "reboot" without the whole app crashing. I added an update for what I've most recently added. It seems to be working, but i'm open to feedback.
comment on: http://stackoverflow.com/q/51862318
score: 0
type: Comment

http://stackoverflow.com/comment/90688232
has text: can you please provide your `f` string?
type: QuestionComment
comment on: http://stackoverflow.com/q/51812883
score: 0
type: Comment

http://stackoverflow.com/comment/90649425
score: 0
type: Comment
type: QuestionComment
has text: You have the same mistake in tag function as the OP from the link. Take a look at the answer there. ` featured_posts.html` is fine.
comment on: http://stackoverflow.com/q/51846977

http://stackoverflow.com/comment/90691457
type: QuestionComment
has text: @EPo Yes, the repository is a package itself. To clarify, I'm working on this project in a team, and I am just testing functionality in the `issue-fix` branch, but I am developing new features myself in the `additional-feature` branch. I hope to have separate environments for each branch so each can be tested and edited independently.
comment on: http://stackoverflow.com/q/51866213
score: 0
type: Comment

http://stackoverflow.com/a/51913344
answers question: http://stackoverflow.com/q/51913232
has body: Operator % has higher precedence than +. See the docs on operator precedence. So a code which does a + b % c evaluates b % c first. In your code, that would mean, the first thing evaluated is ' `` ' % (MemberId) and that fails because there is no %s in ' `` ': 'The user &lt;@%s&gt; have edited his message from ``' + before.content + '`` to `` ' + after.content + ' `` ' % (MemberId) This could be fixed by adding parenthesis around everything before %, e.g.: bot.send_message(bot.get_channel('480495197034381332'), ('The user &lt;@%s&gt; have edited his message from ``' + before.content + '`` to `` ' + after.content + ' `` ') % (MemberId)) But that is still a rather poor way to do it. For example, it fails if there is a % in before.content or in after.content. It also fails if MemberId is a tuple. This would be correct: bot.send_message(bot.get_channel('480495197034381332'), 'The user &lt;@%s&gt; have edited his message from ``%s``' ' to ``%s`` ' % (MemberId, before.content, after.content)) This would be even better: bot.send_message(bot.get_channel('480495197034381332'), f'The user &lt;@{MemberId}&gt; have edited his message from ' f'``{before.content}`` to ``{after.content}`` ')
type: Answer
score: 1
upvote count: 1
downvote count: 0

http://stackoverflow.com/q/51865823
score: 0
tagged with: homebrew
answer count: 1
has answer: http://stackoverflow.com/a/51865927
type: UnansweredQuestion
has title: Homebrew not installing the correct version of Python
has body: I was trying to install Python 3.7 using homebrew with "brew install python". When I check the version of python installed, I get python 2.7.10. Anyone know how to fix this?
type: Question
tagged with: python

http://stackoverflow.com/a/51832546
answers question: http://stackoverflow.com/q/51832490
has comment: http://stackoverflow.com/comment/90619532
type: Answer
has comment: http://stackoverflow.com/comment/90619332
has comment: http://stackoverflow.com/comment/90619301
score: 1
upvote count: 1
has body: You can exclude username field as exclude = ['username'] on your forms.py file and set username to request.user on form's save method. For more information: selecting fields
accepted answer of: http://stackoverflow.com/q/51832490
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90619411
downvote count: 0

http://stackoverflow.com/q/51880774
has answer: http://stackoverflow.com/a/51880971
favorite count: 0
score: 33
type: Question
tagged with: datetime
tagged with: python
has comment: http://stackoverflow.com/comment/90713197
linked to: http://stackoverflow.com/q/48427185
upvote count: 33
tagged with: pyspark
has body: I am trying to figure out, how to extract a date from a datetime value using Pyspark sql. The datetime values look like this: DateTime 2018-05-21T00:00:00.000-04:00 2016-02-22T02:00:02.234-06:00 When I now load this into a spark dataframe and try to extract the date (via Date() or Timestamp() and then Date() I always get the error, that a date or timestamp value is expected, but a DateTime value was provided. Can someone help me with retrieving the date from this value? I think, you need to provide a timezone for that - but since I already had problems extracting only the date, I first wanted to solve this. Thank you and kind regards.
type: UnansweredQuestion
answer count: 2
has title: Pyspark: Extract date from Datetime value
has answer: http://stackoverflow.com/a/51911920
downvote count: 0

text-to-speech
tags question: http://stackoverflow.com/q/51927838
type: Tag
tags question: http://stackoverflow.com/q/51809769
tags question: http://stackoverflow.com/q/51858004
tag name: text-to-speech

http://stackoverflow.com/a/51921921
answers question: http://stackoverflow.com/q/51921673
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51921673
score: 1
has body: The problem is that you're only using static values when calculating the next guess, you're never using the buttons inputted by the user! class GuessForm(FlaskForm): min_a = 0 max_a = 1000 guess = int((max_a - min_a) / 2) + int(min_a) min is always 0, max is always 1000, guess is always 500. Over here: form.max_a = form.guess form.guess = int((form.max_a - form.min_a) / 2) + int(form.min_a) all you use is the min, max and the guess, which we determined were already static, so you're not actually using new information given by the user, hence why you're always seeing the same guess. You need to access, use and update the hidden fields you've already made. I took some time to fix the route, and it works pretty much as expected now: @app.route('/form', methods=['GET', 'POST']) def form(): form = GuessForm() if form.validate(): if form.more.data: form.minn.data = int((int(form.maxx.data) + int(form.minn.data)) / 2) elif form.less.data: form.maxx.data = int((int(form.minn.data) + int(form.maxx.data)) / 2) else: return 'yay' form.guess = int(int(form.maxx.data) - int(form.minn.data)) / 2 + (int(form.minn.data)) return render_template("form.html", form=form)
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90793944
type: Answer

http://stackoverflow.com/comment/90580648
comment on: http://stackoverflow.com/q/51812872
type: QuestionComment
type: Comment
score: 2
has text: At what point is `Bar` known? `class Foo(X):` works just fine even if `X` is a variable, not the literal name of the parent class.

http://stackoverflow.com/q/51935973
possible better answer: http://stackoverflow.com/a/51936041
linked to: http://stackoverflow.com/q/42820342
has answer: http://stackoverflow.com/a/51936041
has body: I am using BeautifulSoup to parse HTML files. I have a HTML file similar to this: Unimportant heading Key A A value I don't want Unimportant heading Key B A value I don't want THE GOOD STUFF Key C I WANT THIS STRING Unimportant heading Key A A value I don't want I want to extract the string "I WANT THIS STRING". The perfect solution would be to get the first table following the h3 heading called "THE GOOD STUFF". I have no idea how to do this with BeautifulSoup - I only know how to extract a table with a specific class, or a table nested within some particular tag, but not following a particular tag. I think a fallback solution could make use of the string "Key C", assuming it's unique (it almost certainly is) and appears in only that one table, but I'd feel better with going for the specific h3 heading.
downvote count: 0
has answer: http://stackoverflow.com/a/51936634
favorite count: 0
tagged with: beautifulsoup
tagged with: python-3.x
has title: How to extract HTML table following a specific heading?
answer count: 3
accepted answer: http://stackoverflow.com/a/51936486
tagged with: python
tagged with: html-parsing
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51936486
score: 4
type: Question
upvote count: 4

http://stackoverflow.com/comment/90571270
type: AnswerComment
has text: Regarding the usage of `lambda`, it's more of a personal preference to explicitly show that in the current context it's only the `page` argument that really matters and allows us to differentiate between the submitted tasks.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51807986

http://stackoverflow.com/comment/90601843
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51809040
score: 0
has text: Yeah sorry thee I was in the middle of doing that but then my laptop suddenly shutdown...

http://stackoverflow.com/a/51943692
has comment: http://stackoverflow.com/comment/90843757
type: Answer
has comment: http://stackoverflow.com/comment/90839960
has body: What you can do is override the ModelAdmin readonly_fields method by making all other fields read only except the one the user should be able to update. def get_readonly_fields(self, request, obj=None): # the logged in user can be accessed through the request object if obj and request.user.is_staff: readonly_fields = [f.name for f in self.opts.fields] readonly_fields.remove('type_leave_field') return readonly_fields Regarding the list comprehension: self.opts gives you access to the Model specified in your Meta class (or @admin.register() should also be fine). self.opts.fields is a tuple consisting of field objects from that model. Each object is a dictionary with meta data of a field. By accessing the .name (key) of each field object we can get the field name represented as a string.
has comment: http://stackoverflow.com/comment/90841918
accepted answer of: http://stackoverflow.com/q/51942716
answers question: http://stackoverflow.com/q/51942716
has comment: http://stackoverflow.com/comment/90839228
has comment: http://stackoverflow.com/comment/90843258
type: AcceptedAnswer
score: 0

http://stackoverflow.com/a/51859030
upvote count: 7
has body: Languages with "infinite" data structures are actually producing objects that produce their values lazily, or "on-demand". Rather than creating the entire list up front, they create an object that, when asked for a value, can create it at that time. In Python, this is most easily managed using a generator. def make_inf_sequence(): x = 0 while True: yield x x = x + 1 # This returns immediately naturals = make_inf_sequence() # This loop runs forever for i in naturals: print(i)
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51858765
type: Answer
answers question: http://stackoverflow.com/q/51858765
score: 7

http://stackoverflow.com/q/51827580
type: Question
tagged with: anaconda
tagged with: gwr
has answer: http://stackoverflow.com/a/51827812
answer count: 1
has title: How to install Pygwr in anaconda?
score: 0
tagged with: python
tagged with: jupyter-notebook
type: UnansweredQuestion
has body: I have found this package for geographically weighted regression (GWR) but I do not know how to install it so I can have access to it while working with Jupiter-notebook?

http://stackoverflow.com/q/51844991
possible better answer: http://stackoverflow.com/a/51847566
has answer: http://stackoverflow.com/a/51847566
score: 0
has title: Compare pandas dataframe rows based on condition
tagged with: pandas
accepted answer: http://stackoverflow.com/a/51845096
tagged with: python
has body: I have a dataframe (df) as follows: d = {'Item':['x','y','z','x','z'], 'Count' : ['10', '11', '12', '9','10'], 'Date' : pd.to_datetime(['2018-8-14', '2018-8-14', '2018-8-14', '2018-8-13','2018-8-13'])} df= pd.DataFrame(data=d) Item Count Date x 10 2018-08-14 y 11 2018-08-14 z 12 2018-08-14 x 9 2018-08-13 x 9 2018-08-12 z 10 2018-08-13 I want to compare rows based on the following: For each item, compare the count of max(Date) with max(Date) - 1. Meaning it should compare the count for item x, for dates 2018-08-13 and 2018-08-14. If the count for max(Date) is greater then it should select that row and store it in a different dataframe. Same for item z, it should compare the counts for dates 2018-08-13 and 2018-08-14 and because the count is greater it should select the row for item z with count 12. Output: df2 Item Count Date x 10 2018-08-14 z 12 2018-08-14 I've tried the following: if ((df.Item == df.Item) and (df.Date &gt; df.Date) and (df.Count &gt; df.Count)): print("we met the conditions!")
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51845096
type: Question
answer count: 2

http://stackoverflow.com/q/51864417
favorite count: 0
has comment: http://stackoverflow.com/comment/90683604
tagged with: python
has comment: http://stackoverflow.com/comment/90682948
tagged with: merging-data
has body: currently I extracted data from sharepoint and have .iqy files that I can open with excel. There are about 30 files and I am trying to merge all the information into one .iqy file or excel file with python. import os, glob import pandas as pd files = [] for file in os.listdir("C:\\Users\\CHI86786\\Downloads"): files.append(file) excels = [pd.ExcelFile(name) for name in files] frames = [x.parse(x.sheet_names[0], header=None, index_col=None) for x in excels] frames[1:] = [df[1:] for df in frames[1:]] combined = pd.concat(frames) combined.to_excel("SPmerged.iqy", header=False, index=False) took a same approach as if I would merge excel files. but I keep getting an error that reads FileNotFoundError: [Errno 2] No such file or directory: 'desktop.ini' EDIT more of the error message File "C:\Users\CHI\source\repos\MergingExcel\MergingExcel\MergingExcel.py", line 8, in &lt;module&gt; excels = [pd.ExcelFile(name) for name in files] #reads names in File "C:\Users\CHI86786\source\repos\MergingExcel\MergingExcel\MergingExcel.py", line 8, in &lt;listcomp&gt; excels = [pd.ExcelFile(name) for name in files] #reads names in File "C:\Users\CHI\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pandas\io\excel.py", line 394, in __init__ self.book = xlrd.open_workbook(self._io) File "C:\Users\CHI\AppData\Local\Programs\Python\Python37-32\lib\site-packages\xlrd\__init__.py", line 116, in open_workbook with open(filename, "rb") as f: FileNotFoundError: [Errno 2] No such file or directory: 'desktop.ini'
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51865372
has comment: http://stackoverflow.com/comment/90682570
accepted answer: http://stackoverflow.com/a/51865372
tagged with: excel
type: Question
has title: Merging iqy files with python
has comment: http://stackoverflow.com/comment/90683072
upvote count: 2
has comment: http://stackoverflow.com/comment/90683669
tagged with: pandas
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/90682710

http://stackoverflow.com/comment/90657889
comment on: http://stackoverflow.com/q/51852574
type: QuestionComment
type: Comment
score: 1
has text: Also, your form action is pointing to `create_post:retrieve_projects` -- should it be pointing to `create_post:create_projects`?

http://stackoverflow.com/q/51833556
type: Question
has answer: http://stackoverflow.com/a/51845963
has body: I am new to Python. Facing below issue. I have below function: def send_request(api_service_name, api_url, parameters, method='GET', access_token='', user_data='', request_header=None, user_id_type=None, connection_timeout=CONNECTION_TIMEOUT, timeout=TOTAL_TIMEOUT, auth_string=AUTH_STRING_AUTHORIZATION, scope=SCOPE_DEFAULT): When calling the function like this: def associate_user(self): self.response = send_request(api_service_name=ASSOCIATION_MODULE, api_url=URL_ASSOCIATION, parameters='', method='POST', access_token='', user_data=self.payload_for_device_association(), request_header=HEADER_USER_BOTH, user_id_type="yes") getting below error: TypeError: send_request() got an unexpected keyword argument 'user_id_type'
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/90623500
answer count: 1
has title: send_request() got an unexpected keyword argument 'user_id_type'
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90621069

http://stackoverflow.com/a/69164235
has comment: http://stackoverflow.com/comment/131880287
type: Answer
answers question: http://stackoverflow.com/q/51921142
has comment: http://stackoverflow.com/comment/131874355
upvote count: 3
score: 3
has body: I found using gcsfs to be the fastest (and most compact) method to use: def load_joblib(bucket_name, file_name): fs = gcsfs.GCSFileSystem() with fs.open(f'{bucket_name}/{file_name}') as f: return joblib.load(f)
downvote count: 0

http://stackoverflow.com/q/51944390
favorite count: 0
has comment: http://stackoverflow.com/comment/90838367
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90869912
linked to: http://stackoverflow.com/q/51947920
tagged with: python
type: AnsweredQuestion
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/51944677
type: Question
has title: Psychopy unexpected keyword argument 'languageStyle'
has body: I saw that psychopy now has support for RTL language: http://www.psychopy.org/api/visual/textstim.html https://discourse.psychopy.org/t/reshaping-english-text-to-arabic/4235/16 I used this manual to install the latest version using conda: http://psychopy.org/installation.html My version is: 1.90.2 with Python 3.5 However, when init TextStim with languageStyle I get an error: from psychopy import visual text_stim = visual.TextStim(self.window, height = height, wrapWidth = wrapWidth, bold= True, text= sentence, pos = (0,0) , color='white', languageStyle='RTL') Any idea how can I use it?
accepted answer: http://stackoverflow.com/a/51944677
answer count: 1
downvote count: 0
tagged with: psychopy

http://stackoverflow.com/a/51947754
has comment: http://stackoverflow.com/comment/90845397
type: Answer
accepted answer of: http://stackoverflow.com/q/51946728
answers question: http://stackoverflow.com/q/51946728
score: 3
has body: Using the suggestion from @Daniel F, you can use cdist like this: cdist(XA, XB, lambda u, v: np.sqrt(np.nansum((u-v)**2))) For instance: import numpy as np from scipy.spatial.distance import cdist, squareform a = np.array([1, 3, np.nan]) b = np.array([2, np.nan, 4]) print(np.sqrt(np.nansum((a-b)**2))) Output: 1.0 The example above is just to demonstrate the effect of the lambda function.
upvote count: 3
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/51934087
has title: GPU out of memory when training convolutional neural network on Tensorflow
tagged with: conv-neural-network
upvote count: 1
has answer: http://stackoverflow.com/a/51934742
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/90818689
tagged with: deep-learning
has comment: http://stackoverflow.com/comment/90819265
tagged with: batching
answer count: 1
downvote count: 0
score: 1
favorite count: 0
has body: I'm using a convolutional neural network to train a set of ~9000 images (300x500) on a GTX1080 Ti using Tensorflow 1.9 but running into an issue of exceeding the memory every time. I get a warning about the system memory being exceeded by 10% and after a few minutes the process gets killed. My code is below. import tensorflow as tf from os import listdir train_path = '/media/NewVolume/colorizer/img/train/' col_train_path = '/media/NewVolume/colorizer/img/colored/train/' val_path = '/media/NewVolume/colorizer/img/val/' col_val_path = '/media/NewVolume/colorizer/img/colored/val/' def load_image(image_file): image = tf.read_file(image_file) image = tf.image.decode_jpeg(image) return image train_dataset = [] col_train_dataset = [] val_dataset = [] col_val_dataset = [] for i in listdir(train_path): train_dataset.append(load_image(train_path + i)) col_train_dataset.append(load_image(col_train_path + i)) for i in listdir(val_path): val_dataset.append(load_image(val_path + i)) col_val_dataset.append(load_image(col_val_path + i)) train_dataset = tf.stack(train_dataset) col_train_dataset = tf.stack(col_train_dataset) val_dataset = tf.stack(val_dataset) col_val_dataset = tf.stack(col_val_dataset) input1 = tf.placeholder(tf.float32, [None, 300, 500, 1]) color = tf.placeholder(tf.float32, [None, 300, 500, 3]) #MODEL conv1 = tf.layers.conv2d(inputs = input1, filters = 8, kernel_size=[5, 5], activation=tf.nn.relu, padding = 'same') pool1 = tf.layers.max_pooling2d(inputs = conv1, pool_size=[2, 2], strides=2) conv2 = tf.layers.conv2d(inputs = pool1, filters = 16, kernel_size=[5, 5], activation=tf.nn.relu, padding = 'same') pool2 = tf.layers.max_pooling2d(inputs = conv2, pool_size=[2, 2], strides=2) conv3 = tf.layers.conv2d(inputs = pool2, filters = 32, kernel_size=[5, 5], activation=tf.nn.relu, padding = 'same') pool3 = tf.layers.max_pooling2d(inputs = conv3, pool_size=[2, 2], strides=2) flat = tf.layers.flatten(inputs = pool3) dense = tf.layers.dense(flat, 2432, activation = tf.nn.…
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90818368

http://stackoverflow.com/comment/90828360
comment on: http://stackoverflow.com/a/51938429
has text: This is excellent! I will have a look at the source in a little more detail. Seems like we aren't *meant* to use it. But for a simple task like this I'm hoping there *aren't* any issues.
type: AnswerComment
type: Comment
score: 1

http://stackoverflow.com/q/51856051
has body: I am using the tkinter module in my python code to create my gui for an simple app I am creating. I was wondering if it is possible to keep the insertion cursor visible even when the the state on my entry widget is set to "readonly". I want the user to still see where the insertion cursor is in the text but not be able to edit the text directly using the keyboard. Note: When I say Insertion Cursor I don't mean the normal mouse cursor/pointer but the flashing bar which shows up on text which you can edit. I'm not sure what the proper name for it is... Below is an example of what I mean (the black bar in the Entry) I have tried setting the 'insertwidth' and other insertion cursor config options in the Entry widget to see if the cursor was perhapes just hidden but it did not work. Any help is appreciated. Thanks!
type: Question
has answer: http://stackoverflow.com/a/51856434
accepted answer: http://stackoverflow.com/a/51856434
score: 1
has title: Keeping the Insertion Cursor on a readonly Tkinter Entry
has answer: http://stackoverflow.com/a/51858835
answer count: 2
upvote count: 1
favorite count: 0
tagged with: python
tagged with: tkinter-entry
possible better answer: http://stackoverflow.com/a/51858835
type: AnsweredQuestion
tagged with: python-3.x
tagged with: tkinter
downvote count: 0

http://stackoverflow.com/q/51892824
score: 2
has comment: http://stackoverflow.com/comment/90737205
type: AnsweredQuestion
tagged with: if-statement
type: Question
has answer: http://stackoverflow.com/a/51893021
tagged with: nonetype
tagged with: missing-data
downvote count: 0
has body: If the value of age is missing I want to create a variable with the value of 1. Instead everything is None in the output of the Value column. raw_data1 = {'id': [1,2,3,5], 'age': [0, np.nan, 10, 2]} df1 = pd.DataFrame(raw_data1, columns = ['id','age']) def my_test(b): if b is None: return 1 df1['Value'] = df1.apply(lambda row: my_test(row['age']), axis=1) How can implement it? I know that there are several ways, but I would like to focus on the use of a function, (def my_test etc.).
has answer: http://stackoverflow.com/a/51892882
has title: None in if condition, how to handle missing data?
has answer: http://stackoverflow.com/a/51892899
tagged with: pandas
answer count: 4
favorite count: 0
possible better answer: http://stackoverflow.com/a/51892899
has answer: http://stackoverflow.com/a/51892903
upvote count: 2
accepted answer: http://stackoverflow.com/a/51892882
tagged with: python
has comment: http://stackoverflow.com/comment/90736543

http://stackoverflow.com/comment/90711858
score: 0
comment on: http://stackoverflow.com/q/51879956
type: Comment
type: QuestionComment
has text: It looks like that it gets extremely slow if I remove the initial ^ or if I use multiline.

http://stackoverflow.com/q/51876515
has title: Data ingestion using kafka from crawlers
tagged with: kafka-producer-api
has comment: http://stackoverflow.com/comment/90717997
tagged with: python
accepted answer: http://stackoverflow.com/a/51887428
upvote count: 2
downvote count: 1
type: Question
tagged with: apache-kafka
type: AnsweredQuestion
has body: I am trying to work with Kafka for data ingestion but being new to this, i am kind of pretty much confused.I have multiple crawlers, who extract data for me from web platform. Now, the issue is i want to ingest that extract data to Hadoop using Kafka without any middle scripts/service file . Is it possible ?
score: 1
tagged with: web-crawler
has answer: http://stackoverflow.com/a/51887428
answer count: 1
favorite count: 0

http://stackoverflow.com/a/51823242
has comment: http://stackoverflow.com/comment/90602428
answers question: http://stackoverflow.com/q/51822735
has comment: http://stackoverflow.com/comment/90602498
has comment: http://stackoverflow.com/comment/90602721
accepted answer of: http://stackoverflow.com/q/51822735
has comment: http://stackoverflow.com/comment/90602444
type: Answer
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/90602569
has comment: http://stackoverflow.com/comment/90602659
has comment: http://stackoverflow.com/comment/90602363
has comment: http://stackoverflow.com/comment/90602457
has body: First of all you need a client code to connect with your server. This is a TCP socket, therefore it is connection oriented. This means that prior to any data transference (socket.recv(), socket.send() ) you need to request a connection from the client to the server, and the server must accept the connection. After the connection is estabilished you will be able to freely send data between the sockets. this is an example of this simple socket design that can be applied genericaly to your program: Client Example import socket # create an ipv4 (AF_INET) socket object using the tcp protocol (SOCK_STREAM) client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # connect the client # client.connect((target, port)) client.connect(('0.0.0.0', 9999)) # send some data (in this case a String) client.send('test data') # receive the response data (4096 is recommended buffer size) response = client.recv(4096) print(response) Server Example import socket import threading bind_ip = '0.0.0.0' bind_port = 9999 max_connections = 5 #edit this to whatever number of connections you need server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind((bind_ip, bind_port)) server.listen(max_connections) # max backlog of connections print (('Listening on {}:{}').format(bind_ip, bind_port)) def handle_client_connection(client_socket): request = client_socket.recv(4096 ) print (str(request)) client_socket.send('ACK!') client_socket.close() while True: client_sock, address = server.accept() print (('Accepted connection from {}:{}').format(address[0], address[1])) client_handler = threading.Thread( target=handle_client_connection, args=(client_sock,) # without comma you'd get a... TypeError: handle_client_connection() argument after * must be a sequence, not _socketobject ) client_handler.start() This example should print test data in the server console and ACK! in the client console. edit: Not sure about python3 prints working as i wrote them here... but it's just a small detail. The…
has comment: http://stackoverflow.com/comment/90602427
has comment: http://stackoverflow.com/comment/90602551
upvote count: 1
has comment: http://stackoverflow.com/comment/90602544
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90602741

http://stackoverflow.com/a/51898024
answers question: http://stackoverflow.com/q/51897643
has body: You can change the node name by setting the tagName attribute Try this, tag_ccc = dom2.getElementsByTagName("CCC")[0] tag_ccc.tagName = "XXX" This should change the tag name to "XXX", below is the test code i used to confirm this using python 2.7 from xml.dom.minidom import parse, parseString xml =""" This is test """ dom = parseString(xml) tag_ccc = dom.getElementsByTagName("CCC")[0] tag_ccc.tagName = "XXX" print tag_ccc.toxml("utf-8") Hope this helped.
type: Answer
upvote count: 5
downvote count: 0
score: 5
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51897643

http://stackoverflow.com/a/51842935
answers question: http://stackoverflow.com/q/51842888
type: Answer
score: 2
upvote count: 3
has body: You can use globals here. Ex: url1 = "https://example1.com" url2 = "https://example2.com" url3 = "https://example3.com" all_urls = {} a= 'url' for i in range(1,4): all_urls[a+str(i)] = globals()[a+str(i)] print(all_urls) Output: {'url1': 'https://example1.com', 'url3': 'https://example3.com', 'url2': 'https://example2.com'}
downvote count: 1

http://stackoverflow.com/a/51809848
type: Answer
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/51809624
accepted answer of: http://stackoverflow.com/q/51809624
type: AcceptedAnswer
downvote count: 0
has body: You haven't specified how and where you installed tensorflow, so I could be wrong, but: (a) it appears that keras is installed with tensorflow, but not in a location that is in the default Python path (hence, you cannot do from keras.datasets import imdb). (b) this combination: import tensorflow as tf from tf.keras.datasets import imdb is invalid, because from x import y searches for x as a module and not as a symbol in your code's globals (and tf is NOT a module name but a global variable, import tensorflow as tf imports tensorflow and sets tf to point to the module object). Therefore (unless you fix your install or your PYTHONPATH to make keras visible as a module), you should use this to import keras (or specific symbols from it): # either this, to access keras.*, e.g., keras.datasets.imdb import tensorflow.keras as keras # or this, as you've done in your example from tensorflow.keras.datasets import imdb

http://stackoverflow.com/q/51929970
favorite count: 0
score: 0
answer count: 3
tagged with: pandas
downvote count: 1
tagged with: python
tagged with: nlp
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51930075
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51930427
has title: How to Split pandas data frame string entry to separate rows?
has body: I have a pandas dataframe in which one column of text strings contains new line separated values. I want to split each CSV field and create a new row per entry. My Data Frame is like: Col-1 Col-2 A Notifications Returning Value Both B mine Why Not? Expected output is: Col-1 Col-2 A Notifications A Returning Value A Both B mine B Why Not?
type: Question
has answer: http://stackoverflow.com/a/51930301
upvote count: 1
has comment: http://stackoverflow.com/comment/90809712
tagged with: string

http://stackoverflow.com/a/51800385
downvote count: 0
has body: is it important for you to use openpyxl to do this? i would suggest using pandas if not. import pandas as pd df = pd.read_excel("path_to_excel_file") df_abc = df[df["Products"] == "ABC"] # this will only contain 2,4,6 rows then: for row in df_abc.iterrows(): # do what you want with the row
upvote count: 11
accepted answer of: http://stackoverflow.com/q/51800122
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51800122
type: Answer
score: 11
has comment: http://stackoverflow.com/comment/90557424

http://stackoverflow.com/q/51917356
answer count: 1
has answer: http://stackoverflow.com/a/72954243
has body: After playing around with some auto correlations I recognized that the values shown on the plot by pandas auto correlation plotting module mentioned above differ from the values I receive when I calculate them manually with x.corr(x.shift(lag)) or with x.autocorr(lag). Does anybody know if pd.plotting.autocorrelation_plot(x) uses another calculation method for the auto correlation than the standard approach?
tagged with: pandas
downvote count: 0
favorite count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: python
score: 2
type: Question
has title: Why does pandas pd.plotting.autocorrelation_plot(x) result in different values than a usual autocorrelation calculation?

http://stackoverflow.com/a/51808342
accepted answer of: http://stackoverflow.com/q/51806675
score: 1
answers question: http://stackoverflow.com/q/51806675
has body: You should be able to do this via tf.cond, which executes one of two branches depending on some condition. I haven't tested the below code so please report whether it works. mean = tf.cond(tf.size(result), lambda: tf.reduce_mean(result), lambda: some_constant) The idea is to check whether result contains any items via tf.size (should return 0 if result is empty). You might need to convert it to a boolean condition explicitly, i.e. use tf.cast(tf.size(result), tf.bool) instead.
upvote count: 1
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/90587433

http://stackoverflow.com/q/51873200
downvote count: 0
has comment: http://stackoverflow.com/comment/90709583
linked to: http://stackoverflow.com/q/36690705
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/90731307
has comment: http://stackoverflow.com/comment/90698404
score: 2
has comment: http://stackoverflow.com/comment/90731289
has comment: http://stackoverflow.com/comment/90697866
has title: How to run a python script directly from RobotFramework
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90699654
has comment: http://stackoverflow.com/comment/90738636
has answer: http://stackoverflow.com/a/51881696
type: Question
tagged with: robotframework
has comment: http://stackoverflow.com/comment/90719606
has comment: http://stackoverflow.com/comment/90731278
has body: I have a python script which automates manual steps on SAP GUI client. The script works perfectly fine without any errors. How can i run this script directly from Robotframework. Details: Script path: 'fakepath\testscript.py' Script doesnt generates any output or doesnt returns any variable or object.
answer count: 1

http://stackoverflow.com/a/51852539
downvote count: 0
has comment: http://stackoverflow.com/comment/90657858
has comment: http://stackoverflow.com/comment/90658308
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51852514
has comment: http://stackoverflow.com/comment/90658353
type: Answer
accepted answer of: http://stackoverflow.com/q/51852514
has body: If names are unique, just concatenate A and B, and drop duplicates. Assuming A and B are your DataFrames, df = pd.concat([A, B]).drop_duplicates(subset=['Name'], keep='first') Or, A = A.set_index('Name') B = B.set_index('Name') idx = B.index.difference(A.index) df = pd.concat([A, B.loc[idx]]).reset_index() Both should be approximately the same in terms of performance.
score: 1
has comment: http://stackoverflow.com/comment/90657963

http://stackoverflow.com/q/51809743
has title: split() in python3 not returning value as expected(spliting the whole string character wise rather than space wise)
linked to: http://stackoverflow.com/q/12238517
answer count: 1
duplicate of: http://stackoverflow.com/q/12238517
favorite count: 0
tagged with: python-3.x
tagged with: python
downvote count: 1
has answer: http://stackoverflow.com/a/51809789
type: AnsweredQuestion
has body: size = int(input()) #a = [0 for x in range(size)] a = input() b=[] a.split() print (a[0]) for x in a: if is_number(x): b.append(int(x)) print (b) Input : 4 12 8 4 0 Output: 1 [1, 2, 8, 4, 0] expecting : 12 [12 , 8, 4, 0] What am I doing wrong here? NB: a.split(" ") also not working
has comment: http://stackoverflow.com/comment/90574482
type: Question
upvote count: 0
accepted answer: http://stackoverflow.com/a/51809789
score: -1

http://stackoverflow.com/q/51852126
type: UnansweredQuestion
tagged with: python
has body: I'm new to python , i tried to install jupyter by using this command sudo pip install jupyter but got Found existing installation: tornado 3.1.1 Cannot uninstall 'tornado'. It is a distutils installed project and thus we cannot accurately determine which files belong to it which would lead to only a partial uninstall. I got that there is more than one version of tornado but couldn't fix it Thanks for any help
has comment: http://stackoverflow.com/comment/90657036
type: Question
has comment: http://stackoverflow.com/comment/90657117
has comment: http://stackoverflow.com/comment/90656997
has answer: http://stackoverflow.com/a/51852664
score: 0
has comment: http://stackoverflow.com/comment/90657051
answer count: 1
has comment: http://stackoverflow.com/comment/90718475
tagged with: jupyter
tagged with: jupyter-notebook
has title: How can i solve the error with installing Jupyter?

http://stackoverflow.com/q/51885913
has answer: http://stackoverflow.com/a/51886015
type: AnsweredQuestion
tagged with: f-string
possible better answer: http://stackoverflow.com/a/51886015
has title: Using f-string with format depending on a condition
accepted answer: http://stackoverflow.com/a/51885978
type: Question
score: 79
answer count: 2
upvote count: 79
downvote count: 0
has comment: http://stackoverflow.com/comment/90723378
has comment: http://stackoverflow.com/comment/90723358
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51885978
has body: How can I use f-string with logic to format an int as a float? I would like if ppl is True to format num to 2 decimal places, and if ppl is False to rformat it as whatever it is. Something like string = f'i am {num:.2f if ppl else num}' but this does not work. The below code demonstrates the behaviour that I want to achieve with a simpler f-string if possible: ppl = True num = 3 string = f'I am {num:.2f}' if ppl else f'I am {num}' print(string) #if ppl False #=&gt; i am 3 #if ppl True #=&gt; i am 3.00
tagged with: python

http://stackoverflow.com/comment/90840315
comment on: http://stackoverflow.com/a/51945389
type: AnswerComment
has text: I think this is the most obvious solution, which probably most people will end up with. If you feel that the numbers loose visual connection to their data points with increasing offset, you could additionally use `annotate` instead of `text`. It provides an additional line or arrow between numbers and data points.
type: Comment
score: 1

http://stackoverflow.com/comment/90797390
score: 0
type: QuestionComment
type: Comment
has text: sure please see the updte
comment on: http://stackoverflow.com/q/51923891

http://stackoverflow.com/q/51853350
type: Question
has answer: http://stackoverflow.com/a/51853382
answer count: 2
has comment: http://stackoverflow.com/comment/90659184
has comment: http://stackoverflow.com/comment/90659263
has comment: http://stackoverflow.com/comment/90659240
downvote count: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/90659241
tagged with: python
has body: The size of my pandas dataframe is 6844 and is named all_data_frame. When I type print(str(all_ssis_data.tail)) I get rows in the index range of 0-29 and 3633-3662. Why doesn't it show me rows around the 6800 range?
favorite count: 0
has comment: http://stackoverflow.com/comment/90659249
has title: Pandas Dataframe Tail Not Working
has comment: http://stackoverflow.com/comment/90659244
has comment: http://stackoverflow.com/comment/90659224
has comment: http://stackoverflow.com/comment/90659259
upvote count: 1
possible better answer: http://stackoverflow.com/a/51853382
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90659218
score: 1
has answer: http://stackoverflow.com/a/51853417
accepted answer: http://stackoverflow.com/a/51853417

http://stackoverflow.com/q/51838583
tagged with: deep-learning
answer count: 1
downvote count: 0
tagged with: keras
has answer: http://stackoverflow.com/a/51839296
tagged with: python
tagged with: nlp
favorite count: 0
upvote count: 1
accepted answer: http://stackoverflow.com/a/51839296
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90631219
has body: I am kind of new to deep learning and I have been trying to create a simple sentiment analyzer using deep learning methods for natural language processing and using the Reuters dataset. Here is my code: import numpy as np from keras.datasets import reuters from keras.preprocessing.text import Tokenizer from keras.models import Sequential from keras.layers import Dense, Dropout, GRU from keras.utils import np_utils max_length=3000 vocab_size=100000 epochs=10 batch_size=32 validation_split=0.2 (x_train, y_train), (x_test, y_test) = reuters.load_data(path="reuters.npz", num_words=vocab_size, skip_top=5, maxlen=None, test_split=0.2, seed=113, start_char=1, oov_char=2, index_from=3) tokenizer = Tokenizer(num_words=max_length) x_train = tokenizer.sequences_to_matrix(x_train, mode='binary') x_test = tokenizer.sequences_to_matrix(x_test, mode='binary') y_train = np_utils.to_categorical(y_train, 50) y_test = np_utils.to_categorical(y_test, 50) model = Sequential() model.add(GRU(50, input_shape = (49,1), return_sequences = True)) model.add(Dropout(0.2)) model.add(Dense(256, input_shape=(max_length,), activation='relu')) model.add(Dropout(0.2)) model.add(Dense(50, activation='softmax')) model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['acc']) model.summary() history = model.fit(x_train, y_train, epochs=epochs, batch_size=batch_size, validation_split=validation_split) score = model.evaluate(x_test, y_test) print('Test Accuracy:', round(score[1]*100,2)) What I do not understand is why, every time I try to use a GRU or LSTM cell instead of a Dense one, I get this error: ValueError: Error when checking input: expected gru_1_input to have 3 dimensions, but got array with shape (8982, 3000) I have seen online that adding return_sequences = True could solve the issue, but as you can see, the issue remains in my case. What should I do in this case?
score: 1
has title: Keras GRU/LSTM layer input dimension error
tagged with: lstm

http://stackoverflow.com/a/51884450
has comment: http://stackoverflow.com/comment/90720892
has comment: http://stackoverflow.com/comment/90722457
has comment: http://stackoverflow.com/comment/90755952
has comment: http://stackoverflow.com/comment/90721280
score: 0
has comment: http://stackoverflow.com/comment/90721019
has comment: http://stackoverflow.com/comment/90720752
has comment: http://stackoverflow.com/comment/90723271
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51883275
accepted answer of: http://stackoverflow.com/q/51883275
has body: To get rid of a multiindex, use the .reset_index() method of your DataFrame object.
type: Answer
has comment: http://stackoverflow.com/comment/90754319
has comment: http://stackoverflow.com/comment/90721652
has comment: http://stackoverflow.com/comment/90720922

http://stackoverflow.com/q/51902156
has comment: http://stackoverflow.com/comment/90761139
score: 2
has body: I want to plot an execution chain using graphs and python. I have to mantain left and right in the plotting, this is possible with networkx and matplotlib ? Something like this: I tryed: import networkx as nx import matplotlib.pyplot as plt g = nx.DiGraph() g.add_nodes_from([1,2,3,4,5]) g.add_edge(1,3) g.add_edge(2,3) g.add_edge(3,5) g.add_edge(3,4) nx.draw(g,with_labels=True) plt.draw() plt.show() but I don't know how to declare de order. I got:
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/90755430
has comment: http://stackoverflow.com/comment/90763283
type: Question
tagged with: networkx
tagged with: graph
has answer: http://stackoverflow.com/a/51905957
has comment: http://stackoverflow.com/comment/90755556
linked to: http://stackoverflow.com/q/42272710
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/90755813
has comment: http://stackoverflow.com/comment/90755700
favorite count: 0
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90755836
has title: Plot network chain in python
tagged with: python
has comment: http://stackoverflow.com/comment/90755460

http://stackoverflow.com/comment/90674053
comment on: http://stackoverflow.com/a/51860720
has text: In your solution, how would you suggest which groups I should make? As in, how do you keep track of which students are being clubbed into which groups? Under the assumption that one student can do into only one group, how do you make the groups?
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/51934199
tagged with: python
has title: How to authenticate app to act as if it was my logged in google account
has answer: http://stackoverflow.com/a/51934698
has body: I have written scripts connecting to the google API to connect to bigquery and google sheets and slides. However, currently I am trying to write a script that would be able to access a non-google site for which I am required to be signed in with my gmail account to access. So essentially when I access this site in a browser, I am asked to login using gmail and allow the site to verify my details, and in return I can view the page. If I don't login with google I cannot view the page. I am not sure how/if the google authentication process for my app could be set up in a way for it to login as if it was myself. But can anybody give me some advice on how I can get my app to pass the google sign-in process, so that my app can access the contents of the website? Please let me know if I can clarify. Thanks!
tagged with: google-api
score: 0
type: Question
tagged with: google-signin
has comment: http://stackoverflow.com/comment/90819230
answer count: 1
tagged with: google-authentication
type: UnansweredQuestion

http://stackoverflow.com/q/51824306
score: 0
linked to: http://stackoverflow.com/q/43442194
answer count: 1
has title: How to pack arrays iwht msgpack on python?
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51824716
has body: I have a dict of arrays like these: gen = {0: [array([0])], 1: [array([1]), array([-1])]} and I would like to save them with msgpack: import msgpack with open('data.msgpack', 'wb') as file: msgpack.pack(gen, file) But it returns the error: TypeError: can't serialize array([0]) What is the problem?
tagged with: save
type: Question
tagged with: arrays

http://stackoverflow.com/a/51941902
score: 4
upvote count: 4
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51894150
answers question: http://stackoverflow.com/q/51894150
has body: Python chi square goodness of fit test (https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.chisquare.html) mentions that "“Delta degrees of freedom”: adjustment to the degrees of freedom for the p-value. The p-value is computed using a chi-squared distribution with k - 1 - ddof degrees of freedom, where k is the number of observed frequencies. The default value of ddof is 0." Hence your code should be corrected as follows. c , p = st.chisquare(observed_values, expected_values, ddof=len(param))
type: Answer

http://stackoverflow.com/a/51895955
downvote count: 0
type: Answer
has body: Change your list comprehension to : output = ['found' if (word and 'some_string' in word) else word for word in wordlist] The key point here is if word. The issue is there are some None elements in your dataframe and that is affecting the iteration. I do not think this has anything to do with unicode elements
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51895280

http://stackoverflow.com/comment/90790425
score: 0
type: AnswerComment
type: Comment
has text: True, but this will require pip to `git clone` the thousands of commits, and takes much longer. You can try it yourself to check
comment on: http://stackoverflow.com/a/51919000

http://stackoverflow.com/comment/90665640
type: Comment
type: QuestionComment
has text: Also there are syntax errors in true and false
comment on: http://stackoverflow.com/q/51856195
score: 0

http://stackoverflow.com/comment/90591758
type: QuestionComment
comment on: http://stackoverflow.com/q/51816005
score: 1
has text: @TaeChoi, It is good that you are exploring like this. It will make it easier to compare and contrast the more Pythonic solution when come across them. I hope you have fun with Python! As I have :-) .
type: Comment

http://stackoverflow.com/q/51859857
tagged with: string
score: 0
tagged with: pandas
tagged with: python
has body: I have a dataframe of publications that have the following rows: publication_ID , title, author_name, date 12344, Design style, Jake Kreath, 20071208 12334, Power of Why, Samantha Finn, 20150704 I ask the user for a string and use that string to search through the titles. The goal: Search through the dataframe to see if the title contains the word the user provides and return the rows in a new dataframe with just the title and publication_ID. This is my code so far: import pandas as pd from pandas import DataFrame publications = pd.read_csv(filepath, sep= "|") search_term = input('Enter the term you are looking for: ') def stringDataFrame(publications, title, regex): newdf = pd.DataFrame() for idx, search_term in publications['title'].iteritems(): if re.search(regex, search_term): newdf = concat([publications[publications['title'] == search_term], newdf], ignore_index=True) return newdf print(newdf.stringDataFrame)
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/51860492
has answer: http://stackoverflow.com/a/51860492
has title: Search through a dataframe for a partial string match and put the rows into a new dataframe with only their IDs
has comment: http://stackoverflow.com/comment/90672646
has comment: http://stackoverflow.com/comment/90672826
accepted answer: http://stackoverflow.com/a/51860232
type: AnsweredQuestion
tagged with: dataframe
has answer: http://stackoverflow.com/a/51860232
type: Question
answer count: 2

http://stackoverflow.com/comment/90777129
comment on: http://stackoverflow.com/q/51913511
type: QuestionComment
score: 0
has text: I haven't done any tkinter programming, so maybe this is the way you're supposed to do it, but the line `add = Button(win, text="Add", command=add)` seems odd to me -- you're creating a new object named `add` which destroys the existing `add()` function.
type: Comment

http://stackoverflow.com/q/51910888
tagged with: dataframe
tagged with: web-crawler
type: Question
tagged with: for-loop
has body: I am interested in learning python but I learned python program for 2 weeks. I coded this program for 2 days but I can't find how I should do. This is the code that I did as follows. =========================================================================== import requests from bs4 import BeautifulSoup import pandas as pd df = pd.read_csv("C:/Users/Administrator/PycharmProjects/naver_datalab.csv",sep=",", encoding ='CP949') df1 = df['키워드'] for i in df1: r=requests.get("https://search.shopping.naver.com/search/all.nhn?query=" + str(i) + "&amp;cat_id=&amp;frm=NVSHATC") c=r.content soup=BeautifulSoup(c,"html.parser") all=soup.find("li",{"class":"snb_all on"}).text all2=all.replace("전체","").replace("\s", "").replace(" ", "").replace("\n", "") df['ProductN'] = all2 print(df) ============================================ First, I read csv file with Pandas and dataframe is as follows. df = pd.read_csv("C:/Users/Administrator/PycharmProjects/naver_datalab.csv",sep=",", encoding ='CP949') 키워드 0 모기퇴치기 1 벌레퇴치기 2 해충퇴치기 3 전기모기퇴치기 ================================================================================ The expecting result page is as follows. print(df) -> enter key 키워드 ProductN 0 모기퇴치기 132,877 1 벌레퇴치기 127,250 2 해충퇴치기 136,109 3 전기모기퇴치기 125,307 =============================================================================== However, actual result page of print(df) is as follows. C:\Users\Administrator\PycharmProjects\untitled\venv\Scripts\python.exe C:/Users/Administrator/PycharmProjects/untitled/test1.py 키워드 ProductN 0 모기퇴치기 132,877 1 벌레퇴치기 132,877 2 해충퇴치기 132,877 3 전기모기퇴치기 132,877 키워드 ProductN 0 모기퇴치기 127,250 1 벌레퇴치기 127,250 2 해충퇴치기 127,250 3 전기모기퇴치기 127,250 키워드 ProductN 0 모기퇴치기 136,109 1 벌레퇴치기 136,109 2 해충퇴치기 136,109 3 전기모기퇴치기 136,109 키워드 ProductN 0 모기퇴치기 125,307 1 벌레퇴치기 125,307 2 해충퇴치기 125,307 3 전기모기퇴치기 125,307 Process finished with exit code 0 ================================================================================ I don't know how I can fix this result. I just …
answer count: 1
accepted answer: http://stackoverflow.com/a/51912810
score: 0
tagged with: pandas
tagged with: python
has answer: http://stackoverflow.com/a/51912810
has title: Python for loop implementation when I make dataframe with Pandas module
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90774446

http://stackoverflow.com/comment/90781129
comment on: http://stackoverflow.com/q/51907791
has text: Thanks for help. WebDriverWait worked well. Also, pinterest has 2 different xpath for the same stuff, so changing it also did it. Everything is scraped now. Will post the code here.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51880157
type: Answer
has body: Prepend a / in your relative_url from urllib.parse import urljoin absolute_url = 'https://ciechgroup.com/en/relacje-inwestorskie/reports/current-reports' relative_url = '/en/relacje-inwestorskie/reports/current-reports/2018/242018/' &gt;&gt;&gt; urljoin(absolute_url, relative_url) 'https://ciechgroup.com/en/relacje-inwestorskie/reports/current-reports/2018/242018/'
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/51879954
downvote count: 0

http://stackoverflow.com/a/51861684
upvote count: 3
has body: While you can create a temporary debug template to make it easier to get back to the point you're at, it is not possible to save the entire state of a running debug session and modify code downstream. My only suggestion would be to run a new instance of your script and keep the debug open for the current session as it is.
accepted answer of: http://stackoverflow.com/q/51859529
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 3
answers question: http://stackoverflow.com/q/51859529
has comment: http://stackoverflow.com/comment/90695845

http://stackoverflow.com/comment/90838583
score: 1
comment on: http://stackoverflow.com/a/51944397
type: AnswerComment
type: Comment
has text: Python (CPython) `threading` (and the underlying `_thread`) use real, proper system threads so they may actually end up executing on different CPUs if that's what the underlying OSs' thread scheduler decides. What they cannot do, due to GIL, is execute in parallel. Concurrent execution is just fine. See [this question](https://stackoverflow.com/questions/1050222/what-is-the-difference-between-concurrency-and-parallelism) for the difference between concurrency and parallelism.

http://stackoverflow.com/q/51823419
score: 1
has answer: http://stackoverflow.com/a/51826345
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/91957532
has title: Writing Pandas data to CSV or SQL results in trailing 0 being dropped
has comment: http://stackoverflow.com/comment/90601910
answer count: 2
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
tagged with: sqlite
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/91957010
has answer: http://stackoverflow.com/a/52508979
has body: I have some data in a pandas data frame which is stored as follows: 0 NASDAQ AAPL 1.63 3.51 2.20 1 NASDAQ AAPL 2.40 3.59 1.74 When I export it either to a CSV file or an SQLite database, any number where the second decimal place is a zero is truncated to one decimal place (e.g. 2.40 becomes 2.4). The code I'm using for the export is: """ Export data to CSV file """ # Output final data as CSV df.to_csv('stock_data-US.csv', sep=',', float_format='%.2f', encoding='utf-8', index=True) # Connect to the database file conn = sqlite3.connect(sqlite_file) c = conn.cursor() """ Export dataframe to sqlite table """ # Export pandas array to sqlite table df.to_sql("stock_data_US", conn, if_exists='replace', index=False) # Commit changes conn.commit() # Close database connection conn.close() As you can see I've specified the float format, however this seems to be being ignored (as decimal places are being rounded up). Ideally, I'd like all numbers exported to remain consistent at 2 decimal places. Thanks in advance for any support!
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/51897471
has comment: http://stackoverflow.com/comment/90746260
score: 0
has body: For the following Matplotlib graph, I would like to: Show the correct labels for all minor ticks Be able to rename the major and minor ticks to the values I need This is my code: import pandas as pd import numpy as np ONE_YEAR_IN_DAYS = 365 ONE_DAY_IN_TIMESTAMP_UNITS = 86400000000000 import pandas as pd start = pd.Timestamp('2016-07-01') end = pd.Timestamp('2017-07-01') t = np.linspace(start.value, end.value, 100 * ONE_YEAR_IN_DAYS) sinus = np.sin(2 * np.pi * 1 * t / ONE_DAY_IN_TIMESTAMP_UNITS) t = end.value - t import matplotlib matplotlib.use('TkAgg') font = {'family': 'normal', 'size': 8} matplotlib.rc('font', **font) import matplotlib.pyplot as plt axes = plt.gca() import matplotlib.ticker as ticker plt.rcParams["figure.dpi"] = 400 plt.xticks(rotation=90) plt.minorticks_on() plt.grid() from matplotlib.ticker import FormatStrFormatter from matplotlib.ticker import LogFormatter plt.minorticks_on() formatter = LogFormatter(labelOnlyBase=True, ) plt.setp(axes.xaxis.get_minorticklabels(), rotation=90) locmaj = matplotlib.ticker.LogLocator(base=5.0,numticks=12) axes.xaxis.set_major_locator(locmaj) locmin = matplotlib.ticker.LogLocator(base=5.0,subs=(0.2,0.4,0.6,0.8),numticks=12) axes.xaxis.set_minor_locator(locmin) axes.xaxis.set_minor_formatter(matplotlib.ticker.NullFormatter()) plt.semilogx(t, sinus, "-o", markersize=2) plt.show() I use Matplotlib 2.0.2. As you can see, I struggle somehow with the correct minor label generation. This is the present result I get:
has comment: http://stackoverflow.com/comment/90746018
has comment: http://stackoverflow.com/comment/90758574
has comment: http://stackoverflow.com/comment/90770527
has comment: http://stackoverflow.com/comment/90757632
linked to: http://stackoverflow.com/q/51910194
type: UnansweredQuestion
tagged with: python
has title: Get tick labels for matplotlib in semilogx plot that I can overwrite
answer count: 0
tagged with: matplotlib
type: Question

http://stackoverflow.com/a/51820711
answers question: http://stackoverflow.com/q/51812617
type: Answer
has body: The problem you're running into is that while from .portal_urls import * just imports everything from portal_urls.py found from the current file's directory, this type of import import appfolder.urls.portal_urls will load both appfolder/__init__.py and appfolder/urls/__init__.py before loading appfolder/urls/portal_urls.py ([*] see example at the bottom). This is why, in your appfolder/__init__.py the compiler gets past this import ... from .portal_urls import * before choking on this one: urlpatterns = [ ... path('portal/', include('appfolder.urls.portal_urls')), If you structure your app the normal way you avoid this problem, i.e. appfolder │ __init__.py │ urls.py │ ├───books │ __init__.py │ urls.py │ ├───movies │ __init__.py │ urls.py │ └───portal __init__.py urls.py where all the __init__.py files are empty and appfolder/urls.py contains urlpatterns = [ ... path(r'^portal/', include('appfolder.portal.urls')), path(r'^movies/', include('appfolder.movies.urls')), path(r'^books/', include('appfolder.books.urls')), this structure also makes it easier to pull one of these folders out into its own module if it grows. [*] if you place print(__file__) in each of the __init__.py files you can check what gets imported: (dev) go|c:\srv\tmp&gt; python -c "import appfolder.books.urls" appfolder\__init__.py appfolder\books\__init__.py
score: 3
upvote count: 3
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51812617
downvote count: 0

http://stackoverflow.com/a/51912336
upvote count: 1
has comment: http://stackoverflow.com/comment/90775103
score: 1
has comment: http://stackoverflow.com/comment/90774964
has body: You would be writing that in a command prompt. For instance, if you are on Windows, pressing the Windows button and typing "Command Prompt" will get you started. If you installed a recent version of Anaconda, you may have to use the "Anaconda Prompt" instead. Note that this will only work if pip is located in a place pointed to by your PATH environment variable, so if the above fails, you may have to modify the variable.
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51912305
has comment: http://stackoverflow.com/comment/90775231
answers question: http://stackoverflow.com/q/51912305
type: Answer

http://stackoverflow.com/comment/90589372
has text: Also, see https://stackoverflow.com/questions/19976018/does-a-dot-have-to-be-escaped-in-a-character-class-square-brackets-of-a-regula
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51817609

http://stackoverflow.com/comment/90850774
comment on: http://stackoverflow.com/q/51950340
score: 2
has text: The problem is pretty clearly that Python's ssl module is not installed… How did you install Python exactly?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90660325
type: Comment
type: QuestionComment
has text: sure just a moment
comment on: http://stackoverflow.com/q/51853429
score: 0

http://stackoverflow.com/q/51907488
answer count: 1
accepted answer: http://stackoverflow.com/a/51907525
has body: I have a Python project with subdirectories and I'm unable to import a module located in the root directory, here logger.py, from another module in a subdirectory, here composite.py. The problem is that logger.py point to a log file in the log directory with a relative path name to it, so composite.py can't find this file from it's sub directory. How can I import module logger from composite.py and from another module in the root directory, like module.py ? ├── data/ module.py logger.py ├── composite/ │ ├── composite.py ├── log/ │ ├── info.log This work : data/logger.py: h_info = RotatingFileHandler('log/info.log', [...]) data/module.py: import logger This doesn't work: data/composite/composite.py: from data import logger FileNotFoundError: [Errno 2] No such file or directory: '/home/abc/project/python/xyz/data/composite/log/info.log'
has comment: http://stackoverflow.com/comment/90765512
has comment: http://stackoverflow.com/comment/90765380
has comment: http://stackoverflow.com/comment/90765308
tagged with: python
has answer: http://stackoverflow.com/a/51907525
has title: How to import a Python module with relative path to a file from another directory?
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/51819441
linked to: http://stackoverflow.com/q/11274040
linked to: http://stackoverflow.com/q/456481
type: Question
has comment: http://stackoverflow.com/comment/90765348
score: 0
has comment: http://stackoverflow.com/comment/90765427

http://stackoverflow.com/a/51830665
score: -1
upvote count: 0
answers question: http://stackoverflow.com/q/51830481
type: Answer
has body: Based on my understanding, you are trying to import modules that are in some other project location. Try this and replace path with the location from where you want to import modules. sys.path.insert(0, path) Please let me know if I misunderstood your question.
downvote count: 1

http://stackoverflow.com/q/51913365
type: Question
upvote count: 1
answer count: 1
accepted answer: http://stackoverflow.com/a/51913569
has body: I want to scrap the heading of this page i.e Yiwu City Jeweler Co. Ltd. from this link: https://www.alibaba.com/energy-jewelrys-suppliers.html The html code snippet is : Yiwu City MJ Jewelry Co., Ltd. i had this code: response.xpath('//*[@class="title ellipsis"]/a/text()').extract() but the output is: ['Yiwu City Mj ', ' Jewelery', 'Co. Ltd.'] The problem is it should have been single item in a list not multiple items. How do i do that? Thanks
favorite count: 0
has title: Scraping title from alibaba using scrapy
has answer: http://stackoverflow.com/a/51913569
tagged with: xpath
downvote count: 0
tagged with: web-scraping
tagged with: python
type: AnsweredQuestion
score: 1
tagged with: scrapy

http://stackoverflow.com/a/51859939
has comment: http://stackoverflow.com/comment/90674132
has body: An index (base=100) is the relative change of a series in retation to its first element. So there's no need to take a detour to relative changes and recalculate the index from them when you can get it directly by df = pd.Series(array1)/array1[0]*100
score: 1
accepted answer of: http://stackoverflow.com/q/51856261
answers question: http://stackoverflow.com/q/51856261
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 1

http://stackoverflow.com/comment/90652908
type: QuestionComment
has text: @donkopotamus Yep
comment on: http://stackoverflow.com/q/51849395
score: 0
type: Comment

http://stackoverflow.com/q/51883058
has comment: http://stackoverflow.com/comment/90737147
has comment: http://stackoverflow.com/comment/90718085
has answer: http://stackoverflow.com/a/79415203
answer count: 3
tagged with: least-squares
downvote count: 0
has answer: http://stackoverflow.com/a/54203457
favorite count: 0
has comment: http://stackoverflow.com/comment/90737843
has comment: http://stackoverflow.com/comment/90736055
linked to: http://stackoverflow.com/q/8930370
has comment: http://stackoverflow.com/comment/90736022
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51896790
has comment: http://stackoverflow.com/comment/90717974
tagged with: python
upvote count: 13
tagged with: regression
tagged with: machine-learning
score: 13
has body: I was wondering if there's a function in Python that would do the same job as scipy.linalg.lstsq but uses “least absolute deviations” regression instead of “least squares” regression (OLS). I want to use the L1 norm, instead of the L2 norm. In fact, I have 3d points, which I want the best-fit plane of them. The common approach is by the least square method like this Github link. But It's known that this doesn't give the best fit always, especially when we have interlopers in our set of data. And it's better to calculate the least absolute deviation. The difference between the two methods is explained more here. It'll not be solved by functions such as MAD since it's an Ax = b matrix equations and requires loops to minimizes the results. I want to know if anyone knows of a relevant function in Python - probably in a linear algebra package - that would calculate “least absolute deviations” regression?
type: Question
has comment: http://stackoverflow.com/comment/90718161
has comment: http://stackoverflow.com/comment/90718281
has title: L1 norm instead of L2 norm for cost function in regression model
has comment: http://stackoverflow.com/comment/90718275

http://stackoverflow.com/comment/90686865
type: AnswerComment
has text: Ah, so the problem was that you had CSRF checks in your app (maybe from [Flask-WTF](https://flask-wtf.readthedocs.io/en/stable/csrf.html)?) and you weren't even getting to your handler. Thanks for bringing the answer back.
comment on: http://stackoverflow.com/a/51856278
type: Comment
score: 0

http://stackoverflow.com/comment/90562003
comment on: http://stackoverflow.com/a/51802535
type: Comment
score: 0
type: AnswerComment
has text: you need to disable the user from inputting in "lst-ib"(id) text input area?and if so u need to prevent them after "this is some text" has been inputted or before that

strftime
type: Tag
tags question: http://stackoverflow.com/q/51918629
tag name: strftime
tags question: http://stackoverflow.com/q/51858833
tags question: http://stackoverflow.com/q/51870510

http://stackoverflow.com/comment/90701400
has text: @JonClements Both of those just list installed packages, don't they?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51874974
type: Comment

http://stackoverflow.com/q/51866690
favorite count: 0
has answer: http://stackoverflow.com/a/51866871
accepted answer: http://stackoverflow.com/a/51866871
downvote count: 0
type: AnsweredQuestion
score: 1
tagged with: matplotlib
has body: In matplotlib I tried to position the axes of a figure such that the axes rectangle has its lower left corner at (100, 100) and its upper right corner at (400, 400), assuming the unit of the given coordinates is point (pt). import matplotlib.pyplot as plt plt.rcParams['ps.papersize'] = 'a4' fig = plt.figure(figsize=(8.27, 11.69)) ax = fig.add_subplot(1,1,1) ax.plot([1,3,2]) mybbox = ax.get_position() mybbox.x0, mybbox.y0 = fig.transFigure.inverted().transform((100, 100)) mybbox.x1, mybbox.y1 = fig.transFigure.inverted().transform((400, 400)) ax.set_position(mybbox) print(fig.transFigure.transform(ax.get_position())) plt.savefig('foo.ps') But the created postscript file yields that the axes' corners are actually at (72,72) and (288,288): 72 72 m 288 72 l 288 288 l 72 288 l cl Thus all coordinates are off target by a constant factor of 0.72. Did I do something wrong by applying the transFigure transformation to calculate the absolute position of the axes?
type: Question
answer count: 1
upvote count: 1
has title: Absolute positioning of axes
tagged with: python

http://stackoverflow.com/comment/90828231
comment on: http://stackoverflow.com/q/51939023
type: QuestionComment
type: Comment
has text: @coldspeed thanks, i tried using IOError as msg, still getting an error..
score: 0

http://stackoverflow.com/q/51914445
tagged with: python
has comment: http://stackoverflow.com/comment/90787078
accepted answer: http://stackoverflow.com/a/51915367
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90779037
has title: Calculating monthly aggregate of expenses with pandas
score: 1
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/90787397
downvote count: 0
has body: I've got a file with a list of expenses: Sample: date item out in 12/01/2017 PAGO FIBERTEL 668.5 0.0 12/01/2017 PAGO GAS NATURAL 2.32 0.0 10/02/2017 EXTRACCION TARJETA 1200.0 0.0 10/02/2017 CPA. STARBUCKS R. PE9A 105.0 0.0 10/02/2017 CPA. STARBUCKS R. PE9A 125.0 0.0 11/03/2017 EXTRACCION TARJETA 1200.0 0.0 11/03/2017 SALES 0.0 10000.0 I want to produce a plot where I can see how some items evolved during a year, each month. For example, i would filter the "item" column using "startbucks" as keyword, i would calculate monthly aggregates and would present that info like this: Dec Jan Mar Starbucks 0 0 230 There's a list of keywords that i take from json file, and that i would use to produce each row. However, I'm not able to do it with only one. I've tried several forms of groupby (with grouper and without), but I think I'm not getting it. This is the code I've got at the moment: import pandas as pd import matplotlib.pyplot as plt import sys import json class Banca(): def __init__(self, name, csv_path, json_path): self.name= name self.df = pd.read_csv(csv_path) with open(json_path) as j: self.json = json.load(j) def prepare(self): #Add header headers = ['fecha','concepto','in','out',"x"] self.df.columns = headers #fix data self.df.fecha = pd.to_datetime(self.df.fecha) #Here i'm testing, this doesnt work g1=self.df.groupby(pd.Grouper(key='fecha', freq='M')['in'].sum()) print(g1.describe().to_string()) print(g1.head()) #g1.plot(y='out', style='.-', figsize=(15,4)) #plt.show() #filter data # some filter def grafica(self): #plot data self.df.plot(x='fecha', y='out',style='.-', figsize=(15,4)) plt.show() def test_df(self): print(self.df.describe(include='all')) def test_json(self): for x,y in self.json.items(): print(x,y) icbc = Banca("ICBC", sys.argv[1], sys.argv[2]) icbc.test_df() icbc.prepare() #icbc.grafica() #icbc.test_json() I'm writing this code as an exercise to learn data manipulation with pandas. I've learn quite a few articules but I've been stuck here for a whi…
has answer: http://stackoverflow.com/a/51915367
tagged with: pandas
has comment: http://stackoverflow.com/comment/90779233
answer count: 1
favorite count: 0

http://stackoverflow.com/q/51845914
tagged with: list
tagged with: set
has title: Run into a python error <generator object <genexpr>
has comment: http://stackoverflow.com/comment/90645149
type: Question
has body: When I run a = ["I","love","you"] a = {(word) for word in a} print a I get this result set(['I', 'you', 'love']) and that's what I expect. But when I run a = ["I","love","you"] a = {((word) for word in c)for c in a} print a I get some unexpected result: set([&lt;generator object &lt;genexpr&gt; at 0x1004d5280&gt;, &lt;generator object &lt;genexpr&gt; at 0x1004d5320&gt;, &lt;generator object &lt;genexpr&gt; at 0x1004d5370&gt;]) And what I expect is set(['e','I','u','o','v','l','y') Can anybody tell my the reason that causes this problem?
downvote count: 0
favorite count: 0
answer count: 1
tagged with: nested
has answer: http://stackoverflow.com/a/51845989
upvote count: 2
accepted answer: http://stackoverflow.com/a/51845989
tagged with: python
score: 2
type: AnsweredQuestion

http://stackoverflow.com/q/51857925
score: 7
linked to: http://stackoverflow.com/q/53729364
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/90671612
favorite count: 0
tagged with: gmail-api
tagged with: email
tagged with: python
has answer: http://stackoverflow.com/a/51908580
has body: I am working on getting large text corpus of the email. There is no API that allows reading a message in Google Group. So the alternative way is to use a Gmail account which is a member of that group. By using this Gmail I can check all the message that is sent to that group. I am using python and Gmail API to fetch the mail. The problem I face is, I couldn't fetch the emails which are from the groups. results = service.users().messages().list(userId='me',q="from:support-dev-group@wso2.com", maxResults=10).execute() When I replace the from: with another normal user id it's working. When I replace the from: with group email id it's giving zero results. Could I get the actual code to fetch the group gmails through my Gmail? the second problem is, when i query using someones's mail : results = service.users().messages().list(userId='me',q="from:xyz@wso2.com", maxResults=10).execute() I get the results like that {'resultSizeEstimate': 82, 'messages': [{'id': '1653929b0b414390', 'threadId': '1644c19f390faf28'}, {'id': '165330aaa5bb9134', 'threadId': '16532ef13e7eec8d'}...... Here it's only returning the message id. In order to get the mail with a body with headers, I have to query again for every id. Can't I get the full JSON in one query?
tagged with: gmail
has title: Get Google Group emails with Gmail API
tagged with: google-groups
type: UnansweredQuestion
upvote count: 7
type: Question

http://stackoverflow.com/q/51821595
type: UnansweredQuestion
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/90599461
has comment: http://stackoverflow.com/comment/90597563
answer count: 0
type: Question
has comment: http://stackoverflow.com/comment/90597700
has comment: http://stackoverflow.com/comment/90597273
score: 0
has title: Filter by string in django
has comment: http://stackoverflow.com/comment/90597057
has comment: http://stackoverflow.com/comment/90597194
has body: I have 2 models: UserProfile and User_Details and I want to display the details for one user.I think the problem is at the filter and I don't know how to filter after a string,I'm new to django.How can I fix this? class ShowProfile(APIView): renderer_classes = [TemplateHTMLRenderer] template_name = 'profile.html' def get(self, request, pk, format=None): details=User_Details.objects.all().filter(user=request.user.username) serializer = ProfileSerializer2(details, many=True) pprint.pprint(json.loads(JSONRenderer().render(serializer.data))) return Response({'fields ': serializer}) def post(self, request): serializer = CreatePostSerializer(data=request.data) if not serializer.is_valid(): return Response({'fields': serializer }) user = UserProfile.objects.filter(username=request.user.username).first() serializer.save(user=user) pprint.pprint(json.loads(JSONRenderer().render(serializer.data))) return redirect('mainPage') Models: class UserProfile(AbstractUser): pass class User_Details(models.Model): user = models.OneToOneField(UserProfile, on_delete=models.CASCADE) first_name = models.CharField(max_length=50, blank = True) last_name = models.CharField(max_length=50, blank=True) gender = models.CharField(max_length=6, blank=True, default='') public_info=models.CharField(max_length=100, blank=True, default='') Template: {% extends 'base2.html' %} {% load rest_framework %} {% block content %} Profile My Posts {% for d in fields %} {{d.firs_name }} a {% endfor %} {% endblock %}
has comment: http://stackoverflow.com/comment/90597089
has comment: http://stackoverflow.com/comment/90598973
tagged with: django-rest-framework

http://stackoverflow.com/q/51859901
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90677227
has comment: http://stackoverflow.com/comment/90692295
downvote count: 1
score: -1
has title: AttributeError: 'GridSearchCV' object has no attribute 'cv_results_' on scikit-learn 0.19.2
has answer: http://stackoverflow.com/a/51860528
type: Question
has body: I'm currently using Scikit-Learn version 0.19.2 and Python 3.6.3 For some reason, I can't access the cv_results_ attribute from my GridSearchCV. This is the code I'm using: df = pd.read_csv(input_file, sep = ";", header=None) numpy_array = df.as_matrix() y=numpy_array[:,1] y[y=='RR']=1 y[y=='AIRR']=0 print(y) y=y.astype('int') vectorizer = TfidfVectorizer(sublinear_tf=True, max_df=0.5, stop_words=stopwords) X=numpy_array[:,0] X=vectorizer.fit_transform(X) param_grid = {"base_estimator__criterion" : ["gini", "entropy"], "base_estimator__splitter" : ["best", "random"], "n_estimators": [1, 2] } DTC = DecisionTreeClassifier(random_state = 11, max_features = "auto", class_weight = "balanced",max_depth = None) # Create and fit an AdaBoosted decision tree bdt = AdaBoostClassifier(base_estimator = DTC) grid_search_ABC = GridSearchCV(bdt, param_grid=param_grid, scoring = 'roc_auc', cv=5, refit=True) pred = grid_search_ABC.fit(X,y) print(metrics.confusion_matrix(y, pred)) mean=grid_search_ABC.cv_results_['mean_test_score'] std=grid_search_ABC.cv_results_['std_test_score'] I read that this has mostly to do with GridSearchCV not being fitted probably, but I can totally use it to predict new instances and etc. Any pointers, please?
upvote count: 0
answer count: 1
tagged with: scikit-learn
tagged with: pandas
tagged with: python
favorite count: 0

http://stackoverflow.com/a/51913423
upvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/126135680
has body: tl;dr: You probably want to do this: subprocess.call(["/usr/bin/open", "-W", "-n", "-a", "/Applications/Facetime.app", "tel://{}".format(number)]) Or, if you want it to make an audio-only call, add &amp;audio=yes to the end. Only a few apps have a command-line tool to control them. Many macOS apps have a powerful scripting interface meant to be used by Automator and/or AppleScript but easily usable from Python—but FaceTime does not. And even trying to use UI event scripting (where you simulate mouse clicks and the like) is painful with FaceTime. But FaceTime does know how to handle the tel URL scheme. So, if you hand it tel://8675309 from the open command (or the SystemEvents scripting interface, or Automator, or Safari, etc.), it will dial 8675309. Well, actually, by default, it won't dial the number, it'll pop up a dialog asking whether you want to dial the number—same as when you click a phone number in an email or note. As far as I know, you can't change that from the calling side, only by setting a global preference to always dial without popping up that dialog. And I think the preference to change that has been hidden since 10.8 or so. (I'd bet somewhere on Ask Different there's a question with the current information on how to change it, but I don't know what it is.) By the way, if you just open tel://8675309 without specifying an app, that will open whatever app is your default tel handler, which is usually FaceTime—but sometimes Skype, or older versions of Google Voice, or various other third-party programs will take that over. So if you want your script to switch to Skype if you change your default, leave off the -a bit; if you want to use FaceTime no matter what, leave it on.
answers question: http://stackoverflow.com/q/51913342
score: 2
downvote count: 0

http://stackoverflow.com/q/51800428
score: 2
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90557533
answer count: 0
has comment: http://stackoverflow.com/comment/90557295
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90557603
has comment: http://stackoverflow.com/comment/90557325
has body: I understand that python internally using the string interning concept to map same string in a particular memory location, and that helps in a way to optimise the memory. &gt;&gt;&gt; a = 'a' &gt;&gt;&gt; id(a) &gt;&gt;&gt; 4503208208 &gt;&gt;&gt; b = 'a' &gt;&gt;&gt; id(b) &gt;&gt;&gt; 4503208208 But why does special character in a string is handled differently &gt;&gt;&gt; i = 'a.' &gt;&gt;&gt; id(i) &gt;&gt;&gt; 4519365240 &gt;&gt;&gt; j='a.' &gt;&gt;&gt; id(j) &gt;&gt;&gt; 4519463824 Why is the same logic and principle not implemented when there is a special character in the string?
has comment: http://stackoverflow.com/comment/90559255
duplicate of: http://stackoverflow.com/q/21203212
type: Question
upvote count: 2
has title: String interning in python with special character
downvote count: 0
tagged with: string
tagged with: string-interning
has comment: http://stackoverflow.com/comment/90557526
linked to: http://stackoverflow.com/q/21203212
tagged with: python
favorite count: 0

http://stackoverflow.com/comment/90721551
type: Comment
type: QuestionComment
score: 1
has text: I believe _gorg and _geqv were both removed from typing, so likely you’ll need to upgrade python-ta.
comment on: http://stackoverflow.com/q/51884808

http://stackoverflow.com/q/51913142
tagged with: python-2.7
has body: Have a below output and wanted to remove the white space and line breaks. \n', ' var [3:0] apple [1:0];\n', ' int mango;\n', ' float banana [5:0];\n', ' int lichi;\n', ' I tried both the below code but its not working. Any comments/corrections ? print str(str(re.sub('[^A-Za-z0-9[:]]+[\r\n]+', ' ', str(match_group_t[i])))) print re.sub(r"(?&lt;=[a-z])\r?\n"," ", match_group_t[i]) Drop in your comments for any correction ! Expected Output is : Only var [3:0] apple [1:0], int mango, float banana [5:0], int lichi. So that I can store type and name separately in an array and use it later. Like variable data in an array: [apple, var, lelem, [3:0], rleme, [1:0]]
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/90776750
has comment: http://stackoverflow.com/comment/90776444
has answer: http://stackoverflow.com/a/51913310
accepted answer: http://stackoverflow.com/a/51913310
has comment: http://stackoverflow.com/comment/90776450
has title: How to remove white space, line breaks etc from a string in python
tagged with: python
type: AnsweredQuestion
score: 1
possible better answer: http://stackoverflow.com/a/51913166
has comment: http://stackoverflow.com/comment/90776469
has answer: http://stackoverflow.com/a/51913166
type: Question
upvote count: 2
linked to: http://stackoverflow.com/q/51905869
answer count: 2
has comment: http://stackoverflow.com/comment/90776698
has comment: http://stackoverflow.com/comment/90776863

http://stackoverflow.com/a/51858734
type: Answer
score: 1
upvote count: 1
has body: api was removed from mapclassify starting with version 2.0. From the github, this was the syntax in 1.0.1: &gt;&gt;&gt; import mapclassify.api as mc &gt;&gt;&gt; y = mc.load_example() &gt;&gt;&gt; y.mean() 125.92810344827588 &gt;&gt;&gt; y.min(), y.max() (0.13, 4111.4499999999998) and became this with 2.0.0: &gt;&gt;&gt; import mapclassify &gt;&gt;&gt; y = mapclassify.load_example() &gt;&gt;&gt; y.mean() 125.92810344827588 &gt;&gt;&gt; y.min(), y.max() (0.13, 4111.4499999999998)
accepted answer of: http://stackoverflow.com/q/51858530
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51858530

http://stackoverflow.com/a/51912316
type: AcceptedAnswer
has body: Absolute Position &amp; Size Absolute size, use self.ids.main_image.norm_image_size Absolute pos x, use self.ids.main_image.center_x - self.ids.main_image.norm_image_size[0] / 2. Absolute pos y, use self.ids.main_image.center_y - self.ids.main_image.norm_image_size[1] / 2. Snippet class ThirdScreen(Screen): def enable_cropping(self): print("\nThirdScreen:") print(self.ids.main_image.pos) print(self.ids.main_image.size) print("\tAbsolute size=", self.ids.main_image.norm_image_size) print("\tAbsolute pos_x=", self.ids.main_image.center_x - self.ids.main_image.norm_image_size[0] / 2.) print("\tAbsolute pos_y=", self.ids.main_image.center_y - self.ids.main_image.norm_image_size[1] / 2.) Example main.py from kivy.uix.boxlayout import BoxLayout from kivy.lang import Builder from kivy.app import App from kivy.uix.screenmanager import ScreenManager, Screen Builder.load_string(""" &lt;MyScreenManager&gt;: ThirdScreen: id: third_screen &lt;ThirdScreen&gt;: name: '_third_screen_' id: third_screen BoxLayout: orientation: "vertical" id: third_screen_boxlayout canvas: Label: id: main_title text: "Title" size_hint: (1, 0.1) canvas.before: Color: rgba: 1, 0, 0, 1 # red Rectangle: pos: self.pos size: self.size Image: id: main_image # source: "C:/Users/OneDrive/0. T2/6. Kivy/4/claymore.jpg" source: "./claymore.jpeg" canvas.before: Color: rgba: 0, 0, 1, 0.5 # blue Rectangle: pos: self.pos size: self.size BoxLayout: id: button_boxlayout orientation: "horizontal" padding: 10 size_hint: (1, 0.15) Button: id: accept_button text: "Okay" size_hint: (0.33, 1) on_press: root.image_accepted_by_user(root.image_address) Button: id: crop_button text: "Crop" size_hint: (0.33, 1) on_press: root.enable_cropping() Button: id: cancel_button text: "Cancel" size_hint: (0.33, 1) on_press: root.manager.current = '_first_screen_' """) class MyScreenManager(ScreenManager): pass class ThirdScreen(Screen): def enable_cropping(self): print("\nThirdScreen:") print(self.ids.main_image.pos) print(self.ids.main_im…
answers question: http://stackoverflow.com/q/51911965
downvote count: 0
type: Answer
score: 3
upvote count: 3
accepted answer of: http://stackoverflow.com/q/51911965

http://stackoverflow.com/a/51860365
score: 4
answers question: http://stackoverflow.com/q/51859032
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51859032
type: Answer
has body: Package your source code and dependencies in a zip file, upload it to S3, and then use the S3Bucket and S3Keys Properties under your AWS::Lambda::Function resource. e.g. On Linux: mkdir project-dir cp myhandler.py project-dir pip install module-name -t /path/to/project-dir # zip the contents of project-dir , this is your deployment package cd project-dir zip -r deployme.zip .
downvote count: 1
upvote count: 5

http://stackoverflow.com/comment/90770509
type: Comment
has text: I don't want the code to have to use print(point2-point1). I should only have to use print(point1.distance(point2)). This is why I am trying to use a function with a classmethod
type: AnswerComment
comment on: http://stackoverflow.com/a/51910179
score: 0

http://stackoverflow.com/q/51928532
has answer: http://stackoverflow.com/a/51928938
answer count: 3
type: UnansweredQuestion
has title: Python2.7 list operation with nop
tagged with: python
has answer: http://stackoverflow.com/a/51928720
tagged with: list
has answer: http://stackoverflow.com/a/51928582
type: Question
tagged with: python-2.7
score: 0
has body: I want to append some data to a list according to condition: arr = ['abc', ('def' if condition else NOP)] here, if condition is false, what should I do with NOP when I want arr to be only contains abc?

http://stackoverflow.com/a/51913474
type: Answer
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/90899146
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51913444
has comment: http://stackoverflow.com/comment/90794813
has body: If the email cannot be sent, it will raise an exception as per the docs. You could do something like the following: cantSendErrors = (smptlib.SMTPHeloError, smptlib.SMTPSenderRefused) # Put any other suitable exceptions in this tuple try: smptlib.sendmail(args, go, here) except cantSendErrors: # Your code here. You could email yourself or write the error to log file for later review, your choice.
accepted answer of: http://stackoverflow.com/q/51913444

http://stackoverflow.com/comment/90570633
comment on: http://stackoverflow.com/q/51807744
score: 2
type: Comment
type: QuestionComment
has text: Why have you created a dozen or more `StringVar`s, some of them twice, some of them replacing other variables of the same names?

http://stackoverflow.com/comment/90572780
score: 1
comment on: http://stackoverflow.com/q/51808715
has text: Where you handle an exception is entirely dependent on the application. There is no one-size-fits-all approach. You handle them where your application requirements say it makes sense they need to be handled.
type: QuestionComment
type: Comment

http://stackoverflow.com/a/51800501
has comment: http://stackoverflow.com/comment/90575293
answers question: http://stackoverflow.com/q/51800441
has body: The problem is that button click results in a call to callback1(), not callback1(something). Try removing the event argument.
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/90575270

http://stackoverflow.com/a/51799790
accepted answer of: http://stackoverflow.com/q/51799047
has body: One possible way would be to add to your model so that everything is contained in a single model that ends with 2 branches. The functional API in keras allows you to define connections between layers however you want, and also provides the infrastructure for having multiple outputs and loss functions. For example: from keras.utils import plot_model from keras.models import Model from keras.layers import Input from keras.layers import Dense from keras.layers.convolutional import Conv2D from keras.layers.pooling import MaxPooling2D visible = Input(shape=(64,64,1)) conv1 = Conv2D(32, kernel_size=4, activation='relu')(visible) pool1 = MaxPooling2D(pool_size=(2, 2))(conv1) conv2 = Conv2D(16, kernel_size=4, activation='relu')(pool1) pool2 = MaxPooling2D(pool_size=(2, 2))(conv2) #add your second model here X = FirstLayer()(pool2) #replace with your actual network layer # ... output2 = YourSecondOutput()(X) hidden1 = Dense(10, activation='relu')(pool2) output = Dense(1, activation='sigmoid')(hidden1) model = Model(inputs=visible, outputs=[output, output2]) #list of outputs model.compile(optimizer='Adam', loss=['sparse_categorical_crossentropy', None], metrics=['accuracy']) model.fit(train_dataset, train_labels, epochs=400, batch_size=512, validation_data=(valid_dataset, valid_labels), verbose=1, callbacks=[early_stop]) # summarize layers print(model.summary()) # plot graph plot_model(model, to_file='convolutional_neural_network.png') Then you’ll just need to update your inputs to fit so that you have labels for each output. You can find more info in the keras documentation on multi input and output models
upvote count: 1
has comment: http://stackoverflow.com/comment/90559121
has comment: http://stackoverflow.com/comment/90557651
type: AcceptedAnswer
downvote count: 0
score: 1
type: Answer
answers question: http://stackoverflow.com/q/51799047

http://stackoverflow.com/comment/134587896
comment on: http://stackoverflow.com/a/51912712
has text: @RobertAtkins Did you run `brew info python` ? Because if I run that on my system, I get the message about unversioned links. And note that **homebrew** now makes the links in `/opt/homebrew/opt/python@3.11/libexec/bin` rather than `usr/local/opt/python/libexec/bin` because it has changed in the 5 years since I wrote this answer.
type: Comment
score: 1
type: AnswerComment

http://stackoverflow.com/q/51953437
answer count: 3
has title: XPath for html elements
favorite count: 0
tagged with: xpath
has comment: http://stackoverflow.com/comment/90857281
tagged with: python
score: 2
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51953599
downvote count: 0
accepted answer: http://stackoverflow.com/a/51959712
tagged with: scrapy
has body: I'd like to use Scrapy to crawl a few hundred websites and just scrape the basic (title, meta* and body) html elements. I know that I should use CrawlSpider for this and adjust some of the settings based on broad crawls. The part that I'm having trouble figuring it out is how to use xpath to create the rules for scraping just those basic html elements. Lots of tutorials I see involve inspecting the element and finding the css class for that element. That is fine for the body element but what about the title and meta tags?
type: Question
has answer: http://stackoverflow.com/a/51959712
has answer: http://stackoverflow.com/a/52017001
upvote count: 2
has answer: http://stackoverflow.com/a/51953599

http://stackoverflow.com/comment/106888759
type: Comment
score: 7
comment on: http://stackoverflow.com/a/51875718
type: AnswerComment
has text: My output was formatted a bit differently. Perhaps pip has been updated. This worked for my case: `pip download --no-cache-dir --verbose "foo<0" 2>&1 |grep 'location(s) to search' -A5`

http://stackoverflow.com/q/51898035
has answer: http://stackoverflow.com/a/51898059
has answer: http://stackoverflow.com/a/51898073
upvote count: 3
has body: Hello I have a List with a lot of element in it. These are numbers and ordered but some numbers are missing. Example: L =[1,2,3,4,6,7,10] Missing: M = [5,8,9] How can I find missing numbers in Python?
has answer: http://stackoverflow.com/a/51898113
downvote count: 2
accepted answer: http://stackoverflow.com/a/51898059
possible better answer: http://stackoverflow.com/a/51898073
type: AnsweredQuestion
tagged with: list
has title: Finding missing elements in a List
has answer: http://stackoverflow.com/a/51898087
score: 1
has comment: http://stackoverflow.com/comment/90747055
has answer: http://stackoverflow.com/a/51898161
type: Question
favorite count: 0
answer count: 5
tagged with: python

http://stackoverflow.com/comment/90709566
type: QuestionComment
comment on: http://stackoverflow.com/q/51876184
has text: @Msquare There are definitely no local maxima or peaks inside that crircle and it is not clear what you mean by "small notch".
score: 0
type: Comment

http://stackoverflow.com/a/51810701
has comment: http://stackoverflow.com/comment/90576467
has comment: http://stackoverflow.com/comment/90576838
has comment: http://stackoverflow.com/comment/90576369
has comment: http://stackoverflow.com/comment/121357629
type: Answer
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/90576426
answers question: http://stackoverflow.com/q/51810163
downvote count: 0
has body: Let us generate a DataFrame simulating yours: &gt;&gt;&gt; df=pd.DataFrame(random.randint(3,size=(8,5)),columns=list("abcde")) &gt;&gt;&gt; df a b c d e 0 2 2 1 2 2 1 1 2 2 0 2 2 0 2 1 0 2 3 2 1 1 0 1 4 0 1 0 0 0 5 0 0 2 0 1 6 2 0 1 1 2 7 2 0 0 0 0 Then numpy.argmax() can be used to find the position of the first nonzero value in each row (you can modify the condition for nonempty string etc.): &gt;&gt;&gt; argmax(df.values!=0,axis=1) array([0, 0, 1, 0, 1, 2, 0, 0], dtype=int64) Let us append this field to df after converting it into the values into the header of df: &gt;&gt;&gt; df['first_nonzero']=df.keys()[argmax(df.values!=0,axis=1)] &gt;&gt;&gt; df a b c d e first_nonzero 0 2 2 1 2 2 a 1 1 2 2 0 2 a 2 0 2 1 0 2 b 3 2 1 1 0 1 a 4 0 1 0 0 0 b 5 0 0 2 0 1 c 6 2 0 1 1 2 a 7 2 0 0 0 0 a Voila!

http://stackoverflow.com/comment/107342606
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51945933
score: 0
has text: FWIW: In a hidden answer @rajkumar-srinivasan stated the same question was asked and answered in SAS Communities post [SAS IOM Bridge with Python](https://communities.sas.com/t5/Developers/SAS-IOM-Bridge-with-Python/m-p/489798). Don't upvote this comment.

http://stackoverflow.com/q/51808715
type: Question
has comment: http://stackoverflow.com/comment/90572851
has comment: http://stackoverflow.com/comment/90573109
has comment: http://stackoverflow.com/comment/90572887
has comment: http://stackoverflow.com/comment/90572833
score: -1
duplicate of: http://stackoverflow.com/q/18679090
has comment: http://stackoverflow.com/comment/90572552
has body: I am trying to work out the most pythonic way of handling exceptions. Let's say we have a long method that completes multiple tasks to do with registering a car e.g. Retrieving car details Calculating the tax Sending out a confirmation email Should the calling method deal with exceptions: def process_car_registration(self, registration): try: car_details = self.retrieve_car_details(registration) except: car_details = None print("Cannot retrieve car details") try: car_tax = self.calculate_tax_due(registration) except: car_tax = None print("Cannot calculate tax due") try: self.send_confirmation_email(registration, car_details, car_tax) except: print("Cannot send confirmation email") def calculate_tax_due(self, registration): return self.dal.get_car_tax(registration) Or should the individual methods itself deal with exceptions. If there are any exceptions in this methods we just want to log it (or in this case print it) and continue. def process_car_registration(self, registration): car_details = self.retrieve_car_details(registration) car_tax = self.calculate_tax_due(registration) self.send_confirmation_email(registration, car_details, car_tax) def calculate_tax_due(self, registration): try: return self.dal.get_car_tax(registration) except: print("Cannot calculate tax due") return None Is one method more pythonic then the other or does it come down to which is more readable? I prefer the second way but we seem to use the first way more often.
has comment: http://stackoverflow.com/comment/90572955
upvote count: 0
has comment: http://stackoverflow.com/comment/90572983
has comment: http://stackoverflow.com/comment/90572817
answer count: 1
has comment: http://stackoverflow.com/comment/90572645
favorite count: 0
has comment: http://stackoverflow.com/comment/90573126
has comment: http://stackoverflow.com/comment/90572780
has comment: http://stackoverflow.com/comment/90572916
has comment: http://stackoverflow.com/comment/90572765
has comment: http://stackoverflow.com/comment/90573069
tagged with: python
has comment: http://stackoverflow.com/comment/90573131
has comment: http://stackoverflow.com/comment/90573023
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90573277
has answer: http://stackoverflow.com/a/51808764
has title: Python: When to handle exceptions
downvote count: 1

http://stackoverflow.com/q/51951429
has comment: http://stackoverflow.com/comment/90853571
has comment: http://stackoverflow.com/comment/90853353
has body: Let's say I create a dictionary a_dictionary where two of the key-value pairs have an identical key: In [1]: a_dictionary = {'key': 5, 'another_key': 10, 'key': 50} In [2]: a_dictionary Out[2]: {'key': 50, 'another_key': 10} Why does Python choose here to keep the last key-value pair instead of throwing an error (or at least raising a warning) about using identical keys? The way I see it, the main downside here is that you may lose data without being aware. (If it's relevant, I ran the code above on Python 3.6.4.)
has answer: http://stackoverflow.com/a/51951581
downvote count: 0
score: 4
favorite count: 0
has comment: http://stackoverflow.com/comment/90856888
possible better answer: http://stackoverflow.com/a/51951581
tagged with: python
tagged with: dictionary
accepted answer: http://stackoverflow.com/a/51957283
has title: When dictionary keys are identical, why does Python keep only the last key-value pair?
answer count: 4
linked to: http://stackoverflow.com/q/34539772
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90853873
has answer: http://stackoverflow.com/a/51952485
has comment: http://stackoverflow.com/comment/90853276
has comment: http://stackoverflow.com/comment/90853158
type: Question
has comment: http://stackoverflow.com/comment/90853690
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51951549
has comment: http://stackoverflow.com/comment/90853356
has comment: http://stackoverflow.com/comment/90857103
has answer: http://stackoverflow.com/a/51957283
upvote count: 4
has comment: http://stackoverflow.com/comment/90853595

http://stackoverflow.com/comment/90649606
type: Comment
type: QuestionComment
has text: This is a highly opinionated question, but I will answer in a comment. If you are already comfortable with NodeJS, I would recommend going forward with NodeJS along with something like the Express framework. This should get you up and running rather quickly and easily.
comment on: http://stackoverflow.com/q/51848143
score: 0

http://stackoverflow.com/comment/90756419
has text: @GrantMcCloskey that's a bit broad to the scope of the question, isn't it pal?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51902595
score: 0

http://stackoverflow.com/comment/90653069
type: Comment
type: QuestionComment
has text: gah ... nevermind ... dumb question ... for some reason, I thought since the x values are evenly distributed, it wouldn't matter if I didn't include them in the `plt.plot`, but it totally matters X.X
comment on: http://stackoverflow.com/q/51849871
score: 0

http://stackoverflow.com/q/51823648
upvote count: 1
has answer: http://stackoverflow.com/a/51824140
downvote count: 1
type: Question
tagged with: discord.py
has body: How would I go about printing to console a list of all my friends? I'm hoping to be able to achieve this with the Discord.py library, hopefully someone here knows. I currently get the error: for user in discord.ClientUser.friends: TypeError: 'property' object is not iterable Program: token = "" prefix = "::" import discord import asyncio import codecs import sys import io from discord.ext import commands from discord.ext.commands import Bot print ("waiting") bot = commands.Bot(command_prefix=prefix, self_bot=True) bot.remove_command("help") @bot.event async def on_ready(): print ("Friends") @bot.command() async def userlist(ctx): for user in discord.ClientUser.friends: print (user.name+"#"+user.discriminator) bot.run(token, bot=False)
has title: Print friends-list to console Discord.py
score: 0
answer count: 3
accepted answer: http://stackoverflow.com/a/51824140
favorite count: 0
tagged with: python
possible better answer: http://stackoverflow.com/a/51823765
tagged with: discord
has answer: http://stackoverflow.com/a/51823765
has answer: http://stackoverflow.com/a/51823775
type: AnsweredQuestion

decision-tree
tags question: http://stackoverflow.com/q/51952814
tags question: http://stackoverflow.com/q/51912370
type: Tag
tags question: http://stackoverflow.com/q/51937185
tag name: decision-tree

http://stackoverflow.com/comment/90573660
type: QuestionComment
comment on: http://stackoverflow.com/q/51809040
score: 2
has text: You forgot to post the code.
type: Comment

amazon-vpc
type: Tag
tags question: http://stackoverflow.com/q/51801942
tag name: amazon-vpc

http://stackoverflow.com/q/51912317
linked to: http://stackoverflow.com/q/357929
downvote count: 0
has body: Let's say we have a model class use to keep track of Fraud Checks: class FraudCheck(object): def __init__(self, score_threshold): self.score = None self.transaction = None self.is_fraud = True self.score_threshold = score_threshold Should we be writing unit tests for this __init__ method? There are other methods in the class as well. So should we be writing tests similar to: @pytest.fixture() def fraud_data(): account = FraudCheck( 1000 ) return account def test_fraud_data(fraud_data): assert fraud_data.score is None assert fraud_data.transaction is None assert fraud_data.is_fraud assert fraud_data.score_threshold == 10 I know this question was marked as a possible duplicate however the other question was a constructor setting on value. In this particular question, we are only setting one value but there are three other variables as well being set to default values. I would think a unit test would be appropriate in case the variables got mixed up during refactoring but I would like other peoples opinions.
score: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51939906
tagged with: python
has comment: http://stackoverflow.com/comment/90775983
has title: Python Unit Test for Model Class
tagged with: pytest
type: UnansweredQuestion
upvote count: 1
has answer: http://stackoverflow.com/a/56050127
tagged with: unit-testing
type: Question
answer count: 2

http://stackoverflow.com/comment/90574399
type: Comment
has text: Good advice, many thanks
comment on: http://stackoverflow.com/q/51809507
score: 0
type: QuestionComment

http://stackoverflow.com/q/51924128
tagged with: selenium
has comment: http://stackoverflow.com/comment/90797930
has answer: http://stackoverflow.com/a/51924709
has body: I am working on selenium to retrieve learning stuff: During the executing of my code, the target website will defensively open a new tab to stop my process. I tried to check the current_url, but it does not work as expected if browser.current_url != start_url: browser.switch_to.window(browser.window_handles[0]) How could I check like this: if browser.current_tab != tab[0]: browser.switch_to.window(browser.window_handles[0])
has comment: http://stackoverflow.com/comment/90797868
type: AnsweredQuestion
has title: Check if the active tab is the correct
accepted answer: http://stackoverflow.com/a/51924709
type: Question
score: 0
tagged with: python
answer count: 1

http://stackoverflow.com/comment/90652423
type: QuestionComment
has text: When you print `a`, you see a string representation of the array, rows and columns, like a table. A 2d array does not actually have 'top left', 'bottom right' etc. properties.
score: 0
comment on: http://stackoverflow.com/q/51849547
type: Comment

http://stackoverflow.com/comment/90824879
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51901399
has text: I realize that you probably don't want to post your host name here (for good reason), but it seems the problem is based around that. but if you just import socket directly and try socket.gethostbyname(host) does it work? or if you do user:pass@host do you get the same error? are there special characters? do you need to percent encode them?
score: 0

http://stackoverflow.com/comment/90760624
type: QuestionComment
has text: A bare xA0 character isn't valid UTF-8. Try changing the XML declaration to read <?xml version="1.0" encoding="latin-1"?> and retry the parse.
comment on: http://stackoverflow.com/q/51890300
score: 0
type: Comment

http://stackoverflow.com/comment/90749549
type: Comment
type: QuestionComment
has text: Well, you just assign the output of the filtering to a new DataFrame.
score: 3
comment on: http://stackoverflow.com/q/51899276

http://stackoverflow.com/comment/90687832
has text: This is one of those things which cannot be strictly defined. You have to use your gut feeling (which means, the more experienced you are, the better decisions you make), because it really depends on more things than one could put in words. Anyway, I would not say that the number of lines is very important, unless it is really extreme (I would not make many files with 3 lines each, nor do I like to have many of them with thousands of lines of code).
comment on: http://stackoverflow.com/q/51867912
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/94804838
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52767459
score: 0
has text: And when the anaconda application does.not launch, the key is to install pyqt5 package using pip. It works all the time

http://stackoverflow.com/comment/90698297
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51872895
has text: not completely, say for 5 employee are working in `ddc systems`, I can see only 2 employee working in `ddc systems` in out put. I know it's little bit strange.
score: 0

http://stackoverflow.com/q/51907780
downvote count: 0
tagged with: bayesian
favorite count: 0
has comment: http://stackoverflow.com/comment/90795148
type: UnansweredQuestion
upvote count: 1
tagged with: python
has body: I am currently struggling to obtain a summary of the statistics of a model I ran through Bayesian regression on. I first used Lasso and model selection to filter the best variables, then used pm.Model to obtain the regression proper. Of course, having 'filtered' the explanatory variables that weren't relevant, the shape of the X matrix had changed. The data I worked on is the load_boston dataset from sklearn.dataset. I coded the data as independent variable and the target as dependent variable. Having performed model selection with SelectFromModel, I used the get.support method to obtain an index of the retained variables. I then used a loop over both the indexes of all variables and the numbers contained in the support, with the purpose of storing the names of the retained variables in an empty list I had created at hoc. The code looks something like this import pandas as pd import numpy as np import pymc3 as pm import matplotlib.pyplot as plt import matplotlib.pyplot as plt import numpy as np np.random.seed(9) # Load the boston dataset. from sklearn.datasets import load_boston boston = load_boston() X, y = boston['data'], boston['target'] # Here is the code for the estimator LassoCV # Here is the code for Model Selection support(indices=True) #to obtain the list of indices of retained variables X_transform = sfm.transform(X) #to remove the unnecessary variables #Here is the line for linear modeling #I initialize some useful variables m = y.shape[0] n = X.shape[1] c = supp.shape[0] L = boston['feature_names'] varnames=[] for i in range (0, n): for j in range (0, c): if i == supp[j]: varnames.append(L[i]) pm.summary(trace, varnames=varnames) The console then displays 'KeyError: RM', which is one of the names of the variables used. One issue I noticed that every object of varnames is classified as str_ object of numpy module, meaning that I can't read the name of the retained variables on the list unless I double click on them. How could I fix this? I have no clue wh…
has title: Issues with Pymc3 Summary
answer count: 0
tagged with: pymc3
score: 1
type: Question

http://stackoverflow.com/comment/98799657
score: 0
type: AnswerComment
has text: Is this a serious suggestion?
type: Comment
comment on: http://stackoverflow.com/a/51826253

http://stackoverflow.com/a/51980769
has comment: http://stackoverflow.com/comment/90923212
type: Answer
has body: Yes, you do need to transform the loop into a function. The function has to be able to take in just one argument. That one argument could be anything such as a list,tuple,dictionary or whatever. Functions with multiple parameters are a little complex to put into the concurrent.futures.*Executor methods. This example below should work for you. from bs4 import BeautifulSoup import pandas as pd from concurrent import futures def create_dataframe(xml): soup = BeautifulSoup(xml, "xml") # Get Attributes from all nodes attrs = [] for elm in soup(): # soup() is equivalent to soup.find_all() attrs.append(elm.attrs) # Since you want the data in a dataframe, it makes sense for each field to be a new row consisting of all the other node attributes fields_attribute_list = [x for x in attrs if 'FieldId' in x.keys()] other_attribute_list = [x for x in attrs if 'FieldId' not in x.keys() and x != {}] # Make a single dictionary with the attributes of all nodes except for the `Field` nodes. attribute_dict = {} for d in other_attribute_list: for k, v in d.items(): attribute_dict.setdefault(k, v) # Update each field row with attributes from all other nodes. full_list = [] for field in fields_attribute_list: field.update(attribute_dict) full_list.append(field) print(len(full_list)) # Make Dataframe df = pd.DataFrame(full_list) # print(df) return df with futures.ThreadPoolExecutor() as executor: # Or use ProcessPoolExecutor df_list = executor.map(create_dataframe, lst) df_list = list(df_list) full_df = pd.concat(list(df_list)) print(full_df)
has comment: http://stackoverflow.com/comment/90923168
has comment: http://stackoverflow.com/comment/90921686
score: 3
upvote count: 3
accepted answer of: http://stackoverflow.com/q/51932585
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51932585
downvote count: 0

http://stackoverflow.com/comment/90822898
comment on: http://stackoverflow.com/a/51935476
type: AnswerComment
type: Comment
has text: My question was in regards to all three hence the lambda function kicking back an error within the python code in regards to the paramiko line. This does not necessarily mean that's the only thing that could have gone wrong hence why it was also tagged with amazon-web-services as well as amazon-ec2.
score: 2

http://stackoverflow.com/comment/90826114
type: AnswerComment
has text: If you're sure we can control the loop iterations manually with pdb, then show how to do it. But I don't think you can (except maybe by screwing around with the attributes of the current frame object or something). The iterator inside the `for` statement is not exposed to the locals in pdb any more than it is to the locals in the original code.
type: Comment
comment on: http://stackoverflow.com/a/51937996
score: 0

http://stackoverflow.com/comment/90817014
comment on: http://stackoverflow.com/q/51930548
score: 0
type: QuestionComment
type: Comment
has text: Did you build your image as a container and make sure the container is running? `docker ps`

http://stackoverflow.com/comment/91364457
has text: I think class `C` needs to be defined like `class C(A, B, metaclass=combine_meta): pass`, right?
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/52207349

http://stackoverflow.com/comment/90571185
type: QuestionComment
score: 2
has text: Why _wouldn't_ it be called? The `self` variable is a name for a `child` object, so when you look up the name `set_state` on `self`, you get `child.set_state` (bound to `self`).
comment on: http://stackoverflow.com/q/51808020
type: Comment

http://stackoverflow.com/q/51891764
has body: I need to install the latest version of pandas on an old Debian Gnu/Linux 8 (jessie) server. apt-get install python-pandas installs pandas==0.14.1 (instead of 0.23.4) and numpy==1.8.2 (instead of 1.15.2). Is it possible to update to the latest version, possibly without compiling the sources? Here the full solution (for the lazy ones) virtualenv env # to create an environment . env/bin/activate # activate it pip install -U pip # to upgrade to the latest version pip install pandas==0.23.4 If installing pandas takes ages like in my case, because of problems with compilation (missing libs) use instead: pip install pandas==0.23.4 --no-build-isolation pip update has been necessary because my previous version (1.5.6) didn't support --no-build-isolation.
score: 0
tagged with: pandas
answer count: 1
accepted answer: http://stackoverflow.com/a/51891886
tagged with: python
has answer: http://stackoverflow.com/a/51891886
has title: How to install latest pandas on old Debian Linux?
type: AnsweredQuestion
tagged with: installation
type: Question

http://stackoverflow.com/a/51914416
answers question: http://stackoverflow.com/q/51914391
upvote count: 1
has comment: http://stackoverflow.com/comment/90779416
score: 1
has comment: http://stackoverflow.com/comment/90779140
has comment: http://stackoverflow.com/comment/90779540
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/90779161
has body: You're almost there already. The only change is in start_urls, which you want to be "all the urls in the *.csv file." The following code easily implements that change. with open('data.csv') as file: start_urls = [line.strip() for line in file]

http://stackoverflow.com/comment/90619888
type: QuestionComment
comment on: http://stackoverflow.com/q/51832038
has text: You can use either a regex or endswith. In addition are there any constraints in the question?
score: 1
type: Comment

legend
tags question: http://stackoverflow.com/q/51900272
tags question: http://stackoverflow.com/q/51908481
tags question: http://stackoverflow.com/q/51902887
tags question: http://stackoverflow.com/q/51812323
type: Tag
tag name: legend

http://stackoverflow.com/q/51905788
score: 0
has answer: http://stackoverflow.com/a/51942139
accepted answer: http://stackoverflow.com/a/51942139
tagged with: nlp
tagged with: python
has title: Add a new stemmer to nltk
type: AnsweredQuestion
tagged with: stemming
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/51924324
tagged with: nltk
tagged with: text-mining
has body: I have this python function that works as expected. Is it possible to save the logic as NLP stemmer? If yes, what changes needs to be done? import itertools, re def dropdup(mytuple): newtup=list() for i in mytuple: i = i[:-3] if i.endswith('bai') else i for r in (("tha", "ta"), ("i", "e")): i = i.replace(*r) i = re.sub(r'(\w)\1+',r'\1', i) newtup.append(''.join(i for i, _ in itertools.groupby(i))) return tuple(newtup) dropdup(('savithabai', 'samiiir', 'aaaabaa')) ('saveta', 'samer', 'aba') I will like the users to import something like this... from nltk.stemmer import indianNameStemmer There are a few more rules to be added to the logic. I just want to know if this is a valid (pythonic) idea.
possible better answer: http://stackoverflow.com/a/51924324

http://stackoverflow.com/comment/90594858
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51820000
has text: i do need the extra column

http://stackoverflow.com/a/51906497
answers question: http://stackoverflow.com/q/51895192
type: Answer
has body: Go with CMU Sphinx. It does exactly what you want. See here: https://cmusphinx.github.io/wiki/
score: 2
upvote count: 2
downvote count: 0

http://stackoverflow.com/q/51865705
tagged with: dictionary
has answer: http://stackoverflow.com/a/51865767
type: AnsweredQuestion
tagged with: mapping
score: 1
possible better answer: http://stackoverflow.com/a/51865767
has body: table = pd.DataFrame(data=[[1,2,3],[4,5,6],[7,8,9]], columns=['High','Middle','Low'], index=['Blue','Green','Red']) df = pd.DataFrame(data=[['High','Blue'], ['High','Green'], ['Low','Red'], ['Middle','Blue'], ['Low','Blue'], ['Low','Red']], columns=['A','B']) &gt;&gt;&gt; df A B 0 High Blue 1 High Green 2 Low Red 3 Middle Blue 4 Low Blue 5 Low Red &gt;&gt;&gt; table High Middle Low Blue 1 2 3 Green 4 5 6 Red 7 8 9 I'm trying to add a third column 'C' which is based on the values in the table. So the first row would get a value of 1, the second of 4 etc. If this would be be a one-dimensional lookup I would convert the table to a dictionary and would use df['C'] = df['A'].map(table). However since this is two-dimensional I can't figure out how to use map or apply. Ideally I would convert the table to dictionary format so I save it together with other dictionaries in a json, however this is not essential.
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51865817
has title: Create column in pandas based on two other columns and table
has comment: http://stackoverflow.com/comment/90683800
answer count: 2
tagged with: pandas
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/51865817
tagged with: python

macos
tags question: http://stackoverflow.com/q/51886342
tags question: http://stackoverflow.com/q/51913342
tags question: http://stackoverflow.com/q/51948440
tags question: http://stackoverflow.com/q/51804203
tags question: http://stackoverflow.com/q/51862518
tags question: http://stackoverflow.com/q/51824734
tags question: http://stackoverflow.com/q/51833310
tags question: http://stackoverflow.com/q/51873758
tags question: http://stackoverflow.com/q/51919720
tags question: http://stackoverflow.com/q/51820782
tags question: http://stackoverflow.com/q/51914127
tags question: http://stackoverflow.com/q/51890623
tags question: http://stackoverflow.com/q/51847801
tags question: http://stackoverflow.com/q/51885394
tags question: http://stackoverflow.com/q/51872798
tags question: http://stackoverflow.com/q/51912816
tags question: http://stackoverflow.com/q/51909209
tags question: http://stackoverflow.com/q/51801282
type: Tag
tags question: http://stackoverflow.com/q/51847580
tags question: http://stackoverflow.com/q/51883544
tags question: http://stackoverflow.com/q/51941543
tags question: http://stackoverflow.com/q/51901570
tag name: macos

http://stackoverflow.com/a/51873505
type: Answer
has body: Tensorflow expected input which is formated in NHWC format, which means: (BATCH, HEIGHT, WIDTH, CHANNELS). Step 1 - Add last dimension: last_axis = -1 grscale_img_3dims = np.expand_dims(image, last_axis) Step 2 - Repeat the last dimension 3 times: dim_to_repeat = 2 repeats = 3 np.repeat(grscale_img_3dims, repeats, dim_to_repeat) So your function should be: def load_image_into_numpy_array(image): # The function supports only grayscale images assert len(image.shape) == 2, "Not a grayscale input image" last_axis = -1 dim_to_repeat = 2 repeats = 3 grscale_img_3dims = np.expand_dims(image, last_axis) training_image = np.repeat(grscale_img_3dims, repeats, dim_to_repeat).astype('uint8') assert len(training_image.shape) == 3 assert training_image.shape[-1] == 3 return training_image
upvote count: 9
score: 9
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90699271
accepted answer of: http://stackoverflow.com/q/51872412
answers question: http://stackoverflow.com/q/51872412
has comment: http://stackoverflow.com/comment/92355835

http://stackoverflow.com/a/51910600
score: 1
upvote count: 1
type: AcceptedAnswer
has body: The lines self.minute += 1 and self.hour += 1 mean that your __add__ and __sub__ both modify the left-hand argument to +/-. Thus, after evaluating time1 + time2, the value of time1 will be different, so you'll get a different answer when you then evaluate time1 - time2.
answers question: http://stackoverflow.com/q/51910555
type: Answer
accepted answer of: http://stackoverflow.com/q/51910555
downvote count: 0

http://stackoverflow.com/comment/90797517
score: 0
type: Comment
type: QuestionComment
has text: `1 topic 1.txt cd` is this what you want? So what I meant is that can I suppose `1.txt` just after `1` to be a `topic` or anything but a dir?
comment on: http://stackoverflow.com/q/51923891

http://stackoverflow.com/q/51898197
has comment: http://stackoverflow.com/comment/90747512
has comment: http://stackoverflow.com/comment/90771079
has body: I have a NxN matrix where all the elements are having values between [-1, 1]. I can calculate Shannon's Entropy manually, but I want something like Von Neumann's Entropy. Is there any inbuilt function in Numpy/Scipy? Manual method will also do. Matrix is usually of size 100x100. Something like this. [[-0.244608 -0.71395497 -0.36534627] [-0.44626849 -0.82385746 -0.74654582] [ 0.38240205 -0.58970239 0.67858516]] Thank You.
tagged with: numpy
tagged with: sympy
downvote count: 5
type: UnansweredQuestion
has title: Calculating the Entropy of a NxN matrix in python
has answer: http://stackoverflow.com/a/61552598
tagged with: entropy
has comment: http://stackoverflow.com/comment/90770943
tagged with: matrix
score: 1
favorite count: 0
linked to: http://stackoverflow.com/q/20312216
has answer: http://stackoverflow.com/a/51898343
type: Question
answer count: 2
tagged with: python
upvote count: 6

http://stackoverflow.com/a/51877094
score: 3
accepted answer of: http://stackoverflow.com/q/51877093
answers question: http://stackoverflow.com/q/51877093
has body: When you've retrieved it in python you get a python datetime object. How this is printed is up to the datetime.strptime / strftime functions.
upvote count: 3
has comment: http://stackoverflow.com/comment/90705317
has comment: http://stackoverflow.com/comment/90705316
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/90705315
downvote count: 0

http://stackoverflow.com/comment/90771040
type: Comment
comment on: http://stackoverflow.com/q/51910430
score: 0
type: QuestionComment
has text: what is the type of `row`? the way your code is accessing, it should be a list

http://stackoverflow.com/a/51878584
accepted answer of: http://stackoverflow.com/q/51873859
upvote count: 3
answers question: http://stackoverflow.com/q/51873859
score: 3
has body: I was able to find the solution myself eventually. Answering here in case somebody else might have the same problem. The problem was that I was trying to update the children element in the div tag. Instead it proved much easier to create an empty chart and write the function to update the figure element of the chart. Below is the code which turned out to work: app = dash.Dash() app.layout = html.Div(children=[ html.H1(children=''' Interactive Chart: '''), dcc.Dropdown( id = "input", options=[ {'label': 'January', 'value': 1}, {'label': 'Febuary', 'value': 2}, {'label': 'March', 'value': 3} ], value = 1 ), dcc.Graph( id="output-graph") ]) @app.callback( Output(component_id='output-graph', component_property='figure'), [Input(component_id='input', component_property='value')]) def update_value(value): start = datetime.datetime(2018, value, 1, 0, 0, 0, 1) end = datetime.datetime(2018, value + 1, 1, 0, 0, 0, 1) subset_df = df[ (df["lost_time"] &gt; start) &amp; (df["lost_time"] &lt; end) ] x = pd.value_counts(subset_df.deal_source).index y = pd.value_counts(subset_df.deal_source).values return({'data': [ {'x': x, 'y': y, 'type': 'bar', 'name': value}, ], 'layout': { 'title': "Deal Flow source for {} 2018".format(months[value-1]) } } ) if __name__ == "__main__": app.run_server(debug = True)
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/comment/90791860
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51920089
has text: can you please solve my this question: https://stackoverflow.com/questions/51887141/unable-to-extract-date-of-birth-from-a-given-format
type: AnswerComment

http://stackoverflow.com/q/51827609
tagged with: django
has title: Django Model: Find Avg by Grouping from models
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51834570
type: Question
has answer: http://stackoverflow.com/a/51828374
tagged with: django-models
possible better answer: http://stackoverflow.com/a/51828374
score: 0
answer count: 2
tagged with: django-annotate
has answer: http://stackoverflow.com/a/51834570
has body: I have been trying to find the avg for rating a get queryset. This is my models.py class Movie(models.Model): title = models.CharField(max_length=240) release = models.DateField(blank=True) review = models.TextField() user = models.ForeignKey(User, on_delete=models.CASCADE) poster = models.FileField(null=True, blank=True) poster_wide = models.FileField(null=True, blank=True) created = models.DateTimeField(auto_now_add=True) def comment_count(self): return self.comment_set.count() def rating_avg(self): rate = self.rating.aggregate(Avg('rating')) return rate['rating__avg'] class Rating(models.Model): movie = models.ForeignKey(Movie,on_delete=models.CASCADE,related_name='rating') rating = models.IntegerField(choices=rating_choices, default=5) user = models.ForeignKey(User, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) Code in views.py def home(request): top_movies = Movie.objects.annotate(avg = Avg('rating')).order_by('avg')[:5] context = { 'top_movies': top_movies, } return render(request, 'home.html', context) I need to find the top 5 rated movies from this given models. But don't know how to group query can find average. The above query does not provide the correct answer. Any links to other answers or documentation that I can refer?

http://stackoverflow.com/q/51820952
tagged with: pivot-table
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51822000
has answer: http://stackoverflow.com/a/62778774
score: 2
has body: I have a 2D numpy array representing depth on grid of coordinates. z = np.array([[100, 101, 102, 103], [101, 102, 103, 104], [102, 103, 104, 105], [103, 104, 105, 106], [104, 105, 106, 107]]) I also have a 1D numpy array listing the vertical coordinates and another 1D numpy array listing the horizontal coordinates. x = np.array([10, 11, 12, 13]) y = np.array([20, 21, 22, 23, 24]) In some cases, this data is provided as a list of 'x y z' data e.g.: 10 20 100 10 21 101 10 22 102 10 23 103 10 24 104 11 20 101 11 21 102 ... 12 23 105 12 24 106 13 20 103 13 21 104 13 22 105 13 23 106 13 24 107 In this case creating a pivot table is trivial.... data = pd.read_csv(file, header=None, names=['x', 'y', 'z'], delim_whitespace=True) pvt = data.pivot_table(values='z', index='y', columns='x', fill_value=-100000) How can I create a pivot table with the same labels, format etc starting with the data in three arrays?
type: Question
tagged with: numpy
has title: Convert 2D numpy array into pandas pivot table
tagged with: arrays
answer count: 2
tagged with: pandas
downvote count: 0
favorite count: 0
upvote count: 2

http://stackoverflow.com/comment/90687186
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51867651
has text: It seems that when I tried to do this, I got this error about "labelTitleTextSize = labelTitleText.len()" and then the error message showed "AttributeError: 'str' object has no attribute 'len'". What should I do to fix?

http://stackoverflow.com/comment/90737883
comment on: http://stackoverflow.com/a/51893593
type: AnswerComment
has text: Or even anything that is valid code but doesn't evaluate to change anything
score: 0
type: Comment

http://stackoverflow.com/q/51813744
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51818291
upvote count: 2
tagged with: python
tagged with: pygame
has title: Skipping sound track (pygame.mixer.music)
accepted answer: http://stackoverflow.com/a/51818291
score: 2
type: AnsweredQuestion
type: Question
tagged with: mixer
has body: I am making a snake game with pygame and I want to know something about pygame.mixer.music(). Code: snakebodypos.insert(0, list(snakepos)) if snakepos[0] == foodpos[0] and snakepos[1] == foodpos[1]: pygame.mixer.music.stop() pygame.mixer.music.load(eatsound) pygame.mixer.music.play(1, 0.0) pygame.mixer.music.load(main) pygame.mixer.music.play(-1, 0.0) foodspawn = False score += 1 So, when I stop and the eatsound is supposed to play, it just skips it and plays the stopped sound again. KEEP IN MIND! When I use pause and unpause, it doesn't unpause again. I don't know why so I use the stop. If you know why that happens, please let me know.
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/90652763
comment on: http://stackoverflow.com/q/51834222
has text: Following https://askubuntu.com/questions/218919/i-accidentally-deleted-usr-bin-python-how-do-i-restore-it , I tried to run `sudo ln -s /usr/bin/python2.7 /usr/bin/python`. However, it returned an error `ln: failed to create symbolic link '/usr/bin/python': File exists`. I tried `nano python` which came up with `Error writing lock file ./.python.swp: Permission denied`. I tried to `rm /usr/bin/python` but this returned `rm: cannot remove '/usr/bin/python': Permission denied`. Any ideas please? I do have /usr/bin/python2.7 as a text file Thanks!
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51895617
has answer: http://stackoverflow.com/a/51895689
tagged with: dataframe
upvote count: 2
has body: I need help with an issue I have concerning the creation of a sequence. The sequence should be based on the value of ID_PROJET_test field that contains a bool which indicates whether we should increment or not. if ID_PROJET_test = False then increment if ID_PROJET_test = True then do not increment For instance, if ID_PROJET_test contains the following Series: s1 = [0,0,1,0,1,0] ID_PROJET should be equal to : [1,2,2,3,3,4] If ID_PROJET_test contains the following Series: s2 = [0,0,0,1,1,1,0,0] ID_PROJET should be equal to : [1,2,3,3,3,3,4,5] I can do it easily with a for loop : compteur = 1 for i in range(len(df)): if df['ID_PROJET_test']==True: df.ID_PROJET[i] = compteur else: compteur += 1 df.ID_PROJET[i] = compteur However, I have around 1.8M records and it is much too slow. Any idea on how to do it?
tagged with: pandas
downvote count: 0
answer count: 1
tagged with: sequence
favorite count: 0
type: UnansweredQuestion
tagged with: python
score: 2
has title: Pandas DF - Create incremental sequence based on a condition without for loop
type: Question

http://stackoverflow.com/a/51931827
score: 2
downvote count: 0
upvote count: 2
answers question: http://stackoverflow.com/q/51931804
type: Answer
has body: Try this: cap = df[df['Comune'] == 'AIRASCA']['cap']

http://stackoverflow.com/comment/90832633
has text: Thanks @RafaelC, I am just wondering for the first slice why it is not 15 min slice ? I want 15 min slice from the beginning of my timestep.
type: AnswerComment
comment on: http://stackoverflow.com/a/51940964
score: 0
type: Comment

http://stackoverflow.com/comment/90707743
type: QuestionComment
comment on: http://stackoverflow.com/q/51866785
score: 0
type: Comment
has text: i still get the same error and for now i'm using it in python shell from requests import * ip = get('https://api.ipify.org').text @BryanOakley

http://stackoverflow.com/comment/90774982
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51912284
has text: I don't know what the second half of that sentence means. Can you run `pip --version` and `python --version` and `python3 -m pip --version` and [edit] the result into your question?

http://stackoverflow.com/comment/90686519
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51865836
type: Comment
has text: thank you for the suggestions. sorry for bad operations.

http://stackoverflow.com/comment/90573308
type: QuestionComment
has text: If you just want to know whether the worker is close to a fence or not but don't care about the actual distance, you could give your fences a second, bigger rect and use that for the collision detection: https://stackoverflow.com/a/49829496/6220679
comment on: http://stackoverflow.com/q/51807787
score: 0
type: Comment

http://stackoverflow.com/comment/90702560
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51875279
type: AnswerComment
has text: i did :( no luck

http://stackoverflow.com/comment/90674659
comment on: http://stackoverflow.com/a/51861018
type: AnswerComment
score: 0
has text: You could simply delete the canvas and recreate also.
type: Comment

http://stackoverflow.com/a/70312196
answers question: http://stackoverflow.com/q/51870788
has body: Django 2.1 - 4.0 When creating an authentication backend it is best to follow the example of ModelBackend and run the default password hasher. The following backend will authenticate using emails as well as usernames. # backends.py from django.contrib.auth import get_user_model from django.contrib.auth.backends import ModelBackend from django.db.models import Q UserModel = get_user_model() class CustomModelBackend(ModelBackend): def authenticate(self, request, username=None, password=None, **kwargs): if username is None: username = kwargs.get(UserModel.USERNAME_FIELD, kwargs.get(UserModel.EMAIL_FIELD)) if username is None or password is None: return try: user = UserModel._default_manager.get( Q(username__exact=username) | Q(email__iexact=username) ) except UserModel.DoesNotExist: # Run the default password hasher once to reduce the timing # difference between an existing and a nonexistent user (#20760). UserModel().set_password(password) else: if user.check_password(password) and self.user_can_authenticate(user): return user Be sure to add your backend to settings.py # settings.py AUTHENTICATION_BACKENDS = ["path.to.backends.CustomModelBackend"]
upvote count: 1
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/q/51814567
answer count: 2
tagged with: sympy
accepted answer: http://stackoverflow.com/a/51814736
has comment: http://stackoverflow.com/comment/90583854
favorite count: 0
has title: Python How to get the value of one specific point of derivative?
tagged with: python
score: 2
has answer: http://stackoverflow.com/a/51814712
type: AnsweredQuestion
tagged with: lambdify
upvote count: 3
has body: from sympy import * x = Symbol('x') y = x ** 2 dx = diff(y, x) This code can get the derivative of y. It's easy dx = 2 * x Now I want to get the value of dx for x = 2. Clearly, dx = 2 * 2 = 4 when x = 2 But how can I realize this with python codes? Thanks for your help!
possible better answer: http://stackoverflow.com/a/51814712
downvote count: 1
has answer: http://stackoverflow.com/a/51814736
type: Question

http://stackoverflow.com/comment/90607202
score: 1
has text: You should also add the full error message.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51826422

http://stackoverflow.com/comment/90923875
has text: Yes, in fact it throttles me before 2500 limit a day and gives me same lat longs for all addresses once it throttles.
score: 0
comment on: http://stackoverflow.com/q/51902757
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/90819320
has text: The output is a list that consists of 3 sets {(B,D),(A,C)}, {(A,B)} and {(A,D)} and it's the same of your example. If it's not what you are looking for, I misread the question.
type: AnswerComment
comment on: http://stackoverflow.com/a/51934312
score: 0
type: Comment

http://stackoverflow.com/q/51920580
has answer: http://stackoverflow.com/a/51931560
score: 0
has comment: http://stackoverflow.com/comment/90807433
answer count: 2
tagged with: google-cloud-platform
has title: "StatusCode.DEADLINE_EXCEEDED" error while using bigtable.scan() function
has body: I have a millions of articles in bigtable and to scan 50,000 articles I have used something as : for key, data in mytable.scan(limit=50000): print (key,data) It works fine for limit upto 10000 but as I exceed the limit of 10000 I get this error _Rendezvous: &lt;_Rendezvous of RPC that terminated with (StatusCode.DEADLINE_EXCEEDED)
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90807215
tagged with: python
tagged with: google-cloud-bigtable
type: Question
has answer: http://stackoverflow.com/a/51931570

http://stackoverflow.com/a/52015702
answers question: http://stackoverflow.com/q/51943165
accepted answer of: http://stackoverflow.com/q/51943165
type: AcceptedAnswer
has body: You should use trapezoidal rule to approximate this integral. def get_mass_distribution(data): a = np.array(data) ag = st.gaussian_kde(a) denom_integral = trapezoidal(ag, 0, max(data), max(data)*10) Fm = [0] x = [] k = 0 while(k &lt; max(data)): x.append(k) k = k+1 for i in x[1:]: enum_integral = trapezoidal(ag, 0, i, i*10) Fm.append(enum_integral/denom_integral) return x, Fm def trapezoidal(ag, a, b, n): h = float(b - a) / n s = 0.0 s += a*ag(a)[0]/2.0 for i in range(1, n): s += (a + i*h)*ag(a + i*h)[0] s += b*ag(b)[0]/2.0 return s * h
score: 0
type: Answer

http://stackoverflow.com/comment/90847359
has text: Could you explain better the possibility you explain? I couldn't find anything about this except [writing data into a TFRecords](http://machinelearninguru.com/deep_learning/data_preparation/tfrecord/tfrecord.html) file in order to convert and prepare that data.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51868939
type: Comment

http://stackoverflow.com/q/51937851
tagged with: pytube
type: Question
has comment: http://stackoverflow.com/comment/90826340
tagged with: python
tagged with: audio
score: 0
has comment: http://stackoverflow.com/comment/90826493
has body: i'm trying to create a virtual assistant. One of the features i would like for my personal assistant to have is the ability to stream or download YouTube videos, in audio mp3 format. So for example, i would be able to say 'Play Hello by Adele' and it would play the audio of the song. I've got the whole virtual assistant part down, i'm just struggling on making it useful. I am creating the virtual assistant on my Raspberry pi using python. As you can see i have already started trying to code the whole music section, but i'm not able to figure out the YouTube par I hope some of what I've done so far has been useful from pytube import YouTube yt = YouTube("https://www.youtube.com/result?ssearch_query=Hello+by+Adele") t=yt.streams.filter(only_audio=True).all() t[0].download(path)
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90826279
has title: How to stream mp3 audio from YouTube using python only with name of song
answer count: 0

http://stackoverflow.com/a/68586691
score: -1
upvote count: 2
downvote count: 3
type: Answer
has body: I faced this issue when I updated my Mac OS version from Catalina to Big Sur. I was trying to run a binary and facing the Killed: 9 issue. I was able to resolve this issue by following the steps below (I referred to this Apple StackExchange post for these steps) :- Download UPX via Homebrew - brew install upx Then decompress the binary - upx -d /path/to/binary/file
answers question: http://stackoverflow.com/q/51833310

http://stackoverflow.com/a/52317022
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/51900138
score: 1
downvote count: 0
has body: Here's another strategy that approaches the problem in the opposite direction. I think this is a better approach for several reasons: The radar observation dataset is sparse, so to run calculations on every output point seems wasteful, even with the help of a spatial index. The output grid has regular spacing so it can be easily calculated. So it would be less work to look at every observation point and calculate which output points are nearby, and use that information to build a list of output points and which observation points they are close to. The observation data is in the form (X,Y,M) (longitude, latitude, measurement). The output is a grid with regular spacing, like every .1 degrees. First create a dictionary for your output grid points that are near to observations: output = {} Then take an observation point and find points nearby that are within the Great Circle distance. Start checking at a nearby output point and iterate your way outwards by row/column until you have found all the possible observation points within your GCD. This will give you a list of grid points that are within the GCD of X and Y. Something like: get_points(X,Y) ----&gt; [[x1, y1], [x2,y2]....] Now we'll flip this around. We want to store each output point and a list of the observation points that are near it. To store the point in the output dictionary we need some kind of unique key. A geohash (which interleaves latitude and longitude and generates a unique string) is perfect for this. For each output point (xn, yn) compute the geohash, and add an entry to the output dictionary with (xn, yn) and start (or append to) a list of observations: key = Geohash.encode(y,x) if key not in output: output[key] = { 'coords': [x, y], 'observations' = X,Y,M } else: output[key][observations].append([X,Y,M]) We store the original x,y instead of reversing the geohash and losing accuracy. When you have run all of your observations you will then have a dictionary of all the output points that requi…

http://stackoverflow.com/q/51859841
type: AnsweredQuestion
tagged with: list
has body: I have a dataframe with the following format: Timestamp X Y Name PlayerID 0 0 0.5 Albert 1 100 0 0.3 Albert 1 200 0 0.5 Albert 1 300 0 0.6 Albert 1 0 -22 4.8 Gregoire 2 100 -32 5 Gregoire 2 200 -11 3.4 Gregoire 2 300 -23 4.4 Gregoire 2 What I need, is a dictionary with the keys being the Unique Timestamp values and the values of the dictionary need to be a list of lists containing the items that belong to that timestamp. That means: {'0': [ ['0','0.5','Albert','1'], ['-22','4.8','Gregoire','2'] ] '100': [ ['0','0.3','Albert','1'], ['-32','5','Gregoire','2'] ] '200': [ ['0','0.5','Albert','1'], ['-11','3.4','Gregoire','2'] ] '300': [ ['0','0.6','Albert','1'], ['-23','4.4','Gregoire','2'] ] } I put the following code together but it only gives me a dictionary containing a the timestamps as keys and the values are a list of all the items that belong to that timestamp: df.set_index('Timestamp').stack().groupby('Timestamp').apply(list).to_dict() Output: {'0': ['0','0.5','Albert','1','-22','4.8','Gregoire','2'] '100': ['0','0.3','Albert','1','-32','5','Gregoire','2'] '200': ['0','0.5','Albert','1','-11','3.4','Gregoire','2'] '300': ['0','0.6','Albert','1','-23','4.4','Gregoire','2'] } Is there a way to do this? I am guessing that something can be changed on that line of code to create sublists instead of one list but I have not figured out how. Thanks for your help!
accepted answer: http://stackoverflow.com/a/51860108
score: 0
tagged with: dataframe
type: Question
answer count: 1
tagged with: pandas-groupby
has title: Python: Creating sublists based on group by result of data frame
has answer: http://stackoverflow.com/a/51860108
favorite count: 0
upvote count: 1
tagged with: python
tagged with: dictionary
downvote count: 1

http://stackoverflow.com/comment/90703578
comment on: http://stackoverflow.com/q/51812001
has text: Why is your expected model input size? (?, 2048) doesn't make too much sense. Tensorflow models usually expect data in NHCW format - (Batch, Height, Width, Channels). it doesn't make a lot of sense to have only 2 input dimensions. if we're speaking of a flattened array - make sure you know the input resolution. Note that it's not an RGB image, since 2048 is not divisible by 3.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51888789
favorite count: 0
score: 2
upvote count: 2
tagged with: python
type: AnsweredQuestion
has body: I have a list of lists with word tockens of the following type: [['java_developer'], ['ETL', 'database_administrator'], ... ['web-developer', 'c#', 'ms_sql']] Also I have a key-value pandas dataframe, where the first column key and the second one is value. E.g.: Key Value 0 java_developer java 1 web-developer web 2 database_administrator database 3 ETL ETL 4 ms_sql database ... ... ... 100 c# c# I want to receive a list of lists of the folowing type: [['java'], ['ETL', 'database'], ... ['web', 'c#', 'database']] How it can be implemented?
has title: If list of lists values are present in Pandas dataframe column replace them with values from another Pandas column
has answer: http://stackoverflow.com/a/51888822
type: Question
answer count: 1
downvote count: 0
tagged with: pandas
accepted answer: http://stackoverflow.com/a/51888822

http://stackoverflow.com/q/51830567
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90615689
possible better answer: http://stackoverflow.com/a/51830952
has comment: http://stackoverflow.com/comment/90615628
type: Question
answer count: 2
tagged with: dataframe
has title: How do I hide the index column in pandas dataframe?
score: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/51830952
has answer: http://stackoverflow.com/a/51830893
accepted answer: http://stackoverflow.com/a/51830893
tagged with: python-3.x
has body: How am I supposed to remove the index column in the first row. I know it is not counted as a column but when I transpose the data frame, it does not allow me to use my headers anymore. In[297] df = df.transpose() print(df) df = df.drop('RTM',1) df = df.drop('Requirements', 1) df = df.drop('Test Summary Report', 1) print(df) This throws me an error "labels ['RTM'] not contained in axis". RTM is contained in an axis and this works if I do index_col=0 df = xl.parse(sheet_name,header=1, index_col=0, usecols="A:E", nrows=6, index_col=None) but then I lose my (0,0) value "Artifact name" as a header. Any help will be appreciated.

http://stackoverflow.com/comment/90941306
score: 0
type: AnswerComment
has text: This got me there! The problem was that pygame does not like being outside the main thread, as that thread is not constantly reporting to the OS. Thank you!
type: Comment
comment on: http://stackoverflow.com/a/51995066

http://stackoverflow.com/comment/90639709
score: 0
comment on: http://stackoverflow.com/q/51843128
type: QuestionComment
type: Comment
has text: @9769953 I've reformat the long if-statement,thanks

http://stackoverflow.com/a/51892003
score: 14
upvote count: 14
has comment: http://stackoverflow.com/comment/90734918
has comment: http://stackoverflow.com/comment/130595017
accepted answer of: http://stackoverflow.com/q/51891951
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51891951
has body: You should be using: @exponential_backoff() def test(): ... The overall decorator is not designed to have arguments be optional, so you must provide () when using it. If want an example of how to make decorator allow argument list be optional, see: https://wrapt.readthedocs.io/en/latest/decorators.html#decorators-with-optional-arguments You might also consider using the wrapt package to make your decorators easier and more robust.
type: Answer
downvote count: 0

http://stackoverflow.com/q/51878371
has answer: http://stackoverflow.com/a/51879612
has comment: http://stackoverflow.com/comment/90852569
tagged with: python
has title: Multi-threading on python for running 2 inter-related threads simultaneously (or may be background processing)
type: UnansweredQuestion
tagged with: multithreading
upvote count: 1
tagged with: parallel-processing
tagged with: opencv
score: 1
has comment: http://stackoverflow.com/comment/90709470
tagged with: multiprocessing
type: Question
has comment: http://stackoverflow.com/comment/90775499
has comment: http://stackoverflow.com/comment/90872975
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/90710602
has body: I want VideoCapture function from opencv to work smoothly while processing frames from it in background. As processing requires 3-4 seconds so at that time capturing video hangs. Hence, I need to run 2 threads, i.e., one capturing video and other processing its output and printing on screen. My code till now: age = None while True: ret, frame = cam.read() if ret == True: # do some processing (3-4 seconds) age = process(frame) fr = update_age(frame, age) cv2.imshow('hello', fr) if cv2.waitKey(1) == 27: break else: print "error" break cv2.destroyAllWindows() Hence, I need a way so that my 3rd line don't have to wait 3-4 seconds to update its frame, while processing frames and printing its output runs in background. More Clarifications(mentioned in comments also): I don't want to separate my threads, as one thread depends on output (frame) of other thread.I just want to run my threads separately I am showing all frames on my screen using cv2.imshow(). Hence, I need every frame captured to let my screen look smooth (and not just hang on after every 4 seconds). And output of processing is shown on screen, i.e., once a output is generated it will remain there until next output is generated after 4 seconds. (It's like a person looking in camera and his age is showing on screen but if is updating after 4 seconds)
has comment: http://stackoverflow.com/comment/90785165

http://stackoverflow.com/comment/90698655
has text: Kindly show what you have done
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51873491

http://stackoverflow.com/comment/90725587
type: QuestionComment
comment on: http://stackoverflow.com/q/51887086
score: 1
has text: `self.score_image` uses `score_image` as an attribute of `Scoreboard`. The fact that it is not an attribute (as you wrote) is exactly what Python is complaining about.
type: Comment

http://stackoverflow.com/q/51919931
downvote count: 0
has comment: http://stackoverflow.com/comment/90789626
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51920017
tagged with: python
tagged with: regex-group
tagged with: regex
type: AnsweredQuestion
score: 1
has body: I have an url: http://200.73.81.212/.CREDIT-UNION/update.php None of reg expressions I've found and develop myself works. I'm working on phishing mails dataset and there are lots of strange hyperlinks. This is one of mine: https?:\/\/([a-zA-z0-9]+.)+)|(www.[a-zA-Z0-9]+.([a-zA-Z0-9]+\.[a-zA-Z0-9]+)+)(((/[\.A-Za-z0-9]+))+/?. Of course no success. I work in Python. EDIT: I need a regex to catch this kind of url's and, also, any ordinary hyperlinks, like: https://cnn.com/ www.foxnews.com/story/122345678 Any thoughts?
upvote count: 1
tagged with: http
type: Question
accepted answer: http://stackoverflow.com/a/51920017
possible better answer: http://stackoverflow.com/a/52027694
answer count: 2
has title: Regex to Catch Url
has answer: http://stackoverflow.com/a/52027694

http://stackoverflow.com/a/64326506
answers question: http://stackoverflow.com/q/51933830
type: Answer
has body: I just wanted to add that, even in Python, you can get a for in effect using a classic C style loop by just using a local variable l = len(mylist) #I often need to use this more than once anyways for n in range(l-1): i = mylist[n] print("iterator:",n, " item:",i)
score: 0

http://stackoverflow.com/a/77398249
answers question: http://stackoverflow.com/q/51811263
type: Answer
has body: For some reason, pip install was not working for me within my conda environment. My pip would always download the x86 version instead of the arm64 version for my M1 Mac. Instead I pip uninstalled gymnasium and box2d-py and then conda installed them both from conda forge: conda install -c conda-forge box2d-py conda install -c conda-forge gymnasium After this it worked great and was able to import.
score: 0

http://stackoverflow.com/a/51911535
score: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51911515
upvote count: 2
type: AcceptedAnswer
has body: You lack one more slicing on your list comprehension: rowRef[x:] = [a + 1 for a in rowRef[x:]] Otherwise, you are iterating through the whole list instead of the remaining list to process each time. Here you have the live example
type: Answer
answers question: http://stackoverflow.com/q/51911515

http://stackoverflow.com/comment/90849292
has text: Thank you - didn't know this existed!
type: Comment
comment on: http://stackoverflow.com/a/51949274
type: AnswerComment
score: 0

http://stackoverflow.com/comment/90763623
type: Comment
has text: the parameter `rotation=45` is not at the good place
comment on: http://stackoverflow.com/q/51906522
score: 0
type: QuestionComment

http://stackoverflow.com/a/51877989
score: 1
answers question: http://stackoverflow.com/q/51877728
upvote count: 1
has body: There are two possible solutions in my opinion: First, create two lists as the upper and lower bounds and use fill_between. The reason you can't multiply directly by 0.9 and 1.1 is because zip returns tuple. Even if you convert it to a list using list(ref_y), you can't multiply each element of a list by an integer/float all at once unlike with arrays: lim_down = [0.9*i for i in ref_y] lim_up = [1.1*i for i in ref_y] plt.fill_between(ref_x, lim_down, lim_up) Second, you convert your y-values to arrays which allows you to simply multiply them by 0.9 and 1.1 which will be applied to each element. plt.fill_between(ref_x, np.array(ref_y) * 0.9, np.array(ref_y) * 1.1) Output (The res is now covered by your error bars/filled region because 10% seems to be too much in this case.):
downvote count: 0
type: Answer

http://stackoverflow.com/q/51863621
type: UnansweredQuestion
tagged with: python
tagged with: queue
type: Question
tagged with: multiprocessing
tagged with: resources
has title: Use a multiprocessing.Queue in luigi
has body: I have a set of tasks in luigi which all need to access a database. I can have up to 8 tasks accessing my database at the same time provided they are on different ports (I have the list of allowed ports). How should I best implement this restriction which seems to be similar to the standard restriction of number of workers, ie for my case a task should run when a worker is free AND a database port is free. I tried creating a multiprocessing.Queue() in __main__ and pass this to the WrapperTask, which receives it as a luigi.Parameter(), but this gives an error and hangs UserWarning: Parameter "queue" with value &lt;multiprocessing.queues.Queue object at 0x00000000149E4518&gt;" is not of type string. warnings.warn('Parameter "{}" with value "{}" is not of type string.'.format(param_name, param_value)) The idea was that a .get() call would hang a Task if the queue is empty and continue once another task .put(port) again. What is going wrong here? Or am I taking the completely wrong approach to managing the resource in luigi?
score: 0
tagged with: luigi
answer count: 1
has answer: http://stackoverflow.com/a/51900464

http://stackoverflow.com/comment/90654502
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51848913
has text: @DSM it all works out as far as i can tell . . . say n_pre = 80, n_post = 10, p = 0.2 . . . then each of the 10 receives 16 connections . . . each of the 80 sends out 2 connections . . . the total in-degree is 10 * 16 = 160, the total out-degree is 2 * 80 = 160 . . . and the proportion of all possible edges is 160 / 800 = 0.2.
score: 0

http://stackoverflow.com/a/51883467
type: Answer
score: 2
upvote count: 2
has body: You can use map in this situtaion: df2['Team Total Diff'] = df2['Team'].map(df1.set_index('Team')['Team Total Diff']) df2 Output: Team Region Curr Sales Prev Sales Net Diff Team Total Diff 0 Blue East 4 4 0 5 1 Blue West 6 1 5 5 2 Orange East 6 3 3 12 3 Orange West 14 5 9 12 4 Yellow East 15 3 12 29 5 Yellow West 25 8 17 29
accepted answer of: http://stackoverflow.com/q/51883057
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51883057
downvote count: 0

http://stackoverflow.com/comment/90653677
score: 0
type: AnswerComment
has text: I have made the recommended changes that you suggested. I am getting below error. ValueError: Expecting property name: line 1 column 2 (char 1)
type: Comment
comment on: http://stackoverflow.com/a/51849915

http://stackoverflow.com/comment/90830947
type: Comment
has text: Well, you can probably circumvent this whole problem by specifying `thousands=','` in whatever `pd.read_` function you are using, and your numbers will be read in properly as floats, or ints.
type: QuestionComment
comment on: http://stackoverflow.com/q/51939744
score: 0

http://stackoverflow.com/a/51835319
has comment: http://stackoverflow.com/comment/90997365
downvote count: 0
has body: There are many formulas for the Luminance, depending on the R,G,B color primaries: Rec.601/NTSC: Y = 0.299*R + 0.587*G + 0.114*B , Rec.709/EBU: Y = 0.213*R + 0.715*G + 0.072*B , Rec.2020/UHD: Y = 0.263*R + 0.678*G + 0.059*B . This is all because our eyes are less sensitive to blue than to red than to green. That being said, you are probably calculating Luma, not Luminance, so the formulas are all wrong anyway. For Constant-Luminance you must convert to linear-light R = R' ^ 2.4 , G = G' ^ 2.4 , B = B' ^ 2.4 , apply the Luminance formula, and convert back to the gamma domain Y' = Y ^ (1/2.4) . Also, consider that converting a 3D color space to a 1D quantity loses 2/3 of the information, which can bite you in the next processing steps. Depending on the problem, sometimes a different formula is better, like V = MAX(R,G,B) (from HSV color space). How do I know? I'm a follower and friend of Dr. Poynton.
score: 8
upvote count: 8
type: Answer
answers question: http://stackoverflow.com/q/51818193
has comment: http://stackoverflow.com/comment/90997403
has comment: http://stackoverflow.com/comment/90883830

http://stackoverflow.com/q/51886795
has body: dear friends! I'm supposed to use a MGRS-library but I'm stuck on this issue: import mgrs m = mgrs.MGRS() d = m.toLatLon('15TWG0000049776') print(d) The console says: mgrs.core.RTreeError: Error in "Convert_MGRS_To_Geodetic": MGRS Errors: String Error
answer count: 1
downvote count: 0
tagged with: string
favorite count: 0
has title: MGRS Errors: String Error
tagged with: python
type: UnansweredQuestion
upvote count: 1
has answer: http://stackoverflow.com/a/54384082
has comment: http://stackoverflow.com/comment/90741985
score: 1
type: Question

http://stackoverflow.com/q/51904251
tagged with: python
tagged with: nlp
has title: Does the TfidfVectorizer implicitly threshold its fitted output for large datasets?
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90761801
upvote count: 2
score: 1
has answer: http://stackoverflow.com/a/51910110
tagged with: machine-learning
downvote count: 1
has comment: http://stackoverflow.com/comment/90770330
type: Question
has comment: http://stackoverflow.com/comment/90769799
accepted answer: http://stackoverflow.com/a/51910110
has body: I'm trying to use sklearn's TfidfVectorizer to output tf-idf scores for a list of inputs, comprised of both unigrams and bigrams. Here's the essence of what I'm doing: comprehensive_ngrams = comprehensive_unigrams + comprehensive_bigrams # List of unigrams and bigrams(comprehensive_unigrams and comprehensive_bigrams are lists in their own right) print("Length of input list: ", len(comprehensive_ngrams)) vectorizer = TfidfVectorizer(ngram_range = (1,2), lowercase = True) vectorizer.fit(comprehensive_ngrams) vocab = vectorizer.vocabulary_ print("Length of learned vocabulary: ", len(vocab)) term_document_matrix = vec.toarray() print("Term document matrix shape is: ", term_document_matrix.shape) This snippet outputs the following: Length of input list: 12333 Length of learned vocabulary: 6196 Term document matrix shape is: (12333, 6196) The length of the dictionary mapping input elements to positional indices emitted by the TfidfVectorizer is shorter than the number of unique inputs it's fed. This doesn't seem to be a problem for smaller datasets (on the order of ~50 elements) - the size of the dictionary the TfidfVectorizer produces once it has been fitted equals the size of the input. What am I missing?
has comment: http://stackoverflow.com/comment/90770292
has comment: http://stackoverflow.com/comment/90773238
answer count: 1
tagged with: scikit-learn
favorite count: 0
tagged with: tf-idf

http://stackoverflow.com/q/51829185
type: Question
has body: I want to import models to dashboards.py file that is in the same folder as models.py: #dashboards.py from models import Listing, City Running the file results in: Traceback (most recent call last): File "dashboards.py", line 6, in &lt;module&gt; from models import Listing, City #, ScrapingDate File "/home/bart/python_projects/javascript/models.py", line 19, in &lt;module&gt; class City(models.Model): File "/home/bart/python_projects/testenv/lib/python3.5/site-packages/django/db/models/base.py", line 100, in __new__ app_config = apps.get_containing_app_config(module) File "/home/bart/python_projects/testenv/lib/python3.5/site-packages/django/apps/registry.py", line 244, in get_containing_app_config self.check_apps_ready() File "/home/bart/python_projects/testenv/lib/python3.5/site-packages/django/apps/registry.py", line 127, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. If I change to: #dashboards.py from .models import Listing, City I get: Traceback (most recent call last): File "dashboards.py", line 6, in &lt;module&gt; from .models import Listing, City #, ScrapingDate SystemError: Parent module '' not loaded, cannot perform relative import I have also tried: #dashboards.py import django django.setup() from models import Listing, City but: Traceback (most recent call last): File "dashboards.py", line 2, in &lt;module&gt; django.setup() File "/home/bart/python_projects/testenv/lib/python3.5/site-packages/django/__init__.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/home/bart/python_projects/testenv/lib/python3.5/site-packages/django/conf/__init__.py", line 56, in __getattr__ self._setup(name) File "/home/bart/python_projects/testenv/lib/python3.5/site-packages/django/conf/__init__.py", line 41, in _setup % (desc, ENVIRONMENT_VARIABLE)) django.core.exceptions.ImproperlyConfigured: Requested setting LOGGING_CONFIG, but settings a…
has comment: http://stackoverflow.com/comment/90615225
has comment: http://stackoverflow.com/comment/90613292
has title: How to import models to a file that resides in the same folder as models.py?
tagged with: python
has comment: http://stackoverflow.com/comment/90612829
answer count: 0
type: UnansweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/90613129
tagged with: django
has comment: http://stackoverflow.com/comment/90612900

http://stackoverflow.com/q/51872501
answer count: 1
favorite count: 0
has title: Lat/long indexing in 2d array
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51977816
tagged with: python
tagged with: netcdf
has body: I have a .nc file where latitude and longitude are in 2d array. I want to extract the values for certain known points. I did not find the way to find the index for that known points. data structure looks like: OrderedDict([(u'lon', &lt;type 'netCDF4._netCDF4.Variable'&gt; float32 lon(y, x) standard_name: longitude long_name: longitude units: degrees_east _CoordinateAxisType: Lon unlimited dimensions: current shape = (146, 209) filling off), (u'lat', &lt;type 'netCDF4._netCDF4.Variable'&gt; float32 lat(y, x) standard_name: latitude long_name: latitude units: degrees_north _CoordinateAxisType: Lat unlimited dimensions: current shape = (146, 209) filling off), (u'time', &lt;type 'netCDF4._netCDF4.Variable'&gt; float64 time(time) standard_name: time units: seconds since 1949-12-1 00:00:00 calendar: proleptic_gregorian axis: T unlimited dimensions: time current shape = (55152,) filling off), (u'TOT_PREC', &lt;type 'netCDF4._netCDF4.Variable'&gt; float32 TOT_PREC(time, y, x) standard_name: precipitation_amount long_name: total precipitation amount units: kg m-2 coordinates: lat lon cell_methods: time: sum unlimited dimensions: time current shape = (55152, 146, 209) filling off)]) Suppose I want to extract the values to the points whose coordinates are: lat=27.25, lon=85.75 then how to get the lat and long index for those coordinates?
upvote count: 1
downvote count: 1
type: Question
tagged with: python-xarray
score: 0

http://stackoverflow.com/comment/97546214
has text: @ItayGabbay did you find a way to do it? :)
type: QuestionComment
comment on: http://stackoverflow.com/q/51820891
score: 0
type: Comment

http://stackoverflow.com/comment/90823703
type: QuestionComment
comment on: http://stackoverflow.com/q/51936698
score: 0
has text: so it works okay now? @JellicleCat
type: Comment

http://stackoverflow.com/q/51901488
has title: TypeError: integer argument expected, got float with apply()
tagged with: typeerror
type: UnansweredQuestion
tagged with: datetime
tagged with: python
has comment: http://stackoverflow.com/comment/90755518
answer count: 0
has body: I try, closure2['NEXT_PERF_DT'] = closure2['perf_dt'].apply(lambda x: dt.datetime((x.year)+(x.month/12), (x.month%12)+1,1)) But I get, TypeError: integer argument expected, got float Closure2 has only 2 columns: perf_dt 10002 non-null datetime64[ns] unknown_exit 10002 non-null int64 Does anyone know what I'm doing wrong?
type: Question
has comment: http://stackoverflow.com/comment/90819076
score: 0

http://stackoverflow.com/comment/90857802
type: QuestionComment
comment on: http://stackoverflow.com/q/51953659
score: 1
has text: Having `indent=4` will always indent all containers with 4 spaces. You can't get the same formatting as in your original file out of the box with `json` from the standard library.
type: Comment

http://stackoverflow.com/q/51875906
has comment: http://stackoverflow.com/comment/90703464
favorite count: 0
answer count: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/2077870
upvote count: 1
tagged with: python
has body: I am trying to call a C# dll in python. I used these 2 approaches: link1 link2 But i am not able to use this line: import clr clr.AddReference('MyDll') from MyNamespace import MyClass my_instance = MyClass() But I get an error: in this line: from MyNamespace import MyClass cannot import name MyClass Does anybody now why?
score: 1
type: Question
tagged with: c#
downvote count: 0
has title: How to load a C# dll in python? - Error
linked to: http://stackoverflow.com/q/7367976
has comment: http://stackoverflow.com/comment/90712375

http://stackoverflow.com/comment/90641821
comment on: http://stackoverflow.com/q/51844209
type: Comment
type: QuestionComment
has text: Specifically, do you know what `set` and `list` do?
score: 1

http://stackoverflow.com/comment/90619515
comment on: http://stackoverflow.com/q/51832272
type: QuestionComment
type: Comment
has text: You can only use a dict with the python side (jwt.encode only accepts dicts) - but for the Ruby side that function accepts a dict or a JSON string - both do not match.
score: 0

http://stackoverflow.com/comment/90649229
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51847649
has text: Perfect, just like as I had expected. Thank you @Netwave!

http://stackoverflow.com/q/51821919
tagged with: actions-on-google
has title: How to send push notification from google assistant through Dialogflow fulfilment in Python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51961677
has comment: http://stackoverflow.com/comment/90621796
downvote count: 0
score: 1
tagged with: dialogflow-es
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/51938897
upvote count: 1
has answer: http://stackoverflow.com/a/51938897
favorite count: 0
accepted answer: http://stackoverflow.com/a/51961677
has comment: http://stackoverflow.com/comment/90617115
has body: I'm developing chatbot in google Dialogflow for google assistance, I've followed this Documentation for showing Push notifications. I've asked for the permission but now I'm stuck at the last step(Exchange the key for an access token and send a notification) in that documentation. Can anybody please help me to do it. Which JSON response should I send from my Python fulfillment code?
tagged with: python

http://stackoverflow.com/comment/110656534
type: QuestionComment
comment on: http://stackoverflow.com/q/51879904
has text: Hi @ModestasJurčius, did you find the reason why this happens? I am getting same speed on K80 and V100 while training YoloV3 keras implementation on my dataset.
score: 0
type: Comment

http://stackoverflow.com/comment/90747227
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51898073
has text: For `L =[1,2,3,4,6,7,10]`, your code gives the output as `{10}`. That's not what the OP wants. Change the order of subtraction

http://stackoverflow.com/a/51904036
accepted answer of: http://stackoverflow.com/q/51881148
score: 5
type: AcceptedAnswer
downvote count: 0
has body: @Josef is correct and you did the right thing with: mod1 = UnobservedComponents(np.zeros(y_post), 'llevel', exog=X_post) mod1.simulate(f_model.params, len(X_post)) The simulate method simulates data according to the model in question, which is why you can't directly use trained_model to simulate when you have exogenous variables. But for some reason the simulations always ended up being lower than y_post. I think this should be expected - running your example and looking at the estimated coefficients, we get: coef std err z P>|z| [0.025 0.975] ------------------------------------------------------------------------------------ sigma2.irregular 0.9278 0.194 4.794 0.000 0.548 1.307 sigma2.level 0.0021 0.008 0.270 0.787 -0.013 0.018 beta.x1 1.1882 0.058 20.347 0.000 1.074 1.303 The variance of the level is very small, which means that it is extremely unlikely that the level would shift upwards by nearly 10 percent in a single period, based on the model you specified. When you used: mod1.simulate(f_model.params, len(X_post), initial_state=0, state_shocks=np.random.normal(size=len(X_post)) what happened is that the level term is the only unobserved state here, and by providing your own shocks with a variance equal to 1, you essentially overrode the level variance actually estimated by the model. I don't think that setting the initial state to 0 has much of an effect here. (see edit). You write: the p-value computation was closer, but still is not correct. I'm not sure what this means - why would you expect the model to think such a jump was a likely occurrence? What p-value are you expecting to achieve? Edit: Thanks for investigating further (in Edit 2). First, what I think you should do is: mod1 = UnobservedComponents(np.zeros(y_post), 'llevel', exog=X_post) initial_state = np.random.multivariate_normal( f_model.predicted_state[..., -1], f_model.predicted_state_cov[..., -1]) mod1.simulate(f_model.params, len(X_post), initial_state=initial_state) Now, the explanation: In…
has comment: http://stackoverflow.com/comment/91262799
type: Answer
answers question: http://stackoverflow.com/q/51881148
has comment: http://stackoverflow.com/comment/90769922
has comment: http://stackoverflow.com/comment/91261712
upvote count: 5

http://stackoverflow.com/q/51826942
tagged with: folium
favorite count: 0
has comment: http://stackoverflow.com/comment/97283328
type: UnansweredQuestion
upvote count: 1
tagged with: python
tagged with: maps
score: 1
has body: I have a program that displays were people are; sometimes two people are exactly at the same point since we rely not on GPS signal but on places. So, in folium, when I add two markers to the same point, it overrides the past one completely, so I can't view the popup of the previous marker nor know about the existence of it. So, is there a way to add multiple markers at the same point while still being able to view the two markers and their popups?
type: Question
has title: Folium: Can I add multiple markers to the same geographical point?
downvote count: 0
has answer: http://stackoverflow.com/a/56859322
tagged with: data-visualization
answer count: 1

http://stackoverflow.com/comment/90838548
comment on: http://stackoverflow.com/a/51942808
score: 0
type: AnswerComment
has text: I have edited my original question adding the output format.
type: Comment

http://stackoverflow.com/q/51924533
accepted answer: http://stackoverflow.com/a/51924545
score: 0
tagged with: pandas
upvote count: 1
answer count: 1
has title: How can I use filter in Pandas when I want to filter only partial values in column using python pandas?
has answer: http://stackoverflow.com/a/51924545
favorite count: 0
tagged with: python
type: AnsweredQuestion
downvote count: 1
type: Question
has body: I want to filter on Timeline column only "Jan". Timeline Goods Price Jan-2018 Sugar 100 Jan-2017 Wheat 150 Feb- 2018 Sugar 120 Feb-2017 Sugar 125 Output: Timeline Goods Price Jan-2018 Sugar 100 Jan-2017 Wheat 150

http://stackoverflow.com/a/51923435
upvote count: 1
answers question: http://stackoverflow.com/q/51919653
type: Answer
has body: Firstly, you should use InlineKeyboardMarkup instead of ReplyKeyboardMarkup to craete the markup object made of InlineKeyboardButtons. Then, you probably should simply use the bot object to send the message with bot.send_message(query.message.chat_id, 'TEST', reply_markup=reply_markup). Lastly, if you really really need to use requests to do manual HTTP request, you should provide the parameters in the requests.post()'s data. import json import requests from telegram import InlineKeyboardButton, InlineKeyboardMarkup keyboard = [[InlineKeyboardButton("Выполнено", callback_data='Done')], [InlineKeyboardButton("MAC", callback_data='MAC'), InlineKeyboardButton("Phone", callback_data='Phone'), InlineKeyboardButton("История", callback_data='History')]] reply_markup = InlineKeyboardMarkup(keyboard) data = {"chat_id": query.message.chat_id, "text": "TEST", "reply_markup": json.dumps(reply_markup.to_dict())} requests.post(url='https://api.telegram.org/bot{blah}/sendMessage', data=data)
downvote count: 0
score: 1

google-chrome
tags question: http://stackoverflow.com/q/51799251
tags question: http://stackoverflow.com/q/51941841
tags question: http://stackoverflow.com/q/51892846
type: Tag
tags question: http://stackoverflow.com/q/51927757
tags question: http://stackoverflow.com/q/51802268
tag name: google-chrome

http://stackoverflow.com/q/51802063
tagged with: python
type: AnsweredQuestion
upvote count: 0
has comment: http://stackoverflow.com/comment/90560523
tagged with: classification
downvote count: 3
has comment: http://stackoverflow.com/comment/90560481
tagged with: machine-learning
type: Question
has comment: http://stackoverflow.com/comment/90563206
has comment: http://stackoverflow.com/comment/90560533
answer count: 1
has answer: http://stackoverflow.com/a/51808989
accepted answer: http://stackoverflow.com/a/51808989
favorite count: 0
tagged with: supervised-learning
has body: I have a training feature set consisting of 92 features. Out of which 91 features are boolean values of 1 or 0. But 1 feature is numerical and it varies from 3-2000. Will it be better if I do feature scaling on my 92nd feature? If yes, what are the best possible ways to do it? I am using Python.
score: -3
has title: When should I do feature scaling or normalisation in machine learning?

http://stackoverflow.com/comment/90812839
has text: yes I am. and I am using markdown and this piece of code is in my private extension.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51929779
type: Comment

http://stackoverflow.com/comment/90747309
type: Comment
comment on: http://stackoverflow.com/a/51897764
has text: I'll check this way. Thanks!
type: AnswerComment
score: 0

http://stackoverflow.com/comment/90796901
type: Comment
score: 0
comment on: http://stackoverflow.com/a/51920167
type: AnswerComment
has text: I just found out that `cv2.namedWindow(" ", cv2.WINDOW_GUI_NORMAL)` does the job but it still keeps the title bar

http://stackoverflow.com/q/51829373
score: 1
type: Question
has title: PyFMI: Restart coupled simulation from result file
has answer: http://stackoverflow.com/a/52243655
accepted answer: http://stackoverflow.com/a/52243655
upvote count: 1
answer count: 1
favorite count: 0
tagged with: python
downvote count: 0
tagged with: modelica
type: AnsweredQuestion
has body: I am using PyFMI to simulate a coupled simulation of two FMUs (Control.fmu and Plant.fmu) as shown below. import matplotlib.pyplot as plt from pyfmi import load_fmu fmu_control = load_fmu('Control.fmu'); fmu_plant = load_fmu('Plant.fmu') # List models models = [fmu_control, fmu_plant] # Set up connections between models connections = [(fmu_control, 'y1', fmu_plant, 'u1'), (fmu_control, 'y2', fmu_plant, 'u2'), (fmu_plant, 'y1', fmu_control, 'u1'), (fmu_plant, 'y2', fmu_control, 'u2')] # Create coupled co-simulation object from pyfmi.master import Master coupled_simulation = Master(models, connections) opts = coupled_simulation.simulate_options() opts['step_size'] = 0.01; opts['linear_correction'] = False opts['block_initialization'] = True; opts['initialize'] = False coupled_simulation.initialize(start_time = 0.0, final_time = 0.01, opts = opts) res = coupled_simulation.simulate(options=opts, final_time = 1.0) Plant_u1 = res[fmu_plant]['u1']; Plant_u2 = res[fmu_plant]['u2'] Plant_y1 = res[fmu_plant]['y1']; Plant_y2 = res[fmu_plant]['y2'] time = res[fmu_plant]['time'] Is there a way to implement a restart capability in the simulation? I would like to load the result files and use them to continue a simulation (i.e., start from where I left off in the previous step). I have been reading result files using: from pyfmi.common.io import ResultDymolaTextual res_control = ResultDymolaTextual('Control_0_result.txt') res_plant = ResultDymolaTextual('Plant_1_result.txt') but I don't know how to define those results as initial conditions of my next simulation step.

http://stackoverflow.com/comment/90810304
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51929643
has text: I tried the package and It worked as expected. Is it possible to re-produce the error?
score: 0

http://stackoverflow.com/a/51835809
has body: One solution using recursion: def get_keys(d:dict): out = [] for key, value in d.items(): if isinstance(value, dict): lst = get_keys(value) out.append([key]+lst[0] if isinstance(lst[0], list) else [key] + lst) else: out.append(key) return out d = {'apple':7,'ball':9,'src':{'dst':6},'svr':{'pre':{'ere':0}}} print(get_keys(d)) Output: ['apple', 'ball', ['src', 'dst'], ['svr', 'pre', 'ere']]
type: Answer
answers question: http://stackoverflow.com/q/51835481
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/q/51897851
possible better answer: http://stackoverflow.com/a/51898075
type: Question
has comment: http://stackoverflow.com/comment/90746752
has answer: http://stackoverflow.com/a/51898075
has title: How to get the method name of a decorated property method?
answer count: 3
has answer: http://stackoverflow.com/a/51898469
tagged with: python
has comment: http://stackoverflow.com/comment/90746794
has body: Lets say I have a method which I decorate with @property. Is there a way to get the underlying name of the decorated method? How could I for instance print the name of the property when it does not have a __name__ attribute? I'm trying to do a RPC call and everything works for methods and static functions but not this.
favorite count: 0
accepted answer: http://stackoverflow.com/a/51898469
upvote count: 2
has answer: http://stackoverflow.com/a/51898181
downvote count: 1
type: AnsweredQuestion
score: 1

http://stackoverflow.com/a/51839296
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/51838583
score: 2
downvote count: 0
has body: The problem is that the shape of x_train is (8982, 3000) so it means that (considering the preprocessing stage) there are 8982 sentences encoded as one-hot vectors with vocab size of 3000. On the other hand a GRU (or LSTM) layer accepts a sequence as input and therefore its input shape should be (batch_size, num_timesteps or sequence_length, feature_size). Currently the features you have are the presence (1) or absence (0) of a particular word in a sentence. So to make it work with GRU you need to add a third dimension to x_train and x_test: x_train = np.expand_dims(x_train, axis=-1) x_test = np.expand_dims(x_test, axis=-1) and then remove that return_sequences=True and change the input shape of GRU to input_shape=(3000,1). This way you are telling the GRU layer that you are processing sequences of length 3000 where each element consists of one single feature. (As a side note I think you should pass the vocab_size to num_words argument of Tokenizer. That indicates the number of words in vocabulary. Instead, pass max_length to maxlen argument of load_data which limits the length of a sentence.) However, I think you may get better results if you use an Embedding layer as the first layer and before the GRU layer. That's because currently the way you encode sentences does not take into account the order of words in a sentence (it just cares about their existence). Therefore, feeding GRU or LSTM layers, which relies on the order of elements in a sequence, with this representation does not make sense.
answers question: http://stackoverflow.com/q/51838583
upvote count: 2

http://stackoverflow.com/q/51911751
favorite count: 0
type: Question
tagged with: python
tagged with: artificial-intelligence
accepted answer: http://stackoverflow.com/a/51911873
upvote count: 3
has title: Using keras api for a multiple output model with the same target value
tagged with: machine-learning
answer count: 1
has body: In the case of multi-input or multi-output models according to https://keras.io/models/model/, one can use model = Model(inputs=a1, outputs=[b1, b2]) What if b1 and b2 are actually identical target values? I.e. After few initial layers, model has two independent "branches" and each should give the same value. Below is very simplified example a = Input(shape=(32,)) b1 = Dense(32)(a) b2 = Dense(32)(a) model = Model(inputs=a, outputs=[b1,b2]) Is there a nicer/better way of doing fit than duplicating target values? model.fit(x_train, [y_train, y_train]) Additionaly, if true labels (y_train) are needed during fit (only), one can use them like this model.fit([x_train,y_train], [y_train, y_train]) Is there any better solution? Also, what to do with the prediction? model.predict([x_test, y_test_fake_labels])
has answer: http://stackoverflow.com/a/51911873
type: AnsweredQuestion
score: 3
downvote count: 0
tagged with: keras

http://stackoverflow.com/a/51827795
upvote count: 1
has body: You can use pattern: (?&lt;=[a-z])\/(?=[a-z]) (?&lt;=[a-z]) Positive lookbehind for letter. \/ Match a /. (?=[a-z]) Positive lookahead for letter. Replacing matched / with empty string in re.sub. In Python: import re string = ['a/b','a//b','a///b'] print(re.sub(r'(?&lt;=[a-z])\/(?=[a-z])',r' ',str(string))) Prints: ['a b', 'a//b', 'a///b']
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51827710
score: 1

web-scraping
tags question: http://stackoverflow.com/q/51849020
tags question: http://stackoverflow.com/q/51917267
tags question: http://stackoverflow.com/q/51888636
tags question: http://stackoverflow.com/q/51861871
tags question: http://stackoverflow.com/q/51915537
tags question: http://stackoverflow.com/q/51913365
tags question: http://stackoverflow.com/q/51925830
tags question: http://stackoverflow.com/q/51832438
tags question: http://stackoverflow.com/q/51897756
tags question: http://stackoverflow.com/q/51807477
tags question: http://stackoverflow.com/q/51952658
tags question: http://stackoverflow.com/q/51861443
tags question: http://stackoverflow.com/q/51804725
tags question: http://stackoverflow.com/q/51922410
tags question: http://stackoverflow.com/q/51858647
tags question: http://stackoverflow.com/q/51873598
tags question: http://stackoverflow.com/q/51933112
tags question: http://stackoverflow.com/q/51850632
tags question: http://stackoverflow.com/q/51853060
tags question: http://stackoverflow.com/q/51896615
tags question: http://stackoverflow.com/q/51807299
tags question: http://stackoverflow.com/q/51860069
tags question: http://stackoverflow.com/q/51913874
tags question: http://stackoverflow.com/q/51861326
tags question: http://stackoverflow.com/q/51929133
tags question: http://stackoverflow.com/q/51869675
tags question: http://stackoverflow.com/q/51903385
tags question: http://stackoverflow.com/q/51875020
tags question: http://stackoverflow.com/q/51826131
tags question: http://stackoverflow.com/q/51920961
tags question: http://stackoverflow.com/q/51840397
tags question: http://stackoverflow.com/q/51913904
tags question: http://stackoverflow.com/q/51825077
tags question: http://stackoverflow.com/q/51823251
tags question: http://stackoverflow.com/q/51863989
tags question: http://stackoverflow.com/q/51939415
tags question: http://stackoverflow.com/q/51847473
tags question: http://stackoverflow.com/q/51919733
tags question: http://stackoverflow.com/q/51825336
tags question: http://stackoverflow.com/q/51839937
tags question: http://stackoverflow.com/q/51903413
tags question: http://stackoverflow.com/q/51945112
tags question: http://stackoverflow.com/q/51849977
tags question: http://stackoverflow.com/q/51816917
tags question: http://stackoverflow.com/q/51843569
tags question: http://stackoverflow.com/q/51914968
tag name: web-scraping
tags question: http://stackoverflow.com/q/51922313
tags question: http://stackoverflow.com/q/51936182
tags question: http://stackoverflow.com/q/51938565
tags question: http://stackoverflow.com/q/51895560
tags question: http://stackoverflow.com/q/51836352
tags question: http://stackoverflow.com/q/51805642
tags question: http://stackoverflow.com/q/51821475
tags question: http://stackoverflow.com/q/51849234
tags question: http://stackoverflow.com/q/51812028
tags question: http://stackoverflow.com/q/51914391
tags question: http://stackoverflow.com/q/51922830
tags question: http://stackoverflow.com/q/51888181
tags question: http://stackoverflow.com/q/51817806
tags question: http://stackoverflow.com/q/51949091
type: Tag
tags question: http://stackoverflow.com/q/51900046
tags question: http://stackoverflow.com/q/51912858
tags question: http://stackoverflow.com/q/51810200
tags question: http://stackoverflow.com/q/51907791
tags question: http://stackoverflow.com/q/51850577
tags question: http://stackoverflow.com/q/51861991
tags question: http://stackoverflow.com/q/51865855
tags question: http://stackoverflow.com/q/51953855
tags question: http://stackoverflow.com/q/51866785
tags question: http://stackoverflow.com/q/51853806
tags question: http://stackoverflow.com/q/51881388
tags question: http://stackoverflow.com/q/51836884
tags question: http://stackoverflow.com/q/51846955
tags question: http://stackoverflow.com/q/51832095
tags question: http://stackoverflow.com/q/51850011
tags question: http://stackoverflow.com/q/51907224
tags question: http://stackoverflow.com/q/51813334
tags question: http://stackoverflow.com/q/51921221

http://stackoverflow.com/a/51856937
answers question: http://stackoverflow.com/q/51856875
type: Answer
upvote count: 2
accepted answer of: http://stackoverflow.com/q/51856875
score: 2
has comment: http://stackoverflow.com/comment/90666795
type: AcceptedAnswer
downvote count: 0
has body: Very likely, one of your DataFrames contains strings, and the other one numbers. For example, if I write df1 = pd.DataFrame([1,2,3]) df2 = pd.DataFrame(['3', '2', '6']) df1 - df2 then I get TypeError: unsupported operand type(s) for -: 'int' and 'str' To fix it, I could add the line df2 = df2.astype(int) and then, the subtraction will work.

http://stackoverflow.com/comment/90612143
has text: No special python rule. When the lambda is ran the `tree` is already defined.
score: 1
comment on: http://stackoverflow.com/a/51828841
type: AnswerComment
type: Comment

http://stackoverflow.com/a/51865741
has body: I need a little more context on this. How many calls are you going to do to the Google Vision API? If you are doing this throughout a whole stream, you'd probably need to get a paid subscription. What are you going to do with this data? How accurate does the OCR need to be? Assuming you get this snapshot from another's twitch stream, dealing with the streamer's video compression and network connectivity, you're going to get pretty blurry snapshot, so OCR is going to be pretty tough. The image is far too blurry because of video compression, so even preprocessing the image to improve quality may not get the image quality high enough for accurate OCR. If you are set on OCR, one approach you could try: Binarize the image to get the non-red text in white and background black as in your binarized image: from PIL import Image def binarize_image(im, threshold): """Binarize an image.""" image = im.convert('L') # convert image to monochrome bin_im = image.point(lambda p: p &gt; threshold and 255) return bin_im im = Image.open("game_text.JPG") binarized = binarize_image(im, 100) Extract only the red text values with a filter, then binarize it: import cv2 from matplotlib import pyplot as plt lower = [15, 15, 100] upper = [50, 60, 200] lower = np.array(lower, dtype = "uint8") upper = np.array(upper, dtype = "uint8") mask = cv2.inRange(im, lower, upper) red_binarized = cv2.bitwise_and(im, im, mask = mask) plt.imshow(cv2.cvtColor(red_binarized, cv2.COLOR_BGR2RGB)) plt.show() However, even with this filtering, it still doesn't extract red well. Add images obtained in (1.) and (2.). combined_image = binarized + red_binarized Do OCR on (3.)
answers question: http://stackoverflow.com/q/51803569
score: 0
type: Answer

http://stackoverflow.com/comment/90775232
type: Comment
comment on: http://stackoverflow.com/a/51912417
has text: Got bless you! It works! Thank you! (by the way, I see you haven't pushed the code to the rep, which is a great idea)
score: 0
type: AnswerComment

http://stackoverflow.com/a/51934312
accepted answer of: http://stackoverflow.com/q/51933046
answers question: http://stackoverflow.com/q/51933046
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90819203
has comment: http://stackoverflow.com/comment/90819320
has comment: http://stackoverflow.com/comment/90819424
type: Answer
has body: It seems that what you are looking for is to find matchings of G, i.e., sets of edges where no two edges share a common vertex. In particular, you are looking for maximal matchings of G. Networkx offers the function maximal_matching. You may extend this function to obtain all the maximal matchings. One way to do it may be the following. You start with a list of partial matchings, each made by an edge. Each partial matching is then extended until it becomes a maximal one, i.e., until it cannot be extended to a matching of larger cardinality. If a partial matching m can be extended to a larger one using an edge (u,v), then m'=m ∪ {(u,v)} is added to the list of partial matchings. Otherwise, m is added to the list of maximal matchings. The following code can be improved to be more efficient in many ways. One way is to check before adding to the list of partial matchings. indeed, the list will contain partial matchings which represent the same one (i.e., [{i,j},{u,v}] and [{u,v},{i,j}] ). import networkx as nx import itertools def all_maximal_matchings(T): maximal_matchings = [] partial_matchings = [{(u,v)} for (u,v) in T.edges()] while partial_matchings: # get current partial matching m = partial_matchings.pop() nodes_m = set(itertools.chain(*m)) extended = False for (u,v) in T.edges(): if u not in nodes_m and v not in nodes_m: extended = True # copy m, extend it and add it to the list of partial matchings m_extended = set(m) m_extended.add((u,v)) partial_matchings.append(m_extended) if not extended and m not in maximal_matchings: maximal_matchings.append(m) return maximal_matchings T = nx.Graph() T.add_edge('A','B') T.add_edge('A','C') T.add_edge('B','D') T.add_edge('D','A') print(all_maximal_matchings(T))
score: 2
upvote count: 2

http://stackoverflow.com/comment/90579543
has text: I really don't know what you're asking for. Please see [how to ask](https://stackoverflow.com/help/how-to-ask). Have you tried anything?
comment on: http://stackoverflow.com/q/51812287
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/q/51890685
has comment: http://stackoverflow.com/comment/90748630
favorite count: 0
has answer: http://stackoverflow.com/a/51891781
type: Question
has comment: http://stackoverflow.com/comment/90748671
tagged with: python
tagged with: django-templates
answer count: 3
tagged with: django
upvote count: 1
has body: I am trying to program a "Save and add another" functionality in my Django App. I put an elif condition to a button. I can't find any helpful resources and references around the web especially with my set of codes. I have tried puting two returns inside the elif and putting the self.object snippet inside. Any suggestions what I can do? I am very new with Django. Please help. Views.py def post(self, request, *args, **kwargs): if "cancel" in request.POST: return HttpResponseRedirect(reverse('skillsMatrixApp:index')) elif "another" in request.POST: #try 1 #self.object = self.get_object() #url = self.get_success_url() #return HttpResponseRedirect(url) #try 2 #return HttpResponseRedirect(reverse('skillsMatrixApp:employee-add')) #return super(employeeCreate, self).post(request, *args, **kwargs) else: return super(employeeCreate, self).post(request, *args, **kwargs) employee_form.html Cancel Submit Save and add another urls.py urlpatterns = [ url(r'^$', views.IndexView.as_view(), name='index'), url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'), url(r'employee/$', views.employeeList.as_view(), name='employee-list'), url(r'employee/add/$', views.employeeCreate.as_view(), name='employee-add'),
has comment: http://stackoverflow.com/comment/90732895
has answer: http://stackoverflow.com/a/51891531
tagged with: django-views
has answer: http://stackoverflow.com/a/51891409
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90732873
has comment: http://stackoverflow.com/comment/90748712
has title: Django - Save and add another functionality
has comment: http://stackoverflow.com/comment/90734120
downvote count: 0
tagged with: web
score: 1

http://stackoverflow.com/comment/90638957
comment on: http://stackoverflow.com/q/51842888
type: Comment
type: QuestionComment
has text: why are you storing them in different objects? store them in a separate `dict` from beginning
score: 1

http://stackoverflow.com/comment/90711500
type: QuestionComment
comment on: http://stackoverflow.com/q/51878397
score: 1
has text: Well, that's a real bugger. I think you are right, it looks like a bug in the anaconda interpreter. If it matters, I am also on windows, not linux.
type: Comment

http://stackoverflow.com/comment/90781279
type: QuestionComment
has text: are you getting any errors? do you also realise the web output that you're providing is not correct `json`?
comment on: http://stackoverflow.com/q/51915150
score: 0
type: Comment

http://stackoverflow.com/comment/90808785
type: AnswerComment
has text: that is the output of some collections that i saved in `a`
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51929600

http://stackoverflow.com/a/51848212
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51848161
has comment: http://stackoverflow.com/comment/111456277
accepted answer of: http://stackoverflow.com/q/51848161
has body: You can turn the matrix into a datframe and use concat with axis=1: For example, given a dataframe df and a numpy array mat: &gt;&gt;&gt; df a b 0 5 5 1 0 7 2 1 0 3 0 4 4 6 4 &gt;&gt;&gt; mat array([[0.44926098, 0.29567859, 0.60728561], [0.32180566, 0.32499134, 0.94950085], [0.64958125, 0.00566706, 0.56473627], [0.17357589, 0.71053224, 0.17854188], [0.38348102, 0.12440952, 0.90359566]]) You can do: &gt;&gt;&gt; pd.concat([df, pd.DataFrame(mat)], axis=1) a b 0 1 2 0 5 5 0.449261 0.295679 0.607286 1 0 7 0.321806 0.324991 0.949501 2 1 0 0.649581 0.005667 0.564736 3 0 4 0.173576 0.710532 0.178542 4 6 4 0.383481 0.124410 0.903596
type: Answer
has comment: http://stackoverflow.com/comment/117166475
score: 41
downvote count: 0
upvote count: 41

http://stackoverflow.com/q/51881911
answer count: 2
tagged with: python-huey
has answer: http://stackoverflow.com/a/51881954
has body: I'm trying to deploy a project https://github.com/kc1/flask-huey-example to heroku to allow usage of a task queue and flask. The project layout is as above. You can also take a look at the github repo which I have updated. The project is running without issue locally on windows (gunicorn is not used locally) . My Procfile: web: gunicorn run_app:app worker: python /app/.heroku/python/bin/huey_consumer run_huey.huey I had previously gotten an error Failed to find application object 'app' in 'run_app' . I tried to fix that by changing run_app.py to: from app import create_app, config if __name__ == '__main__': import logging logging.basicConfig() logging.getLogger().setLevel(logging.DEBUG) app = create_app() app.run(host='localhost', port=6060, debug=True) else: app = create_app() app.run(debug=False) Unfortunately , now when I push to heroku, I see: 2018-08-16T16:37:59.253114+00:00 app[web.1]: [2018-08-16 16:37:59 +0000] [8] [ERROR] Exception in worker process 2018-08-16T16:37:59.253118+00:00 app[web.1]: Traceback (most recent call last): 2018-08-16T16:37:59.253121+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker 2018-08-16T16:37:59.253123+00:00 app[web.1]: worker.init_process() 2018-08-16T16:37:59.253124+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/base.py", line 129, in init_process 2018-08-16T16:37:59.253126+00:00 app[web.1]: self.load_wsgi() 2018-08-16T16:37:59.253128+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/base.py", line 138, in load_wsgi 2018-08-16T16:37:59.253130+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2018-08-16T16:37:59.253132+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/base.py", line 67, in wsgi 2018-08-16T16:37:59.253133+00:00 app[web.1]: self.callable = self.load() 2018-08-16T16:37:59.253135+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/…
tagged with: gunicorn
has answer: http://stackoverflow.com/a/68371752
type: UnansweredQuestion
tagged with: python
tagged with: heroku
has comment: http://stackoverflow.com/comment/90715446
type: Question
has title: OSError: [Errno 98] Address already in use - Heroku
score: 0

http://stackoverflow.com/q/51929282
answer count: 1
upvote count: 3
tagged with: pandas
tagged with: python
favorite count: 0
tagged with: python-3.x
downvote count: 0
accepted answer: http://stackoverflow.com/a/51929311
type: Question
has body: I have dataframe of genres df = pd.DataFrame({'genres': [['Drama'], ['Music', 'Drama', 'Romance'], ['Action', 'Adventure', 'Comedy'], ['Thriller', 'Romance', 'Drama'], ['Adventure', 'Family']] }) print(df) genres = ['Action', 'Adventure', 'Comedy', 'Drama', 'Family', 'Music', 'Romance', 'Thriller'] # list of all genres data: genres 0 [Drama] 1 [Music, Drama, Romance] 2 [Action, Adventure, Comedy] 3 [Thriller, Romance, Drama] 4 [Adventure, Family] i want to have output like: genres Action Adventure Comedy Drama Family \ 0 [Drama] 0 0 0 1 0 1 [Music, Drama, Romance] 0 0 0 1 0 2 [Action, Adventure, Comedy] 1 1 1 0 0 3 [Thriller, Romance, Drama] 0 0 0 1 0 4 [Adventure, Family] 0 1 0 0 1 Music Romance Thriller 0 0 0 0 1 1 1 0 2 0 0 0 3 0 1 1 4 0 0 0
type: AnsweredQuestion
score: 3
tagged with: dataframe
has answer: http://stackoverflow.com/a/51929311
has title: python - dataframe make columns representing vector

http://stackoverflow.com/comment/90855797
score: 0
has text: @tripleee hmm... still couldn't get it to work: `proc = Popen('read -r -p "test" abc',shell=True,stderr=PIPE,stdin=PIPE) proc.stderr.read(1) # <--- hangs`
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51952165

http://stackoverflow.com/comment/90646628
type: Comment
comment on: http://stackoverflow.com/q/51846670
type: QuestionComment
has text: Dictionaries aren't ordered in some versions of Python, do you want to use the key to sort?
score: 0

http://stackoverflow.com/q/51903204
has comment: http://stackoverflow.com/comment/90757709
has comment: http://stackoverflow.com/comment/90757621
has title: How to marge/add two or more Python dictionaries?
downvote count: 2
answer count: 3
has comment: http://stackoverflow.com/comment/90757459
favorite count: 0
has comment: http://stackoverflow.com/comment/90757602
possible better answer: http://stackoverflow.com/a/51904425
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51904425
has comment: http://stackoverflow.com/comment/90757548
has comment: http://stackoverflow.com/comment/90757601
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
upvote count: 0
has answer: http://stackoverflow.com/a/73357134
accepted answer: http://stackoverflow.com/a/51904349
has comment: http://stackoverflow.com/comment/90757646
type: Question
score: -2
has body: Lets say I have two python dictionaries: dct_01 = {'a': 1, 'b': 2, 'c': 3} dct_02 = {'a': 2, 'b': 1, 'c': 3, 'd': 4} and I want: dct_03 = {'a': 3, 'b': 3, 'c': 3, 'd': 4} If both the dictionary have same key->value pair, it should remain same, if there is same key with different values it should add up. How can I do this?
has answer: http://stackoverflow.com/a/51904349

http://stackoverflow.com/q/51831653
tagged with: set
has comment: http://stackoverflow.com/comment/90617907
has answer: http://stackoverflow.com/a/51831706
has comment: http://stackoverflow.com/comment/90617429
has answer: http://stackoverflow.com/a/51831822
upvote count: 5
has answer: http://stackoverflow.com/a/51831692
has answer: http://stackoverflow.com/a/51831860
type: Question
has title: How to keep ordered list using 'set'?
has body: I want to be able to keep the order of the list when it compares. Notice when I compare list1 with list2, it returns me 8 then 7 (reverse). How do I have it maintain the order? &gt;&gt;&gt; list1 = ['1','2','3','4','7','8'] &gt;&gt;&gt; list2 = ['1','2','3','4','5','6'] &gt;&gt;&gt; list(set(list2) - set(list1)) ['5', '6'] &gt;&gt;&gt; list(set(list1) - set(list2)) ['8', '7']
score: 5
has comment: http://stackoverflow.com/comment/90617469
has answer: http://stackoverflow.com/a/51831746
downvote count: 0
answer count: 7
has answer: http://stackoverflow.com/a/51831707
has answer: http://stackoverflow.com/a/51831711
tagged with: python
linked to: http://stackoverflow.com/q/47985297
favorite count: 0
tagged with: list
type: UnansweredQuestion

http://stackoverflow.com/comment/90863811
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51951256
has text: Try to search for `Python 3.5` in your `.idea` folder or the per-user settings directory...
score: 0

http://stackoverflow.com/q/51892741
answer count: 1
tagged with: mystic
upvote count: 3
has body: Background Auto-tuner for a car application: The application may change depending on model of the car, so naturally the objective function is going to change as well. The problem is to tune the parameters to the optimum ones for the specific car model. Input: car model, output: optimum paramters for the application for the specific car model. I want to solve this with optimization I'm trying to minimize a complex nonlinear function, constrained with two nonlinear constraints, one inequality and one equality constraint. The problem is not bounded per se but i've put bounds on the parameters anyway to help speed up the optimization since I know more or less where the correct parameters lie. Parameters are: [x0,x1,x2,x3] I've used the scipy.optimize.minimize() function with SLSQP method and found good results when the problem is bounded correctly. Although, the scipy.optimize.minimize() function is a local optimizer and solves QP problems which I don't think that my problem is. I've therefore started using a global optimization method with mystic,(mystic.differential_evolution). Since I'm not an expert in global optimization I naturally have some questions. The problem If I choose the bounds too wide the optimizer (mystic.differential_evolution) will stop iterating after a while and print: STOP("ChangeOverGeneration with {'tolerance': 0.005, 'generations': 1500}") When I run the solution that the optimizer found, I see that the result is not as good as if I were to lower(shrink) the bounds. Obviously the global optimizer has not found the global optimum, yet it stopped iterating. I know that there are a multiple parameter sets that yield the same global minimum. Since the objective function may change with the car model, I want the bounds to remain relativley broad in case the global optimum changes which would change the correct parameters. Question How do I tune the settings of the optimizer to get it to keep searching and find the global optimum? Is the npop = 10*di…
tagged with: scipy
has answer: http://stackoverflow.com/a/51897710
type: AnsweredQuestion
downvote count: 0
accepted answer: http://stackoverflow.com/a/51897710
favorite count: 0
type: Question
score: 3
has title: Constrained global optimization tuning [mystic]
tagged with: nonlinear-optimization
tagged with: python

http://stackoverflow.com/comment/90714618
has text: Possible duplicate of [Python: UnboundLocalError: local variable 'count' referenced before assignment](https://stackoverflow.com/questions/36720607/python-unboundlocalerror-local-variable-count-referenced-before-assignment)
comment on: http://stackoverflow.com/q/51881526
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/123858626
has text: Cryptodome and pycryptodomex work for Python 3.9
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51824838

http://stackoverflow.com/comment/90751562
type: Comment
comment on: http://stackoverflow.com/a/51899930
has text: @Sheljohn: There are certainly annoyances in the Python import system. (Personally, I've always hated how easy it is to wind up with three distinct modules created from the same file.) What you're seeing is a consequence of how local files get dumped into the same top-level module namespace as stdlib and installed modules. Python wasn't designed with the whole stdlib in a `std` package like C++'s `std` namespace, and there's no implicit package for local files or anything like that to keep local files out of top-level.
score: 1
type: AnswerComment

http://stackoverflow.com/comment/90619844
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/51827499
has text: What if my labels are in shape of (1414,100). Then also I shouldn't reshape? How will dense layer work then?
type: Comment

http://stackoverflow.com/q/51874297
score: 1
has comment: http://stackoverflow.com/comment/90700961
upvote count: 1
has answer: http://stackoverflow.com/a/51877126
has comment: http://stackoverflow.com/comment/90701578
type: Question
has comment: http://stackoverflow.com/comment/90704990
has comment: http://stackoverflow.com/comment/90700623
has comment: http://stackoverflow.com/comment/90700377
tagged with: dataframe
has title: Comparing two dataframes to return a new dataframe using pandas - Python
tagged with: pandas
has body: Need your help please. I have two dataframes created from csvs and I need to return a new dataframe which will be the difference between the two on a specific field/column. For example, if ID from df1 is not in df2, then df3 should give me all columns and rows from df1 that are not in df2. Note df1 and df2 columns are not identical i.e df1 could have more or less columns than df2 but the columns in df3 should be as of d1. Also, the ID (from df1) and User ID (df2) values are going to be the reconciling factor, the data in the fields will be the common factor but the actual field names are different. Apologies in advance as the tables below are not clear. So in the below example, 1st row in df1 is not in df2, df3 should have this row. Once done, I need to save df3 as csv. DF1 Direction ID Quantity Company Status Sell - 09 - 32000 - T LTD - Rejected Buy - 12 - 25000 - G Ltd - Done Sell - 15 - 35000 - H Ltd - Done DF2 Direction User ID Quantity Company Status Rating Buy - 12 - 25000 - G Ltd - Done - Good Rating Sell - 15 - 35000 - H Ltd - Done - Good Rating Many thanks in advance code so far: import pandas as pd fileLocationDF1 = "BBG.csv" fileLocationDF2 = "corp.csv" createDf1 = pd.read_csv(fileLocationDF1, low_memory = False) createDf2 = pd.read_csv(fileLocationDF2, engine='python') I have found the isin method which I think will help but the problem is that the "User ID" column (df2) has a space in the data frame (as is the case in the csv). createDf1[createDf1.ID.isin(createDf2.columns[2].values)] and I get the below error when AttributeError: 'str' object has no attribute 'values' I passed columns [2] in the isin method as the User ID has a space Please help address the error and why the data is not being read so that i can get a unique set where the user Id from df2 is not in ID in df1. See below - the one highligted is the one that is missing in DF2 and I would like this in df3 CParserError: Error tokenizing data. C error: Buffer overflow caught - possible malfor…
accepted answer: http://stackoverflow.com/a/51877126
downvote count: 0
has comment: http://stackoverflow.com/comment/90700477
answer count: 1
has comment: http://stackoverflow.com/comment/90700572
favorite count: 0
has comment: http://stackoverflow.com/comment/90704224
has comment: http://stackoverflow.com/comment/90700519
has comment: http://stackoverflow.com/comment/90707056
tagged with: python
has comment: http://stackoverflow.com/comment/90703716
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90707407

http://stackoverflow.com/comment/90658239
has text: That just looks like you haven't imported pandas?
comment on: http://stackoverflow.com/q/51852850
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/a/57323479
answers question: http://stackoverflow.com/q/51889378
has body: I don't think this should be blame on that bug because it seems be fixed already in 2016. Note that there is an positive argument in this function: min_delta: threshold for measuring the new optimum, to only focus on significant changes. Which is set as 0.0001 by default. Therefore even though val_loss improved from last epoch, if the reduction is smaller than min_delta. It will still be regard as bad lr.
type: Answer
score: 13
upvote count: 13
downvote count: 0

http://stackoverflow.com/q/51842987
tagged with: python
has answer: http://stackoverflow.com/a/65825202
upvote count: 3
has title: Django-postman not working
downvote count: 0
type: UnansweredQuestion
type: Question
score: 3
favorite count: 0
has answer: http://stackoverflow.com/a/57445799
has answer: http://stackoverflow.com/a/70114593
answer count: 3
has body: I tried to implement Django-postman for the user to user messaging system. I cloned the repo and did this in my settings.py and URLs.py file too: In URLs.py of main file i have included : re_path(r'^messages/', include('postman.urls', namespace='postman')), In Settings.py file I have included: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'postman', 'account', 'landingpage', ] POSTMAN_I18N_URLS = True # default is False POSTMAN_DISALLOW_ANONYMOUS = True # default is False POSTMAN_DISALLOW_MULTIRECIPIENTS = True # default is False POSTMAN_DISALLOW_COPIES_ON_REPLY = True # default is False POSTMAN_DISABLE_USER_EMAILING = True # default is False POSTMAN_FROM_EMAIL = 'from@host.tld' # default is DEFAULT_FROM_EMAIL #POSTMAN_PARAMS_EMAIL = get_params_email # default is None POSTMAN_AUTO_MODERATE_AS = True # default is None POSTMAN_SHOW_USER_AS = 'get_full_name' # default is None POSTMAN_NAME_USER_AS = 'last_name' # default is None POSTMAN_QUICKREPLY_QUOTE_BODY = True # default is False POSTMAN_NOTIFIER_APP = None # default is 'notification' POSTMAN_MAILER_APP = None # default is 'mailer' URLs of postman: urlpatterns = [ # Translators: keep consistency of the &lt;option&gt; parameter with the translation for 'm' url(pgettext_lazy('postman_url', r'^inbox/(?:(?P&lt;option&gt;m)/)?$'), InboxView.as_view(), name='inbox'), # Translators: keep consistency of the &lt;option&gt; parameter with the translation for 'm' url(pgettext_lazy('postman_url', r'^sent/(?:(?P&lt;option&gt;m)/)?$'), SentView.as_view(), name='sent'), # Translators: keep consistency of the &lt;option&gt; parameter with the translation for 'm' url(pgettext_lazy('postman_url', r'^archives/(?:(?P&lt;option&gt;m)/)?$'), ArchivesView.as_view(), name='archives'), # Translators: keep consistency of the &lt;option&gt; parameter with the translation for 'm' url(pgettext_lazy('postman_url'…
tagged with: django

http://stackoverflow.com/comment/90851906
score: 0
has text: Why do you do `body_dict=collections.OrderedDict()` and then replace that with a plain `dict` a few lines later? And at the end of your code, why do you do `new_dict.update(body_dict)` twice?
comment on: http://stackoverflow.com/q/51950730
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90685260
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/51865757
has text: @FanZhao Nope. use the .dt.days method below.
type: Comment

http://stackoverflow.com/a/51954105
type: Answer
has body: Delete the following line from your code (rest everything remains the same): fig, add_ax = plt.subplots() add_ax = axs[1][1].twinx() is sufficient alone and will add a second y axis to your bottom, right subplot.
upvote count: 1
has comment: http://stackoverflow.com/comment/90858641
has comment: http://stackoverflow.com/comment/90858691
has comment: http://stackoverflow.com/comment/90858827
score: 1
answers question: http://stackoverflow.com/q/51953680
accepted answer of: http://stackoverflow.com/q/51953680
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90869985
has comment: http://stackoverflow.com/comment/90858939
has comment: http://stackoverflow.com/comment/90858772

http://stackoverflow.com/a/51842196
type: Answer
has comment: http://stackoverflow.com/comment/90639199
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51838835
has comment: http://stackoverflow.com/comment/90639234
has body: Coding shouldn't be a mean to satisfy any IDE requirements, you're talking about not use the IDE's auto-completion to see which parameters are expected... Your code shouldn't be written to make your IDE happy, instead it should be easy to be uses by other coders. What does this mean? Your exposed public interfaces should be intuitive and easy to learn by people, not IDEs. I'd say one of the many requisites that good code satisfies is whether you don't even need to read any doc at all but the public interface are self-explanatory. Here's an interesting programming quote for you to consider: The ideal numbers of arguments for a function is zero (niladic). Next comes one (monadic), followed closely by two (dyadic). Three arguments (triadic) should be avoided where possible. More than three (polyadic) requires very special justification ‐ and then shouldn't be used anyway. By looking at the non-relevant example you've proposed I can say straight-away that's not good OOP design, not just in terms of exposed public interfaces but also in terms of relationships (hierarchies should be created with proper reasoning). Maybe if you presented a real world-case I could advice further to make proper refactoring but with meaningless imaginary code with no use-cases and fictional meaningless parameters I don't see the point. In any case, the best advice I can give you is about trying to come up with good encapsulated objects with proper logical relationships and thin self-explanatory public interfaces. Said otherwise, make your code "attractive" and "pleasant" to be used by others and you'll be fine :)
downvote count: 0
has comment: http://stackoverflow.com/comment/90639528

http://stackoverflow.com/q/51894603
has body: I have a sample dataframe like this, Column: ID and Main ID,Main 0,[30 115 266 38;662 99 1199 43] [511 133 25 47] [664 162 49 22] How do I make my dataframe something like below using pandas Expected Output ID,Main 0,30 115 266 38 0,662 99 1199 43 0,511 133 25 47 0,664 162 49 22
tagged with: dataframe
has answer: http://stackoverflow.com/a/51894772
type: Question
has comment: http://stackoverflow.com/comment/90739724
answer count: 1
has comment: http://stackoverflow.com/comment/90739790
has title: creating multiple rows from multiple list using same Id, pandas
upvote count: 3
tagged with: pandas
tagged with: python
favorite count: 0
downvote count: 0
accepted answer: http://stackoverflow.com/a/51894772
type: AnsweredQuestion
score: 3

timer
tag name: timer
tags question: http://stackoverflow.com/q/51826601
type: Tag

http://stackoverflow.com/q/51908009
tagged with: shell
tagged with: string
favorite count: 0
has comment: http://stackoverflow.com/comment/90766363
has answer: http://stackoverflow.com/a/51908231
has body: In Jupyter Notebook my Code runs fine, but when I run it from shell i get a syntax error at this part of my code: res = f'"x"'+" "+f'"y"'+" "+f'"t"'+" "+f'"id"'+" "+f'"id2"' ^ SyntaxError: invalid syntax However I need the String res to look like: ""x" "y" "t" "id" "id2"" I guess that the way i create it is causing the error. Is there any other way to create a String containing quotation marks? Or anything to get rid of the syntax error? Thanks!
tagged with: python
tagged with: quotation-marks
has comment: http://stackoverflow.com/comment/90766477
possible better answer: http://stackoverflow.com/a/51908231
accepted answer: http://stackoverflow.com/a/51908219
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90766650
has comment: http://stackoverflow.com/comment/90766568
upvote count: 1
downvote count: 1
type: Question
tagged with: syntax-error
has comment: http://stackoverflow.com/comment/90766839
has comment: http://stackoverflow.com/comment/90766238
has comment: http://stackoverflow.com/comment/90766313
has comment: http://stackoverflow.com/comment/90766337
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/51908219
has title: SyntaxError: invalid syntax (when running python code from shell)
has comment: http://stackoverflow.com/comment/90766367

http://stackoverflow.com/q/51876240
score: -2
has answer: http://stackoverflow.com/a/51876328
has body: My code: import re url=input("enter the url") match_obj=re.match( r'^(?:http)s?://',url,re.I|re.M) if match_obj: print("valid url",match_obj.group()) else: print("invalid url") Is there a better way to do it?
has comment: http://stackoverflow.com/comment/90705395
answer count: 2
downvote count: 3
upvote count: 1
has answer: http://stackoverflow.com/a/51876292
accepted answer: http://stackoverflow.com/a/51876292
tagged with: url
favorite count: 0
has title: how to validate only http:// or https:// starting urls using python
has comment: http://stackoverflow.com/comment/90704761
tagged with: python
has comment: http://stackoverflow.com/comment/90703689
possible better answer: http://stackoverflow.com/a/51876328
has comment: http://stackoverflow.com/comment/90703987
type: AnsweredQuestion
type: Question

http://stackoverflow.com/a/51851350
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/51851239
has body: You just need to use a regular expression that ignores the cases ie (?i) is same as re.I. Since df.replace does not take a flag argument, you will invoke this manually. This ensures that all the other characters are maintained the way they were before deletion. Ie if they were capital, they remain so and vice versa autos_df.name.replace(regex=r'(?i)'+ autos_df.brand,value="") Out[1726]: 0 _807_160_NAVTECH_ON_BOARD 1 _740i_4_4_Liter_HAMANN_UMBAU_Mega_Optik 2 _Golf_1.6_United 3 __fortwo_coupe_softouch/F1/Klima/Panorama 4 _Grand_Voyager_2.8_CRD_Aut.Limited_Stow´n_Go_S... Name: name, dtype: object
upvote count: 1
has comment: http://stackoverflow.com/comment/90655735

http://stackoverflow.com/a/67385104
score: 5
upvote count: 5
type: Answer
has body: my issue was solved by disabling this extension that was not installed completely Visual Studio IntelliCode
downvote count: 0
answers question: http://stackoverflow.com/q/51874486

http://stackoverflow.com/comment/90766822
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51885694
has text: @ShadowRanger post [your answer](https://stackoverflow.com/questions/4020539/process-escape-sequences-in-a-string-in-python/51904799#51904799) here that I accept it as the solution. You solved my problem.

http://stackoverflow.com/comment/90583102
type: QuestionComment
has text: Thanks! I feel kind of silly now, but that fixed it. Thanks again!
score: 0
comment on: http://stackoverflow.com/q/51814121
type: Comment

http://stackoverflow.com/a/51876617
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/90704687
has body: I had a similar problem in my project root ... django complained that it couldn't find the module mysite.urls. Turns out my ROOT_URLCONF variable in settings.py, which was set up using the default values, was set incorrect. Instead of "mysite.urls", it should have been simply "urls" I changed it, and voila, it worked.
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51876376

http://stackoverflow.com/q/51922614
type: UnansweredQuestion
downvote count: 1
has comment: http://stackoverflow.com/comment/90794829
score: -1
has answer: http://stackoverflow.com/a/51922655
type: Question
upvote count: 0
answer count: 1
has body: I wrote a python class, but when using it, it can not find any of the functions inside. I tested it on windows and MAC, it does not work both. Here is the some of the code of the class I defined:(I here is not the full code as it it too many codes and it's not allowed to copy here) import numpy as np import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data import matplotlib.pyplot as plt class VanillaInfoGAN(object): def __init__(self,learning_rate,batch_size,num_epoches,z_dim,c_cat_dim,c_cont_dim,model_num,print_every=30,show_every=50, store_path = './ckpt/',training_picture_path='./pictures/'): self.learning_rate = learning_rate self.batch_size = batch_size self.num_epoches = num_epoches self.z_dim = z_dim self.c_cat_dim = c_cat_dim self.c_cont_dim = c_cont_dim self.print_every = print_every self.show_every = show_every self.data =input_data.read_data_sets('MNIST',one_hot=True) self.data_dim = 784 self.store_path = store_path self.model_num = model_num self.training_picture_path = training_picture_path self.real_data_placeholder = tf.placeholder(tf.float32,[None,self.data_dim]) self.z_placeholder = tf.placeholder(tf.float32,[None,self.z_dim]) self.c_cat_placeholder = tf.placeholder(tf.float32,[None,self.c_cat_dim]) self.c_cont_placeholder = tf.placeholder(tf.float32,[None,self.c_cont_dim]) self.c = tf.concat([self.c_cat_placeholder,self.c_cont_placeholder],axis=1) self.z_c = tf.concat([self.z_placeholder,self.c_cat_placeholder,self.c_cont_placeholder],axis=1) self.g_out = self.generator() d_out_real = self.discriminator(self.real_data_placeholder) d_out_fake = self.discriminator(self.g_out,reuse=True) q_out = self.q_net(self.g_out) self.g_loss,self.d_loss,self.q_loss = self.build_loss(self.g_out,d_out_real,d_out_fake,q_out) self.g_opt,self.d_opt,self.q_opt = self.optimizer(self.g_loss,self.d_loss,self.q_loss) self.saver= tf.train.Saver() print('Model graph has built') def generator(self,reuse=False): with tf.variable_scope('generator',reu…
favorite count: 0
tagged with: python
tagged with: python-3.x
has title: Python class can not find its function

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

http://stackoverflow.com/q/51868214
has comment: http://stackoverflow.com/comment/90688317
score: 0
answer count: 1
tagged with: asynchronous
has answer: http://stackoverflow.com/a/51868271
tagged with: python
has body: I'm trying to learn how to use Python's multiprocessing module. Playing around with it, I've tried to write the same code both in a non-parallelized and a parallelized manner. The problem is that they are returning different results. Here is the non-parallelized version: import numpy as np m = 3 num_points = 200 iterMax = 20 NMax = 3 np.random.seed(0) y = np.random.rand(num_points,m) w = list(range(NMax - 1)) for N in range(NMax-1): w[N] = np.random.uniform(0,1,(N+2,np.size(y,axis=1))) - 0.5 iterCount = 1 while iterCount &lt; iterMax: for selectedInput in y: w[N] = w[N] + (np.random.rand() - 0.5) * selectedInput iterCount += 1 for i in w: print(i) Here's the parallelized version: import numpy as np import multiprocessing as mp m = 3 num_points = 200 iterMax = 20 NMax = 3 np.random.seed(0) y = np.random.rand(num_points,m) def neuron_run(N): w = np.random.uniform(0,1,(N+2,np.size(y,axis=1))) - 0.5 # Initialize weights iterCount = 1 while iterCount &lt; iterMax: for selectedInput in y: w = w + (np.random.rand() - 0.5) * selectedInput iterCount += 1 return w if __name__ == '__main__': w = [] pool = mp.Pool(processes=NMax) for N in range(NMax-1): pool_result = pool.apply_async(neuron_run, args = (N,)) w.append(pool_result.get()) pool.close() pool.join() for i in w: print(i) Both should return the same w because of this line: np.random.seed(0). But they are not. Where is the mistake? I'm not being able to spot it.
tagged with: parallel-processing
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51868271
type: Question
tagged with: multiprocessing
has title: Why is this parallelized script not returning the correct result?

http://stackoverflow.com/q/51866342
has comment: http://stackoverflow.com/comment/90714899
score: 2
has comment: http://stackoverflow.com/comment/90685186
type: AnsweredQuestion
downvote count: 0
favorite count: 0
tagged with: python-3.x
type: Question
accepted answer: http://stackoverflow.com/a/51866577
tagged with: python
tagged with: properties
has title: Setter ignored when property is assigned to variable (Python 3.4)
has comment: http://stackoverflow.com/comment/90685215
upvote count: 2
answer count: 1
has comment: http://stackoverflow.com/comment/90714556
has body: I'm creating a Verdict class which will evaluate to true until it is set false after which it always evaluates false even if you set it to true. The only way I could think of to do that would be to have a property and a setter. It works, but for simplicity rather than having: v = Verdict() v.verdict = ... v.verdict = ... v.verdict = ... I thought I could do: v = Verdict().verdict v = ... v = ... v = ... But it seems that v in the second case is the attribute directly, and is ignoring the setter. class Verdict(): def __init__(self): self.__verdict = True @property def verdict(self): return self.__verdict @verdict.setter def verdict(self, value): if self.__verdict is True: self.__verdict = value def __bool__(self): return self.__verdict class A(): v = Verdict().verdict y = Verdict() def foo(cls): cls.y = False cls.y = True # Uses setter and stays false cls.v = False cls.v = True # should use setter and stay false but doesn't Is there a way to fix this, or a better method to achieve the Verdict?
has answer: http://stackoverflow.com/a/51866577
tagged with: setter
has comment: http://stackoverflow.com/comment/90685051

aws-security-group
type: Tag
tags question: http://stackoverflow.com/q/51801942
tag name: aws-security-group
tags question: http://stackoverflow.com/q/51954181

http://stackoverflow.com/comment/90691953
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51869915
has text: It depends on your purpose. I would suggest you use indexing within `try: ... except: ...` because indexing out of range is not an expected operation. Slicing will silently handle the problem, which can be omitted when you don't pay attention.

http://stackoverflow.com/comment/90802982
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51925299
has text: Yes, as I already mentioned, you can have a mapping (a dictionary) of the slider data to your intervals, and/or your values: for each slider value, you calculate the corresponding value you want, and access it in a dictionary of `slider_value --> usable_value`

http://stackoverflow.com/q/51942096
favorite count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: python
score: 2
has title: Python Pandas Bar plot shows no color
has comment: http://stackoverflow.com/comment/90833704
type: Question
has body: When I follow the examples in the pandas documentation for visualizing a bar chart: https://pandas.pydata.org/pandas-docs/version/0.23/generated/pandas.DataFrame.plot.bar.html See the first example titled Basic plot. with 3 bars. The pandas documentation shows: But when I type the same in my local jupyter notebook, I get no color: Why does my notebook not have color? What can I do to display the colors?
downvote count: 0
answer count: 1
tagged with: pandas
has answer: http://stackoverflow.com/a/51942428

http://stackoverflow.com/comment/90873152
score: 0
type: QuestionComment
type: Comment
has text: It has to be stored by itself, imagine it as a variable where you only need the SQL script. I'm glad it helped, please consider [accept/upvote](https://stackoverflow.com/help/someone-answers) my answer. Good luck!
comment on: http://stackoverflow.com/q/51940352

http://stackoverflow.com/q/51922259
tagged with: pandas
favorite count: 0
has title: Parsing json values in pandas read_json
has answer: http://stackoverflow.com/a/51922303
upvote count: 1
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
has body: I am reading a json file to get data. The json begins like this: { "rows": [ [ 2013, "Mazda", "3", "917723", 7795, 20895 ], [ 2016, "Cadillac", "ATS", "DD16135D", 54890, 66000 ] I am trying to get the values in a row into separate columns. I have tried doing the following: df = pd.read_json(path, orient='values') and got the result: rows 0 [2013, Mazda, 3, 917723, 77... 1 [2016, Cadillac, ATS, DD161... 2 [2015, Mitsubishi, Outlander,... 3 [2016, BMW, 528I, 918058, 3... 4 [2015, Toyota, Venza, 91806... Ultimately, I would like to have 7 columns in my dataframe, each column representing each item in a row. How can I achieve this?
score: 1
tagged with: http://stackoverflow.com/tag/json
tagged with: dataframe
type: Question
accepted answer: http://stackoverflow.com/a/51922303
downvote count: 0
answer count: 1

http://stackoverflow.com/a/51934104
upvote count: 2
answers question: http://stackoverflow.com/q/51933901
downvote count: 0
type: Answer
has body: In Python, files opened as text are iterable over their lines. The simplest solution is therefore with open('myfile.txt') as f: my_list = list(f) This is better than using readlines because the iterator strips newlines while readlines does not. If you want to strip additional spaces from each line, as other answers suggest, you can use a comprehension: with open('myfile.txt') as f: my_list = [line.strip() for line in f] or map: with open('myfile.txt') as f: my_list = list(map(str.strip, f))
score: 2

http://stackoverflow.com/comment/90662488
has text: Yes I just tried it out, unfortunately does not work either ... I've tried with other valid URLs as well and the `if` statement never succeed with them either ! How is that possible ??
type: AnswerComment
comment on: http://stackoverflow.com/a/51854984
type: Comment
score: 1

http://stackoverflow.com/comment/90731563
comment on: http://stackoverflow.com/q/51888323
has text: Are you trying to find documents where the key `size` has the values defined in the SON Object?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51941863
has title: Passing YAML key values to Python
type: Question
has comment: http://stackoverflow.com/comment/90833322
has comment: http://stackoverflow.com/comment/90833511
has comment: http://stackoverflow.com/comment/90833294
score: 0
has comment: http://stackoverflow.com/comment/90833365
tagged with: yaml
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90833342
tagged with: python
has comment: http://stackoverflow.com/comment/90833531
has comment: http://stackoverflow.com/comment/90844400
answer count: 0
has comment: http://stackoverflow.com/comment/90833343
has body: I have a YAML file i.e. test.yml which looks like the following: details: server1: abc.host.com port: 80 I am trying to read these keys and assign to a string using Python with code: #!/usr/bin/python import os import yaml with open('test.yml', 'r') as cfg: yamlcfg=yaml.load(cfg) str1 = "Hostname: " + (yamlcfg['details']['server1']) print str1 When I run this code. I get error: TypeError: list indices must be integers, not str What am I doing wrong?

http://stackoverflow.com/comment/90774498
type: Comment
type: QuestionComment
score: 0
has text: I'm not sure what house numbers are (the numbers in the sectors with the 6 in a weird place?) and you're not showing the code for them, which makes it difficult to help. But I guess you noticed your axes are flipped between both images, right?
comment on: http://stackoverflow.com/q/51912101

http://stackoverflow.com/a/51897872
downvote count: 0
type: Answer
has body: You can create a numpy array of complex numbers with broadcasting, 1j * np.arange(10) Or you can keep a 2D array where the first column is the real part and the second column is the imaginary part.
has comment: http://stackoverflow.com/comment/90757308
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51897822
answers question: http://stackoverflow.com/q/51897822
type: AcceptedAnswer

http://stackoverflow.com/a/52411184
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51937806
accepted answer of: http://stackoverflow.com/q/51937806
type: Answer
has body: After pd.melt , do the following: df['aggval'] = df['Week'].map(str) + df['Rotation'] df['aggval'] = df.groupby(['aggval']).cumcount()+1 pivot = df.pivot_table(index=['Rotation','aggval'], columns='Week', values='Name', aggfunc=lambda x: ' '.join(x)).fillna('') pivot = pivot.reindex(weeks, axis=1)
score: 0

http://stackoverflow.com/a/55065889
accepted answer of: http://stackoverflow.com/q/51862186
has body: As visible in this thread the atomic replace functionality for windows has been added for version 3.3. The patch is visible here. In the background MoveFileEx with when nessesary the MOVEFILE_REPLACE_EXISTING flag added is called. MoveFileEx is the same method as the openjdk calls. I can't find any documentation stating it is atomic, but the community seems to rely on it.
downvote count: 0
score: 7
has comment: http://stackoverflow.com/comment/131109968
upvote count: 7
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51862186
type: Answer

http://stackoverflow.com/a/51932519
type: AcceptedAnswer
downvote count: 0
score: 3
type: Answer
answers question: http://stackoverflow.com/q/51895602
upvote count: 3
accepted answer of: http://stackoverflow.com/q/51895602
has body: It seems that the distCoeffs in projectPoints are of the same type that calibrateCamera outputs. I ran a more thorough simulation where I added distortion using projectPoints, and then estimated it again using calibrateCamera, and it gave me the same distortion matrix. E.g with the following code distortion_given = np.array([[0.2, 0.01, 0.0, 0.0, 0.01]])# Note the negative sign ... = projectPoints(... , distortion_given , ...) ... , distortion_estimated , ... = calibrateCamera (...) print (distortion_given) print (distortion_estimated) which created the following projected image with Barrel distortion Resulted in: distortion_given = [[-0.2, -0.01, 0.0, 0.0, -0.01]] distortion_estimated = [[-0.19999985 -0.01000031 0. 0. -0.00999981]] This means that when this website I mentioned in the question should put more emphasis on the word typically, as I observed the opposite. barrel distortion (typically k_1 > 0) and pincushion distortion (typically k_1 &lt; 0).

http://stackoverflow.com/comment/90599739
type: Comment
type: QuestionComment
has text: @andrew_reece Thanks for the correction! Yes, it's possible, but that is outside the scope of my question. I hope (and plan) to utilize the answer in outer situations with similar circumstances.
comment on: http://stackoverflow.com/q/51822161
score: 0

http://stackoverflow.com/comment/90830278
type: Comment
has text: The python output is base64 encoded. crypt.crypt and crypto.pbkdf2 are not directly comparable anyway.
type: QuestionComment
comment on: http://stackoverflow.com/q/51937382
score: 0

http://stackoverflow.com/comment/90699442
type: Comment
comment on: http://stackoverflow.com/a/51841067
type: AnswerComment
has text: how do I save the output to a csv file ? What is best to use ? Regular Csv or Panda ? I need to have it printed into a column.
score: 0

http://stackoverflow.com/comment/98311698
type: Comment
has text: i thought you won't see DEBUG logs in the file, since the logger won't even pass them to the FileHandler?
comment on: http://stackoverflow.com/a/51908376
type: AnswerComment
score: 0

http://stackoverflow.com/a/52047197
score: 1
accepted answer of: http://stackoverflow.com/q/51954478
answers question: http://stackoverflow.com/q/51954478
upvote count: 1
type: AcceptedAnswer
has body: After putting it aside for about a week, I've finally had to sit down and fix this issue. For those with the same problem who're also scratching their heads at the answer to this question: Hide QScrollBar arrows, I've found a pretty obvious fix, now that I think about it. While the following style sheet does in fact hide the arrow buttons, it does not remove them. Which is obvious in practice, since with further testing, clicking the areas still moved the handle as if I were clicking on the arrow buttons. QScrollBar::left-arrow:horizontal, QScrollBar::right-arrow:horizontal, QScrollBar::add-page:horizontal, QScrollBar::sub-page:horizontal { border: none; background: none; color: none; } QScrollBar::add-line, QScrollBar::sub-line { border:none; background-color:none; } The solution is pretty simple: The arrow buttons don't appear to share a style with the rest of the scrollbar (since the scrollbar is separated into sub-styles). This means doing something like setting the width and height properties of the arrow buttons to 0px will make it so you can click on the handle. note: For good measure, I've also set the add-line and sub-line properties to 0px. QScrollBar::left-arrow:horizontal, QScrollBar::right-arrow:horizontal, QScrollBar::add-page:horizontal, QScrollBar::sub-page:horizontal { border: none; background: none; color: none; width: 0px; height: 0px; } QScrollBar::add-line, QScrollBar::sub-line { border:none; background-color:none; width: 0px; height: 0px; }
type: Answer
downvote count: 0

http://stackoverflow.com/a/75208146
score: 0
type: Answer
has body: I have came to the same issue. After reading colorgram.py description i have tried to extract 20 colors from an image. I've made it work with this code: import colorgram from turtle import Turtle, Screen turtle = Turtle() screen = Screen() colors = colorgram.extract("image.jpg", 20) #extracts colors as NamedTuples pallet_colors = [] for i in range (20): rgb = colors[i].rgb #rgb is saved as (Rgb(xxx,xxx,xxx)) r = rgb.r #r variable is saved as (xxx) g = rgb.g #g variable is saved as (xxx) b = rgb.b #b variable is saved as (xxx) new_color = (r, g, b) #new_color has Tuple form (xxx,xxx,xxx) pallet_colors.append(new_color) print(pallet_colors)
answers question: http://stackoverflow.com/q/51812672

http://stackoverflow.com/a/51849674
score: 3
answers question: http://stackoverflow.com/q/51849395
has comment: http://stackoverflow.com/comment/90653151
downvote count: 1
has body: I don't know how it works in this specific case, but in general you will use some 'behind the scenes magic': class Parent: def __init__(self): self.active_child = None def ContextManager(self): return Child(self) def Attribute(self): return self.active_child.Attribute() class Child: def __init__(self,parent): self.parent = parent def __enter__(self): self.parent.active_child = self def __exit__(self, exc_type, exc_val, exc_tb): self.parent.active_child = None def Attribute(self): print("Called Attribute of child") Using this code: p = Parent() with p.ContextManager(): attr = p.Attribute() will yield to following output: Called Attribute of child
has comment: http://stackoverflow.com/comment/90653086
type: Answer
upvote count: 4

http://stackoverflow.com/comment/92021265
type: QuestionComment
comment on: http://stackoverflow.com/q/51909312
has text: Ok. I moved my comment to an answer, given your confirmation that it's not tensorflow- or TPU-specific.
score: 0
type: Comment

http://stackoverflow.com/a/51897843
score: 12
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/102982441
has body: Would something like this work? tuple(df.itertuples(index=False, name=None))
upvote count: 12
answers question: http://stackoverflow.com/q/51897708

http://stackoverflow.com/q/51815161
has comment: http://stackoverflow.com/comment/90584782
has answer: http://stackoverflow.com/a/51815525
score: -1
has title: How do i import a pre-existing Django project into Eclipse?
tagged with: eclipse
has body: Currently, there is no option in eclipse to import a Django project even after installing PyDev in eclipse. I followed a solution which asks to generate a new python project and then copy .project and .pyproject to the existing project but eclipse throws an error "source folder is not found".
tagged with: import
answer count: 2
possible better answer: http://stackoverflow.com/a/51815525
upvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/51818231
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90585110
linked to: http://stackoverflow.com/q/2231474
tagged with: django
has comment: http://stackoverflow.com/comment/90584793
downvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/51818231

http://stackoverflow.com/q/51912101
has comment: http://stackoverflow.com/comment/90782966
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90774686
answer count: 0
downvote count: 0
score: 1
has body: I try to wrote an astrology application. This application plot a natal chart for a given time and location. The below image is the correct image. But what I want to do this, using sign symbols instead of names. And the below image is from when images were used instead of text. I did not understand why such components like "house numbers" are changed. The codes that create both text and image have no effect on "house numbers". Can you help me? Edit: For whole codes and images, visit this link. def draw_sign_names(self): asc = self.house_cusps()[1] for i, j in enumerate(self.SIGNS): end = 30 - (asc % 30) + 180 start = end - 30 start += (30 * i) end += (30 * i) if start &gt; 360: start -= 360 if end &gt; 360: end -= 360 if start &gt; 330: midpoint = (start + end + 360) / 2 else: midpoint = (start + end) / 2 if midpoint &gt; 360: midpoint -= 360 _x1, _y1 = self.x_y(angle=midpoint, r1=480, r2=400) img = plt.imread(f"{self.sign_pos()[1][i]}.png") plt.imshow(img, aspect="auto", interpolation="gaussian", extent=[_x1[0], _x1[1], _y1[1], _y1[0]]) # plt.text(sum(_x1) / 2, sum(_y1) / 2, self.sign_pos()[1][i], color="black", size=8, rotation=-10)
has comment: http://stackoverflow.com/comment/90774498
has comment: http://stackoverflow.com/comment/90821093
type: Question
has title: Python/Matplotlib: How can I display an image according to a specific (x, y) position?
tagged with: matplotlib
upvote count: 1
has comment: http://stackoverflow.com/comment/90781328
favorite count: 0

python-2.7
tags question: http://stackoverflow.com/q/51827820
tags question: http://stackoverflow.com/q/51908302
tags question: http://stackoverflow.com/q/51894217
tags question: http://stackoverflow.com/q/51899849
tags question: http://stackoverflow.com/q/51832141
tags question: http://stackoverflow.com/q/51865819
tags question: http://stackoverflow.com/q/51811671
tags question: http://stackoverflow.com/q/51843978
tags question: http://stackoverflow.com/q/51826128
tags question: http://stackoverflow.com/q/51869683
tags question: http://stackoverflow.com/q/51886759
tags question: http://stackoverflow.com/q/51805843
tags question: http://stackoverflow.com/q/51799953
tags question: http://stackoverflow.com/q/51848406
tags question: http://stackoverflow.com/q/51873147
tags question: http://stackoverflow.com/q/51825853
tags question: http://stackoverflow.com/q/51898026
tags question: http://stackoverflow.com/q/51861153
tags question: http://stackoverflow.com/q/51814397
tags question: http://stackoverflow.com/q/51804203
tags question: http://stackoverflow.com/q/51847671
tags question: http://stackoverflow.com/q/51881293
tags question: http://stackoverflow.com/q/51872892
tags question: http://stackoverflow.com/q/51848530
tags question: http://stackoverflow.com/q/51893858
tags question: http://stackoverflow.com/q/51950417
tags question: http://stackoverflow.com/q/51807885
tags question: http://stackoverflow.com/q/51882486
tags question: http://stackoverflow.com/q/51892835
tags question: http://stackoverflow.com/q/51803670
tags question: http://stackoverflow.com/q/51906293
tags question: http://stackoverflow.com/q/51928837
tags question: http://stackoverflow.com/q/51928532
tags question: http://stackoverflow.com/q/51913726
tags question: http://stackoverflow.com/q/51948219
tags question: http://stackoverflow.com/q/51954665
tags question: http://stackoverflow.com/q/51915626
tags question: http://stackoverflow.com/q/51940581
tags question: http://stackoverflow.com/q/51821846
tags question: http://stackoverflow.com/q/51827797
tags question: http://stackoverflow.com/q/51823427
tags question: http://stackoverflow.com/q/51817304
tags question: http://stackoverflow.com/q/51920058
tags question: http://stackoverflow.com/q/51814121
tags question: http://stackoverflow.com/q/51858004
tags question: http://stackoverflow.com/q/51926699
tags question: http://stackoverflow.com/q/51890024
tags question: http://stackoverflow.com/q/51830966
tags question: http://stackoverflow.com/q/51851931
tags question: http://stackoverflow.com/q/51871477
tags question: http://stackoverflow.com/q/51922119
tags question: http://stackoverflow.com/q/51923555
tags question: http://stackoverflow.com/q/51905869
tags question: http://stackoverflow.com/q/51898251
tags question: http://stackoverflow.com/q/51881157
tags question: http://stackoverflow.com/q/51870724
tags question: http://stackoverflow.com/q/51817104
tags question: http://stackoverflow.com/q/51848004
tags question: http://stackoverflow.com/q/51886880
tags question: http://stackoverflow.com/q/51921388
tags question: http://stackoverflow.com/q/51920849
tags question: http://stackoverflow.com/q/51806361
tags question: http://stackoverflow.com/q/51882146
tags question: http://stackoverflow.com/q/51849056
tags question: http://stackoverflow.com/q/51852983
tags question: http://stackoverflow.com/q/51913142
tags question: http://stackoverflow.com/q/51901478
tags question: http://stackoverflow.com/q/51846057
tags question: http://stackoverflow.com/q/51910978
tags question: http://stackoverflow.com/q/51833556
tags question: http://stackoverflow.com/q/51844916
tags question: http://stackoverflow.com/q/51901657
tags question: http://stackoverflow.com/q/51875669
tags question: http://stackoverflow.com/q/51878605
tags question: http://stackoverflow.com/q/51885092
tags question: http://stackoverflow.com/q/51902143
tags question: http://stackoverflow.com/q/51885868
tags question: http://stackoverflow.com/q/51840328
tags question: http://stackoverflow.com/q/51885394
tags question: http://stackoverflow.com/q/51823379

http://stackoverflow.com/q/51930898
type: AnsweredQuestion
upvote count: 0
has title: handling negative infinite numbers in pandas or numpy
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/90813129
has body: I have a file that contains large number of negative infinite numbers (-np.inf) and I've tried every solution I can think of to delete or replace them with 0. Here is what the data looks like. id kind value time 0 1 tmx2005-01 -3.402823e+38 01 1 1 tmx2005-02 -3.402823e+38 02 2 1 tmx2005-03 -3.402823e+38 03 3 1 tmx2005-04 -3.402823e+38 04 4 1 tmx2005-05 -3.402823e+38 05 As you can see, the infinite numbers are under the 'value' column and some of the solutions I tried are: df2.dropna() df2.fillna(0, inplace=True) df2.replace([np.inf, -np.inf], 0).dropna(subset=["value"], how="all") df2['value'].replace([np.inf, -np.inf], np.nan) df2['value']=df2['value'].mask(-np.isinf(df2['value'])) df2['value'][-np.isinf(df2['value'])] =0 Any thoughts on what I might be doing wrong or why its not working?
tagged with: dataframe
has answer: http://stackoverflow.com/a/51931586
score: -1
accepted answer: http://stackoverflow.com/a/51930997
answer count: 2
tagged with: pandas
downvote count: 1
has answer: http://stackoverflow.com/a/51930997
favorite count: 0
has comment: http://stackoverflow.com/comment/90814596
has comment: http://stackoverflow.com/comment/90811607
has comment: http://stackoverflow.com/comment/90811604
tagged with: python
possible better answer: http://stackoverflow.com/a/51931586

http://stackoverflow.com/q/51845791
answer count: 2
downvote count: 0
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51846021
has comment: http://stackoverflow.com/comment/90645019
tagged with: python
tagged with: parameters
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90645428
score: 1
possible better answer: http://stackoverflow.com/a/51845874
upvote count: 1
accepted answer: http://stackoverflow.com/a/51846021
has answer: http://stackoverflow.com/a/51845874
type: Question
has title: Updating different class attributes with one function
tagged with: class
has body: In a module, I would like to ask an instance of a class to update a class attribute if needed. Here's an example of the code: class ExampleClass: def __init__(self): self.data1 = None self.data2 = None self.data3 = None def updateData1(self, withInfo): self.dataUpdater(self.data1, withInfo) def updateData2(self, withInfo): self.dataUpdater(self.data2, withInfo) def updateData3(self, withInfo): self.dataUpdater(self.data3, withInfo) def dataUpdater(self, data, withInfo): # Very long and complex class function. # I would like to keep this logic in one function instead of making copies of it. data = 'new data' But when that data is updated and I try to get that particular data in another module it's still None. Now I understand what is going on. I am basically rewriting and making a new variable in the dataUpdater called data. And my particular class attribute is never being updated. My question is how can I update the data (the particular class attribute) that I passed in? I have spent half the day trying to figure this out and I can not seem to find anything like what I am trying.

http://stackoverflow.com/a/51813390
has body: A tar.gz file is just a tar file that's been gzipped. As you must know given that you wrote this Unix command: gzip -c example.tar &gt; example.tar.gz If you want to do the same thing from within Python, just use the gzip library: with open('example.tar', 'rb') as inf, gzip.open('example.tar.gz', 'wb') as outf: shutil.copyfileobj(inf, outf) In fact, this is directly equivalent to one of the Examples of Usage in the docs. Is this optimal? We're avoiding the untarring and tarring part. Which is pretty minimal work (tar is a dead-simple format…), but not zero. We obviously have to read every byte of the tarball, and you have to write every byte of the gzipped tarball, but we want to avoid reading the whole file at once (which might use up all your RAM) or reading so little at a time that you can't keep the disk moving. copyfileobj takes care of that for you. So, it's pretty much exactly the same work that the gzip tool does. But we're not creating a child process, and we're not relying on a tool that might not be there (e.g., on Windows, or iOS, or in some really weird scenario where you created a chroot that has python but not gzip).
has comment: http://stackoverflow.com/comment/90581669
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/51813355
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51813355
type: Answer

http://stackoverflow.com/q/51827349
tagged with: machine-learning
has answer: http://stackoverflow.com/a/51827499
type: Question
tagged with: neural-network
tagged with: recurrent-neural-network
has body: I have features in shape of (size,2) and labels in shape of (size,1) i.e. for [x,y] in feature the label will be z. I want to build an LSTM in keras that can do such job since the feature is linked somehow with the previous inputs i.e. 1 or multiple(I believe its a hyperparameter). Sample dataset values are:- features labels [1,2] [5] [3,4] [84] Here is what I have done so far:- print(labels.shape) #prints (1414,2) print(features.shape) #prints(1414,1) look_back=2 # reshape input to be [samples, time steps, features] features = np.reshape(features, (features.shape[0], 1, features.shape[1])) labels = np.reshape(labels, (labels.shape[0], 1, 1)) X_train, X_test, y_train, y_test = train_test_split(features,labels,test_size=0.2) model = Sequential() model.add(LSTM(4, input_shape=(1, look_back))) #executing correctly model.add(Dense(1)) #error here is "ValueError: Error when checking target: expected dense_1 to have 2 dimensions, but got array with shape (1131, 1, 1)" model.summary() model.compile(loss='mean_squared_error', optimizer='adam') model.fit(X_train, y_train, epochs=100, batch_size=1, verbose=2) So can anyone please help me build a minimal LSTM example to run my code? Thank you. I don't know how can dense layer have 2 dimensions I mean it is an integer telling how many units to use in the dense layer.
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/51827499
tagged with: keras
favorite count: 0
has title: LSTM output Dense expects 2d input
tagged with: python
type: AnsweredQuestion
score: 2
upvote count: 2

http://stackoverflow.com/a/51837908
has body: Try list comprehension to filter the list: log_lines = ["Aug 7 11:00:00 abc newsyslog[25714]: logfile turned over due to size&gt;1024K", "Aug 7 11:00:00.000 abc xyz lol"] arg = "Aug 7 11:00:00" [line for line in log_lines if line.startswith(arg)] Output: ['Aug 7 11:00:00 abc newsyslog[25714]: logfile turned over due to size&gt;1024K', 'Aug 7 11:00:00.000 abc xyz lol']
type: Answer
answers question: http://stackoverflow.com/q/51831939
score: 0

http://stackoverflow.com/q/51859489
tagged with: python
has answer: http://stackoverflow.com/a/51860555
has title: Algorithm for filtering table
type: UnansweredQuestion
score: 1
upvote count: 1
type: Question
has body: The following is the raw dataset for one candidate (df_wrong). It has some rows which are correct and some which are not. A row is considered incorrect if the timestamp for a stage does not follow the corresponding order logic for stage_names. For ex: Stage names must occur in the order of [Applied, Screen call, Hometask, Hometask review, 1st interview, 2nd interview, etc.]. Each stage can only occur once and must occur consecutively in the order shown above So this is df_wrong: df_wrong = pd.DataFrame({'stage_name':['Applied', 'Screen call', 'Hometask', '2nd interview', 'Hometask review','Screen call', '2nd interview' ], 'stage_num': [1,2,3,6,4,2,6], 'stage_time_mooving_in': ['2018-08-10 12:00:00', '2018-08-10 13:00:00', '2018-08-10 14:00:00', '2018-08-10 15:00:00', '2018-08-10 16:00:00', '2018-08-10 17:00:00', '2018-08-10 19:00:00']}) And I want to create an algorithm, that will convert wrong table in right one: df_right = pd.DataFrame({'stage_name':['Applied', 'Screen call', 'Hometask', 'Hometask review', '2nd interview' ], 'stage_num': [1,2,3,4,6], 'stage_time_mooving_in': ['2018-08-10 12:00:00', '2018-08-10 13:00:00', '2018-08-10 14:00:00', '2018-08-10 16:00:00', '2018-08-10 19:00:00']}) My question is how to create such algorithm. I try to sort df and remove duplicates, but I don't know how make it works for all cases. All stages, that can be in my pipeline listed in this table: full_pipeline = pd.DataFrame({'stage_name':['Applied', 'Screen call', 'Hometask', 'Hometask review', '1st interview', '2nd interview', 'Final interview','Offer'], 'stage_num': [1,2,3,4,5,6,7 ,8]}) NOTE: There is some suggestion, that can help in creating algorithm: First and last rows are always correct due to way of filling in. Note all stages can be in this table.
tagged with: algorithm
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/a/51817297
accepted answer of: http://stackoverflow.com/q/51817242
has comment: http://stackoverflow.com/comment/90588713
has comment: http://stackoverflow.com/comment/90588614
score: 3
has comment: http://stackoverflow.com/comment/90588763
type: AcceptedAnswer
downvote count: 0
has body: That's because you use re.split, which is designed to split the text at the patterns. Instead, use `re.findall: pattern = re.compile(r'\S*\.?w{3}\.\S+\.\S+') matches = pattern.findall(fileContent)
type: Answer
upvote count: 3
answers question: http://stackoverflow.com/q/51817242

http://stackoverflow.com/comment/90630234
has text: Thanks, I thought about that too, but it is somehow uncomfortable, as I should do this procedure in a loop. It's a solution I will implement in case I can't find anything else.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51838397

http://stackoverflow.com/q/51954549
upvote count: 2
accepted answer: http://stackoverflow.com/a/51956786
has answer: http://stackoverflow.com/a/51956051
tagged with: django
tagged with: python
has title: Lookup django model using two or more different keys
type: AnsweredQuestion
score: 2
tagged with: django-views
type: Question
has body: First time developing a django application, and am trying to do something somewhat non-standard... Is there a way to configure a view that will allow a user to look up a certain model by either one of two unique model attributes. Ideally, both of these URL schemes would be possible urlpatterns = [ path('api/somemodel/&lt;int:model_id&gt;/', views.SomeModelDetailView.as_view()) path('api/somemodel/&lt;str:model_name&gt;/', views.SomeModelDetailView.as_view()) ] A simplified example model... Both the id and the name are guaranteed to be unique. Also, by convention, my data is entered in such a way that a name will always be a string and never an integer from django.db import models class SomeModel(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=100, unique=True) Currently, I have this working with the following view... from rest_framework import generics from rest_framework import status from rest_framework.response import Response from . import models class SomeModelDetailView(generics.RetrieveAPIView): queryset = models.SomeModel.objects.all() serializer_class = serializers.SomeModelSerializer def get(self, request, model_name=None, model_id=None, format=None): field = None key = None try: if model_id: field = "model_id" key = model_id m = models.SomeModel.objects.get(id=model_id) elif model_name: field = "model_name" key = model_name m = models.SomeModel.objects.get(name=model_name) else: return Response("Neither model_id nor model_name were provided", status=status.HTTP_400_BAD_REQUEST) except models.SomeModel.DoesNotExist: return Response("Unknown {field}: {key}".format(field=field, key=key), status=status.HTTP_400_BAD_REQUEST) serializer_class = self.get_serializer_class() serializer = serializer_class(m) return Response(serializer.data) However, I am wondering if there is a better way that fits more into a ViewSet/Router (or other) DRF mechanic. Any ideas?
possible better answer: http://stackoverflow.com/a/51956144
has answer: http://stackoverflow.com/a/51956786
tagged with: django-rest-framework
has answer: http://stackoverflow.com/a/51956144
answer count: 3
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/140143782

http://stackoverflow.com/q/51837110
has body: I have multiple datasets, each with a different number of images (and different image dimensions) in it. In the training loop I want to load a batch of images randomly from among all the datasets but so that each batch only contains images from a single dataset. For example, I have datasets A, B, C, D and each has images 01.jpg, 02.jpg, … n.jpg (where n depends on the dataset), and let’s say the batch size is 3. In the first loaded batch, for example, I may get images [B/02.jpg, B/06.jpg, B/12.jpg], in the next batch [D/01.jpg, D/05.jpg, D/12.jpg], etc. So far I have considered the following: Use a different DataLoader for each dataset, e.g. dataloaderA, dataloaderB, etc., and then in each training loop randomly select one of the dataloaders and get a batch from it. However, this will require a for loop and for large number of datasets it would be very slow since it can’t be split among workers to do it in parallel. Use a single DataLoader with all of the images from all datasets together but with a custom collate_fn which will create a batch using only images from the same dataset. (I’m not sure how exactly to go about this.) I have looked at the ConcatDataset class but from its source code it looks like if I use it and try getting a new batch the images in it will be mixed up from among different datasets which I don’t want. What would be the best way to do this? Thanks!
has answer: http://stackoverflow.com/a/51843148
favorite count: 0
tagged with: pytorch
type: UnansweredQuestion
upvote count: 1
tagged with: python
has title: PyTorch data loading from multiple different-sized datasets
score: 1
type: Question
downvote count: 0
answer count: 1

adventure
tags question: http://stackoverflow.com/q/51939096
tags question: http://stackoverflow.com/q/51887888
tag name: adventure
type: Tag

http://stackoverflow.com/comment/90758439
comment on: http://stackoverflow.com/q/51903394
score: 0
type: Comment
type: QuestionComment
has text: Would the proper way to convey that be, if `found = False`, then `not found = True` when `found == True`? Or am I still wrong and that makes no sense to anyone? If so, how do you express `not found` becoming true, or false, for that matter?

http://stackoverflow.com/comment/90767563
comment on: http://stackoverflow.com/a/51908554
score: 0
type: AnswerComment
type: Comment
has text: If none elements found, I'm not sure it make sense to search for the second one with the same approach

http://stackoverflow.com/q/51951604
has title: Replace a line of a text file in python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90853594
tagged with: file
duplicate of: http://stackoverflow.com/q/39086
type: Question
has answer: http://stackoverflow.com/a/51951886
tagged with: replace
score: 0
answer count: 1
linked to: http://stackoverflow.com/q/39086
has comment: http://stackoverflow.com/comment/90854269
has body: I'm pretty new to Python and I'm trying to make a discord bot using discord.py and the idea is that you can earn coins that are showed on your profile. The problem is that I need to store the profiles in a single file so it looks like this userID1,10 userID2,20 userID3,30 Expected output: userID1,10 userID2,120 userID3,30 Basically "discord id of a user,amount of coins" and I'm trying to replace the line but with a different amount of coins and I have no idea on how to do this without making another file. This is all I have right now. def addExp(userID,Points): with open(fname) as f: for line in f: if userID in line: info = line.split(',') newPoints= int(info[1]) + Points UserID is the ID of an user so it's different for each user and Points is the amount of points I want to add
tagged with: python
accepted answer: http://stackoverflow.com/a/51951886

http://stackoverflow.com/comment/90555771
type: AnswerComment
has text: I want to copy content of the folder PSTools into the folder c:/WINDOWS/System32 so files will under System32 folder
comment on: http://stackoverflow.com/a/51799426
score: 0
type: Comment

http://stackoverflow.com/q/51835755
has answer: http://stackoverflow.com/a/51835829
has answer: http://stackoverflow.com/a/51835801
has comment: http://stackoverflow.com/comment/90625028
answer count: 3
upvote count: 0
favorite count: 0
has title: try - except struggle
has answer: http://stackoverflow.com/a/51835818
has body: I am trying to stop this program if the number the person enters is not 4 numbers long, using the try-except structure. I don't really get why it skips the except block if I enter a 2 or 3 digit number for example. All help appreciated. guess = int(input('Guess a 4 digit number:\n')) guesslist = [int(x) for x in (str(guess))] x = 0 y = 0 try: print(len(str(guess))) len(str(guess)) == 4 except: print('please enter a 4 digit number') quit() print('past')
tagged with: python
type: AnsweredQuestion
downvote count: 2
tagged with: except
type: Question
tagged with: try-catch
accepted answer: http://stackoverflow.com/a/51835818
score: -2
possible better answer: http://stackoverflow.com/a/51835801

http://stackoverflow.com/a/52744791
score: 22
answers question: http://stackoverflow.com/q/51901399
has body: It seems this is an issue from the socket module. It fails when the URL exceeds 64 characters. This is still an open issue https://bugs.python.org/issue32958 The error can be consistently reproduced when the first substring of the url hostname is greater than 64 characters long, as in "0123456789012345678901234567890123456789012345678901234567890123.example.com". This wouldn't be a problem, except that it doesn't seem to separate out credentials from the first substring of the hostname so the entire "[user]:[secret]@XXX" section must be less than 65 characters long. This is problematic for services that use longer API keys and expect their submission over basic auth. There is an alternative solution: It seems you're trying to use the Shopify API so I'll take it as an example. Encode {api_key}:{password} in base64 and send this value in the headers of your request eg. {'Authorization': 'Basic {token_base_64}'} See the example below: import base64 import requests auth = "[API KEY]:[PASSWORD]" b64_auth = base64.b64encode(auth.encode()).decode("utf-8") headers = { "Authorization": f"Basic {b64_auth}" } response = requests.get( url="https://[YOUR-SHOP].myshopify.com/admin/[ENDPOINT]", headers=headers )
type: Answer
upvote count: 22
downvote count: 0

http://stackoverflow.com/comment/90829033
type: AnswerComment
has text: @khelwood Here, at this fragment, I did not need to add more elements to the set; so I froze it.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51936552

http://stackoverflow.com/comment/90563243
comment on: http://stackoverflow.com/q/51803371
has text: I don't have it here, but I remember installing tensorflow at work (using pip & manual wheel installs since we don't have internet directly on our machines, so it took a while) and it imported properly. Using python 3.5 (anaconda)
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51843263
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: regex
downvote count: 0
type: Question
has title: The fastest way to apply all substitution regular expressions from a dict to a given text
score: 1
has answer: http://stackoverflow.com/a/51843887
tagged with: replace
upvote count: 1
answer count: 1
has body: I have a dict in the form (regexp, substitution_string) and I want to apply all regular expressions from this dict to the text (the order of operations doesn't matter). Now I have something along these lines: EMOTICON_REGEXPS = { r'(:D|;D|:-D|;-D|&lt;3|:\*)': ' EMOJIPOS ', r'[:|;]?(\))\1+': ' EMOJIPOS ', r'[:|;]?(\()\1+': ' EMOJINEG ', } def replace_emoticons(text): text_no_emoticons = text for (regexp, emoticon) in EMOTICON_REGEXPS_: text_no_emoticons = re.sub(regexp, emoticon, text_no_emoticons) return text_no_emoticons Is there any faster/shorter way to do the same thing? I also know about reduce(lambda t, (regex, emoticon): re.sub(regex, emoticon, t), EMOTICON_REGEXPS, text) but that doesn't appear to be any faster.

http://stackoverflow.com/q/51902830
type: Question
tagged with: python
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/90756828
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51902868
downvote count: 0
score: 1
tagged with: variables
has body: So here's a really quick program I though of writing down. var = input ("Insert A Variable: ") #Integer if isinstance(var, int): VarType = "Integer" #String if isinstance(var, str): VarType = "String" #List if isinstance(var, list): VarType = "List" #IDictionary if isinstance(var, dict): VarType = "Dictionary" print ("Variable Type: " + VarType + ".") But, every input returns the String value, seeing 12 as "12", [] as "[]", etc. Any ideas? Thanks in advance!
has title: How to have input recognize other types of variables?
favorite count: 0
accepted answer: http://stackoverflow.com/a/51902868

http://stackoverflow.com/comment/90675838
type: Comment
comment on: http://stackoverflow.com/q/51828454
score: 0
type: QuestionComment
has text: There's no better solution than the two options that I previously proposed, to the best of my knowledge.

http://stackoverflow.com/a/66938460
score: 1
has body: For anyone seeking clarification on the top answer's one-line solution, I thought this might be useful: [9*i + x for i, x in enumerate(sorted(random.sample(range(13), 4)))] The 9 represents: min_distance - 1 The 4 represents: sample_size The 13 represents: range_size - ((min_distance - 1) * (sample_size - 1)) e.g.; 40 - 9*3 = 13 in the example case. Also, if you find you run into an error where the sample size you want exceeds the calculated sample range (i.e.; 13 in the example), using random.choices() in place of random.sample() may help you, as it allows replacement when sampling, and achieves close to the same effect as the original solution. For example, to generate a list of 100 random integers with minimum distance 7 for a range of 765, the original solution will not work. However, the following will: [7*i+x for i,x in enumerate(sorted(random.choices(list(range(72)),k=100)))]) Where the values mirror what I laid out above, except min_distance - 1 is replaced by min_distance. So, 7 equals min_distance, 100 equals sample size, and 72 = range_size - (min_distance * (sample_size - 1)), or 765 - 7*99. This method extrapolates to any values of range, distance, sample for distance * sample &lt; range, which the original solution does not. The problem with using random.choices() here is that, while it does generate all possible outcomes, it does not guarantee equal likelihood of all possible outcomes, as in the original solution. Depending on the task, however, this may not be important to you.
downvote count: 0
answers question: http://stackoverflow.com/q/51918580
type: Answer
upvote count: 1

http://stackoverflow.com/comment/90651806
type: QuestionComment
has text: Sure , please :-)
score: 0
comment on: http://stackoverflow.com/q/51849095
type: Comment

http://stackoverflow.com/q/51812241
linked to: http://stackoverflow.com/q/8306654
has comment: http://stackoverflow.com/comment/90579419
has comment: http://stackoverflow.com/comment/90579438
has comment: http://stackoverflow.com/comment/90579487
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90579499
tagged with: recursion
score: 1
has body: I am going through popular interview questions, and came up with the following solution to "Compute all permutations of a string." def perm(s): if len(s) == 0: return [''] else: l = [] prev = perm(s[1:]) for old_str in prev: for i in range(len(old_str)): new_str = old_str[0:i] + s[0] + old_str[i:] l.append(new_str) return l However, this solution returns [] on all input. If I make the string in the base case any string other than the empty string, the computation runs as expected. For example, with 'hi' in the base case, perm('abc') returns ['abchi', 'bachi', 'bcahi', 'bchai', 'acbhi', 'cabhi', 'cbahi', 'cbhai', 'achbi', 'cahbi', 'chabi', 'chbai', 'abhci', 'bahci', 'bhaci', 'bhcai', 'ahbci', 'habci', 'hbaci', 'hbcai', 'ahcbi', 'hacbi', 'hcabi', 'hcbai'] As far as I can tell the algorithm for this code is correct. I am unsure of why the empty string isn't behaving as I anticipate, while other strings do. I have referenced this thread for better solutions, but I am still puzzled by why this one doesn't work.
upvote count: 1
has title: Why does [""] not behave as expected in recursion?
type: Question
has answer: http://stackoverflow.com/a/51812270
downvote count: 0
has comment: http://stackoverflow.com/comment/90579522

http://stackoverflow.com/comment/90674389
comment on: http://stackoverflow.com/q/51860945
score: 1
has text: This is not related to `self`. It would not even work with `x = 1` followed by `[x for i in range(2)]`. See [List comprehension scope error from Python debugger](https://stackoverflow.com/questions/24149168/list-comprehension-scope-error-from-python-debugger) for answers.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51949023
tagged with: arrays
has answer: http://stackoverflow.com/a/51949635
has comment: http://stackoverflow.com/comment/90852935
favorite count: 0
has answer: http://stackoverflow.com/a/51949520
linked to: http://stackoverflow.com/q/28207743
has title: Unable to convert String to numpy 1d array
tagged with: python
possible better answer: http://stackoverflow.com/a/51949520
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51949635
score: 0
upvote count: 1
downvote count: 1
linked to: http://stackoverflow.com/q/50881875
type: Question
has body: For facial recognition, we need to read vector from mysql DB and convert to 1D array for recognition. The following object is retrieved from mysql which is stored as JSON format in mysql. s1= [-0.12783311307430267, 0.13190957903862, 0.09596485644578934, -0.09712248295545578, -0.11780811846256256, 0.007217485923320055, -0.11222986876964568, -0.04876283556222915, 0.2216355949640274, -0.10998672991991044, 0.18791022896766665, 0.08736929297447205, -0.16356715559959412, -0.01818229630589485, -0.021847818046808243, 0.13041044771671295, -0.13738003373146057, -0.09671961516141891, -0.02172057516872883, -0.14230197668075562, 0.05242226645350456, 0.09029272198677064, -0.002328673377633095, 0.00397188076749444, -0.20264719426631927, -0.2703503370285034, -0.12626759707927704, -0.07806601375341415, 0.1267593950033188, -0.13493752479553223, -0.043157391250133514, -0.016596168279647827, -0.16287413239479065, -0.0656481683254242, 0.03958671912550926, 0.07427462935447693, -0.06913568824529648, -0.0629347711801529, 0.178871750831604, 0.08766687661409378, -0.09091204404830933, 0.011706589721143246, 0.04953945055603981, 0.27260822057724, 0.16323423385620117, 0.0253637433052063, 0.10930740833282472, -0.11138659715652466, 0.12710365653038025, -0.21879185736179352, 0.08703845739364624, 0.1319100558757782, 0.034353598952293396, 0.10928373038768768, 0.12201938033103944, -0.17505870759487152, 0.014886455610394478, 0.09721830487251282, -0.1538517326116562, 0.1672624796628952, 0.10802490264177322, -0.0300880316644907, -0.10113763064146042, -0.006332905497401953, 0.2025756984949112, 0.09179922193288804, -0.113119974732399, -0.20894797146320343, 0.15196490287780762, -0.12537285685539246, -0.05446625128388405, 0.11561021953821182, -0.11292491853237152, -0.11957288533449172, -0.2860523462295532, 0.08072254806756973, 0.4256277084350586, 0.15420164167881012, -0.11120182275772096, 0.0442705899477005, -0.06239746138453483, -0.043058544397354126, 0.03340786322951317, 0.06541167199611664, -0.12657742202…
tagged with: numpy
answer count: 2
has comment: http://stackoverflow.com/comment/90854464

http://stackoverflow.com/comment/90732500
has text: @avi There has been no `autocommit` parameter in PostgreSQL since 2003.
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51890055

http://stackoverflow.com/q/51830218
type: Question
accepted answer: http://stackoverflow.com/a/51830241
has body: I am trying to perform some action on my excel sheet using pandas and concatenating tables using the following codes. I have written the following functions to concatenate strings and save it in a data frame. def row_split(row, product, measure, price): out_dict = dict.fromkeys(row.index) for i in out_dict.keys(): out_dict[i] = [] cols = [x for x in out_dict.keys() if x not in [product, measure, price]] temp_list = [] for i, j in zip(row[measure],row[price]): try: temp_list.append([row['Products'] + ' ' + i, i, int(j)]) except ValueError: temp_list.append([row['Products'], np.nan, np.nan]) for i in cols: for x in row['Measure']: out_dict[i].append(row[i]) for x in temp_list: for i, j in zip([product, measure, price], x): out_dict[i].append(j) return pd.DataFrame(out_dict) split_tables = [] for index, row in (tab1).iterrows(): split_tables.append(row_split(row, 'Products', 'Measure', 'Price')) temp = pd.concat(split_tables[1], split_tables[2]) final_df = reduce(lambda x, y: pd.concat([x, y]), split_tables) But it returns an error- File "&lt;ipython-input-8-b1c137cbfc9c&gt;", line 48, in &lt;module&gt; temp = pd.concat(split_tables[1], split_tables[2]) File "/anaconda3/lib/python3.6/site-packages/pandas/core/reshape/concat.py", line 225, in concat copy=copy, sort=sort) File "/anaconda3/lib/python3.6/site-packages/pandas/core/reshape/concat.py", line 241, in __init__ '"{name}"'.format(name=type(objs).__name__)) TypeError: first argument must be an iterable of pandas objects, you passed an object of type "DataFrame" Can someone help me fix it?
has comment: http://stackoverflow.com/comment/90615282
has title: Concat tables in pandas
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/51830241
upvote count: 1
tagged with: python
type: AnsweredQuestion
score: 1

http://stackoverflow.com/q/51819063
tagged with: jenkins
score: 1
upvote count: 1
tagged with: triggers
has answer: http://stackoverflow.com/a/51834642
type: Question
has body: I'm new to python, Below is python script for triggering the Jenkins project. '''subprocess for triggering jenkins''' print("Update Started 2.........subprocess for triggering jenkins.") #cmd2 = ['curl', c3] mycmd = r'start chrome/new-tab {}'.format(c3) n2=subprocess.Popen(mycmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE) #wait for the process to terminate #out, err = n2.communicate() #errcode = n2.returncode '''wait until trigger the jenkins''' print("Wait until trigger the jenkins..................") # Deadlock is happening here. n2.wait() print("Wait done.......................................") it's not triggering the project, But, When i tried in Debug mood - Deadlock is happening at this place n2.wait() Below is log of the script: Update Started 2.........subprocess for triggering jenkins. Wait until trigger jenkins.................. Update 1: When I tried by modifying.. n2.wait(10) Below is the console printed data. Traceback (most recent call last): File "C:/Users/adevaraj/Desktop/Jenkins_CVS_Testing_Apr/CVS_LOG_Compare.py", line 189, in &lt;module&gt; n2.wait(10) File "C:\Program Files (x86)\Python36-32\lib\subprocess.py", line 1057, in wait raise TimeoutExpired(self.args, timeout) subprocess.TimeoutExpired: Command 'start chrome/new-tab http://localhost:8080/job/P16G0804_GM_A2XX_PSS/build?token=A2XX' timed out after 10 seconds Update 2: Url is fetching from Excel sheet(That code is not posted here) Update 3: In this code c3 is url of the trigger from backend Can any one help me out.
has title: Command for triggering jenkins is not working
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/51838397
has body: solution 1 I would suggest breaking your pipeline up in smaller steps, which can then be automated in a bash script etc. First you generate all the commands that needs to be run through slurm. If you submit them as a slurm job array (see e.g. here), you can then simultaneous submit the script that parses the output of all these commands. Using slurm dependencies, you can make this job start only after the job array has finished. solution 2 You could do a while loop in your python script and check the status of the jobs: import time t = time.time() while True: # Break if this takes more than some_limit if time.time() - t &gt; some_limit: break # Check if the jobs are done. This could be done by # grep'ing squeue for your username and some tags # that you name your jobs check_for_completion() # Sleep for a while depending on the estimated completion time of the jobs time.sleep(some_time) solution 3 Reserve N nodes on slurm and run your script there. This avoids cluttering the front end. I suggest gnu parallel to distribute your jobs on the node.
score: 5
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/90630576
has comment: http://stackoverflow.com/comment/90630234
accepted answer of: http://stackoverflow.com/q/51838249
answers question: http://stackoverflow.com/q/51838249
has comment: http://stackoverflow.com/comment/90631141
has comment: http://stackoverflow.com/comment/90630638
upvote count: 5

http://stackoverflow.com/comment/90658761
type: Comment
has text: Requiring "run as administrator" to get elevated access was meant to encourage developers to write code that works for standard users. A better design would save per-user data under `%LocalAppData%` or `%AppData%` (roaming), or for all users under `%ProgramData%`. The latter requires modifying security on a subdirectory (e.g. via icacls.exe) to allow all users to modify files. That could also be done for a sudirectory of the application directory under `%ProgramFiles%`, but `%ProgramData%`is the more obvious place for program data.
comment on: http://stackoverflow.com/q/51842612
score: 0
type: QuestionComment

http://stackoverflow.com/q/51842335
has answer: http://stackoverflow.com/a/52044581
type: AnsweredQuestion
tagged with: python-requests
type: Question
accepted answer: http://stackoverflow.com/a/52044581
tagged with: nested-table
score: 0
tagged with: token
answer count: 1
has body: im trying to get the info of some tables in the form of a json file. The thing is i can't seem to get the right tables. See, there are two json files, the one i can get in the page, but this one just contains the non nested info, this one i can get just fine. The problem seems to be the nested ones. the print of the tables i need to get: I need the content of all those tables in a json file, but, i cant seem to get the right tokens in this case. And they allways return the login page, as if the session had expired. here is the code i am using to scrape the tables: #does a json post for the last 100 elements url = "https://Awebsite.com/virtualaccount/entries" querystring = {"userId":"userid","moffset":"0"} payload = "sEcho=1&iColumns=4&sColumns=DateCtz%2CReason%2CDescription%2CFormattedAmount&iDisplayStart=0&iDisplayLength=100&mDataProp_0=DateCtz&mDataProp_1=Reason&mDataProp_2=Description&mDataProp_3=FormattedAmount&sSearch=&bRegex=false&sSearch_0=&bRegex_0=false&bSearchable_0=true&sSearch_1=&bRegex_1=false&bSearchable_1=false&sSearch_2=&bRegex_2=false&bSearchable_2=false&sSearch_3=&bRegex_3=false&bSearchable_3=false&sSortCol%5B0%5D=DateCtz&bSortDir%5B0%5D=false&iSortingCols=1&bSortable_0=true&bSortable_1=false&bSortable_2=false&bSortable_3=false" pgtos = session.post(url,params=querystring,data=payload,headers=headers) #gets the texts and converts it in python json json_data = pgtos.text json1_data = json.loads(json_data) cooki = session.cookies.get_dict() coooookie = pgtos.cookies.get_dict() print 'cookies' print cooki print coooookie print cookie #here is the postman area im using... the problem is i can't seem to get the payload __requestverificationtoken right. If i use the postman one it works for a while before it expires. url = "https://Awebsite.com/virtualaccount/transactions" querystring = {"entryId":"<each one of the tables has a diferent entryId>"} payload = "__RequestVerificationToken=QMA2UREXdlRfwIagBWIjekZG4D1ykXrFXxtWnzWV3kc55529C26MyKbL4pHNbaiTjBBAvr…
has title: Can't get the right tokens for the nested tables
tagged with: python

http://stackoverflow.com/q/51926443
answer count: 1
tagged with: pandas
tagged with: python
favorite count: 0
has title: groupby by max of column and returns the complete row
has body: I have a dataframe with 5 different columns. My actual problem is groupby a specific field with a max() and return the row that fulfils this condition. Example (I put the code and a print-screen of the data frames): A = pd.DataFrame([[datetime(2005,1,1), datetime(2005,1,2), 1240, 1234, 12],\ [datetime(2005,1,1), datetime(2005,1,2), 1250, 1235, 13], [datetime(2005,1,1), datetime(2005,1,3), 1230, 1235, 12], [datetime(2005,1,1), datetime(2005,1,3), 1240, 1235, 13], [datetime(2005,1,1), datetime(2005,1,4), 1240, 1235, 12], [datetime(2005,1,1), datetime(2005,1,5), 1240, 1235, 13], [datetime(2005,1,1), datetime(2005,1,5), 1240, 1233, 11], [datetime(2005,1,1), datetime(2005,1,6), 1240, 1235, 14]], \ columns=['quote_date', 'expiration', 'strike', 'price', 'var']).set_index(['quote_date', 'expiration', 'strike']) If I groupby by strike, I will get only the quote_date, expiration and strike: A.reset_index().groupby(by = ['quote_date', 'expiration'])['strike'].max() The goal is to obtain the following dataframe:
has answer: http://stackoverflow.com/a/51926488
accepted answer: http://stackoverflow.com/a/51926488
type: AnsweredQuestion
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/90803458
type: Question
has comment: http://stackoverflow.com/comment/90802456
upvote count: 1

http://stackoverflow.com/a/51803511
score: 1
type: Answer
upvote count: 1
has body: You could use numpy, and the only loops used will be implicit, and fast. But also less readable: import numpy as np &gt;&gt;&gt; np.stack(np.array(list1)[:,0])[:,0] array([100, 200, 300, 400])
downvote count: 0
answers question: http://stackoverflow.com/q/51803476

http://stackoverflow.com/q/51864730
answer count: 4
favorite count: 0
has comment: http://stackoverflow.com/comment/90681695
downvote count: 2
tagged with: jinja2
type: AnsweredQuestion
tagged with: plotly
tagged with: matplotlib
has answer: http://stackoverflow.com/a/51881060
has answer: http://stackoverflow.com/a/51864846
has answer: http://stackoverflow.com/a/63983926
has title: What is the process to create pdf reports with charts from a DB?
type: Question
possible better answer: http://stackoverflow.com/a/63983926
has answer: http://stackoverflow.com/a/66490549
has body: I have a database generated by a survey to evaluate university professors. What I want is a python script that takes the information from that database, generates a graphing table for each user, creates graphs for each user, and then renders it in a template to export it to a pdf. What does the database look like? User Professor_evaluated Category Question Answer _________________________________________________________________ Mike Professor Criss respect 1 3 Mike Professor Criss respect 2 4 Mike Professor Criss wisdom 3 5 Mike Professor Criss wisdom 4 3 Charles Professor Criss respect 1 3 Charles Professor Criss respect 2 4 Charles Professor Criss wisdom 3 5 Charles Professor Criss wisdom 4 3 Each teacher has several categories assigned to be evaluated (respect, wisdom, etc.) and in turn each category has associated questions. In other words, a category has several questions. Each row of the DB is the answer to a question from a student evaluating a teacher What do I need? I need to create a script for automatically generate pdf reports that summarizes this information through charts, for example a chart with the overall score of each teacher, another chart with the score of each teacher by category, another chart with the average of each student, etc..Finally, every teacher would have a report.I want a report like this What is my question? my question is about which python packages and modules I would need to do this task. And what would be the general process of doing so. I don't need the code, because I know the answer is very general, but the knowledge of how I could do it. For example: you would first need to process the information with pandas, to create a table that summarizes the information you want to graph, then plot it, then create a template of your report with XYZ module and then export it to pdf with XYZ module.
accepted answer: http://stackoverflow.com/a/51881060
score: 55
upvote count: 57
tagged with: pandas
tagged with: python

http://stackoverflow.com/comment/126135680
type: Comment
comment on: http://stackoverflow.com/a/51913423
has text: Where shall you add `&audio=yes`to the end of the code to only make phone calls?
type: AnswerComment
score: 0

http://stackoverflow.com/q/51865072
tagged with: numpy
has comment: http://stackoverflow.com/comment/90682979
has answer: http://stackoverflow.com/a/51865158
answer count: 2
accepted answer: http://stackoverflow.com/a/51865800
favorite count: 0
possible better answer: http://stackoverflow.com/a/51865158
tagged with: python
score: -2
type: AnsweredQuestion
downvote count: 3
upvote count: 1
has body: I have this code: qcmz = session1.query(func.sum(KCom.c1)).filter(KCom.users_id != current_user.id and KCom.ofv_id == cmz_id).all() qcmz1 = np.array(qcmz) + 0. qcmz2 = float(qcmz1[0]) qcmz3 = float("{0:.2g}".format(qcmz2)) And is returning this error: Traceback (most recent call last): File "/home/ubuntu/workspace/avb/venv/lib/python3.6/site-packages/flask/app.py", line 1982, in wsgi_app response = self.full_dispatch_request() File "/home/ubuntu/workspace/avb/venv/lib/python3.6/site-packages/flask/app.py", line 1614, in full_dispatch_request rv = self.handle_user_exception(e) File "/home/ubuntu/workspace/avb/venv/lib/python3.6/site-packages/flask/app.py", line 1517, in handle_user_exception reraise(exc_type, exc_value, tb) File "/home/ubuntu/workspace/avb/venv/lib/python3.6/site-packages/flask/_compat.py", line 33, in reraise raise value File "/home/ubuntu/workspace/avb/venv/lib/python3.6/site-packages/flask/app.py", line 1612, in full_dispatch_request rv = self.dispatch_request() File "/home/ubuntu/workspace/avb/venv/lib/python3.6/site-packages/flask/app.py", line 1598, in dispatch_request return self.view_functions[rule.endpoint](**req.view_args) File "/home/ubuntu/workspace/avb/venv/lib/python3.6/site-packages/flask_login/utils.py", line 228, in decorated_view return func(*args, **kwargs) File "/home/ubuntu/workspace/avb/app.py", line 822, in fcmz qcmz1 = np.array(qcmz) + 0. TypeError: unsupported operand type(s) for +: 'NoneType' and 'float' The ideea is when the db table is populated is not returning any errors only when is empty, I mean when the KCom.c1 asociated to another by ForeignKey and is empty is returning this issue.
has comment: http://stackoverflow.com/comment/90683178
has title: I need a hint how to sorted out this error
type: Question
has answer: http://stackoverflow.com/a/51865800
linked to: http://stackoverflow.com/q/42681231
has comment: http://stackoverflow.com/comment/90682989
tagged with: sqlalchemy

http://stackoverflow.com/q/51900185
type: Question
has body: I'm trying to develop some graphs using bqplot in Python but I'm having some questions regarding the documentation and where I can find the appropriate options to personalize a graph. I'm trying to make a boxplot graph and chenge the axes_options, but I don't find anywhere what's the possible options of 'axes_options' argument. Here's a toy example of the boxplot that I want to change: import bqplot.pyplot as plt x = [1] y = [[7,9,7,6,4,3,2,5,6,7,1,2,3,1,4.4,7.7]] fig = plt.figure() # add x and y labels using axes_options axes_options = {'x': {'label': 'X'}, 'y': {'label': 'Variable Value'}} boxes = plt.boxplot(x, y, box_fill_color='gray', outlier_fill_color='black', axes_options=axes_options) fig How can I, for example, change axes limits inside the axes_options dictionary? And how can I find the available options?
has comment: http://stackoverflow.com/comment/90811123
has comment: http://stackoverflow.com/comment/90751850
tagged with: matplotlib
score: 0
answer count: 1
has title: bqplot documentation in Python
has answer: http://stackoverflow.com/a/51962396
has comment: http://stackoverflow.com/comment/90752805
tagged with: bqplot
tagged with: python
has comment: http://stackoverflow.com/comment/90756981
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90751650

http://stackoverflow.com/q/51867176
has title: Splitting a single Dictionary Key and Value based on space in Python
has answer: http://stackoverflow.com/a/51867312
upvote count: 3
tagged with: split
linked to: http://stackoverflow.com/q/51878354
downvote count: 1
has answer: http://stackoverflow.com/a/51867381
has body: I am fairly new to Python and not really sure where to start on this, so please forgive the poor directions. Say I've got a dictionary: Dict = {'Name': 'Dr. John Smith'} How would I go about splitting that to create: Dict = {'Title': 'Dr.' 'First': 'John' 'Last': 'Smith'}
favorite count: 0
answer count: 3
type: UnansweredQuestion
tagged with: python
tagged with: dictionary
score: 2
type: Question
has answer: http://stackoverflow.com/a/51867234

http://stackoverflow.com/a/51802828
has comment: http://stackoverflow.com/comment/90562078
answers question: http://stackoverflow.com/q/51802770
score: 1
accepted answer of: http://stackoverflow.com/q/51802770
has comment: http://stackoverflow.com/comment/90562135
has comment: http://stackoverflow.com/comment/90562200
has comment: http://stackoverflow.com/comment/90562111
has comment: http://stackoverflow.com/comment/90562061
has comment: http://stackoverflow.com/comment/90562249
has comment: http://stackoverflow.com/comment/90562138
type: AcceptedAnswer
downvote count: 0
has body: change "D:\Projects\Python\Practice\1.png" into "D:\\Projects\\Python\\Practice\\1.png" a single backslash \ acts as a escape character. So you can see in your error that the program reads your paths as "D:\Projects\Python\Practice .png", which is wrong.
type: Answer
upvote count: 1

http://stackoverflow.com/comment/90607271
score: 1
comment on: http://stackoverflow.com/a/51826196
has text: @MrYouMath If you put code or pseudocode in the comments you will not understand, please edit your question and add your full .kv.
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/90580433
comment on: http://stackoverflow.com/q/51812575
score: 0
type: Comment
type: QuestionComment
has text: [This question](https://stackoverflow.com/questions/3567238/) explains things well, and has a link to the Tkinter Book article with an extensive and clear example (although that example has to be updated from Python 2.4).

http://stackoverflow.com/a/51949408
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51949034
type: Answer
has comment: http://stackoverflow.com/comment/90849315
accepted answer of: http://stackoverflow.com/q/51949034
upvote count: 3
score: 3
has comment: http://stackoverflow.com/comment/90848668
has body: Using np.interp a=df[0].values np.interp(a, (a.min(), a.max()), (0, +1)) Out[36]: array([0. , 0.70967742, 1. , 0.35483871])
has comment: http://stackoverflow.com/comment/90849327

http://stackoverflow.com/comment/90565799
has text: Possible duplicate of [Calling an external command in Python](https://stackoverflow.com/questions/89228/calling-an-external-command-in-python)
comment on: http://stackoverflow.com/q/51804930
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51861871
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/90676401
linked to: http://stackoverflow.com/q/988228
has comment: http://stackoverflow.com/comment/90676205
has comment: http://stackoverflow.com/comment/90677229
type: UnansweredQuestion
tagged with: web-scraping
upvote count: 1
downvote count: 1
type: Question
has body: example_string = "Bla bla {"value": "1"} bla bla" Is there a way I can search through a string with the goal of extracting only the dictionary(s) without using regular expressions? I am trying to extract a dictionary in a script tag of a website. EDIT: I added the exact string below. Didn't want to use regex simply because I am not familiar with it and was looking for an easier way (performance is not an issue). I tried the suggested solution with regex with no succes. """ var spConfig = new Product.Config({"attributes":{"6993":{"id":"6993","code":"irs_02010201_asafstand","label":"Asafstand","multiselect":false,"options":[{"id":"289022","label":"72 mm","price":0,"oldPrice":-45.76,"products":["1212907","1280900"]},{"id":"289025","label":"92 mm","price":0,"oldPrice":-45.76,"products":["1280407","1280899","1289700","1289750"]}]},"6994":{"id":"6994","code":"irs_02010201_doornmaat","label":"Doornmaat","multiselect":false,"options":[{"id":"306161","label":"35 mm","price":0,"oldPrice":-45.76,"products":["1280899"]},{"id":"306205","label":"40 mm","price":0,"oldPrice":-45.76,"products":["1289750"]},{"id":"306192","label":"45 mm","price":0,"oldPrice":-45.76,"products":["1289700"]},{"id":"306194","label":"50 mm","price":0,"oldPrice":-45.76,"products":["1280900"]},{"id":"306034","label":"55 mm","price":0,"oldPrice":-45.76,"products":["1212907","1280407"]}]},"6995":{"id":"6995","code":"irs_02010201_krukhoogte","label":"Krukhoogte","multiselect":false,"options":[{"id":"306193","label":"1050 mm","price":0,"oldPrice":-45.76,"products":["1212907","1280407","1280899","1280900","1289700","1289750"]}]},"6996":{"id":"6996","code":"irs_02010201_kruknoot","label":"Kruknoot","multiselect":false,"options":[{"id":"289046","label":"8 mm","price":0,"oldPrice":-45.76,"products":["1212907","1280407","1280899","1280900","1289700","1289750"]}]},"6997":{"id":"6997","code":"irs_02010201_materiaa_eb7faf79","label":"Materiaal voorplaat","multiselect":false,"options":[{"id":"289083","label":"Verzinkt",…
has comment: http://stackoverflow.com/comment/90676129
has comment: http://stackoverflow.com/comment/90676213
has comment: http://stackoverflow.com/comment/90677894
has answer: http://stackoverflow.com/a/51862027
has answer: http://stackoverflow.com/a/51862122
has comment: http://stackoverflow.com/comment/90676107
has comment: http://stackoverflow.com/comment/90675993
has comment: http://stackoverflow.com/comment/90678655
has comment: http://stackoverflow.com/comment/90676712
has title: How do I extract a dictionary in a Python string?
score: 0
has comment: http://stackoverflow.com/comment/90676001
answer count: 3
has answer: http://stackoverflow.com/a/51862002

http://stackoverflow.com/comment/90638070
has text: @colidyre. Sorry I was using python2.7
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51842431
type: Comment

http://stackoverflow.com/a/51926545
has comment: http://stackoverflow.com/comment/90878296
score: 0
answers question: http://stackoverflow.com/q/51925842
has comment: http://stackoverflow.com/comment/90868250
has comment: http://stackoverflow.com/comment/90871931
has body: Hi is that what you want to do? DIC_01 = {'A': ['Low'], 'B': ['High']} DIC_02 = {'A': [2623.83740234375, -1392.9608154296875, 416.20831298828125], 'B': [1231.1268310546875, -963.231201171875, 1823.742431640625]} smv_X = [] smv_Y = [] for e in DIC_01: smv_X.append(DIC_02[e]) smv_Y.append(DIC_01[e][0]) print(smv_X) # [[2623.83740234375, -1392.9608154296875, 416.20831298828125], [1231.1268310546875, -963.231201171875, 1823.742431640625]] print(smv_Y) # ['Low', 'High'] for k,v in DIC_01.items(): # k = key # v = value
has comment: http://stackoverflow.com/comment/90871612
type: Answer

http://stackoverflow.com/comment/90773384
comment on: http://stackoverflow.com/a/51911534
has text: But, this is not a random walk as the values are not dependent on the previous values.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/51887811
downvote count: 0
has comment: http://stackoverflow.com/comment/90812917
has comment: http://stackoverflow.com/comment/94576291
upvote count: 2
answers question: http://stackoverflow.com/q/51887758
type: Answer
has body: There are couple of ways to stop autosaves. There is a contrib nbextension called AutoSaveTime if you have installed jupyter-contrib-nbextensions that adds an autosave time configuration on the toolbar of a notebook, just ensure: "autosavetime/main": true is set in your notebook.json configuration file. Alternatively in a Cell, to change the autosave value for the current notebook, you can write: %autosave 0 Or you can change your custom.js to make this permanent for all notebooks: define([ 'base/js/namespace', 'base/js/events' ], function(IPython, events) { events.on("notebook_loaded.Notebook", function () { IPython.notebook.set_autosave_interval(0); } ); } );
has comment: http://stackoverflow.com/comment/90728452
score: 2

http://stackoverflow.com/q/51922523
has title: IronPython "name 'locals' is not defined" when running in sandbox but not when I run the script directly
tagged with: ironpython
has comment: http://stackoverflow.com/comment/90795245
has comment: http://stackoverflow.com/comment/90794726
score: 0
has body: If I call the locals function in an IronPython script sandboxed in this game I'm working on, I get an error "name 'locals' is not defined", but if I call it in a standalone script, it works. What could be deleting the locals function from my script context in the sandbox? edit: added an example script, this script works when I run it during a turn, but when I go to generate the next turn, it crashes saying str is not defined. import sys, imp; import __builtin__ as builtins; builtins_code = """"""; exec builtins_code in builtins.__dict__; import clr clr.AddReference('System.Core') import System clr.ImportExtensions(System.Linq) clr.AddReference('FrEee.Core') import FrEee import FrEee.Utility clr.ImportExtensions(FrEee.Utility.Extensions) from FrEee.Modding import Mod from FrEee.Game.Objects.Space import Galaxy from FrEee.Game.Objects.Civilization import Empire 'Generates ' + str(ShieldPointsGenerated) + ' shield points.' The ShieldPointsGenerated variable is injected like so: engine.GetBuiltinModule().SetVariable(kvp.Key, kvp.Value); where the key/value pairs are the variable names and values I'm using in the script.
has comment: http://stackoverflow.com/comment/93158780
tagged with: python
has comment: http://stackoverflow.com/comment/90795417
answer count: 0
type: UnansweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/90795236

http://stackoverflow.com/a/51887279
answers question: http://stackoverflow.com/q/51887086
has comment: http://stackoverflow.com/comment/90726022
has body: You do not call prep_score; score_image is never created - change class Scoreboard(): def __init__(self, ai_settings, screen, stats): .... .... self.prep_score to class Scoreboard(): def __init__(self, ai_settings, screen, stats): .... .... self.prep_score()
type: AcceptedAnswer
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/51887086

http://stackoverflow.com/comment/90636871
comment on: http://stackoverflow.com/a/51841842
has text: Probably you can also add a third option as I wrote in my comment above. It would be helpful to other people reading your answer in the future.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/51843054
favorite count: 0
has title: Python Windows raw socket invalid bind argument
tagged with: sockets
tagged with: windows
tagged with: python
has answer: http://stackoverflow.com/a/53681672
tagged with: python-3.x
type: UnansweredQuestion
upvote count: 1
type: Question
tagged with: raw-sockets
linked to: http://stackoverflow.com/q/39924563
score: 1
has body: I want to create a raw socket in Windows to connect to a specific interface on my laptop. I have it working on Linux but it does not work in Windows. This is my code that is fine in Linux but not in Windows: import socket s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_TCP) #s.bind(("192.168.1.100", 0)) s.bind((socket.gethostname(), 0)) #s.bind((socket.gethostbyname(socket.gethostname()), 0)) The commented out lines are suggestions I found here: Python Raw Socket to Ethernet Interface (Windows) but they did not work for me. I always get this error: Traceback (most recent call last): File "D:/raw_socket.py", line 5, in &lt;module&gt; s.bind((socket.gethostname(), 0)) OSError: [WinError 10022] An invalid argument was supplied I was unable to find a solution while researching this problem. Any help is highly appreciated.
downvote count: 0
answer count: 1

http://stackoverflow.com/q/51878000
has answer: http://stackoverflow.com/a/51881980
tagged with: python
tagged with: selenium-webdriver
has comment: http://stackoverflow.com/comment/90707416
tagged with: list
type: UnansweredQuestion
tagged with: selenium
has comment: http://stackoverflow.com/comment/90707263
has body: Month Jan Feb Mar Apr May Jun Jul Aug Sept Oct Nov Dec Dec Jan Jun I want to sort by alphabetically like Apr,Aug,Dec.. And want to remove the repeated values like Dec,Jan,Jun Once I am doing the below code i am able to read all the values in the drop-down , but not able to sort and remove duplicate values: dropdownoption = driver.find_elements_by_xpath("//*[@id='month']/option") print len(dropdownoption) for val in dropdownoption: print val.text
downvote count: 1
tagged with: webdriver
score: -1
has comment: http://stackoverflow.com/comment/90727615
type: Question
answer count: 3
upvote count: 0
has title: How do I sort the values of Dropdown list and also remove the duplicate values within the Dropdown through Selenium and Python
has answer: http://stackoverflow.com/a/51878518
has answer: http://stackoverflow.com/a/51878240
favorite count: 0

http://stackoverflow.com/comment/90647645
has text: Insert this line in your MergeSort function (as the first line) and see for yourself whats going on `print("Start %i End %i" % (start,end))` . This has nothing to do with recursion limit
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51846957
score: 0

http://stackoverflow.com/q/51859708
has answer: http://stackoverflow.com/a/51859787
downvote count: 0
has body: I am struggling with database relationships and Django, but have simplified my case drastically in order to get to the point. I have the following class: class Car(object): owner = 'No owner' def get_owner(self): return self.owner If I do not instantiate Car, but set nissan to None and then call get_owner, I get the following error: nissan = None nissan.get_owner() AttributeError. 'NoneType' object has no attribute 'get_owner' Is it possible to return None when calling nissan.get_owner() if nissan is None? The bigger picture: I am writing a Django templatetag that returns some data based on whether database relationships exist. It would be nice to write such code one one line though. In the end, I just want to get the value from get_owner() or get None. nissan.get_owner() or None Is not working here...
favorite count: 0
has answer: http://stackoverflow.com/a/51860434
has comment: http://stackoverflow.com/comment/90671667
type: UnansweredQuestion
tagged with: django
has answer: http://stackoverflow.com/a/51859790
tagged with: python
has comment: http://stackoverflow.com/comment/90672114
answer count: 4
has answer: http://stackoverflow.com/a/51859793
score: 1
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/90671945
has title: Call class method or return None

http://stackoverflow.com/comment/90680527
comment on: http://stackoverflow.com/q/51863562
type: Comment
type: QuestionComment
has text: mad_ I am using them separately as simply importing the csv into the database gives me a table with no primary key. Parfait, if I do that then I have a table with a primary key already assigned, right? Which I don't want.
score: 0

http://stackoverflow.com/q/51874176
downvote count: 0
has title: Create function from a Boolean field odoo 10
favorite count: 0
tagged with: python
type: AnsweredQuestion
score: 1
upvote count: 1
has body: I would like to create a function that checks whether the value of a boolean is True or False. If this boolean is True, I would like to execute a sequence of instructions. This function is created in the same class as my booleen field. Do I have to use a function decorator? My class : class ResPartner_school(models.Model): _name = 'ecole.partner.school' _order = 'id desc' half_pension = fields.Boolean(string='Restauration Scolaire', copy=False) My Function : def synchroHalfPension(self): if self.half_pension: print "BOOLEAN TRUE" else: print "BOOLEAN FALSE" How to simply verify that my function works ? I am a beginner. Thank you EDIT : The first part of my problem is solved and thank you. Now I notice something, the message is displayed as soon as I activate the boolean in Odoo. I would like the "half_pension is on" message to appear only when I save my form. How can I do that? cordially –
type: Question
tagged with: odoo
has answer: http://stackoverflow.com/a/51874619
accepted answer: http://stackoverflow.com/a/51874619
has comment: http://stackoverflow.com/comment/90702430
answer count: 1

http://stackoverflow.com/a/51919163
accepted answer of: http://stackoverflow.com/q/51873735
type: Answer
upvote count: 5
answers question: http://stackoverflow.com/q/51873735
score: 5
has body: For Debian/Ubuntu systems you just have to run sudo apt-get install glpk-utils You can check the installed version and the installation path by typing glpsol --version and which glpsol For OSX, the command is brew install glpk using Homebrew. Another solution consists in downloading the tarball directly from the official website https://www.gnu.org/software/glpk/#downloading and to build and install it.
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/51852893
type: UnansweredQuestion
tagged with: selenium
has comment: http://stackoverflow.com/comment/90666668
has title: Selenium common exception Timeout exception Message: timeout Error
has answer: http://stackoverflow.com/a/51905826
type: Question
score: 0
answer count: 1
has body: I've been working on an Online status check script for OkCupid. So what happens, if the person I am monitoring logs on OkCupid, the script will detect it based on &lt;div class="userinfo2015-basics-username-online-icon isOnline"&gt;&lt;/div&gt; which shows after they log on. It loops every minute to see if there are any status changes. For the most part it works well, it can go on for 30-40 minutes, but then it crashes. The output of the script looks like this: ---------------------------------------------- [i] Status | Last Checked | Update | ---------------------------------------------- [-] Offline 08-14 18:33:03 60 Sec | [+] Online 08-14 18:34:05 60 Sec | [+] Online 08-14 18:35:09 60 Sec | [+] Online 08-14 18:36:10 60 Sec | ---------------------------------------------- This is the loop: try: while 1: status = driver.find_elements_by_tag_name('div')[41].get_attribute('class') # Span Class for Online status driver.refresh() time_online = datetime.now().strftime('%m-%d %H:%M:%S') time.sleep(5) if status == str('userinfo2015-basics-username-online-icon isOnline'): print('[+] Online'+7*' '+time_online+5*' '+str(update+5)+' Sec |') elif status != str('userinfo2015-basics-username-online-icon isOnline'): print(bc.red+'[-] Offline'+6*' '+time_online+5*' '+str(update+5)+' Sec |') time.sleep(update) except KeyboardInterrupt: print(' Exiting\n'+46*'-') driver.quit() Then the error: Traceback (most recent call last): File "okCupid_online_status.py", line 38, in &lt;module&gt; status = driver.find_elements_by_tag_name('div')[41].get_attribute('class') # Span Class for Online status File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 539, in find_elements_by_tag_name return self.find_elements(by=By.TAG_NAME, value=name) File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 985, in find_elements 'value': value})['value'] or [] File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webd…
tagged with: python

http://stackoverflow.com/q/51841936
has comment: http://stackoverflow.com/comment/90643297
tagged with: database
has comment: http://stackoverflow.com/comment/90644637
has comment: http://stackoverflow.com/comment/90640905
has comment: http://stackoverflow.com/comment/90637318
has body: I am trying to fetch a .csv file stored in a Mysql database as a BLOB. I first tried with a .txt file and everything works perfectly, but I now have issue when it comes to a csv file : though the SELECT query works on Mysql, it doesn't seem to be the case on python. This error keeps appearing : SystemError: &lt;built-in method fetch_row of _mysql_connector.MySQL object at 0x00000172B02080B0&gt; returned a result with an error set Here is my code : import mysql.connector cnx = mysql.connector.connect(user='user', password='password', database='test') cursor = cnx.cursor() query = ("SELECT * FROM blob_test where id=1") cursor.execute(query) test_file = cursor.fetchone() FYI, I am just testing with a simple table with 3 columns : (id SMALLINT, name VARCHAR, file BLOB)
score: 0
tagged with: mysql-python
tagged with: python-3.x
has title: Fetch csv using Python mysql connector
answer count: 0
has comment: http://stackoverflow.com/comment/90695296
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90644078
tagged with: python
has comment: http://stackoverflow.com/comment/90734914
has comment: http://stackoverflow.com/comment/90643205
tagged with: mysql
has comment: http://stackoverflow.com/comment/90640828
has comment: http://stackoverflow.com/comment/90637521
type: Question
has comment: http://stackoverflow.com/comment/90734747

http://stackoverflow.com/q/51865934
type: Question
linked to: http://stackoverflow.com/q/8382847
tagged with: python
has comment: http://stackoverflow.com/comment/90783055
duplicate of: http://stackoverflow.com/q/8382847
has title: How to sftp connect through Paramiko with public key - python
tagged with: pysftp
upvote count: 1
type: UnansweredQuestion
tagged with: paramiko
downvote count: 0
answer count: 0
score: 1
favorite count: 0
has body: i'm using Paramiko to connect through sftp to a server.but i can't understand how to connect with below Putty User key file Code: local_path = "C:\blp\aisrvintraday1045.csv" remote_path = "/aisrvintraday1045.csv" cnopts = pysftp.CnOpts () cnopts.hostkeys.load('C:\Python code\SSH-KEY-08142018(private).ppk') with pysftp.Connection (host='sftp.bloomberg.com', username='user', password='pass', cnopts=cnopts) as sftp: sftp.get(local_path, remote_path) data = sftp.listdir () for i in data: print(i) sftp.close() I connect to it with this ppk file: PuTTY-User-Key-File-2: ssh-rsa Encryption: none Comment: rsa-key@20180814 Public-Lines: 12 [12 lines key] Private-Lines: 28 [28 lines key] Private-MAC: [hash] Error: (&lt;class 'paramiko.ssh_exception.SSHException'&gt;, SSHException('Bad host key from server',), &lt;traceback object at 0x7fa76269c5a8&gt;) Bad host key from server I've tried to include that ppk file and set to auth_public_key, but didn't work. Can you please help me? I am struggling for long time.
tagged with: sftp

http://stackoverflow.com/a/51895830
score: 0
has body: Inspired by N. Wouda's answer I tried yet another approach. When testing their answer I noticed a pattern in the indices resembling n-ary encoding (here for 3 sets): ... (1,1,0) (1,1,1) (0,0,2) (0,1,2) (1,0,2) &lt;- ! (1,1,2) (0,2,0) (0,2,1) (1,2,0) ... Notice that lower numbers increase before higher ones do. So I replicated this pattern in code: idx = np.zeros((len(args)), dtype=np.int) while max(idx) &lt; 50: # TODO stop condition yield [arg[i] for arg,i in zip(args,idx)] low = np.min(idx) imin = np.argwhere(idx == low) inxt = np.argwhere(idx == low+1) idx[imin[:-1]] = 0 # everything to the left of imin[-1] idx[imin[-1]] += 1 # increase the last of the lowest indices idx[inxt[inxt &gt; imin[-1]]] = 0 # everything to the right I took some shortcuts since I was just testing; the results are not too bad. While in the beginning this function outperforms N. Wouda's solution, it becomes worse the longer it goes. I think the "index-wave" is shaped differently, resulting in higher noise for indices further away from the origin. Interesting! Edit I thought this is quite interesting, so I visualized the way the indices are iterated over - JFYI :) Index wavefront N. Wouda Index wavefront from this answer
has comment: http://stackoverflow.com/comment/90743136
type: Answer
answers question: http://stackoverflow.com/q/51872181

http://stackoverflow.com/comment/90787063
comment on: http://stackoverflow.com/q/51916181
score: 0
type: Comment
type: QuestionComment
has text: As a part of the class, `getent()` needs to take a `self` parameter, and be referred to as `self.getent`. You also need to change `entvar` to `self.entvar`, so that it still exists when you need to access it.

http://stackoverflow.com/comment/90825914
has text: @DanielPaczuskiBak And if you somehow delete the list, your interpreter will probably segfault—but there's no way to delete the list without going under the covers of the interpreter. Just `del lst` doesn't delete the list, it just deletes a _variable_ which was _one reference to_ the list value. If there are any other references to it (like, say, the one inside the listiterator), the list is not garbage and will therefore not be deleted.
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51937482

http://stackoverflow.com/comment/93114502
type: QuestionComment
comment on: http://stackoverflow.com/q/51904912
has text: Hey, so were you ever able to fix this issue? The code seems correct, so it might be that there is some corrupted character or empty character in one row of your dataset.
score: 0
type: Comment

http://stackoverflow.com/comment/90709763
type: Comment
has text: I just edited, my apologies! I hope: `[['4027221', 'MX', '0.4', 1], ['4027222', 'MX', '0.4', 1]]`
comment on: http://stackoverflow.com/a/51878007
type: AnswerComment
score: 0

http://stackoverflow.com/q/51914373
type: UnansweredQuestion
tagged with: django
tagged with: python
tagged with: django-models
type: Question
answer count: 1
has title: Take advantage of Django Migration to save some data
score: 0
has body: I noticed that when you run Django Migration, some data is added to table auth_permission when a new model is created. Is there any way you can take advantage of migration process to do the same with your own models? I red Django Documentation about writing Migrations, but it only covers the creation of brand new migration processes, it doesn't say anything about using the default one for your own porpoises.
has answer: http://stackoverflow.com/a/51914479

http://stackoverflow.com/comment/90867047
has text: Does `module` have to be '*'? If it isn't optional, leave the default required. Or '+' if you want to provide more than one. Then the parser will reserve the last string for this Action. `argparse` does allow for required optionals and optional positionals, but -- it's simpler for and your users, if you don't mix the concepts.
comment on: http://stackoverflow.com/q/51954897
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90711312
type: QuestionComment
has text: this is the bare minimum i can cut down to, instead of simply asking """Return urls which only have visitors from the same country as the url was created from""" I have made an effort to provide you with examples and also the files. Also I have made the template. I know its not a free programming site, neither do i expect you to provide complete solution but just some pointers as to how I go about.
comment on: http://stackoverflow.com/q/51868723
score: 0
type: Comment

http://stackoverflow.com/comment/90596110
type: Comment
comment on: http://stackoverflow.com/a/51821008
has text: http://docs.python-requests.org/en/master/_modules/requests/exceptions/
score: 0
type: AnswerComment

http://stackoverflow.com/comment/90728553
has text: @ Junaid Ghauri. Thanks for response. Can you please elaborate what does you mean by python takes in another way around?
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51879515

http://stackoverflow.com/comment/90623440
comment on: http://stackoverflow.com/q/51834857
type: Comment
type: QuestionComment
has text: I found some questions which were somewhat simillar to this but none of them using boto3, so I asked this one as I'm in urgent need of answer.
score: 3

http://stackoverflow.com/a/51899848
type: Answer
answers question: http://stackoverflow.com/q/51899276
score: 0
has body: I quickly figure this one out. Apologies for the seemingly naive question, but hope it helps out other Python newbies like myself. The solution, as raised by @mattmilten, is to simply assign the output of the filtering to the same or a new data frame. That is, In [3]: to_drop = ['Clerk', 'Bagger'] df = df[~df['title'].isin(to_drop)] df Out[3]: fName lName email title 0 John Smith jsmith@gmail.com CEO

http://stackoverflow.com/comment/90556075
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51799104
has text: I dont. Please forgive me as I forgot to make the expected output clear.

http://stackoverflow.com/comment/90849062
type: QuestionComment
comment on: http://stackoverflow.com/q/51949554
score: 0
has text: I am confused on exactly what you are asking. Can you rephrase and add expected output from this given data.
type: Comment

http://stackoverflow.com/comment/90673915
type: AnswerComment
comment on: http://stackoverflow.com/a/51860765
has text: `12` is not a variable name... @lenik ;) and can not be `join`ed
type: Comment
score: 4

http://stackoverflow.com/a/51859037
has comment: http://stackoverflow.com/comment/90670125
accepted answer of: http://stackoverflow.com/q/51848277
upvote count: 2
answers question: http://stackoverflow.com/q/51848277
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90682652
type: Answer
has comment: http://stackoverflow.com/comment/90686048
has body: You have to pass the all_sprites argument in the Worker.__init__ method to the __init__ method of the Sprite class, so that the sprite will be added to this group. pygame.sprite.Sprite.__init__(self, all_sprites, groups) You could also rearrange the parameters of the __init__ method and pass the two groups as the last arguments (they will be added to the groups list). # In the Worker class. def __init__(self, idw, image_running, image_idle, image_accident, location, *groups): # Pass the two groups as the `groups` argument. Worker(idw, IMG_WORKER_RUNNING, IMG_WORKER_IDLE, IMG_WORKER_ACCIDENT, (50, 50), self.all_sprites, self.workers) In the while loop you need to blit a background surface or fill the screen every frame in order to clear it, then draw the sprites and finally update the screen with pygame.display.flip() (you need to indent it in your example). while carry_on: for event in pygame.event.get(): if (event.type == pygame.QUIT) or (simulation_time == 0): carry_on = False # You probably don't want to decrement the # simulation_time once per event. Dedent # this line to decrement it once per frame. simulation_time -= 1 agent_action = 0 send_alert = np.random.normal(0, 0.1, 1) if send_alert &gt; 0.2: agent_action = 1 self.all_sprites.update(self.screen, agent_action) # Blit a background surface or fill the screen. self.screen.fill((0, 40, 0)) # Fill with dark green. # Blit all sprites. self.all_sprites.draw(self.screen) # Update the screen. pygame.display.flip() clock.tick(20)
score: 2

http://stackoverflow.com/a/51955646
has comment: http://stackoverflow.com/comment/90862020
type: Answer
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/90861979
accepted answer of: http://stackoverflow.com/q/51955487
answers question: http://stackoverflow.com/q/51955487
has comment: http://stackoverflow.com/comment/90862118
upvote count: 2
has comment: http://stackoverflow.com/comment/90862221
type: AcceptedAnswer
has body: You forgot to provide the full code, notably, the exact place where you're trying to extract the selected items. I added some code to do it in a button, and it seems to work fine here: The code is your code, I only added this just before the call to mainloop(): # ... your code here ... import tkinter.messagebox as tkmsg def clicked(): selected = [list_box.get(pos) for pos in list_box.curselection()] tkmsg.showinfo(title='Selected', message='Items selected: {}'.format(', '.join(selected))) Button(root, text='Go!', command=clicked).pack() mainloop()
has comment: http://stackoverflow.com/comment/90861935

http://stackoverflow.com/comment/90784308
score: 0
type: AnswerComment
has text: You are absolutely current, in my code the exit definition comes *before* the try catch, that's why it worked for me..
comment on: http://stackoverflow.com/a/51916311
type: Comment

http://stackoverflow.com/q/51932123
has answer: http://stackoverflow.com/a/51932533
has body: I want to remove all lines from a CSV file which don't start with a number. As far as I understood I can do that by creating a new CSV file and I need to copy the desired rows from the input to the output file but when I execute my code, the output files separates every character with the default delimiter which in my case is , and it creates rows in the output file with , after every character. That's my code: import os, sys, csv input_dir = "/home/test/input/" for csv_in in os.listdir(input_dir): if csv_in.lower().endswith('.csv') and not csv_in.lower().startswith('fixed_'): csv_infile = input_dir + csv_in csv_out = input_dir + "fixed_" + csv_in with open(csv_infile) as f, open(csv_out, 'wb') as f_out: reader = csv.reader(f) writer = csv.writer(f_out) for row in f: if row.startswith(tuple('0123456789')): writer.writerow(row)
type: Question
has answer: http://stackoverflow.com/a/51932269
tagged with: copy
accepted answer: http://stackoverflow.com/a/51932269
score: 0
answer count: 2
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
possible better answer: http://stackoverflow.com/a/51932533
type: AnsweredQuestion
has title: Remove all rows in a CSV file which aren't starting with numbers in python

http://stackoverflow.com/comment/90718278
score: 0
has text: Can you provide samples of both input dataframes or create some toy dataframe with the problem and show the expected output from this data?
comment on: http://stackoverflow.com/q/51883275
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90945932
score: 0
type: Comment
has text: So the best is the most general solution with not remove original indices, working with duplicates values?
type: AnswerComment
comment on: http://stackoverflow.com/a/51944022

http://stackoverflow.com/comment/90678068
comment on: http://stackoverflow.com/q/51854661
type: Comment
has text: Thanks for the comment, @Zulan. I will consider your advice. As I already posted on comment before, I'm not targeting a specific subprocess or child process since there are many subprocesses (Let say, 10 `apache` are made by subprocess module. Then, `perf` should be created 10 times. That's nonsense.) So, I decided to use `-a` option. I will update my question and answer soon.
score: 0
type: QuestionComment

http://stackoverflow.com/comment/90753016
type: QuestionComment
comment on: http://stackoverflow.com/q/51900647
score: 0
has text: @lojza doing `import cx-Oracle` gives a syntax error on the '-' character
type: Comment

http://stackoverflow.com/comment/90768085
comment on: http://stackoverflow.com/a/51906984
type: Comment
score: 1
has text: Highly unlikely. OneToOnefield is the solution. Your solution is not pythonic
type: AnswerComment

http://stackoverflow.com/comment/90854861
type: Comment
type: AnswerComment
has text: @DanaMcDowelle you probably have to be more specific than that: where are you trying to remove the brackets? That error usually happens when you try to assign to a non-scalar to an element of an array, for instance `arr = np.arange(3); arr[0] = [1,2]`. I don't see anything like this in your code, apart from the undefined `rg.predict` call which I have no idea what might be :)
comment on: http://stackoverflow.com/a/51886940
score: 0

http://stackoverflow.com/q/51924095
upvote count: 2
tagged with: pubnub
has comment: http://stackoverflow.com/comment/90797686
has answer: http://stackoverflow.com/a/52028371
accepted answer: http://stackoverflow.com/a/52028371
score: 2
type: AnsweredQuestion
downvote count: 0
possible better answer: http://stackoverflow.com/a/51990324
favorite count: 0
has answer: http://stackoverflow.com/a/51990324
type: Question
has body: I want to use PubNub to publish a message from a Django view. I'm running my web app on pythonanywhere. It seems to work fine at first, but if I refresh the page a few times in succession, I eventually catch a RuntimeError exception with the message "can't start new thread". If I wait a bit (I'm not sure how long), it resumes working again, and then repeats the same behavior. It seems the issue is with starting a new thread for the callback, but I'm not sure. Here's the code for my view and callback in views.py: def my_view(request): try: pnconfig = PNConfiguration() pnconfig.subscribe_key = '&lt;sub key&gt;' pnconfig.publish_key = '&lt;pub key&gt;' pnconfig.ssl = False pubnub = PubNub(pnconfig) pubnub.publish().channel('MyDemoChannel').message({"text": "Message from my_view()"}).async(publish_callback) except: logger.exception("Caught exception in my_view()") context = {'val_1': 1, 'val_2': 2} return render( request, 'my_app/my_view.html', context) def publish_callback(envelope, status): if not status.is_error(): pass else: pass And the stack trace: [25/Aug/2018 11:30:25] ERROR [league.views:42] Caught exception in my_view() Traceback (most recent call last): File "/home/tennis/tennis.pythonanywhere.com/website/league/views.py", line 40, in my_view pubnub.publish().channel('MyDemoChannel').message({"text": "Message from my_view()"}).async(publish_callback) File "/home/tennis/.virtualenvs/tennis.pythonanywhere.com/lib/python3.6/site-packages/pubnub/endpoints/endpoint.py", line 116, in async cancellation_event=self._cancellation_event) File "/home/tennis/.virtualenvs/tennis.pythonanywhere.com/lib/python3.6/site-packages/pubnub/pubnub.py", line 68, in request_async callback, cancellation_event) File "/home/tennis/.virtualenvs/tennis.pythonanywhere.com/lib/python3.6/site-packages/pubnub/request_handlers/requests_handler.py", line 81, in async_request thread.start() File "/usr/lib/python3.6/threading.py", line 846, in start _start_new_thread(self._bootstrap, ()) Runtime…
answer count: 2
tagged with: django
tagged with: python
has title: Using PubNub to publish message in Django view
tagged with: pythonanywhere

http://stackoverflow.com/comment/90863402
type: QuestionComment
comment on: http://stackoverflow.com/q/51956261
score: 0
has text: what is the input data ?>
type: Comment

http://stackoverflow.com/a/51923511
type: Answer
has body: Here are some hyperparameters that you change:- Loss - Try changing the method used to calculate the loss from mse to a variation of crossentropy Optimizers - SGD is one the basic optimizer provided by Keras, You can try other optimizers such as Adam, RMSprop etc.. Learning rate - the rate at which the weights are updated You can also try changing the window size in Convolution Layers, also try different padding schemes in Maxpooling and Conv2D layers
score: 0
answers question: http://stackoverflow.com/q/51923075

http://stackoverflow.com/a/51868492
has body: You can run your desired Python executable directly from /path/to/Python/bin/python.exe .
score: 0
has comment: http://stackoverflow.com/comment/90689134
has comment: http://stackoverflow.com/comment/90689169
answers question: http://stackoverflow.com/q/51868433
has comment: http://stackoverflow.com/comment/90688955
has comment: http://stackoverflow.com/comment/90689145
has comment: http://stackoverflow.com/comment/90689246
has comment: http://stackoverflow.com/comment/90689056
type: Answer
has comment: http://stackoverflow.com/comment/90715059
has comment: http://stackoverflow.com/comment/90688929
has comment: http://stackoverflow.com/comment/90689054

http://stackoverflow.com/a/51799866
answers question: http://stackoverflow.com/q/51799818
has comment: http://stackoverflow.com/comment/90556270
accepted answer of: http://stackoverflow.com/q/51799818
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 11
has comment: http://stackoverflow.com/comment/90556512
upvote count: 11
has body: Use stack for MultiIndex Series, then SeriesGroupBy.value_counts and last unstack for DataFrame: np.random.seed(123) df = pd.DataFrame(np.random.choice(list('ABC'), size=(10,5)), columns=['c1','c2','c3','c4','c5'], index=pd.MultiIndex.from_product([['foo', 'bar'], ['w','y','x','y','z']])) print (df) c1 c2 c3 c4 c5 foo w C B C C A y C C B C B x C B A B C y B A C A B z C B A A A bar w A B C A C y A A B A B x A A A C B y B C C C B z A A C B A df1 = df.stack().groupby(level=[0,2]).value_counts().unstack(1, fill_value=0) print (df1) c1 c2 c3 c4 c5 bar A 4 3 1 2 1 B 1 1 1 1 3 C 0 1 3 2 1 foo A 0 1 2 2 2 B 1 3 1 1 2 C 4 1 2 2 1

http://stackoverflow.com/comment/90836550
type: QuestionComment
comment on: http://stackoverflow.com/q/51942665
score: 0
has text: @GPT14 You are right, I have overlooked the question description
type: Comment

http://stackoverflow.com/q/51956252
score: 0
answer count: 1
has title: Python-Kivy: BoxLayout with stretch capability
tagged with: python
tagged with: kivy
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51957961
type: Question
has body: How can I make my boxlayout expand according to dynamically added content? Here is my code to illustrate what I am trying to do: main.py from kivy.app import App from kivy.uix.label import Label class TestApp(App): def add_label(self): label = Label(text='StackOverflow', color=(0,0,0,1)) self.root.ids.myBox.add_widget(label) if __name__ == '__main__': TestApp().run() test.kv BoxLayout: orientation: 'vertical' spacing: 400 BoxLayout: orientation: 'vertical' size_hint: None, None size: dp(280), dp(100) pos_hint: {'center_x': 0.5, 'center_y': 0.5} #width: self.minimum_width #height: self.minimum_height id: myBox background_color: (1,1,1,1) canvas.before: Color: rgba: self.background_color Rectangle: pos: self.pos size: self.size Button: text: 'BUTTON' size_hint: None, None size: dp(100), dp(50) pos_hint: {'center_x': 0.5, 'center_y': 0.1} on_release: app.add_label() The button has the effect of dynamically adding a label to the boxlayout. But the more the labels are added, the size of the boxlayout does not change and the texts are superimposed. Thanks in advance for your help.
has answer: http://stackoverflow.com/a/51957961

http://stackoverflow.com/a/51876620
upvote count: 3
downvote count: 0
has body: One solution is to set the the foreign key to UNIQUE and NOT NULL, that is: user_id = Column(Integer, ForeignKey('user.id'), unique=True, nullable=False) That ensures an exception is raised once the two elements with the same foreign key are inserted into the database. As the ORM doesn't touch the database while the objects are being created, it has no way of ensuring the consistency of the database up until the point of insertion.
answers question: http://stackoverflow.com/q/51875493
type: Answer
score: 3

docker-api
tag name: docker-api
type: Tag
tags question: http://stackoverflow.com/q/51853154

http://stackoverflow.com/a/51864931
answers question: http://stackoverflow.com/q/51864930
type: Answer
upvote count: 2
has body: After testing it out for myself, the chat-id does change on migration to a supergroup. However I found the following way, using python-telegram-bot to keep your chat-ids updated: def migchat(bot, update): oldchatid = update.message.migrate_from_chat_id newchatid = update.message.chat.id # process those values as needed (e.g. update a database) dispatcher.add_handler(MessageHandler(Filters.status_update.migrate, migchat)) This uses the Filters submodule to call migchat whenever a chat is being migrated. This is how the JSON response of the message from the /getUpdates call looks like:
score: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51864930

http://stackoverflow.com/a/51813483
answers question: http://stackoverflow.com/q/51812972
accepted answer of: http://stackoverflow.com/q/51812972
has comment: http://stackoverflow.com/comment/90581732
has body: raw_data_lst = ['100 g ','5 oz (142 g)','12 oz','200 g ','12 oz (340 g)','10 f oz (296ml)','750 ml','1 l','250 ml', '8 OZ',] # 10 f oz (296ml) don't know what f is # if more there is more data like this then gram_conv_dict.keys() loop over this instead of directly ... doing what i have done below in_grams_colm = [] gram_conv_dict ={ 'g':1, 'oz': 28.3495, 'kg':1000, 'l': 1000 # assuming 1 litre of water --&gt; grams } # ml --&gt; g is tricky as density varies def convert2num(string_num): try: return int(string_num) except ValueError: return float(string_num) def get_in_grams(unit): try: return gram_conv_dict[unit.lower()] except: print('don\'t know how much grams is present in 1',unit+'.') return 1 for data in raw_data_lst: i = 0 quantity_str ='' quantity_num = 0 while i &lt; len(data): if 47 &lt; ord(data[i]) &lt; 58 or data[i] == '.': quantity_str+= data[i] else: # data[i] = '' most abbrv has at most length = 2 therefore data[i+1:i+3] or u can just send the whole data[i+1:] # gram_conv_dict[data[i+1:i+3].strip()] directly check if key exist break i+=1 quantity_num = convert2num(quantity_str)*get_in_grams(data[i+1:i+3].strip()) # assuming each data has this format numberspace-- len 2 abbrv in_grams_colm.append(quantity_num) # if u want only integer int(quantity_num) #print(in_grams_colm) def nice_print(): for _ in in_grams_colm: print('{:.2f}'.format(_)) nice_print() ''' output don't know how much grams is present in 1 f. don't know how much grams is present in 1 ml. don't know how much grams is present in 1 ml. 100.00 141.75 340.19 200.00 340.19 10.00 750.00 1000.00 250.00 226.80'''
has comment: http://stackoverflow.com/comment/90581848
has comment: http://stackoverflow.com/comment/90581754
score: 0
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/comment/90764044
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51901655
type: Comment
has text: You are probably running outdated container.

http://stackoverflow.com/a/51950218
answers question: http://stackoverflow.com/q/51950049
has comment: http://stackoverflow.com/comment/90851081
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90850397
has comment: http://stackoverflow.com/comment/90850434
has body: Very simple! Exploit the fact that pandas is built on top of numpy and use DataFrame.values df.values[rows, cols] = np.nan Output: 0 1 2 3 0 NaN 1.0 1.0 1.0 1 1.0 1.0 NaN 1.0 2 1.0 1.0 1.0 NaN 3 1.0 1.0 1.0 1.0
type: Answer
has comment: http://stackoverflow.com/comment/90850906
score: 5
has comment: http://stackoverflow.com/comment/90850856
upvote count: 5
accepted answer of: http://stackoverflow.com/q/51950049

http://stackoverflow.com/a/52482151
downvote count: 0
has comment: http://stackoverflow.com/comment/107645662
has body: The request you are using will create a data store and configure the feature type automatically. AFAIK you can not control the name of the feature type when it is created. In the request you can specify to not configure the feature type at this point with the parameter configure set to none. The second step is to create a new feature type from the data using the /workspaces/<ws>/datastores/<ds>/featuretypes URL (see: http://docs.geoserver.org/stable/en/user/rest/api/featuretypes.html). Here you want to set the name parameter but you need to specify the nativeName also, to let Geoserver know which feature to use. nativeName should be "myshapefile" in your case. I did not find documentation about this, but after a bit of trial and error it worked (also see this link for general advice how to use the REST API: https://gis.stackexchange.com/questions/12970/create-a-layer-in-geoserver-using-rest - the basic idea is to browse http://your-server/geoserver/rest and find your feature type, get the XML representation to see what parameters can be changed with the POST requests). The final code: import requests resource_id = "e477fb5b4d5748b9aabb617475e47b01" url = "http://127.0.0.1:8181/geoserver/rest/workspaces/testws/datastores/" + resource_id + "/external.shp?configure=none" data = "file:///xxx/myshapefile.shp" auth = ("admin", "geoserver") response = requests.put(url, data=data, auth=auth) url = "http://127.0.0.1:8181/geoserver/rest/workspaces/testws/datastores/" + resource_id + "/featuretypes" data = " " + resource_id + " myshapefile " headers = {'Content-type': 'text/xml'} response = requests.post(url, data=data, auth=auth, headers=headers)
type: Answer
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/51886054

http://stackoverflow.com/a/51842736
has comment: http://stackoverflow.com/comment/90640125
score: 1
has comment: http://stackoverflow.com/comment/90640044
answers question: http://stackoverflow.com/q/51842075
upvote count: 1
has comment: http://stackoverflow.com/comment/90639985
accepted answer of: http://stackoverflow.com/q/51842075
has comment: http://stackoverflow.com/comment/90639849
has body: First we need to make some fixes to the query itself: the __day will have a range of 1-31, which is probably not what we want. We want the week day, so: from django.db.models import Count from django.db.models.functions import ExtractHour, ExtractWeekDay qs = Photo.objects.annotate( hour=ExtractHour('timestamp'), day=ExtractWeekDay('timestamp') ).values('hour', 'day').annotate( photos=Count('id') ).order_by('hour', 'day') Next we will need to do some post processing: from datetime import date dow = date.today().isoweekday() + 1 result = [ [(row['day'] - dow) % 7, row['hour'], row['photos']] for row in qs ] This will result in an n&times;3-list, that can then, for example, be transmitted through JSON.
has comment: http://stackoverflow.com/comment/90640254
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90639880
type: Answer
has comment: http://stackoverflow.com/comment/90640019

http://stackoverflow.com/comment/90706344
type: AnswerComment
comment on: http://stackoverflow.com/a/51877025
type: Comment
has text: @trixn I'd say that's a question of personal taste, although you might prefer catching the `ValueError` because "It's easier to ask forgiveness than it is to get permission". If the case where the exception is thrown is frequent, I believe it is slightly slower.
score: 1

http://stackoverflow.com/a/51859587
upvote count: 5
has body: Try installing numpy first, maybe pandas installation will work after. pip install numpy pip install pandas If it does not work, try installing specific versions of pandas, like: pip install pandas==0.23.4 Hope it helps!
accepted answer of: http://stackoverflow.com/q/51859533
score: 5
answers question: http://stackoverflow.com/q/51859533
type: AcceptedAnswer
downvote count: 0
type: Answer

camera-matrix
tag name: camera-matrix
type: Tag
tags question: http://stackoverflow.com/q/51955394

http://stackoverflow.com/comment/90670650
comment on: http://stackoverflow.com/a/51859131
type: Comment
has text: how do i get status and output?
score: 0
type: AnswerComment

http://stackoverflow.com/q/51866010
accepted answer: http://stackoverflow.com/a/51866039
has title: Error 'builtin_function_or_method' object is not subscriptable - when appending list inside a for loop
type: Question
answer count: 2
downvote count: 0
score: 1
favorite count: 0
tagged with: pandas
tagged with: python
has body: I want to create a new list from a existing list within a for loop and then pass the list through an if else statement, one element at a time. I do not have the proper knowledge to utilize a list in this manner. Hence this post sample data: f = {'Sales_Person': ['John', 'Tom', 'Dick', 'Harry', 'Rob', 'Mike', 'Miz', 'Sally', 'Buck', 'Roger'], 'location': ['NY', 'NY', 'NY', 'NJ', 'PA', 'NJ', 'NJ', 'PA', 'NY', 'NJ'], 'product_code': ['10NYXX', '11NYXX', '10NYXX', '10NJXY', '11PAXY', '11MNYY', '12NJYX', '11PAYY', '12NYXX', '11CAPQ']} df1 = pd.DataFrame(data = f) df1['statusNY'] = 'n/a' df1['statusPA'] = 'n/a' df1['statusIL'] = 'n/a' df1['statusOR'] = 'n/a' df1['statusNJ'] = 'n/a' The data looks like- I am taking these column names ['statusNY', 'statusPA', 'statusIL', 'statusOR', 'statusNJ'] and extract state names [NY, PA, IL, OR and NJ] from them. Then I will check if the column 'product_code' contains these state names. If true then assign 1 to 'statusNY', if false assign 0 to 'statusNY'.Similarly for rest of the column names 'statusPA', 'statusIL', 'statusOR', 'statusNJ' Output should look like: I have following code: for col in ['statusNY', 'statusPA', 'statusIL', 'statusOR', 'statusNJ']: x = col[6:8] df1.loc[df1['product_code'].str.contains(x) == True, col] = '1' df1.loc[df1['product_code'].str.contains(x) == False, col] = '0' Ideally the second line should create a list which should be passed through third and fourth line. But this doesn't work. Then I thought of appending the list - newlist = [] for col in ['statusNY', 'statusPA', 'statusIL', 'statusOR', 'statusNJ']: newlist.append[col[6:8]] But ended up getting this error: TypeError: 'builtin_function_or_method' object is not subscriptable. I googled it and also checked other relevant posts, but the results were not quite relevant to my case.
has answer: http://stackoverflow.com/a/51866039
upvote count: 1
type: AnsweredQuestion
tagged with: list
possible better answer: http://stackoverflow.com/a/51866368
has answer: http://stackoverflow.com/a/51866368

http://stackoverflow.com/q/51945206
has answer: http://stackoverflow.com/a/51945387
type: AnsweredQuestion
has body: With the help of following code I am plotting a graph; however, the values are not clearly visible; they are mixed with graph: for x111,y1 in zip(x1,loss_list): plt.text(x111, y1, '%.2f' % y1, ha='right', va= 'bottom', color='blue') for x112,y2 in zip(x1,val_loss_list): plt.text(x112, y2, '%.2f' % y2, ha='left', va= 'top', color='orange') plt.plot(xc,train_loss_history) plt.plot(xc,val_loss_history) plt.xlabel('num of Epochs') plt.ylabel('loss') plt.title('train_loss vs val_loss') #plt.grid(True) plt.legend(['train','val']) plt.show() where x111 and other values and list i got from my code. and getting following plot how to make the visualization more readable?
upvote count: 2
accepted answer: http://stackoverflow.com/a/51945387
has title: values not visible clearly in plot
downvote count: 1
type: Question
tagged with: matplotlib
possible better answer: http://stackoverflow.com/a/51945481
has answer: http://stackoverflow.com/a/51945389
has answer: http://stackoverflow.com/a/51945481
answer count: 3
score: 1
favorite count: 0
tagged with: python

http://stackoverflow.com/q/51852504
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51852752
linked to: http://stackoverflow.com/q/32409629
type: Question
has body: I need to run my script named train.py but I also need to set up the flas, by issuing this command in bash: train.py --logtostderr --train_dir=training/ --pipeline_config_path=training/faster_rcnn_inception_v2_pets.config However, it catches this error: File "/Users/cvsanbuenaventura/miniconda3/lib/python3.6/site-packages/google/protobuf/text_format.py", line 1288, in _ConsumeSingleByteString raise self.ParseError('String missing ending quote: %r' % (text,)) google.protobuf.text_format.ParseError: 123:17 : String missing ending quote: '"/Users/cvsanbuenaventura/Documents/tensorflow/models/research/object_detection/train.record“' So I want to debug in Python Shell or Jupyter Notebook line by line. However I also need to set th train_dir flag. How do I accomplish this?
upvote count: 5
tagged with: flags
linked to: http://stackoverflow.com/q/45823991
has comment: http://stackoverflow.com/comment/90657748
answer count: 2
score: 5
downvote count: 0
has answer: http://stackoverflow.com/a/60298388
favorite count: 0
tagged with: python
has title: How to set flags inside Jupyter Notebook or Python Shell
has comment: http://stackoverflow.com/comment/90657686
tagged with: jupyter-notebook

http://stackoverflow.com/q/51860069
tagged with: xpath
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51860286
has title: Xpath for specific child element of a parent element which is not distinguished by class?
tagged with: python
has body: The html snippet is like this: &lt;div class="busi-attr"&gt; &lt;p&gt;&lt;span class="attrName"&gt;Min. Order: &lt;/span&gt;1 Piece&lt;/p&gt; &lt;p&gt;&lt;span class="attrName"&gt;Supply Ability: &lt;/span&gt;10,000&amp;nbsp;&amp;nbsp;Piece/Pieces per Month&lt;/p&gt; &lt;/div&gt; I only want the second &lt;p&gt; element that is amount 10,000 and nothing else, how do i do that? thanks
tagged with: web-scraping
type: Question
score: 0
answer count: 1
linked to: http://stackoverflow.com/q/51861991

http://stackoverflow.com/comment/90730378
has text: could you add namespace and try `path('quickstart/', include('quickstart.urls', namespace="quickstart")),`
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51888750

http://stackoverflow.com/a/51806885
type: Answer
answers question: http://stackoverflow.com/q/51806714
upvote count: 1
has comment: http://stackoverflow.com/comment/90569254
has body: This is how the combination of ModelViewset and DefaultRouter class behave. From the DRF Doc, it provides a bunch of end-point by default which is very very handy if you are doing CRUD Operations. From your description, I understood that you are not dealing with CRUD operations, and hence you can't use the Magic of the DefaultRouter and ModelViewset. So, What I suggest is, use rest_framework.views.APIView class for your purpose. Example views.py from rest_framework.views import APIView from rest_framework.response import Response class MyViewClass(APIView): def get(self, *args, **kwargs): # This fucntion will handle your "HTTP GET" requests # put your logic here return Response(data={"mymsg": "this is my response"}) def post(self, *args, **kwargs): return Response("This is post method") and in your urls.py from django.conf.urls import url urlpatterns = [ url(r'mysample/', MyViewClass.as_view()) ] References 1. DRF Router 2. DRF viewset 3. DRF APIview UPDATE-1 Read the Django document How Django processes a request When a user requests a page from your Django-powered site, this is the algorithm the system follows to determine which Python code to execute: Django determines the root URLconf module to use. Ordinarily, this is the value of the ROOT_URLCONF setting, but if the incoming HttpRequest object has an attribute called urlconf (set by middleware request processing), its value will be used in place of the ROOT_URLCONF setting. Django loads that Python module and looks for the variable urlpatterns. This should be a Python list, in the format returned by the function django.conf.urls.patterns(). Django runs through each URL pattern, in order, and stops at the first one that matches the requested URL. Once one of the regexes matches, Django imports and calls the given view, which is a simple Python function. The view gets passed an HttpRequest as its first argument and any values captured in the regex as remaining arguments. If no regex matches, or if an exception i…
has comment: http://stackoverflow.com/comment/90569277
has comment: http://stackoverflow.com/comment/90569494
score: 1
has comment: http://stackoverflow.com/comment/90569440
has comment: http://stackoverflow.com/comment/90569307
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90569465
has comment: http://stackoverflow.com/comment/90569202
accepted answer of: http://stackoverflow.com/q/51806714
has comment: http://stackoverflow.com/comment/90569534

http://stackoverflow.com/comment/90791882
type: QuestionComment
score: 0
has text: Looks like there is no `status` field here. Are you sure this is not an *attribute* (some logic at the Django side)?
comment on: http://stackoverflow.com/q/51920779
type: Comment

http://stackoverflow.com/q/51945955
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52094883
accepted answer: http://stackoverflow.com/a/52094883
has body: I'm new to Kivy and I trying to get myself an kind of template for later upcoming program parts. Now I'm stuck because my wonderful round .png Buttons all get King of "edges/bumps" when I try to resize them. This is how the Button should look like ... ... and this is what actually happens (please ignore the white background) I tried it with multiple other .png's so I'm very sure that the problem is not within the .png itself. Here is my code (I shortened it so that its easy to find the relevant part. if you feel like you need more code, of course I can add it): test.kv #:kivy 1.0.9 &lt;MainWindow&gt;: BoxLayout: #[shortened for readability reasons] BoxLayout: #[shortened for readability reasons] BoxLayout: #[shortened for readability reasons] AnchorLayout: #[shortened for readability reasons] FloatLayout: canvas: Rectangle: pos: self.pos size: self.size Button: id: leftButton background_normal: 'assets/graphics/buttons/dummy.png' background_down: 'assets/graphics/buttons/.png' size_hint: .15, .15 pos_hint: {'x':root.size_hint_x/2, 'y':root.size_hint_y/2} Perhaps someone here has an idea whats the problem and how to fix it? Please keep in mind that I want to fix that in the .kv file (if possible) so I can reuse it later on more easily. Another minor problem is the positioning of some other buttons. I want to get them aligned to the right side, but I couldn't find how to access the width of the button itself so I can subtract it from self.width (which should be the width of the surrounding layout if I got that right) Any suggestions? I did a little testing in the meantime to be sure that the file type isn't the problem here. I tried with .gif and .tif, as far as I know the other most common file types that support transparency. The outcome is the same as with .png To clarify how the design should look in the end I'll add another picture: So I think I have to do it with a FloatLayout. I would like to do it with grid like in pyqt, but in kivy it's not possible to define…
type: Question
has title: How to avoid bumps at my .png's when resizing them in Python/Kivy
possible better answer: http://stackoverflow.com/a/51954692
tagged with: resize
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/51954692
tagged with: python
tagged with: kivy
tagged with: http://stackoverflow.com/tag/png

http://stackoverflow.com/comment/90714004
type: QuestionComment
comment on: http://stackoverflow.com/q/51867653
has text: Just forget about Python (temporarily). Pretend your own C++ code needs to use v.data(). But you cannot place v in the same function that needs it. How would you do this?
score: 0
type: Comment

http://stackoverflow.com/q/51921142
has answer: http://stackoverflow.com/a/69164235
linked to: http://stackoverflow.com/q/48498929
has answer: http://stackoverflow.com/a/60543240
has answer: http://stackoverflow.com/a/66399096
type: Question
answer count: 6
tagged with: google-cloud-storage
has title: How to load a model saved in joblib file from Google Cloud Storage bucket
downvote count: 0
tagged with: scikit-learn
tagged with: joblib
has answer: http://stackoverflow.com/a/72669857
favorite count: 0
has answer: http://stackoverflow.com/a/51931947
tagged with: python
score: 11
possible better answer: http://stackoverflow.com/a/59108701
has answer: http://stackoverflow.com/a/59108701
upvote count: 11
type: AnsweredQuestion
has body: I want to load a model which is saved as a joblib file from Google Cloud Storage bucket. When it is in local path, we can load it as follows (considering model_file is the full path in system): loaded_model = joblib.load(model_file) How can we do the same task with Google Cloud Storage?
accepted answer: http://stackoverflow.com/a/51931947

http://stackoverflow.com/comment/90834011
comment on: http://stackoverflow.com/q/51942250
type: Comment
type: QuestionComment
has text: Please show what have you tried and where did you face problem. Please visit here to see how to create classes in python https://docs.python.org/3/tutorial/classes.html
score: 3

http://stackoverflow.com/comment/90659184
type: QuestionComment
score: 2
has text: I think you forget `()` like `print(all_ssis_data.tail())`
comment on: http://stackoverflow.com/q/51853350
type: Comment

http://stackoverflow.com/q/51920267
has comment: http://stackoverflow.com/comment/90791675
tagged with: docker
answer count: 2
has comment: http://stackoverflow.com/comment/90792281
has title: How to setup flask-socketio in a docker container?
has answer: http://stackoverflow.com/a/51932912
downvote count: 0
favorite count: 0
tagged with: eventlet
has comment: http://stackoverflow.com/comment/90813920
has answer: http://stackoverflow.com/a/51926714
tagged with: python
has comment: http://stackoverflow.com/comment/90791698
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51926714
accepted answer: http://stackoverflow.com/a/51932912
tagged with: flask-socketio
has body: Hello I'm trying to setup flask-socketio in a docker container. It seems to run but I get an error( from the browser) when I try to access localhost on port 5000 like I'm used to do with flask apps. It say's: unable to connect! I will show you the 5 important files: Dockerfile, requirements.txt, docker-compose.yml, web_app.py and index.html Dockerfile: FROM python:3.6.5 WORKDIR /code COPY * /code/ RUN pip install -r requirements.txt requirements.txt: Flask==1.0.2 Flask-SocketIO==3.0.1 eventlet==0.24.1 docker-compose.yml: version: "3" services: web: build: ./web ports: - '5000:5000' volumes: - './web:/code' I use the commands docker-compose up --build and docker-compose run web /bin/bash to enter this container in interactive mode. web_app.py: from flask import Flask, render_template from flask_socketio import SocketIO, emit app = Flask(__name__) app.config['SECRET_KEY'] = 'secret!' socketio = SocketIO(app) @app.route('/') def index(): return render_template('index.html') @socketio.on('my event') def log_message(message): emit('my response', {'data': 'got it!'}) if __name__ == '__main__': socketio.run(app) index.html: SocketIO Once inside the container I simple run: python web_app.py but nothing happens. No error and no working page. I feel like I'm missing so steps to initialize everything correctly but I cant find out what it is. The web is full of very different examples and I'm confused. What makes it even harder is that I'm using eventlet here but not every example goes this route. Some use gevent or other things. I would be really glad if someone gave me a little hint. Cheers
has comment: http://stackoverflow.com/comment/90791584
type: Question
score: 5
upvote count: 5
tagged with: flask

http://stackoverflow.com/comment/90806154
score: 1
comment on: http://stackoverflow.com/q/51921806
type: Comment
type: QuestionComment
has text: have you tried file.get('nextPageToken') and see whats actually in that.

http://stackoverflow.com/comment/90647259
comment on: http://stackoverflow.com/q/51846948
score: 2
type: Comment
type: QuestionComment
has text: upgrade seaborn to 0.9

http://stackoverflow.com/a/51886615
type: Answer
has body: IIUC df.set_index('ticker',inplace=True) df=pd.DataFrame(s.values*s.values[:,None]*df.values) df.values[[np.arange(len(df))]*2] = 1 df Out[24]: 0 1 2 3 4 0 1.000000 0.000056 0.000061 0.000070 0.000042 1 0.000056 1.000000 0.000086 0.000117 0.000046 2 0.000061 0.000086 1.000000 0.000089 0.000043 3 0.000070 0.000117 0.000089 1.000000 0.000050 4 0.000042 0.000046 0.000043 0.000050 1.000000
answers question: http://stackoverflow.com/q/51886179
has comment: http://stackoverflow.com/comment/90750530
score: 0

http://stackoverflow.com/a/51921904
answers question: http://stackoverflow.com/q/51919051
has body: Michael Bayer REPO OWNER SQLAlchemy does not have support for OUT parameters on any backend except Oracle at this time. In order to use OUT parameters now, you need to use the DBAPI function callproc(), see http://initd.org/psycopg/docs/cursor.html#cursor.callproc. your function should look like this: def execproc(procname, engine, queryParams=[]): connection = engine.raw_connection() cursor = connection.cursor() try: cursor.callproc(procname, queryParams) rows = list(cursor.fetchall()) cursor.close() connection.commit() return rows finally: connection.close()
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51919051
type: Answer

http://stackoverflow.com/q/51926699
tagged with: python-3.x
type: UnansweredQuestion
has body: I am trying to create a program with python, I wrote code that allows one computer to connect another, I don't know how I can see the other computer desktop and control it's running programs ip = "127.0.0.1" username = ""#"username" password = ""#"password" try: print ("Establishing connection to %s" %ip) connection = wmi.WMI(ip, user=username, password=password) connection.Win32_Process.Create(CommandLine="notepad.exe /c text.txt") print ("Connection established") except wmi.x_wmi: print ("Your Username and Password of "+getfqdn(ip)+" are wrong.")
tagged with: python
has answer: http://stackoverflow.com/a/51928094
type: Question
has title: Create remote control desktop with python
tagged with: remote-control
tagged with: python-2.7
score: 0
answer count: 1

http://stackoverflow.com/a/51839611
has body: As per your question to decide the three options and run the next step accordinglyyou can use the following solution : You can write a function as test_me() which will take an argument as the id of the element and provide the status as follows: def test_me(myString): try: driver.find_element_by_id(myString) print("Exits") except NoSuchElementException: print("Doesn't exit") Now you can call the function test_me() from anywhere within your code as follows: test_me("smc") #or test_me("editPage") # test_me("cas2_ilecell")
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51838719

http://stackoverflow.com/a/51856177
has body: The hacky way is to use tf.assign to assign the weight to the variable you want (make sure it only happens once at the begining, and not every iteration, otherwise the model won't be able to adjust those weights). The slightly less hacky way is to load the graph and session of the trained model and modify the graph to add the operations you need. This will make the graph a bit more messy since you also have the entire graph of the original model, but it's a bit cleaner since you can depend directly on the operations instead of the weights (that is if the original model was doing a sigmoid activation, this will copy the activation as well). The unused parts of the graph will be automatically pruned by tensorflow. The clean way to do it is to use www.tenforflow.com/hub . It's a library that allows you to define parts of the graph as modules that you can export and import into any graph. This will handle all dependencies and configuration and also gives you nice controls over the training (i.e. if you want to freeze the weights, or delay the training for some number of iterations, etc.)
type: Answer
accepted answer of: http://stackoverflow.com/q/51852089
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/51852089
has comment: http://stackoverflow.com/comment/90690241
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/51833065
has body: You didn't actually active your virtual-env, and your error information show as: C:\Users\xxxx\AppData\Local\Temp\pip-unpack- kc0_p8wh\Django-2.1-py3-none-any.whl Nothing about venv/xxx/path, so you should active by. FOR Linux source venv\Scripts\activate first. and then try install again. FOR WIN Thanks for @metatoaster remind at the comments below. But it depends on where are you virtualenv path. C:\Venv\Scripts&gt;activate To make sure whether you are in virtual-env , just check whether you have a special subfix at the begin of command line. something like: (my_venv)landpacks
type: Answer
has comment: http://stackoverflow.com/comment/90620416
answers question: http://stackoverflow.com/q/51833041
has comment: http://stackoverflow.com/comment/90620433
score: 0
has comment: http://stackoverflow.com/comment/90620062
has comment: http://stackoverflow.com/comment/90620421

http://stackoverflow.com/comment/90686166
type: AnswerComment
type: Comment
has text: would you explain why its different from @pkqxdd answer? https://stackoverflow.com/a/51852326/2519073 , do we need the __next__ and not __iter__? (its another question i know, but just in case you have time..)
comment on: http://stackoverflow.com/a/51852437
score: 0

http://stackoverflow.com/comment/90800767
type: AnswerComment
has text: Thanks, but this also gives me an error? Complete output from command python setup.py egg_info: Traceback (most recent call last): File "<string>", line 1, in <module> File "C:\ProgramData\Anaconda3\lib\tokenize.py", line 452, in open buffer = _builtin_open(filename, 'rb') FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\nicje\\A ppData\\Local\\Temp\\pip-c68kl3v7-build\\setup.py'
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51896276

http://stackoverflow.com/comment/90627098
type: Comment
comment on: http://stackoverflow.com/a/51831771
score: 0
type: AnswerComment
has text: Thanks, the `__subclasses__` attribute is exactly what I was seeking for, in that case, the particles will deal with forces, attract and repeal each other, so, is really important for a particle to know its system.

http://stackoverflow.com/q/51922283
has comment: http://stackoverflow.com/comment/90794449
duplicate of: http://stackoverflow.com/q/11205254
has comment: http://stackoverflow.com/comment/90794330
type: UnansweredQuestion
tagged with: python
has title: How to sort a List of string by Numeric Order in Python 3.6?
answer count: 0
has comment: http://stackoverflow.com/comment/130158546
score: 0
has comment: http://stackoverflow.com/comment/90794358
has comment: http://stackoverflow.com/comment/90794236
type: Question
has comment: http://stackoverflow.com/comment/90794223
has comment: http://stackoverflow.com/comment/90795306
tagged with: sorting
linked to: http://stackoverflow.com/q/16460616
has comment: http://stackoverflow.com/comment/90794477
has body: I have the follow code: x='10 0 17 5' a = x.split(' ') first = a.pop(0) print(first) print(a) c = a.sort(key=int) print(c) I am removing the 1st element and I want to sort the remaining This is what I am getting: 10 ['0', '17', '5'] None Where we see None, I was expecting to see ['0', '5', '17'], as per this post- Sort a List of string by Numeric Order. Why it is not working?
has comment: http://stackoverflow.com/comment/90794367

http://stackoverflow.com/a/51846821
downvote count: 1
upvote count: 0
score: -1
has body: import random def find_min(d, fixed_key): # Given a dictionary of dictionaries d, and a fixed_key, get the dictionary associated with the key myDict = d[fixed_key] # treat the dictionary keys as a list # get the index of the minimum value, then use it to get the key sub_key = list(myDict.keys())[myDict.values().index(min(myDict.values()))] return sub_key dict1 = {0: {0: 7, 1: 2, 2: 5}, 1: {0: 3, 1: 10, 2: 10}} print dict1 print find_min(dict1, 0)
has comment: http://stackoverflow.com/comment/90647065
type: Answer
answers question: http://stackoverflow.com/q/51846590

http://stackoverflow.com/comment/90749306
has text: `'-'.join((k1, k2)): np.var(v1 + v2)` to avoid key tuple
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51898997
score: 0

http://stackoverflow.com/q/51810381
has answer: http://stackoverflow.com/a/51810519
downvote count: 0
type: UnansweredQuestion
type: Question
upvote count: 2
has body: I'm trying to implement an enemy that chases the player, but when the enemy moves diagonally, it appears to move slower than when it moves on a single axis and I'm not sure why. Here's my code for the enemy: import pygame import constants import math from Character import Player class Enemy(pygame.sprite.Sprite): def __init__(self, filename, x, y): super().__init__() self.image = pygame.image.load(filename).convert() self.image.set_colorkey(constants.BLACK) self.rect = self.image.get_rect() self.rect.y = y self.rect.x = x self.speedx = -3 self.speedy = -3 self.health = 100 def update(self, player): dx = self.rect.x - player.rect.x dy = self.rect.y - player.rect.y dist = math.hypot(dx, dy) dx = dx / dist dy = dy / dist self.rect.x += dx * self.speedx self.rect.y += dy * self.speedy * in the main loop * current_room.enemy_sprites.update(player) Let me know if any more code is necessary, but I don't think there would be as none of my other code affects the enemy movement. Any help at all would be much appreciated!
answer count: 1
favorite count: 0
has title: Diagonal movement
tagged with: python
tagged with: pygame
score: 2

peewee
tags question: http://stackoverflow.com/q/51810328
tag name: peewee
type: Tag
tags question: http://stackoverflow.com/q/51807367
tags question: http://stackoverflow.com/q/51876258

http://stackoverflow.com/tag/html
tags question: http://stackoverflow.com/q/51863989
tags question: http://stackoverflow.com/q/51914350
tags question: http://stackoverflow.com/q/51863740
tags question: http://stackoverflow.com/q/51809578
tags question: http://stackoverflow.com/q/51903651
tags question: http://stackoverflow.com/q/51898527
tags question: http://stackoverflow.com/q/51838630
tags question: http://stackoverflow.com/q/51949293
tags question: http://stackoverflow.com/q/51882107
tags question: http://stackoverflow.com/q/51860222
tags question: http://stackoverflow.com/q/51862924
tags question: http://stackoverflow.com/q/51941135
tags question: http://stackoverflow.com/q/51899770
tags question: http://stackoverflow.com/q/51875168
tags question: http://stackoverflow.com/q/51830894
tags question: http://stackoverflow.com/q/51905101
tags question: http://stackoverflow.com/q/51867458
tags question: http://stackoverflow.com/q/51949091
type: Tag
tags question: http://stackoverflow.com/q/51928222
tags question: http://stackoverflow.com/q/51869434
tags question: http://stackoverflow.com/q/51954482
tags question: http://stackoverflow.com/q/51824170
tags question: http://stackoverflow.com/q/51843569
tags question: http://stackoverflow.com/q/51860448
tags question: http://stackoverflow.com/q/51941827
tags question: http://stackoverflow.com/q/51893239
tags question: http://stackoverflow.com/q/51815470
tags question: http://stackoverflow.com/q/51929071
tags question: http://stackoverflow.com/q/51921882
tags question: http://stackoverflow.com/q/51809248
tags question: http://stackoverflow.com/q/51848174
tags question: http://stackoverflow.com/q/51879740
tags question: http://stackoverflow.com/q/51832095
tags question: http://stackoverflow.com/q/51846229
tags question: http://stackoverflow.com/q/51813334
tags question: http://stackoverflow.com/q/51849112
tags question: http://stackoverflow.com/q/51838887
tags question: http://stackoverflow.com/q/51939159
tags question: http://stackoverflow.com/q/51852574
tags question: http://stackoverflow.com/q/51915646
tags question: http://stackoverflow.com/q/51803798
tags question: http://stackoverflow.com/q/51869115
tags question: http://stackoverflow.com/q/51814146
tags question: http://stackoverflow.com/q/51897969
tags question: http://stackoverflow.com/q/51834809
tags question: http://stackoverflow.com/q/51922686
tags question: http://stackoverflow.com/q/51950380
tags question: http://stackoverflow.com/q/51803041
tags question: http://stackoverflow.com/q/51899780
tags question: http://stackoverflow.com/q/51869608
tags question: http://stackoverflow.com/q/51806436
tag name: html
tags question: http://stackoverflow.com/q/51859200
tags question: http://stackoverflow.com/q/51956543
tags question: http://stackoverflow.com/q/51897917
tags question: http://stackoverflow.com/q/51809129
tags question: http://stackoverflow.com/q/51919976
tags question: http://stackoverflow.com/q/51829893
tags question: http://stackoverflow.com/q/51852588
tags question: http://stackoverflow.com/q/51903521
tags question: http://stackoverflow.com/q/51897756
tags question: http://stackoverflow.com/q/51799523
tags question: http://stackoverflow.com/q/51941227
tags question: http://stackoverflow.com/q/51913220

http://stackoverflow.com/q/51910960
has title: Forming a magic square
has answer: http://stackoverflow.com/a/64418718
tagged with: magic-square
has body: We define a magic square to be an matrix of distinct positive integers from to where the sum of any row, column, or diagonal of length is always equal to the same number: the magic constant. You will be given a matrix of integers in the inclusive range . We can convert any digit to any other digit in the range at cost of . Given , convert it into a magic square at minimal cost. Print this cost on a new line. Note: The resulting magic square must contain distinct integers in the inclusive range . For example, we start with the following matrix : 5 3 4 1 5 8 6 4 2 We can convert it to the following magic square: 8 3 4 1 5 9 6 7 2 This took three replacements at a cost of . 5-8 + 8-9 + 4-7 = 7 I Have Write a programm to slove this but i get the incorrect result when i try to run it. def formingMagicSquare(s): arr=[] duplicates=[] totaldifference=0 for i in range(0,len(s)): linesum=sum(s[i]) for j in range(0,len(s[i])): if(s[i][j] in arr and linesum!=15): duplicates.append(i*10+j) else: arr.append(s[i][j]) for i in range(0,len(duplicates)): iarr = duplicates[i]//10 jarr = duplicates[i]%10 linesum=sum(s[i]) difference=15-linesum totaldifference = totaldifference + difference return totaldifference if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') s = [] for _ in range(3): s.append(list(map(int, input().rstrip().split()))) result = formingMagicSquare(s) fptr.write(str(result) + '\n') fptr.close()
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90772677
tagged with: python
has comment: http://stackoverflow.com/comment/111670852
has comment: http://stackoverflow.com/comment/90774178
type: Question
has answer: http://stackoverflow.com/a/51914919
answer count: 2
has comment: http://stackoverflow.com/comment/90774263
score: 0
has comment: http://stackoverflow.com/comment/90772502

http://stackoverflow.com/a/51843783
has comment: http://stackoverflow.com/comment/90719593
has body: You're looking for A.iloc[Rw,4] where Rw is an integer, but your index is set to be a datetime, from your .set_index() call. You shouldn't be doing a for loop here - one of the joys of pandas is its ability to work much more quickly through vectorised operations. In particular, you appear to be wanting to use .shift() to compare against the previous day's values, which you can do like so: from io import StringIO import pandas as pd data = StringIO('''datetime Open High Low Close AdjClose Volume 2018-07-23 31.1100 31.3500 30.6000 30.8200 30.8200 6023310 2018-07-20 31.2900 31.3100 30.8450 31.1100 31.1100 5022452 2018-07-26 28.4800 29.1200 27.5500 28.9800 28.9800 10582061 2018-07-27 28.8200 29.3350 27.7050 28.1300 28.1300 8101362 2018-07-24 30.4500 30.9400 29.9650 30.1400 30.1400 5706941''') df = pd.read_csv(data, sep='\s+') df['datetime'] = pd.to_datetime(df['datetime']) df.set_index('datetime', inplace=True) df.sort_index(inplace=True) df['Mv'] = df['AdjClose'] - df['AdjClose'].shift(1) print(df) Which gives us the following dataframe: Open High Low Close AdjClose Volume Mv datetime 2018-07-20 31.29 31.310 30.845 31.11 31.11 5022452 NaN 2018-07-23 31.11 31.350 30.600 30.82 30.82 6023310 -0.29 2018-07-24 30.45 30.940 29.965 30.14 30.14 5706941 -0.68 2018-07-26 28.48 29.120 27.550 28.98 28.98 10582061 -1.16 2018-07-27 28.82 29.335 27.705 28.13 28.13 8101362 -0.85
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51842593
accepted answer of: http://stackoverflow.com/q/51842593
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/comment/90659482
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/51853515
has text: One cannot understand what you want to implement bro... Do you want to implement the number e ? as e=2.71... ? or do you want to use e like, just calculate what ever is up there

http://stackoverflow.com/a/51926953
upvote count: 1
has body: There is no reason to do the time-expensive np.exp and np.sqrt functions on distances that will cause np.exp(-dist) to underflow to zero. The smallest double greater than zero is 5e-324, and -np.log(5e-324) = 744.44007192138122. Now in your exampe the minimum distance is only ~1.4, but I assume that in practice the distances will be larger. With that in mind we can do: import numpy as np def V(dist_sq, thr = 5e-324): #Here, dist_sq is dist**2, a float d_sq_thr = np.log(thr)**2 mask = dist_sq &lt; d_sq_thr # mask is True where you want to do calculations out = np.sqrt(dist_sq[mask]) # square root only in place and only for valid distances out = np.exp(-out) / out # same with `np.exp` return out, mask i, j = np.triu_indices(N, 1) # gives you the valid (i, j) values r_rel = r[i] - r[j] sq_distances = np.sum(r_rel**2, axis = 1) # squared distances v_, mask = V(sq_distances) F[i[mask], j[mask], :] = v_ * r_rel[mask] F[j[mask], i[mask], :] = -F[i[mask], j[mask], :] Now, you can set your thr value to something larger than machine precision and speed things up even more, even before you start jumping into wrapping it innumba as @max9111 suggests. Not a numba expert, but I think this would work: @nb.njit(parallel=True,error_model='numpy',fastmath=True) def distance(r, thr = None): if thr == None: d_sq_thr = np.log(5e-324)**2 else: d_sq_thr = np.log(thr)**2 N = r.shape[0] F = np.zeros((N,N,2)) #give the compile all information available assert r.shape[1]==2 for i in nb.prange(N): #change i to N to get all results for j in range(i): r_rel_1 = r[i,0] - r[j,0] r_rel_2 = r[i,1] - r[j,1] dist_rel_sq = r_rel_1 ** 2 + r_rel_2 ** 2 if dist_rel_sq &gt; d_sq_thr : continue dist_rel = np.sqrt(dist_rel_sq) V = np.exp(-dist_rel) / (dist_rel+1) F[i,j,0] = V * r_rel_1 F[i,j,1] = V * r_rel_2 return F Keep in mind this method will be slower than the others on your toy problem, as the distance check is just overhead (as your r values are all bounded on [0,1]), but when larger distances are use…
score: 1
answers question: http://stackoverflow.com/q/51918954
has comment: http://stackoverflow.com/comment/90806437
has comment: http://stackoverflow.com/comment/90808817
downvote count: 0
has comment: http://stackoverflow.com/comment/90808424
type: Answer

http://stackoverflow.com/q/51823023
favorite count: 0
has comment: http://stackoverflow.com/comment/90601051
accepted answer: http://stackoverflow.com/a/51824346
has title: matplotlib - shape mismatch issue when trying to add more columns
has comment: http://stackoverflow.com/comment/90602004
tagged with: shapes
tagged with: python
downvote count: 1
has comment: http://stackoverflow.com/comment/90601228
type: AnsweredQuestion
tagged with: charts
tagged with: matplotlib
score: -1
has comment: http://stackoverflow.com/comment/90602257
has comment: http://stackoverflow.com/comment/90603727
has comment: http://stackoverflow.com/comment/90603077
type: Question
has comment: http://stackoverflow.com/comment/90600759
upvote count: 0
has answer: http://stackoverflow.com/a/51824346
has comment: http://stackoverflow.com/comment/90601355
has body: I'm new to matplotlib and python charts in general, so forgive me in advance if I got terminology wrong. I'm trying to generate chart, it's a combo of scatter + stacked column bars. The thing is it's only ok when the number of columns is identical to the number of rows, as I assume either numpy or other libs are generating shapes this way (which is what the error mentions) but I can't figure out how to add more columns, and still remain with the same number of rows. The result I'm expecting is to add, say additional X columns in my current 5*5 the table + upper chart. code below, any help will be appreciated, error is reproduced when additional items to data[] and data2 [] #!/usr/bin/env python2.7 import os import sys import numpy as np import matplotlib.pyplot as plt lst_keys_ordered = [] dict_quotes = {} def main(): rows = ['bid 5','bid 4','bid 3','bid 2','bid 1','ask 1','ask 2','ask 3','ask 4','ask 5'] colors = ['red','crimson','indianred','lightcoral','lightsalmon','greenyellow','lawngreen','limegreen','green','darkgreen'] value_increment = 100 size_ratio = 50 """ this config works """ price = [55,55.5,55.2,55.9,60.3] price2 = [55.5,56,55.7,56.5,60.8] data = [[100,200,100,200,100],[20,200,50,100,50],[100,100,50,50,300],[400,50,100,50,50],[80,120,40,60,100]] data2 = [[100,200,100,200,100],[20,200,50,100,50],[100,100,50,50,300],[400,50,100,50,50],[80,120,40,60,100]] columns = ('09:30:01', '09:30:02', '09:30:03', '09:30:04', '09:30:05') """ below generates errors - 6 columns data with 5 elements in data list items """ """ price = [55,55.5,55.2,55.9,60.3,60.3] price2 = [55.5,56,55.7,56.5,60.8,60.3] data = [[100,200,100,200,100],[20,200,50,100,50],[100,100,50,50,300],[400,50,100,50,50],[80,120,40,60,100],[80,120,40,60,100]] data2 = [[100,200,100,200,100],[20,200,50,100,50],[100,100,50,50,300],[400,50,100,50,50],[80,120,40,60,100],[80,120,40,60,100]] columns = ('09:30:01', '09:30:02', '09:30:03', '09:30:04', '09:30:05', '09:30:06') """ for i,row in enumerate(data): fo…
answer count: 1

http://stackoverflow.com/a/51931395
has body: Problem So basically what is happening over here is you are playing with three different formats of images (at least those that appear in your question). They are respectively: RGB (of dimension (420, 310, 3)), three channels RGB-A (of dimension (420, 310, 4)), four channels Grayscale (of dimension (420, 310)), single channel The third dimension that you are seeing is what represents the number of channels in your image (the first two being the height and width respectively). An example will further clear it up. I downloaded random images from the internet each belonging to one of the three formats mentioned above. RGB image dog.png RGB-A image fish.png Grayscale image lena.png Here's a python script to load each of them using PIL and display their shape: from PIL import Image import numpy as np dog = Image.open('dog.png') print('Dog shape is ' + str(np.array(dog).shape)) fish = Image.open('fish.png') print('Fish shape is ' + str(np.array(fish).shape)) lena = Image.open('lena.png') print('Lena shape is ' + str(np.array(lena).shape)) And here is the output: Dog shape is (250, 250, 3) Fish shape is (501, 393, 4) Lena shape is (512, 512) Hence, when you are trying to iteratively assign all the images to an array (np.array), you are getting the shape mis-match error. Solution The easiest way to resolve this is to convert all the images to one particular format before saving it in the array. Assuming you will be using a pre-trained ImageNet model, we will convert them to RGB format (you can similarly choose a format of your choice also). We will convert RGB-A to RGB using the following code: fish = Image.open('fish.png') print('Fish RGB-A shape is ' + str(np.array(fish).shape)) rgb = fish.convert('RGB') print('Fish RGB shape is ' + str(np.array(rgb).shape)) Output is: Fish RGB-A shape is (501, 393, 4) Fish RGB shape is (501, 393, 3) Similarly you can do for all your images, and then you have a consistent number of channels (three in this case) for all your images. NOTE: …
has comment: http://stackoverflow.com/comment/90839351
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90837761
has comment: http://stackoverflow.com/comment/90818337
has comment: http://stackoverflow.com/comment/90818420
type: Answer
has comment: http://stackoverflow.com/comment/135003858
score: 21
accepted answer of: http://stackoverflow.com/q/51923503
upvote count: 21
answers question: http://stackoverflow.com/q/51923503

http://stackoverflow.com/q/51943561
accepted answer: http://stackoverflow.com/a/51944896
type: Question
answer count: 2
has body: I am trying to write a script finding duplicated values in a dictionary. My dictionary is having an integer key and a list as a value: {5: ['13139', '3219', '3'], 6: ['14072', '3214', '3'], 7: ['13137', '3219', '3'], 8: ['13141', '3219', '3'], 9: ['13139', '3219', '3']} Here is my code: for key, value in dict.iteritems(): for other_key, other_value in dict.iteritems(): if value == other_value and key != other_key: print "We have duplicated values at key {} and key {}".format(key, other_key) The problem is that when I run the script I got duplicated lines like this: We have duplicated values at key 5 and key 9 We have duplicated values at key 9 and key 5 So I want to omit the second row and this script also won't show me if I have duplicated values on more than 2 keys for example if I have duplicated values at key 5, 9 and 52 it will show me: We have duplicated values at key 5 and key 9 We have duplicated values at key 5 and key 52 We have duplicated values at key 9 and key 5 We have duplicated values at key 9 and key 52 And I want to show me that I have duplicated values at key 5, 9 and 52 I also want to show me all the keys with duplicated values so for example I can have duplication at key 5, 9 and 52 and another duplication of the values at key 40 and 65.
has answer: http://stackoverflow.com/a/51943957
score: 0
possible better answer: http://stackoverflow.com/a/51943957
has answer: http://stackoverflow.com/a/51944896
favorite count: 0
has title: Finding duplicated values in a dictionary in Python
upvote count: 2
downvote count: 2
tagged with: python
tagged with: dictionary
type: AnsweredQuestion

http://stackoverflow.com/comment/90804696
comment on: http://stackoverflow.com/q/51926032
score: 0
type: QuestionComment
has text: Ok I misunderstood what you meant by generating
type: Comment

http://stackoverflow.com/q/51913201
accepted answer: http://stackoverflow.com/a/51913245
has comment: http://stackoverflow.com/comment/90776684
has body: I need to create a dictionary where I create the key using for loops and then get the value for each key from a file. My text file has individual lines like this for each of the 12 x 12 tables. 'I ate and I ate until I was sick on the floor, 8 x 8 is 64.' I feel writing the rhymes like this in a txt document would be better than writing them in the python program. I would then like to make a dictionary where the key follows this structure: 8 x 8 = 64 and the value is the whole sentence: 'I ate and I ate until I was sick on the floor, 8 x 8 is 64.' To give further context, I basically have a list of incorrect answers from a game which follows the structure of: 8 x 8 = 64 (as illustrated above). This list is contained within a listbox in tkinter. So far, I have got my program to print the current selection from the listbox onto the console whenever the user selects an item e.g. 2 x 2 = 4. I would like to have it so that when they choose a particular question/ key from the list (e.g. 8 x 8 = 64) next to it a label changes to the value of that question/key e.g. 'I ate and I ate until I was sick on the floor, 8 x 8 is 64.' This would then give them help to remember the correct answer in future attempts at the game. Below displays my code so far but yet again, I'm stuck! :( d = {} with open('help.txt', 'r') as f: for line in f: val = line for i in range (1,13): for n in range (1,13): answer = n * i key = '{} x {} = {}'.format(n, i, answer) d [key] = val I hope I've managed to explain my problem clearly. I'm open to other ways to do this too.
has comment: http://stackoverflow.com/comment/90776542
possible better answer: http://stackoverflow.com/a/51913417
tagged with: python
has answer: http://stackoverflow.com/a/51913417
favorite count: 0
tagged with: tkinter
has comment: http://stackoverflow.com/comment/90776568
has comment: http://stackoverflow.com/comment/90776564
has comment: http://stackoverflow.com/comment/90776555
score: -3
has answer: http://stackoverflow.com/a/51913245
type: AnsweredQuestion
downvote count: 3
has comment: http://stackoverflow.com/comment/90776656
has title: Need help writing a dicitonary where the value comes from a file
type: Question
answer count: 2
upvote count: 0
has comment: http://stackoverflow.com/comment/90776697
has comment: http://stackoverflow.com/comment/90776602

http://stackoverflow.com/comment/90801436
score: 0
type: AnswerComment
type: Comment
has text: @certainperformace this regex also matches single words like : foo ; i only want to match words separated by spaces and they are not separated by AND/OR. So, single words should not match either.
comment on: http://stackoverflow.com/a/51914205

http://stackoverflow.com/comment/90591282
has text: Thank you. It ha solved the issue
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51818670

http://stackoverflow.com/comment/90579339
comment on: http://stackoverflow.com/a/51811934
has text: Check what's the value of `STATICFILES_DIRS`. And what is actually stored in `STATIC_ROOT`. You can print that out on the start of app.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/51836629
has body: I often have to create plots which have a fixed width (e.g. the column width of an article) and whose subplots have a fixed ratio in the data coordinate system. I want to set the width manually and obtain a plot with this chosen width, aspect ratio of the subplots and the appropriate height. Example: The columns of an article have a width of 8.5cm. I want to create a plot with two subplots (axes) and for both axes the option ax.set_aspect("equal") is chosen so that 1 unit on the y axis takes the same physical space as one unit on the x axis. My plot should now have a total width of 8.5cm but the height should be calculated from matplotlib by taking into account the aspect ratio of the subplots as well as the xlim and ylim values. How can I achieve this? Additionally, how do I make sure that the font size used in the plots is the same as in the article? So if my article is set with "times" in 11pt, how do I get the same font with the same size in my plot? I tried to use params = {'text.usetex': True, 'font.size': 11, 'font.family': 'times', 'text.latex.unicode': True, } plt.rcParams.update(params) but for example the x- and y-label fonts in my plot are now much larger than in the article. I thought that 'font.size' updates all font sizes?
has title: Set width of plot and infer height from aspect ratio of subplots
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90642232
tagged with: matplotlib
type: Question
has comment: http://stackoverflow.com/comment/90638552
has answer: http://stackoverflow.com/a/51846737
answer count: 1
score: 0
accepted answer: http://stackoverflow.com/a/51846737

http://stackoverflow.com/comment/90860250
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51954482
has text: Thanks. The other guy beat me to the answer. *tips hat*
type: Comment

http://stackoverflow.com/a/51890749
type: AcceptedAnswer
type: Answer
score: 0
accepted answer of: http://stackoverflow.com/q/51886541
has body: Maybe something like (I cannot test it unless you provide a working example): with open(newFile, 'wb') as csvfile: fwriter = csv.writer(csvfile) for line in data: fwriter.writerow(line)
answers question: http://stackoverflow.com/q/51886541

http://stackoverflow.com/comment/90574307
comment on: http://stackoverflow.com/q/51807787
score: 0
has text: @skrx: Thanks. I need the actual distance (20 px, 30 px, etc.). I checked these threads. In particular, this one: https://stackoverflow.com/questions/4978323/how-to-calculate-distance-between-two-rectangles-context-a-game-in-lua. In the top answer the function `rect_distance` is suggested. What I misunderstand is how to get the input parameters for this function in my particular case?
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/90581652
type: AnswerComment
type: Comment
has text: `df['category'].apply(pd.Series)` nooo!! You should consider Counter + itertools.chain instead.
score: 2
comment on: http://stackoverflow.com/a/51813384

http://stackoverflow.com/comment/90703062
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51875213
has text: Yes, which is why row 4 is deleted exactly like row 2. I am trying to filter out rows where values are close to each other.

http://stackoverflow.com/comment/90573176
type: Comment
comment on: http://stackoverflow.com/a/51809038
has text: Oh, so simple! Thanks!
score: 0
type: AnswerComment

http://stackoverflow.com/comment/90819267
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51934119
has text: However, even if it did run the python interpreter, it would not import the current file in any way, would it?
score: 0

http://stackoverflow.com/q/51940568
has answer: http://stackoverflow.com/a/51940576
linked to: http://stackoverflow.com/q/25675943
downvote count: 3
score: -1
has title: TypeError: must be str, not float (Python, return value)
has answer: http://stackoverflow.com/a/51940750
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/90830919
has body: I'm trying to learn Python with CS Dojo's tutorial. I'm currently working on the task he gave us, which was building a "miles to kilometers converter". The task itself was very simple, but I want to build a program that does a little more than that. I want the output to be like "The distance" + "name (ex. from NewYork to Washington)" + " is" + (Value) + " in kilometers." but it is giving me the same error message over and over. My code is # miles variables name1 = "from_NewYork_to_Washington" miles1 = 20 name2 = "from_Boston_to_Dallas" miles2 = 30 name3 = "from_Tokyo_to_Seoul" miles3 = 40 #define function def conver(name, distance): d = distance * 1.6 print("result: ") print(d) return "The distance" + name + "is" + d + "in kilometers." # result variables result1 = conver(name1, miles1) result2 = conver(name2, miles2) result3 = conver(name3, miles3) The error message is following: result: 32.0 --------------------------------------------------------------------------- TypeError Traceback (most recent call last) &lt;ipython-input-135-4d54c2c21df2&gt; in &lt;module&gt;() 17 18 # result variables ---&gt; 19 result1 = conver(name1, miles1) 20 result2 = conver(name2, miles2) 21 result3 = conver(name3, miles3) &lt;ipython-input-135-4d54c2c21df2&gt; in conver(name, distance) 14 print("result: ") 15 print(d) ---&gt; 16 return "The distance" + name + "is" + d + "in kilometers." 17 18 # result variables TypeError: must be str, not float Thanks.
duplicate of: http://stackoverflow.com/q/25675943
tagged with: python
favorite count: 0
upvote count: 2
type: UnansweredQuestion

http://stackoverflow.com/a/51919579
has comment: http://stackoverflow.com/comment/90788880
score: 2
answers question: http://stackoverflow.com/q/51919467
accepted answer of: http://stackoverflow.com/q/51919467
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90788903
has comment: http://stackoverflow.com/comment/90788978
has body: The following should do it: credit = [['Math',6],['English',3],['Drama',2]] scores = [['Amy',None,90,80],['Jack',60,30,50],['Tom',80,None,50]] output = [ [stud[0]] + [ None if score is None else score * credit[idx][1] for idx, score in enumerate(stud[1:]) ] for stud in scores ] print(output) # [['Amy', None, 270, 160], ['Jack', 360, 90, 100], ['Tom', 480, None, 100]] That said, you should probably implement this simpler, without list comprehension.
upvote count: 2
type: Answer

http://stackoverflow.com/q/51904300
type: UnansweredQuestion
score: 34
has body: How do you list all Pipenv environments like virtualenv's lsvirtualenv command? The documentation does not say how. Thanks a lot to all for the help given. Cheers!
upvote count: 34
tagged with: pipenv
has answer: http://stackoverflow.com/a/61182777
type: Question
downvote count: 0
tagged with: virtualenv
has comment: http://stackoverflow.com/comment/90759498
has title: List all Pipenv environments
has answer: http://stackoverflow.com/a/70570674
tagged with: python
answer count: 4
has answer: http://stackoverflow.com/a/53235469
favorite count: 0
has answer: http://stackoverflow.com/a/67597205

http://stackoverflow.com/a/51927406
score: 0
answers question: http://stackoverflow.com/q/51871856
type: Answer
has body: Basic example Java code to search contact, send message and/or file. You can implement explicit wait if need. driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); List&lt;String&gt; targets = new ArrayList&lt;&gt;(); for (String target:targets) { driver.findElement(By.xpath("//button[.//span[@data-icon='search']]/..//input")).clear(); driver.findElement(By.xpath("//button[.//span[@data-icon='search']]/..//input")).sendKeys(target); try { driver.findElement(By.cssSelector("span[title='"+target+"']")).click(); } catch (WebDriverException e) { System.out.println("Not found"); continue; } driver.findElement(By.cssSelector("div[contenteditable='true']")).sendKeys("MassageToSend"); driver.findElement(By.cssSelector("span[data-icon='send']")).click(); //To send attachments //click to add driver.findElement(By.cssSelector("span[data-icon='clip']")).click(); //add file to send by file path driver.findElement(By.cssSelector("input[type='file']")).sendKeys("FilePath"); //click to send driver.findElement(By.cssSelector("span[data-icon='send-light']")).click(); } In python (may contains syntax errors): if msgToSend[count][0]==curHour and msgToSend[count][1]==curMin and msgToSend[count][2]==curSec: # utility variables to tract count of success and fails success = 0 sNo = 1 failList = [] # Iterate over selected contacts for target in targets: print(sNo, ". Target is: " + target) sNo+=1 inputSearchBox = driver.find_element_by_id('//button[.//span[@data-icon="search"]]/..//input') inputSearchBox.clear() inputSearchBox.send_keys(target[1:len(target) - 1]) try: wait5.until(EC.presence_of_element_located((By.CSSSELECTOR, 'span[title="'+ target +'"]'))) except: print("Cannot find Target: " + target) failList.append(target) continue driver.find_element_by_css_selector('div[contenteditable="true"]').sendKeys("Hello, " + target + "."+ Keys.SHIFT + Keys.ENTER + msgToSend[count][3] + Keys.SPACE) driver.find_element_by_css_selector('span[data-icon="send"]').click() # To send attac…

http://stackoverflow.com/comment/90668334
type: QuestionComment
comment on: http://stackoverflow.com/q/51857010
has text: As explained in the comment of the answer below, shouldn't it be a two- or three-liner to resample between the range? The default behaviour does not make sense to me..
score: 0
type: Comment

http://stackoverflow.com/a/51916766
answers question: http://stackoverflow.com/q/51916745
has comment: http://stackoverflow.com/comment/90784085
has comment: http://stackoverflow.com/comment/90783641
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/90784107
has body: Use random.randint to get a random index and use pop to get the element with that index from the list &gt;&gt;&gt; import random &gt;&gt;&gt; l = [1,2,4,6] &gt;&gt;&gt; idx = random.randint(0, len(l)-1) &gt;&gt;&gt; r = l.pop(idx) &gt;&gt;&gt; r 4 &gt;&gt;&gt; l [1, 2, 6]
upvote count: 2
type: Answer

http://stackoverflow.com/comment/90640732
type: Comment
has text: I use lowercase for my foreign and M2M fields, and uppercase for strictly local ones. thought that was a convention?
comment on: http://stackoverflow.com/a/51828853
score: 0
type: AnswerComment

http://stackoverflow.com/comment/90643289
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/51842529
has text: I don't think you can access the pipeline from within one of the steps. Maybe if you would explain what in you Regressor.fit would use this information, I can help with an alternative

http://stackoverflow.com/comment/90681213
comment on: http://stackoverflow.com/q/51864040
type: Comment
has text: Thanks for your inputs. Understood.
score: 0
type: QuestionComment

http://stackoverflow.com/q/51860378
accepted answer: http://stackoverflow.com/a/51861999
has comment: http://stackoverflow.com/comment/90675399
possible better answer: http://stackoverflow.com/a/51861758
has body: I'm looking for a way to merge multiple dicts with each other, which contain nested dicts too. The number of nested dicts is not static but dynamic. At the end the Final dict should contain all the dicts of dicts and the sum of their values: COUNTRY1 = {'a': {'X': 10, 'Y': 18, 'Z': 17}, 'b': {'AA':{'AAx':45,'AAy':22},'BB':{'BBx':45,'BBy':22}}, 'c': 100} COUNTRY2 = {'a': {'U': 12, 'V': 34, 'W': 23}, 'b': {'AA':{'AAz':23,'AAa':26},'BB':{'BBz':11,'BBa':15}}, 'c': 115} COUNTRY3 = {'a': {'Y': 15, 'Z': 14, 'X': 12}, 'b': {'AA':{'AAx':45,'AAz':22},'BB':{'BBy':45,'BBz':22}}, 'c': 232} # After merging the dictionaries the result should look like: ALL &gt;&gt;&gt; {'a': {'X': 22, 'Y': 33, 'Z': 31, 'U': 12, 'V': 34, 'W': 23}, 'b': {'AA':{'AAx':90,'AAy':22,'AAz':45,'AAa':26},'BB':{'BBx':45,'BBy':67, 'BBz':33,'BBa':15}}, 'c': 447} I tried the following code which allows nested dicts to a max of 3 nested dicts. Unfortunately the code doesn't do what I expected. Thereby it doesn't look very clean, I feel like this could be done with a recursive function, however I can't find a way to do it. COUNTRIES = ['COUNTRY1','COUNTRY2', 'COUNTRY3'] ALL = {} for COUNTRY_CODE in COUNTRIES: COUNTRY = pickle.load(open(COUNTRY_CODE+".p", "rb")) keys = COUNTRY.keys() for key in keys: try: keys2 = COUNTRY[key].keys() print(key, keys2) for key2 in keys2: try: keys3 = COUNTRY[key][key2].keys() print(key2, keys3) for key3 in keys3: try: keys4 = COUNTRY[key][key2][key3].keys() print(key3, keys4) except: print(key3, "NO KEY3") if not key3 in ALL[key][key2]: ALL[key][key2][key3] = COUNTRY[key][key2][key3] else: ALL[key][key2][key3] =+ COUNTRY[key][key2][key3] except: print(key2, "NO KEY2") if not key2 in ALL[key]: ALL[key][key2] = COUNTRY[key][key2] else: ALL[key][key2] =+ COUNTRY[key][key2] except: print(key, "NO KEY") if not key in ALL: ALL[key] = COUNTRY[key] else: ALL[key] =+ COUNTRY[key] print(ALL)
has answer: http://stackoverflow.com/a/51861758
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/90675034
has title: Merging dict of dicts and sum values
favorite count: 0
has comment: http://stackoverflow.com/comment/90674635
has comment: http://stackoverflow.com/comment/90674780
type: Question
score: 3
has answer: http://stackoverflow.com/a/51861999
tagged with: python
tagged with: merge
tagged with: dictionary
tagged with: python-3.x
upvote count: 3
answer count: 2

http://stackoverflow.com/a/51811204
type: Answer
score: 1
upvote count: 1
has body: csv.writerows requires a list of lists, not a list of strings. Since strings are iterable, you were getting a single character as they are being iterated. Since the output isn't really a CSV, you should use the CSV module to read the file, and not write the file.
answers question: http://stackoverflow.com/q/51811096
downvote count: 0

http://stackoverflow.com/q/51855627
has comment: http://stackoverflow.com/comment/90666507
score: 0
tagged with: jupyter-notebook
answer count: 0
type: UnansweredQuestion
has title: "empty vocabulary" error for spam classifier
tagged with: machine-learning
tagged with: python
tagged with: vectorization
has comment: http://stackoverflow.com/comment/90666609
tagged with: anaconda
has body: I'm trying to make a spam classifier and I've used the following code to do so. But the issue is that I'm getting an error stating that my program has an "empty library" and that "My document has nothing but stop words". Do you know what's causing this? import os import io from pandas import DataFrame from sklearn.feature_extraction.text import CountVectorizer from sklearn.naive_bayes import MultinomialNB def readFiles(path): for root, dirnames, filenames in os.walk(path): for filename in filenames: path = os.path.join(root, filename) inBody = False lines = [] f = io.open(path, 'r', encoding='latin1') for line in f: if inBody: lines.append(line) elif line == '\n': inBody = True f.close() message = '\n'.join(lines) yield path, message def dataFrameFromDirectory(path, classification): rows = [] index = [] for filename, message in readFiles(path): rows.append({'message': message, 'class': classification}) index.append(filename) return DataFrame(rows, index=index) data = DataFrame({'message': [], 'class': []}) data = data.append(dataFrameFromDirectory('C:/Users/Tapan/Desktop/enron/enron1/spam', 'spam')) data = data.append(dataFrameFromDirectory('C:/Users/Tapan/Desktop/enron/enron1/ham', 'ham')) vectorizer = CountVectorizer() counts = vectorizer.fit_transform(data['message'].values) classifier = MultinomialNB() targets = data['class'].values classifier.fit(counts, targets) examples = ['prescribed online and shipped overnight to your door', 'vastar owns 68% of the gross production'] examples_counts = vectorizer.transform(examples) predictions = classifier.predict(examples_counts) print(predictions)
type: Question

http://stackoverflow.com/a/51857708
accepted answer of: http://stackoverflow.com/q/51857601
answers question: http://stackoverflow.com/q/51857601
has comment: http://stackoverflow.com/comment/90667755
upvote count: 7
type: Answer
has body: You can use a custom function with a dictionary comprehension: prob_tokens = ['119', '120', '123', '1234', '12345'] complete_tokens = ['112', '120', '121', '123', '1233', '1234', '1235', '12345'] def mapper(val, ref_list): if any(x.startswith(val) and (len(x) &gt; len(val)) for x in ref_list): return False if val in ref_list: return True return False res = {i: mapper(i, complete_tokens) for i in prob_tokens} print(res) {'119': False, '120': True, '123': False, '1234': False, '12345': True} If the number of characters criterion is important to you, you can adjust your logic accordingly using chained comparisons and an additional input: def mapper(val, ref_list, max_len): if any(x.startswith(val) and (0 &lt; (len(x) - len(val)) &lt;= max_len) for x in ref_list): return False if val in ref_list: return True return False min_len_sec_list = 3 max_len_sec_list = 5 add_lens = max_len_sec_list - min_len_sec_list res = {i: mapper(i, complete_tokens, add_lens) for i in prob_tokens}
downvote count: 0
has comment: http://stackoverflow.com/comment/90673713
score: 7
type: AcceptedAnswer

http://stackoverflow.com/q/51850165
favorite count: 0
accepted answer: http://stackoverflow.com/a/51850251
upvote count: 2
has comment: http://stackoverflow.com/comment/90653745
tagged with: python
score: 2
type: AnsweredQuestion
has title: Pandas DataFrame filter column A depending on if column B contains x for group of values in A
type: Question
has answer: http://stackoverflow.com/a/51850251
answer count: 1
tagged with: dataframe
tagged with: pandas
has comment: http://stackoverflow.com/comment/90653905
downvote count: 0
has body: I would like to filter the below DataFrame df on column ref, based on if for the value in ref, column type contains the value 'P'. In [32]: df Out[32]: ref type 0 1 P 1 1 C 2 1 A 3 2 C 4 3 P 5 3 P 6 4 P 7 4 A 8 5 C 9 5 A Here, ref values 1, 3, and 4 contain at least one row with value 'P' in column type, while 2 and 5 do not. I am trying to filter out any rows with ref 2 and 5 so that the final output is: In [34]: df Out[34]: ref type 0 1 P 1 1 C 2 1 A 4 3 P 5 3 P 6 4 P 7 4 A How could I do this (preferably in one step)?

http://stackoverflow.com/a/51886192
upvote count: 2
downvote count: 0
has body: Use random.sample instead of shuffle &gt;&gt;&gt; input_list = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t'] &gt;&gt;&gt; sum((random.sample(input_list[n:n+10], 10) for n in range(0,len(input_list),10)), []) ['f', 'i', 'd', 'a', 'g', 'j', 'e', 'c', 'b', 'h', 'p', 'l', 'r', 'q', 'm', 't', 's', 'n', 'o', 'k']
type: Answer
score: 2
answers question: http://stackoverflow.com/q/51885942

http://stackoverflow.com/q/51799953
score: 1
has title: ggplot Python : Error : TypeError: 'module' object is not callable
upvote count: 1
accepted answer: http://stackoverflow.com/a/51800044
type: Question
tagged with: python-ggplot
tagged with: python-2.7
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/51800044
has body: Hi I am trying to use ggplot library in Python. So I pip install gglot in my Anaconda command prompt. I tried basic plotting (Example from http://ggplot.yhathq.com/docs/geom_density.html) in jupyter notebook. But I am getting error saying 'TypeError: 'module' object is not callable'. There is no error while running the import statement of ggplot in the noteobok. But I am getting error while running the ggplot() + geom statement. from ggplot import * df = pd.DataFrame({ "x": np.random.normal(0, 10, 1000), "y": np.random.normal(0, 10, 1000), "z": np.random.normal(0, 10, 1000) }) df = pd.melt(df) ggplot(aes(x='value', color='variable'), data=df) + \ geom_density() TypeError Traceback (most recent call last) &lt;ipython-input-12-162182859f18&gt; in &lt;module&gt;() 6 df = pd.melt(df) 7 ----&gt; 8 ggplot(aes(x='value', color='variable'), data=df) + geom_density() TypeError: 'module' object is not callable Is there something I am missing here ?
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/a/51846025
upvote count: 7
has comment: http://stackoverflow.com/comment/90647621
has comment: http://stackoverflow.com/comment/98703858
score: 7
has comment: http://stackoverflow.com/comment/90645731
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51845977
has comment: http://stackoverflow.com/comment/90650234
has body: You can use drop_duplicates on subset=['CUSTOMER_FULL_NAME'] in the merge with how='left' to keep all rows from people such as: full = pd.merge( people, orders.drop_duplicates(subset=['CUSTOMER_FULL_NAME'], keep='first'), #here the differance left_on='FULL_NAME', right_on='CUSTOMER_FULL_NAME', how='left' #and add the how='left' ) So orders.drop_duplicates(subset=['CUSTOMER_FULL_NAME'], keep='first') will contain only once each name and during the merge, the matching will be with only this unique name
has comment: http://stackoverflow.com/comment/90650531
accepted answer of: http://stackoverflow.com/q/51845977
has comment: http://stackoverflow.com/comment/90650452
type: Answer
has comment: http://stackoverflow.com/comment/90645599

http://stackoverflow.com/q/51817919
score: 4
upvote count: 4
has comment: http://stackoverflow.com/comment/90589895
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/90589832
favorite count: 0
has body: I am a bit confused of the iloc function of pandas, because I want to select a range of columns and the output is different than expected. The same will happen to row selection, so I wrote a little example: template = pd.DataFrame( {'Headline': ['Subheading', '', 'Animal', 'Tiger', 'Bird', 'Lion'], 'Headline2': ['', 'Weight', 2017, 'group1', 'group2', 'group3'], 'Headline3': ['', '', 2018, 'group1', 'group2', 'group3'] }) Headline Headline2 Headline3 0 Subheading 1 Weight 2 Animal 2017 2018 3 Tiger group1 group1 4 Bird group2 group2 5 Lion group3 group3 I want to select line 1 to line 2 with print(template.loc[1:2]) the result is what I have expected: Headline Headline2 Headline3 1 Weight 2 Animal 2017 2018 If I do this print(template.iloc[1:2]) I would think that I get the same result, but no: Headline Headline2 Headline3 1 Weight I am a bit confused, because I expected the same behavior for both functions, but the output of both functions differ if I select a range (FROM:TO). It seems like using iloc needs to have the TO value +1 in order to have the same result as loc print(template.iloc[1:3]): Headline Headline2 Headline3 1 Weight 2 Animal 2017 2018 Can someone put some light on it?
accepted answer: http://stackoverflow.com/a/51818001
tagged with: pandas
tagged with: python
type: AnsweredQuestion
has title: Pandas iloc returns different range than loc
linked to: http://stackoverflow.com/q/31593201
duplicate of: http://stackoverflow.com/q/31593201
type: Question
has answer: http://stackoverflow.com/a/51818001
tagged with: dataframe

http://stackoverflow.com/q/51834382
type: AnsweredQuestion
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/90745566
accepted answer: http://stackoverflow.com/a/51952478
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/90832498
has answer: http://stackoverflow.com/a/51952478
tagged with: tensorflow-estimator
tagged with: bazel
upvote count: 1
answer count: 1
favorite count: 0
tagged with: python
has body: I'm trying to make a *.pb model using tf.estimator and export_savedmodel(), it is a simple classifier to classify iris dataset (4 features, 3 classes): import tensorflow as tf num_epoch = 500 num_train = 120 num_test = 30 # 1 Define input function def input_function(x, y, is_train): dict_x = { "thisisinput" : x, } dataset = tf.data.Dataset.from_tensor_slices(( dict_x, y )) if is_train: dataset = dataset.shuffle(num_train).repeat(num_epoch).batch(num_train) else: dataset = dataset.batch(num_test) return dataset def my_serving_input_fn(): input_data = tf.placeholder(tf.string, [None], name='input_tensors') receiver_tensors = {"inputs" : input_data} # 2 Define feature columns feature_columns = [ tf.feature_column.numeric_column(key="thisisinput", shape=4),] features = tf.parse_example( input_data, tf.feature_column.make_parse_example_spec(feature_columns)) return tf.estimator.export.ServingInputReceiver(features, receiver_tensors) def main(argv): tf.set_random_seed(1103) # avoiding different result of random # 2 Define feature columns feature_columns = [ tf.feature_column.numeric_column(key="thisisinput", shape=4),] # 3 Define an estimator classifier = tf.estimator.DNNClassifier( feature_columns=feature_columns, hidden_units=[10], n_classes=3, optimizer=tf.train.GradientDescentOptimizer(0.001), activation_fn=tf.nn.relu, model_dir = 'modeliris2/' ) # Train the model classifier.train( input_fn=lambda:input_function(xtrain, ytrain, True) ) # Evaluate the model eval_result = classifier.evaluate( input_fn=lambda:input_function(xtest, ytest, False) ) print('\nTest set accuracy: {accuracy:0.3f}\n'.format(**eval_result)) print('\nSaving models...') classifier.export_savedmodel("modeliris2pb", my_serving_input_fn) if __name__ == "__main__": tf.logging.set_verbosity(tf.logging.INFO) tf.app.run(main) Which will produce a saved_model.pb file. I've confirmed that the model works. I can also make another program which loads and runs it. Now, I want to summarize and freeze the model …
has title: Bazel error parsing tf.estimator model

http://stackoverflow.com/q/51800165
has answer: http://stackoverflow.com/a/51800447
tagged with: timezone
score: 0
has body: I am having trouble dealing with dealing with DateTimeField field. The question is, lets say i created datetime with timezone like that &gt;&gt;&gt; x = datetime.tzinfo("Asia/Kuala_Lumpur") &gt;&gt;&gt; y = datetime.datetime(2018, 7, 29, 12, 0, 13, 204815, x) i want to convert "y" to UTC so that I can save it to DateTimeField How do I do that ? Here is rest of my console test &gt;&gt;&gt; a = Attendance.objects.last() &gt;&gt;&gt; a &lt;Attendance: wawa&gt; &gt;&gt;&gt; a.updated_at datetime.datetime(2018, 7, 29, 13, 37, 26, 459259, tzinfo=&lt;UTC&gt;) &gt;&gt;&gt; a.updated_at = timezone.now() &gt;&gt;&gt; a.updated_at datetime.datetime(2018, 8, 11, 8, 49, 5, 381198, tzinfo=&lt;UTC&gt;) &gt;&gt;&gt; a.updated_at = timezone.now() &gt;&gt;&gt; a.updated_at datetime.datetime(2018, 8, 11, 8, 52, 33, 243825, tzinfo=&lt;UTC&gt;) &gt;&gt;&gt; x = datetime.tzinfo("Asia/Kuala_Lumpur") &gt;&gt;&gt; y = datetime.datetime(2018, 7, 29, 12, 0, 13, 204815, x) &gt;&gt;&gt; y datetime.datetime(2018, 7, 29, 12, 0, 13, 204815, tzinfo=&lt;datetime.tzinfo object at 0x113ac6600&gt;) &gt;&gt;&gt; y = datetime.datetime(2018, 7, 29, 12, 0, 13, 204815, x) &gt;&gt;&gt; y = datetime.datetime(2018, 7, 29, 12, 0, 13, 204815, x) &gt;&gt;&gt; a.updated_at = y &gt;&gt;&gt; a.updated_at datetime.datetime(2018, 7, 29, 12, 0, 13, 204815, tzinfo=&lt;datetime.tzinfo object at 0x113ac6600&gt;) &gt;&gt;&gt; a.save() &gt;&gt;&gt; a = Attendance.objects.last() &gt;&gt;&gt; a.updated_at datetime.datetime(2018, 8, 11, 13, 21, 2, 38046, tzinfo=&lt;UTC&gt;)
answer count: 2
tagged with: django
has answer: http://stackoverflow.com/a/51800746
type: UnansweredQuestion
has title: how to convert datetime from certain timezone to UTC ? django DateTimeField
type: Question
tagged with: datetime
tagged with: python

http://stackoverflow.com/comment/90594114
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51819046
type: AnswerComment
has text: Make all the quantifiers before the label text lazy instead of greedy, eg `(?=(?:.*?^From` https://regex101.com/r/pOThDP/4

http://stackoverflow.com/comment/90966859
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51959565
type: AnswerComment
has text: Just want to let you know that it worked perfectly fine after creating the project using visual studio. Thanks for all your help and support.

http://stackoverflow.com/q/51868760
has title: How to change input and output shape of any model architecture in Keras?
tagged with: keras
has comment: http://stackoverflow.com/comment/90759279
has body: I recently collected several Keras models for which I'm importing their architecture using keras.Models.model_from_json function (Note that there is no training made yet). My image data generator can be customized to produce batches of samples with different sizes and shapes (varying in the same flow generator). For instance, I may generate data with the shape (*batchsize*,32,32,3) and a total of 6 classes. Currently, the imported models have different input and output shapes, let's say (5*100*100*3) and 2 classes assigned to their layers. My goal is to change the input and output shape of such layers in order to compare different image sizes in the model performance. First, in the input layer, I have tried: model.layers[0].input.set_shape((None,32,32,3)) I received the following error: Dimension 1 in both shapes must be equal, but are 100 and 32. Shapes are [?,100,100,3] and [?,32,32,3]. Similarly for the output layer, using model.layers[len(model.layers)-1].output.set_shape((None,6)) the same error was throw Dimension 1 in both shapes must be equal, but are 2 and 6. Shapes are [?,2] and [?,6]. TLDR: Is there a generic function/util to dynamically change the input and output shape of any model architecture in Keras? PS: If the model has several outputs or the last two layers are, keras.layers.Dense followed by keras.layers.Activation, changing the shape of last layer is a viable solution?
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90711628
tagged with: tensorflow
type: Question
score: 0
has answer: http://stackoverflow.com/a/51919958
answer count: 1

http://stackoverflow.com/comment/90732634
score: 0
type: Comment
type: QuestionComment
has text: Is *Jane, I don't like cavillers or questioners; besides, there is something truly forbidding in a child taking up her elders in that manner.* one single sentence?
comment on: http://stackoverflow.com/q/51890444

http://stackoverflow.com/q/51884808
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51885106
has comment: http://stackoverflow.com/comment/90721551
answer count: 1
downvote count: 0
has title: python3 django manage.py migrate error _gorg
tagged with: virtualenv
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90721197
tagged with: django
tagged with: python
has body: I am trying to debug an error with python3. Below are versions of modules and the error when I try to run python3 manage.py migrate Python 3.6.5 python-ta 1.2.0 Below the error we are getting. Any advice or help on this appreciated. Traceback (most recent call last): File "manage.py", line 10, in &lt;module&gt; execute_from_command_line(sys.argv) File "/home/pcrs/.virtualenvs/pcrsenv/lib/python3.6/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/home/pcrs/.virtualenvs/pcrsenv/lib/python3.6/site-packages/django/core/management/__init__.py", line 337, in execute django.setup() File "/home/pcrs/.virtualenvs/pcrsenv/lib/python3.6/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/home/pcrs/.virtualenvs/pcrsenv/lib/python3.6/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models() File "/home/pcrs/.virtualenvs/pcrsenv/lib/python3.6/site-packages/django/apps/config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "/home/pcrs/.virtualenvs/pcrsenv/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/pcrs/pcrs/pcrs/problems_python/models.py", line 15, in &lt;module&gt; import python_ta File "/home/pcrs/.virtualenvs/pcrsenv/lib/python3.6/site-packages/python_ta/__init__.py", line 30, in &lt;module&gt; from .patches import patch_all File "/home/pcrs/.virtualenvs/…
type: UnansweredQuestion
score: 1

http://stackoverflow.com/comment/90853134
score: 0
type: Comment
has text: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/178460/discussion-between-bazingaa-and-headoverfeet).
type: QuestionComment
comment on: http://stackoverflow.com/q/51949000

http://stackoverflow.com/comment/90862497
comment on: http://stackoverflow.com/q/51955647
type: Comment
type: QuestionComment
has text: The problem may be garbage in your boto plugins directory and/or config. Have you installed any plugins or edited the boto configuration?
score: 0

http://stackoverflow.com/q/51838175
has body: I'm making a pong game which is basketball orientated. I'm trying to change the rectangles I currently have into basketball player sprites, to make it look more appealing. What happens is my player on the left side doesn't appear at all, and is invisible, but still functions as a block, and will hit the ball. Any help is much appreciated, thanks! import pygame black = (0,0,0) white = (255,255,255) pygame.init() size = 800,600 screen = pygame.display.set_mode(size) pygame.display.set_caption("Basketball Shootout") done = False clock = pygame.time.Clock() class Player1(pygame.sprite.Sprite): def __init__(self, x, y): """Constructor function""" # Call the parent's constructor super().__init__() # Set height, width self.image = pygame.Surface([15, 15]) self.image = pygame.image.load("player1.png") def player1(x1, y1, xsize, ysize): Player1(screen, [x1, y1, xsize, ysize]) def player2(x2, y2, xsize, ysize): pygame.draw.rect(screen, black, [x2,y2,xsize,ysize]) def ball(ballx, bally): pygame.draw.circle(screen, black, [ballx,bally],20) def Score1(score1): font = pygame.font.Font("Minecraft.ttf" ,50) text = font.render(str(score1), True, white) screen.blit(text, [160, 550]) def Score2(score2): font = pygame.font.Font("Minecraft.ttf" ,50) text = font.render(str(score2), True, white) screen.blit(text, [610, 550]) x1 = 20 y1 = 175 xsize = 35 ysize = 150 speed1 = 0 x2 = 740 y2 = 175 speed2 = 0 ballx = 550 bally = 250 speedx = 8 speedy = 5 score1 = 0 score2 = 0 bg = pygame.image.load("pongbg2.png") rect1 = pygame.Rect(50,510,100,50) def pausescreen(): import pausescreen display_game = True game_page = 1 while not done: for event in pygame.event.get(): if event.type == pygame.QUIT: done = True pygame.draw.rect(screen, (255, 255, 255), rect1) if event.type == pygame.KEYDOWN: if event.key == pygame.K_w: speed1 = -15 if event.key == pygame.K_s: speed1 = 15 if event.key == pygame.K_UP: speed2 = -15 if event.key == pygame.K_DOWN: speed2 = 15 if event.type == pygame.KEYUP: if event.key …
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90643379
downvote count: 2
type: Question
linked to: http://stackoverflow.com/q/29950906
score: -2
has comment: http://stackoverflow.com/comment/90630126
upvote count: 0
answer count: 1
has title: Sprite does not appear in pygame
favorite count: 0
has answer: http://stackoverflow.com/a/51845166
tagged with: python
tagged with: pygame

http://stackoverflow.com/q/51871101
has comment: http://stackoverflow.com/comment/90699345
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/90693873
has answer: http://stackoverflow.com/a/51874051
favorite count: 0
has answer: http://stackoverflow.com/a/51871155
has comment: http://stackoverflow.com/comment/90693956
upvote count: 0
type: UnansweredQuestion
has body: Please provide me any example and installation process in python. Example required is: Python file should available in localhost and server file should available in other system or remote server.So when I run the python file then Api should call for return json from the server file which is present in remote system
downvote count: 3
score: -3
tagged with: python
has comment: http://stackoverflow.com/comment/90693568
has title: How to call rest api in python which is present in other system

http://stackoverflow.com/comment/90621738
comment on: http://stackoverflow.com/q/51833922
score: 0
has text: Basically, the code is just straight up wrong and does not output what I want.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90669583
comment on: http://stackoverflow.com/q/51858530
has text: That is a fork of the original repo and has not been updated since last year. It therefor reflects an outdated version of the code
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/51879112
has title: Flask/Python - passing variables between functions
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51892638
type: Question
tagged with: function
linked to: http://stackoverflow.com/q/16043797
score: 0
answer count: 2
has body: I've spent a few days looking at this on and off but I can't work out what I'm doing wrong. I've tried to follow this: Passing Variables between functions I'm still not clear on what I need to do though. This is what I have presently but I've tried various permutations: def root(): hivelogin() occupancy() print (hiveSessionId) return ("Done") I need this to work in lots of places but I'll use hivelogin() as the example: def hivelogin(): import requests url = "https://api.prod.bgchprod.info:443/omnia/auth/sessions" payload = "{\n \"sessions\": [{\n \"username\": \"xxxxxxxxxxx\",\n \"password\": \"xxxxxxxxxxx\",\n \"caller\": \"WEB\"\n }]\n}" headers = { 'Content-Type': "application/vnd.alertme.zoo-6.1+json", 'Accept': "application/vnd.alertme.zoo-6.1+json", 'X-Omnia-Client': "Hive Web Dashboard", 'Cache-Control': "no-cache", } response = requests.request("POST", url, data=payload, headers=headers) data=response.json() hiveSessionId = (data['sessions'][0]['sessionId']) session['hiveSessionId'] = (data['sessions'][0]['sessionId']) return hiveSessionId I've got round it by using a session variable in this case but I don't want to have to do this when I've probably got loads of variables I need to pass around. So, what I need is for hiveSessionId to my root (or any other) function. If I do: def root(hiveSessionId=None) I get nothing - as I'd expect. If I do: def root(hiveSessionId=hiveSessionId) I get an error - as I'd expect. So, the simple question is how I pass a variable from the function that creates it to any other function in my app - probably between routes as I'm using Flask but I'm using MySQL to give some persistence. I've done a tiny bit of coding in the past with PHP but please bear in mind that I'm old, been learning Python for about 3 weeks, and this is my first app. I did the "Hello world" thing, watched a video about Python on Youtube and then did this so it's probably going to make you want to cry. EDIT: Simplified pseudo version of what I want: def a()…
accepted answer: http://stackoverflow.com/a/51892638
tagged with: variables
possible better answer: http://stackoverflow.com/a/51881455
has answer: http://stackoverflow.com/a/51881455
tagged with: python

http://stackoverflow.com/comment/90599461
comment on: http://stackoverflow.com/q/51821595
score: 0
type: Comment
has text: Is your `request.user` a `UserProfile` or a `User`?
type: QuestionComment

http://stackoverflow.com/a/51879603
answers question: http://stackoverflow.com/q/51877778
type: Answer
upvote count: 1
score: 1
has body: Join only those records where expected id equals actual and there is mismatch in any other column: df1.join(df2, df1.id=df2.id and (df1.name != df2.name or df1.age != df2.age...)) This means you will do for loop only across mismatched rows, instead of whole dataset.
downvote count: 0

http://stackoverflow.com/comment/90677758
comment on: http://stackoverflow.com/q/51862401
type: QuestionComment
has text: Note that `sorted` *returns* a sorted list, without altering the original. The command you gave simply discards the result, unless it's run from the Python shell (which would print the return value).
type: Comment
score: 1

http://stackoverflow.com/comment/90844089
score: 0
comment on: http://stackoverflow.com/q/51947042
type: QuestionComment
type: Comment
has text: Was missing an addition operator, had copied from old code. Thank you. @Rup

http://stackoverflow.com/a/51867991
has comment: http://stackoverflow.com/comment/90687996
downvote count: 0
has comment: http://stackoverflow.com/comment/90687807
type: Answer
has comment: http://stackoverflow.com/comment/90687893
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51867959
has comment: http://stackoverflow.com/comment/90687952
has body: Once you read in the file such that the contents are a string in the name text. You can pass that to the pandas.value_counts function to give you the counts of each character. In order to filter out only letters, I use the filter function and pass the str.isalpha as a predicate to determine the truthfulness for each character. pandas.value_counts Your code should look like this: import pandas as pd import os fileName = input("Enter file Name: ") if os.path.exists(fileName): with open(fileName) as f: text = f.read() else: print(("Error 404 File Not Found!") counts = pd.value_counts([*filter(str.isalpha, text)]) / len(text) print(counts) a 0.064935 f 0.058442 q 0.051948 d 0.045455 r 0.045455 j 0.038961 e 0.032468 l 0.032468 k 0.032468 s 0.032468 t 0.032468 u 0.032468 i 0.032468 p 0.025974 w 0.025974 h 0.025974 g 0.019481 o 0.019481 y 0.012987 n 0.012987 T 0.006494 Q 0.006494 R 0.006494 dtype: float64 Setup text = """ a;sdlkfja;sldkfja spogkia ;dlkfq ;welrfuq[3094t8urq34TRQaaj] aksdfjpaoi43urpq9384t983456tuyweirghnwehrg q34haed89fy9q9384uithnjlfasdf;q3p[er]q34t9rwiofdj"""

http://stackoverflow.com/comment/90617756
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51831692
type: AnswerComment
has text: @wim The problem is that subtracting two odict_keys returns a regular set with arbitrary ordering.

http://stackoverflow.com/comment/90754217
type: AnswerComment
type: Comment
has text: You can find the max value and divide everything by this max. And invert it by multiplying the same value.
comment on: http://stackoverflow.com/a/51901458
score: 1

http://stackoverflow.com/a/51898181
has body: If you use functools.wraps() in your decorator, the decorated function will have the __name__ of the wrapped function. IF you had some sample code for the decorator in your question, I could show more precisely how to do this...
type: Answer
downvote count: 1
answers question: http://stackoverflow.com/q/51897851
score: -1
upvote count: 0

http://stackoverflow.com/comment/90711624
has text: And that problem is?
type: AnswerComment
type: Comment
score: 0
comment on: http://stackoverflow.com/a/51879483

http://stackoverflow.com/comment/90804917
comment on: http://stackoverflow.com/q/51923874
has text: to check if the key is int or not
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52247885
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/51955417
has body: This is a bug in Airflow version &lt;= 1.8. This does work in Airflow version >= 1.9.
answers question: http://stackoverflow.com/q/51955417
score: 0

http://stackoverflow.com/comment/90626465
type: Comment
type: QuestionComment
has text: Please have a look at https://stackoverflow.com/help/how-to-ask & https://stackoverflow.com/help/mcve
comment on: http://stackoverflow.com/q/51807792
score: 0

http://stackoverflow.com/q/51812302
tagged with: selenium-webdriver
linked to: http://stackoverflow.com/q/11223011
has body: Actually this button is located inside container. Please provide syntax for python Here this property has unique name, but dont know how to use this [data-control-name="job_search_category_suggestion_it"] IT I used this code: elem = driver.find_elements_by_xpath('//button[@data-control-name="job_search_category_suggestion_it]').click()
has answer: http://stackoverflow.com/a/51916120
tagged with: webdriver
type: Question
upvote count: 0
score: -2
answer count: 1
tagged with: python
has title: How to find the element from the HTML provided through Selenium and Python?
favorite count: 0
tagged with: xpath
type: UnansweredQuestion
downvote count: 2
tagged with: selenium

http://stackoverflow.com/comment/90811392
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51929357
has text: Hahaha. Seems like you did the same mistake as I did. You were trying to execute it from IDE. Now while executing it from terminal it got replicated. :P
type: Comment

http://stackoverflow.com/comment/90843097
type: QuestionComment
score: 2
has text: How do you want it to "ignore" the `nan` data? Just don't include that dimension (eeek)? Replace it with something? Predict it?
comment on: http://stackoverflow.com/q/51946728
type: Comment

http://stackoverflow.com/q/51801722
has answer: http://stackoverflow.com/a/51801787
has answer: http://stackoverflow.com/a/51801769
has answer: http://stackoverflow.com/a/51801758
has body: I am trying to write each element inside a list to multiple files. Suppose I have a list: value = [ 'abc' , 'def' , 'ghi' ] How can write each element inside the list value to multiple files? So, in this case, there should be three text files be created and each value abc,def and ghi in each file. I have a simple python script which will write all the list values to a single text file: value = ['a','b','c'] for i in value: f=open('/tmp/new.txt','a') f.write(i) How can I achieve my use-case? Thanks in advance.
tagged with: python
has title: How to write each element of list in multiple text file?
answer count: 4
has answer: http://stackoverflow.com/a/51801780
has comment: http://stackoverflow.com/comment/90559732
type: UnansweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/90559752
score: 0

http://stackoverflow.com/q/51854107
has answer: http://stackoverflow.com/a/51854292
score: 0
has comment: http://stackoverflow.com/comment/90660752
answer count: 1
has comment: http://stackoverflow.com/comment/90661189
tagged with: python-3.x
has body: I am trying to create an anagram program quiz. One of the things I have done is having one central method of reading from a specified file dependant on which option the user has chosen rather than having to repeat the code. However, when trying to save the info to file, the variable saved has the pathfile saved inside it. How can I split it so that it will only save the name of the file (i.e, name of the quiz) that has been opened? def main(): name = input("Please Enter your name to begin") print("Hi",name,"Welcome to the Computer Science Quiz") user_choice = menu() option = choice(user_choice) option, counter = questions(option) update_file(name, option, counter) def menu(): print("Select from the following categories:") print("1 for System's Architecture, 2 for Memory, 3 for Storage or 4 for Network Topologies") choice = int(input("choose option")) if choice &gt;0 and choice&lt;=4: ## range check print("you have chosen",choice,) else: print("This is an invalid number") menu() return choice def choice(user_choice): if user_choice == 1: systems = open('systems.csv','r') return systems elif user_choice ==2: memory = open('memory.csv','r') return memory else: storage = open('storage.csv','r') return storage def questions(option): counter = 0 for line in option: anagrams = (line.rstrip("\n").split(",")) question = anagrams[0] answer = anagrams[1] print (question) print (answer) guess = input("Enter your guess") if guess == answer: print("Well Done") counter = counter + 1 else: print("oops") print("You have scored",counter,"correctly") return option,counter def update_file(name, option, counter): string_counter = (str(counter)) string_option = (str(option)) results = [name,",",string_counter,",",string_option,"\n"] file = open('results.csv','a') file.writelines(results) file.close() This is what it shows when the file is saved for the option variable: &lt;_io.TextIOWrapper name='storage.csv' mode='r' encoding='cp1252'>
linked to: http://stackoverflow.com/q/8384737
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90661070
tagged with: python
has title: Splitting a Python Filename
duplicate of: http://stackoverflow.com/q/8384737
has comment: http://stackoverflow.com/comment/90661250
tagged with: filenames
type: Question
has comment: http://stackoverflow.com/comment/90661350

parallel-processing
tags question: http://stackoverflow.com/q/51917981
tags question: http://stackoverflow.com/q/51878371
tags question: http://stackoverflow.com/q/51804560
tags question: http://stackoverflow.com/q/51868214
tags question: http://stackoverflow.com/q/51828790
tags question: http://stackoverflow.com/q/51908579
tags question: http://stackoverflow.com/q/51951400
type: Tag
tag name: parallel-processing
tags question: http://stackoverflow.com/q/51947860
tags question: http://stackoverflow.com/q/51844679
tags question: http://stackoverflow.com/q/51939518
tags question: http://stackoverflow.com/q/51824191

http://stackoverflow.com/q/51933016
type: Question
score: 3
tagged with: conda
downvote count: 0
has title: Where should i locate my conda env used by the root user?
favorite count: 0
tagged with: linux
tagged with: python
answer count: 0
upvote count: 3
type: UnansweredQuestion
has body: I have a script that should run every night on multiple servers. The Python environment is managed by conda and there is an environment.yml to set it up. The script sets its Python to the one in the environment that it depends on. I want to have a conda env that can be used when running these cron jobs, without it being owned by a specific person. Is there a way to make a "user neutral" conda env? Or do I have to create a new user that belongs to the project?

http://stackoverflow.com/comment/90721728
has text: OpenCV have a thinning algorithm implemented in the `ximgproc` module. It process a skeletonization so it reduce the numbers to the fewest number of pixel possible for each region. Then you can take a look to the module `text` of OpenCV
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51856575
type: Comment

http://stackoverflow.com/comment/90667657
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51852545
has text: John La Rooy Your answer is great too, and a great implementation of "itertools" (it's probably faster too)
score: 0

http://stackoverflow.com/q/51926237
tagged with: match
downvote count: 1
tagged with: list
type: Question
score: 0
answer count: 2
has body: Suppose I have a nested list which looks like this: my_list = [['Germany', 'B-LOC'], ['Angela', 'B-PER'], ['Merkel', 'I-PER']] So each element contains two strings, the first representing a word from text data and the second string represents the label from a machine learning model. Here, B-LOC refers to Begin Location, B-PER to Begin Person and I-PER to Inside Person. What I am interested in is a smart way to find strings that belong together, based on their label. In this case I would like to output something like print(....) &gt;&gt;&gt; Germany Location &gt;&gt;&gt; Angela Merkel Person Any suggestion/hint how I could start?
tagged with: string
favorite count: 0
has comment: http://stackoverflow.com/comment/90802077
has comment: http://stackoverflow.com/comment/90802001
has answer: http://stackoverflow.com/a/51926477
has comment: http://stackoverflow.com/comment/90802041
has comment: http://stackoverflow.com/comment/90802033
tagged with: python
has title: Find strings that belong together based on their label
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51926362
upvote count: 1

http://stackoverflow.com/comment/90740920
type: Comment
comment on: http://stackoverflow.com/q/51893567
score: 0
has text: Solved.Had to uninstall PyCharm, install bs4 and re install pycharm.
type: QuestionComment

http://stackoverflow.com/comment/90857751
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51953659
has text: Could you explain what is tabs in list?

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

http://stackoverflow.com/comment/90561736
comment on: http://stackoverflow.com/a/51802440
has text: Have you tested it in your python script? That should work for the last two digits.
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/90695950
type: AnswerComment
score: 0
type: Comment
has text: Working fine SIr.
comment on: http://stackoverflow.com/a/51871959

http://stackoverflow.com/a/51937996
has comment: http://stackoverflow.com/comment/90826114
has body: If you are not aware of the pdb debugger in python, please give it a try. It's a very interactive debugger I have ever come across. python debugger I am sure we can control the loop iterations manually with pdb. But altering list mid way, not sure. Give it a try.
downvote count: 2
type: Answer
score: -2
upvote count: 0
answers question: http://stackoverflow.com/q/51937482

http://stackoverflow.com/a/51865012
has comment: http://stackoverflow.com/comment/90682700
answers question: http://stackoverflow.com/q/51864925
has body: First of all, make both functions return lists of strings which contain the full paths of the images which will be copied, and the directories to where they will be copied. Afterwards, save the results of allimgs() and allfolders() into variables and loop through them. Here is how the first function should look like: def allimgs(): ret = [] counter = 0 for imgs in path: if imgs.endswith('.JPG'): counter += 1 #if hits the 24th images then stop and #copy the first until 24 to another 24 folders one by one if counter &gt; 24: break else: src = os.path.join('C:\\Users\\User\\Desktop\\img',imgs) ret.append(src) return ret (I left the other one for you as an exercise) Then loop over them: for image_path in allimgs(): for folder_path in allfolders(): shutil.copy(image_path, folder_path)
score: 0
has comment: http://stackoverflow.com/comment/90683558
type: Answer

http://stackoverflow.com/comment/90722808
score: 0
type: Comment
type: QuestionComment
has text: My issue is a permission error. py.test should be able to run without a test file, where the output is something like the following: ============================= test session starts ============================= platform darwin -- Python 3.6.0, pytest-3.0.5, py-1.4.32, pluggy-0.4.0 rootdir: /Users/Student, inifile: collected 0 items ========================= no tests ran in 0.02 seconds ========================
comment on: http://stackoverflow.com/q/51885525

http://stackoverflow.com/q/51936010
tagged with: ms-access
favorite count: 0
has comment: http://stackoverflow.com/comment/90851624
type: Question
tagged with: pandas
has comment: http://stackoverflow.com/comment/90849154
score: 3
has comment: http://stackoverflow.com/comment/90856898
has comment: http://stackoverflow.com/comment/90825891
has answer: http://stackoverflow.com/a/51936309
has comment: http://stackoverflow.com/comment/90825602
upvote count: 3
tagged with: python
answer count: 1
has comment: http://stackoverflow.com/comment/90856821
has comment: http://stackoverflow.com/comment/90828341
has comment: http://stackoverflow.com/comment/90822972
has comment: http://stackoverflow.com/comment/90851047
has title: Read access table into dataframe
has body: I'm trying to read an Access table into a pandas dataframe and am a relative newbie. The name of the file/table are: Name of MS Access file: test.mdb table Name: MA MEMBERSHIP COMBINED CAP REPORT I've trying the pandas_access package w/o luck. Code I tried is below: import pandas_access as mdb import pandas as pd df=pd.DataFrame() df = mdb.read_table("test.mdb", "MA MEMBERSHIP COMBINED CAP REPORT 2018") Table I'm reading is about 700 MB. Would appreciate any suggestions? -Joe
downvote count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/51872090
score: -1
downvote count: 2
upvote count: 1
tagged with: scrapy
answer count: 1
has title: how to scrape
type: UnansweredQuestion
has body: I newbie in using scrappy. I want to scrape link in this website harga-hp . in this element like I share the picture when I click on xiaomi it will link to the xiaomi page and then I will scrape the price and the name . can someone help me to fix this code. import scrapy from handset.items import HandsetItem class HandsetpriceSpider(scrapy.Spider): name = 'handsetprice' start_urls = ['http://id.priceprice.com/harga-hp/'] def parse(self, response): urls = response.css('ul.maker &gt; a::attr(href)').extract() for url in urls: url = response.urljoin(url) yield scrapy.Request(url=url, callback=self.parse_details) next_page_url = response.css('li.last &gt; a::attr(href)').extract_first() if next_page_url: next_page_url = response.urljoin(next_page_url) yield scrapy.Request(url=next_page_url, callback=self.parse) def parse_details(self, response): yield { 'Name' : response.css('li.name a::text').extract_first(), 'Price' : response.css('.newPice::text').extract_first(), } and the items.py : import scrapy from scrapy.item import Item, Field class HandsetItem(scrapy.Item): Name =scrapy.Field() Price =scrapy.Field()
has answer: http://stackoverflow.com/a/51908431
favorite count: 0
type: Question
tagged with: python

http://stackoverflow.com/comment/90814041
type: AnswerComment
type: Comment
has text: Where did you put the sleep at? Also, make sure you `hover` the menu tab instead of `clicking` it.
comment on: http://stackoverflow.com/a/51920098
score: 0

http://stackoverflow.com/comment/90692085
score: 0
type: Comment
has text: Thanks Martin Bonner. The problem is fixed!
type: AnswerComment
comment on: http://stackoverflow.com/a/51870244

http://stackoverflow.com/q/51858067
possible better answer: http://stackoverflow.com/a/52284494
favorite count: 0
has body: I have a CSV files with all numeric values except the header row. When trying to build tensors, I get the following exception: Traceback (most recent call last): File "pytorch.py", line 14, in &lt;module&gt; test_tensor = torch.tensor(test) ValueError: could not determine the shape of object type 'DataFrame' This is my code: import torch import dask.dataframe as dd device = torch.device("cuda:0") print("Loading CSV...") test = dd.read_csv("test.csv", encoding = "UTF-8") train = dd.read_csv("train.csv", encoding = "UTF-8") print("Converting to Tensor...") test_tensor = torch.tensor(test) train_tensor = torch.tensor(train) Using pandas instead of Dask for CSV parsing produced the same error. I also tried to specify dtype=torch.float64 inside the call to torch.tensor(data), but got the same error again.
has answer: http://stackoverflow.com/a/63949856
answer count: 5
has answer: http://stackoverflow.com/a/71697128
tagged with: python
has answer: http://stackoverflow.com/a/77779972
upvote count: 22
type: AnsweredQuestion
downvote count: 0
tagged with: pytorch
has answer: http://stackoverflow.com/a/51859020
accepted answer: http://stackoverflow.com/a/51859020
has title: Parsing CSV into Pytorch tensors
type: Question
score: 22
has answer: http://stackoverflow.com/a/52284494
tagged with: pandas

http://stackoverflow.com/comment/90585756
type: QuestionComment
has text: actually i was struggling with that too :(, but didnt know how to phrase it. True story admit not the best description for my problem, agreed
type: Comment
comment on: http://stackoverflow.com/q/51815397
score: 0

http://stackoverflow.com/comment/90751899
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51900310
has text: yes, it is defined.

http://stackoverflow.com/comment/90775992
has text: Question is a bit ambiguous, I like your answer too, I think the question could use some clarification
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51912932

http://stackoverflow.com/comment/90652018
type: Comment
type: QuestionComment
has text: Haven't tested - but you might be creating a list of list when you're doing `names = [col_names]` which makes it equal to `'TransID', 'BusinessName', 'Timestamp'`; try with `names = col_names`
comment on: http://stackoverflow.com/q/51848030
score: 0

http://stackoverflow.com/a/51914404
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/51914153
answers question: http://stackoverflow.com/q/51914153
has body: Taking a shot here zeros = df.col2.eq(0) vals = df.groupby(['col1', df.col2.ne(df.col2.shift()).cumsum()]).col3.cumsum() df['id'] = np.where(zeros, 0, vals) Explanation: Whenever col2 is 0, just set 0. Else, just set the cumsum of the grouped values.
has comment: http://stackoverflow.com/comment/90792532
has comment: http://stackoverflow.com/comment/90788134
upvote count: 1
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/90790314
has comment: http://stackoverflow.com/comment/90778818

discord
tags question: http://stackoverflow.com/q/51814995
tags question: http://stackoverflow.com/q/51851334
tags question: http://stackoverflow.com/q/51858123
tags question: http://stackoverflow.com/q/51914224
tags question: http://stackoverflow.com/q/51818387
type: Tag
tags question: http://stackoverflow.com/q/51887465
tags question: http://stackoverflow.com/q/51882207
tags question: http://stackoverflow.com/q/51807056
tags question: http://stackoverflow.com/q/51826426
tags question: http://stackoverflow.com/q/51919352
tags question: http://stackoverflow.com/q/51946158
tags question: http://stackoverflow.com/q/51913232
tags question: http://stackoverflow.com/q/51867193
tags question: http://stackoverflow.com/q/51915962
tags question: http://stackoverflow.com/q/51922926
tag name: discord
tags question: http://stackoverflow.com/q/51877958
tags question: http://stackoverflow.com/q/51909488
tags question: http://stackoverflow.com/q/51886428
tags question: http://stackoverflow.com/q/51853854
tags question: http://stackoverflow.com/q/51922091
tags question: http://stackoverflow.com/q/51823648
tags question: http://stackoverflow.com/q/51887472

http://stackoverflow.com/comment/90593699
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/51819773
has text: There's no shortage of Python tutorials, starting with the official one...

http://stackoverflow.com/comment/90861466
comment on: http://stackoverflow.com/a/51955379
has text: If you do the spearmanr correlation on the column then you get the correlation between the two columns. I want the correlation of every row in the two columns. Does that make more sense?
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/51812656
tagged with: sql
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/90580392
possible better answer: http://stackoverflow.com/a/51812801
favorite count: 0
has title: Cannot assign "9": "Characterweapons.weaponid" must be a "Weapons" instance
tagged with: django
tagged with: python
type: AnsweredQuestion
tagged with: django-views
has answer: http://stackoverflow.com/a/51812826
upvote count: 1
has body: I've been reading similar questions to mine but they didn't help me. I'm getting this error while I try to submit my form: Cannot assign "9": "Characterweapons.weaponid" must be a "Weapons" instance. This "9" is the ID from the weapon I got from my form, so that's very good, but when I try to put it in my weaponid column in my table Characterweapons, it gives me the error. models.py: from __future__ import unicode_literals from django.db import models class Category(models.Model): categoryid = models.AutoField(db_column='CategoryID', primary_key=True) # Field name made lowercase. categoryname = models.CharField(db_column='CategoryName', max_length=50, blank=True, null=True) # Field name made lowercase. class Meta: managed = True db_table = 'category' def __str__(self): return self.categoryname class Characters(models.Model): characterid = models.AutoField(db_column='CharacterID', primary_key=True) # Field name made lowercase. name = models.CharField(db_column='Name', unique=True, max_length=255) # Field name made lowercase. level = models.IntegerField(db_column='Level') # Field name made lowercase. credits = models.IntegerField(db_column='Credits') # Field name made lowercase. class Meta: managed = True db_table = 'characters' def __str__(self): return '%s %s %s' % (self.name, self.level, self.credits) class Weapons(models.Model): weaponid = models.AutoField(db_column='WeaponID', primary_key=True) # Field name made lowercase. weaponname = models.CharField(db_column='WeaponName', unique=True, max_length=255) # Field name made lowercase. class Meta: managed = True db_table = 'weapons' def __str__(self): return '%s %r' % (self.weaponname, self.weaponid) class Characterweapons(models.Model): characterid = models.ForeignKey(Characters, models.DO_NOTHING, db_column='CharacterID') # Field name made lowercase. weaponid = models.ForeignKey(Weapons, models.DO_NOTHING, db_column='WeaponID', blank=True, null=True) # Field name made lowercase. categoryid = models.ForeignKey(Cate…
type: Question
has comment: http://stackoverflow.com/comment/90580491
tagged with: django-models
has answer: http://stackoverflow.com/a/51812801
accepted answer: http://stackoverflow.com/a/51812826
answer count: 2
has comment: http://stackoverflow.com/comment/90580381

http://stackoverflow.com/a/51908418
type: Answer
upvote count: 1
has body: You can simply install tensorflow without anaconda environment. Just type pip install tensorflow (make sure you have deactivated any environment). From now on you will be able to use tensorflow without activating any environment.
score: 1
answers question: http://stackoverflow.com/q/51908302
downvote count: 0
has comment: http://stackoverflow.com/comment/90778432

http://stackoverflow.com/comment/90788144
type: Comment
comment on: http://stackoverflow.com/a/51915367
type: AnswerComment
has text: @Matias Salimbene It create `DataFrame` from `Series`, you can assign it to another variable like `df1 = pd.concat(all_s, axis=1).fillna(0).asfreq('MS', fill_value=0) print (df1)` for prevent overwrite `DataFrame`.
score: 0

http://stackoverflow.com/comment/90720590
comment on: http://stackoverflow.com/a/51884462
score: 0
type: AnswerComment
has text: thank you both answers work. above answers handles nan as well
type: Comment

http://stackoverflow.com/comment/90581240
type: AnswerComment
type: Comment
has text: Thanks for your suggestion, it works as desired. Unfortunately, I am not allowed to import itertools (can only use pandas and numpy). More general solution to this problem would be replacing hardcoded part of product function.
comment on: http://stackoverflow.com/a/51809894
score: 0

http://stackoverflow.com/a/51822750
accepted answer of: http://stackoverflow.com/q/51822615
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51822615
score: 4
type: Answer
has body: Symbolic mathematics is not something that most general-purpose programming languages do. Python works with integers and (real and complex) floating point values. For example the symbol math.pi is not a representation of the mathematical constant π, but just a Python variable containing a finite-precision floating point approximation of π. However, some people do sometimes want to do symbolic mathematics, so tools exist as third-party libraries. For example, you can do symbolic maths in Python by installing the SymPy package.
downvote count: 0
upvote count: 4

flask-sqlalchemy
tags question: http://stackoverflow.com/q/51825893
tags question: http://stackoverflow.com/q/51805995
tags question: http://stackoverflow.com/q/51803875
type: Tag
tags question: http://stackoverflow.com/q/51817484
tags question: http://stackoverflow.com/q/51937823
tags question: http://stackoverflow.com/q/51920541
tags question: http://stackoverflow.com/q/51949279
tags question: http://stackoverflow.com/q/51929968
tags question: http://stackoverflow.com/q/51802196
tags question: http://stackoverflow.com/q/51862572
tags question: http://stackoverflow.com/q/51830528
tags question: http://stackoverflow.com/q/51802862
tags question: http://stackoverflow.com/q/51952814
tag name: flask-sqlalchemy
tags question: http://stackoverflow.com/q/51914900
tags question: http://stackoverflow.com/q/51813834
tags question: http://stackoverflow.com/q/51864066
tags question: http://stackoverflow.com/q/51802694
tags question: http://stackoverflow.com/q/51807954
tags question: http://stackoverflow.com/q/51938668

http://stackoverflow.com/comment/90753583
comment on: http://stackoverflow.com/a/51900641
has text: I like this one, its clean, short, pythonic and works on an arbitrary length of a, would be really nice if we would now the actual use case...
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/90680057
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51863721
has text: Could you create fixtures called `gpu` and `cpu` that directly return whatever `data` currently returns for those cases, and then have `data` do something like `if request.param == "gpu": return gpu()` and likewise for `cpu`? That way `data` would still exist as a single feature, but you could also access the two separate versions directly for cases where you need to do so.
score: 0

http://stackoverflow.com/comment/90761485
type: Comment
type: QuestionComment
has text: @jamesfdearborn The linked question basically demonstrates a common restriction for *consumer* email infrastructure. Once you have your own email server with a good reputation, all sorts of trickery from the dark 1990s become possible again.
comment on: http://stackoverflow.com/q/51903282
score: 0

http://stackoverflow.com/comment/90587219
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51815721
has text: yeah ill just have a look at that
type: AnswerComment

http://stackoverflow.com/q/51878397
has comment: http://stackoverflow.com/comment/90708436
has comment: http://stackoverflow.com/comment/90710793
tagged with: python
has comment: http://stackoverflow.com/comment/90708488
has comment: http://stackoverflow.com/comment/90708383
has comment: http://stackoverflow.com/comment/90710463
score: 7
has title: Local scripts conflict with builtin modules when loading numpy
downvote count: 1
has comment: http://stackoverflow.com/comment/90711500
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/90710875
has comment: http://stackoverflow.com/comment/90708795
has comment: http://stackoverflow.com/comment/90709143
tagged with: anaconda
has comment: http://stackoverflow.com/comment/90711107
has answer: http://stackoverflow.com/a/51899930
tagged with: conda
has comment: http://stackoverflow.com/comment/90708304
has comment: http://stackoverflow.com/comment/90708532
has comment: http://stackoverflow.com/comment/90708723
has comment: http://stackoverflow.com/comment/90709715
answer count: 1
has comment: http://stackoverflow.com/comment/90709552
has comment: http://stackoverflow.com/comment/90708674
has body: There are many posts about relative/absolute imports issues, and most of them are about Python 2 and/or importing submodules. This is not my case: I am using Python 3, so absolute import is the default; (I have also reproduced this issue with Python 2); I am not trying to import a submodule from within another submodule, or any other complicated situation. I am just trying to import numpy in a script. My problem is simple: . └── foo ├── a.py └── math.py 1 directory, 2 files where a.py just contains import nupmy, and math.py contains x++ (intentionally invalid). In that case, running python3 foo/a.py causes an error, due to NumPy seemingly not being able to import the standard math module: Traceback (most recent call last): File "foo/a.py", line 1, in &lt;module&gt; import numpy File "/path/to/Anaconda3/lib/python3.6/site-packages/numpy/__init__.py", line 158, in &lt;module&gt; from . import add_newdocs File "/path/to/Anaconda3/lib/python3.6/site-packages/numpy/add_newdocs.py", line 13, in &lt;module&gt; from numpy.lib import add_newdoc File "/path/to/Anaconda3/lib/python3.6/site-packages/numpy/lib/__init__.py", line 3, in &lt;module&gt; import math File "/private/tmp/test-import/foo/math.py", line 1 x++ ^ SyntaxError: invalid syntax I am relatively inexperienced with Python, but this looks like a bug to me. I thought statements like import math in Python 3 behaved as absolute imports; how can a local file conflict with a standard module? Am I doing something wrong? To clarify, what I find surprising is that NumPy is unable to load the standard math module with import math, because I have a file in my local folder named math.py. Note that I never try to import that module myself. EDIT This seems to be an issue specific to conda (reproduced with both Anaconda and Miniconda). I am using Anaconda 5.2.0 (on OSX 10.13.6), and people in comments have been able to reproduce with different versions of python/anaconda, and different systems. I was able to reproduce this issue…
favorite count: 0
upvote count: 8
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90708641

http://stackoverflow.com/comment/90828311
score: 1
comment on: http://stackoverflow.com/q/51939096
has text: Where is the closing parenthesis?
type: QuestionComment
type: Comment

http://stackoverflow.com/q/51837333
favorite count: 0
has answer: http://stackoverflow.com/a/57421231
upvote count: 8
type: Question
has title: Adding form to Dash/Plotly app
has body: Ok, So I want to go one step further. I don't know if it is possible with a dash. I want to create a form ( probably WTForm from Flask ). The form should have date and annotation/comments section. When someone submits a form, it will save to the database. Then dash will read it and show on the graph. My graph looks like that: On the x-axis will be date from FlaskForm representing Event that it was stored in the database, and annotation will be showed in the graph itself when I hover to that exact date Something similar to this one: And now, can you please tell me if it's possible? What tools should I use it? It's just a concept, but I think will be helpful for everyone.
answer count: 2
tagged with: python
tagged with: plotly
has answer: http://stackoverflow.com/a/51840057
tagged with: plotly-dash
score: 8
tagged with: dashboard
downvote count: 0
type: UnansweredQuestion

http://stackoverflow.com/a/51912019
accepted answer of: http://stackoverflow.com/q/51911933
answers question: http://stackoverflow.com/q/51911933
score: 15
upvote count: 15
type: AcceptedAnswer
downvote count: 0
has body: chess_data is a dataframe chess_data.winner is a series chess_data.winner.str is an accessor to methods that are string specific and optimized (to a degree) chess_data.winner.str.split is one such method chess_data.winner.map is a different method that takes a dictionary or a callable object and either calls that callable with each element in the series or calls the dictionaries get method on each element of the series. In the case of using chess_data.winner.str.split Pandas does do a loop and performs a kind of str.split. While map is a more crude way of doing the same thing. With your data. chess_data.winner.str.split(':') 0 [A, 1] 1 [A, 2] 2 [A, 3] 3 [A, 4] 4 [B, 1] 5 [B, 2] Name: winner, dtype: object In order to get each first element, you'll want to use the string accessor again chess_data.winner.str.split(':').str[0] 0 A 1 A 2 A 3 A 4 B 5 B Name: winner, dtype: object This is the equivalent way of performing what you had done in your map chess_data.winner.map(lambda x: x.split(':')[0]) You could have also used a comprehension chess_data.assign(new_col=[x.split(':')[0] for x in chess_data.winner]) winner new_col 0 A:1 A 1 A:2 A 2 A:3 A 3 A:4 A 4 B:1 B 5 B:2 B
type: Answer

http://stackoverflow.com/a/51881319
has body: you can instead make a definition in Python instead, so you define it once. And where ever you need to use this definition again, you can simply call it. You can also make it a class once this function gets more complicated. Your code will be this instead: def train_time(times_hitz, time_luz): if times_hitz and times_luz: Code to be executed if both contain values elif times_luz: Code to be executed if only times_luz contains values elif times_hitz: Code to be executed if only times_hitz contains values else: print("No content available") sys.exit() return leave Where the "leave" will be from your executed code to determine when the next train leaves. And whenever you need to evaluate if the train is leaving, simply do: leave = train_time(times_hitz, time_luz)
type: Answer
has comment: http://stackoverflow.com/comment/90715486
has comment: http://stackoverflow.com/comment/90714135
score: 0
answers question: http://stackoverflow.com/q/51881176

http://stackoverflow.com/a/51891888
score: 1
has comment: http://stackoverflow.com/comment/90735999
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51891441
has body: To create a "fallback" route, i.e. route that would be invoked when no other more specific route matches. @app.route('/', defaults={'path': ''}) @app.route('/&lt;path:path&gt;') def root(path): return render_template("/login.html")
upvote count: 1

http://stackoverflow.com/a/57841614
upvote count: 2
score: 2
answers question: http://stackoverflow.com/q/51919448
has body: Iterating over a list or array with code like ar = [10, 11, 12] for i in ar: print(i) will actually put the values of the list sequentially in i - so this is the resulting output: 10 11 12 However, in the original code, i is mistakenly treated as an index into the list. In the first iteration for this example, ar[i] would mean ar[10] - which is, of course, an out-of-range index, causing an IndexError.
downvote count: 0
type: Answer

http://stackoverflow.com/comment/90835317
comment on: http://stackoverflow.com/a/51942613
type: AnswerComment
score: 0
type: Comment
has text: Thank you for the kindness. First of all, I tried the step six to create a string, but an error message "cannot create value:Error writing to the registry." appears.

http://stackoverflow.com/q/51940828
duplicate of: http://stackoverflow.com/q/40275234
has answer: http://stackoverflow.com/a/51942063
score: 1
upvote count: 1
linked to: http://stackoverflow.com/q/44757678
type: Question
has title: Unable to install Ta-lib on ubuntu - error with pip and make
linked to: http://stackoverflow.com/q/40275234
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python-3.x
has body: I've tried some alternatives but I can't install ta-lib or use make on my ubuntu ,when I send pip install ta-Lib Collecting ta-Lib Using cached https://files.pythonhosted.org/packages/90/05/d4c6a778d7a7de0be366bc4a850b4ffaeac2abad927f95fa8ba6f355a082/TA-Lib-0.4.17.tar.gz Requirement already satisfied: numpy in ./miniconda3/lib/python3.6/site-packages (from ta-Lib) (1.15.0) Building wheels for collected packages: ta-Lib Running setup.py bdist_wheel for ta-Lib ... error Complete output from command /home/user/miniconda3/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-install-ugk06wz4/ta-Lib/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" bdist_wheel -d /tmp/pip-wheel-v2gctt6z --python-tag cp36: /tmp/pip-install-ugk06wz4/ta-Lib/setup.py:79: UserWarning: Cannot find ta-lib library, installation may fail. warnings.warn('Cannot find ta-lib library, installation may fail.') running bdist_wheel running build running build_py creating build creating build/lib.linux-x86_64-3.6 creating build/lib.linux-x86_64-3.6/talib copying talib/stream.py -&gt; build/lib.linux-x86_64-3.6/talib copying talib/deprecated.py -&gt; build/lib.linux-x86_64-3.6/talib copying talib/abstract.py -&gt; build/lib.linux-x86_64-3.6/talib copying talib/test_stream.py -&gt; build/lib.linux-x86_64-3.6/talib copying talib/test_abstract.py -&gt; build/lib.linux-x86_64-3.6/talib copying talib/test_data.py -&gt; build/lib.linux-x86_64-3.6/talib copying talib/__init__.py -&gt; build/lib.linux-x86_64-3.6/talib copying talib/test_pandas.py -&gt; build/lib.linux-x86_64-3.6/talib copying talib/test_func.py -&gt; build/lib.linux-x86_64-3.6/talib running build_ext building 'talib._ta_lib' extension creating build/temp.linux-x86_64-3.6 creating build/temp.linux-x86_64-3.6/talib gcc -pthread -B /home/user/miniconda3/compiler_compat -Wl,--sysroot=/ -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -f…
tagged with: linux
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/100468323
tagged with: python

http://stackoverflow.com/comment/90633562
type: QuestionComment
comment on: http://stackoverflow.com/q/51840150
type: Comment
has text: @ellyanesc I am not sure how to reproduce this error but it occurs only with the qpixmap line
score: 0

spyder
tag name: spyder
tags question: http://stackoverflow.com/q/51839219
tags question: http://stackoverflow.com/q/51885478
type: Tag
tags question: http://stackoverflow.com/q/51907963
tags question: http://stackoverflow.com/q/51867655
tags question: http://stackoverflow.com/q/51818723

http://stackoverflow.com/a/51811951
type: Answer
downvote count: 0
score: 1
has body: First one creates a new array from the two. Second one mutates the original list.
upvote count: 1
answers question: http://stackoverflow.com/q/51811937

http://stackoverflow.com/q/51814224
has answer: http://stackoverflow.com/a/54223687
downvote count: 0
tagged with: dataset
tagged with: keras
favorite count: 0
has comment: http://stackoverflow.com/comment/90585879
upvote count: 6
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/56612738
score: 6
tagged with: python
has comment: http://stackoverflow.com/comment/90586016
has comment: http://stackoverflow.com/comment/90585783
tagged with: tensorflow
type: Question
has body: Tensorflow 1.10 on Google Colab (python 2.7) or my local system (python 3.6) Using sample code from https://www.tensorflow.org/guide/keras Code is import numpy as np import tensorflow as tf from tensorflow import keras data = np.random.random((1000, 32)) labels = np.random.random((1000, 10)) dataset1 = tf.data.Dataset.from_tensor_slices((data, labels)) dataset1 = dataset1.batch(32) dataset1 = dataset1.repeat() model = keras.Sequential() model.add(keras.layers.Dense(64, activation='relu')) model.add(keras.layers.Dense(64, activation='relu')) model.add(keras.layers.Dense(10, activation='softmax')) model.compile(optimizer=tf.train.AdamOptimizer(0.001), loss='categorical_crossentropy', metrics=['accuracy']) model.fit(dataset1, epochs=10, steps_per_epoch=30) Throws the following error: Error TypeError: Input 'y' of 'Mul' Op has type float32 that does not match type float64 of argument 'x'. packages/tensorflow/python/framework/op_def_library.pyc in _apply_op_helper(self, op_type_name, name, **keywords) 544 "%s type %s of argument '%s'." % 545 (prefix, dtypes.as_dtype(attrs[input_arg.type_attr]).name, --&gt; 546 inferred_from[input_arg.type_attr])) 547 548 types = [values.dtype] TypeError: Input 'y' of 'Mul' Op has type float32 that does not match type float64 of argument 'x'.
answer count: 2
has title: TypeError: Input 'y' of 'Mul' Op has type float32 that does not match type float64 of argument 'x'
has comment: http://stackoverflow.com/comment/90585857

http://stackoverflow.com/q/51800030
has comment: http://stackoverflow.com/comment/90556630
score: -1
has answer: http://stackoverflow.com/a/51800211
has comment: http://stackoverflow.com/comment/90556436
tagged with: pandas
answer count: 1
downvote count: 1
favorite count: 0
has body: I had just started with notebooks and Python. When I print my list will I just the list and then number how often they occur. I would like to if I could get hour as a header above 12 and 8 and count as a header above 7 and 3. x=df['hour'].value_counts() print(x[0:2]) 12 7 8 3 How I want it: Hour . count 12 7 8 3 For the moment am I getting this below my results Name: hour, dtype: int64 /Lisa
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90556479
tagged with: python
has title: Create list headings in Panda
upvote count: 0
has comment: http://stackoverflow.com/comment/90556527
type: Question

http://stackoverflow.com/comment/90711973
type: AnswerComment
has text: Ok it comes from the shape of y_pred, which is slightly different from y_test, so that the comparison is performed element-wise. I update my answer accordingly.
type: Comment
comment on: http://stackoverflow.com/a/51879001
score: 1

http://stackoverflow.com/comment/91283554
has text: but I think your problem started at step 6, you should try `python django-admin` rather than `django-admin.py`
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51909725
type: QuestionComment

http://stackoverflow.com/a/51936619
has body: IIUC, just use to_excel in groupby for acc, g in df.groupby('account_key'): g.to_excel(f'account_{acc}.xlsx') If your have an older version of python which does not support f-strings, use for acc, g in df.groupby('account_key'): g.to_excel('account_{}.xlsx'.format(acc)) To name the worksheet, just pass the name as second argument g.to_excel(f'account_{acc}.xlsx', 'myNote')
has comment: http://stackoverflow.com/comment/90824029
type: Answer
accepted answer of: http://stackoverflow.com/q/51936575
answers question: http://stackoverflow.com/q/51936575
has comment: http://stackoverflow.com/comment/90823589
has comment: http://stackoverflow.com/comment/90823545
score: 4
upvote count: 4
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90828081
has comment: http://stackoverflow.com/comment/90823981

http://stackoverflow.com/q/51871937
linked to: http://stackoverflow.com/q/21555942
tagged with: redis
upvote count: 8
has answer: http://stackoverflow.com/a/75217844
tagged with: python
has answer: http://stackoverflow.com/a/51872019
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51876129
type: Question
possible better answer: http://stackoverflow.com/a/51876129
downvote count: 0
accepted answer: http://stackoverflow.com/a/51872019
answer count: 3
has comment: http://stackoverflow.com/comment/103738406
has body: I'd like to check the version of redis, it could be accomplished on command line In [181]: !redis-server --version Redis server v=4.0.10 sha=00000000:0 malloc=libc bits=64 build=ea14acb2d1b3b56f However, when it return the redis-py's version rather than redis version if In [184]: redis.__version__ Out[184]: '2.10.6 It could be achieved in a wieldy way In [186]: subprocess.run("redis-server --version", shell=True) Redis server v=4.0.10 sha=00000000:0 malloc=libc bits=64 build=ea14acb2d1b3b56f Out[186]: CompletedProcess(args='redis-server --version', returncode=0) How could I check the version of redis directly with pure code?
favorite count: 0
score: 8
has title: Check the version of Redis

http://stackoverflow.com/comment/90607381
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51824211
has text: Your code isn't closing only the current tab... it's closing all the tabs *except* the current tab. Please clarify what you are trying to do.

http://stackoverflow.com/q/51930542
favorite count: 0
has answer: http://stackoverflow.com/a/51930746
has comment: http://stackoverflow.com/comment/90810924
has comment: http://stackoverflow.com/comment/90810926
tagged with: python
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/90811119
has comment: http://stackoverflow.com/comment/90811208
has answer: http://stackoverflow.com/a/51930700
type: Question
possible better answer: http://stackoverflow.com/a/51930746
tagged with: combinations
has body: I have a set of tuples in a form of a list: [(1, 2), (3, 4), (5, 6), (7, 8)] Not necessary in such an order, it can be as well: [(1, 4), (2, 6), (3, 5), (7, 8)] These lists have two properties: if sorted and flattened they become a range from 1 to n (like [1, 2, 3,..n]) n is even n is larger than 2 all values are unique (no value is repeated). so, let's say I have: a = [(1, 2), (3, 4), (5, 6), (7, 8)] What is the way to create list of tuples b out of a such that no original tuples would be in it? so for example b = [(1, 8), (3, 7), (2, 6), (4, 5)] is ok but b = [(1, 2), (3, 7), (5, 6), (4, 8)] is not ok, because it contains (1, 2) and (5, 6) presented in a PS: (The title is messy, but I don't know how to explain better (will be happy to edit).
has title: list of lists with pairs that do not have a match in the original set
tagged with: list-comprehension
answer count: 3
has answer: http://stackoverflow.com/a/51930672
accepted answer: http://stackoverflow.com/a/51930672
upvote count: 1
downvote count: 0

psychopy
tags question: http://stackoverflow.com/q/51911675
type: Tag
tags question: http://stackoverflow.com/q/51809979
tags question: http://stackoverflow.com/q/51800926
tags question: http://stackoverflow.com/q/51944390
tag name: psychopy

http://stackoverflow.com/a/60914840
type: Answer
upvote count: 6
score: 6
answers question: http://stackoverflow.com/q/51811024
has comment: http://stackoverflow.com/comment/129028960
has body: Until the issue in https://github.com/python/mypy/issues/708 is fixed, one clean way to work around this is to make the callable attribute optional, and wrap it in a method with an assert: from typing import Any, Callable, Optional class SomeClass: _reference: Optional[Callable[[], Any]] def reference(self) -&gt; Any: assert self._reference is not None return self._reference() def __init__(self, reference): self.reference = reference c = SomeClass(lambda: 42) print(c.reference()) $ mypy test.py Success: no issues found in 1 source file
downvote count: 0
has comment: http://stackoverflow.com/comment/109729696

http://stackoverflow.com/comment/90695980
score: 0
type: Comment
type: QuestionComment
has text: @Julio, I agree with you. So, maybe some tockenizers or another nlp tools exist that can help me with my problem.
comment on: http://stackoverflow.com/q/51871693

http://stackoverflow.com/q/51900292
type: UnansweredQuestion
downvote count: 2
tagged with: python
has answer: http://stackoverflow.com/a/51900449
type: Question
has answer: http://stackoverflow.com/a/51900379
score: -2
has body: I am working on a project, I am trying to complete a tutorial where you save monthly until you reach a certain amount for a down payment These are inputs needed: annual salary(120,000), portion of salary to be saved(0.10), house cost(1,000,000) annual_salary = float(input('Enter your annual salary: ')) portion_saved = float(input('Enter the percent of your salary to save, as a decimal: ')) total_cost = float(input('Enter the cost of your dream home: ')) You have nothing saved up to begin with, months is used as a counter current_savings = 0.0 months = 0 down_payment = 0.25*total_cost Heres my while loop, I end up stopping the program myself and current_savings only updates once while months runs into the billions, why is this? while current_savings &lt; down_payment: current_savings = (current_savings*0.04)/12 + (annual_salary/12)*portion_saved months += 1 print('Number of months ', months) current_savings*0.04 refers to a return on investment of 4% per annum, when I stop the program current_savings = 1003.3 which means its only calculated once.
answer count: 3
tagged with: while-loop
upvote count: 0
has comment: http://stackoverflow.com/comment/90751672
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51900475
has title: while loop isn't updating the current savings variable

http://stackoverflow.com/q/51857477
favorite count: 0
tagged with: extjs
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/90667605
has comment: http://stackoverflow.com/comment/90668920
upvote count: 2
has title: Problems installing extdirect on the django project
tagged with: django
downvote count: 1
type: UnansweredQuestion
has body: I installed the django project in python 3.6 and I want to use extjs 6 for server and client interaction. As a basis, I took an article written by the user "k0smita" - https://www.sencha.com/forum/showthread.php?130149-Samples-Examples-for-ExtJS-4-0-and-Django. After creating and configuring the django project, I added the extdirect.django package using pycharm. In the settings.py file, INSTALLED_APPS added 'extdirect.django', and when the application is launched, an error is produced first module is not installed 'decorators'. To fix this, I installed the decorators package and now I get an error: ImportError: can not import name 'remoting'. In the requirements.txt file I have the following: decorators == 0.1.1 Django == 1.11.15 extdirect == 0.4 extdirect.django == 0.3 pytz == 2018.5 Why can an error "ImportError: can not import name 'remoting'" occur while the decorators package is installed on my project?
answer count: 0
score: 1

http://stackoverflow.com/comment/90726443
comment on: http://stackoverflow.com/q/51886156
score: 0
type: Comment
type: QuestionComment
has text: @BinyaminEven Chat?

http://stackoverflow.com/q/51918128
accepted answer: http://stackoverflow.com/a/51918213
score: 0
type: Question
tagged with: algorithm
has title: Search data in a list and export them into a .csv file
has body: I already finished another part of the code and get two sets of numbers: set1(postcode and rents in Western Australia): [['6004', '240'], ['6004', '350'], ['6004', '350'], ['6004', '315'], ['6004', '490'], ['6004', '280'], ['6004', '275'], ['6004', '240'], ['6050', '260'], ['6050', '330'], ['6050', '220'], ['6050', '250'], ['6000', '390'], ['6000', '220'], ['6000', '400'], ['6000', '250'], ['6000', '320'], ['6000', '390'], ['6000', '220'], ['6000', '400'], ['6004', '395'], ['6004', '230'], ['6004', '350'], ['6004', '300'], ['6004', '300'], ['6004', '340'], ['6000', '420'], ['6000', '190'], ['6000', '300'], ['6000', '380'], ['6000', '270'], ['6000', '380'], ['6000', '350'], ['6000', '380'], ['6004', '360'], ['6004', '450'], ['6004', '200'], ['6004', '250'], ['6004', '350']] set2(postcodes in set1): ['6004', '6050', '6000'] What I need to do now is to put them in a .csv file like this: Postcodes are in the frist row (like an index). The rest of the rows are rents in these postcode(example: in postcode 6004, there are 3 houses, the rents are 240,350,350) What kind of method should I use to get what I want? I tried dictionary but it says just 2 elements are required.
has answer: http://stackoverflow.com/a/51918517
has comment: http://stackoverflow.com/comment/90786148
answer count: 2
linked to: http://stackoverflow.com/q/3199171
has answer: http://stackoverflow.com/a/51918213
possible better answer: http://stackoverflow.com/a/51918517
tagged with: python
has comment: http://stackoverflow.com/comment/90786080
type: AnsweredQuestion

http://stackoverflow.com/q/51892369
score: 5
has title: Python app build with flatpak can not find package
downvote count: 0
has body: I'm trying to create a flatpak for our tool: https://github.com/IENT/RDPlot My flatpak config and other files are here: https://github.com/IENT/flathub/tree/de.ient.RDPlot When I try to call start the tool I get flatpak-builder --run buildDir de.ient.RDPlot.yaml rdplot --filesystem=host Traceback (most recent call last): File "/app/bin/rdplot", line 5, in &lt;module&gt; from pkg_resources import load_entry_point 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/lib/python3.5/site-packages/setuptools-22.0.5-py3.5.egg/pkg_resources/__init__.py", line 2927, in &lt;module&gt; File "/usr/lib/python3.5/site-packages/setuptools-22.0.5-py3.5.egg/pkg_resources/__init__.py", line 2913, in _call_aside File "/usr/lib/python3.5/site-packages/setuptools-22.0.5-py3.5.egg/pkg_resources/__init__.py", line 2940, in _initialize_master_working_set File "/usr/lib/python3.5/site-packages/setuptools-22.0.5-py3.5.egg/pkg_resources/__init__.py", line 635, in _build_master File "/usr/lib/python3.5/site-packages/setuptools-22.0.5-py3.5.egg/pkg_resources/__init__.py", line 943, in require File "/usr/lib/python3.5/site-packages/setuptools-22.0.5-py3.5.egg/pkg_resources/__init__.py", line 829, in resolve pkg_resources.DistributionNotFound: The 'sip' distribution was not found and is required by rdplot I tried to set PYTHONPATH both locally before calling the command and in the flatpak config, but this did not work. I verified that the package was installed correctly: cd /var/lib/flatpak/app/de.ient.RDPlot/current/active/files/lib/python3.5/site-packages ipython In [1]: import sip In [2]: sip.__file__ Out[2]: '/var/lib/flatpak/app/de.ient.RDPlot/x86_64/master/028d157308e77fd7ea66c39d93bf661dc3ddebc570aae0bcad6f07ab92ae4257/files/lib…
tagged with: packaging
favorite count: 0
upvote count: 5
answer count: 0
type: UnansweredQuestion
tagged with: python
tagged with: flatpak
type: Question

http://stackoverflow.com/comment/90554701
comment on: http://stackoverflow.com/q/51798784
type: Comment
type: QuestionComment
has text: @PyMatFlow Yes. But is it a good idea to training my small dataset of 10 classes and 5 images per class on the Inception ResNetV2 from scratch (On all the layers) ? I could remove custom layers too. Will it make some difference ?
score: 0

http://stackoverflow.com/a/51946609
type: Answer
has comment: http://stackoverflow.com/comment/91157332
upvote count: 3
accepted answer of: http://stackoverflow.com/q/51944199
score: 3
answers question: http://stackoverflow.com/q/51944199
has body: You can't use scatter_update because that's for 1D data. You probably need to take a look at how gather_nd and scatter_nd works. But the following code works for your problem. import tensorflow as tf num_actions = 3 batch_size = 2 tf.reset_default_graph() output = tf.convert_to_tensor([[10, 20.2, 4.3],[5, 3, 8.9]]) # There's a bit of dark magic looking reshaping going here # Essentially to get tensor a in the correct shape of indices # gather_nd requires a_idx = tf.reshape(tf.range(batch_size),[-1,1]) a = tf.convert_to_tensor([[1],[2]]) a_reshaped = tf.reshape(tf.concat([a_idx,a],axis=1),[-1,1,2]) r = tf.convert_to_tensor([[30.0],[15.0]]) diff = tf.gather_nd(output, a_reshaped) loss = tf.scatter_nd(a_reshaped, r-diff, (batch_size, num_actions))
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/90748404
score: 0
type: AnswerComment
type: Comment
has text: I'm not quite sure I am following what you mean here. Are you asking how to execute the code on multiple sheets? Also, what do you mean with "select the date in whole workbook"?
comment on: http://stackoverflow.com/a/51886554

http://stackoverflow.com/comment/90657286
score: 0
comment on: http://stackoverflow.com/q/51832301
type: Comment
type: QuestionComment
has text: @dawg Thank you for the explanation. However, what happens to the elements in this case. Since new temp_list is created everytime, what happens to the elements from the earlier iteration: a, b = map(int, input().split()) list_of_lists = [] for i in range(b): temp_list = list(map(float, input().split())) print(temp_list, i) list_of_lists.append(temp_list)

http://stackoverflow.com/comment/90672387
has text: That was me by accident. But also not so sure if your answer makes it any clearer for him to be honest.
type: Comment
comment on: http://stackoverflow.com/a/51859790
score: 0
type: AnswerComment

http://stackoverflow.com/comment/129703687
type: Comment
type: QuestionComment
has text: Should this be tagged with Windows or not?
comment on: http://stackoverflow.com/q/51922364
score: 0

http://stackoverflow.com/q/51870312
score: 1
has comment: http://stackoverflow.com/comment/90771905
upvote count: 1
has comment: http://stackoverflow.com/comment/90820750
has title: Python Clear Output in Atom (Mac)?
type: Question
has body: I know how to clear output when running the file in terminal, but as an added convenience is there a way to clear output when running the file from Atom's Script package? For clarification, I am on macOS High Sierra 10.13.6, running Python 3.5. And in case you came to this link by searching how to clear output in python, do it by print("\033[H\033[J") This works in terminal, but not atom.
has comment: http://stackoverflow.com/comment/90820906
tagged with: atom-editor
downvote count: 0
has comment: http://stackoverflow.com/comment/90771831
favorite count: 0
has comment: http://stackoverflow.com/comment/90772048
has comment: http://stackoverflow.com/comment/90822467
type: UnansweredQuestion
tagged with: python
answer count: 0

http://stackoverflow.com/q/51884553
has comment: http://stackoverflow.com/comment/90723113
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90720924
score: 1
type: Question
has title: AES ECB Encrypting in Python
has comment: http://stackoverflow.com/comment/90721290
has comment: http://stackoverflow.com/comment/90721109
has answer: http://stackoverflow.com/a/51885174
accepted answer: http://stackoverflow.com/a/51885174
upvote count: 3
tagged with: python-3.7
answer count: 1
tagged with: python
has body: My main goal is to rewrite this javascript into python password = "AAAABBBBCCCC"; passwordMd5 = CryptoJS.MD5(password); //e1b6b2b3211076a71632bbf2ad0edc05 passwordKey = CryptoJS.SHA256(CryptoJS.SHA256(passwordMd5 + data.v1) + data.v2); //4a5148da63f40e1bcd3e3225f9b79412b7aee745f4b7f831b9d0893d0d6d666f encryptedPassword = CryptoJS.AES.encrypt(passwordMd5, passwordKey, {mode: CryptoJS.mode.ECB,padding: CryptoJS.pad.NoPadding}); //U2FsdGVkX198V2FiYyEGAKISlXBcmad7V0scbooxQ8QMSmp84vtyAfHytynX2mrw encryptedPassword = CryptoJS.enc.Base64.parse(encryptedPassword.toString()).toString(CryptoJS.enc.Hex); //53616c7465645f5f7c57616263210600a21295705c99a77b574b1c6e8a3143c40c4a6a7ce2fb7201f1f2b729d7da6af0 Here is my code in python passwordMd5 = hashlib.md5(password.encode("utf-8")).hexdigest() # e1b6b2b3211076a71632bbf2ad0edc05 passwordKey = hashlib.sha256((hashlib.sha256((passwordMd5 + prelogin["v1"]).encode("utf-8")).hexdigest() + prelogin["v2"]).encode("utf-8")).hexdigest() # 4a5148da63f40e1bcd3e3225f9b79412b7aee745f4b7f831b9d0893d0d6d666f cipher = AESCipher(passwordKey) encryptedPassword = cipher.encrypt(passwordMd5) print(encryptedPassword) AESCipher.py (original: here), import base64 import hashlib from Crypto import Random from Crypto.Cipher import AES BS = 32 def pad(s): s + (BS - len(s) % BS) * chr(BS - len(s) % BS).encode() def unpad(s): s[:-ord(s[len(s)-1:])] class AESCipher(object): def __init__(self, key): self.key = key def encrypt(self, message): message = message.encode() raw = pad(message) cipher = AES.new(self.key, AES.MODE_ECB) enc = cipher.encrypt(raw) return base64.b64encode(enc).decode('utf-8') def decrypt(self, enc): enc = base64.b64decode(enc) cipher = AES.new(self.key, AES.MODE_ECB) dec = cipher.decrypt(enc) return unpad(dec).decode('utf-8') When i try to run it, it give me error: Traceback (most recent call last): File "main.py", line 97, in &lt;module&gt; encryptedPassword = cipher.encrypt(passwordMd5) File "AESCipher.py", line 31, in encrypt cipher = AE…
favorite count: 0
tagged with: aes
downvote count: 2

http://stackoverflow.com/comment/90888125
score: 0
type: Comment
type: QuestionComment
has text: Well done peter! You can add the answer to your question and mark it as the answer in a couple of days. So your question can be closed.
comment on: http://stackoverflow.com/q/51950002

glfw
tags question: http://stackoverflow.com/q/51918633
type: Tag
tag name: glfw

http://stackoverflow.com/comment/90768834
comment on: http://stackoverflow.com/a/51905242
score: 0
type: AnswerComment
has text: Thanks Sruthi! It's a really good answer. The only caveat is that the sub_range list needs to be inside the range. But this gave me a good starting point.
type: Comment

http://stackoverflow.com/comment/90677775
comment on: http://stackoverflow.com/a/51854753
type: Comment
has text: Thank you, in the future I will ensure to save the date to the csv file as well
score: 0
type: AnswerComment

http://stackoverflow.com/comment/90857455
type: AnswerComment
type: Comment
has text: Okay this will solve your problem then https://stackoverflow.com/a/42933728
comment on: http://stackoverflow.com/a/51942345
score: 0

http://stackoverflow.com/q/51887978
tagged with: python
has comment: http://stackoverflow.com/comment/90727223
linked to: http://stackoverflow.com/q/37152031
has answer: http://stackoverflow.com/a/60531118
has comment: http://stackoverflow.com/comment/90727197
score: 0
type: Question
has comment: http://stackoverflow.com/comment/90727332
has body: I have some code that looks like this number_of_pairs = int(len(path_list) / 2) pairs_of_images = [np.zeros( (number_of_pairs, self.image_height, self.image_height, 1)) for i in range(2)] labels = np.zeros((number_of_pairs, 1)) size = 105,105 for pair in range(number_of_pairs): image = Image.open(path_list[pair * 2]) image = image.resize((105,105)) image = np.asarray(image).astype(np.float64) print("before resize is{}".format(image)) pairs_of_images[0][pair, :, :, 0] = image However, I'm getting an error where pairs_of_images[1][pair, :, :, 0] = image ValueError: could not broadcast input array from shape (105,105,4) into shape (105,105) Is there a way to get rid of the 3rd dimension of the array?
tagged with: numpy
answer count: 1
has comment: http://stackoverflow.com/comment/90737979
has title: Resize 3D array to 2D
type: UnansweredQuestion

http://stackoverflow.com/a/51872305
type: Answer
score: 1
upvote count: 1
has body: I have figured out the issue in there. It turns out that we do use the same parameter and above code will give an error in second iteration saying that bidirectional kernel already exists. To fix this, we need to set, reuse=AUTO_REUSE while defining scope variable. Therefore, the line with tf.variable_scope('encoder_{}'.format(layer)): will become with tf.variable_scope('encoder_{}'.format(layer),reuse=AUTO_REUSE): Now we are using the same layers for each batch.
accepted answer of: http://stackoverflow.com/q/51872304
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51872304

http://stackoverflow.com/q/51886140
upvote count: 2
has title: Blender (Python): Checking if vertex is visible from camera in script (with occlusion)
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90728850
tagged with: python
tagged with: occlusion
score: 2
answer count: 0
has body: How can I check if a vertex in a model can be seen by a camera or if it's hidden behind another object? I aim to use that information to find the coordinates and size of a bounding box that would be drawn around an object viewed from a camera, then save that bounding box's info in a text file (which is already done and working). I do not need nor want the vertexes to be selected, I simply want their position and if they can be seen by the camera. That way, I can check for the highest and lowest vertexes as well as the most left and most right vertexes and use these coordinates to create my bounding box. Thanks!
type: Question
tagged with: blender
has comment: http://stackoverflow.com/comment/90747459
downvote count: 0
tagged with: vertex
favorite count: 0

http://stackoverflow.com/comment/90738442
score: 0
type: QuestionComment
has text: Possible duplicate of [numpy convert categorical string arrays to an integer array](https://stackoverflow.com/questions/3172509/numpy-convert-categorical-string-arrays-to-an-integer-array)
type: Comment
comment on: http://stackoverflow.com/q/51893702

http://stackoverflow.com/q/51824174
has body: I have a dataframe consisting of 130,000 points which has a head like this: Latitude Longitude 0 36.577570 36.578930 1 36.577634 36.578939 2 36.577574 36.578917 3 36.577639 36.578926 4 36.576966 36.583783 I tried to create a heat map of these points using seaborn and matplotlib however I failed and I don't know what to do at this point. I am not required to plot these points on a real world map, I just need to create a regular heat map. If you guys could help that would be great, thanks a lot.
type: Question
has answer: http://stackoverflow.com/a/65139858
has comment: http://stackoverflow.com/comment/90602822
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/90602429
answer count: 1
tagged with: seaborn
type: UnansweredQuestion
tagged with: python
tagged with: heatmap
has title: Creating a heatmap of coordinates using plotly or seaborn
tagged with: matplotlib

http://stackoverflow.com/q/51870321
accepted answer: http://stackoverflow.com/a/51870559
has title: Why is the string index out of range when calling this lambda command?
has comment: http://stackoverflow.com/comment/90692800
has comment: http://stackoverflow.com/comment/90692191
has comment: http://stackoverflow.com/comment/90701986
has body: I made this function as part of a tkinter calculator in order to generate all of the calculator buttons through a single function as opposed to creating them one by one. I'm getting the following error: line 49, in &lt;lambda&gt; button_list[i].configure(command = lambda: self.num_press(button_characters[i])) IndexError: string index out of range The error comes up for the index called on the configure line by lambda, although the index used (button_characters[i]) works fine with no problems earlier in the function when setting the button text. The num_press function at the moment does the following. def num_press(self, num): print(num) Could somebody please help me and inform me why the command isn't working and why it says the index is out of range?? I've had a look around online and haven't found anything.
tagged with: python
has comment: http://stackoverflow.com/comment/90692173
tagged with: indexing
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90692441
has answer: http://stackoverflow.com/a/51870566
has comment: http://stackoverflow.com/comment/90692649
has comment: http://stackoverflow.com/comment/90724877
has comment: http://stackoverflow.com/comment/90692059
has comment: http://stackoverflow.com/comment/90692082
upvote count: 1
has comment: http://stackoverflow.com/comment/90692300
type: Question
possible better answer: http://stackoverflow.com/a/51870566
has answer: http://stackoverflow.com/a/51870559
has comment: http://stackoverflow.com/comment/90692505
answer count: 2
has comment: http://stackoverflow.com/comment/90695830
downvote count: 0
has comment: http://stackoverflow.com/comment/90692482
score: 1
favorite count: 0

http://stackoverflow.com/q/51956101
has comment: http://stackoverflow.com/comment/90930650
type: AnsweredQuestion
tagged with: swig
tagged with: http://stackoverflow.com/tag/c
has comment: http://stackoverflow.com/comment/90918046
type: Question
tagged with: numpy
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/52030988
score: 1
tagged with: pointers
favorite count: 0
has comment: http://stackoverflow.com/comment/90874999
has comment: http://stackoverflow.com/comment/90947778
has comment: http://stackoverflow.com/comment/134406835
has body: I need to pass a pointer from Python to a C function. I'm currently trying with SWIG but I'm ready to switch to anything that will solve my issue :) To simplify my problem, I wrote this empty C function in SWIG: extern void myvoidp(void *p); I've setup my .i and .c files, all compile fine and work in Python. I'd like to pass a Numpy array. I can get the memory address of the Numpy data like this &gt;&gt;&gt; anp = array([1,2,3]) array([1, 2, 3]) &gt;&gt;&gt; anp.ctypes.data 40546992 I can cast it to a void * like this with ctypes and numpy: &gt;&gt;&gt; anp.ctypes.data_as(ctypes.c_void_p) c_void_p(40546992) I've tried endless variants. Whatever I do, when I invoke my C function I get this error. &gt;&gt;&gt; myswig.myvoidp(anp.ctypes.data_as(ctypes.c_void_p)) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: in method 'myvoidp', argument 1 of type 'void *' I can't figure out how to write a Python / numpy statement that allows me to (simply) pass a pointer to my C function. :-(
tagged with: python
has title: Python passing void pointer as parameter to C function (SWIG, Numpy)
accepted answer: http://stackoverflow.com/a/52030988
upvote count: 1

http://stackoverflow.com/q/51852298
score: 2
type: AnsweredQuestion
tagged with: posix
has body: There is a patch to add support for the POSIX openat functions (and other *at functions like fstatat) to the python standard library that is marked as closed with resolution fixed, but the os, posix and platform modules do not currently include any of these methods. These methods are the standard way of solving problems like this in C and other languages efficiently and without race conditions. Are these included in the standard library currently somewhere? And if not, are there plans to include this in the future.
has title: Support for POSIX openat functions in python
upvote count: 2
type: Question
answer count: 1
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/51852542
tagged with: python-3.x
linked to: http://stackoverflow.com/q/51851986
tagged with: python
has answer: http://stackoverflow.com/a/51852542

http://stackoverflow.com/a/51907192
type: Answer
answers question: http://stackoverflow.com/q/51906971
has body: For filtering this list of words there are two possibilities: list_of_words = ['word_without_colon', 'word:with:colon'] The filter-function: words_with_colons = list(filter(lambda word: ':' in word, list_of_words)) List comprehensions: words_with_colons = [word for word in list_of_words if ':' in word] Guido van Rossum, the creator of Python, recommends using list comprehensions and even planned to remove the filter-function completely in Python 3: I think dropping filter() and map() is pretty uncontroversial; filter(P, S) is almost always written clearer as [x for x in S if P(x)], and this has the huge advantage that the most common usages involve predicates that are comparisons, e.g. x==42, and defining a lambda for that just requires much more effort for the reader (plus the lambda is slower than the list comprehension). Even more so for map(F, S) which becomes [F(x) for x in S].
score: 0

http://stackoverflow.com/q/51861845
has title: kubectl terminal command not working from crontab , how to fix?
downvote count: 1
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/90710040
has answer: http://stackoverflow.com/a/51869999
has comment: http://stackoverflow.com/comment/90676050
has body: I have below small python script import os os.system('kubectl get pods --context students-cmn') when i run this command manually from terminal it is working , no issue , so i configured it to run as a cron job , but when cron job triggered getting below error sh: kubectl: command not found why , when the cronjob triggered , kubectl not working ? can anyone please help
tagged with: cron
tagged with: kubectl
tagged with: kubernetes
favorite count: 0
has comment: http://stackoverflow.com/comment/90676042
type: UnansweredQuestion
tagged with: python
upvote count: 4
has answer: http://stackoverflow.com/a/60560644
has comment: http://stackoverflow.com/comment/90676092
has comment: http://stackoverflow.com/comment/90675955
score: 3

http://stackoverflow.com/a/60886176
score: 2
downvote count: 0
has body: I faced the same issue while integrating Dialogflow with external client. The root cause for my case was that even though I created the service account for my external client, I forgot to add the service account and give "Dialogflow API Admin' Role. How I resolve: In GCP project, go to IAM > click the top "+ADD" button and search for the service account that you want to grant permission access, choose role type "Dialogflow API Admin" (or edit the role to give Dialogflow API Admin if you have added the service account previously as Client role)
upvote count: 2
answers question: http://stackoverflow.com/q/51855169
type: Answer

http://stackoverflow.com/comment/90839298
has text: I have updated my original thread, there I have put the format of my dictionary, this solution will work if the value is a single item, but in my case I have a list of values, and I want to compare this list for uniqueness
type: AnswerComment
comment on: http://stackoverflow.com/a/51943957
score: 0
type: Comment

http://stackoverflow.com/comment/116920959
type: AnswerComment
has text: I also tried this, but found that PyTorch doesn't provide this module: `pip3 show torch -f | grep setup_helper` doesn't show any such files.
type: Comment
score: 1
comment on: http://stackoverflow.com/a/51882594

http://stackoverflow.com/comment/90643233
type: Comment
type: AnswerComment
has text: Yes I use windows.
score: 0
comment on: http://stackoverflow.com/a/51844792

http://stackoverflow.com/a/51853451
upvote count: 0
answers question: http://stackoverflow.com/q/51853349
score: -1
has comment: http://stackoverflow.com/comment/90661567
has comment: http://stackoverflow.com/comment/90695707
has body: Pandas -> pyspark spark = SparkSession.builder.master("local[*]").getOrCreate() sparkDf = spark.createDataFrame(pandas_df)` Pyspark -> pandas pdf = sparkDf.toPandas()
downvote count: 1
type: Answer

http://stackoverflow.com/a/51939753
has comment: http://stackoverflow.com/comment/90829763
has comment: http://stackoverflow.com/comment/90939868
has comment: http://stackoverflow.com/comment/90829991
has comment: http://stackoverflow.com/comment/90830246
has body: Unfortunately for you the reason you can't find anything changing is that on windows "explorer.exe" which is responsible for pretty much all file operations (file explorer, desktop management, etc...) is always open, and runs from a single instance. I'm not aware of any way you can do this from python but I do have a solution that you can incorporate, even if it's not ideal. Using PIL, found here http://www.pythonware.com/products/pil/, you can grab an image of the screen and check pixel colors at specific points, which should allow what you're currently after. If you need to grab pixel colors from the screen the best tool I can think of for quick mockups would be autohotkeys window spy. Hopefully this helps, I know how annoying automation can be sometimes when you have to do hacks like this so let me know if you have any other questions. Edit: I was messing around with the idea that when file explorer is open the amount of handles open by explorer will increase by a decent margin, and if you aren't doing anything except running automated scripts the behavior is fairly predictable but would require a little experimentation on your end. This is what I have: import psutil for proc in psutil.process_iter(): if 'explorer' in proc.name(): print(proc.name() + " handles:" + str(proc.num_handles())) When I run this with my file explorer closed vs file explorer open I get a random increase of about 100 handles or more, so you might be able to store the previous amount and poll the current amount assuming you do not open anything else when the handles increase by X amount you know that file explorer has been opened and can begin typing, then after it drops near X amount you know its closed and you resave the new handle count and wait for your X increase again. While this is not a perfect solution you should be able to make it work quite well for what you want. Edit2: This works for me, you may need to change the usualIncrease amount since it might be a larger or smaller amoun…
score: 0
has comment: http://stackoverflow.com/comment/90830097
has comment: http://stackoverflow.com/comment/90830113
has comment: http://stackoverflow.com/comment/90830066
answers question: http://stackoverflow.com/q/51939557
has comment: http://stackoverflow.com/comment/90829913
type: Answer
has comment: http://stackoverflow.com/comment/90829713
has comment: http://stackoverflow.com/comment/90829961

memory-management
tags question: http://stackoverflow.com/q/51799764
tags question: http://stackoverflow.com/q/51888774
tags question: http://stackoverflow.com/q/51946818
tags question: http://stackoverflow.com/q/51881958
type: Tag
tag name: memory-management

http://stackoverflow.com/q/51867959
has body: The idea is simple, you open a text file, you read it, you find how many times did the letters repeated itself and then estimate the percentage of each letter in text. fileName = input("Enter file Name: ") with open(fileName) as f: text = f.read() print(text) def count_char(text, char): count=0 for c in text: if c == char: count+=1 return count for char in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" and "abcdefghijklmnopqrstuvwxyz": percentage = 100 * count_char(text, char) / len(text) print("\n letter: {0} is taking {1}% of the text and that is {2}".format(char, round(percentage,2), count_char(text, char))) I did manage to do this but I can't put these values into dataframe to look more user friendly. Also, I want to make an if-else statement if the user entered a file that does not exist ("Error 404 File Not Found!") message.
has answer: http://stackoverflow.com/a/51867991
score: 1
upvote count: 1
type: Question
tagged with: dataframe
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
has title: Putting three acquired values from for loops into DataFrame / Python
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/51937378
answers question: http://stackoverflow.com/q/51936705
score: 0
type: Answer
has body: I'm not sure if this is what you are looking for but here is how I would do it. First get the city from the user: city = input("input City: ").lower() Then I would create some data structure, say dictionary, that holds all the zones and their cities: zones = {'zone1': ['boston', 'new york'], 'zone2': ['san fransisco', 'los angeles']} Then you can have a function that takes in a city and returns a zone def get_zone(city): for zone in zones.keys(): if city in zones[zone]: return zone return "Error city not found" Of course you would have to do something to normalize user input. Then you could create a command string and execute the command def execute_command(zone, weight, country): cmd = "SELECT {zone} FROM baltikum WHERE country={country} AND weight={weight}".format(zone = zone, country = country, weight = weight) data = c.execute(cmd) return data Then you only get data from selected zone. Hope this helps!
accepted answer of: http://stackoverflow.com/q/51936705
type: AcceptedAnswer

http://stackoverflow.com/comment/90605019
score: 1
has text: Is 'Labels' the name of the column? It doesn't seem like it's finding the column. Check your headers.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51825360

http://stackoverflow.com/comment/90580274
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51812634
has text: In my javascript console it saying my main.js (which is the name of my file) is not defined.

http://stackoverflow.com/comment/90704888
score: 0
type: Comment
type: QuestionComment
has text: @ Alla Tarighati. I got this data from my simulation tests. In which, I have applied three different conditions. It looks like that the third peak (middle one) is neither not clear nor satisfying the standard local maximum definition. I want the python to identify it. Assume, there is no maximum. But, presence of a small notch which I circled in Fig. 1 indicates the presence of peak.
comment on: http://stackoverflow.com/q/51876184

http://stackoverflow.com/comment/90619301
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51832546
has text: it dose hide the username part but this code isnt working if form.is_valid(): instance=form.save(commit=False) instance.username=request.user instance.save()

http://stackoverflow.com/a/51914517
type: Answer
accepted answer of: http://stackoverflow.com/q/51914481
upvote count: 3
answers question: http://stackoverflow.com/q/51914481
score: 3
has body: replace (by itself) isn't a good fit here, because you want to perform partial string replacement. You want regex based replacement. One simple solution, when you have a manageable number of stop words, is using str.replace. p = re.compile("({})".format('|'.join(map(re.escape, cached_stop_words)))) df['Text'] = df['Text'].str.lower().str.replace(p, '') df ID Text 0 1 eat launch 1 2 outside have fun If performance is important, use a list comprehension. cached_stop_words = set(cached_stop_words) df['Text'] = [' '.join([w for w in x.lower().split() if w not in cached_stop_words]) for x in df['Text'].tolist()] df ID Text 0 1 eat launch 1 2 outside have fun
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90779022

http://stackoverflow.com/a/51906644
type: AcceptedAnswer
type: Answer
score: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51906514
answers question: http://stackoverflow.com/q/51906514
upvote count: 2
has body: You need to $unwind the array_field and then again $group to rollback db.collection.aggregate([ { "$unwind": "$array_field" }, { "$sort": { "array_field": 1 }}, { "$group": { "_id": "$_id", "array_field": { "$push": "$array_field" } }} ])

http://stackoverflow.com/comment/90596350
has text: You add the workers to the fences group when you instantiate them: `Worker(IMG_WORKER_RUNNING, IMG_WORKER_IDLE, IMG_WORKER_ACCIDENT, pos, all_sprites, workers, fences)`. The last three arguments are passed as the `groups` argument. You need to remove the `fences` argument.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51813677

http://stackoverflow.com/comment/90787369
comment on: http://stackoverflow.com/q/51918395
has text: There are lots... http://www.steves-internet-guide.com/mosquitto_pub-sub-clients/ or this https://spin.atomicobject.com/2014/03/19/mqtt-protocol-ethernet/
score: 0
type: QuestionComment
type: Comment

python-3.6
tags question: http://stackoverflow.com/q/51850919
tags question: http://stackoverflow.com/q/51872584
tags question: http://stackoverflow.com/q/51856195
tags question: http://stackoverflow.com/q/51868433
tags question: http://stackoverflow.com/q/51806127
tags question: http://stackoverflow.com/q/51859032
tags question: http://stackoverflow.com/q/51860186
tags question: http://stackoverflow.com/q/51911554
type: Tag
tags question: http://stackoverflow.com/q/51941343
tags question: http://stackoverflow.com/q/51800772
tags question: http://stackoverflow.com/q/51912598
tags question: http://stackoverflow.com/q/51955195
tags question: http://stackoverflow.com/q/51919641
tags question: http://stackoverflow.com/q/51911416
tags question: http://stackoverflow.com/q/51844220
tags question: http://stackoverflow.com/q/51901751
tags question: http://stackoverflow.com/q/51933481
tags question: http://stackoverflow.com/q/51851570
tags question: http://stackoverflow.com/q/51804857
tags question: http://stackoverflow.com/q/51929474
tags question: http://stackoverflow.com/q/51951256
tags question: http://stackoverflow.com/q/51861442
tags question: http://stackoverflow.com/q/51810479
tags question: http://stackoverflow.com/q/51937252
tags question: http://stackoverflow.com/q/51835152
tags question: http://stackoverflow.com/q/51845099
tags question: http://stackoverflow.com/q/51903640
tag name: python-3.6
tags question: http://stackoverflow.com/q/51812449
tags question: http://stackoverflow.com/q/51804560
tags question: http://stackoverflow.com/q/51903732
tags question: http://stackoverflow.com/q/51886499
tags question: http://stackoverflow.com/q/51941830

http://stackoverflow.com/comment/90622379
has text: the edge function implementation is cited in your question, it starts with "function [eout,thresh,gv_45,gh_135] = edge(varargin)" , no? look at the varagin parsing : [a,method,thresh,sigma,thinning,H,kx,ky] = parse_inputs(args{:}); in your case **a**=mask, ** method**='canny'.... ?
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51810905

http://stackoverflow.com/q/51800651
has answer: http://stackoverflow.com/a/51800888
has answer: http://stackoverflow.com/a/51802659
tagged with: dictionary
has title: Constructing a ndarray of values from another ndarray containing dictionary keys
tagged with: numpy
tagged with: numpy-ndarray
score: 2
accepted answer: http://stackoverflow.com/a/51800888
downvote count: 0
has body: I have a ndarray containing the dictionary keys arranged in a specific order. I want to create another ndarray containing the values of the respective keys. The order have to be maintained. Obvious approach is to iterate over the array containing the keys element by element but the problem is there is no way to know the shape of the array beforehand. Is it possible to flatten the ndarray of keys and iterate over it to generate flat ndarray of values and finally unravel it without harming the order? mydict = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5, 'f':6} input_pattern = np.array([['a', 'f'], ['b', 'e'], ['c', 'd']]) expected_output = np.array([[1, 6], [2, 5], [3, 4]]) N. B. : In the above example pattern array is 2D, it may not be the case always. Also it may not contain all keys of the dictionary.
type: AnsweredQuestion
favorite count: 0
tagged with: python-3.x
type: Question
upvote count: 2
answer count: 2
possible better answer: http://stackoverflow.com/a/51802659
tagged with: python

http://stackoverflow.com/comment/90606020
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51824718
has text: What is the use case for this? Do you need to recover some data that is not available in the original format? Color maps are a terrible choice for encoding gray values.
score: 0

http://stackoverflow.com/a/51818805
type: Answer
answers question: http://stackoverflow.com/q/51816106
score: 3
upvote count: 3
has body: Sql coalesce should help. It will return the first non-null value among the list of values. from sqlalchemy import func q = session.query(Table1.column1, func.coalesce(Table2.column1, Table2.column2).label('content')) \ .outerjoin(Table2) \ .all()
accepted answer of: http://stackoverflow.com/q/51816106
type: AcceptedAnswer
downvote count: 0

tweepy
tags question: http://stackoverflow.com/q/51812960
tags question: http://stackoverflow.com/q/51909669
tags question: http://stackoverflow.com/q/51953688
type: Tag
tag name: tweepy

http://stackoverflow.com/comment/90662329
score: 0
type: Comment
type: QuestionComment
has text: @Andersson I deleted that exception. It seems that it is not root cause... Still get "chromedriver.exe" stop working.
comment on: http://stackoverflow.com/q/51854268

http://stackoverflow.com/q/51896486
answer count: 1
has answer: http://stackoverflow.com/a/51897240
favorite count: 0
has comment: http://stackoverflow.com/comment/90744656
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90744473
tagged with: python
has comment: http://stackoverflow.com/comment/90744931
downvote count: 1
type: AnsweredQuestion
tagged with: matplotlib
has body: I have tried something like the following: import matplotlib.pyplot as plt import numpy as np d= [1,2,3,4] f = [1,2,3,4,5] plt.ion() fig = plt.figure() fig.set_size_inches(10,5) ax1 = fig.add_subplot(111) line1, = ax1.plot(np.arange(len(d)),d,color='blue', label='first',marker=".") line2, = ax1.plot(np.arange(len(f)),f,color='red', label='second',marker=".") plt.show() for i in range(20): d.append(i) f.append(i) line1.set_xdata(np.arange(len(d))) line2.set_xdata(np.arange(len(f))) line1.set_ydata(d) line2.set_ydata(f) Got the error something like this: &gt;&gt;&gt; Exception in Tkinter callback Traceback (most recent call last):ges\numpy\lib\stride_tricks.py", line 249, in broadcast_arrays File "C:\Python35\lib\site-packages\matplotlib\backends\tkagg.py", line 26, in blit dataptr, colormode, bboxptr)kages\numpy\lib\stride_tricks.py", line 184, in _broadcast_shape _tkinter.TclError: this isn't a Tk application ValueError: shape mismatch: objects cannot be broadcast to a single shape During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Python35\lib\tkinter\__init__.py", line 1549, in __call__ return self.func(*args) File "C:\Python35\lib\tkinter\__init__.py", line 596, in callit func(*args) File "C:\Python35\lib\site-packages\matplotlib\backends\_backend_tk.py", line 310, in idle_draw self.draw() File "C:\Python35\lib\site-packages\matplotlib\backends\backend_tkagg.py", line 13, in draw tkagg.blit(self._tkphoto, self.renderer._renderer, colormode=2) File "C:\Python35\lib\site-packages\matplotlib\backends\tkagg.py", line 34, in blit dataptr, colormode, bboxptr) _tkinter.TclError: this isn't a Tk application Even it is not changing the x-axis values. I want to display both the values in same graph like the real time display. The arrays have different sizes. I am getting error after applying the solution from the question referred as the duplicate: ValueError: shape mismatch: objects cannot be broadcast to a sing…
has title: Matplotlib not changing the x scale for continuous displaying data
type: Question
upvote count: 0
accepted answer: http://stackoverflow.com/a/51897240
score: -1

http://stackoverflow.com/comment/90828910
type: QuestionComment
type: Comment
score: 1
comment on: http://stackoverflow.com/q/51938963
has text: Possible duplicate of [Why does my program's memory not release?](https://stackoverflow.com/questions/29529135/why-does-my-programs-memory-not-release)

http://stackoverflow.com/comment/90726446
type: QuestionComment
comment on: http://stackoverflow.com/q/51887533
has text: The built-ins aren't really a separate scope that anything looks at specifically; it's more of an automatic fallback when a name isn't found in the current global scope. The exact same bytecode is generated for a function accessing a built-in name as one accessing a global name.
score: 1
type: Comment

http://stackoverflow.com/comment/90559265
type: QuestionComment
comment on: http://stackoverflow.com/q/51800340
has text: @VPfB: but now that choice is making your life anything but simple and predictable. You end up having to duplicate your whole API between synchronous and asynchronous modes.
score: 0
type: Comment

http://stackoverflow.com/q/51919841
has title: Python OpenCV: draw outer contours inside a specific contour
tagged with: opencv
has body: I'm new to OpenCV and I'm trying to draw the outer contours inside a specific contour. Here's the image I'm using to clarify (already grayscaled, thresholded, etc.) What I want is to find all the contours of the circles (120 in total), inside the outer rectangle. contours = cv2.findContours(image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) So I basically used RETR_EXTERNAL for this but it only returns the outer rectangle. I tried using RETR_TREE but in that case it's returning me way more contours than there are circles, for some reason I don't understand. To clarify: I just want 1 contour per circle. How can I use RETR_EXTERNAL and ignore the outer contour (rectangle), so that it only returns the circles?
has comment: http://stackoverflow.com/comment/90798628
type: Question
has answer: http://stackoverflow.com/a/51920697
answer count: 1
downvote count: 0
favorite count: 0
score: 2
upvote count: 2
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/51952712
tagged with: conv-neural-network
tagged with: tensorflow
type: Question
accepted answer: http://stackoverflow.com/a/51953008
has answer: http://stackoverflow.com/a/51953035
tagged with: neural-network
has body: So let's assume that I have RGB images of shape [128,128,3], I want to create a CNN with two Conv-ReLu-MaxPool layers as below. def cnn(input_data): #conv1 conv1_weight = tf.Variable(tf.truncated_normal([4,4,3,25], stddev=0.1,),tf.float32) conv1_bias = tf.Variable(tf.zeros([25]), tf.float32) conv1 = tf.nn.conv2d(input_data, conv1_weight, [1,1,1,1], 'SAME') relu1 = tf.nn.relu(tf.nn.add(conv1, conv1_bias)) max_pool1 = tf.nn.max_pool(relu1, [1,2,2,1], [1,1,1,1], 'SAME') #conv2 conv2_weight = tf.Variable(tf.truncated_normal([4,4,25,50]),0.1,tf.float32) conv2_bias = tf.Variable(tf.zeros([50]), tf.float32) conv2 = tf.nn.conv2d(max_pool1, conv2_weight, [1,1,1,1], 'SAME') relu2 = tf.nn.relu(tf.nn.add(conv2, conv2_bias)) max_pool2 = tf.nn.max_pool(relu2, [1,2,2,1], [1,1,1,1], 'SAME') After this step, I need to transform the output into 1xN layer for the next fully connected layer. However, I am not sure how I should determine what N is in 1xN. Is there a specific formula including the layer size, strides, max pool size, image size etc? I am pretty lost in this phase of the problem even though I think that I get the intuition behind a CNN.
answer count: 3
downvote count: 0
possible better answer: http://stackoverflow.com/a/51953077
has answer: http://stackoverflow.com/a/51953077
favorite count: 0
upvote count: 2
has title: After going through convolution steps, what should be the shape of the tensor in fully connected layer?
has answer: http://stackoverflow.com/a/51953008
tagged with: python
score: 2
type: AnsweredQuestion

http://stackoverflow.com/comment/90776698
comment on: http://stackoverflow.com/q/51913142
score: 0
type: Comment
type: QuestionComment
has text: @truecam: print match_group_t[i].replace("\n",""). Is not replace the required \n with "".

http://stackoverflow.com/a/51828782
has body: Just run wusa using the subprocess module: import subprocess for update in ['2982791', '2988227', '1337567']: subprocess.run(['wusa', '/uninstall', '/kb:' + update, '/quiet'])
type: Answer
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/51828582
accepted answer of: http://stackoverflow.com/q/51828582
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/51884961
upvote count: 1
score: 1
downvote count: 0
has body: os.walk(top, topdown=Ture, onerror=None, followlinks=False) The walk() function in module os can traverse all files in a folder. The function returns a tupple(dirpath, dirnames, filenames). Parameters: dirpath：string, the path of directory, dirnames：list, includes all directories’ name filenames：list，includes all files’ name. p.s. dirnames and filenames didn’t include the path information, if you need entire path, use os.path.join(dirpath, dirnames)
type: Answer
answers question: http://stackoverflow.com/q/51884844

http://stackoverflow.com/q/51907699
tagged with: django
tagged with: python
tagged with: gis
score: 2
type: AnsweredQuestion
downvote count: 0
tagged with: geodjango
type: Question
upvote count: 2
has body: I am trying to create member instances in a very simple way to practice GeoDjango. I am able to create the instances but they are not showing correctly in the admin map (See images Below) below are my models.py from django.contrib.gis.db import models class Member(models.Model): name = models.CharField(max_length=150) image = models.ImageField() lat = models.FloatField() lon = models.FloatField() point = models.PointField() objects = models.GeoManager() def __str__(self): return self.name below is my views.py class MemberCreate(CreateView): model = Member fields = ('name', 'image', 'lat', 'lon') def form_valid(self, form, *args, **kwargs): self.object = form.save(commit=False) self.object.point = fromstr('POINT(%s %s)'%(self.object.lat, self.object.lon), srid=4326) self.object.save() return redirect('member:all_members') The model and views are successfully creating the model instance on my admin.py below is the code for admin.py from django.contrib.gis import admin from .models import Member admin.site.register(Member, admin.OSMGeoAdmin) The point on Admin of my GeoDjango Project See Below The place where the point actually is on the internet( Notice same lat, lon See Below) How can I fix this
tagged with: postgis
has title: GeoDjango. Admin not showing map location for point = models.PointField() in created instances
accepted answer: http://stackoverflow.com/a/51921162
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51921162

http://stackoverflow.com/q/51916961
has comment: http://stackoverflow.com/comment/90842753
has comment: http://stackoverflow.com/comment/90784313
answer count: 1
has comment: http://stackoverflow.com/comment/90787940
favorite count: 0
has comment: http://stackoverflow.com/comment/90784731
tagged with: instagram
type: UnansweredQuestion
tagged with: python
has title: Python Selenium Automatic Follow Instagram
has comment: http://stackoverflow.com/comment/90787988
score: 3
downvote count: 0
tagged with: selenium
has comment: http://stackoverflow.com/comment/90842306
type: Question
has body: This script doesn't follow on Instagram why? import time from time import sleep from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.common.keys import Keys browser = webdriver.Chrome('./chromedriver') "GO INSTAGRAM PAGE FOR LOGIN" browser.get('https://www.instagram.com/accounts/login/?hl=it') sleep(2) "ID AND PASSWORD" elem = browser.find_element_by_name("username").send_keys('id') elem = browser.find_element_by_name("password").send_keys('password') "CLICK BUTTON AND OPEN INSTAGRAM" good_elem = browser.find_element_by_xpath('//*[@id="react-root"]/section/main/div/article/div/div[1]/div/form/span/button').click() sleep(2) browser.get("https://www.instagram.com") "GO TO PAGE FOR FOLLOW" browser.get("https://www.instagram.com/test/") time.sleep(30) "FOLLOW (DON'T WORK)" follow = browser.find_element_by_xpath('//*[@id="react-root"]/section/main/div/header/section/div[1]/span/span[1]/button').click()
has answer: http://stackoverflow.com/a/51917619
upvote count: 3

http://stackoverflow.com/q/51906909
tagged with: import
type: Question
tagged with: python-import
downvote count: 2
has answer: http://stackoverflow.com/a/51907040
accepted answer: http://stackoverflow.com/a/51907040
has comment: http://stackoverflow.com/comment/136689326
score: -2
answer count: 1
has body: I am trying to import just one function from a .py file which has a space in its title. Due to external constraints, I cannot rename the file. My first try was: from File 1 import my_func But that got a SyntaxError. Following advice on other StackOverflow, I found ways to import all the functions from a module/file: V1: exec(open("File 1.py").read()) V2: globals().update(vars(__import__('File 1'))) However, I would like to only import my_func. I would also prefer to do this without using other modules like importlib. Any help is very much appreciated, I am still learning!
linked to: http://stackoverflow.com/q/301134
has title: Importing a specific function from a file with a space in its name
tagged with: python
favorite count: 0
upvote count: 0
tagged with: whitespace
linked to: http://stackoverflow.com/q/9123517
duplicate of: http://stackoverflow.com/q/70147659
type: AnsweredQuestion
duplicate of: http://stackoverflow.com/q/301134

http://stackoverflow.com/comment/90764027
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51906808
has text: Have you installed `cuda` and `cudnn`?
type: Comment

http://stackoverflow.com/comment/90753406
type: QuestionComment
has text: The powerhouses in SQL are SELECT, UPDATE, INSERT, and DELETE. SELECT let's you LOOK at records in your database. UPDATE let's you EDIT records in your database. INSERT let's you put in NEW records into your database. DELETE let's you delete records from your database. In this case you want to update a value, so you need to use an UPDATE statement instead of a SELECT statement.
comment on: http://stackoverflow.com/q/51900158
score: 0
type: Comment

http://stackoverflow.com/comment/90720838
has text: Thank you for your help, I do only want it where the title matches. I get the following error at the "if (df.loc[j,'end_date'] >= df.loc[i,'second_date']) == True:" line. :KeyError: 'the label [0] is not in the [index]'
comment on: http://stackoverflow.com/a/51884361
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/90832014
score: 0
type: Comment
has text: Filter by area, width/height ratio, approx points number and so on, I get 234/240 circles in total. Note, the bottom four circles are connected to the bottom lines,so it's not easy to distinguish. This is my result. https://i.sstatic.net/XKXDC.png
type: QuestionComment
comment on: http://stackoverflow.com/q/51920907

http://stackoverflow.com/comment/90620611
type: Comment
type: QuestionComment
has text: How are you calling your Python script? Is there a shell pipeline into or out of Python?
score: 0
comment on: http://stackoverflow.com/q/51831538

http://stackoverflow.com/a/51840649
type: Answer
has body: I would use an open source that already done the hard work and try to modify it to my needs. For example: https://github.com/ericfourrier/scrape-linkedin Note: this will only work for public data
answers question: http://stackoverflow.com/q/51840397
has comment: http://stackoverflow.com/comment/90635742
upvote count: 5
has comment: http://stackoverflow.com/comment/90636334
has comment: http://stackoverflow.com/comment/90635496
score: 5
downvote count: 0
has comment: http://stackoverflow.com/comment/90636005

http://stackoverflow.com/q/51922500
tagged with: python
upvote count: 6
has comment: http://stackoverflow.com/comment/90902422
has answer: http://stackoverflow.com/a/65756935
accepted answer: http://stackoverflow.com/a/53006893
type: AnsweredQuestion
score: 6
possible better answer: http://stackoverflow.com/a/65756935
tagged with: tensorflow
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/53006893
has title: tf.metrics.auc yielding very different from sklearn.metrics.roc_auc_score
downvote count: 0
has body: tf.metrics.auc is yielding very different values comparing to sklearn.metrics.roc_auc_score for some situations. I'm unable to determine what is the particularities of such situations, but I was able to procure a reproducible example: Code and data downloadable from https://www.dropbox.com/s/ym2ptqaqw2qjite/minimal_program_AUC.zip?raw=1 Code: import sklearn.metrics from keras.models import Model, load_model import tensorflow as tf from keras import backend as K import numpy as np def auc(y_true, y_pred): auc = tf.metrics.auc(y_true, y_pred, num_thresholds=65)[1] K.get_session().run(tf.local_variables_initializer()) return auc model = load_model('Model.hdf5', custom_objects={'auc': auc}) X = np.fromfile('X_test(65, 80, 1292, 1).txt', sep=',').reshape(65, 80, 1292, 1) Y = np.fromfile('Y_test(65, 1).txt', sep=',').reshape(65, 1) batchsize = 45 evaluation = model.evaluate(X, Y, batch_size=batchsize, verbose=1) predictions = model.predict(X, batch_size=batchsize, verbose=0, steps=None) auc = sklearn.metrics.roc_auc_score(Y, predictions, average='macro', sample_weight=None) print('sklearn.metrics.roc_auc_score: ', auc) print('vs') print('tf.metrics.auc: ', evaluation[2]) Results: sklearn.metrics.roc_auc_score: 0.40476190476190477 vs tf.metrics.auc: 0.2756012196724231 Discussion: I've read that tf.metrics.auc is approximate, and the higher the num_thresholds the closer to the ideal AUC it gets. (Change-Request/Side-note: My data only has 65 samples, so with 65 thresholds it's possible to compute the ideal AUC) I've tested with several thresholds, and the outputted AUC value varies, but does not closely match sklearn.metrics.roc_auc_score EDIT: I also tested with batchsize = X.shape[0] so its computed in only 1 batch, and that didn't "fix" it I did not find out if sklearn.metrics.roc_auc_score is approximate or ideal. Question: What's up? Should we create a bug ticket? EDIT2: Here is the culprit, the predictions are all almost 0.5, which causes the approximate nature of the…
tagged with: scikit-learn
favorite count: 0

http://stackoverflow.com/a/51948882
downvote count: 0
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/51948795
score: 1
has body: data.readline() will give you the trailing newline character \n. You need to call text.strip() before passing to the encrypt function to get arid of it.

semaphore
type: Tag
tags question: http://stackoverflow.com/q/51811575
tag name: semaphore

http://stackoverflow.com/comment/90633361
has text: Thank you, timedelta seems fine. Although, timedelta lacks hours and minutes return methods, so I might need to extend this class
comment on: http://stackoverflow.com/q/51839911
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51891917
has answer: http://stackoverflow.com/a/53907460
score: 0
has comment: http://stackoverflow.com/comment/94536226
has comment: http://stackoverflow.com/comment/90734836
linked to: http://stackoverflow.com/q/50071378
linked to: http://stackoverflow.com/q/41328451
type: UnansweredQuestion
has title: ssl module in Python is not available
tagged with: python
has comment: http://stackoverflow.com/comment/90751879
type: Question
has body: I am trying to install Python3 with some python libs (pyqt5, lxml) on the following machine: $ uname -a Linux devel_server 4.11.0-22.el7a.aarch64 #1 SMP Sun Sep 3 13:39:10 CDT 2017 aarch64 aarch64 aarch64 GNU/Linux $ cat /etc/*-release CentOS Linux release 7.4.1708 (AltArch) NAME="CentOS Linux" VERSION="7 (AltArch)" ID="centos" ID_LIKE="rhel fedora" VERSION_ID="7" PRETTY_NAME="CentOS Linux 7 (AltArch)" ANSI_COLOR="0;31" CPE_NAME="cpe:/o:centos:centos:7" HOME_URL="https://www.centos.org/" BUG_REPORT_URL="https://bugs.centos.org/" SIG_FAMILY="AltArch aarch64" CENTOS_MANTISBT_PROJECT="CentOS-7" CENTOS_MANTISBT_PROJECT_VERSION="7" REDHAT_SUPPORT_PRODUCT="centos" REDHAT_SUPPORT_PRODUCT_VERSION="7" CentOS Linux release 7.4.1708 (AltArch) CentOS Linux release 7.4.1708 (AltArch) using the following script: #!/bin/bash PYTHON_VERSION=3.6.5 sudo yum install openssl-devel sudo yum install zlib-devel cd /tmp/ wget https://www.python.org/ftp/python/${PYTHON_VERSION}/Python-${PYTHON_VERSION}.tgz tar -xzvf Python-${PYTHON_VERSION}.tgz cd Python-${PYTHON_VERSION} ./configure make sudo make install pip3 install pyqt5 pip3 install lxml cd - everything goes well, until it gets to actually installing the python libs: pip3 install pyqt5. It fails with the following output: pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available. Collecting pyqt5 Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.",)': /simple/pyqt5/ Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.",)': /simple/pyqt5/ Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.",)': /sim…
answer count: 1
linked to: http://stackoverflow.com/q/5937337

http://stackoverflow.com/comment/90792712
comment on: http://stackoverflow.com/a/51921498
has text: In this case, you can use `driver.find_elements_by_link_text("your link text")`.
type: Comment
score: 1
type: AnswerComment

http://stackoverflow.com/a/51824781
answers question: http://stackoverflow.com/q/51824723
has body: Because you're not returning anything if the request method is GET, I assume? Of course you'll get an error if you're trying to return the variables x, y, z and a outside the scope of your if statement as they won't be defined.
has comment: http://stackoverflow.com/comment/90606472
has comment: http://stackoverflow.com/comment/90603854
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90603823
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51824723
score: 1

http://stackoverflow.com/comment/90780555
score: 0
has text: *"not getting a hyperlink for the reference"*. I don't understand. For what reference do you expect a hyperlink?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51881692

http://stackoverflow.com/comment/90757794
has text: `treelib` module looks promising [docs](https://treelib.readthedocs.io/en/latest/examples.html#basic-usage) , [code example](https://github.com/caesar0301/treelib/blob/master/examples/recursive_dirtree_generator.py)
comment on: http://stackoverflow.com/q/51903172
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51857261
answers question: http://stackoverflow.com/q/51856948
score: 1
downvote count: 0
has body: "What does return do?" The return statement returns the value to the caller of the function. Here is a simple example: def give_me_a_number(): return 7 Now, give_me_a_number will always return 7, so we can do this: x = give_me_a_number() Variable x now has value 7 because that is what give_me_a_number returned. "What's the difference between where I put the return?" Where you put the return statement is important because statements are executed sequentially and when return is encountered, the function ends. For example: def my_function(): a = 1 a = 2 return a a = 3 Function my_function will return value 2, because that is the value of a when return is encountered. Note that a = 3 is never executed. The code from the question (return within for loop) In your case if return statement is indented, then it is inside the for block and will be executed the first time for loop is executed, so that means not all scores will be looped through. def grades_sum(scores): total=0 for i in scores: total+=i return total print (total) If it is not indented, then it is outside of the for loop and will be executed after the all scores are looped though by the for loop.
type: Answer
upvote count: 1

http://stackoverflow.com/a/51938432
has comment: http://stackoverflow.com/comment/90827095
has comment: http://stackoverflow.com/comment/90827399
accepted answer of: http://stackoverflow.com/q/51938385
upvote count: 1
has comment: http://stackoverflow.com/comment/90892231
score: 1
has comment: http://stackoverflow.com/comment/90829351
has comment: http://stackoverflow.com/comment/90827375
has comment: http://stackoverflow.com/comment/90892425
has comment: http://stackoverflow.com/comment/90827492
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90827928
type: Answer
has body: Updated to address comments You will want to leverage in here and it's best to create a set from the two lists as mentioned by @abarnert in the comments. You could wrap this inside of a function and recursively call the function if the conditions are not satisfied (note I have changed raw_input() to input() for Python 3 compatibility): getuser = input("Please enter your username :") print("1. render_device") print("2. audit_device") askuser = input("Would you like to render_device or audit_device? : ") def verify_input(sites_set): get_site_name = input("Please enter the site name you'd like to render :") if get_site_name in sites_set: print('Proceed') return else: print('Not in either list!') verify_input(sites_set) if askuser == "1": sites_2017 = ["bob", "joe", "charlie"] sites_2018 = ["sarah", "kelly", "christine"] verify_input(set(sites_2017 + sites_2018)) EDIT However, a much simpler implementation is to just use a while loop: getuser = input("Please enter your username :") print("1. render_device") print("2. audit_device") askuser = input("Would you like to render_device or audit_device? : ") if askuser == "1": sites_2017 = ["bob", "joe", "charlie"] sites_2018 = ["sarah", "kelly", "christine"] sites_set = set(sites_2017 + sites_2018) proceed = False while not proceed: get_site_name = input("Please enter the site name you'd like to render :") if get_site_name in sites_set: print('Proceed') proceed = True else: print('Not in either list!')
answers question: http://stackoverflow.com/q/51938385

http://stackoverflow.com/a/51800888
downvote count: 0
type: Answer
upvote count: 5
has comment: http://stackoverflow.com/comment/90562901
accepted answer of: http://stackoverflow.com/q/51800651
answers question: http://stackoverflow.com/q/51800651
score: 5
has body: You can use np.vectorize with dict.get: d = np.vectorize(mydict.get) res = d(input_pattern) print(res) array([[1, 6], [2, 5], [3, 4]])
type: AcceptedAnswer

http://stackoverflow.com/a/51806492
has body: you can use timeit module to achieve it. import timeit first = """ from pathlib import Path list_comprehension = [item for item in Path('.').iterdir()] """ second = """ from pathlib import Path list_method = list(Path('.').iterdir()) """ print(timeit.timeit(stmt=first, number=10000)) # 1.0698672000000329 print(timeit.timeit(stmt=second, number=10000)) # 1.0508478000000423
accepted answer of: http://stackoverflow.com/q/51806456
type: Answer
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/90568678
has comment: http://stackoverflow.com/comment/90568637
has comment: http://stackoverflow.com/comment/90568672
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51806456

http://stackoverflow.com/q/51828454
has answer: http://stackoverflow.com/a/51834988
tagged with: django
tagged with: python
tagged with: boto
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90611454
has answer: http://stackoverflow.com/a/51828523
type: Question
has body: I tried using boto, but it has the .list() method, which takes way to long for my data set, and the .get_all_keys(), which gets it random. I want to get about 100-1000 of the most recent keys in my S3 bucket, which has millions of keys in it. What is the most efficient way of doing this.
has comment: http://stackoverflow.com/comment/90675838
tagged with: amazon-s3
has comment: http://stackoverflow.com/comment/90611316
has comment: http://stackoverflow.com/comment/90611602
has comment: http://stackoverflow.com/comment/90611577
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/90611468
tagged with: amazon-web-services
has title: Python: getting the first 100 most recent keys in amazon s3 bucket

http://stackoverflow.com/a/51940001
has body: Using datetime.datetime object: from datetime import datetime start = datetime.strptime('20180827', '%Y%m%d') current = datetime.strptime('20180912', '%Y%m%d') print((current - start).days//7 +1) # The week number # Output: 3 This can also handle different years. Note that this only works when the start date is Monday.
type: Answer
accepted answer of: http://stackoverflow.com/q/51939716
answers question: http://stackoverflow.com/q/51939716
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/90850685
score: 0
has text: Please provide us more details like, what have you tried already?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51950002

http://stackoverflow.com/comment/90555806
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51799156
type: AnswerComment
has text: Thank you very much. I tried the first command: df2 = df_selecao_atual.dropna().groupby(['nome', 'tipo']).resumo.agg(', '.join).str.split(', ').agg(Counter).reset_index()

http://stackoverflow.com/a/51983590
answers question: http://stackoverflow.com/q/51919417
score: 0
type: Answer
has body: I think I found the solution because it works for me. I had to make a Tensorflow session for each model I create(ie a Tensorflow graph). This is how the server can create multiple models simultaneously. You can refer to this issue : https://github.com/keras-team/keras/issues/8538#issuecomment-358720718

http://stackoverflow.com/q/51859492
favorite count: 0
has comment: http://stackoverflow.com/comment/90674584
has answer: http://stackoverflow.com/a/51861363
has comment: http://stackoverflow.com/comment/90671894
has comment: http://stackoverflow.com/comment/90673858
tagged with: python
tagged with: line
has body: I am plotting data in a radar plot and adding two vertical lines to mark an event +/- the standard deviation of that event. I would really like to shade between these lines covering the whole of the y axis. So far I have tried ax.fill_between and ax.span but I'm not having any luck. Does anyone know how to do this? Basic code below. import numpy as np import matplotlib.pyplot as plt from matplotlib.path import Path from matplotlib.spines import Spine from matplotlib.projections.polar import PolarAxes from matplotlib.projections import register_projection from math import pi data = [1, 5, 10, 11, 15] data = np.asarray(data) labels = [10, 20, 30, 40, 50] event1 = 3 st_dev_event1 = 1 def _radar_factory(num_vars): theta = 2*np.pi * np.linspace(0, 1-1./num_vars, num_vars) theta += np.pi/2 def unit_poly_verts(theta): x0, y0, r = [0.5] * 3 verts = [(r*np.cos(t) + x0, r*np.sin(t) + y0) for t in theta] return verts class RadarAxes(PolarAxes): name = 'radar' RESOLUTION = 1 def fill(self, *args, **kwargs): closed = kwargs.pop('closed', True) return super(RadarAxes, self).fill(closed=closed, *args, **kwargs) def plot(self, *args, **kwargs): lines = super(RadarAxes, self).plot(*args, **kwargs) for line in lines: self._close_line(line) def _close_line(self, line): x, y = line.get_data() if x[0] != x[-1]: x = np.concatenate((x, [x[0]])) y = np.concatenate((y, [y[0]])) line.set_data(x, y) def set_varlabels(self, labels): self.set_thetagrids(theta * 180/np.pi, labels) def _gen_axes_patch(self): verts = unit_poly_verts(theta) return plt.Polygon(verts, closed=True, edgecolor='k') def _gen_axes_spines(self): spine_type = 'circle' verts = unit_poly_verts(theta) verts.append(verts[0]) path = Path(verts) spine = Spine(self, spine_type, path) spine.set_transform(self.transAxes) return {'polar': spine} register_projection(RadarAxes) return theta N = len(labels) theta = _radar_factory(N) fig = plt.figure() plt.clf() ax = fig.add_subplot(1, 1, 1, projection='radar') ax.plot(theta+(data&lt;0.0…
type: AnsweredQuestion
has title: Matplotlib Radar Plot fill between vertical lines
downvote count: 1
accepted answer: http://stackoverflow.com/a/51861363
type: Question
has comment: http://stackoverflow.com/comment/90673969
tagged with: matplotlib
score: -1
has comment: http://stackoverflow.com/comment/90674889
tagged with: radar-chart
has comment: http://stackoverflow.com/comment/90674492
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/90674205

http://stackoverflow.com/comment/90770661
type: AnswerComment
comment on: http://stackoverflow.com/a/51904952
type: Comment
has text: thanks @DYZ, I get this error: `*** IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices`
score: 0

http://stackoverflow.com/a/51845402
has body: Start using a terminal multiplexer like tmux or screen and launch python under it. My favourite is tmux. Your python session would persist till you kill the tmux session or till logout / reboot
type: Answer
answers question: http://stackoverflow.com/q/51844590
score: 0

http://stackoverflow.com/q/51840326
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/90634939
has body: I have a question for the below code, which is basically a function taking 2 parameters one is a column and one is a dataframe, and I'm having a hard time to understand the for loop iterating over the column and checking if values in the column is keys in the empty dictionary "langs_counts", how is it possible to check when it's an empty dictionary, please explain to me the for loop and why we put 'entry' between square brackets. for entry in col: if entry in langs_count.keys(): langs_count[entry] += 1 else: langs_count[entry] = 1 # Define count_entries() def count_entries(df, col_name): """Return a dictionary with counts of occurrences as value for each key.""" # Initialize an empty dictionary: langs_count langs_count = {} # Extract column from DataFrame: col col = df[col_name] # Iterate over lang column in DataFrame for entry in col: # If the language is in langs_count, add 1 if entry in langs_count.keys(): langs_count[entry] += 1 # Else add the language to langs_count, set the value to 1 else: langs_count[entry] = 1 # Return the langs_count dictionary return langs_count # Call count_entries(): result result = count_entries(tweets_df, 'lang') # Print the result print(result)
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90633897
has comment: http://stackoverflow.com/comment/90634374
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51841793
has comment: http://stackoverflow.com/comment/90636631
upvote count: 0
has comment: http://stackoverflow.com/comment/90633810
has title: function Iterating over a dictionary with If conditions
type: Question
score: -1
has comment: http://stackoverflow.com/comment/90637333
has comment: http://stackoverflow.com/comment/90636369
has comment: http://stackoverflow.com/comment/90636275

http://stackoverflow.com/comment/90719575
score: 0
comment on: http://stackoverflow.com/q/51883926
has text: Updated the question description to be more accurate.
type: QuestionComment
type: Comment

http://stackoverflow.com/a/51905746
has comment: http://stackoverflow.com/comment/90763828
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51905712
type: Answer
has comment: http://stackoverflow.com/comment/90762052
accepted answer of: http://stackoverflow.com/q/51905712
has comment: http://stackoverflow.com/comment/90763074
has comment: http://stackoverflow.com/comment/90762075
upvote count: 116
has comment: http://stackoverflow.com/comment/90762127
has body: Use value_from_object: field_name = 'name' obj = MyModel.objects.first() field_object = MyModel._meta.get_field(field_name) field_value = field_object.value_from_object(obj) Which is the same as getattr: field_name = 'name' obj = MyModel.objects.first() field_object = MyModel._meta.get_field(field_name) field_value = getattr(obj, field_object.attname) Or if you know the field name and just want to get value using field name, you do not need to retrieve field object firstly: field_name = 'name' obj = MyModel.objects.first() field_value = getattr(obj, field_name)
score: 116
has comment: http://stackoverflow.com/comment/90762041

http://stackoverflow.com/a/51925628
upvote count: 4
has comment: http://stackoverflow.com/comment/90878701
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51925228
score: 4
has comment: http://stackoverflow.com/comment/90878151
has comment: http://stackoverflow.com/comment/90878874
accepted answer of: http://stackoverflow.com/q/51925228
has comment: http://stackoverflow.com/comment/90878728
type: Answer
has comment: http://stackoverflow.com/comment/90879221
has body: Here I'm overwrite the existing image with reduced size image. The artwork.foreground is a file-pointer and we passed the fp to the PIL class. The save() method of Image class takes filename/path-conatining-filename as first argument. At that point the .path attribute became handy from PIL import Image def do_resize(image): pil_img = Image.open(image) resize_limit = 100, 150 pil_img.thumbnail(resize_limit, Image.ANTIALIAS) pil_img.save(image.path) for artwork in ArtworkForeground.objects.filter(foreground__isnull=False): do_resize(artwork.foreground) UPDATE-1 Where should I put this snippet? If you set some kind of restriction or validation from Now Onwards, just run this script in your Django Shell ( This is only for a one time use)

http://stackoverflow.com/q/51803041
tagged with: python
has body: Span class names and div class information of HTML page is missing when i am trying to open the Web page with the python program. I have tried urllib.request.urlopen() , requests.get(), wget, robobrowser and some other packages in saving the web page with data of class names,but not succeeded. url = 'https://www.google.com/maps/dir/Navallur,+Tamil+Nadu+600130/Vijayawada,+Andhra+Pradesh/@14.6711659,78.0012123,7z/data=!3m1!4b1!4m13!4m12!1m5!1m1!1s0x3a525a51439fd9f3:0x5fdacd19ed90126c!2m2!1d80.225463!2d12.8447728!1m5!1m1!1s0x3a35eff9482d944b:0x939b7e84ab4a0265!2m2!1d80.6480153!2d16.5061743' page = urllib.request.urlopen(url).read() page1 = requests.get(url).content html = open('some1.html','wb') html.write(page) html.close()
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52231421
accepted answer: http://stackoverflow.com/a/52231421
has title: What is the difference between saving web page info with Python program(urllib, request) and save through browser
type: Question
has comment: http://stackoverflow.com/comment/90562593
score: 0
tagged with: urllib2
answer count: 1
tagged with: url
tagged with: http://stackoverflow.com/tag/html

http://stackoverflow.com/a/52418702
downvote count: 0
type: Answer
upvote count: 5
answers question: http://stackoverflow.com/q/51909997
has body: This might be a case-by-case problem. Several days ago I met a problem that my computer will freeze when I call dataset.shuffle(180000). It turned out that, if I map() before shuffle(), it will freeze; but if I map() after shuffle(), it will not. It feels like (at least according to my experience) that when shuffling, tensorflow is probably shuffling the actual tensors in the memory, instead of their reference (or "pointer"). In my case, my files are images with 112x112 pixels and 3 color channels. If I map() before shuffle(), shuffle(180000) will shuffle 180000 tensors with 112x112x3 numbers ; but if I shuffle() before map(), shuffle(180000) will just shuffle 180000 tensors that each only contains a short string (filename like "abc-001.jpeg"). According to my experience above, without any parallel computation, if the data you are going to map() is much larger in size than their filename (which is usually the case), then shuffle() before map() should be faster than map() before shuffle(). In the stock example, I think it is because the stock data is relatively small in size. Unlike 112x112x3 numbers in one tensor in my case, each stock datapoint should only have 4 prices(open,close,high,low) and 1 time(year-month-day-hour:min:sec). In this case shuffle() the data won't become an issue. To conclude, I think in most cases (where file size > filename size), shuffle() before map() is better.
score: 5

http://stackoverflow.com/comment/90721832
type: QuestionComment
has text: If the array is not sorted, what would your expected output be? For example with `Input = 15` and `arr = [10, 20, 14]`, would you expect `0,1` or `1,2` as output?
score: 1
comment on: http://stackoverflow.com/q/51885086
type: Comment

http://stackoverflow.com/comment/90867969
comment on: http://stackoverflow.com/q/51940596
type: Comment
has text: Indeed. Sadly 3D rotation is not working with Google Colab.
score: 4
type: QuestionComment

http://stackoverflow.com/comment/90760399
has text: thanks for the suggest. The pandas was reading the csv as str rather than bytes.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51904765

http://stackoverflow.com/comment/90825195
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51937482
has text: I have added some explanations of what I'm attempting @ArthurDent

http://stackoverflow.com/comment/90786621
comment on: http://stackoverflow.com/a/51912371
type: AnswerComment
type: Comment
has text: For me, AUDIO_FILE = path.join(path.dirname(path.realpath('__file__')), "english.wav") worked.
score: 0

http://stackoverflow.com/a/51933751
has body: Visualization of data is quite unintuitive when using libraries like matplotlib, seaborn, bokeh and the like. Thank’s to Jake VanderPlas, there exists Altair, a declarative libraries that is very straight forward. Just load your not aggregate date data to df.Assuming you have one column of non-aggregated dates you could do: #pip install altair import altair as alt alt.Chart(df).transform_aggregate( count='count()', groupby=['date'] ).mark_line().encode( x='date', y='count()',\ tooltip='count:Q' )
type: Answer
answers question: http://stackoverflow.com/q/51931258
accepted answer of: http://stackoverflow.com/q/51931258
score: 0
type: AcceptedAnswer

http://stackoverflow.com/q/51903086
tagged with: machine-learning
upvote count: 1
tagged with: python
downvote count: 1
has comment: http://stackoverflow.com/comment/90757666
has comment: http://stackoverflow.com/comment/90832363
has body: I am trying to train a canned estimator tf.estimator.DNNClassifier for a binary classification problem def input_fn_train(features, labels, batch_size): dataset = tf.data.Dataset.from_tensor_slices((dict(features), labels)) dataset = dataset.shuffle(1000).repeat().batch(batch_size) return dataset hidden_units=[1024, 512, 256] estimator = tf.estimator.DNNClassifier( feature_columns=my_feature_columns, hidden_units=hidden_units, model_dir=model_dir, optimizer=tf.train.ProximalAdagradOptimizer( learning_rate=0.01, l1_regularization_strength=0.001)) estimator.train(input_fn=lambda:input_fn_train(train_x, train_y, batch_size), steps=train_steps) But, when I try to run estimator.train, I get the following error [libprotobuf FATAL T:\src\github\tensorflow\cmake_build\protobuf\src\protobuf\src\google\protobuf\message_lite.cc:68] CHECK failed: (byte_size_before_serialization) == (byte_size_after_serialization): tensorflow.GraphDef was modified concurrently during serialization. I am pretty sure it has to do with the size of the CSV training file stored in the variable train_x because I tried the same code with smaller training CSV files (~500 MB) and it works perfectly fine. My CSV training file has 801 columns (including the label 0 or 1 ), the 800 features are numeric values between 0 and 1 (float). The training file has more than 1 million of instances ( 801 x 1172480 ), Also, it is important to mention that train_x , the variable that contain the data from the 7GB CSV, is successfully populated with the 7GB data in memory. Moreover, I don't have any problems with memory overflow ( my computer has 128 GB of memory RAM), so the only thing left is that Tensorflow [unfortunately] can't handle CSV training files of that size. I am planning to split the training set in different files and use the checkpoint feature to keep training over those files, but I am not sure if that is the optimal solution, any suggestion would be appreciated
tagged with: tensorflow
type: Question
has title: Tensorflow: tf.estimator does not work with large CSV training files (~7GB)
score: 0
tagged with: deep-learning
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/90832542
favorite count: 0
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/a/51841300
has body: In the function get_cleaned_data delete 'password': self.validated_data.get('password', ''), and insert 'password1': self.validated_data.get('password1', ''), 'password2': self.validated_data.get('password2', ''), It solved my problem
score: 0
accepted answer of: http://stackoverflow.com/q/51822247
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51822247
type: Answer

http://stackoverflow.com/comment/90746752
type: QuestionComment
comment on: http://stackoverflow.com/q/51897851
has text: Isn't the name of the method decorated by `@property` always the same as the name of the property itself?
score: 0
type: Comment

http://stackoverflow.com/a/68307313
score: 5
downvote count: 0
has body: All above are pretty good answers but i want to try to explain it in much simpler way My urls.py inside polls app: urlpatterns = [ path('', views.index, name='index'), # /polls/5/ # sends the values of question_id to the views path('<int:question_id>/', views.detail, name='detail'), # /polls/5/results path('<int:question_id>/results', views.results, name='results'), # /polls/5/vote path('<int:question_id>/vote', views.vote, name='vote'), ] and a small part of my index.html is: index detail results Inside index.html this shows index detail results as links as obvious, but notice here that inside tag I use url tag of the Django The correct format of using url tag of Django is: {% url 'NAME OF URL here' any_variables_here %} NAME OF URL means the name that we give the name to a URL inside name argument of path() that means we only have to use name of the URL inside href attribute, we now don't have to use the hectic and complex url everywhere inside our code that's awesome feature of Django. And the most important advantage is like if we changed our URL inside the urls.py like: <int:question_id>/vote to <int:question_id>/funny_poll/vote then now you don't need to worry about changing the url in each and every file wherever you used it before. This is quite awesome and a Django developer should use this feature. HaPpY Coding
type: Answer
answers question: http://stackoverflow.com/q/51922641
upvote count: 5

http://stackoverflow.com/comment/90620892
score: 2
comment on: http://stackoverflow.com/a/51833440
type: AnswerComment
has text: This does not explain the behaviour of their code. It does not help anyone learn.
type: Comment

http://stackoverflow.com/comment/90664803
has text: Perfect, thanks so much! Also you wouldn't happen to be the Wiggy that helped Moderate a large Discord server with myself and a few others about a month ago? We hit 3k members then got closed?
type: Comment
comment on: http://stackoverflow.com/a/51853290
type: AnswerComment
score: 0

http://stackoverflow.com/comment/90716681
score: 0
comment on: http://stackoverflow.com/q/51881388
type: Comment
type: QuestionComment
has text: I wanna get text below tag

http://stackoverflow.com/comment/90599373
type: QuestionComment
has text: It is more useful to post excerpts of code as text in your question, rather than links to screenshots.
score: 5
type: Comment
comment on: http://stackoverflow.com/q/51822701

http://stackoverflow.com/a/51947746
answers question: http://stackoverflow.com/q/51947583
type: Answer
score: 0
has body: All your functions, configured in this setup, return None. That is the default return value for functions, one that is returned if no return is specified. Your other_func(), however, returns the return value of print_func(). Given that you haven't specified any return value for print_func() it returns None making other_func() return None as well. If you had specified any return value for print_func() - it would be picked up by other_func(), but not by other_func2().

http://stackoverflow.com/comment/90823666
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51936698
has text: Well. I found the problem. Apparently, I had a bash alias shadowing my `python` command. (⁄ ⁄•⁄ω⁄•⁄ ⁄) (I don't understand why `which python` didn't reveal the alias' location, though.)

http://stackoverflow.com/comment/90689798
type: Comment
score: 0
comment on: http://stackoverflow.com/a/51853396
has text: Thanks for you comment. Never aware the difference of string and raw string thingy before hand. Learnt something here, again thanks.
type: AnswerComment

http://stackoverflow.com/comment/90686876
has text: `np.vectorize` uses `np.frompyfunc`, and allows you to `exclude` certain arguments from 'vectorization' - I think it passes those arguments through a cover function.
type: Comment
comment on: http://stackoverflow.com/a/51867441
score: 0
type: AnswerComment

http://stackoverflow.com/q/51816275
answer count: 1
has body: I'm having the 'TypeError: argument of type 'NoneType' is not iterable and adding an exception doesn't seem to work' error that I've seen elsewhere on here and have found from other answers that it's due to the loop returning a None value but adding a None exception doesn't work and I can't see how else to do this. I'm using openpyxl with Python3 and have subjects in column A that are updated through another project so could have 0 to multiple lines (I unmerge them all at the start of the script). I need to search all of the rows for each project in column J for dates to copy across to another column, and as column 2 is blank for rows that have been updated I use a for loop with a if statement to add blank rows to an array for later deletion. All rows that aren't blank, I use the else statement to count in tempList how many blank rows are in that project and then for loop to set myStringTest as the column J value so I can search for the text I want - if I find it I want to copy a slice of the text (a date) across to another column - I just have print('test') here at the moment. for i in range(2, sheet.max_row + 1): if sheet.cell(row=i, column=1).value == None: print('This row has nothing in it') arrayForDeletion2.append(i) else: tempList = 1 x = i while sheet.cell(row=x+1, column=1).value == None: tempList += 1 x += 1 if tempList &gt;30: break print(i) print(tempList) for y in range(i, i+tempList): myStringTest = (sheet.cell(row=i, column=10).value) if 'Original' in myStringTest and not None: print('test') i += 1 &gt;&gt;&gt;Traceback (most recent call last): File "main.py", line 113, in &lt;module&gt; if 'Original' in myStringTest and not None: TypeError: argument of type 'NoneType' is not iterable So A2 may have 6 update rows, with J4, J5 and J7 each having a string saying 'Original target date: XX/XX/XX' - I'm looking to recognise that in the if statement and if so to copy out just the date to another column. If no string, do nothing. That's probably not very cle…
has comment: http://stackoverflow.com/comment/90611256
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90586862
tagged with: openpyxl
has title: Openpyxl python3 project where TypeError: argument of type 'NoneType' is not iterable and adding an exception doesn't seem to work
has comment: http://stackoverflow.com/comment/90589912
has answer: http://stackoverflow.com/a/51817128
tagged with: python
linked to: http://stackoverflow.com/q/2710940
type: Question
score: 0
linked to: http://stackoverflow.com/q/3965104

http://stackoverflow.com/comment/90697729
score: 0
type: QuestionComment
has text: But only when we are sure that no other combination would work (like in my example, there should not be NaNs)
type: Comment
comment on: http://stackoverflow.com/q/51872838

http://stackoverflow.com/comment/90789906
type: Comment
has text: Thank you so much for the efforts. It is working fine for the data I have mentioned here. Is it possible to make changes to my code? because the data which I have changes a lot and we cannot use a particular regex for that
comment on: http://stackoverflow.com/a/51888659
type: AnswerComment
score: 0

http://stackoverflow.com/q/51829369
type: Question
accepted answer: http://stackoverflow.com/a/51847120
score: 0
answer count: 1
tagged with: pom.xml
tagged with: maven
tagged with: python
has answer: http://stackoverflow.com/a/51847120
has body: I have a maven project that contains several folders, each with multiple python classes. Something like this: MyProject | |-- folder1 | |-- a.py | |-- b.py | |-- folder2 | |-- c.py | |-- d.py | | -- pom.xml Since this is not a traditional program structure (src/main/..) I'm having difficulty getting SonarQube to scan the python within folder1 and folder2. It just ignores them. I thought the solution would be to add them as additional src directories within the pom, like this: org.codehaus.mojo build-helper-maven-plugin generate-sources add-source folder1 folder2 But still SonarQube still ignores them. How do I specify in the pom additional folders I want to be scanned?
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90629330
tagged with: sonarqube
has title: SonarQube not scanning additional folders in maven project

http://stackoverflow.com/comment/90557649
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51800605
type: QuestionComment
has text: What exactly is your question? Are you saying that your function always returns `None` and you are asking why? Do you want your function to *sometimes* return `None` or *never*?

http://stackoverflow.com/comment/90558572
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51800975
type: Comment
has text: @jezrael - very helpful and we are pretty close to solve this one but only the last customer gets saved to variables. So after i run the script and then type name variable i only get name of the last customer. Is there a way to assign EVERY customer name to a SEPARATE variable? Name1, Name2 etc.

http://stackoverflow.com/comment/90706030
comment on: http://stackoverflow.com/a/51877405
type: Comment
score: 3
has text: `df.apply(pd.Series)` rather not, because slow - check [this](https://stackoverflow.com/a/35491399/2901002)
type: AnswerComment

http://stackoverflow.com/q/51939360
tagged with: opencv
linked to: http://stackoverflow.com/q/27035672
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/90831660
accepted answer: http://stackoverflow.com/a/51940000
favorite count: 0
has title: How to compare OpenCV image with color
tagged with: python
has answer: http://stackoverflow.com/a/51940000
type: AnsweredQuestion
downvote count: 0
score: 1
tagged with: image-processing
has body: The problem is relatively simple. I have an image and I know a background color of the image. Given that I want to create foreground mask of the image. I tried this: background_color = np.array([255, 255, 255], dtype=np.uint8) foreground = image != background_color What I expect is a boolean matrix with the shape of HxWx1 with True where colors are matching and False where they are not matching. But this operation compare not the color, but all three color components and I'm getting HxWx3 sized matrix with True where color components matching and False where they're not matching. I created a temporary solution with for loop: foreground = np.zeros(shape=(height, width, 1), dtype=np.bool) for y in range(height): for x in range(width): if not np.array_equal(image[y, x], background_color): foreground[y, x] = True But that, of course, works slowly. My question is the following: Is there a proper way of doing such kind of comparison with the help of numpy or OpenCV methods?
type: Question
tagged with: numpy

http://stackoverflow.com/q/51923075
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/90832836
tagged with: keras
favorite count: 0
has body: My model's accuracy is not improving, not on validation data set and not on test data set. Before this, i have tried dense layers with drop out, but i had the same problem. Could you please suggest me any solution. How can i improve my accuracy? shall i change the model parameters, if so what parameters i need to change? model = Sequential() model.add(Convolution2D(125, kernel_size=(5, 5), strides=(1, 1),padding="same", data_format="channels_last",input_shape= (100,8,1))) #model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2), padding='same')) model.add(Convolution2D(64, (5, 5),padding="same", activation='relu')) model.add(Convolution2D(64, (5, 5),padding="same", activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2),padding='same')) model.add(Flatten()) #model.add(Dense(32, activation='relu')) model.add(Dense(5, activation='softmax')) sgd = SGD(lr=0.0001, decay=1e-6, momentum=0.9, nesterov=True) model.compile(loss='mse', optimizer=sgd, metrics=['accuracy']) print(model.summary()) Output _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= conv2d_16 (Conv2D) (None, 100, 8, 125) 3250 _________________________________________________________________ conv2d_17 (Conv2D) (None, 100, 8, 64) 200064 _________________________________________________________________ conv2d_18 (Conv2D) (None, 100, 8, 64) 102464 _________________________________________________________________ max_pooling2d_7 (MaxPooling2 (None, 50, 4, 64) 0 _________________________________________________________________ flatten_6 (Flatten) (None, 12800) 0 _________________________________________________________________ dense_6 (Dense) (None, 5) 64005 ================================================================= Total params: 369,783 Trainable params: 369,783 Non-trainable params: 0 _________________________________________________________________ None Model.fit x_train = x_train.reshap…
tagged with: python
has title: My model's accuracy is not improving, model is overfit on train data
type: UnansweredQuestion
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51923511
tagged with: conv-neural-network
has comment: http://stackoverflow.com/comment/90864924
has comment: http://stackoverflow.com/comment/90815801
score: -1
has comment: http://stackoverflow.com/comment/90797693

http://stackoverflow.com/comment/90570048
has text: And your primary key
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51807348
type: Comment

http://stackoverflow.com/a/51908978
type: Answer
has comment: http://stackoverflow.com/comment/90768474
answers question: http://stackoverflow.com/q/51908926
has comment: http://stackoverflow.com/comment/90768327
has body: I think you probably have the order of arguments wrong. The axis (1) comes second. It would also be easier to do it all in one swoop: nd = np.delete(nd, [0,1,6], 1).
score: 4
upvote count: 4
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51908926

http://stackoverflow.com/comment/90587577
type: AnswerComment
type: Comment
has text: No problem. Yeah. I think that would be prudent. Make another question, with new code, and comment the new link here and I'll have a look.
comment on: http://stackoverflow.com/a/51812278
score: 0

http://stackoverflow.com/q/51891921
has answer: http://stackoverflow.com/a/51892220
answer count: 3
has answer: http://stackoverflow.com/a/51892223
downvote count: 0
score: 4
tagged with: opcode
favorite count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/51892223
type: AnsweredQuestion
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51897005
has title: Understanding why theses opcodes from different codes are the same
tagged with: cpython
type: Question
has body: I would like to deeply understand why these two following generated opcodes are the same (except for the values loaded/stored). Especially how can this 'BINARY_MULTIPLY' be used for both str and int ? Does C (CPython) type checks under the hood and apply the correct function whether values are strings or ints ? And can we say that this mechanism is related to duck typing ? &gt;&gt;&gt; def tata(): ... a = 1 ... b = 1 ... c = a * b ... &gt;&gt;&gt; dis.dis(tata) 2 0 LOAD_CONST 1 (1) 3 STORE_FAST 0 (a) 3 6 LOAD_CONST 1 (1) 9 STORE_FAST 1 (b) 4 12 LOAD_FAST 0 (a) 15 LOAD_FAST 1 (b) 18 BINARY_MULTIPLY 19 STORE_FAST 2 (c) 22 LOAD_CONST 0 (None) 25 RETURN_VALUE &gt;&gt;&gt; def toto(): ... a = "1" ... b = "1" ... c = a * b ... &gt;&gt;&gt; dis.dis(toto) 2 0 LOAD_CONST 1 ('1') 3 STORE_FAST 0 (a) 3 6 LOAD_CONST 1 ('1') 9 STORE_FAST 1 (b) 4 12 LOAD_FAST 0 (a) 15 LOAD_FAST 1 (b) 18 BINARY_MULTIPLY 19 STORE_FAST 2 (c) 22 LOAD_CONST 0 (None) 25 RETURN_VALUE
tagged with: duck-typing
possible better answer: http://stackoverflow.com/a/51892220
upvote count: 4

http://stackoverflow.com/a/51931235
score: -1
has comment: http://stackoverflow.com/comment/90812955
has comment: http://stackoverflow.com/comment/90812757
upvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51930833
has comment: http://stackoverflow.com/comment/90812287
has comment: http://stackoverflow.com/comment/90812664
type: Answer
has body: On windows 10: Ctrl+Shift+P and selecting the environment gets the job done. After setting the environment, I execute by pressing Crtl+F5 to execute without debugging and F5 to debug.
downvote count: 1
answers question: http://stackoverflow.com/q/51930833

http://stackoverflow.com/comment/90641495
comment on: http://stackoverflow.com/q/51843974
score: 0
has text: Have you thought about distributing with docker? With docker for Mac and docker for Windows you can run Linux containers on all the most common operating systems, and it will provide a lot more isolation between components than merely vending dependencies. It also alleviates the need for separate distributions, especially if your code isn't pure Python
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90740351
has text: @Tim I assume that what you call an "issue" is simply a misunderstanding of how the things work. When you start a transaction you effectively tell the database that you want to execute **several** queries `at once` instead of one by one (`autocommit` means `one by one`)
type: Comment
comment on: http://stackoverflow.com/a/51859484
score: 0
type: AnswerComment

http://stackoverflow.com/a/51942932
upvote count: 1
answers question: http://stackoverflow.com/q/51930548
has comment: http://stackoverflow.com/comment/90836891
score: 1
has comment: http://stackoverflow.com/comment/90836726
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: For deploying Web Application on Azure container. The images are the import key. When the images are in the public registry, you just need to follow the steps below: Create a resource group in Azure. Create a Service Plan. Create the Web Application with the image. For more details, see Deploy a Docker/Go web app in Web App for Containers. When the images are in the private registry, here make an example with Azure Container Registry. You need one more step, set the container config for your web app like this: az webapp config container set --name &lt;app_name&gt; --resource-group &lt;resourceGroup_Name&gt; --docker-custom-image-name &lt;azure-container-registry-name&gt;.azurecr.io/&lt;image_name&gt; --docker-registry-server-url https://&lt;azure-container-registry-name&gt;.azurecr.io --docker-registry-server-user &lt;registry-username&gt; --docker-registry-server-password &lt;password&gt; For more details, see Use a Docker image from any private registry.
accepted answer of: http://stackoverflow.com/q/51930548

http://stackoverflow.com/comment/90758448
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51903599
has text: This is exactly what was needed. Thanks a million for this "aha" moment with the Not operator.

web-crawler
tags question: http://stackoverflow.com/q/51910888
tags question: http://stackoverflow.com/q/51800600
tags question: http://stackoverflow.com/q/51952658
tags question: http://stackoverflow.com/q/51932842
tags question: http://stackoverflow.com/q/51847473
tags question: http://stackoverflow.com/q/51876515
tag name: web-crawler
tags question: http://stackoverflow.com/q/51919033
type: Tag
tags question: http://stackoverflow.com/q/51907224
tags question: http://stackoverflow.com/q/51919821
tags question: http://stackoverflow.com/q/51799821
tags question: http://stackoverflow.com/q/51861443
tags question: http://stackoverflow.com/q/51943838

http://stackoverflow.com/comment/90750881
type: Comment
has text: @Aran-Fey So when i binded a value to my_list, shouldn't it be passed to the purchased_list too. Because purchased_list knows the address of my_list and no matter what functions I perform on my_list, should also happen with purchased_list?
score: 0
comment on: http://stackoverflow.com/q/51899618
type: QuestionComment

http://stackoverflow.com/comment/105588041
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51925183
has text: @bhathiya-perera If you have async libraries, you should definitely use them. `run_in_executor` is just a helper for executing legacy sync code in an async context.
score: 1

http://stackoverflow.com/comment/90668440
score: 0
has text: As I can see, it's even possible with just Flask-login: in load_user make a query to 2 collections one by one and return user if it exists as mongo's ids are cross-db unique.
type: QuestionComment
comment on: http://stackoverflow.com/q/51814146
type: Comment

http://stackoverflow.com/comment/90653086
comment on: http://stackoverflow.com/a/51849674
has text: Thanks, but I didn't get it. The idea was to have something like with contextmanager : foo() and then have foo() somehow get access to contextmanager. In your example, this seems to be done by keeping p around and using it as a bridge, which seems to not achieve the same goal.
type: AnswerComment
type: Comment
score: 2

http://stackoverflow.com/a/51843229
has comment: http://stackoverflow.com/comment/90706667
has comment: http://stackoverflow.com/comment/90758593
type: AcceptedAnswer
type: Answer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51842245
has comment: http://stackoverflow.com/comment/90730618
has body: You're just missing the step where you calculate the gradient average. Also note that instead of using class, I'm using clc: N = len(ft) for _ in range(5000): s = np.dot(ft, w) prediction = 1 / (1 + np.exp(-s)) # sigmoid function gr = np.dot(ft.T, clc - prediction) # gradient of loss function gr /= N # calculate gradient average w += 0.01 * gr # update weights Adding entire code import numpy as np from sklearn.linear_model import LogisticRegression np.random.seed(1) # for reproducibility f = 100 mean1 = [-5, -3] cov1 = [[5, 0], [0, 3]] mean2 = [4, 3] cov2 = [[3, 0], [0, 2]] g1 = np.random.multivariate_normal(mean1, cov1, f) g2 = np.random.multivariate_normal(mean2, cov2, f) ft = np.vstack((g1, g2)) # data stacked on each other cls = np.hstack((np.zeros(f), np.ones(f))) # class values in column matrix clc = np.reshape(cls,(2 * f, 1)) # class values in an array w = np.zeros((2, 1)) # weights matrix N = len(ft) for _ in range(5000): s = np.dot(ft, w) prediction = 1 / (1 + np.exp(-s)) # sigmoid function gr = np.dot(ft.T, clc - prediction) # gradient of loss function gr /= N # calculate gradient average w += 0.01 * gr # update weights print("w = {}".format(w)) lr = LogisticRegression(fit_intercept=False) lr.fit(ft, cls) print("lr.coef_ = {}".format(lr.coef_)) Output w = [[1.28459432] [1.07186532]] lr.coef_ = [[1.23311932 1.0363586 ]]
has comment: http://stackoverflow.com/comment/90767794
has comment: http://stackoverflow.com/comment/90677123
answers question: http://stackoverflow.com/q/51842245
has comment: http://stackoverflow.com/comment/90660795
score: 2
has comment: http://stackoverflow.com/comment/90651227
has comment: http://stackoverflow.com/comment/90672006
has comment: http://stackoverflow.com/comment/90663001
upvote count: 2

http://stackoverflow.com/comment/90558185
has text: What is the need for the passw argument of __init__()? And why is 'name' an argument of the password function?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51800808
type: QuestionComment

http://stackoverflow.com/a/51814546
type: Answer
score: 2
downvote count: 0
has body: As for the height, set size_hint_y: 0.5 and size_hint_y: 0.1 to TextInput and Button widgets respectively. Replace size: 400, 500 and size: 400, 100 with size_hint_x: None and width: 400 Widget » size_hint_y size_hint_y y size hint. size_hint_y is a NumericProperty and defaults to 1. See size_hint_x for more information, but with widths and heights swapped. Widget » size_hint If you don’t want to use a size_hint for either the width or height, set the value to None. Snippet BoxLayout: size_hint_y: 0.5 TextInput: size_hint_x: None width: 400 BoxLayout: size_hint_y: 0.1 Button: size_hint_x: None width: 400 Example main.py from kivy.lang import Builder from kivy.base import runTouchApp runTouchApp(Builder.load_string(''' #:kivy 1.11.0 BoxLayout: orientation: 'vertical' BoxLayout: size_hint_y: 0.5 TextInput: pos: 200, 100 size_hint_x: None width: 400 font_size: '25sp' multiline: True text: 'Summary:' BoxLayout: size_hint_y: 0.1 Button: pos: 200, 0 size_hint_x: None width: 400 text: "Back Home" font_size: '25sp' ''')) Output
answers question: http://stackoverflow.com/q/51813766
accepted answer of: http://stackoverflow.com/q/51813766
upvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/a/73716819
has comment: http://stackoverflow.com/comment/137710665
downvote count: 0
type: Answer
upvote count: 3
score: 3
answers question: http://stackoverflow.com/q/51857315
has body: It is sufficient to change event to _event.

http://stackoverflow.com/a/51903515
has body: You need the value attribute of the Enums. Then one possibility would be using a lambda with df.rename. df.rename(lambda x: x.value, axis=1, copy=False).to_json() # Out '{"hello":{"0":1,"1":2},"world":{"0":1,"1":2}}'
type: Answer
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51903414
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51903414
downvote count: 0

http://stackoverflow.com/q/51888992
tagged with: django
type: Question
tagged with: django-models
has comment: http://stackoverflow.com/comment/90762839
upvote count: 3
answer count: 2
has body: I have a long task, that is adding many records to a database table. In the table, there is a field called "end". This field will be empty until the task is done. As soon as the task is done, I will write a value in the "end" field. Can I have an HTML page, that is refreshing the page every 5 seconds with the items from the table until the field "end" has a value? Does somebody have an example script for this?
has title: Django Refresh database until end of transaction
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90728989
has answer: http://stackoverflow.com/a/51889143
type: UnansweredQuestion
tagged with: python
score: 3
downvote count: 0
has answer: http://stackoverflow.com/a/51889286

http://stackoverflow.com/comment/90642456
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51843673
type: Comment
has text: Unfortunatley pstatix that approach did not work. Can you clarify your comment @intentionally left blank, I've never used fmt so this code looks quite foreign to me.

project-lib
tag name: project-lib
tags question: http://stackoverflow.com/q/51906172
type: Tag

http://stackoverflow.com/comment/90847328
comment on: http://stackoverflow.com/a/51948774
type: Comment
score: 1
type: AnswerComment
has text: Oh, `defaultdict` nails it! Thank you!

http://stackoverflow.com/q/51895252
favorite count: 0
has title: pandas - creating data frame from json data, specific which columns to include
tagged with: python
has body: I am currently creating my data frame with the below commands getting data from url ... devices = get_device_data.json() device_data = devices["data"] p_dev = pd.DataFrame(device_data) However the json dictionary has 60 columns in, of which I only want two of them, is there a way to specify which columns to include when creating a data frame, or any way I can achieve the desired result? Thanks EDIT: some sample data with some columns deleted. I actually only want the id and hostname columns [ { "id": 474378238 "account": "https: //www.****.com/api/v2/accounts/38021/", "bsid": None, "carrier": "BOB", "carrier_id": "BOB BOB", "channel": None, "connection_state": "connected", "gsn": "356853050758871", "homecarrid": "BOB", "hostname": "BOB1345345", "is_asset": True, "is_gps_supported": True, "is_upgrade_available": False, "is_upgrade_supported": True, "ltebandwidth": "20 MHz", "mac": None, "serial": "356853050758871", "service_type": "LTE", "ssid": None, "summary": "connected", "txchannel": "19667", "type": "mdm", "uid": "f5a8da8f", "updated_at": "2018-08-17T11:19:57.019938+00:00", "uptime": 86412.8558200002, }, { "id": 5674657356 "account": "https: //www.****.com/api/v2/accounts/38021/", "bsid": None, "carrier": "BOB", "carrier_id": "BOB BOB", "channel": None, "connection_state": "connected", "gsn": "356853050758871", "homecarrid": "BOB", "hostname": "BOB10765", "is_asset": True, "is_gps_supported": True, "is_upgrade_available": False, "is_upgrade_supported": True, "ltebandwidth": "20 MHz", "mac": None, "serial": "356853050758871", "service_type": "LTE", "ssid": None, "summary": "connected", "txchannel": "19667", "type": "mdm", "uid": "f5a8da8f", "updated_at": "2018-08-17T11:19:57.019938+00:00", "uptime": 86412.8558200002, }, { "id": 5674657465 "account": "https: //www.****.com/api/v2/accounts/38021/", "bsid": None, "carrier": "BOB", "carrier_id": "BOB BOB", "channel": None, "connection_state": "connected", "gsn": "356853050758871", "homecarrid": "BOB", "hostname": "BO…
has answer: http://stackoverflow.com/a/51895399
type: AnsweredQuestion
score: 1
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/90741052
downvote count: 0
possible better answer: http://stackoverflow.com/a/51895399
tagged with: pandas
upvote count: 1
has answer: http://stackoverflow.com/a/51895705
accepted answer: http://stackoverflow.com/a/51895705

http://stackoverflow.com/comment/90908664
score: 0
type: AnswerComment
has text: botocore.exceptions.ClientError: An error occurred (ValidationException) when calling the BatchWriteItem operation: The provided key element does not match the schema
type: Comment
comment on: http://stackoverflow.com/a/51964622

http://stackoverflow.com/comment/90873655
comment on: http://stackoverflow.com/q/51950281
has text: @MohanRadhakrishnan yes there are no problems, but I don't understand why in jupyter or terminal I can use GPU and in PyCharm can't.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51949872
has answer: http://stackoverflow.com/a/51953595
tagged with: elasticsearch
tagged with: python
linked to: http://stackoverflow.com/q/46471922
favorite count: 0
tagged with: python-3.x
linked to: http://stackoverflow.com/q/50961773
possible better answer: http://stackoverflow.com/a/51953595
has comment: http://stackoverflow.com/comment/98824619
upvote count: 1
linked to: http://stackoverflow.com/q/20288770
linked to: http://stackoverflow.com/q/49556729
type: AnsweredQuestion
tagged with: elastic-stack
score: 1
type: Question
has title: Reading Elastic cluster data into python data frame
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/51954295
has body: I am pretty new with elasticsearch. so, please forgive if i am asking a very simple question. In my workplace we have a proper setup of ELK. Due to the very large volume of data we are just storing 14 days of data and my question is how can i read the data in Python and later store my analysis in some NOSQL. As of now my primary goal is to read the raw data into python in the form of data frame or any format from the elastic cluster. I want to get it for different time intervals like 1 day, 1 week, 1 month etc.. I am struggling for the last 1 week.
tagged with: python-2.7
accepted answer: http://stackoverflow.com/a/51954295

http://stackoverflow.com/a/51914397
type: AcceptedAnswer
type: Answer
has body: Since you want to capture all the text before the date substring regardless, it looks like all you have to do is include dashes and underscores in the initial group: ([\w-_]+) (and drop the following group that captures an optional standalone dash): You may also use ^ and $ to ensure that matches span the entire line: ^([\w-_]+)(\d{4}\d{2}\d{2})(\w+)?(\.csv|\.dat|\.txt)?$ https://regex101.com/r/M5kIo6/1
accepted answer of: http://stackoverflow.com/q/51914342
answers question: http://stackoverflow.com/q/51914342
score: 0

mechanicalsoup
tag name: mechanicalsoup
tags question: http://stackoverflow.com/q/51914581
type: Tag

xml-parsing
tags question: http://stackoverflow.com/q/51931167
tags question: http://stackoverflow.com/q/51929779
tag name: xml-parsing
type: Tag
tags question: http://stackoverflow.com/q/51860927

http://stackoverflow.com/q/51910421
has answer: http://stackoverflow.com/a/51911021
upvote count: 1
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90771712
accepted answer: http://stackoverflow.com/a/51911021
score: 1
type: Question
has answer: http://stackoverflow.com/a/51910552
tagged with: numpy
linked to: http://stackoverflow.com/q/4432208
has comment: http://stackoverflow.com/comment/90771701
has comment: http://stackoverflow.com/comment/90772415
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/90771963
possible better answer: http://stackoverflow.com/a/51910552
favorite count: 0
has title: How can I set a range to work with numpy's arange
has comment: http://stackoverflow.com/comment/90772172
has comment: http://stackoverflow.com/comment/90772042
has comment: http://stackoverflow.com/comment/90772350
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90771765
has body: I am trying to create a weather widget in a Flask application. I am stuck on working with wind direction in degrees (angle). If we use the following image as a representation: Wind Directions When working with wind direction we are limited to a 360 degree range. I would like to assign an icon based on which range within 360 degrees I get for wind direction, to help you understand here is some information: | Cardinal Direction | Degree Direction | |:------------------:|------------------| | N | 348.75 - 11.25 | | NNE | 11.25 - 33.75 | | NE | 33.75 - 56.25 | | ENE | 56.25 - 78.75 | | E | 78.75 - 101.25 | | ESE | 101.25 - 123.75 | | SE | 123.75 - 146.25 | | SSE | 146.25 - 168.75 | | S | 168.75 - 191.25 | | SSW | 191.25 - 213.75 | | SW | 213.75 - 236.25 | | WSW | 236.25 - 258.75 | | W | 258.75 - 281.25 | | WNW | 281.25 - 303.75 | | NW | 303.75 - 326.25 | | NNW | 326.25 - 348.75 | I will store the keys/values in a dict and create an if elif else loop that will do something like the following: from numpy import arange degrees = the_json_response['wind']['deg'] wind_directions = { 'N': arange(348.75, 11.25, 0.25), ... } degrees_range = range(0, 360) if degrees in wind_direction['N']: dirction = north_icon elif degrees in wind_direction['NNE']: direction = north_north_east_icon The above is only pseudo code.. To summarize, How can I apply this so that we only ever work with a 360 degree range because obviously it will throw errors when working with North wind direction due to it being in a range of 348.75 - 11.25, we need to tell it we are working with 360 degrees. The reason I cannot for the life of my figure this out is I never learnt complex mathmatics (which to me this is). If anyone has a suggestion on how I can apply this in a better way I am very open to those suggestions.

http://stackoverflow.com/q/51824213
has comment: http://stackoverflow.com/comment/90603046
tagged with: dataframe
type: Question
answer count: 2
tagged with: pandas
score: 2
has comment: http://stackoverflow.com/comment/90604177
accepted answer: http://stackoverflow.com/a/51824434
downvote count: 0
favorite count: 0
linked to: http://stackoverflow.com/q/464864
possible better answer: http://stackoverflow.com/a/51824555
has body: i have a dataset where I want to split the data set based on the column values. At every iteration, the training set will include all data except those that belong to 2 values which will be kept for test set. As an example, we have column x with values a, b, c, d, e and f. At the moment I am doing a manual selection but since I want to try it for every possible combinations, I am not sure how best to do that. train = df.loc[~df['x'].isin(['a','b'])] test = df.loc[df['x'].isin(['a','b'])] How do I change this code to consider all possible combinations? I would also like to be able to print these combinations to see the combinations that were used for training and test sets.
tagged with: python
has answer: http://stackoverflow.com/a/51824555
upvote count: 2
has title: how to split data into train and test based on a column values and shuffle the combinations?
has answer: http://stackoverflow.com/a/51824434
type: AnsweredQuestion

http://stackoverflow.com/a/51995066
downvote count: 0
answers question: http://stackoverflow.com/q/51956370
has comment: http://stackoverflow.com/comment/90941306
has body: You have to call one of the pygame event functions (e.g. pygame.event.pump() or pygame.event.get()) each frame or the window will become unresponsive and the program will appear to have crashed. If you call one of those functions, you should be able to press Alt+Tab (in Windows) to get back to the desktop without crashing the program (if you select the desktop, the window will be minimized and if you select another window, it will just be brought to the front). def main(display_state_object): running = True while running: for event in pygame.event.get(): if event.type == pygame.KEYDOWN: # Press Esc to quit. if event.key == pygame.K_ESCAPE: running = False if display_state_object.get_state(): SCREEN.fill(BACKGROUND) pygame.display.flip() else: return 1 return
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51956370
has comment: http://stackoverflow.com/comment/90940627
score: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/90586760
score: 0
type: AnswerComment
has text: Oh your answer really helped me. Thanks. I didn't think about using **isinstance** function. I also didn't know at all that I could recommend to the user about the type of the variable the function expects. Thanks again.
type: Comment
comment on: http://stackoverflow.com/a/51816066

http://stackoverflow.com/comment/90687944
type: QuestionComment
comment on: http://stackoverflow.com/q/51867912
score: 0
has text: Sure, and once they are defined e.g. in PEP-8, then they are no longer opinion-based ;) And what you are asking is not defined in a PEP, so the best answer you can get is that it is not defined, or many conflicting answers based on users' opinions - which is why such questions are off topic ;)
type: Comment

http://stackoverflow.com/q/51880405
has body: Suppose I have the following 2 dataframes: One where I have a time series which contains missing price values (column 'val') for different id's: import pandas as pd df1 = pd.DataFrame({'id': ['1', '1', '1', '2', '2'], 'year': [2013, 2014, 2015, 2012, 2013], 'val': [np.nan, np.nan, 300, np.nan, 150]}) df1 Which looks like: id year val 0 1 2013 NaN 1 1 2014 NaN 2 1 2015 300.0 3 2 2012 NaN 4 2 2013 150.0 One where I have an price index series over time, where I can calulate the factor of price inflation between different years: df2 = pd.DataFrame({'year': [2011, 2012, 2013, 2014, 2015], 'index': [100, 103, 105, 109, 115]}) df2['factor'] = df2['index'] / df2['index'].shift() df2 Which looks like: year index factor 0 2011 100 NaN 1 2012 103 1.030000 2 2013 105 1.019417 3 2014 109 1.038095 4 2015 115 1.055046 Now suppose I want to do backward indexation for the most recently available price value for a given id (item) using the factor of the second dataframe. Which is the most efficient way of doing this? So far I tried the following (but this loop is very slow for the large dataset i use, because it only fills 1 time period back for each loop): df1 = df1.merge(df2'year', 'factor', how = 'left', on = 'year') missings = df1['val'].sum() while df1['val'].isnull().sum() &lt; missings: missings = df1['val'].isnull().sum() df1.loc[df1['val'].notnull(), 'factor'] = 1 df1['val'] = df1.groupby('id')['val'].fillna(method='bfill', limit=1) df1['val'] = df1['val'] / df1['factor'] df1.drop(columns = 'factor').head() Which yields the following results: id year val 0 1 2013 283.486239 1 1 2014 288.990826 2 1 2015 300.000000 3 2 2012 145.631068 4 2 2013 150.000000 So the value for 2014: 300 / 1.038095. And the value for 2013: 300 / 1.038095 / 1.019417. Is there any better and faster way to achieve the same results? Thanks in advance!
score: 2
type: AnsweredQuestion
upvote count: 2
has comment: http://stackoverflow.com/comment/90712569
has comment: http://stackoverflow.com/comment/90712432
type: Question
has answer: http://stackoverflow.com/a/51898753
tagged with: time-series
has comment: http://stackoverflow.com/comment/90712343
tagged with: missing-data
has comment: http://stackoverflow.com/comment/90712506
has comment: http://stackoverflow.com/comment/90712350
tagged with: pandas
has comment: http://stackoverflow.com/comment/90747775
answer count: 1
has title: Pandas indexation missing values
downvote count: 0
accepted answer: http://stackoverflow.com/a/51898753
favorite count: 0
has comment: http://stackoverflow.com/comment/90804242
has comment: http://stackoverflow.com/comment/90713229
has comment: http://stackoverflow.com/comment/90712372
tagged with: python

pca
tag name: pca
tags question: http://stackoverflow.com/q/51897313
tags question: http://stackoverflow.com/q/51900109
type: Tag
tags question: http://stackoverflow.com/q/51884727
tags question: http://stackoverflow.com/q/51855080
tags question: http://stackoverflow.com/q/51926849

http://stackoverflow.com/comment/90565888
has text: First of all, it is not good to overwrite an existing keyword, in this case `eval`
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51805043

http://stackoverflow.com/comment/90782385
score: 0
type: Comment
has text: thanks sir,yes, its was giving error for that `request` in that line, but can i know why it was raising error?
type: AnswerComment
comment on: http://stackoverflow.com/a/51916116

http://stackoverflow.com/a/56354392
score: 0
type: Answer
has body: Well, K-Means is a clustering Algorithm so you can use it to cluster the movies based on the genres. Columns: movieId, genres There's a new dataset which includes relevant tags for each movie, so you can also cluster them based on those tags. However, you can also make use of K-Nearest Neighbors to find out how users are similar to each other. In the reviews dataset, you would use the following columns: Columns: userId, rating While in the movies dataset you would use the movieId. The idea is to figure out which movies every user has viewed, then use those movies to compute the similarity index of users (eg; user1, user2)
answers question: http://stackoverflow.com/q/51877919

http://stackoverflow.com/comment/90692968
comment on: http://stackoverflow.com/q/51842008
score: 0
type: Comment
has text: Thanks to @pacholik for detailed answer. His explanation cleared everething up for me and his suggestion solved my problem
type: QuestionComment

object
tags question: http://stackoverflow.com/q/51940769
tag name: object
tags question: http://stackoverflow.com/q/51829362
tags question: http://stackoverflow.com/q/51918136
tags question: http://stackoverflow.com/q/51853732
tags question: http://stackoverflow.com/q/51889876
tags question: http://stackoverflow.com/q/51954210
tags question: http://stackoverflow.com/q/51876378
tags question: http://stackoverflow.com/q/51828012
tags question: http://stackoverflow.com/q/51887086
type: Tag
tags question: http://stackoverflow.com/q/51863302
tags question: http://stackoverflow.com/q/51912613
tags question: http://stackoverflow.com/q/51873651
tags question: http://stackoverflow.com/q/51912655

http://stackoverflow.com/a/51824838
answers question: http://stackoverflow.com/q/51824628
has comment: http://stackoverflow.com/comment/122989167
type: AcceptedAnswer
score: 54
has body: &gt;&gt; pip install pycryptodome from Crypto.Cipher import AES #Works or &gt;&gt; pip install pycryptodomex from Cryptodome.Cipher import AES For python3 the package name is now pycryptodome or pycryptodomex If you need compatibility with your project with Python2 use pycryptodome or else use pycryptodomex which is a library independent of the old PyCrypto.
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/90708807
has comment: http://stackoverflow.com/comment/123858626
upvote count: 54
accepted answer of: http://stackoverflow.com/q/51824628

http://stackoverflow.com/a/51853198
has comment: http://stackoverflow.com/comment/90659146
type: Answer
has body: This variable is timezone-aware: datetime.now(timezone.utc) whereas this is not: last_run = (row[4]) In which case, you can add timezone information to the latter using last_run = row[4].astimezone(timezone.utc) last_run = row[4].replace(tzinfo=timezone.utc) # if db is already in UTC The complete example becomes cursor.execute("SELECT * FROM tbl_rpt_log") reports_to_run = cursor.fetchall() for row in reports_to_run : last_run = row[4].astimezone(timezone.utc) time_since_last_request = datetime.now(timezone.utc) - last_run
accepted answer of: http://stackoverflow.com/q/51853132
upvote count: 1
answers question: http://stackoverflow.com/q/51853132
score: 1
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/90566799
has text: The problem is that `node = node.right` doesn't modify anything. All it does is rebind the local variable`node` to be a name for what used to be `node.right` instead of a name for the original `node`. You need to either pass the parent node down the recursive chain so it can be modified, or pass the change information up the chain and modify things on the way up. (The latter is probably more complicated to reason about and to implement, but it might be worth considering if you're going to add self-balancing later.)
type: Comment
score: 0
comment on: http://stackoverflow.com/q/51805571
type: QuestionComment

http://stackoverflow.com/comment/90843108
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51929345
has text: I updated examples. Now you can see that image actually can have segments with different colors, and every segment must be extracted.
type: AnswerComment

http://stackoverflow.com/comment/90817944
type: QuestionComment
has text: If you try it with a tuple instead of a list, it does the exact same thing. If you try it with a dict instead of a list, it does the same thing, but with the keys of the dict (and, before Python 3.7, those are in an arbitrary order). More generally, with any iterable type, it iterates all of the elements of that value, and you can read the docs for that type to see what that means.
score: 0
comment on: http://stackoverflow.com/q/51933830
type: Comment

http://stackoverflow.com/comment/90823830
has text: Could you describe a single problem in-depth along with the context of that problem? There are numerous approaches to feature selection and there is no single answer to your question. How you perform feature selection could depend on the type of model you're using and what exactly your features are.
type: QuestionComment
comment on: http://stackoverflow.com/q/51936644
type: Comment
score: 3

http://stackoverflow.com/q/51952253
accepted answer: http://stackoverflow.com/a/51953466
has comment: http://stackoverflow.com/comment/90855170
has comment: http://stackoverflow.com/comment/90855374
has comment: http://stackoverflow.com/comment/90855388
has comment: http://stackoverflow.com/comment/90854803
has comment: http://stackoverflow.com/comment/90855301
tagged with: python
tagged with: merge
downvote count: 1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90854841
has comment: http://stackoverflow.com/comment/90854914
type: Question
has comment: http://stackoverflow.com/comment/90854941
has answer: http://stackoverflow.com/a/51953466
upvote count: 0
has title: merge some data with pandas
has comment: http://stackoverflow.com/comment/90855281
answer count: 1
score: -1
tagged with: pandas
has body: I have some data like this: df = pd.DataFrame ({'code': ['A', 'A','A' ,'B', 'B','B', 'C'], 'type' : ['a', 'a', 'b', 'c', 'c', 'c', 'd'], 'start': ['2017-1-1', '2018-5-5', '2017-5-21', '2017-6-6','2017-7-8','2017-8-9','2018-5-1'], 'end': ['2017-5-20', 'now', '2017-5-4', '2017-7-7','2017-8-8','now','now']}) ╔═══╦══════╦══════╦═══════════╦═══════════╗ ║ ║ code ║ type ║ start ║ end ║ ╠═══╬══════╬══════╬═══════════╬═══════════╣ ║ 0 ║ A ║ a ║ 2017-1-1 ║ 2017-5-20 ║ ╠═══╬══════╬══════╬═══════════╬═══════════╣ ║ 1 ║ A ║ a ║ 2018-5-5 ║ now ║ ╠═══╬══════╬══════╬═══════════╬═══════════╣ ║ 2 ║ A ║ b ║ 2017-5-21 ║ 2017-5-4 ║ ╠═══╬══════╬══════╬═══════════╬═══════════╣ ║ 3 ║ B ║ c ║ 2017-6-6 ║ 2017-7-7 ║ ╠═══╬══════╬══════╬═══════════╬═══════════╣ ║ 4 ║ B ║ c ║ 2017-7-8 ║ 2017-8-8 ║ ╠═══╬══════╬══════╬═══════════╬═══════════╣ ║ 5 ║ B ║ c ║ 2017-8-9 ║ now ║ ╠═══╬══════╬══════╬═══════════╬═══════════╣ ║ 6 ║ C ║ d ║ 2018-5-1 ║ now ║ ╚═══╩══════╩══════╩═══════════╩═══════════╝ and I want to convert it as shown below using pandas: ╔═══╦══════╦══════╦═══════════╦═══════════╗ ║ ║ code ║ type ║ start ║ end ║ ╠═══╬══════╬══════╬═══════════╬═══════════╣ ║ 0 ║ A ║ a ║ 2017-1-1 ║ 2017-5-20 ║ ╠═══╬══════╬══════╬═══════════╬═══════════╣ ║ 1 ║ A ║ a ║ 2018-5-5 ║ now ║ ╠═══╬══════╬══════╬═══════════╬═══════════╣ ║ 2 ║ A ║ b ║ 2017-5-21 ║ 2017-5-4 ║ ╠═══╬══════╬══════╬═══════════╬═══════════╣ ║ 3 ║ B ║ c ║ 2017-6-6 ║ now ║ ╠═══╬══════╬══════╬═══════════╬═══════════╣ ║ 4 ║ C ║ d ║ 2018-5-1 ║ now ║ ╚═══╩══════╩══════╩═══════════╩═══════════╝ The data needs to be merged on code and type fields for which the date values form a continuous date range(like the dates [2017-6-6], [2017-7-7], [2017-7-8], [2017-8-8], [2017-8-9], now can be merged into [2017-6-6] to now). If the dates are not continuous then they should not be grouped/merged and no changes to the start and end. How can I achieve this?
has comment: http://stackoverflow.com/comment/90855131
favorite count: 0

facet-grid
tags question: http://stackoverflow.com/q/51891370
type: Tag
tags question: http://stackoverflow.com/q/51876744
tags question: http://stackoverflow.com/q/51837338
tag name: facet-grid

algorithm
tags question: http://stackoverflow.com/q/51812452
tag name: algorithm
tags question: http://stackoverflow.com/q/51823927
tags question: http://stackoverflow.com/q/51816005
tags question: http://stackoverflow.com/q/51914145
tags question: http://stackoverflow.com/q/51894043
tags question: http://stackoverflow.com/q/51859489
tags question: http://stackoverflow.com/q/51940548
tags question: http://stackoverflow.com/q/51914544
tags question: http://stackoverflow.com/q/51805471
tags question: http://stackoverflow.com/q/51889381
tags question: http://stackoverflow.com/q/51893702
tags question: http://stackoverflow.com/q/51930752
tags question: http://stackoverflow.com/q/51848913
tags question: http://stackoverflow.com/q/51881599
tags question: http://stackoverflow.com/q/51869907
tags question: http://stackoverflow.com/q/51945233
tags question: http://stackoverflow.com/q/51844794
tags question: http://stackoverflow.com/q/51918128
type: Tag
tags question: http://stackoverflow.com/q/51954069
tags question: http://stackoverflow.com/q/51834467
tags question: http://stackoverflow.com/q/51897251
tags question: http://stackoverflow.com/q/51848999
tags question: http://stackoverflow.com/q/51950193
tags question: http://stackoverflow.com/q/51948286
tags question: http://stackoverflow.com/q/51846957
tags question: http://stackoverflow.com/q/51827510
tags question: http://stackoverflow.com/q/51804721
tags question: http://stackoverflow.com/q/51919407
tags question: http://stackoverflow.com/q/51904479
tags question: http://stackoverflow.com/q/51832310
tags question: http://stackoverflow.com/q/51912354
tags question: http://stackoverflow.com/q/51818193
tags question: http://stackoverflow.com/q/51881460
tags question: http://stackoverflow.com/q/51936481

http://stackoverflow.com/a/51806926
has body: If you have NaNs in the input data, I would think you want to use np.nanmedian to ignore NaNs from the median calculation. Going with it, we can use the combined mask for the upper and lower thresholds to set the invalid ones to NaNs as well and finally use np.nanmean - a = data_tsl.values # use data_tsl.values.copy() to avoid editing input df med = np.nanmedian(a,axis=1) U = maxval*med L = minval*med a[(a &gt;= U[:,None]) | (a &lt;= L[:,None])] = np.nan out = np.nanmean(a,axis=1)
answers question: http://stackoverflow.com/q/51806750
score: 2
has comment: http://stackoverflow.com/comment/90579505
accepted answer of: http://stackoverflow.com/q/51806750
has comment: http://stackoverflow.com/comment/90578992
type: AcceptedAnswer
downvote count: 0
upvote count: 2
type: Answer

http://stackoverflow.com/comment/90684824
comment on: http://stackoverflow.com/q/51866285
has text: Why should an email address include first and last names? Most don't. But in any case, if you can get the f_name and the l_name, all you have to do is convert them to lower case, concatenate them with a period in between and then see if that is a substring of the email field. Then do it for every row.
type: QuestionComment
type: Comment
score: 1

http://stackoverflow.com/comment/90794949
score: 0
comment on: http://stackoverflow.com/q/51922622
has text: I should point out that in general, in Numpy, you don't usually find "the first of…", you find "all of…" (maybe ever in parallel), and then just use the first one or vectorize (or sometimes iterate over) all of them. So, if short-circuiting at the first one is important for correctness, or is expected to give you more performance gain than vectorizing does, you may need to loop.
type: QuestionComment
type: Comment

http://stackoverflow.com/q/51940703
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/90831226
has title: How come my python script can't properly import installed libraries on windows
tagged with: windows-10
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90831461
answer count: 0
has comment: http://stackoverflow.com/comment/90832844
tagged with: pip
has comment: http://stackoverflow.com/comment/90867072
type: Question
has comment: http://stackoverflow.com/comment/90831265
has body: I have python installed in the default location C:\Python27. I installed pip and was able to install libraries The libraries got installed in C:\Python27\Lib\site-packages. When I run the python interpreter I can successfully import the libraries but when I run a python file it gives an Import Error. I was wondering how to fix this.
has comment: http://stackoverflow.com/comment/90831224

http://stackoverflow.com/comment/90573298
has text: Hey @Divakar, I actually did. `a running window of size 2 and skip lengths of 2 should result in: [2, 7, 2, 0] since the first window is 3, 5, the second window is 1,8 etc. `
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51808573
score: 0

http://stackoverflow.com/a/51818089
upvote count: 1
score: 1
has body: You could try with something like this: x = 'col_name' [my_function(df[x], df[col]) for col in df if col!=x] Example: df = pd.DataFrame( {'a':[1,2],'b':[4,3],'c':[5,9], 'd':[2,9]}) x = 'a' df1 = pd.DataFrame({}) def my_function(a,b, name): c = a+b df1[name] = c [my_function(df[x], df[col], name) for name, col in enumerate(df) if col!=x] print df1 Output: 1 2 3 0 5 6 3 1 5 11 11
downvote count: 0
answers question: http://stackoverflow.com/q/51817573
has comment: http://stackoverflow.com/comment/90619362
has comment: http://stackoverflow.com/comment/90622827
type: Answer

http://stackoverflow.com/q/51882838
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90717551
possible better answer: http://stackoverflow.com/a/51883000
has body: I'm learning Python, so I decided to code something to joke with a friend. Basically the project is about helping Anderson to reach the car. The 'A' will move in every D input from the user. I made my map a list (file Anderson.py, line 5) but I can't delete those spaces from the list. I keep having a ValueError: list.remove(x): x not in list. main: from Andershow import Anderson if __name__ == "__main__": anderson = Anderson anderson.icon = 'A' icon = anderson.icon print("Ajude o anderson a chegar até o carro!") anderson.print_map() for x in range(1, 5): comando = input("GO:") if comando == "D": anderson.walk(comando) print(anderson.Anderson.map_area) Anderson.py class Anderson: icon = '' comando = '' map_area = list("A Carro") resultado = '' def __init__(self, icon, map): self.icon = 'A' self.map = map def walk(comando): icon = 'A' map_area = list("A Carro") resultado = '' if comando == "D": for items in map_area: map_area.remove(resultado) joining = "".join(map_area) def print_map(): print("A Carro") That's it from now! Thank you so much!
has answer: http://stackoverflow.com/a/51883000
score: 0
has answer: http://stackoverflow.com/a/51883257
answer count: 3
has answer: http://stackoverflow.com/a/51883024
has comment: http://stackoverflow.com/comment/90717513
has comment: http://stackoverflow.com/comment/90717497
has comment: http://stackoverflow.com/comment/90717388
tagged with: python
accepted answer: http://stackoverflow.com/a/51883257
has title: Deleting elements from a List
has comment: http://stackoverflow.com/comment/90718301
has comment: http://stackoverflow.com/comment/90717614

http://stackoverflow.com/q/51860990
answer count: 2
has body: I have a DF as shown below. DF_Old = ID NER tID POS token R 1 B-ORG 1 NNP univesity "OrgBased_In+university of washington seismology lab.*wash" 1 I-ORG 1 IN of "OrgBased_In+university of washington seismology lab.*wash" 1 I-ORG 1 NNP washington"OrgBased_In+university of washington seismology lab.*wash" 1 I-ORG 1 NNP seismology"OrgBased_In+university of washington seismology lab.*wash" 1 L-ORG 1 NNP lab "OrgBased_In+university of washington seismology lab.*wash" 1 U-LOC 22 NNP wash "OrgBased_In+university of washington seismology lab.*wash" All columns should be pretty self-explaining except column R. This column contains the label of the row (OrgBased_In) with its direction. Meaning the characters after the "+" and before the "*" belong to the first argument and the characters after the "*" belong to the second argument. I now want to filter that vital information (and the Label of the NER) into a new column Relations. I perfomed many necessary steps to get my desired DF DF["Re"]= DF.R.str.findall(r"(Kill|Live_In|Located_In|OrgBased_In|Work_For)\+").str.join(',') DF["Re"]= DF["Re"].str.split(',').apply(set).str.join(',') DF["Argument1"] = DF["R"].str.split('+').str[+1] DF["Argument1"] = DF["Argument1"].str.split('*').str[0] DF["Argument2"] = DF["R"].str.split('*').str[-1] DF["Argument2"] = DF["Argument2"].str.split(',').str[0] DF["Argument1"] = DF["Argument1"].fillna("N") DF["Argument2"] = DF["Argument2"].fillna("N") conditions = [[x[0] in x[1] for x in zip(DF['token'].replace("-\d[\d]*","", regex=True), DF['Argument1'])], [x[0] in x[1] for x in zip(DF['token'].replace("-\d[\d]*","", regex=True), DF['Argument2'])]] choices = ["ARG1", "ARG2"] DF["ARG"] = np.select(conditions, choices, default="O") DF["Re"] = used_testing_global["Re"].str.split(',').str[0] DF["Relations"] = DF["Re"] + "-" + DF["ARG"] + "-" + DF["NER"].str.split("-").str[0] And dropping all unnecessary columns I get this (correct) result: DF_New = ID NER tID POS token Re ARG Relations 1 B-ORG 1 NNP uni…
downvote count: 0
tagged with: string
favorite count: 0
accepted answer: http://stackoverflow.com/a/51901362
tagged with: pandas
has title: Multiple entries in one column changing output in pandas Dataframe
tagged with: python
has answer: http://stackoverflow.com/a/51901362
score: 2
possible better answer: http://stackoverflow.com/a/51898586
type: Question
type: AnsweredQuestion
tagged with: dataframe
upvote count: 2
has answer: http://stackoverflow.com/a/51898586

http://stackoverflow.com/comment/90849348
type: Comment
type: QuestionComment
has text: Same thing: I assume the `Book` model has the price, your total_price is just an aggregation as well. Actually the Django [documentation on aggregation](https://docs.djangoproject.com/en/dev/topics/db/aggregation/) contains an example that's very similar to your case.
score: 0
comment on: http://stackoverflow.com/q/51949189

http://stackoverflow.com/comment/90649189
has text: @Aakib than it should be simple regex with `\d{n}` for n-length number instead of patterns for days and months ranges.
type: Comment
comment on: http://stackoverflow.com/a/51847754
type: AnswerComment
score: 0

http://stackoverflow.com/comment/90796119
type: Comment
comment on: http://stackoverflow.com/a/51880542
type: AnswerComment
score: 0
has text: I means `requests` parameters include header and data. Or i forgot some parameters to use?

http://stackoverflow.com/comment/90739317
type: QuestionComment
type: Comment
score: 2
has text: Ok, so presumably you have written some code? What are you struggling with and what is your question? At the moment this is just a statement of what you want. Please see [how to ask](https://stackoverflow.com/help/how-to-ask)
comment on: http://stackoverflow.com/q/51894381

http://stackoverflow.com/a/51902905
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51902851
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51902851
type: Answer
downvote count: 0
has body: This line: foo = main_pb2.Foo should have been: foo = main_pb2.Foo() I wasn't calling the constructor. That fixes the error.
score: 1

http://stackoverflow.com/comment/90806908
has text: Your second script expects to read from `stdin` on `input("Select the keyword preset you want to use:")` But you are not providing any for the invoked subprocess as far as I can see
comment on: http://stackoverflow.com/q/51928521
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/comment/90828571
has text: @rahlf23 would it make a difference if index 'Year' was removed from the table, leaving only 'Rotation' in index ?
comment on: http://stackoverflow.com/q/51937806
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90831232
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51930548
type: QuestionComment
has text: @CharlesXu-MSFT I didnt get you question. I have saved the image on azure container registry and then simply creating the web app, while creating I am selecting the docker option and in the container settings I am selecting the azure container registry, that how I am doing it.

http://stackoverflow.com/comment/90640616
has text: @Tendero ToolButton is not QToolButton, QToolButton is toolButton inside ToolButton, check the code well, Do you understand my code?
comment on: http://stackoverflow.com/a/51830109
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/90611003
has text: If you're using Python 2.6 or 3.2 or something, it may be that the last version of `dateutil` that works with your Python was 2 years ago, but that's just because you're using a Python that's way past end-of-life, not because `dateutil` is.
score: 0
comment on: http://stackoverflow.com/q/51828219
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51943032
has comment: http://stackoverflow.com/comment/90836304
has body: See this question: how use grid search with fit generator in keras The first answer seems answer your question.
type: Answer
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/90837195
has comment: http://stackoverflow.com/comment/90836828
answers question: http://stackoverflow.com/q/51940417
downvote count: 0
has comment: http://stackoverflow.com/comment/90840765
has comment: http://stackoverflow.com/comment/90839037
has comment: http://stackoverflow.com/comment/90841695

http://stackoverflow.com/a/51840978
has body: Based on the comments you have added and the line File "C:\Python\Python35-32\lib\site- packages\aiohttp\protocol.py", line 11, in &lt;module&gt; from wsgiref.handlers import format_date_time ImportError: cannot import name 'format_date_time' The problem seems to be that 'format_date_time' could not be imported from the built in library wsgiref. Turns out that the file ...\Python35-32\lib\wsgiref\handlers.py was completely empty indicating that something corrupted your python installation. Two possible solutions: Reinstall your python completely which also has the benefit of solving other potential corruptions that you might not have noticed yet (Note that the underlying cause for this corruption remains unknown) Go into the Cython git and copy the contents of the handlers.py into the local file. This is a very specific solution however and you should be aware that other parts of your python installation might also be corrupt.
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51839909
answers question: http://stackoverflow.com/q/51839909
score: 4
type: AcceptedAnswer
type: Answer
upvote count: 4

http://stackoverflow.com/comment/90659259
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51853350
has text: Jezrael your solution worked. If you post your solution as the answer, instead of a comment, I'll mark it as the answer in the future when my time restriction is up.

http://stackoverflow.com/comment/90695431
type: Comment
score: 1
has text: @SteveBarnes: `file` is not a keyword (see `keyword.kwlist`). It used to be an alias for `open` in the old python 2, but we have gone past that a long time ago. I tend to avoid it myself, but the OP used it.
type: AnswerComment
comment on: http://stackoverflow.com/a/51871865

http://stackoverflow.com/q/51873147
has comment: http://stackoverflow.com/comment/90731751
has comment: http://stackoverflow.com/comment/90703402
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90713308
tagged with: python
has comment: http://stackoverflow.com/comment/90731770
has comment: http://stackoverflow.com/comment/90707799
answer count: 0
type: UnansweredQuestion
has body: In my test, a function on a router/switch to be executed via CLI. The function I speak via CLI as a query, and the function does exactly what it should. Problem now, the unit test, how do I build this? Output should be: a.) Connect to SSH Works / does not work b.) prompt opens Works / does not work c.) Command (AAA Accounting) is executed Works / does not work d.) command accounting disable is listed Works / does not work e.) Now, of course, the test should make an output accordingly. I had looked at some examples but just can not get on. I used Python 3.7 with the packages Paramiko I am happy to answer any questions and would be very happy if one or the other could answer accordingly. This is the function (a part !) I have implemented so far. This also works: s = SSH(host='172.xxx.xxx.xxx', username='xxxx', password='xxxx') s.query_interactive = True if s.login(): q = s.query('aaa') #CLI function open #accounting disable function q = s.query('accounting disable') # show information q = s.query('show config') print('sysinfo:', q)
has comment: http://stackoverflow.com/comment/90704173
tagged with: paramiko
type: Question
tagged with: python-2.7
score: 0
has title: Create Unitest out of SSH Session / Router CLI
has comment: http://stackoverflow.com/comment/90713207

http://stackoverflow.com/a/51918815
downvote count: 1
has comment: http://stackoverflow.com/comment/90789387
answers question: http://stackoverflow.com/q/51918580
has comment: http://stackoverflow.com/comment/90789277
upvote count: 0
has comment: http://stackoverflow.com/comment/90789319
type: Answer
score: -1
has body: Depending on the distribution you want, you could do this: import random def random_separated(n, start, stop, gap): numbers = [] for i in range(n): while True: num = random.randint(start, stop) if all(n - gap &lt; num &lt; n + gap for n in numbers): break numbers.append(num) return numbers

http://stackoverflow.com/q/51953748
has answer: http://stackoverflow.com/a/51954265
linked to: http://stackoverflow.com/q/34142485
tagged with: dot-product
has answer: http://stackoverflow.com/a/51954071
tagged with: numpy
downvote count: 0
has answer: http://stackoverflow.com/a/51958766
favorite count: 0
tagged with: python
possible better answer: http://stackoverflow.com/a/51954265
answer count: 4
type: AnsweredQuestion
upvote count: 3
tagged with: vectorization
type: Question
accepted answer: http://stackoverflow.com/a/51954071
has title: How can I vectorize the dot product in Python?
score: 3
has answer: http://stackoverflow.com/a/51953882
has body: I want to compute N group of the dot product, for each group suppose it was a (4,3) matrix, called x_i. So I vectorize these N matrices into a (N,4,3) matrix, such as: [[[1,2,3], [4,5,6], [7,8,9], [0,1,2]], ... [7,2,2], [4,2,4], [7,1,9], [3,1,2]]]. # #N matrices If I compute each dot product of x_i and x_i.T individually: np.dot(x_i, x_i.T) It will get a (4,4) matrix. But how to compute these after vectorization? The final result should be (N,4,4).

http://stackoverflow.com/q/51862932
type: Question
has answer: http://stackoverflow.com/a/51863188
tagged with: browser
upvote count: 0
answer count: 1
tagged with: url
favorite count: 0
has body: I want to see all the websites that are opened in the currently working browser. Let's say that person is currently watching something on www.youtube.com and I want to see with that script that www.youtube.com is opened. Code: # something like this import someModule openedURLs = someModule.openedulrs() I know this code is useless but it is just some example how I would use it. Is this even possible? If yes with what modules? Thanks!
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/51863188
tagged with: python
score: -2
has title: How to get opened websites in browser with Python?
has comment: http://stackoverflow.com/comment/90681064
has comment: http://stackoverflow.com/comment/90680427
type: AnsweredQuestion
downvote count: 2

http://stackoverflow.com/q/51941307
linked to: http://stackoverflow.com/q/40323783
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51955505
has body: The return value of the map function in Python 3 is an Iterator. Why can the reduce function use the map result, when it needs an Iterable? #!/usr/bin/env python3 # -*- coding: utf-8 -*- from functools import reduce def fn(x, y): return x * 10 + y def char2num(s): digits = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9} return digits[s] reduce(fn, map(char2num, '13579'))
type: Question
tagged with: iterator
has comment: http://stackoverflow.com/comment/90832347
has answer: http://stackoverflow.com/a/51955505
score: 0
has comment: http://stackoverflow.com/comment/90832506
answer count: 1
has title: the function map and reduce in python3
tagged with: python-3.x
linked to: http://stackoverflow.com/q/9884132

http://stackoverflow.com/q/51834431
type: UnansweredQuestion
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/90623189
has body: What could possibly be the reason of this error? I am using a ubuntu guest server in a windows 10 host system The entire error is as follows: ` File "train_data.py", line 36, in &lt;module&gt; update_database.insert_features(features) File "/pupyl/preprocessing_data/update_database_with_features.py", line 59, in insert_features self.db_operation.insert_record(records, "train") File "/pupyl/database_client/database_operations.py", line 33, in insert_record self.db.train.insert(record) File "/usr/local/lib/python3.6/site-packages/pymongo/collection.py", line 3161, in insert check_keys, manipulate, write_concern) File "/usr/local/lib/python3.6/site-packages/pymongo/collection.py", line 607, in _insert bypass_doc_val, session) File "/usr/local/lib/python3.6/site-packages/pymongo/collection.py", line 595, in _insert_one acknowledged, _insert_command, session) File "/usr/local/lib/python3.6/site-packages/pymongo/mongo_client.py", line 1242, in _retryable_write with self._tmp_session(session) as s: File "/usr/local/lib/python3.6/contextlib.py", line 81, in __enter__ return next(self.gen) File "/usr/local/lib/python3.6/site-packages/pymongo/mongo_client.py", line 1571, in _tmp_session s = self._ensure_session(session) File "/usr/local/lib/python3.6/site-packages/pymongo/mongo_client.py", line 1558, in _ensure_session return self.__start_session(True, causal_consistency=False) File "/usr/local/lib/python3.6/site-packages/pymongo/mongo_client.py", line 1511, in __start_session server_session = self._get_server_session() File "/usr/local/lib/python3.6/site-packages/pymongo/mongo_client.py", line 1544, in _get_server_session return self._topology.get_server_session() File "/usr/local/lib/python3.6/site-packages/pymongo/topology.py", line 427, in get_server_session None) File "/usr/local/lib/python3.6/site-packages/pymongo/topology.py", line 199, in _select_servers_loop self._error_message(selector)) pymongo.errors.ServerSelectionTimeoutError: localhost:27017: [Errno 111] Connec…
has title: pymongo.errors.ServerSelectionTimeoutError
type: Question
score: 0
tagged with: mongodb
has answer: http://stackoverflow.com/a/51838502
answer count: 1
has comment: http://stackoverflow.com/comment/90622990

http://stackoverflow.com/comment/90701704
score: 0
type: Comment
has text: so I can do it both Iframe and regular source in one loop ? Can you help me with that please ?
type: QuestionComment
comment on: http://stackoverflow.com/q/51861326

http://stackoverflow.com/q/51881293
type: AnsweredQuestion
has title: Have subclass inherit non-default __init__ values from an instantiated main class
has answer: http://stackoverflow.com/a/51883404
accepted answer: http://stackoverflow.com/a/51883404
type: Question
tagged with: inheritance
has comment: http://stackoverflow.com/comment/90714111
tagged with: python-2.7
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/90717916
has comment: http://stackoverflow.com/comment/90716755
has body: How can I have a subclass that inherits not just __init__ variables from the main class, but also inherits the instantiated values from an instantiated main class. For example, say I have these classes: class MainClass(object): def __init__(self, mainVar1=None, mainVar2=None): self.mainVar1 = mainVar1 self.mainVar2 = mainVar2 class SubClass(MainClass): def __init__(self): super(SubClass, self).__init__() self.subVar1 = -1 And I do this: main = MainClass(mainVar1=1, mainVar2=2) sub = SubClass() print(sub.mainVar1) This prints out None and not 1 because sub calls the __init__ of MainClass in which mainVar1 by default is set to None. What I'd like to do is instantiate SubClass in such a way that it gets the input values used to instantiate MainClass, so that print(sub.mainVar1) prints 1 instead of None. I want to do this without repeating the same variables when instantiating the classes: main = MainClass(mainVar1=1, mainVar2=2) # This is what I'm trying to avoid. sub = SubClass(mainVar1=1, mainVar2=2) print(sub.mainVar1) Is this possible? Is this a terrible design choice? What's the best way to do this? EDIT: Concrete Example I have a class called ServerTools that provides functions for accessing data on a server. This is my MainClass class in the example above. To instantiate this class I need a username, password, and server_url. I then have a subclass called Docs that creates a document from data on the server. To instantiate this class I need username, password, server_url, and some other arguments. This subclass needs the functions from the main class ServerTools to access data on the server. My thought process was to have Docs be a tool in ServerTools, in which a document cannot be created without instantiating ServerTools. I'm not sure whether Docs should be a subclass, an inner-class, or something else entirely.
possible better answer: http://stackoverflow.com/a/51881383
has comment: http://stackoverflow.com/comment/90714050
has comment: http://stackoverflow.com/comment/90716399
tagged with: python
has comment: http://stackoverflow.com/comment/90714932
has answer: http://stackoverflow.com/a/51881383

http://stackoverflow.com/comment/90603362
comment on: http://stackoverflow.com/a/51802436
has text: Try my above comment in your code. It works the way you wanted.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/51832963
score: 2
downvote count: 0
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/51832920
has body: Try the following code, you need to change the if statement to for #!/usr/bin/env python import os for i in range(1, 255): all_=os.system("echo 10.11.1."+str(i)) print(all_)

http://stackoverflow.com/comment/90759645
type: Comment
has text: @stanleyli `queue.PriorityQueue` uses `heapq` underneath.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51904206

http://stackoverflow.com/q/51868410
has answer: http://stackoverflow.com/a/51868687
has title: Can't read a .CSV file in Spyder (Python 3.6) and it's not a path or character issue
tagged with: python
has comment: http://stackoverflow.com/comment/90690265
score: 1
has answer: http://stackoverflow.com/a/67687136
upvote count: 1
type: Question
answer count: 2
tagged with: pandas
downvote count: 0
has comment: http://stackoverflow.com/comment/90689100
has comment: http://stackoverflow.com/comment/90688678
favorite count: 0
has comment: http://stackoverflow.com/comment/90689154
has body: I'm new in python, I'm learning it so, please, try to be simple when answer me =) thx since now! I'm using Spyder (Python 3.6) and trying to run these lines: import pandas as pd df=pd.read_csv(r'Legumes.csv') df But, I'm having every possible kind of error, and trust me, I read and tried a lot of solutions but, none seemed to fix my problem. First, the file "Legumes" does exist, and it is in the same folder than the spyder file (.py one). 1-I inicially tried run the lines using a relative path, since the two files are in the same folder, spyder returned me this error: FileNotFoundError: File b'Legumes.csv' does not exist 2-Then I tried use a full path, but, I've got this error: SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape 3-Then, I tried insert the "r", before the path, so python would understand that this string means a path, and, I've got this: FileNotFoundError: File b'Legumes.csv' does not exist Note: I made sure of using no invalid caracters in the path and in the file (.csv), like ´, ^, or ~. I also tried use "r" in full and relative path (as shown in my paste above), the error message was the same. 4-I tried rename the files and run, nothing changed. Tried also re-load .py file to discart some location issues, nothing again... The most irritating thing is, it works only for the first time, I wrote it last friday and worked just fine, I just saved and closed. Today when I got back to work it just don't run anymore!! I'm blowing up with this!!!!
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv

http://stackoverflow.com/comment/90843973
type: Comment
type: QuestionComment
has text: `temp += " " curr_line` does that compile? You probably need an operator to combine the space and curr_line, e.g. +.
comment on: http://stackoverflow.com/q/51947042
score: 0

http://stackoverflow.com/q/51911124
answer count: 3
tagged with: pandas
tagged with: datetime
has answer: http://stackoverflow.com/a/51911192
favorite count: 0
tagged with: python
tagged with: lambda
type: AnsweredQuestion
score: 4
accepted answer: http://stackoverflow.com/a/51911192
tagged with: apply
type: Question
upvote count: 4
possible better answer: http://stackoverflow.com/a/51911372
downvote count: 0
has body: I have a feature in my data set that is a pandas timestamp object. It has (among many others) the following attributes: year, hour, dayofweek, month. I can create new features based on these attributes using some brute force methods: df["year"] = df["timeStamp"].apply(lambda x : x.year) df["hour"] = df["timeStamp"].apply(lambda x : x.hour) . . . However, I want to iterate over a list: nomtimes = ["year", "hour", "month", "dayofweek"] for i in nomtimes: df[i] = df["timeStamp"].apply(lambda x : x.i) I get the following AttributeError: 'Timestamp' object has no attribute 'i', and I get it and understand why I am having this error. How can I get the quoted string to unquote so that I can pass it as an attribute?
has answer: http://stackoverflow.com/a/51911372
has answer: http://stackoverflow.com/a/51911202
has title: Python - Iterate over a list of attributes

http://stackoverflow.com/q/51913726
type: Question
accepted answer: http://stackoverflow.com/a/51913742
upvote count: 0
has comment: http://stackoverflow.com/comment/90777494
has comment: http://stackoverflow.com/comment/90777519
tagged with: python-2.7
has answer: http://stackoverflow.com/a/51914041
favorite count: 0
tagged with: pattern-matching
score: -1
has answer: http://stackoverflow.com/a/51913745
has answer: http://stackoverflow.com/a/51913742
tagged with: python
tagged with: regex
downvote count: 1
has title: Regex check if specific multiple words present in a sentence
has comment: http://stackoverflow.com/comment/90777485
answer count: 4
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51913766
has answer: http://stackoverflow.com/a/51913766
has body: Is there a regex for us to check if multiple words are present in a string Ex : sentence = "hello i am from New York city" I want to check if 'hello' 'from' and 'city' are present in sentence. I have tried using re.compile("hello|from|city") but no luck as it returns true if even a single match is found.

http://stackoverflow.com/comment/90715153
type: Comment
has text: You’re parsing the JSON file perfectly; you’re just not using the list right. Either `for item in data: print item` or `for index in range(len(data)): print data[index]`. (Hopefully it’s obvious why the first one is better.)
comment on: http://stackoverflow.com/q/51881794
score: 4
type: QuestionComment

http://stackoverflow.com/q/51860186
type: Question
answer count: 1
upvote count: 6
has title: NamedTuple Class with ABC mixin
has answer: http://stackoverflow.com/a/51861064
linked to: http://stackoverflow.com/q/50367661
accepted answer: http://stackoverflow.com/a/51861064
downvote count: 0
tagged with: python-3.6
score: 6
type: AnsweredQuestion
tagged with: python
tagged with: abc
favorite count: 0
has body: My problem is as follows: I want to create a class that inherits from typing.NamedTuple and another mixin which in an abstract class. Ideally I want to do something like this: from typing import * from abc import ABC, abstractmethod class M(ABC): @abstractmethod def m(self, it: Iterable[str]) -&gt; str: pass class N(NamedTuple, M): attr1: str def m(self, it): return self.attr1 + it When I try to do that now I get this error: TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases I know that I can do it this way: from typing import * from abc import ABC, abstractmethod class M(ABC): @abstractmethod def m(self, it: Iterable[str]) -&gt; str: pass class NT(NamedTuple): attr1: str class N(NT, M): def m(self, it): return self.attr1 + it But I don't want to have to do that because it seems kinda gross and defines 2x the number of classes I am actually going to use. I am also looking for a solution that ideally changes M in some way, not something that I have to specify when creating N everytime.
tagged with: namedtuple

http://stackoverflow.com/a/51885106
answers question: http://stackoverflow.com/q/51884808
type: Answer
score: 0
has body: You will need to upgrade your python-ta package. The type_interface_visitor.py in transforms in the current stable release seems not to contain the line where your program is erroring from - and is instead importing _gorg from its own internal modules. Hope that helps!

http://stackoverflow.com/comment/90619964
score: 2
comment on: http://stackoverflow.com/q/51833010
has text: It is helpful to give the error message instead of just saying "it errored out". It sounds like you don't have the execute bit set on the script.
type: QuestionComment
type: Comment

http://stackoverflow.com/q/51929390
has comment: http://stackoverflow.com/comment/90808520
tagged with: collections
has comment: http://stackoverflow.com/comment/90809386
has body: from collections import defaultdict a = defaultdict(list, {'./lec5.pdf': ['social'], './some 3.pdf': ['social']}) a.values() Out[10]: dict_values([['social'], ['social'], []]) # One empty list at last a.keys() Out[11]: dict_keys(['./social', './some 3.pdf', 0]) #O at last I want to understand from where an empty list([]) is created inside a.values() and for a.keys() 0 is created inside.
type: Question
has comment: http://stackoverflow.com/comment/90808748
answer count: 2
upvote count: 0
has comment: http://stackoverflow.com/comment/90808642
score: -1
has comment: http://stackoverflow.com/comment/90808588
has comment: http://stackoverflow.com/comment/90809190
has comment: http://stackoverflow.com/comment/90808389
has comment: http://stackoverflow.com/comment/90808435
has title: keys and Values output - Python Collections
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90809448
has answer: http://stackoverflow.com/a/51929593
has comment: http://stackoverflow.com/comment/90808609
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51929600
tagged with: python
downvote count: 1

http://stackoverflow.com/a/51865646
has comment: http://stackoverflow.com/comment/90684906
has comment: http://stackoverflow.com/comment/90694263
answers question: http://stackoverflow.com/q/51860448
has body: One solution would be to open the HTML file into a temporary workbook, and copy the sheet from there into the workbook containing all of them: workbook = excel_app.Application.Workbooks.Add() sheet = workbook.Sheets(1) for path in read_path.glob('*.html'): workbook_tmp = excel_app.Application.Workbooks.Open(path) workbook_tmp.Sheets(1).Copy(Before=sheet) workbook_tmp.Close() # Remove the redundant 'Sheet1' excel_app.Application.ShowAlerts = False sheet.Delete() excel_app.Application.ShowAlerts = True
accepted answer of: http://stackoverflow.com/q/51860448
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90684525
upvote count: 2
has comment: http://stackoverflow.com/comment/90684354
type: Answer
has comment: http://stackoverflow.com/comment/90704423
score: 2
has comment: http://stackoverflow.com/comment/90684459
has comment: http://stackoverflow.com/comment/90684592
has comment: http://stackoverflow.com/comment/90685594
has comment: http://stackoverflow.com/comment/90684934

http://stackoverflow.com/a/51865572
has body: It's a long JOIN but I guess it will work: select t1.*, t2.* from table1 t1 join table2 t2 on (t1.cola = '*' or t1.cola = t2.cola) and (t1.colb = '*' or t1.colb = t2.colb) ... and (t1.colz = '*' or t1.colz = t2.colz) If you have wildcards * in table2 then the query becomes a little bit more complex: select t1.*, t2.* from table1 t1 join table2 t2 on (t1.cola = '*' or t2.cola = '*' or t1.cola = t2.cola) and (t1.colb = '*' or t2.colb = '*' or t1.colb = t2.colb) ... and (t1.colz = '*' or t2.colz = '*' or t1.colz = t2.colz)
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/90683511
answers question: http://stackoverflow.com/q/51865334
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/90683467

http://stackoverflow.com/a/51915299
answers question: http://stackoverflow.com/q/51915286
type: Answer
has body: you can extract the values of any dict by calling on values() &gt;&gt;&gt; a = {"a":"1"} &gt;&gt;&gt; a.values() 0: ['1']
score: 0

http://stackoverflow.com/q/51873133
duplicate of: http://stackoverflow.com/q/39078467
answer count: 1
downvote count: 0
has title: How to access a function from within it without naming it directly
has comment: http://stackoverflow.com/comment/90697641
favorite count: 0
has body: I want to know how to access a function from within it without naming it directly. def fact(n): this = # some code, where we don't use the name "fact" print(fact == this) # True if n &lt; 1: return 1 return n * this(n-1) The code above should behave exactly like: def fact(n): if n &lt; 1: return 1 return n * fact(n-1) Does anyone have any ideas? EDIT: My question is different from Determine function name from within that function (without using traceback). I need fact == this in the code above to return True. EDIT2: @ksbg's answer is a good one, but consider the folowing code: from inspect import stack, currentframe def a(): def a(): f_name = stack()[0][3] # Look up the function name as a string this = currentframe().f_back.f_globals[f_name] print(a == this) a() a() # False In this case it wont work as expected.
has answer: http://stackoverflow.com/a/51873373
tagged with: python
type: UnansweredQuestion
score: 1
upvote count: 1
type: Question
linked to: http://stackoverflow.com/q/5067604

http://stackoverflow.com/q/51800605
tagged with: while-loop
has comment: http://stackoverflow.com/comment/90557676
has comment: http://stackoverflow.com/comment/90557740
downvote count: 0
has comment: http://stackoverflow.com/comment/90557828
has comment: http://stackoverflow.com/comment/90557810
has comment: http://stackoverflow.com/comment/90557659
favorite count: 0
has comment: http://stackoverflow.com/comment/90557756
has comment: http://stackoverflow.com/comment/90557649
has answer: http://stackoverflow.com/a/51800720
has comment: http://stackoverflow.com/comment/90557712
tagged with: python
has answer: http://stackoverflow.com/a/51800751
has comment: http://stackoverflow.com/comment/90557793
has title: Python | Returns none when doing a while loop
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90557684
possible better answer: http://stackoverflow.com/a/51800720
score: 1
accepted answer: http://stackoverflow.com/a/51800751
has comment: http://stackoverflow.com/comment/90557866
upvote count: 1
type: Question
has body: # Let's put it all together. Write code for the function process_madlib, which takes in # a string "madlib" and returns the string "processed", where each instance of **# "NOUN" is replaced with a random noun and each instance of "VERB" is # replaced with a random verb. You're free to change what the random functions **# return as verbs or nouns for your own fun, but for submissions keep the code the way it is!**** from random import randint def random_verb(): random_num = randint(0, 1) if random_num == 0: return "run" else: return "kayak" def random_noun(): random_num = randint(0,1) if random_num == 0: return "sofa" else: return "llama" def word_transformer(word): if word == "NOUN": return random_noun() elif word == "VERB": return random_verb() else: return word[0] def process_madlib(text): proc ="" lenght = len("NOUN") i=0 while text[i:i+lenght] !='': i +=1 if text[i:1+lenght] == "NOUN": proc= text[i:-1] + word_transformer("NOUN") + text[i+lenght:] return proc ** **# you may find the built-in len function useful for this quiz # documentation: https://docs.python.org/2/library/functions.html#len** ** test_string_1 = "ds NOUN ds" test_string_2 = "I'm going to VERB VERB to the store and pick up a NOUN or two." print process_madlib(test_string_1) print process_madlib(test_string_2) Always Return none , if i tested it manually and change "i" all look good edit : adding code ...... your can read the instruction in the comments
has comment: http://stackoverflow.com/comment/90557851
answer count: 2

http://stackoverflow.com/comment/90685751
type: AnswerComment
comment on: http://stackoverflow.com/a/51866523
has text: There's no easy way to do that. You have to find the appropriate ASCII codes and convert them. On that note tho, if this was helpful, make sure to hit that checkmark! Next to the arrows
score: 0
type: Comment

http://stackoverflow.com/comment/90830499
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51940077
has text: So i've renamed my 'User' model to 'BananaMan' and I deleted and recreated the database but it still gives me the same error. Also thanks for the image field information, i'll look into it :)

http://stackoverflow.com/comment/90732672
has text: there was a mistake in the question. it's already fixed. thank you very much for spotting :)
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51880970

http://stackoverflow.com/comment/90643525
type: Comment
has text: yes, you are right. The reason I didn't is that I should have written around 200 rows. But something similar, in a reduced version, can be seen in the link I put (there, the value column is missing because it was not relevant for that question).
comment on: http://stackoverflow.com/q/51844916
score: 0
type: QuestionComment

torchvision
tags question: http://stackoverflow.com/q/51895123
type: Tag
tag name: torchvision

seaborn
tags question: http://stackoverflow.com/q/51829462
tags question: http://stackoverflow.com/q/51837338
tags question: http://stackoverflow.com/q/51824174
tags question: http://stackoverflow.com/q/51851956
tags question: http://stackoverflow.com/q/51813207
tags question: http://stackoverflow.com/q/51849978
tags question: http://stackoverflow.com/q/51887631
tag name: seaborn
tags question: http://stackoverflow.com/q/51824053
tags question: http://stackoverflow.com/q/51868613
tags question: http://stackoverflow.com/q/51840390
tags question: http://stackoverflow.com/q/51826447
tags question: http://stackoverflow.com/q/51828996
tags question: http://stackoverflow.com/q/51846948
tags question: http://stackoverflow.com/q/51816297
tags question: http://stackoverflow.com/q/51856973
tags question: http://stackoverflow.com/q/51866324
tags question: http://stackoverflow.com/q/51801433
tags question: http://stackoverflow.com/q/51876744
tags question: http://stackoverflow.com/q/51926684
tags question: http://stackoverflow.com/q/51834448
tags question: http://stackoverflow.com/q/51825223
tags question: http://stackoverflow.com/q/51811972
tags question: http://stackoverflow.com/q/51863684
tags question: http://stackoverflow.com/q/51800309
tags question: http://stackoverflow.com/q/51891370
tags question: http://stackoverflow.com/q/51823126
tags question: http://stackoverflow.com/q/51916372
tags question: http://stackoverflow.com/q/51849075
type: Tag

http://stackoverflow.com/q/51810036
has title: RESTful API versioning using Tornado
tagged with: webserver
tagged with: tornado
type: Question
upvote count: 4
downvote count: 0
score: 4
favorite count: 0
tagged with: rest
has body: I have a RESTful service which was written using the Python asynchronous web framework Tornado I am trying to support API versioning inside my RESTful service, so I can support simultaneous versions of the same API. One clear way is to simply add the version to the URL path and route each path to a different API class, as follows: http://mydomain/api/v2/myapi/myarg http://mydomain/api/v1.1/myapi/myarg http://mydomain/api/v1/myapi/myarg But this will result in a tangled and duplicated code. Another way would be to get the version by header, and check the version inside the API class, and operate accordingly. This way is also not very native, and seems like a patch to solve the use of API versioning. It will force me to call the "IF-SWITCH" code that checks the version explicitly in each API class. Is there a way to do API versioning in Tornado in a more native way? (where the versioning is treated using some hidden Tornado code, such that is done with other Tornado decorators).
tagged with: python
has comment: http://stackoverflow.com/comment/105673042
answer count: 0
type: UnansweredQuestion

indexing
tags question: http://stackoverflow.com/q/51953869
tags question: http://stackoverflow.com/q/51878139
tags question: http://stackoverflow.com/q/51927999
type: Tag
tags question: http://stackoverflow.com/q/51883275
tags question: http://stackoverflow.com/q/51816479
tags question: http://stackoverflow.com/q/51851956
tags question: http://stackoverflow.com/q/51918444
tags question: http://stackoverflow.com/q/51886874
tags question: http://stackoverflow.com/q/51923088
tags question: http://stackoverflow.com/q/51805272
tag name: indexing
tags question: http://stackoverflow.com/q/51897581
tags question: http://stackoverflow.com/q/51866229
tags question: http://stackoverflow.com/q/51931800
tags question: http://stackoverflow.com/q/51842565
tags question: http://stackoverflow.com/q/51838479
tags question: http://stackoverflow.com/q/51870321

http://stackoverflow.com/comment/90849219
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51948205
type: AnswerComment
has text: Use `if len(daily_info) == 5` because there is `5` columns before assign (it add 6.th column)

http://stackoverflow.com/a/51844217
type: Answer
downvote count: 0
has body: As noted by someone in a comment, a list isn't the most appropriate data structure to store this information in. When you want to make sure that members of one collection aren't present in another collection, you should use a set which will enforce this. If you are insistent upon having lists then the easiest thing to do is current_users = ["bob", "sally"] new_users = ["harry", "sally"] current_users = list(set(current_users).union(set(new_users))) print(current_users) &gt;&gt;&gt; ['bob', 'sally', 'harry'] Here .union() is being used to update the current_users with the users in new_users that are actually new. If you want to know which users in new_users are already in current_users then you can use .intersection() like so actually_new_users = list(set(new_users) - set(current_users)) print(actually_new_users) &gt;&gt;&gt; ['harry'] This is somewhat inefficient because it will result in a lot of copying, BUT it's still likely better than an O(n^2) comparison between two lists*. *Depending on the size of the lists.
score: 3
has comment: http://stackoverflow.com/comment/90642316
upvote count: 3
has comment: http://stackoverflow.com/comment/90642128
has comment: http://stackoverflow.com/comment/90642181
answers question: http://stackoverflow.com/q/51844034

http://stackoverflow.com/comment/90842753
type: QuestionComment
comment on: http://stackoverflow.com/q/51916961
score: 0
type: Comment
has text: Do you know class name for unfollow?

http://stackoverflow.com/comment/90693334
has text: Dictionaries aren't guarranteed to be ordered. In python 3.7 - "the insertion-order preservation nature of dict objects has been declared to be an official part of the Python language spec."
comment on: http://stackoverflow.com/q/51870964
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/a/51955932
has body: You can do this using set_index and mul: df1 = df.set_index(['Rotation','Year']) df1.filter(like='Week').mul(df1['Name'], axis=0)\ .replace('',np.nan)\ .sort_index() Output: Week1 Week2 Week3 Week4 Rotation Year ABD freshman NaN NaN name3 name3 ERJD freshman name1 NaN NaN name1 sophomore NaN name2 NaN NaN sophomore NaN NaN name2 name2 MAM freshman name3 NaN NaN NaN freshman NaN NaN name1 NaN PEDI freshman NaN name1 NaN NaN freshman NaN name3 NaN NaN sophomore name2 NaN NaN NaN
type: Answer
score: 0
answers question: http://stackoverflow.com/q/51937806

http://stackoverflow.com/q/51817242
has comment: http://stackoverflow.com/comment/90588537
accepted answer: http://stackoverflow.com/a/51817297
tagged with: python
duplicate of: http://stackoverflow.com/q/1071191
tagged with: regex
linked to: http://stackoverflow.com/q/4697882
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51817356
score: 0
has answer: http://stackoverflow.com/a/51817356
duplicate of: http://stackoverflow.com/q/4697882
upvote count: 1
has body: I want my regex to find an url to be able to turn it into a html link.The regex will be used on links that look like the following: www.site.extension and https://site.extension. The regex is \S*.?w{3}.\S+.\S+ and it does give the desired result when using https://regexr.com/. When using my python script however, I get the opposite result of what's desired, so everything that isn't a link is seens as if it were, but the links aren't found. The python code is: testbestand = """TESTBESTAND Div1 kjaskdjfiudhgjnkcvdnbk djskj ij g ijg jkdfnbdiiji jj iikdafnbn ojedfkj giqw34 Akdjfkjasdf Div2 aksjdfkj sadfkjg sdkjiew kvckjeri cdkj sdkeridk erkire Div3 kajkdjfkjakdjgsdghijskdg Div 4 www.link.com Div5 Table Left Table Right Table Left 2 Table Right 2 Table Left 3 Table Right 3 """ fileContent = testbestand toAddToFile = "" #find links pattern = re.compile(r'\S*\.?w{3}\.\S+\.\S+') matches = re.split(pattern, fileContent)\ for match in matches: match = match.strip() if len(match) &gt; 0: #TODO change to 'edit' file, instead of adding to it test = """&lt;a href=" """ + match + """&gt;" """ + match + "&lt;/a&gt;" print(test) toAddToFile += """&lt;a href=" """ + match + """&gt;" """ + match + "&lt;/a&gt;" Thanks in advance for any help! If more info or code is needed, I'll provide it straight away.
downvote count: 1
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/51817297
has title: Python: regex matching the opposite of what's desired
favorite count: 0

http://stackoverflow.com/a/51862251
has body: Try open(line).read() to access the string in the files
upvote count: 1
answers question: http://stackoverflow.com/q/51862164
downvote count: 0
score: 1
type: Answer

http://stackoverflow.com/a/76700456
has body: Another way to read an edf file --&gt; array using pyedflib (if you don't want to use mne for dependency reasons): import pyedflib def edf_to_arr(edf_path): f = pyedflib.EdfReader(edf_path) n = f.signals_in_file signal_labels = f.getSignalLabels() sigbufs = np.zeros((n, f.getNSamples()[0])) for i in np.arange(n): sigbufs[i, :] = f.readSignal(i) return sigbufs There's more documentation here: pyedflib docs
downvote count: 0
answers question: http://stackoverflow.com/q/51869713
type: Answer
upvote count: 1
score: 1

http://stackoverflow.com/comment/90771704
comment on: http://stackoverflow.com/q/51910563
type: Comment
type: QuestionComment
has text: What do you mean by "split the column name"? Please tell us the step where you are stuck: reading the file, reading the first row, splitting that row into column names (is this what you mean?), reading the other rows, splitting those rows into values, creating the nested dictionary, or something else? If your problem is splitting the first row, show us your code before that point and as much as possible after that point.
score: 0

http://stackoverflow.com/q/51916407
tagged with: sniffing
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90782660
upvote count: 3
tagged with: scapy
accepted answer: http://stackoverflow.com/a/51919000
type: Question
score: 3
has comment: http://stackoverflow.com/comment/90782717
answer count: 1
downvote count: 0
tagged with: wifi
favorite count: 0
has title: How to see all packets in the air with scapy on Windows?
has body: I am trying to sniff some packets in python 3.4 in scapy. I am using Windows 8.1, and I know that the socket module does not have a PF_PACKET or something like on Windows to sniff packets, so i used the scapy.sniff function. I have already installed WinPcap 4.1.3 . I tried to sniff and was surprised that it only sniffs packets from the wireless network that I am connected to right now, so if i am not connected to any network it will not sniff anything (I have been waiting for 10 mins, and it didn't print anything). The code: from scapy.all import sniff, tshark pkts = sniff(count=30) # iface does not work tshark is the same as sniff, gives the same results. I have an ALFA wireless realtek interface card, it supports monitor mode. Is there a solution here? Does wspy (wireshark in python) work in Windows? Does it support WiFi monitor mode?
tagged with: python
has answer: http://stackoverflow.com/a/51919000

http://stackoverflow.com/a/51861747
answers question: http://stackoverflow.com/q/51861153
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51861153
has body: Also refer to What Every Programmer Should Know About Floating-Point Arithmetic, which has more detailed explanations for why this is happening as it is. This is a mess. First of all, as far as float is concerned, there is no such number as 0.493125, when you write 0.493125 what you actually get is: 0.493124999999999980015985556747182272374629974365234375 So this number is not exactly between two decimals, it's actually closer to 0.49312 than it is to 0.49313, so it should definitely round to 0.49312, that much is clear. The problem is that when you multiply by 105, you get the exact number 49312.5. So what happened here is the multiplication gave you an inexact result which by coincidence canceled out the rounding error in the original number. Two rounding errors canceled each other out, yay! But the problem is that when you do this, the rounding is actually incorrect... at least if you want to round up at midpoints, but Python 3 and Python 2 behave differently. Python 2 rounds away from 0, and Python 3 rounds towards even least-significant digits. Python 2 if two multiples are equally close, rounding is done away from 0 Python 3 ...if two multiples are equally close, rounding is done toward the even choice... Summary In Python 2, &gt;&gt;&gt; round(49312.5) 49313.0 &gt;&gt;&gt; round(0.493125, 5) 0.49312 In Python 3, &gt;&gt;&gt; round(49312.5) 49312 &gt;&gt;&gt; round(0.493125, 5) 0.49312 And in both cases, 0.493125 is really just a short way of writing 0.493124999999999980015985556747182272374629974365234375. So, how does it work? I see two plausible ways for round() to actually behave. Choose the closest decimal number with the specified number of digits, and then round that decimal number to float precision. This is hard to implement, because it requires doing calculations with more precision than you can get from a float. Take the two closest decimal numbers with the specified number of digits, round them both to float precision, and return whichever is close…
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90677640
type: Answer
has comment: http://stackoverflow.com/comment/90677777
has comment: http://stackoverflow.com/comment/90675999
score: 3
upvote count: 3

http://stackoverflow.com/q/51830450
tagged with: encryption
tagged with: libraries
type: Question
has title: Encrypt a Library Linux
has comment: http://stackoverflow.com/comment/90615441
downvote count: 6
has comment: http://stackoverflow.com/comment/90615433
linked to: http://stackoverflow.com/q/6578452
answer count: 3
has body: I've created my own Python library on my Raspberry Pi 3 called myLibrary.py, and in another program called example.py, I use this library: import myLibrary I need to hand this Pi over to someone else, but I want the library encrypted. I've tried GnuPG, bcrypt, and ccrypt. My issue is that the program no longer runs once the library is encrypted, I can an error saying "No module named myLibrary How can I encrypt the library and still be allowed to use it in my program? Thanks
has answer: http://stackoverflow.com/a/51830464
score: -6
favorite count: 0
linked to: http://stackoverflow.com/q/3344115
has answer: http://stackoverflow.com/a/51830761
tagged with: python
has comment: http://stackoverflow.com/comment/90615614
upvote count: 0
has answer: http://stackoverflow.com/a/51830551
type: UnansweredQuestion

http://stackoverflow.com/a/51843148
answers question: http://stackoverflow.com/q/51837110
score: 0
has comment: http://stackoverflow.com/comment/117448140
has body: You can use ConcatDataset, and provide a batch_sampler to DataLoader. concat_dataset = ConcatDataset((dataset1, dataset2)) ConcatDataset.comulative_sizes will give you the boundaries between each dataset you have: ds_indices = concat_dataset.cumulative_sizes Now, you can use ds_indices to create a batch sampler. See the source for BatchSampler for reference. Your batch sampler just has to return a list with N random indices that will respect the ds_indices boundaries. This will guarantee that your batches will have elements from the same dataset.
type: Answer
has comment: http://stackoverflow.com/comment/111757807

instantiation
type: Tag
tags question: http://stackoverflow.com/q/51849115
tag name: instantiation

http://stackoverflow.com/comment/92708245
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51882152
has text: Maybe this will work for another case, but still, thank you. :)
type: Comment

http://stackoverflow.com/q/51814619
upvote count: 2
tagged with: machine-learning
tagged with: python
has comment: http://stackoverflow.com/comment/90602212
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90585045
accepted answer: http://stackoverflow.com/a/51819872
type: Question
score: 2
tagged with: arrays
answer count: 1
downvote count: 0
tagged with: scikit-learn
favorite count: 0
has body: Currently learning a machine learning application and the output by a method has really stumped me, never have I seen an output like this. Code: def IsCloseTogether(data): amount_of_data = len(data) #i have an array loaded with examples local_feature = np.reshape(data, (amount_of_data,-1)) #changes the array so it would work with the clf.fit labels = [1, 0, 0, 0, 1, 1] # 1 means it matches, 0 means it doesn't (supervised learning) clf = tree.DecisionTreeClassifier() clf = clf.fit(local_feature, labels) prediction = clf.predict([["111011101"], ["101"]]) #these number strings are the strings im making the machine predict whether they are similar enough to be deemed "similar" or "different" return prediction After printing it I get this output: [1 0] Although it the numbers make sense themselves, I ideally would like to the elements to show up as actual list elements like: ['1','0'] I've tried using .join but it's not a string so I can't seem to get it to work, any idea how to format this output?
has answer: http://stackoverflow.com/a/51819872
has title: How to format scikit-learn output data?

http://stackoverflow.com/comment/90681520
comment on: http://stackoverflow.com/a/51855024
has text: @user2526586 .I don't think a wildcard exists for others. But you can view all supported languages by pressing `Ctrl + Shift + P`, then run this command, **Preferences: Configure language specific settings...** Select the language you want and move on.
score: 1
type: AnswerComment
type: Comment

http://stackoverflow.com/a/51899645
has body: Right, so here's how I did this. Despite author Charlie Clark's suggestion to use reversed, I still haven't identified the syntax to use that method. However, this worked fine: print('BEGIN: sheet.max_row: ' + str(sheet.max_row)) for rr in range(sheet.max_row, 1, -1): hasData = False for cc in range(1, sheet.max_column+1): tmp = AlphaFromIndex(cc) ref = str(tmp) + str(rr) val = sheet[ref].value if val is not None: hasData = True if not hasData: print('Row: ' + str(rr) + ' -- Deleting row: ' + str(rr)) sheet.delete_rows(rr, 1) else: print('Row: ' + str(rr) + ' of (' +str(sheet.max_row)+')') print('END: sheet.max_row: ' + str(sheet.max_row)) def AlphaFromIndex(num): ab = ["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"] return ab[num - 1] * BUT * The main take away from this exercise is that OpenPyXL will not update formulas in rows below any deleted rows. So, deleting blank rows is a bad idea in OpenPyXL as any pre-existing formulas will now refer to the wrong rows.
score: 0
answers question: http://stackoverflow.com/q/51866161
type: Answer

http://stackoverflow.com/q/51878006
has body: Multiloginapp supports selenium remote driver, but when I try to start browser: mla_url = 'http://127.0.0.1:37001/api/v1/webdriver' driver = webdriver.Remote(command_executor=mla_url, desired_capabilities={'multiloginapp-profileId': profile_id}) It always crashes: urllib3.exceptions.ProtocolError: ('Connection aborted.', BadStatusLine('\x15\x03\x03\x00\x02\x02\n',)) What am I doing wrong? Lang: python
tagged with: selenium
has answer: http://stackoverflow.com/a/52469181
has title: Multiloginapp (browser) and selenium
linked to: http://stackoverflow.com/q/20345132
type: Question
score: 0
answer count: 1
linked to: http://stackoverflow.com/q/34543443
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/90606332
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51825576
has text: What do you get if you run `pip freeze | grep scikit`? You could try updating your scikit with `pip install -U scikit-learn`. I just did exactly that and your code ran fine :)

http://stackoverflow.com/q/51886142
answer count: 1
downvote count: 1
tagged with: keras
favorite count: 0
tagged with: python
type: AnsweredQuestion
upvote count: 0
accepted answer: http://stackoverflow.com/a/51891133
tagged with: tensorflow
type: Question
has body: I have one Thousand review sentences (or paragraphs) with associated Positive or Negative labels (Same one Thousand), so i am trying to use glove word embedding (Pretrained word representation), so below is the architecture have been decided (Many to One). By considering below image as single review prediction, I am trying to fixing each sentence up to 1000 words (time sequence) (Either by removing extra words or Padding by zero vectors) [each word would be transformed into 300D array] But i don't know how to materialize this architecture in Keras or Tensorflow Getting lot of confusions about the shapes of each cells, can any one explain the shapes accordingly (Each cell in LSTM) by considering 1 layer LSTM with 1000 word sequence (And each word is gonna have 300D vector/array). Architeture Picture
has answer: http://stackoverflow.com/a/51891133
score: -1
tagged with: lstm
has title: LSTM / Pretrained word embedding - Positive/Negative review prediction
tagged with: deep-learning

http://stackoverflow.com/comment/90584525
comment on: http://stackoverflow.com/q/51815087
type: Comment
type: QuestionComment
has text: Just write `Questions_List[score][1]` instead.
score: 1

rasa-nlu
tags question: http://stackoverflow.com/q/51840550
tag name: rasa-nlu
type: Tag
tags question: http://stackoverflow.com/q/51934371

http://stackoverflow.com/comment/90712506
type: QuestionComment
has text: @AndreMotta In the second dataframe each year is only mentioned once, so it has no duplicates. The first dataframe can have the same year multiple times for different id's. How can I make my question clearer for you?
type: Comment
comment on: http://stackoverflow.com/q/51880405
score: 0

http://stackoverflow.com/a/51812274
score: 0
type: Answer
has body: As of Bokeh 0.13.0 there is not. You would need to call p.circle, p.square, etc. for each "sub" line in the multi-line.
has comment: http://stackoverflow.com/comment/90590081
answers question: http://stackoverflow.com/q/51805080
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51805080

http://stackoverflow.com/comment/90680472
has text: @RustyShackleford All I'm saying is that sacul's answer is more stable
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51864128

http://stackoverflow.com/comment/90761332
type: AnswerComment
has text: Adding and should be conditional on having at least two elements.
comment on: http://stackoverflow.com/a/51905238
type: Comment
score: 0

http://stackoverflow.com/comment/90847564
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51948262
has text: exactly what I was looking for (Y) - I cast this into an answer for better readability.

http://stackoverflow.com/a/51804648
accepted answer of: http://stackoverflow.com/q/51802974
score: 9
answers question: http://stackoverflow.com/q/51802974
type: AcceptedAnswer
downvote count: 0
upvote count: 9
type: Answer
has body: What is the difference between the two following expressions? first_name = account['first_name'] if account['first_name'] else "" vs first_name = account['first_name'] or "" The primary difference is that the first, in Python, is the conditional expression, The expression x if C else y first evaluates the condition, C rather than x. If C is true, x is evaluated and its value is returned; otherwise, y is evaluated and its value is returned. while the second uses the boolean operation: The expression x or y first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned. Note that the first may require two key lookups versus the second, which only requires one key lookup. This lookup is called subscript notation: name[subscript_argument] Subscript notation exercises the __getitem__ method of the object referenced by name. It requires both the name and the subscript argument to be loaded. Now, in the context of the question, if it tests as True in a boolean context (which a non-empty string does, but None does not) it will require a second (redundant) loading of both the dictionary and the key for the conditional expression, while simply returning the first lookup for the boolean or operation. Therefore I would expect the second, the boolean operation, to be slightly more efficient in cases where the value is not None. Abstract Syntax Tree (AST) breakdown Others have compared the bytecode generated by both expressions. However, the AST represents the first breakdown of the language as parsed by the interpreter. The following AST demonstrates that the second lookup likely involves more work (note I have formatted the output for easier parsing): &gt;&gt;&gt; print(ast.dump(ast.parse("account['first_name'] if account['first_name'] else ''").body[0])) Expr( value=IfExp( test=Subscript(value=Name(id='account', ctx=Load()), slice=Index(value=Str(s='first_name')), ctx=Load()), body=Subscript(value=Name(id='account', ctx=Lo…

http://stackoverflow.com/a/51929270
answers question: http://stackoverflow.com/q/51929071
has body: In def page(self), you have: return redirect(url_for('view.files')) It should be return redirect(url_for('page1')) so it points to your page1 function. Solution from: https://teamtreehouse.com/community/flask-redirect-vs-redirecturlfor
score: 0
has comment: http://stackoverflow.com/comment/90808265
type: Answer
has comment: http://stackoverflow.com/comment/90809246

http://stackoverflow.com/comment/90599248
has text: @Nordle, Thts right, But tomtom webfleet api suggests same format for creating orders.
comment on: http://stackoverflow.com/q/51822347
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51950465
tagged with: pandas
has comment: http://stackoverflow.com/comment/90851051
answer count: 1
has title: Pandas: grouping values by date-time index
favorite count: 0
has answer: http://stackoverflow.com/a/51950522
tagged with: python
type: AnsweredQuestion
upvote count: 1
downvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/51950522
has body: I have the following dataframe: Values Date_Time 2016-01-04 12:00:00 778000 2016-01-04 18:00:00 35 2016-02-04 04:00:00 45 2016-02-04 11:00:00 47 2016-03-04 07:00:00 51 I want to count how many occurrences I have for each day: Occurrences Date_Time 2016-01-04 2 2016-02-04 2 2016-03-04 1 And I am trying to achieve it by doing: df2=df.groupby.index.count_values(), but the result is not what I wish it was. What am I doing wrong?
score: 0

http://stackoverflow.com/comment/90745708
type: AnswerComment
has text: I tried updated solution and it's not working too. The same. Type of result is string again. For the sake of easiness, i add a template tag to get type of an object. When i apply your solution, the type of result seems `<class 'str'>` again.
score: 0
comment on: http://stackoverflow.com/a/51894138
type: Comment

http://stackoverflow.com/q/51925843
has answer: http://stackoverflow.com/a/51926044
tagged with: dataframe
has title: Find element in pandas dataframe
answer count: 2
tagged with: pandas
upvote count: 1
has answer: http://stackoverflow.com/a/51926230
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/90801504
downvote count: 0
score: 1
has body: I have a table: Name1 Name2 Name3 0 ABC FGD NNY 1 ABSTRE PC ABSTRE Tree in 2 P ABSTRE NNY 3 JJJ FGD NNY 4 ABSFRE PC ABSKRE I need get these info: ['ABSTRE', 'ABSFRE', 'ABSTRE', 'ABSKRE'] So its means that code has the same 3 letters and the same length. The same 3 letters: ABS Length: 6 I need get all codes from table. I think it should be something like these: t='^[A-Z0-9]{3,10}?$' for i in df.items(): l=df[df[i].str.contains(t)] Could you please help me with this?
type: Question

http://stackoverflow.com/comment/90858194
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51907245
has text: Sorry, I phrased my question incorrectly @PatrickHaugh. I would like to make it possible to accept strings and roles.
score: 0

http://stackoverflow.com/a/51841229
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51836388
type: Answer
has body: I was a able to find the answer with a quite a bit of research. Instead of trying to edit it manually I did the following: import requests session_requests = requests.session() login_url = "http://*host ip*/v2_Website/aspx/Login.aspx" result = session_requests.get(login_url) result = session_requests.post(login_url, headers= dict(referer=login_url)) This pulls through the needed cookie and adds everything as need. My headers come back as follows: POST /_v2_Website/aspx/Login.aspx HTTP/1.1 Host: *host IP* User-Agent: python-requests/2.18.4 Accept-Encoding: gzip, deflate Accept: */* Connection: close referer: http://*hostIP*/v2_Website/aspx/Login.aspx Cookie: ASP.NET_SessionId=3crqoo45hnn21anuqulmmr55; CookieLoginAttempts=5 Content-Length: 79 Content-Type: application/x-www-form-urlencoded
accepted answer of: http://stackoverflow.com/q/51836388
score: 0

http://stackoverflow.com/q/51822411
score: 2
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/6838238
downvote count: 0
has answer: http://stackoverflow.com/a/51822510
accepted answer: http://stackoverflow.com/a/51822510
possible better answer: http://stackoverflow.com/a/51822555
duplicate of: http://stackoverflow.com/q/6838238
has title: Multiple conditions python
type: Question
tagged with: if-statement
has comment: http://stackoverflow.com/comment/90598759
has body: I want to do a function that counts the consonants in a string, so I tried to do this: def vowel_count(foo): count = 0 for i in foo: if not i == 'a' and i == 'e' and i ... and i == 'O' and i == 'U': count += 1 return count But this is pretty ugly and tedious to do, more so with many more conditions. Is there any way to put them together?
upvote count: 2
has comment: http://stackoverflow.com/comment/90598689
answer count: 2
has comment: http://stackoverflow.com/comment/90598816
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/51822555

http://stackoverflow.com/comment/90710314
has text: Could you post your `data` variable?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51877520
score: 0

infinite-scroll
tag name: infinite-scroll
tags question: http://stackoverflow.com/q/51807299
type: Tag
tags question: http://stackoverflow.com/q/51825077

http://stackoverflow.com/comment/90666546
has text: @santoku - be aware that what's most efficient changes as your inputs change. For this trivial dataset all the solutions given are about the same. As the inputs grow what is most efficient changes drastically.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51848354
score: 1

http://stackoverflow.com/a/51860962
downvote count: 0
type: Answer
upvote count: 3
score: 3
has body: You can use any: a = ['119', '120', '123', '1234', '12345'] b = ['112', '120', '121', '123', '1233', '1234', '1235', '12345'] new_d = {c:c in b and not any(i.startswith(c) and len(c) &lt; len(i) for i in b) for c in a} Output: {'120': True, '1234': False, '119': False, '123': False, '12345': True}
answers question: http://stackoverflow.com/q/51857601

http://stackoverflow.com/q/51924925
has title: How to view only doc text with pydoc
tagged with: pydoc
type: AnsweredQuestion
score: 1
favorite count: 0
type: Question
upvote count: 1
tagged with: perldoc
tagged with: python
answer count: 1
has answer: http://stackoverflow.com/a/51925480
tagged with: perl
downvote count: 0
has body: Being a perl developer I am aware of the perldoc utility. I am new to python and I was looking for same and found pydoc. But the problem with pydoc is it is also executing my script while I want to see only doc written inside triple quotes. Any help would be appreciated.
accepted answer: http://stackoverflow.com/a/51925480

http://stackoverflow.com/q/51934363
type: Question
score: -1
possible better answer: http://stackoverflow.com/a/51935022
has title: How to get data from web in python using curl?
has comment: http://stackoverflow.com/comment/90818898
answer count: 2
downvote count: 1
has answer: http://stackoverflow.com/a/51934531
accepted answer: http://stackoverflow.com/a/51934531
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/90818844
type: AnsweredQuestion
upvote count: 0
has comment: http://stackoverflow.com/comment/90819102
has body: In bash when I used myscript.sh file="/tmp/vipin/kk.txt" curl -L "myabcurlx=10&amp;id-11.com" &gt; $file cat $file ./myscript.sh gives me below output 1,2,33abc 2,54fdd,fddg3 3,fffff,gfr54 When I tried to fetch it using python and tried below code - mypython.py command = curl + ' -L ' + 'myabcurlx=10&amp;id-11.com' output = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE).stdout.read().decode('ascii') print(output) python mypython.py throw error, Can you please point out what is wrong with my code. Error : /bin/sh: line 1: &amp;id=11: command not found Wrong Parameter
has answer: http://stackoverflow.com/a/51935022

javascript
tags question: http://stackoverflow.com/q/51933714
tags question: http://stackoverflow.com/q/51949481
tags question: http://stackoverflow.com/q/51917816
tags question: http://stackoverflow.com/q/51941101
tags question: http://stackoverflow.com/q/51956476
tags question: http://stackoverflow.com/q/51876706
tags question: http://stackoverflow.com/q/51903521
tags question: http://stackoverflow.com/q/51932057
tags question: http://stackoverflow.com/q/51916449
tags question: http://stackoverflow.com/q/51920961
tags question: http://stackoverflow.com/q/51942404
tags question: http://stackoverflow.com/q/51822192
tag name: javascript
tags question: http://stackoverflow.com/q/51945705
tags question: http://stackoverflow.com/q/51914968
tags question: http://stackoverflow.com/q/51888388
tags question: http://stackoverflow.com/q/51922105
tags question: http://stackoverflow.com/q/51931143
tags question: http://stackoverflow.com/q/51862924
tags question: http://stackoverflow.com/q/51815038
tags question: http://stackoverflow.com/q/51915453
tags question: http://stackoverflow.com/q/51858168
tags question: http://stackoverflow.com/q/51949091
type: Tag
tags question: http://stackoverflow.com/q/51933083
tags question: http://stackoverflow.com/q/51849112
tags question: http://stackoverflow.com/q/51851434
tags question: http://stackoverflow.com/q/51838887
tags question: http://stackoverflow.com/q/51953016
tags question: http://stackoverflow.com/q/51867897
tags question: http://stackoverflow.com/q/51919821
tags question: http://stackoverflow.com/q/51952293
tags question: http://stackoverflow.com/q/51812634
tags question: http://stackoverflow.com/q/51893045
tags question: http://stackoverflow.com/q/51815470
tags question: http://stackoverflow.com/q/51888326
tags question: http://stackoverflow.com/q/51827089
tags question: http://stackoverflow.com/q/51813334
tags question: http://stackoverflow.com/q/51921221
tags question: http://stackoverflow.com/q/51910264
tags question: http://stackoverflow.com/q/51817148
tags question: http://stackoverflow.com/q/51951051
tags question: http://stackoverflow.com/q/51886503
tags question: http://stackoverflow.com/q/51849100
tags question: http://stackoverflow.com/q/51913744
tags question: http://stackoverflow.com/q/51897291
tags question: http://stackoverflow.com/q/51915150
tags question: http://stackoverflow.com/q/51798793
tags question: http://stackoverflow.com/q/51932858
tags question: http://stackoverflow.com/q/51940010
tags question: http://stackoverflow.com/q/51948810
tags question: http://stackoverflow.com/q/51897969
tags question: http://stackoverflow.com/q/51867948
tags question: http://stackoverflow.com/q/51881388
tags question: http://stackoverflow.com/q/51838087
tags question: http://stackoverflow.com/q/51936433
tags question: http://stackoverflow.com/q/51951533
tags question: http://stackoverflow.com/q/51807299
tags question: http://stackoverflow.com/q/51879956
tags question: http://stackoverflow.com/q/51897917

http://stackoverflow.com/a/66027126
has body: I had same issue and i solved it by making sure i am doing a volume mount in my compose file volumes: - ./dags:/usr/local/airflow/dags - ./config/airflow.cfg:/usr/local/airflow/airflow.cfg
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51829200
upvote count: 3
has comment: http://stackoverflow.com/comment/116884125
score: 3

http://stackoverflow.com/q/51900638
has body: I fitted data to a polynomial equation using a mixed linear regression fit (mixedlm): y = a + bx + cx2 The model gives me a, b and c, and I want to quickly create the graph of the polynomial curve. Is there a fast way to do it without having to manually enter all of the parameters in the formula? I read of coefplot2 but I was not able to install it on python, any suggestion would be welcomed thanks
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90752425
downvote count: 3
type: Question
tagged with: graph
accepted answer: http://stackoverflow.com/a/51902226
answer count: 2
upvote count: 0
possible better answer: http://stackoverflow.com/a/51900701
score: -3
has answer: http://stackoverflow.com/a/51900701
has title: How can I graph a regression model?
has comment: http://stackoverflow.com/comment/90752381
favorite count: 0
tagged with: model
has answer: http://stackoverflow.com/a/51902226
has comment: http://stackoverflow.com/comment/90755217
tagged with: python
tagged with: plot

http://stackoverflow.com/comment/92807533
has text: I am facing the same issue. While I am not able to solve this problem, I looked around the web and discovered that this might be related to the installation of pdftotext package. I am not able to install pdftotext on my Windows 10.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51907281
type: Comment

http://stackoverflow.com/comment/90570896
has text: @PM2Ring I’m not sure `operator` would really help here, since the functions are all nullary closures over the `x` and `y` params, so you’d have to write something like `functools.partial(operator.add, x, y)`, which isn’t as much benefit as you usually get from the module. But still, definitely good advice in general.
score: 0
comment on: http://stackoverflow.com/q/51807788
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51859533
score: 3
has answer: http://stackoverflow.com/a/51859587
has body: I am fairly new to using pip and python. I installed other libraries in python but can't install pandas. It gives lots of error after 22 percent installation. See the errors in image Can anyone help?
upvote count: 4
answer count: 2
has answer: http://stackoverflow.com/a/51893558
favorite count: 0
has comment: http://stackoverflow.com/comment/90671355
possible better answer: http://stackoverflow.com/a/51893558
linked to: http://stackoverflow.com/q/27885397
tagged with: pandas
has title: Can't install pandas library
accepted answer: http://stackoverflow.com/a/51859587
tagged with: python
tagged with: pip
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/90671605
type: AnsweredQuestion

http://stackoverflow.com/comment/90807544
type: QuestionComment
has text: You should add a file `flask_api/__init__.py`
comment on: http://stackoverflow.com/q/51928627
score: 0
type: Comment

http://stackoverflow.com/comment/90782123
type: Comment
has text: Sure you can use a binary search to find the index of the value in the other list and then check if the index is the same in both lists, but why would you?
type: QuestionComment
comment on: http://stackoverflow.com/q/51916029
score: 0

http://stackoverflow.com/comment/90731936
has text: Thanks. It works with the sample data. When I applied to main data, it showed some error such as : expected hh:mm:ss format
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51889848
type: Comment

http://stackoverflow.com/comment/90775927
type: Comment
score: 0
comment on: http://stackoverflow.com/q/51912909
has text: `5, 5, 4` _is_ descending rather than ascending order. 4 is smaller than 5.
type: QuestionComment

http://stackoverflow.com/comment/90647067
type: Comment
type: QuestionComment
score: 3
has text: That depends purely on your `run_nmap.py` script and how it builds its internal path to the XML.
comment on: http://stackoverflow.com/q/51846667

http://stackoverflow.com/q/51861992
score: 0
has comment: http://stackoverflow.com/comment/90676387
favorite count: 0
type: UnansweredQuestion
has title: Segmentation Fault occurring while assigning Daemon Threads for a Helper Function
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/90676358
upvote count: 1
has comment: http://stackoverflow.com/comment/90678650
downvote count: 1
type: Question
has body: I am doing data analysis on a dataset which features 55 million rows. Specifically, I am calculating the total distance between two points on Earth, which is a sphere, given their coordinates in terms of their latitudes and longitudes. The formula I'm using to calculate this distance is the haversine formula. I am using the numpy python library to perform the haversine calculation on each set of points. Considering the size of my dataset, it would be highly beneficial to fully utilize all 4 threads that my processor possesses. So, I'm using the following code snippet to distribute slices of my Pandas dataframe (the data structure I'm using the store the latitude and longitude values of the two points in question) and assign each thread to a helper function which processes each slice: CHUNK_AMOUNT = 4 #set this value to the number of threads you can afford to use ind = 0 #start index of each slice, and set is the pandas dataframe for i in range(CHUNK_AMOUNT): chunk = set[ind:int((i+1)*(set.shape[0]/CHUNK_AMOUNT))] t = threading.Thread(target=calculate_abs_displacement, args=(chunk, i)) #calculate_abs_displacement is the implementation of the haversine distance t.setDaemon(True) t.start() ind = int((i+1)*(set.shape[0]/CHUNK_AMOUNT)) However, when I run my code, I get the following error: Segmentation fault (core dumped). For the sake of reference, I am running Ubuntu 16.04 LTS on a local machine (not a VM) with a quad-core Intel Core i5-2400 CPU. Just for the sake of reference, when I run the "top" command in terminal, I find that only one core is at 100% while the rest of the cores are at 0% utilization. Then, after the error message shows up in console, all CPU cores are at 0% usage. What is the cause of this erratic behavior?

http://stackoverflow.com/a/51939973
score: 0
type: Answer
has body: You must add a foreign key fields which refers to User class of Django. Example : from django.contrib.auth.models import User class yourUserModel(models.Model): user = models.ForeignKey(User, on_delete=True) def your_authenticated_method(): self.user.is_authenticated() I hope that I answered well at your question
answers question: http://stackoverflow.com/q/51939726

http://stackoverflow.com/a/67088442
score: 29
downvote count: 1
answers question: http://stackoverflow.com/q/51937381
has body: Using the solution proposed in this answer has the drawbacks to apply the DPI to all the other figures that will be created within the notebook. This is fine in most cases, but if you need to set the DPI value ONLY for one figure, you can do it as follows: plt.imshow(img) plt.gcf().set_dpi(300) plt.show()
upvote count: 30
has comment: http://stackoverflow.com/comment/126693390
type: Answer

wifi
tag name: wifi
tags question: http://stackoverflow.com/q/51917850
type: Tag
tags question: http://stackoverflow.com/q/51916407

http://stackoverflow.com/comment/90603155
type: AnswerComment
has text: can you provide code where you used bulk_save_method?
type: Comment
comment on: http://stackoverflow.com/a/51822137
score: 1

http://stackoverflow.com/comment/90612725
type: QuestionComment
has text: When you say "it's not working", what does that mean? Only some records get inserted, nothing does, etc.? Is the list_files returning the proper results?
comment on: http://stackoverflow.com/q/51829008
score: 0
type: Comment

pandas-groupby
tags question: http://stackoverflow.com/q/51862276
tags question: http://stackoverflow.com/q/51946944
tags question: http://stackoverflow.com/q/51842534
tags question: http://stackoverflow.com/q/51851723
tags question: http://stackoverflow.com/q/51879295
tags question: http://stackoverflow.com/q/51948664
tags question: http://stackoverflow.com/q/51854809
tags question: http://stackoverflow.com/q/51914153
tags question: http://stackoverflow.com/q/51806361
tags question: http://stackoverflow.com/q/51906998
tag name: pandas-groupby
tags question: http://stackoverflow.com/q/51831161
tags question: http://stackoverflow.com/q/51866908
tags question: http://stackoverflow.com/q/51903925
tags question: http://stackoverflow.com/q/51926668
tags question: http://stackoverflow.com/q/51812382
tags question: http://stackoverflow.com/q/51832592
tags question: http://stackoverflow.com/q/51944727
tags question: http://stackoverflow.com/q/51826234
type: Tag
tags question: http://stackoverflow.com/q/51799818
tags question: http://stackoverflow.com/q/51942957
tags question: http://stackoverflow.com/q/51836237
tags question: http://stackoverflow.com/q/51851956
tags question: http://stackoverflow.com/q/51859841
tags question: http://stackoverflow.com/q/51849186
tags question: http://stackoverflow.com/q/51857052
tags question: http://stackoverflow.com/q/51923444
tags question: http://stackoverflow.com/q/51827686
tags question: http://stackoverflow.com/q/51938042

http://stackoverflow.com/comment/90863669
type: AnswerComment
type: Comment
has text: yeah, I figured that out on my own (but numpy is not available as a module in Renpy, so not an option). However, I've found another problem - it seems that the string-match only matches on first word of string - I will update my question a bit
comment on: http://stackoverflow.com/a/51955949
score: 0

http://stackoverflow.com/q/51904896
has title: Selenium: click() is not working when I print(), and calling error when I comment out print()
has answer: http://stackoverflow.com/a/51905028
has answer: http://stackoverflow.com/a/51905964
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51905964
has comment: http://stackoverflow.com/comment/90760629
has comment: http://stackoverflow.com/comment/90760691
type: Question
accepted answer: http://stackoverflow.com/a/51905028
tagged with: python
has body: I am trying using selenium to automate inputting of student comments into D2L. I am running into a problem that D2L has 2 instances of each element on the same page. GFD = driver.find_element_by_xpath("//a[@class='d2l-imagelink'][starts- with(@id,'ICN_Feedback_')][contains(@title,'Enter comments for FIRSTNAME LASTNAME in a new window')]") print(GFD) GFD.click() print() returns: <selenium.webdriver.remote.webelement.WebElement (session="729913326ada06df2b665cb77e224755", element="0.5122921302415122-1" but the GFD.click() wont work. To make matters more confusing for me, if i comment out the print(), i get an error from the GFD.click() Message: unknown error: Element ... is not clickable at point (894, 858). Other element would receive the click: ... (Session info: chrome=68.0.3440.106) (Driver info: chromedriver=2.41.578737 (49da6702b16031c40d63e5618de03a32ff6c197e),platform=Windows NT 10.0.17134 x86_64) I know that D2L has put 2 instances of the same link ID on the page (probably just to spite me). Is it possible to click() the first instance of this link using find_elements some how?
tagged with: selenium-webdriver
score: 0
answer count: 2
tagged with: selenium

http://stackoverflow.com/q/51872721
tagged with: datetime
upvote count: 1
tagged with: python
tagged with: regex
has body: import re exp1="2018-7-12 13:00:00" exp2="13:00:00 2018-7-12" reg= r'\d\d\d\d[./-](0?[1-9]|1[0-2])[./-](0?[1-9]|[12][0-9]|3[01]) (00|[0- 9]|1[0-9]|2[0-3]):([0-9]|[0-5][0-9]):([0-9]|[0-5][0-9])' compDate = re.search(reg,exp1) I have also tried lookahead expressions but they don't get to make them work. Any other solution is welcome
has comment: http://stackoverflow.com/comment/90696936
score: 1
has answer: http://stackoverflow.com/a/51873031
has answer: http://stackoverflow.com/a/51872976
type: Question
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/90696885
favorite count: 0
has comment: http://stackoverflow.com/comment/90696995
has title: How should I do to find dates and times without taking care of the order in Python?
has comment: http://stackoverflow.com/comment/90696853
type: UnansweredQuestion

http://stackoverflow.com/comment/90715684
type: AnswerComment
comment on: http://stackoverflow.com/a/51881916
score: 0
has text: Thank you so much! You are the best!
type: Comment

http://stackoverflow.com/comment/90828090
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51897701
has text: yes just adding to what @OluwafemiSule said, do check if you are connecting to the primary server and not the secondary.Better if you could share the exception. I have run the command on mongodb 4.0.1 with python 3.6, it works fine, you just one extra closing parentheses.

jupyter-notebook
tags question: http://stackoverflow.com/q/51907184
tags question: http://stackoverflow.com/q/51839697
tags question: http://stackoverflow.com/q/51832304
tags question: http://stackoverflow.com/q/51951323
tags question: http://stackoverflow.com/q/51886250
tags question: http://stackoverflow.com/q/51912284
tags question: http://stackoverflow.com/q/51810242
tags question: http://stackoverflow.com/q/51931874
tags question: http://stackoverflow.com/q/51926684
tags question: http://stackoverflow.com/q/51917736
tags question: http://stackoverflow.com/q/51869574
tags question: http://stackoverflow.com/q/51855627
tags question: http://stackoverflow.com/q/51887758
tags question: http://stackoverflow.com/q/51940146
tags question: http://stackoverflow.com/q/51851217
tags question: http://stackoverflow.com/q/51847654
tags question: http://stackoverflow.com/q/51830963
tags question: http://stackoverflow.com/q/51916337
tags question: http://stackoverflow.com/q/51816005
type: Tag
tags question: http://stackoverflow.com/q/51896866
tags question: http://stackoverflow.com/q/51868631
tags question: http://stackoverflow.com/q/51852465
tags question: http://stackoverflow.com/q/51877700
tags question: http://stackoverflow.com/q/51917470
tags question: http://stackoverflow.com/q/51799764
tags question: http://stackoverflow.com/q/51916265
tags question: http://stackoverflow.com/q/51949586
tags question: http://stackoverflow.com/q/51951373
tags question: http://stackoverflow.com/q/51934528
tags question: http://stackoverflow.com/q/51820891
tags question: http://stackoverflow.com/q/51852126
tags question: http://stackoverflow.com/q/51847645
tags question: http://stackoverflow.com/q/51852850
tags question: http://stackoverflow.com/q/51866261
tags question: http://stackoverflow.com/q/51852504
tags question: http://stackoverflow.com/q/51886722
tags question: http://stackoverflow.com/q/51827580
tags question: http://stackoverflow.com/q/51899881
tags question: http://stackoverflow.com/q/51812306
tags question: http://stackoverflow.com/q/51815744
tags question: http://stackoverflow.com/q/51923086
tags question: http://stackoverflow.com/q/51809893
tags question: http://stackoverflow.com/q/51914413
tag name: jupyter-notebook
tags question: http://stackoverflow.com/q/51851780
tags question: http://stackoverflow.com/q/51850537
tags question: http://stackoverflow.com/q/51798738
tags question: http://stackoverflow.com/q/51892593
tags question: http://stackoverflow.com/q/51813586
tags question: http://stackoverflow.com/q/51939708
tags question: http://stackoverflow.com/q/51956476
tags question: http://stackoverflow.com/q/51824991

http://stackoverflow.com/comment/90693336
type: QuestionComment
comment on: http://stackoverflow.com/q/51814307
has text: out of curiosity did any of these answer help you? Will you be marking one as accepted? (doesn't have to be mine).
score: 0
type: Comment

http://stackoverflow.com/q/51813207
tagged with: seaborn
has answer: http://stackoverflow.com/a/51813306
upvote count: 1
tagged with: python
type: AnsweredQuestion
score: 1
has title: Matplotlib/Seaborn on calculated value (Pandas Dataframe)
type: Question
accepted answer: http://stackoverflow.com/a/51813306
tagged with: pandas
downvote count: 0
answer count: 1
has body: I have the following table (Sorry for the format): Date Service Reference Document 2018-05-14 A Null 3542523 2018-05-15 B 01 6234242 2018-05-16 A 09 2342146 2018-05-16 C Null 2342342 I have a calculated value [Calculated] that is the Reference.count/Document.count() I want to create a graph similar to the next one: Where in the x-axis I have the date, on the y axis the calculated column but shown with different lines representing the different Services. So far I have this: def calculate(df): return df.Reference.count() / df.Document.count() df1 = df.groupby(['Date']).apply(calculate) However if I try to add Services to the groupby I cannot plot it using sns.lineplot() Is there another way or an easier way to add the Services dimension to the plot? Thanks
favorite count: 0

http://stackoverflow.com/q/51805947
upvote count: 1
accepted answer: http://stackoverflow.com/a/51806207
has title: Finding websites IP through reading lines
has comment: http://stackoverflow.com/comment/90567495
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51806200
downvote count: 0
score: 1
favorite count: 0
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/51806028
type: Question
has answer: http://stackoverflow.com/a/51806028
has comment: http://stackoverflow.com/comment/90567515
has answer: http://stackoverflow.com/a/51806207
tagged with: python
has body: i am trying to achieve a task that a script can load a file and iterate through lines and finding domain ip from each line. Tried doing it with this code: import socket with open('test.txt','r') as f: for i in f.readlines(): i.strip('\n') i.strip('\t') i.strip('\r') print(socket.gethostbyname(i)) f.close() But shows error Traceback (most recent call last): File "ip.py", line 8, in print(socket.gethostbyname(i)) socket.gaierror: [Errno -2] Name or service not known Any help would be appreciated. Thanks
answer count: 3

http://stackoverflow.com/q/51928856
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90810451
has comment: http://stackoverflow.com/comment/90810180
tagged with: text-classification
has answer: http://stackoverflow.com/a/73946341
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/73946341
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/90810522
has title: ValueError: cannot use sparse input in 'SVC' trained on dense data
has answer: http://stackoverflow.com/a/51930351
score: 0
tagged with: python-3.x
has body: I'm trying to run my classifier but I get this error import pandas import numpy as np import pandas as pd from sklearn import svm from sklearn.svm import SVC from sklearn import cross_validation from sklearn.metrics import confusion_matrix from sklearn.multiclass import OneVsOneClassifier from sklearn.linear_model import LogisticRegression from sklearn.model_selection import train_test_split from sklearn.metrics import precision_recall_fscore_support as score from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer dataset = pd.read_csv('all_topics_limpo.csv', encoding = 'utf-8') data = pandas.get_dummies(dataset['verbatim_corrige']) labels = dataset['label'] X_train, X_test, y_train, y_test = train_test_split(data, labels, test_size = 0.2, random_state = 0) count_vector = CountVectorizer() tfidf = TfidfTransformer() classifier = OneVsOneClassifier(SVC(kernel = 'linear', random_state = 100)) #classifier = LogisticRegression() train_counts = count_vector.fit_transform(X_train) train_tfidf = tfidf.fit_transform(train_counts) classifier.fit(X_train, y_train) test_counts = count_vector.transform(X_test) test_tfidf = tfidf.transform(test_counts) predicted = classifier.predict(test_tfidf) predicted = classifier.predict(X_test) print("confusion matrix") print(confusion_matrix(y_test, predicted, labels = labels)) print("F-score") print(f1_score(y_test, predicted)) print(precision_score(y_test, predicted)) print(recall_score(y_test, predicted)) print("cross validation") test_counts = count_vector.fit_transform(data) test_tfidf = tfidf.fit_transform(test_counts) scores = cross_validation.cross_val_score(classifier, test_tfidf, labels, cv = 10) print(scores) print("Accuracy: {} +/- {}".format(scores.mean(), scores.std() * 2)) My output error: ValueError: cannot use sparse input in 'SVC' trained on dense data I can not execute my code because of this problem and I am not understanding anything of what is happening. all output error Traceback (most recent ca…
tagged with: machine-learning
accepted answer: http://stackoverflow.com/a/51930351
tagged with: python

http://stackoverflow.com/q/51858681
has title: Use /dev/input/mice to generate a RSA key in Python3
tagged with: python-3.x
has body: Here's my code so far. What I want to do is generate an RSA key based on the user's mouse movements. from Crypto.PublicKey import RSA def rand(leng): data = open("/dev/input/mice","rb").read(leng) return data key = RSA.generate(1024,rand) print(key.exportKey()) The issue I'm having is that the program just freezes. The error seems to be in reading /dev/input/mice from inside a function. If I try reading it in python from anywhere else, it works as expected.
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90669441
answer count: 0
type: Question
has comment: http://stackoverflow.com/comment/90680397
score: 0
tagged with: public-key-encryption

cassandra-driver
type: Tag
tag name: cassandra-driver
tags question: http://stackoverflow.com/q/51818651

http://stackoverflow.com/comment/90760106
type: Comment
score: 0
comment on: http://stackoverflow.com/a/51901525
type: AnswerComment
has text: web2py _does_ support Python 3, so the problem must lie elsewhere.

http://stackoverflow.com/q/51809076
possible better answer: http://stackoverflow.com/a/51809333
tagged with: python
has comment: http://stackoverflow.com/comment/90574028
type: AnsweredQuestion
score: 3
type: Question
tagged with: numpy
answer count: 2
linked to: http://stackoverflow.com/q/32531377
tagged with: arrays
tagged with: python-xarray
upvote count: 3
has answer: http://stackoverflow.com/a/51812124
accepted answer: http://stackoverflow.com/a/51812124
has answer: http://stackoverflow.com/a/51809333
favorite count: 0
has title: Element-wise operations of arrays of different size
has body: What would be the fastest and most pythonic way to perform element-wise operations of arrays of different size without oversampling the smaller array? For example: I have a large array, A 1000x1000 and a small array B 10x10 I want each element in B to respond to 100x100 elements in array B. There is no need for any interpolation, just to use the same element in B for all 10000 operations in A. I can adjust the size of the two arrays to make the shape of A is a multiple of B. Typically they will be 1:10000 or 1:1000 in all dimensions. The arrays represents data samples with different resolution but same extent. I know that I can oversample array B, e.g. by using Kronecker product, but It would be nicer to keep array B small, especially as some of my arrays get really big to handle and store. I'm using xarray and dask, but any numpy operation would also work. I hope this snippet explains what I want to do: import numpy as np A = np.random.rand(10,10) B = np.random.rand(1000,1000) res = np.shape(B)[0]//np.shape(A)[0] #I want to add A and B so that each element in A is added to 100x100 elements in B. #This doesn't work of obvious reasons: #C = A+B #This solution sacrifices the resolution of B: C = A+B[::res,::res] #These solutions creates an unnecessary large array for the operation(don't they?): K = np.ones((res,res)) C = np.kron(A, K) + B C = np.repeat(np.repeat(A,res, axis=0), res, axis=1)+B I have a feeling that this problem must have been up before, but I couldn't find any answer that works for this particular case.
tagged with: dask
downvote count: 0

http://stackoverflow.com/q/51846013
accepted answer: http://stackoverflow.com/a/51846542
score: 0
answer count: 2
has body: I wrote a spider and it returns me data which is littered with spaces and newline characters. The newline characters also caused extract() method to return as a list. How do I filter these before it touch the selector? Filtering these after extract() is called breaks the DRY principle as there are a lot of data from a page I need to extract that is attributeless which makes the only way to parse it is through indexing. How do I filter these? Source it returns bad data like this { 'aired': ['\n ', '\n Apr 3, 2016 to Jun 26, 2016\n '], 'broadcast': [], 'duration': ['\n ', '\n 24 min. per ep.\n '], 'episodes': ['\n ', '\n 13\n '], 'favourites': ['\n ', '\n 22,673\n'], 'genres': ['Action', 'Comedy', 'School', 'Shounen', 'Super Power'], 'image_url': ['https://myanimelist.cdn-dena.com/images/anime/10/78745.jpg', 'https://myanimelist.cdn-dena.com/images/anime/10/78745.jpg', 'https://myanimelist.cdn-dena.com/images/anime/10/78745.jpg', 'https://myanimelist.cdn-dena.com/images/anime/10/78745.jpg', 'https://myanimelist.cdn-dena.com/images/anime/10/78745.jpg', 'https://myanimelist.cdn-dena.com/images/anime/10/78745.jpg', 'https://myanimelist.cdn-dena.com/images/anime/10/78745.jpg', 'https://myanimelist.cdn-dena.com/images/anime/10/78745.jpg', 'https://myanimelist.cdn-dena.com/images/anime/10/78745.jpg', 'https://myanimelist.cdn-dena.com/images/anime/10/78745.jpg', 'https://myanimelist.cdn-dena.com/images/anime/10/78745.jpg', 'https://myanimelist.cdn-dena.com/images/anime/10/78745.jpg', 'https://myanimelist.cdn-dena.com/images/anime/10/78745.jpg', 'https://myanimelist.cdn-dena.com/images/anime/10/78745.jpg', 'https://myanimelist.cdn-dena.com/images/anime/10/78745.jpg'], 'licensors': ['Funimation'], 'members': ['\n ', '\n 818,644\n'], 'popularity': ['\n ', '\n #21\n'], 'premiered': ['Spring 2016'], 'producers': ['Dentsu', 'Mainichi Broadcasting System', 'Movic', 'TOHO animation', 'Shueisha'], 'ranked': ['\n ', '\n #135', '\n ', '\n'], 'rating': ['\n ', '\n PG-13 - Teens 13 or ol…
linked to: http://stackoverflow.com/q/17098553
possible better answer: http://stackoverflow.com/a/51847173
tagged with: python
has comment: http://stackoverflow.com/comment/90645322
has answer: http://stackoverflow.com/a/51847173
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51846542
tagged with: scrapy
type: Question
has comment: http://stackoverflow.com/comment/90645483
has title: Scrapy returns garbage data such as spaces and newlines. How shall I filter these?

http://stackoverflow.com/q/51844797
type: Question
has body: This seems to be such a simple thing, but I seem to not be able to delete an event in Google Calendar using the library. With my code, I comment out the "delete event" code and run, which inserts an event and then lists that event. I also check to make sure I can see it in the UI. I then take the id from the event that was created and then put that as the eventId in the "delete event" call. Then I uncomment the deletion code and comment out the insertion code and run it again. This approach doesn't seem to work: I still see the event listed in the events().list output, and I still see it in the UI. # Delete Event resp = service.events().delete(calendarId='primary', eventId='9c9ppp94isp15103t54mtjss8s') pprint(vars(resp)) print('Event Deleted') # Inserts Event GMT_OFF = '-07:00' # PDT/MST/GMT-7 EVENT = { 'summary': 'Test Event2', 'start': {'dateTime': '2018-09-15T19:00:00%s' % GMT_OFF}, 'end': {'dateTime': '2018-09-15T22:00:00%s' % GMT_OFF}, } e = service.events().insert(calendarId='primary', sendNotifications=True, body=EVENT).execute() print('''*** %r event added: Start: %s End: %s''' % (e['summary'].encode('utf-8'), e['start']['dateTime'], e['end']['dateTime'])) # Read Events now = datetime.datetime.utcnow().isoformat() + 'Z' # 'Z' indicates UTC time print('Getting the upcoming 10 events') events_result = service.events().list(calendarId='primary', timeMin=now, maxResults=10, singleEvents=True, orderBy='startTime').execute() events = events_result.get('items', []) if not events: print('No upcoming events found.') for event in events: start = event['start'].get('dateTime', event['start'].get('date')) print(start, event['id'], event['summary']) When I print out the delete response (pprint(vars(resp))) it looks like this: {'_in_error_state': False, '_rand': &lt;built-in method random of Random object at 0x7f9ac007e420&gt;, '_sleep': &lt;built-in function sleep&gt;, 'body': None, 'body_size': 0, 'headers': {'accept': '*/*', 'accept-encoding': 'gzip, deflate', 'user-ag…
has answer: http://stackoverflow.com/a/51845530
answer count: 1
downvote count: 0
tagged with: google-calendar-api
tagged with: google-api-python-client
tagged with: python
accepted answer: http://stackoverflow.com/a/51845530
favorite count: 0
type: AnsweredQuestion
score: 3
upvote count: 3
has title: Deleting a calendar event using Google's Python client library

http://stackoverflow.com/q/51918151
tagged with: tesseract
has answer: http://stackoverflow.com/a/51918957
linked to: http://stackoverflow.com/q/41384732
type: Question
answer count: 1
has body: I'm using python tesseract wrapper (tesserocr) over tesseract v4. I'm running some sample code over a simple "HELLO WORLD" white-on-black image, but although the letters are correctly recognised, I'm getting wrong bounding boxes, see the original image overlayed with results Here is the code based on this SO post. Any idea how to get correct bboxes? Thank you! import cv2 import json from PIL import Image from tesserocr import PyTessBaseAPI, RIL img = cv2.imread('helloworld.jpg') gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) pillowImg = Image.fromarray(gray_img) with PyTessBaseAPI() as api: api.SetImage(pillowImg) api.Recognize() ri = api.GetIterator() level = RIL.SYMBOL for r in tesserocr.iterate_level(ri, level): bbox = r.BoundingBoxInternal(level) symbol = r.GetUTF8Text(level) conf = r.Confidence(level) print(json.dumps([symbol, conf, bbox])) And here is the output: ["H", 99.57249450683594, [185, 361, 234, 427]] ["E", 99.54733276367188, [251, 361, 292, 427]] ["L", 99.50984954833984, [311, 361, 353, 427]] ["L", 99.4959716796875, [362, 361, 404, 427]] ["O", 99.55082702636719, [420, 359, 472, 428]] ["W", 99.52144622802734, [529, 361, 589, 427]] ["O", 99.55513763427734, [589, 361, 611, 427]] ["R", 99.56971740722656, [647, 359, 721, 428]] ["L", 99.55563354492188, [756, 361, 779, 427]] ["D", 99.56954956054688, [807, 361, 861, 427]]
score: 0
has title: why python tesseract gives wrong bonuding boxes for letters?
tagged with: python
tagged with: python-tesseract
type: UnansweredQuestion

http://stackoverflow.com/comment/90764882
type: AnswerComment
has text: Whether it can be executed in a single line to handle huge dataframe with more than 2500k rows ?
score: 0
comment on: http://stackoverflow.com/a/51907075
type: Comment

http://stackoverflow.com/comment/90852692
has text: add `print(duration)` and I'm sure you will figure this out
comment on: http://stackoverflow.com/q/51951181
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51822820
score: 6
tagged with: pad
has answer: http://stackoverflow.com/a/56875026
upvote count: 6
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/69313237
accepted answer: http://stackoverflow.com/a/51823093
type: Question
has answer: http://stackoverflow.com/a/60617340
has comment: http://stackoverflow.com/comment/90599749
downvote count: 0
has title: Python Tkinter Entry pad text
possible better answer: http://stackoverflow.com/a/60617340
has answer: http://stackoverflow.com/a/51823048
has comment: http://stackoverflow.com/comment/90600389
has body: How could I pad the entry widget so it does not start writing right at the border of the widget? Visually, having a little space from the entry widget border. My progress: entry_widget.bind('&lt;FocusIn&gt;', lambda f: entry_widget.insert(0, ' ')) That adds an empty space when the user clicks the widget but there are multiple issue with this solution: When clicking out and clicking back in, it will add another space on top of the empty space or any text the user had filled in. I considered clearing the entry widget on FocusOut but that would also clear all the text that the user might have written. The user can delete the inserted space when getting the content, there is the additional space at the beginning. Though this is a small problem which can be solved by removing the first character of the content. And there might be more issues which I did not account for. I think the way where my code is heading is bad, therefore I am asking if anyone has any idea how to 'properly' pad the entry widget?
has answer: http://stackoverflow.com/a/51823093
linked to: http://stackoverflow.com/q/17635905
tagged with: python
tagged with: tkinter-entry
favorite count: 0
tagged with: tkinter
answer count: 5

http://stackoverflow.com/q/51880881
score: 0
has comment: http://stackoverflow.com/comment/90713459
has answer: http://stackoverflow.com/a/63464091
has title: TypeError: a bytes-like object is required, not 'str' when writing to a file
favorite count: 0
tagged with: python-3.x
has body: import socket def Main(): host = '127.0.0.1' port = 5001 server = ('127.0.0.1',5000) s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.bind((host, port)) message = input("-&gt; ") while message != 'q': s.sendto (message, server) data, addr = s.recvfrom(1024) print ('Received from server: ' + (data)) message = input("-&gt; ") s.close() if __name__ == '__main__': Main() When I run this code the line s.sendto (message, server) causes a TypeError: a bytes-like object is required, not 'str'. How do you fix this kind of problem? I tried searching the internet but can't find a solution.
type: UnansweredQuestion
tagged with: sockets
linked to: http://stackoverflow.com/q/35092256
tagged with: python
has answer: http://stackoverflow.com/a/51880964
upvote count: 1
downvote count: 1
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/90728147

http://stackoverflow.com/a/51808413
has comment: http://stackoverflow.com/comment/90586164
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/90573565
accepted answer of: http://stackoverflow.com/q/51806436
has body: Solution As @Andersson already mentioned, you can use get_attribute('value') to extract the text from input field. Let's create the following example: driver.get('http://demo.automationtesting.in/Register.html') # get sample page time.sleep(3) # pause to wait until page loads input_el = driver.find_element_by_xpath("//*[@id='basicBootstrapForm']/div[4]/div/input") # phone input field input_el.click() input_el.send_keys("123") print(input_el.text) # prints nothing print(input_el.get_attribute("value")) # prints '123' Analysis If we go to the dev tools: we will see the following HTML for our input: it does not have any text in the tag, that's why calling print(input_el.text) will print nothing. If the HTML would look like: Email address* then print(label_el.text) would print the text inside label tag - Email address*.
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51806436
type: Answer
has comment: http://stackoverflow.com/comment/90578285

http://stackoverflow.com/comment/90780468
type: Comment
has text: Your "answer" isn't nearly half as descriptive as the comments, would you consider putting some effort into the answer please?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51915258

http://stackoverflow.com/q/51870981
upvote count: 1
type: Question
tagged with: flask
has answer: http://stackoverflow.com/a/51871284
has answer: http://stackoverflow.com/a/51871321
answer count: 3
has answer: http://stackoverflow.com/a/51871270
tagged with: url
downvote count: 0
has body: so here is my relativly simple code: @app.route("/[&lt;string:pfade&gt;]") def testaufruf(pfade): s=list(pfade) part = [i for i,x in enumerate(s) if x=="$"] print(part) s[part]="\\" print(part) My problem is I want to pass something like 127.0.0.1:5000/[Test$path1] now I take this Test$path1 make it an list and want to replace every $ with an \ These lines work: s=list(pfade) part = [i for i,x in enumerate(s) if x=="$"] print(part) They return me the place where the $ is located but the second part to replace the $ does not work. I did search a lot but couldnt find a solution to this problem. Thanks for help in advance.
favorite count: 0
possible better answer: http://stackoverflow.com/a/51871321
tagged with: python-3.x
tagged with: arguments
tagged with: python
has title: Change character in list Python Flask
accepted answer: http://stackoverflow.com/a/51871270
type: AnsweredQuestion
score: 1

http://stackoverflow.com/q/51826601
score: 0
has comment: http://stackoverflow.com/comment/90607845
has comment: http://stackoverflow.com/comment/90625425
tagged with: timer
type: UnansweredQuestion
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/90607511
has title: Timer function to Python Script
type: Question
linked to: http://stackoverflow.com/q/19641619
has comment: http://stackoverflow.com/comment/90614845
has comment: http://stackoverflow.com/comment/90618580
has body: I’m relatively new to Python and I’m trying to figure out how to set up a timer in my script for it to run daily at a specific time instead of using Windows Task Scheduler. The below script opens a macro enabled excel spreadsheet and runs the macro. I’ve verified that everything is working as expected. #REFERENCE FILE PATH AND RUN MACROS# import os import win32com import win32com.client # path where macro enable sheet is if os.path.exists ("C:\\Users\\hernri01\\Documents\\Python Scripts\\SDK Cert Source\\Macro Autosave\\Macro_SDKtoXLSX.xlsm"): xl = win32com.client.Dispatch('Excel.Application') xl.Workbooks.Open(Filename = "C:\\Users\\hernri01\\Documents\\Python Scripts\\SDK Cert Source\\Macro Autosave\\Macro_SDKtoXLSX.xlsm", ReadOnly=1) # runs macro xl.Application.Run("openfilesandsave") del xl #PRINT FINAL COMPLETED MESSAGE print("Macro refresh completed!") When I try to add the Timer I am receiving an error message. Script and error below: #REFERENCE FILE PATH AND RUN MACROS# import os import win32com import win32com.client import datetime from threading import Timer xl = win32com.client.Dispatch('Excel.Application') def run_prog(): xl.Workbooks.Open(Filename = "C:\\Users\\hernri01\\Documents\\Python Scripts\\SDK Cert Source\\Macro Autosave\\Macro_SDKtoXLSX.xlsm", ReadOnly=1) xl.Application.Run("openfilesandsave") xl.Workbooks.Close() #PRINT FINAL COMPLETED MESSAGE# print("Macro refresh completed!") # how often python to run #t = Timer(3600 * 24,run_prog) #3600 = seconds in 1 hour t = Timer(10,run_prog) # 10 = run every 10 seconds t.start() x=datetime.datetime.today() #y=x.replace(day=x.day, hour=4, minute=0, second=0, microsecond=0) y=x.replace(day=x.day, hour=11, minute=56, second=0, microsecond=0) delta_t=y-x secs=delta_t.seconds+1 print (secs) t = Timer(secs, run_prog) t.start() print("Macro refresh completed!") Error Message: 48 Macro refresh completed! &gt;&gt;&gt; Exception in thread Thread-1: Traceback (most recent call last): File "C:\Users\hernri01\AppDa…

http://stackoverflow.com/comment/90716477
score: 0
type: AnswerComment
type: Comment
has text: They don't, since they use the standard input and output. It is then the client's reponsibility to be able to read the files. I'll quote the docs on why superuser is required, if directly copying from a named file: "COPY naming a file or command is only allowed to database superusers, since it allows reading or writing any file that the server has privileges to access." In other words you could overwrite for example configuration files and the like.
comment on: http://stackoverflow.com/a/51860610

http://stackoverflow.com/comment/90769202
has text: You're clearly using `pack`, I don't know why you think everything is using `grid`. The error message means exactly what it says: you can't mix `grid` and `pack` with widgets that share the same parent. You have to use one or the other.
comment on: http://stackoverflow.com/q/51908825
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/comment/90860805
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51935876
type: Comment
has text: Thanks, this worked, I like using the numpy.where command to create the Quality column and set the value in one go. I was doing this with 2 lines before, and thought about using an if statement... I like this better... Also thank you for putting the comments, a lot of responses do not include them.

http://stackoverflow.com/comment/90644921
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51845321
has text: I add this to the for loop if words[i] == words[i+1] and words[i] != words[i-1] doesn't this do the same? It seem like it workd
score: 0

http://stackoverflow.com/q/51849001
has title: Anaconda installation trouble for mac osx
has comment: http://stackoverflow.com/comment/90651892
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90651339
tagged with: anaconda
answer count: 0
type: Question
has comment: http://stackoverflow.com/comment/90651545
has comment: http://stackoverflow.com/comment/90651312
has body: Quick question to try and find out what I'm doing wrong for installing anaconda on mac osx. I've downloaded the version for python 3.5, but when I try to open and run the file it just opens in textedit with a bunch of symbols. A sample of what appears in the text editor: xar! (± ÆB x⁄îWY”¢H≥æ7¬ˇ–—Á“ò \&amp;ﬁÓâbG e ÔX§dW ¸ı_È€o˜7=}ŒÃπ0ÑL2+´2ü'≥ﬁ˛ ‚”˝‹¥i]}˘L˛N|˛tÆ¢:N+¯Â≥cãø≠?ˇ˘uÚ6 Õ◊…ß∑Æéﬂß∑®9 ∂¯≠KÀÛWä ◊ø Ão cìÙ ÃÍ äyõˇıìó—Â Âm_~jª±8 ˘‹^ ÚÛSÛÈ≠Níˆ‹}%ﬁÊﬂû^“6}&lt;ùøÕ_ O Û Ø∑6ÖU–ıÕ˘√£iÅø:§~ÈëY˛p˘Èmw ï*©?·É®⁄/ü/]w˝c>G ˝é ø◊ úS AÃâÕ „%ˇÁ}âOo Do I not have something updated correctly? I also notice that within Finder -> Downloads, where the file is located, under the "Kind" column is says document, when in the installing videos I've watched it says install package. So maybe it's not even downloading correctly. Anyone have any ideas?
score: 0

http://stackoverflow.com/q/51861119
favorite count: 0
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/59005788
has comment: http://stackoverflow.com/comment/90674605
has body: I have written a python function which will make api call from postman I am getting the result in a json format that too in a line like this [{u'major': 1, u'uuid': u'b5b182c7-eab1-4988-aa99-b5c1517008d8', u'imageurl': u'', u'name': u'Asset 0', u'location': {u'lampid': u'40000c2a691226b3', u'longitude': -121.91999816894531, u'altitude': 33.269363438, u'lampname': u'LAMP_3', u'floorid': u'50522CB5-F8F8-4F43-808A-44CFD86EC0CF', u'suiteid': u'2FF35822-81DB-4469-8AE3-95D34B6EEDB1', u'lastseen': u'2018-08-15T11:10:06.510Z', u'latitude': 37.40650177001953, u'rssi': -39, u'buildingid': u'93CB2950-46D0-4231-B21C-C4691ACFCC1D'}, u'assettypeid': u'07810021-DD92-4BA9-946B-4829AD8E56DC', u'id': u'226854A8-C634-4BB8-9959-0A080B932BD0', u'minor': 5, u'description': None}, {u'locationError': u'no location found', u'major': 1, u'uuid': u'b5b182c7-eab1-4988-aa99-b5c1517008d8', u'imageurl': u'', u'name': u'Asset 3', u'assettypeid': u'07810021-DD92-4BA9-946B-4829AD8E56DC', u'id': u'E6DBA4C2-C2E9-4162-83F4-5906101F8EE8', u'minor': 8, u'description': None}, {u'major': 1, u'uuid': u'b5b182c7-eab1-4988-aa99-b5c1517008d8', u'imageurl': u'', u'name': u'Asset 2', u'location': {u'lampid': u'40000c2a691226b3', u'longitude': -121.91999816894531, u'altitude': 33.269363438, u'lampname': u'LAMP_3', u'floorid': u'50522CB5-F8F8-4F43-808A-44CFD86EC0CF', u'suiteid': u'2FF35822-81DB-4469-8AE3-95D34B6EEDB1', u'lastseen': u'2018-08-15T11:10:12.552Z', u'latitude': 37.40650177001953, u'rssi': -48, u'buildingid': u'93CB2950-46D0-4231-B21C-C4691ACFCC1D'}, u'assettypeid': u'07810021-DD92-4BA9-946B-4829AD8E56DC', u'id': u'8EF8189A-C902-4BCA-B1CA-787FE8E137AA', u'minor': 7, u'description': None}, {u'locationError': u'no location found', u'major': 1, u'uuid I want it in block My code is def getAllAssets(api, token): url = api + '/v1/assettracking/assets?inline=location' headers = {'authorization': 'Bearer ' + token, 'content-type': 'application/json'} data = requests.get(url, headers=headers) if data.status_code…
accepted answer: http://stackoverflow.com/a/51861232
has comment: http://stackoverflow.com/comment/90674473
upvote count: 2
possible better answer: http://stackoverflow.com/a/59005788
answer count: 3
has title: how to convert json into plain text in python
has comment: http://stackoverflow.com/comment/90674701
tagged with: http://stackoverflow.com/tag/json
has answer: http://stackoverflow.com/a/51861255
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51861232
has comment: http://stackoverflow.com/comment/90677507
downvote count: 0

http://stackoverflow.com/comment/90664017
type: AnswerComment
type: Comment
has text: Hello, thank you for your time, and your advice, alas, it does not work. I am a little lost, I apply your advice, my formulary is good ? => https://pastebin.com/NyCYa7r4 . Again thank you for helping me
comment on: http://stackoverflow.com/a/51850330
score: 0

http://stackoverflow.com/q/51947506
has comment: http://stackoverflow.com/comment/90845424
type: UnansweredQuestion
downvote count: 2
tagged with: pip
type: Question
has comment: http://stackoverflow.com/comment/90844676
score: -2
has comment: http://stackoverflow.com/comment/90845873
linked to: http://stackoverflow.com/q/10919569
has comment: http://stackoverflow.com/comment/90844669
has answer: http://stackoverflow.com/a/51947693
has comment: http://stackoverflow.com/comment/90845520
upvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/51947627
has body: i have been trying to install module for python-3.6 through pip. i've read these post from stackoverflow and from python website, which seemed promising but they didn't worked for me. Install a module using pip for specific python version python website I've added python3.6 main folder,Scripts and Lib to PATH and i've tried these commands.But somehow they refer to anaconda installations. C:\Program Files (x86)\Python36-32\Scripts&gt; pip3 install xlrd C:\Program Files (x86)\Python36-32\Scripts&gt; pip install xlrd C:\Program Files (x86)\Python36-32\Scripts&gt; pip3.6 install xlrd C:\Program Files (x86)\Python36-32\Scripts&gt; py -3.6 -m pip install xlrd C:\Program Files (x86)\Python36-32\Scripts&gt; py -3 -m pip install xlrd but they give same answer. Requirement already satisfied: xlrd in c:\programdata\anaconda3\lib\site-packages (1.1.0)
has comment: http://stackoverflow.com/comment/90844995
answer count: 3
tagged with: python
has comment: http://stackoverflow.com/comment/90844459
has title: how to install python module for specific python version
has answer: http://stackoverflow.com/a/52115542
tagged with: python-3.x

http://stackoverflow.com/q/51939224
score: 2
answer count: 1
tagged with: arrays
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/90829028
has comment: http://stackoverflow.com/comment/90828872
tagged with: python
tagged with: spread
upvote count: 2
type: UnansweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/90828964
has body: I am plotting 16 arrays with different shapes onto one plot.However, things are getting difficult because what I would like to do is plot the maximum spread of data by essentially finding the maximum and minimum value at each point on the y-axis and shading between this area. It would hopefully look something like this, except my lines are vertical so the spread would be across on the x rather than the y as shown here. For simplicity, I'm working with some very simplified dummy data to figure out the best way to do this, but ultimately I'll be plotting more data with much larger lengths and a bit different values. import matplotlib as mp import matplotlib.pylab as plt import numpy as np d1 = np.random.randint(0,10,15) d2 = np.random.randint(0,10,20) d3 = np.random.randint(0,10,25) d4 = np.random.randint(0,10,30) y1=np.linspace(0,30,15,True) y2=np.linspace(0,30,20,True) y3=np.linspace(0,30,25,True) y4=np.linspace(0,30,30,True) plt.style.use('bmh') fig = plt.figure(figsize=(5,15)) plt.plot(d1,y1,'red') plt.plot(d2,y2,'blue') plt.plot(d3,y3,'green') plt.plot(d4,y4,'orange') plt.xticks(np.arange(0,11,1)) plt.yticks(np.arange(0,31,1)) plt.show() And with this code, this is currently what the plot looks like as shown on the left. What I want is something like on the right (which I did quickly by hand as an example) with the area between the black lines shaded. As you can see below, the black line follows whatever line is farthest on the outside (i.e. the smallest and largest values at each y point), and then I'd like to shade this region in between the two black lines. Thanks for any help or advice!
tagged with: linegraph
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/90828940
has title: Finding spread of values between multiple arrays of different shapes in a line graph with matplotlib
has comment: http://stackoverflow.com/comment/90828713
has answer: http://stackoverflow.com/a/51953216

http://stackoverflow.com/a/51818386
has comment: http://stackoverflow.com/comment/119505104
has comment: http://stackoverflow.com/comment/130438397
upvote count: 25
type: AcceptedAnswer
has body: Django has - as far as I know at the moment - no builtin support for views. But you can construct such views, by using the django-database-view package. After installing the package (for example with pip): pip install django-database-view Furthermore the dbview app has to be registered in the settings.py file: # settings.py INSTALLED_APPS = ( # ... 'dbview', # ... ) Now you can construct a view, this looks a bit similar to the construction of a model, except that you need to implement a view(..) function that specifies the query behind the view. Something similar to: from django.db import models from dbview.models import DbView class CustomerEMailList(DbView): cust = models.OneToOneField(Customer, primary_key=True) cust_name = models.CharField() cust_email = models.CharField() @classmethod def view(klass): qs = (Customers.objects.filter(cust_email__isnull=False) .values('cust_id', 'cust_name', 'cust_email')) return str(qs.query) Now we can make a migrations: ./manage.py makemigrations Now in the migration, we need to make a change: the calls to migrations.CreateModel that are related to the constructed view(s), should be changed to the CreateView of the dbview module. Something that looks like: from django.db import migrations from dbview import CreateView class Migration(migrations.Migration): dependencies = [] operations = [ CreateView( name='CustomerEMailList', fields=[ # ... ], ), ]
answers question: http://stackoverflow.com/q/51817841
type: Answer
accepted answer of: http://stackoverflow.com/q/51817841
score: 25
has comment: http://stackoverflow.com/comment/135570339
downvote count: 0
has comment: http://stackoverflow.com/comment/99614595
has comment: http://stackoverflow.com/comment/130484731
has comment: http://stackoverflow.com/comment/130446112
has comment: http://stackoverflow.com/comment/94545781
has comment: http://stackoverflow.com/comment/110000588

http://stackoverflow.com/q/51900989
has title: Python List: Select two lists of the respective index
type: Question
linked to: http://stackoverflow.com/q/1663807
has body: list1 = ['ibsdr1', 'ibsds1', 'ibsds1', 'ibsdm2', 'ibsdm2', 'ibsdm2'] list2 = ['Gig 0/0/1', 'Gig 6/47', 'Gig 5/47', 'Gig 6/7', 'Gig 6/3', 'Gig 5/3'] I have two lists, I need to run below script on each device of list1 with the respective port of list2. list1[0]. should select only list2[0], it shouldn't select the rest of list2. Each and every list index should select only their respective index. ibsdr1 should select Gig 0/0/1 ibsds1 should select Gig 6/47 ibsds1 should select Gig 5/47 ibsdm2 should select Gig 6/7 ibsdm2 should select Gig 6/3 ibsdm2 should select Gig 5/3 Below is the script I am trying to run, but I am not getting the right output. list1 indexes are selecting all the list2 indexes one by one. for (sw, op) in zip(list1, list2): connect = {'device_type': 'cisco_ios', 'ip': sw, 'username': user, 'password': password, 'port': 22} net_connect1 = ConnectHandler(**connect) opout = net_connect1.send_command_expect('show interfaces '+op+' switchport') opp.append(opout) print (opp)
has comment: http://stackoverflow.com/comment/90754107
has comment: http://stackoverflow.com/comment/90753514
has comment: http://stackoverflow.com/comment/90754012
score: 0
has comment: http://stackoverflow.com/comment/90753478
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90753442
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90754052
tagged with: python
has comment: http://stackoverflow.com/comment/90754347

http://stackoverflow.com/comment/90833543
score: 0
type: AnswerComment
type: Comment
has text: No, then one executes before the other. Updated the answer slightly.
comment on: http://stackoverflow.com/a/51934816

http://stackoverflow.com/comment/90789390
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51919153
has text: But that isn't the point. The point is that one socket corresponds to one wsgi file. If your subdomain is serving a separate Django site via a separate wsgi file, it needs a separate socket and a separate gunicorn instance.

http://stackoverflow.com/a/51826399
type: Answer
has comment: http://stackoverflow.com/comment/90607088
has body: Just do it in two steps, like this: def transform(x): result = {'name': x.name}; try: result['result_cap1'] = NLTK.parser(cap1) except: result['result_cap1'] = " " try: result['result_cap2'] = NLTK.parser(cap2) except: result['result_cap2'] = " " return result
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/51826296

http://stackoverflow.com/comment/90874157
has text: Sure. For the record: please consider deleting comments that are no longer required/useful.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51946545

http://stackoverflow.com/q/51818724
has body: I have a multi-index dataframe where the index has been dervied from dates. It comprises year and quarter values. What I want to achive is a plot with two sets of tick labels on the x axis. The minor tick label should represent the quarter values (1 to 4) and the major ticklabels the year values. However, I do not want all of the year ticklabels displayed, only unique years for each of the four quarters. This is straightforward to represent in an excel graph, here is an example of what I am trying to reproduce. Here is a sample from my dataset. serotype_df = pd.DataFrame({'13v': {(2002, 1): 5, (2002, 2): 9, (2002, 3): 23, (2002, 4): 11, (2003, 1): 1, (2003, 2): 12, (2003, 3): 22, (2003, 4): 15, (2004, 1): 10, (2004, 2): 11, (2004, 3): 30, (2004, 4): 11, (2005, 1): 9, (2005, 2): 20, (2005, 3): 20, (2005, 4): 7}, '23v': {(2002, 1): 1, (2002, 2): 8, (2002, 3): 18, (2002, 4): 5, (2003, 1): 5, (2003, 2): 16, (2003, 3): 13, (2003, 4): 7, (2004, 1): 4, (2004, 2): 4, (2004, 3): 20, (2004, 4): 5, (2005, 1): 4, (2005, 2): 5, (2005, 3): 10, (2005, 4): 5}, '7v': {(2002, 1): 30, (2002, 2): 75, (2002, 3): 148, (2002, 4): 68, (2003, 1): 26, (2003, 2): 75, (2003, 3): 147, (2003, 4): 67, (2004, 1): 32, (2004, 2): 84, (2004, 3): 151, (2004, 4): 62, (2005, 1): 21, (2005, 2): 49, (2005, 3): 81, (2005, 4): 26}, 'Non-typed': {(2002, 1): 1, (2002, 2): 2, (2002, 3): 4, (2002, 4): 4, (2003, 1): 3, (2003, 2): 5, (2003, 3): 9, (2003, 4): 8, (2004, 1): 1, (2004, 2): 4, (2004, 3): 6, (2004, 4): 4, (2005, 1): 4, (2005, 2): 10, (2005, 3): 7, (2005, 4): 11}, 'Non-vaccine': {(2002, 1): 2, (2002, 2): 7, (2002, 3): 10, (2002, 4): 6, (2003, 1): 4, (2003, 2): 5, (2003, 3): 13, (2003, 4): 8, (2004, 1): 2, (2004, 2): 4, (2004, 3): 19, (2004, 4): 8, (2005, 1): 4, (2005, 2): 3, (2005, 3): 15, (2005, 4): 5}}) I have tried to use some code from a different SO example. Here is the code I tried. import pandas as pd import matplotlib.pyplot as plt fig = plt.figure(figsize=(14,8), dpi=200) ax = fig.add_subplot(1…
type: AnsweredQuestion
tagged with: matplotlib
duplicate of: http://stackoverflow.com/q/19184484
type: Question
upvote count: 15
linked to: http://stackoverflow.com/q/31845258
score: 15
has comment: http://stackoverflow.com/comment/114173427
has answer: http://stackoverflow.com/a/51824748
duplicate of: http://stackoverflow.com/q/31845258
tagged with: pandas
answer count: 1
downvote count: 0
has title: Plot two levels of x_ticklabels on a pandas multi-index dataframe
favorite count: 0
tagged with: python-3.x
linked to: http://stackoverflow.com/q/66016045
linked to: http://stackoverflow.com/q/19184484
accepted answer: http://stackoverflow.com/a/51824748
tagged with: python

http://stackoverflow.com/a/51940854
has body: Given a list: In [11]: xs = ['test_a','help_b','apple_c'] I can split each element and then "unzip" (transpose) the results: In [12]: a, b = zip(*map(lambda x: x.split('_'), xs)) This is what I'm left with: In [13]: a Out[13]: ('test', 'help', 'apple') In [14]: b Out[14]: ('a', 'b', 'c')
score: 1
upvote count: 1
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51940830

http://stackoverflow.com/a/51948766
has comment: http://stackoverflow.com/comment/90850186
has comment: http://stackoverflow.com/comment/90848207
type: Answer
has comment: http://stackoverflow.com/comment/90848153
has comment: http://stackoverflow.com/comment/90868466
answers question: http://stackoverflow.com/q/51944665
score: 0
has body: You are using --master yarn-cluster which is deprecated, as the log you posted says on the first line. This could be the cause of your problem, but I'm not sure. Try changing your shell script to: #!/bin/sh /usr/lib/software/spark/spark-2.1/bin/spark-submit \ --master yarn \ --deploy-mode cluster \ --driver-memory 5G \ --num-executors 12 \ ./job.py See: https://spark.apache.org/docs/2.1.0/submitting-applications.html Alternatively, you could try to run your application in client mode. The driver will then run on the local machine (where you run spark-submit from), but the executors will run on YARN worker nodes. This is done using --deploy-mode client. This will likely solve your error, but you might have a specific reason to run the driver on a YARN node.

http://stackoverflow.com/q/51945357
answer count: 3
tagged with: python
has answer: http://stackoverflow.com/a/51945709
has answer: http://stackoverflow.com/a/51945889
type: AnsweredQuestion
has title: Django rest_framework: How to pass additional attribute to exception / error response?
accepted answer: http://stackoverflow.com/a/51945889
tagged with: django
type: Question
has body: I'm using Python 3.6 with Django 1.11.9 and rest_framework 3.6.2. I have a view (APIView) which can only be accessed by some users who successfully pass a given HasUnlimitedAccesPermission check. In case of failure to pass the latter, I raise a PermissionDenied with a detailed message of my choice about the error to pass on to front-end. So far so good, all of that is easily achievable by applying the HasUnlimitedAccessPermission to my view thanks to the "permission_classes" decorator (yeah, I'm using a function_based view, here). Now, what I would like to achieve is passing an additional attribute to my error response JSON (when the user fails to pass the permission test). This attribute would be an "error_id" attribute that would give the front-end developer the ability to adapt the error display depending on the "error_id" value. An example of the response JSON would be : { "error": "To enjoy this feature, go pick one of our pay offer!", "error_id": "no_unlimited_access" } Any idea on how to achieve this?
has comment: http://stackoverflow.com/comment/90840127
has comment: http://stackoverflow.com/comment/90840171
possible better answer: http://stackoverflow.com/a/51945589
tagged with: django-rest-framework
has answer: http://stackoverflow.com/a/51945589
score: 0

http://stackoverflow.com/a/51984694
upvote count: 1
answers question: http://stackoverflow.com/q/51941475
score: 1
downvote count: 0
type: Answer
has body: I'm not sure why are you using sub_filter in your nginx config. Seems to me you are hosting flower in a particular url like xyz.com/flower that's why you are using sub_filter. Though I have not used flower in such a way, but it seems to me wrong. There is another mistake which I could find, i.e. you are placing location /flower/static/ below location /flower/ hence all static requests are going to be handled by the location /flower/ code block You nginx config should look something like this: server { location /flower/static { alias /the/path/to/flower/static; } location /flower { rewrite ^/flower/(.*)$ /$1 break; proxy_pass http://localhost:5555; proxy_set_header X-Real-IP $remote_addr; proxy_set_header Host $host; } } You could read more about the settings on the documentation and example

http://stackoverflow.com/comment/94751919
type: QuestionComment
comment on: http://stackoverflow.com/q/51898157
has text: Also, try this: https://stackoverflow.com/questions/46744968/how-to-suppress-console-error-warning-info-messages-when-executing-selenium-pyth
score: 0
type: Comment

http://stackoverflow.com/q/51874042
linked to: http://stackoverflow.com/q/24752395
type: Question
tagged with: exception
has comment: http://stackoverflow.com/comment/90699838
tagged with: python
has answer: http://stackoverflow.com/a/51874480
upvote count: 2
answer count: 1
has comment: http://stackoverflow.com/comment/90699840
has title: how to handle exceptions while writing a library in python
has comment: http://stackoverflow.com/comment/90699875
accepted answer: http://stackoverflow.com/a/51874480
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90699784
downvote count: 0
has body: Consider writing a small library in python that has this one simple method x which accepts an argument ac &amp; returns the computed value 10/ac. now the catch here is ac cannot be 0. so how do i handle this case in my method.there are these ways that comes to my mind. NOTE: i have looked into python exception handling but it just shows how to use try except not the specific problem that i am asking. method 1 def x(ac): try: return (10/ac) except ZeroDivisionError: raise ZeroDivisionError("ac cannot be zero") The above code just uses a plain try except block to catch spcific exceptions and raises the exception to the calling code. so the calling code would look like this: # some script... try: x(0) except ZeroDivisionError as e: log(e) but in this case, i would have to know before hand what all possible exceptions that method x might raise. Method 2: def x(ac): if ac == 0: raise ValueError("ac cannot be zero") # or ZeroDivisionError?? else: return (10/ac) i guess this is semantically same as previous one except that to check some conditions(that we know might occur) using if's &amp; raising exceptions based on that. It also suffers from the same problem of knowing beforehand what exceptions the method might throw. method 3 The last method is not handling any exception in the library method rather leave it to the client code but this obviously doesn't makes sense as the client would never be able to know why exactly the error might occur while resort to something like def x(ac): return (10/ac) try: x(20) except Exception as e: log(e) now this method here was a simple method with just one opertaion but what if the method itself is doing something complicated like connecting to the database then fetching some results. something like : def x(db): conn = db.connect('localhost') results = connec.fetch(user_id=2) return results if something is unclear please let me know.
favorite count: 0

http://stackoverflow.com/comment/90696941
comment on: http://stackoverflow.com/a/51871764
score: 0
type: AnswerComment
type: Comment
has text: Why do you think that target link is *"React element"*?

http://stackoverflow.com/comment/90577919
type: AnswerComment
has text: Also, if you want to handle negatives, it's not enough to just do `i = -i`. You also need to account for negative *multiples* of each number, and assuming the list is sorted no longer guarantees that divisors are on the left and multiples are on the right.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/51811369

http://stackoverflow.com/q/51910372
downvote count: 0
has answer: http://stackoverflow.com/a/51910521
has answer: http://stackoverflow.com/a/51910404
has answer: http://stackoverflow.com/a/51910488
accepted answer: http://stackoverflow.com/a/51910462
favorite count: 0
has comment: http://stackoverflow.com/comment/90771067
answer count: 5
tagged with: python
has comment: http://stackoverflow.com/comment/90771155
has comment: http://stackoverflow.com/comment/90771163
has title: Python list of string manipulation
upvote count: 3
has body: Consider the list ['010','10','00'] ; I'm trying to identify index positions that contain the character '1'. Here, the expected result is, [0,1], since element 1, '010' contains '1' at index 1 and element 2, '10' contains '1' at index 0. sample = ['010','10','00'] result = set() for e in sample: for i,c in enumerate(list(e)): if c == '1': result.add(i) Is there a more efficient solution for this?
has comment: http://stackoverflow.com/comment/90771057
type: Question
has comment: http://stackoverflow.com/comment/90771044
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51910462
score: 3
has comment: http://stackoverflow.com/comment/90770906
tagged with: list-comprehension
has comment: http://stackoverflow.com/comment/90771186
has answer: http://stackoverflow.com/a/51910491
possible better answer: http://stackoverflow.com/a/51910404

http://stackoverflow.com/comment/90892110
has text: hi, so the next part of my program actually requires me to conduct equations on variables such as the variable I had set as onetotal. Is there a way from this code to still set onetotal so I can do calculations such as this: onetotaladjusted = onetotal * 1.2?
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51954062

http://stackoverflow.com/q/51952333
has comment: http://stackoverflow.com/comment/90855817
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/90855468
favorite count: 0
has answer: http://stackoverflow.com/a/51953223
tagged with: python
accepted answer: http://stackoverflow.com/a/51953223
upvote count: 3
has body: I have a pandas dataframe in the following format that I would like to reduce. Index CITY YEAR MONTH HOUR TEMP DP CC ASTR BSTR 2018-04-10 00:00:00 AAA 2018 4 1 20 10 0 hd pv 2018-04-10 01:00:00 AAA 2018 4 2 10 10 10 fg pv ... 2018-04-10 00:00:00 BBB 2018 4 1 30 20 5 cv er 2018-04-10 01:00:00 BBB 2018 4 2 20 20 5 hd fd ... 2018-04-10 00:00:00 CCC 2018 4 1 20 30 10 cv fd 2018-04-10 01:00:00 CCC 2018 4 2 10 10 5 df ee ... Then the output should be something like: Index YEAR MONTH HOUR TEMP DP CC ASTR BSTR 2018-04-10 00:00:00 2018 4 1 24 20 5 cv er 2018-04-10 01:00:00 2018 4 2 14 14 6.5 hd fd ... Where the TEMP, DP, and CC columns are a weighted average of each CITY's value for each unique index (the index is a datetime), and ASTR and BSTR is just the value of BBB. YEAR, MONTH, and HOUR should stay the same. The weights for the above example could be given by the following dictionary: weights = {"AAA" : 0.3, "BBB" : 0.4, "CCC" : 0.3} My actual data has over 4 years worth of hourly data for multiple cities, so I would like some help coming up with an efficient solution, thanks!
linked to: http://stackoverflow.com/q/31521027
has title: Reducing Dataframe Using Weights
type: AnsweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/90855848
tagged with: pandas
score: 3

http://stackoverflow.com/q/51826706
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/58891378
type: UnansweredQuestion
tagged with: python
score: 2
linked to: http://stackoverflow.com/q/49837854
upvote count: 2
tagged with: tensorflow
has title: Tensorflow: Load a .pb file and then save it as a frozen graph issues
type: Question
has body: This question is very similar to this one: How do you use freeze_graph.py in Tensorflow? but that one has not been answered and I have a different approach to the problem. Thus I would like some input. I am also trying to load a .pb binary file and then freeze it. This is the code I tried. Let me know if this gives you any ideas. This does not return errors. It just crashes my jupyter notebook. import tensorflow as tf import sys from tensorflow.python.platform import gfile from tensorflow.core.protobuf import saved_model_pb2 from tensorflow.python.util import compat with tf.Session() as sess: model_filename ='saved_model.pb' # binary .pb file with gfile.FastGFile(model_filename, 'rb') as f: data = compat.as_bytes(f.read()) # reads binary sm = saved_model_pb2.SavedModel() print(sm) sm.ParseFromString(data) # parses through the file print(sm) if 1 != len(sm.meta_graphs): print('More than one graph found. Not sure which to write') sys.exit(1) g_in = tf.import_graph_def(sm.meta_graphs[0].graph_def) output_graph = "frozen_graph.pb" # Getting all output nodes for the frozen graph output_nodes = [n.name for n in tf.get_default_graph().as_graph_def().node] # This not working fully output_graph_def = tf.graph_util.convert_variables_to_constants( sess, # The session is used to retrieve the weights tf.get_default_graph().as_graph_def(), # The graph_def is used to retrieve the nodes output_nodes# The output node names are used to select the usefull nodes ) # Finally we serialize and dump the output graph to the filesystem with tf.gfile.GFile(output_graph, "wb") as f: f.write(output_graph_def.SerializeToString()) print("%d ops in the final graph." % len(output_graph_def.node)) print(g_in) LOGDIR='.' train_writer = tf.summary.FileWriter(LOGDIR) train_writer.add_graph(sess.graph) This code should generate a frozen file, but I don't completely understand tensorflow's saving mechanisms. If I take out the freezing the graph part from this code I get and events.out. file that can be r…
has answer: http://stackoverflow.com/a/51865645
answer count: 2

http://stackoverflow.com/q/51883057
tagged with: merge
answer count: 4
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51883467
linked to: http://stackoverflow.com/q/43893457
has comment: http://stackoverflow.com/comment/90717764
possible better answer: http://stackoverflow.com/a/51883229
accepted answer: http://stackoverflow.com/a/51883467
has answer: http://stackoverflow.com/a/51883229
has title: Python Pandas merge 2 dataframes
type: Question
has answer: http://stackoverflow.com/a/51883091
tagged with: dataframe
has comment: http://stackoverflow.com/comment/90718166
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/90717809
has body: I am trying to merge 2 dataframes that have the same information but broken down differently df1: #net total at team level Team Current Sales Previous Sales Team Total Diff Blue 10 5 5 Orange 20 8 12 Yellow 40 11 29 df2: #net total's broken down by region Team Region Curr Sales Prev Sales Net Diff Blue East 4 4 0 Blue West 6 1 5 Orange East 6 3 3 Orange West 14 5 9 Yellow East 15 3 12 Yellow West 25 8 17 Merged Dataframe: Team Region Curr Sales Previ Sales Net Diff Team Total Diff Blue East 4 4 0 5 Blue West 6 1 5 5 Orange East 6 3 3 12 Orange West 14 5 9 12 Yellow East 15 3 12 29 Yellow West 25 8 17 29 I am doing this so i can do additional statistical functions in new columns, but i am not sure how to merge the two. If i add df1['Team Total Diff'] to df2, it fills the first 3 records and doesnt fill down for each team name. if i use the following merge function, i dont see any change: df2.merge(df1'team_sort', 'Team', how='inner', on='Team') 'team_sort' is used as an index to keep the teams sorted based on Net Team Diff in ascending order Any help would be appreciated
has comment: http://stackoverflow.com/comment/90718724
has answer: http://stackoverflow.com/a/51883168
tagged with: python

http://stackoverflow.com/comment/116609451
score: 0
type: AnswerComment
type: Comment
has text: This actually does not answer the question which was about how to programatically determine the name of the output file of the setup.py script.
comment on: http://stackoverflow.com/a/51943921

http://stackoverflow.com/q/51878265
type: AnsweredQuestion
score: 2
tagged with: pyqt5
has body: I'm trying to change the color of the combobox background. I want it to be white, but I can't make it have any color different from gray. The picture on top is what I'm getting, and the one on the bottom is what I'm after. Here's my code: from PyQt5 import QtWidgets, QtGui class combodemo(QtWidgets.QWidget): def __init__(self, parent = None): super(combodemo, self).__init__(parent) layout = QtWidgets.QHBoxLayout() self.cb = QtWidgets.QComboBox() self.cb.addItem("1") self.cb.addItem("2") pal = self.cb.palette() pal.setColor(self.cb.backgroundRole(),QtGui.QColor(255,255,255)) self.cb.setPalette(pal) self.cb.setAutoFillBackground(True) layout.addWidget(self.cb) self.setLayout(layout) if __name__ == '__main__': app = QtWidgets.QApplication([]) ex = combodemo() ex.show() app.exec_()
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/60916964
tagged with: pyqt
downvote count: 0
upvote count: 2
has title: Change background color of ComboBox in PyQt
has answer: http://stackoverflow.com/a/51878524
accepted answer: http://stackoverflow.com/a/51878524
favorite count: 0
linked to: http://stackoverflow.com/q/54160285
tagged with: qcombobox
possible better answer: http://stackoverflow.com/a/60916964
tagged with: python

http://stackoverflow.com/q/51816722
type: Question
tagged with: binning
has comment: http://stackoverflow.com/comment/90587717
has comment: http://stackoverflow.com/comment/90587767
has comment: http://stackoverflow.com/comment/90593701
has body: I have a dataframe with 2 columns x and y that contains 10 bins of a column of some other dataframe and their respective values. I am trying to plot the xs against the ys, but I get the error: import pandas as pd import matplotlib.pyplot as plt df = pd.DataFrame(columns=['x','y']) df['x'] = ['19.0-23.0', '24.0-28.0', '29.0-33.0', '34.0-38.0', '39.0-43.0', '44.0-48.0', '49.0-53.0', '54.0-58.0', '59.0-63.0', '64.0-68.0'] df['y'] = ['0.065217', '0.039548', '0.06015', '0.054945', '0.085366', '0.071429', '0.137931', '0.129032', '0.190476', '0'] plt.plot([str(i) for i in df['x']], df['y']) --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) &lt;ipython-input-28-001ebdb8bf81&gt; in &lt;module&gt;() 7 df['y'] = ['0.065217', '0.039548', '0.06015', '0.054945', '0.085366', '0.071429', '0.137931', '0.129032', '0.190476', '0'] 8 ----&gt; 9 plt.plot([str(i) for i in df['x']], df['y']) ~\AppData\Local\Continuum\anaconda3\lib\site-packages\matplotlib\pyplot.py in plot(*args, **kwargs) 3315 mplDeprecation) 3316 try: -&gt; 3317 ret = ax.plot(*args, **kwargs) 3318 finally: 3319 ax._hold = washold ~\AppData\Local\Continuum\anaconda3\lib\site-packages\matplotlib\__init__.py in inner(ax, *args, **kwargs) 1896 warnings.warn(msg % (label_namer, func.__name__), 1897 RuntimeWarning, stacklevel=2) -&gt; 1898 return func(ax, *args, **kwargs) 1899 pre_doc = inner.__doc__ 1900 if pre_doc is None: ~\AppData\Local\Continuum\anaconda3\lib\site-packages\matplotlib\axes\_axes.py in plot(self, *args, **kwargs) 1404 kwargs = cbook.normalize_kwargs(kwargs, _alias_map) 1405 -&gt; 1406 for line in self._get_lines(*args, **kwargs): 1407 self.add_line(line) 1408 lines.append(line) ~\AppData\Local\Continuum\anaconda3\lib\site-packages\matplotlib\axes\_base.py in _grab_next_args(self, *args, **kwargs) 405 return 406 if len(remaining) &lt;= 3: --&gt; 407 for seg in self._plot_args(remaining, kwargs): 408 yield seg 409 return ~\AppData\Loc…
score: 0
has comment: http://stackoverflow.com/comment/90594915
tagged with: pandas
favorite count: 0
has comment: http://stackoverflow.com/comment/90594266
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90587845
tagged with: plot
answer count: 0
tagged with: matplotlib
upvote count: 1
downvote count: 1
has title: How to fix the "AttributeError: 'Series' object has no attribute 'find'" error when plotting with the x-axis as bins?

http://stackoverflow.com/q/51888790
has answer: http://stackoverflow.com/a/51899143
favorite count: 0
tagged with: fft
has comment: http://stackoverflow.com/comment/90748684
tagged with: python
has comment: http://stackoverflow.com/comment/90745687
has title: Can't generate Numpy FFT properly
tagged with: audio
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90747373
score: 1
has comment: http://stackoverflow.com/comment/90748710
has body: I'm trying to find the frequency spectrum of people speaking in a wav file but before that, I figured I'd try doing this with just a simple 200hz audio file. In the following code, I read in the 200hz file and plot it on the screen. Note: The 200hz file has a sample rate of 192000. My chunk size is 1/10th that, so every 19200 samples from scipy.io import wavfile import numpy as np ### This is just for drawing import matplotlib.pyplot as plt import matplotlib.animation as animation ### Above is for drawing # Read the .wav file sample_rate, data = wavfile.read('200hz.wav') CHUNK_SAMPLES_PER_SECOND = 10 CHUNK = sample_rate / CHUNK_SAMPLES_PER_SECOND # Now compute the spectrum on a given frame fig = plt.figure() ax1 = fig.add_subplot(1,1,1) # Now, lets just draw the plot for frame in range(len(data) / CHUNK): ax1.clear() frame_data = data[frame * CHUNK:(frame + 1) * CHUNK, 0] # normally 2 channel, take 1st channel frame_data = frame_data * 1.0 / frame_data.max() #### Below, activate those to use the FFT #### # frame_data = np.fft.fft(frame_data) # Calculate FFT on dataset # frame_data = frame_data * 1.0 / frame_data.max() # Normalize FFT data # ax1.set_xlabel('frequency') ax1.plot(np.abs(frame_data), '-') ax1.set_xlabel('sample') ax1.set_ylabel('volume') plt.pause(1.0 / CHUNK_SAMPLES_PER_SECOND) The above code produces: To me, this looks correct. Since I am only taking 19200 samples of a 192000 sample rate, the plot should be for 0.1 seconds. Thus, a 200 Hz signal should have roughly 20 full waves. When I then go to enable the following code by uncommenting: #### Below, activate those to use the FFT #### # frame_data = np.fft.fft(frame_data) # Calculate FFT on dataset # frame_data = frame_data * 1.0 / frame_data.max() # Normalize FFT data # ax1.set_xlabel('frequency') It produces a funky looking fft chart: I guess what I expected it to show was a peak at around ~200hz or well at least one well defined peak for the frequency of the signal. Thanks! Edit: I added the actua…
type: Question
accepted answer: http://stackoverflow.com/a/51899143
upvote count: 1
downvote count: 0
answer count: 1

http://stackoverflow.com/q/51923599
has comment: http://stackoverflow.com/comment/90796757
has answer: http://stackoverflow.com/a/51923727
type: Question
possible better answer: http://stackoverflow.com/a/51923727
has body: I have a hex array buffer[]. From eclipse I can see that the values are stored in the array as: ['\x03', '\x9f', '\x04', '\x9f'] I want to cut the \x part of it and just want the array as (hex array): [03, 9f, 04, 9f] I tried the format option: hex(buffer[0][2:]) Just to check if it is getting formatted, but it doesn't. Any help to convert the whole array to my expected output format?
tagged with: arrays
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/51923756
has answer: http://stackoverflow.com/a/51923742
has answer: http://stackoverflow.com/a/51923734
tagged with: python
answer count: 4
type: AnsweredQuestion
tagged with: list
accepted answer: http://stackoverflow.com/a/51923734
has title: How to trim out the \x part of the array elements?
score: 1
upvote count: 1

http://stackoverflow.com/comment/90832044
type: Comment
comment on: http://stackoverflow.com/q/51941038
has text: @Kristada673 Do you mean the order is the same as the column?
score: 0
type: QuestionComment

http://stackoverflow.com/q/51846001
type: AnsweredQuestion
upvote count: 1
has title: How to pass a data frame through a function and return another data frame?
type: Question
score: 1
tagged with: dataframe
has answer: http://stackoverflow.com/a/51846132
tagged with: function
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/51846132
has comment: http://stackoverflow.com/comment/90645367
favorite count: 0
tagged with: pandas
has body: I have a data frame with real estate information about the neighborhood, type of property, type of negotiation, and price. It looks like this: **neighborhood type_property type_negotiation price** Smallville house rent 2000 Oakville apartment for sale 100000 King Bay house for sale 250000 . . What I want to do is pass this through a function that sort the data frame by neighborhood I enter into it, if its a house, if its for sale, the number of properties that fit these requirements, and also gives the 90th percentile and 10th percentile. The function and code I have so far is below, but I keep running into multiple syntax and other errors: def function(string): a = df[(df.type_negotiation == 'for sale')&amp;(df.type_property == 'house')&amp;(df.neighborhood == string) b = pd.new_df([a.price.quantile(.10),a.price.quantile(.90),a.shape], columns=('tenthpercentile','ninetiethpercentile','Quantity')) return b Thank you for any help in advance.
tagged with: python

http://stackoverflow.com/comment/90595221
comment on: http://stackoverflow.com/q/51820515
type: Comment
type: QuestionComment
score: 1
has text: Can you elaborate on your failed attempts to use TreeView and ScrollView? What was the problem? What didn't you like?

http://stackoverflow.com/a/79052345
upvote count: 5
answers question: http://stackoverflow.com/q/51925384
downvote count: 0
type: Answer
has body: This worked for me on Windows, installing pip-system-certs was not working for whatever reason. pip install truststore and then import truststore truststore.inject_into_ssl() # thing that calls requests.get
score: 5

http://stackoverflow.com/a/51945352
type: AcceptedAnswer
has body: I tried to reproduce your problem, but with no success. Do you mind sharing any more detail about the source of data you are importing? If your strings are in unicode originally and you use .to_excel('test.xls') function, it should work with no problem. If you want to force a special encoding in Excel, use an argument .to_excel('test.xls', encoding='utf16'). So, make sure that you know in what encoding is your original data (e.g. your csv files or your database). When loading to Python, always try to decode data in unicode as soon as possible. Then it should work out of the box. df['delivery_dt'] = df['delivery_dt'].apply(lambda x: unicode(x)) Again, as always, using Python 3 makes your life much easier when it comes to non-ascii characters.
type: Answer
has comment: http://stackoverflow.com/comment/90844245
answers question: http://stackoverflow.com/q/51944309
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51944309
score: 1
has comment: http://stackoverflow.com/comment/90843706
has comment: http://stackoverflow.com/comment/90843647
has comment: http://stackoverflow.com/comment/90909155
has comment: http://stackoverflow.com/comment/90842638
has comment: http://stackoverflow.com/comment/90843664
upvote count: 1

http://stackoverflow.com/comment/90796757
type: Comment
comment on: http://stackoverflow.com/q/51923599
type: QuestionComment
score: 0
has text: `[03, 9f, 04, 9f]` is not a valid Python literal. Did you mean `['03', '9f', '04', '9f']`, which is a list of strings?

http://stackoverflow.com/comment/90602371
has text: Please show the script that uses some packages in this list. That behavior is not correct, and shouldn't happen. Python does not "fetch packages" from the base environment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/51821131
type: QuestionComment

http://stackoverflow.com/comment/90718818
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/51883484
has text: Check your indentation. You have not placed some of your lines in `while` loop.

http://stackoverflow.com/q/51881146
upvote count: 1
answer count: 1
accepted answer: http://stackoverflow.com/a/51881414
favorite count: 0
tagged with: python-3.x
has body: I have a dll function that can take a variable number of parameters of the type ICString class ICString(ctypes.Structure): _fields_ = [('len', c_long), ('text', c_char_p)] This is the way I´m setting up the argtypes and the parameters of the function num_params = len(argumentos) self.__U2_C_INTERFACE.ic_malloc.argtypes = [POINTER(c_long)] self.__U2_C_INTERFACE.ic_free.argtypes = [ctypes.c_voidp] sub_name_in = c_char_p(bytes(subrutina, self.__sistema_codificacion)) sub_name_len_in = c_long(len(subrutina)) num_params_len_in = c_long(num_params) code = c_long(0) p_in = [None]*num_params argumentos_tipo = [c_char_p, POINTER(c_long), POINTER(c_long), POINTER(c_long)] for idx, parametro in enumerate(argumentos): argumentos_tipo += [POINTER(ICString)] param_len = len(parametro) p_in[idx] = ICString(c_long(0)) if param_len &gt; 0: temp = self.__U2_C_INTERFACE.ic_malloc(byref(c_long(param_len))) memcpy_dest = ctypes.cast(temp, ctypes.c_char_p) ctypes.memmove(memcpy_dest, bytes(parametro, self.__sistema_codificacion), param_len*sizeof(ctypes.c_char)) p_in[idx].len = c_long(param_len) p_in[idx].text = memcpy_dest self.__U2_C_INTERFACE.ic_subcall.argtypes = argumentos_tipo But I don´t know how to pass this list of arguments to the function, and not doing somethin like this if num_params== 1 self.__U2_C_INTERFACE.ic_subcall(sub_name_in, byref(sub_name_len_in), byref(code), byref(num_params_len_in), byref(p_in[0])) if num_params== 2 self.__U2_C_INTERFACE.ic_subcall(sub_name_in, byref(sub_name_len_in), byref(code), byref(num_params_len_in), byref(p_in[0]), byref(p_in[1])) if num_params== 3 self.__U2_C_INTERFACE.ic_subcall(sub_name_in, byref(sub_name_len_in), byref(code), byref(num_params_len_in), byref(p_in[0]), byref(p_in[1]), byref(p_in[2]))
tagged with: python
has answer: http://stackoverflow.com/a/51881414
type: AnsweredQuestion
downvote count: 0
score: 1
type: Question
tagged with: ctypes
has title: Passing variable number of parameters of custom type with ctypes

http://stackoverflow.com/a/51832435
score: 0
type: AcceptedAnswer
has body: A couple of issues: You shouldn't del temp_list[:] you are deleting the object you just added. Your loop would be better as a for loop. Your variable is called list_of_lists not list_of_list, so list_of_list.append() should throw a NameError map in Py3 returns an iterator, so you need to turn it into a list, you could use temp_list.extend(map(...)) but you can just create it directly. Note: your first use of map(...) is unpacked into individual variables so works as expected. Updated code: a, b = map(int, input().split()) list_of_lists = [] for i in range(b): temp_list = list(map(float, input().split())) print(temp_list, i) list_of_lists.append(temp_list)
answers question: http://stackoverflow.com/q/51832301
type: Answer
accepted answer of: http://stackoverflow.com/q/51832301

http://stackoverflow.com/a/51867441
has body: Your first func takes 2 inputs, which are broadcast against each other, and element tuples are passed to reshape_to_array dump is (4,4), pattern is (2,2). The error says that it can pair up the 2 - which should be obvious if you understand broadcasting. If you reduce dump to (2,2) (or (2,1) or (1,2)) it should work. So would a pattern that is (1,4) or (4,1). In the 2nd case, the outer frompyfunc is passing each of the (4,4) dump elements to reshape_to_array. and (4,4) pattern is evaluated. I suspect x = func(dump[:,:,np.newaxis, np.newaxis], pattern) would work, generating the same values but in a (4,4,2,2) array. With different np.newaxis arangements we could produce (4,2,4,2) etc. broadcasting dict and pattern In [291]: fn = lambda in_dict, pattern: in_dict.get(pattern) In [299]: fn1 = np.frompyfunc(fn,2,1) With a (4,4) dump, I can use a (1,4) pattern (or a (4,1)): In [300]: fn1(dump, pattern.reshape(1,4)) Out[300]: array([['a00', 'b01', 'c02', 'd03'], ['a10', 'b11', 'c02', 'd13'], ['a20', 'b21', 'c22', 'd23'], ['a30', 'b31', 'c32', 'd33']], dtype=object) If I add newaxis to dump I can get a (4,4,2,2) array: In [302]: fn1(dump[:,:,None,None], pattern) Out[302]: array([[[['a00', 'b00'], ['c00', 'd00']], [['a01', 'b01'], ['c01', 'd01']], [['a02', 'b02'], ['c02', 'd02']], .... [['a32', 'b32'], ['c32', 'd32']], [['a33', 'b33'], ['c33', 'd33']]]], dtype=object) In [303]: _.shape Out[303]: (4, 4, 2, 2) These are the same as your x, except without the (4,4) (2,2) nesting. If I copy-n-paste your x, which produces a (4,4,2,2) 'U3' array (it doesn't preserve the nesting), and compare: In [309]: np.all(xx == Out[302].astype('U3')) Out[309]: True wrapped pattern You can wrap your last version in a function definition: def foo(pattern): def reshape_to_array(in_dict): vec_func = np.frompyfunc(in_dict.get, 1, 1) return vec_func(pattern) func = np.frompyfunc(reshape_to_array,1,1) return func Which will be used as: In [313]: foo(pattern) Out[313]: &lt;ufunc '? (vectorized)'&gt; In…
has comment: http://stackoverflow.com/comment/90686776
has comment: http://stackoverflow.com/comment/90686876
has comment: http://stackoverflow.com/comment/90717067
has comment: http://stackoverflow.com/comment/90715921
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90718519
type: Answer
answers question: http://stackoverflow.com/q/51867272
accepted answer of: http://stackoverflow.com/q/51867272
has comment: http://stackoverflow.com/comment/90714195
has comment: http://stackoverflow.com/comment/90716876
score: 1
has comment: http://stackoverflow.com/comment/90716380
has comment: http://stackoverflow.com/comment/90722288
upvote count: 1
has comment: http://stackoverflow.com/comment/90686995
has comment: http://stackoverflow.com/comment/90695353

http://stackoverflow.com/comment/90814629
comment on: http://stackoverflow.com/a/51929310
has text: Ok, I edited it with an example, hope that is enough.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/51902250
downvote count: 0
linked to: http://stackoverflow.com/q/74622229
linked to: http://stackoverflow.com/q/51903732
has answer: http://stackoverflow.com/a/51903062
answer count: 1
has title: Read data from a file and create a tree using anytree in python
tagged with: anytree
favorite count: 0
has body: Is there a way to read data from a file and construct a tree using anytree? Parent Child A A1 A A2 A2 A21 I can do it with static values as follows. However, I want to automate this by reading the data from a file with anytree. &gt;&gt;&gt; from anytree import Node, RenderTree &gt;&gt;&gt; A = Node("A") &gt;&gt;&gt; A1 = Node("A1", parent=A) &gt;&gt;&gt; A2 = Node("A2", parent=A) &gt;&gt;&gt; A21 = Node("A21", parent=A2) Output is A ├── A1 └── A2 └── A21
tagged with: python
accepted answer: http://stackoverflow.com/a/51903062
tagged with: tree
type: AnsweredQuestion
tagged with: file
score: 9
type: Question
upvote count: 9

http://stackoverflow.com/comment/99614595
score: 1
comment on: http://stackoverflow.com/a/51818386
type: AnswerComment
type: Comment
has text: I think this package is broken, this does not work.

http://stackoverflow.com/q/51840164
has body: Me and a couple friends have created a basketball game with different game modes the user can choose from. I was in charge of the main menu and have to link all the games together. It's a group of four tasks. The way I've linked it by importing the file and sending the user to that file when the user clicks the button. It works for my other two friends but one friend's module only changes the caption when the button is clicked. My main menu code: import pygame import sys # Define some colors BLACK = (0, 0, 0) WHITE = (255, 255, 255) GREEN = (0, 255, 0) RED = (255, 0, 0) pygame.init() # Set the height and width of the screen size = [800, 600 ] screen = pygame.display.set_mode(size) pygame.display.set_caption("Basketball") # Loop until the user clicks the close button. done = False # Used to manage how fast the screen updates clock = pygame.time.Clock() # This is a font we use to draw text on the screen (size 36) 'https://www.pygame.org/docs/ref/font.html' font = pygame.font.Font(None, 36) font2 = pygame.font.Font("Minecraft.ttf", 60) font3 = pygame.font.Font("Minecraft.ttf", 40) font4 = pygame.font.Font("Minecraft.ttf", 30) font5 = pygame.font.Font("Minecraft.ttf", 30) display_menu = True start_page = 1 #Background 'https://stackoverflow.com/questions/28005641/how-to-add-a-background-image-into-pygame' bg = pygame.image.load("resize.png") bg2 = pygame.image.load("dar.png") bg3 = pygame.image.load("controls.png") bg4 = pygame.image.load("startscreen.png") #Rectangle 'https://www.cs.ucsb.edu/~pconrad/cs5nm/topics/pygame/drawing/' 'start screen buttons' rect1 = pygame.Rect(300,300,205,80) rect2 = pygame.Rect(300,400,205,80) rect3 = pygame.Rect(300,500,205,80) 'spacebar button' rect4 = pygame.Rect(90,350,650,100) 'back button' rect5 = pygame.Rect(50,510,100,50) 'universal idk button' rect6 = pygame.Rect(300,400,205,80) 'play button in start screen' rect7 = pygame.Rect(610,25,120,70) rect8 = pygame.Rect(610,210,120,70) rect9 = pygame.Rect(610,410,120,70) def play_music():…
type: Question
has answer: http://stackoverflow.com/a/51842786
linked to: http://stackoverflow.com/q/28005641
has title: Module won't load, caption only changes (pygame)
downvote count: 0
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/51842786
tagged with: python
tagged with: pygame
score: 2
type: AnsweredQuestion
upvote count: 2

http://stackoverflow.com/comment/90780859
score: 1
has text: @BenyaminJafari Yes, python:alpine is 3.7 (https://hub.docker.com/_/python/), hence my suggestion to check Cython version.
type: Comment
comment on: http://stackoverflow.com/a/51915350
type: AnswerComment

http://stackoverflow.com/comment/90789319
type: AnswerComment
score: 0
type: Comment
has text: @MadPhysicist Yeah. I was originally planning to implement yours but with a sparse array, but I found that too hard and so decided to go with one that would waste valuable entropy. This one works for sufficiently large numbers, though. (I started before you posted, but don't have a real keyboard at the moment so was slow.)
comment on: http://stackoverflow.com/a/51918815

http://stackoverflow.com/q/51943473
type: Question
tagged with: deep-learning
answer count: 1
score: 0
has body: I hope to use tf.data.Dataset.from_generator to help me generate the input data flow. dataset = tf.data.Dataset.from_generator(sample_generator, output_types=(tf.float32, tf.float32, tf.float32), output_shapes=(tf.TensorShape([size_image, size_image, 3]),tf.TensorShape([size_image,size_image,3]), tf.TensorShape([size_gt, size_gt]))) sample_generator function could generate three numpy arrays with the proposed shape. There is no problem with the part mentioned above. However, tf.data.Dataset.from_generator could only generate the data flow, I need to feed the generated data to network. The code is as follows: dataset = dataset.map(transform_fn, num_parallel_calls=self.config['prefetch_threads']) # transform_fn just returns the input dataset = dataset.prefetch(self.config['prefetch_capacity']) dataset = dataset.repeat() dataset = dataset.batch(self.config['batch_size']) and the iterator is self.iterator = self.dataset_tf.make_one_shot_iterator() self.iterator.get_next() Thanks!
has answer: http://stackoverflow.com/a/51997898
tagged with: python
type: UnansweredQuestion
has title: Can't read data from tf.data.Dataset.from_generator
tagged with: tensorflow

http://stackoverflow.com/a/51829543
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/51828551
has body: Using the data should do the job for you: tmp = torch.ones(3, 2, 2, requires_grad=True) out = tmp ** 2 print("\n{}".format(out.data)) Output: tensor([[[1., 1.], [1., 1.]], [[1., 1.], [1., 1.]], [[1., 1.], [1., 1.]]])
accepted answer of: http://stackoverflow.com/q/51828551
downvote count: 0
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/comment/90778537
has text: Its `pair["Name"]` not `pair["Key"]`
comment on: http://stackoverflow.com/a/51914188
type: AnswerComment
type: Comment
score: 2

http://stackoverflow.com/comment/90853544
has text: that content is dynamically rendered.
score: 0
comment on: http://stackoverflow.com/q/51951583
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51939126
answers question: http://stackoverflow.com/q/51939052
accepted answer of: http://stackoverflow.com/q/51939052
type: AcceptedAnswer
has body: Try: df.loc[:,df.columns[df.iloc[10] &gt; 0]] Output: UniqueDate Apr 04, 2014 Apr 11, 2014 Apr 24, 2014 Time 00:00:00 NaN NaN NaN 00:01:00 -0.066291 0.136705 0.000000 00:02:00 -0.066291 0.136705 0.000000 00:03:00 -0.066291 0.136705 0.059305 00:04:00 -0.066291 0.205049 0.000004 00:05:00 -0.066291 0.136710 0.059308 00:06:00 -0.066291 0.136710 0.059308 00:07:00 0.000004 0.068367 0.000007 00:08:00 0.066295 0.136715 0.118617 00:09:00 0.066295 0.136715 0.059319 00:10:00 0.132582 0.136715 0.059319
score: 0
has comment: http://stackoverflow.com/comment/90828351
type: Answer

http://stackoverflow.com/a/51879528
type: Answer
answers question: http://stackoverflow.com/q/51879403
has comment: http://stackoverflow.com/comment/90711068
has comment: http://stackoverflow.com/comment/90713595
has comment: http://stackoverflow.com/comment/90710856
has comment: http://stackoverflow.com/comment/90711345
has body: I believe need get_level_values for first level of MultiIndex, convert it to Series by to_series for possible replace NaNs by forward filling created by mask with isin, last set_index: idx1 = df.index.get_level_values(0).to_series() idx2 = df.index.get_level_values(1) idx = idx1.mask(idx1.isin(idx2)).ffill().astype(int) df = df.set_index([idx, idx2]) print (df) given_name index1 index2 1 2 1.0 3 0.0 4 1.0 5 0.5 6 7 1.0 8 1.0 9 0.0
has comment: http://stackoverflow.com/comment/90712131
score: 0
has comment: http://stackoverflow.com/comment/90728465
has comment: http://stackoverflow.com/comment/90713699
has comment: http://stackoverflow.com/comment/90712813

http://stackoverflow.com/comment/91074242
score: 1
has text: Thanks @asynts stupid mistake by me, will take a look
type: Comment
comment on: http://stackoverflow.com/a/52061703
type: AnswerComment

http://stackoverflow.com/comment/90859944
comment on: http://stackoverflow.com/a/51954693
has text: I think we were answering at the same time
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/51855808
has body: Drop that column from your dataframe: df.drop(["Unnamed: 1"], inplace=True)
answers question: http://stackoverflow.com/q/51855777
downvote count: 0
upvote count: 2
type: Answer
score: 2

http://stackoverflow.com/comment/90695169
has text: @sai_636 - How working `' '.join(df["read"].astype(str))` or `' '.join(df["read"].dropna())` if `float` values are `NaN`s
type: Comment
score: 4
type: AnswerComment
comment on: http://stackoverflow.com/a/51871650

http://stackoverflow.com/comment/90787815
type: QuestionComment
comment on: http://stackoverflow.com/q/51918954
score: 0
has text: Your approach has a computational complexity of Ω(n²), which is going to be slow for large n. It's certainly possible to get rid of the explicit for loop in favour of vectorised operations, which will speed this up by a constant factor, but it will still be Ω(n²). A proper solution would be to sort your points into a quadtree and use a hierarchical multipole expansion on the branches, which would allow you to achieve a complexity of Ω(n log n), which for large n will beat any Ω(n²) algorithm.
type: Comment

apache-spark-dataset
tag name: apache-spark-dataset
tags question: http://stackoverflow.com/q/51853704
type: Tag

http://stackoverflow.com/comment/105218594
comment on: http://stackoverflow.com/a/52676577
type: AnswerComment
has text: for some reason in my setup python still could not find the glfw shared library. I checked that it can get it via the environment variable `PYGLFW_LIBRARY` and exported the variable to the path: `set -x PYGLFW_LIBRARY /usr/lib/i386-linux-gnu/libglfw.so` (in fish shell). It works.
type: Comment
score: 2

http://stackoverflow.com/a/51929754
type: Answer
score: 1
has comment: http://stackoverflow.com/comment/90949407
upvote count: 1
has body: According to the documentation of the Imatest Python interface regarding importing imatest.it: Behind the scenes, the ImatestLibrary constructor will start up the Matlab MCR Runtime and load all the IT libraries into memory. This suggests that imatest itself meddles with the state of the MATLAB engine. While the order of imports usually doesn't matter, occasionally certain imports should happen before others for proper initialization, when modules imported later rely on modules imported earlier (for instance, importing matplotlib first and setting a backend before importing pyplot that would use said backend). So my only suggestion is to try switching the order of imports to see if that helps. If it doesn't you're out of luck (as far as Stack Overflow is concerned): both MATLAB and Imatest are expensive proprietary (and even closed source) products so you should file bug reports to either or both of them, because nobody else will be able to tell if and how the conflict could be fixed.
has comment: http://stackoverflow.com/comment/90904160
downvote count: 0
answers question: http://stackoverflow.com/q/51929303

django-admin
tags question: http://stackoverflow.com/q/51908142
tags question: http://stackoverflow.com/q/51895405
tags question: http://stackoverflow.com/q/51940077
tags question: http://stackoverflow.com/q/51892413
tags question: http://stackoverflow.com/q/51830948
type: Tag
tag name: django-admin
tags question: http://stackoverflow.com/q/51855147

http://stackoverflow.com/q/51810720
has comment: http://stackoverflow.com/comment/90576752
has body: after doing a bulk_create, I'm trying to add some elements to my table but I got an IntegrityError as the sequence still starts with 1 when using save() Is there any way to update the sequence within Django after the bulk_create ? Or should I generate the id myself using a max filter ? I'm using a postgre database. Here is a sample of my code: elements is a list of Identifiants objects (I'm trying to import the list on a "dump" database first to be sure everything is fine) try: Identifiants.objects.using('import-check').all().delete() Identifiants.objects.using('import-check').bulk_create(elements) except: traceback.print_exc() return False else: Identifiants.objects.all().delete() Identifiants.objects.bulk_create(elements) return True And here's the model class Identifiants(models.Model): taxon = models.IntegerField(unique=True) noms = models.TextField(blank=True, null=True) fiche = models.IntegerField(blank=True, null=True) sms = models.NullBooleanField() I let Django create the pk itself And the view related for further insertions : elif req.method == 'POST' and req.POST['action'] == "add": id_form = AddFormId(req.POST) nom_form = AddFormNom(req.POST) search_form = LightSearchForm(req.POST) if id_form.is_valid() and nom_form.is_valid(): inst = id_form.save(commit = False) num_fiche = Identifiants.objects.all().aggregate(Max('fiche'))['fiche__max'] num_fiche += 1 inst.fiche = num_fiche inst.save() values = nom_form.save(commit = False) values.taxon = inst values.codesyno = 0 values.save() return redirect(reverse(details, kwargs = {'id_item' : values.id})) I got the issue with multiple tables. I always add elements with a form.
favorite count: 0
type: UnansweredQuestion
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/90576606
answer count: 0
score: 1
upvote count: 1
type: Question
has title: IntegrityError for AutoField after a bulk_create()
tagged with: postgresql
has comment: http://stackoverflow.com/comment/90576558
downvote count: 0
has comment: http://stackoverflow.com/comment/90576401

http://stackoverflow.com/q/51820700
tagged with: python
answer count: 1
tagged with: flask-migrate
tagged with: sqlalchemy
has answer: http://stackoverflow.com/a/51823292
has title: Alembic shows "empty message" when running upgrade
downvote count: 0
score: 2
type: AnsweredQuestion
tagged with: alembic
favorite count: 0
has body: When I run an Alembic upgrade I see "empty message" next to the revision number instead of "users table". I am following this tutorial. What should appear according to the author: (venv) $ flask db upgrade INFO [alembic.runtime.migration] Context impl SQLiteImpl. INFO [alembic.runtime.migration] Will assume non-transactional DDL. INFO [alembic.runtime.migration] Running upgrade -&gt; e517276bb1c2, users table What appeared for me: (venv) PS C:\Users\HP\microblog&gt; flask db upgrade INFO [alembic.runtime.migration] Context impl SQLiteImpl. INFO [alembic.runtime.migration] Will assume non-transactional DDL. INFO [alembic.runtime.migration] Running upgrade -&gt; 907246db53d3, empty message
accepted answer: http://stackoverflow.com/a/51823292
type: Question
upvote count: 2

http://stackoverflow.com/comment/90784250
comment on: http://stackoverflow.com/q/51916775
score: 1
has text: `os.system()` is a broken API. It takes a single string and launches a new shell process which parses that string back into a list of arguments (for potentially multiple commands), and then executes that. You already have a list of arguments: don't smush them together into a string just to have that string parsed back into a list of arguments -- instead use an API that takes a list of arguments directly. The `subprocess` module has lots of options here and has very good documentation.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90612250
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51823780
has text: No, that doesn't work. When I try it reports: ValueError: operands could not be broadcast together with shapes (4,4) (2,2)

http://stackoverflow.com/comment/90746569
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51897667
has text: @pkqxdd you can "pip" in vim commands like so `vim +'Ex command1 | Ex command2 | ...' file`

http://stackoverflow.com/q/51877834
answer count: 1
downvote count: 0
tagged with: keras
favorite count: 0
accepted answer: http://stackoverflow.com/a/51924343
tagged with: keras-2
tagged with: autoencoder
upvote count: 2
has body: I want to use autoencoders on real life photos (and not simple MNIST digits). I have taken the cats and dog dataset and train with it. My parameters are: I stick with a grayscale and a scaled down verson of 128x128 px image and do some preprocessing in the ImageDataGenerator for data augmentation. I train with different of datasets of about 2000 images or cats and dogs. I could take 10000 but it lasts too long. I choose a convolution network with basic downsamplers and upsamplers and toyed with the parameters and ended up with a bootlebeck of 8x8x8 = 512 (it is 1/32 of the original image with 128x128px). Here is the python code: from keras.preprocessing.image import ImageDataGenerator from keras.layers import Input, Conv2D, MaxPooling2D, UpSampling2D from keras.models import Model from keras import metrics from keras.callbacks import EarlyStopping import os root_dir = '/opt/data/pets' epochs = 400 # epochs of training, the more the better batch_size = 64 # number of images to be yielded from the generator per batch seed = 4321 # constant seed for constant conditions # keras image input type definition img_channel = 1 # 1 for grayscale, 3 for color # dimension of input image for network, the bigger the more CPU and RAM is used img_x, img_y = 128, 128 input_img = Input(shape = (img_x, img_y, img_channel)) # this is the augmentation configuration we use for training train_datagen = ImageDataGenerator( rescale=1./255, shear_range=0.2, zoom_range=0.2, horizontal_flip=True) # this is the augmentation configuration we will use for testing test_datagen = ImageDataGenerator(rescale=1./255) # this is a generator that will read pictures found in # subfolders of 'data/train', and indefinitely generate # batches of augmented image data train_generator = train_datagen.flow_from_directory( root_dir + '/train', # this is the target directory target_size=(img_x, img_y), # all images will be resized batch_size=batch_size, color_mode='grayscale', class_mode='input', # necessarry for a…
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90772757
has title: Fine-tuning of Keras autoencoders of cat images
has answer: http://stackoverflow.com/a/51924343
type: Question
score: 2

http://stackoverflow.com/q/51886398
has title: HTTPS Flask using POST data
tagged with: https
has answer: http://stackoverflow.com/a/51886424
type: Question
has body: Thanks for reading in advance. I have a working Apache2 server which is currently successfully serving both :80 and :443. I have a simple FLASK based site at the moment that is being served HTTPS successfully. using Mod_wsgi and self-signed certs at the moment. Here's where I run into trouble. I have a login which uses POST data to send info back from a FORM in my template to my server for user authentication. It works fine in HTTP however in HTTPS I get: Bad Request The browser (or proxy) sent a request that this server could not understand. Having googled around for a couple hours it seems like there could be some mix of context settings and or app extensions that could be used with the server SSL certs,keys to help here. But I'm a babe in the woods when it comes to SSL. Could anyone point me to what changes I need to make to adapt to SSL handling of client/server in Flask? I've tried SSLify (didn't work - same error) Very Best Regards, Tom
tagged with: ssl
score: -1
tagged with: flask
downvote count: 2
upvote count: 1
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/90738157
comment on: http://stackoverflow.com/a/51893555
has text: to me it seems like the help text just ends up after the input field (to the right), so this does not help ... also I think it needs to be help_text='You can add description here'
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/51916021
has comment: http://stackoverflow.com/comment/90782572
type: Answer
has body: First of all, if you need to get just script output use subprocess.check_output() function. When you want to return json from django view, the JsonResponse is best match for you. import subprocess from django.http import JsonResponse def home(request): output = subprocess.check_output(["python","adoptions/executer.py"]) return JsonResponse(output)
score: 0
answers question: http://stackoverflow.com/q/51915943

http://stackoverflow.com/comment/90592906
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51819259
score: 0
has text: yes that was what I did first and when it didn't work I changed to the source code directory suspecting it could not find the path to the directory

http://stackoverflow.com/q/51801925
tagged with: python
has comment: http://stackoverflow.com/comment/90561071
type: AnsweredQuestion
score: 1
tagged with: mysql
upvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/51803361
has comment: http://stackoverflow.com/comment/90560546
has title: MySQL python connector code aborts without error (Code from the MySQL documentation)
has comment: http://stackoverflow.com/comment/90560366
has comment: http://stackoverflow.com/comment/90561034
has body: I was trying to use the python connector code given in the MySQL documentation and test it on a small database already created, but it aborts. The code is just supposed to connect to the db and add a new email adress. import mysql.connector from mysql.connector import errorcode cnx = mysql.connector.connect(user='root', password='pwd', host='localhost', database='db') cursor = cnx.cursor() add_email = ("INSERT INTO employee(MID, Email) VALUES (%s,%s)") email_details = (NULL, "a@a.de") cursor.execute(add_email, email_details) cnx.commit() input("data entered successfully") cnx.close() By setting breakpoints I found out that the problem probably lies in the cursor.execute() statement. (I used Null as the first %s since MID is Auto Incrementing btw)
tagged with: sql
tagged with: mysql-python
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/90562812
favorite count: 0
has answer: http://stackoverflow.com/a/51803361

http://stackoverflow.com/comment/90561594
score: 0
has text: thanks, but that still doesnt solve the problem that when I enter something, the text "This is some very long text" gets corrupted
type: Comment
comment on: http://stackoverflow.com/a/51802535
type: AnswerComment

binary-tree
tag name: binary-tree
type: Tag
tags question: http://stackoverflow.com/q/51889381
tags question: http://stackoverflow.com/q/51888227
tags question: http://stackoverflow.com/q/51921782

http://stackoverflow.com/comment/90723575
type: Comment
has text: yes, comma part of regex should be treated as part of word.
score: 0
comment on: http://stackoverflow.com/q/51885868
type: QuestionComment

http://stackoverflow.com/comment/90701799
score: 0
comment on: http://stackoverflow.com/q/51874974
has text: have you tried **pip show (package_name)** .... it results in info where there are points called **Requires** and **Requires_by**... ?.. this may help out to straight out the dependencies...or if in linux try **which pip** to get the pip running source...might help ?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90797724
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51923974
has text: @eyllanesc I'm using shebang line and then ./filename.py to run the script. I'm using VS code. I was not running the same file. User DYZ gave me the solution below. Thanks you.

http://stackoverflow.com/comment/90714405
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51880563
has text: So zeros in the same places for both B and D?
score: 0

http://stackoverflow.com/a/51914056
has comment: http://stackoverflow.com/comment/90793663
answers question: http://stackoverflow.com/q/51913220
type: Answer
has comment: http://stackoverflow.com/comment/90793710
accepted answer of: http://stackoverflow.com/q/51913220
has comment: http://stackoverflow.com/comment/90793886
has body: Your code snippet has a few issues, mostly: Your AJAX request is not bind to the button click event, so clicking the button does nothing. You have two html elements with the same id textbox, id are supposed to be unique. To get an html element by id use "#textbox" On the server side (Flask): Use the function get_json() of the request To process the POST request you need to check for POST not GET Try wrapping your POST request like this: $("button").click(function (e) { e.preventDefault(); var value = $("#textbox").val(); alert(value); $.ajax({ type: "POST", url: "parse_data", data: JSON.stringify({ "text" : value } ), contentType: "application/json; charset=utf-8", dataType: "json", success: function (data) { alert(JSON.stringify(data)); } }); }); Also remove the duplicate ids textbox, change the id of the form to something like textbox-form, finally change your parse_data function to something like this: @app.route('/parse_data', methods=['GET', 'POST']) def parse_data(): if request.method == 'POST': search = request.get_json() return jsonify(search) return render_template('index.html')
score: 3
has comment: http://stackoverflow.com/comment/90791806
upvote count: 3
has comment: http://stackoverflow.com/comment/90793813
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90793781
downvote count: 0
has comment: http://stackoverflow.com/comment/90786324

http://stackoverflow.com/a/51947240
answers question: http://stackoverflow.com/q/51946944
has comment: http://stackoverflow.com/comment/90843976
has body: One solution is to split your problem into 2 parts. First flatten your dataframe to ensure df['A'] consists only of strings. Then concatenate a couple of GroupBy operations. Step 1: Flatten your dataframe You can use itertools.chain and numpy.repeat to chain and repeat values as appropriate. from itertools import chain A = df['A'].apply(lambda x: [x] if not isinstance(x, list) else x) lens = A.map(len) res = pd.DataFrame({'ID': np.repeat(df['ID'], lens), 'A': list(chain.from_iterable(A)), 'C': np.repeat(df['C'], lens)}) print(res) # A C ID # 0 a 1 1 # 1 a 2 1 # 2 a 15 1 # 3 b 5 1 # 4 b 13 1 # 4 c 13 1 # 4 d 13 1 # 5 a 6 2 # 6 a 7 2 # 7 a 1 2 # 7 b 1 2 # 7 c 1 2 Step 2: Concatenate GroupBy on original and flattened agg_df = pd.concat([res.groupby('ID')['A'].nunique(), df.groupby('ID')['C'].sum()], axis=1) print(agg_df) # A C # ID # 1 4 36 # 2 3 14
downvote count: 0
has comment: http://stackoverflow.com/comment/90844056
type: Answer
upvote count: 1
score: 1

http://stackoverflow.com/comment/90816936
comment on: http://stackoverflow.com/a/51930703
type: AnswerComment
has text: Hey @TheHadrien ! Glad my answer was helpful to you. Could you please still select it as helpful? Thank you!
score: 0
type: Comment

http://stackoverflow.com/a/51844649
score: 2
has body: python command doesn't preserve your work You can try installing IPython, Jupyter, or use a proper IDE for practicing
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/51844590
downvote count: 0

http://stackoverflow.com/q/51844794
has title: Finding hierarchical structure in messy energy data
tagged with: pandas
has comment: http://stackoverflow.com/comment/90643860
has comment: http://stackoverflow.com/comment/90643822
has comment: http://stackoverflow.com/comment/90644097
favorite count: 0
has comment: http://stackoverflow.com/comment/90643572
type: UnansweredQuestion
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/90650541
score: 1
tagged with: energy
type: Question
tagged with: numpy
tagged with: algorithm
has answer: http://stackoverflow.com/a/51844923
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/90644233
has comment: http://stackoverflow.com/comment/90646759
has body: I have energy profile data (sampled at 3 hour intervals) for about 25 electricity meters in a building as pandas dataframe time series. The meters form a hierarchical structure where the top level meters include consumption data for the lower level meters. For example , ( a possible layered structure ) total - A - A1 - A2 - B - C - C1 - C2 - C21 - C22 where the lower levels add up to higher level consumption. (eg. C = C1 + C2) Now the task is to identify the inherent structure present in the data to use for other energy data analysis. Is there any algorithm that can be used to detect this layered structure from messy data? Must I exhaustively try all possible combinations for lets say 4 level structures to identify a possible match ( with some tolerance since the data is messy)? Kindly advise certain strategies to think about this problem differently from an algorithmic perspective. Note: The meter names are numbers and can not be interpreted to be different levels directly. I do not have a metering strategy . The magnitude of energy consumption varies (for eg. it may well be the case that A2 > C (in the above fig.)) Put in a better way , the hierarchy can only represent relative magnitudes between levels.
has comment: http://stackoverflow.com/comment/90646284

http://stackoverflow.com/q/51893568
tagged with: try-except
accepted answer: http://stackoverflow.com/a/51893593
tagged with: python
type: AnsweredQuestion
score: 0
possible better answer: http://stackoverflow.com/a/51893683
type: Question
has answer: http://stackoverflow.com/a/51893683
has answer: http://stackoverflow.com/a/51893593
has comment: http://stackoverflow.com/comment/90738295
tagged with: continue
has body: I have a try and except statement within a for loop. I am looking at data stored in a (perhaps over complicated) list that itself is stored in a defaultdict. I expect IndexErrors, but when they occur I simply do not need to compare any data, so I want to ignore the error. Here's my current code: for key, list_item in defdict.iteritems(): if len(list_item) == 2: if len(list_item[0][1]) &gt; 1 or len(list_item[1][1]) &gt; 1: compare00,compare01=[],[] if another_list.__contains__(list_item[0][0]): try: for item in defdict.iteritems(): if item[1][0][0] == list_item[0][0]: compare00.append(compare_function(item)) except IndexError: continue if another_list.__contains__(list_item[1][0]): try: for item in defdict.iteritems(): if item[1][1][0] == list_item[1][0]: compare10.append(compare_function(item)) except IndexError: continue print compare00,compare10 #etc I have since realised the continue statement is not correct. My if statements needn't be mutually exclusive, therefore, neither going to the next iteration of the loop (continue) nor leaving the loop (break) are appropriate. A blank except IndexError:, i.e., without the continue, is incorrect syntax. How should I ignore the error?
tagged with: python-2.7
has title: Ignore an IndexError in Python2.7 without continue statement
answer count: 2

http://stackoverflow.com/a/51945904
has body: Too long for a comment. I'm not exactly sure how ethereum works and what exact problem you are facing. But a quick google gave me these links A reddit answer to something similar you are asking The link which is being referred seems broken, so I did some backtracking, and here is the probable link to the referred code python library for ethereum
answers question: http://stackoverflow.com/q/51945714
score: 0
type: Answer

http://stackoverflow.com/comment/90824042
type: QuestionComment
comment on: http://stackoverflow.com/q/51936785
score: 1
has text: Sure, storing just the module and function name in the json is technically feasible... [`import_module`](https://docs.python.org/3/library/importlib.html#importlib.import_module) can import a module given its name, and you can get a function given its name using `getattr`. But it's hard to say whether this is the most practical approach for whatever it is you're trying to achieve.
type: Comment

http://stackoverflow.com/a/51879675
score: 1
downvote count: 0
has body: As an alternative to removing words you don't want, you can choose to select the words that you do want. As your example rows follow the same pattern, it looks like you want to select the 2nd and 6th word and use them to make the new name of the location. This would look something like this: df['new_location'] = '' for i,location in enumerate(df.Locations): df.new_location.iloc[i] = location.split(' ')[1] +' &amp; ' +location.split(' ')[5]
answers question: http://stackoverflow.com/q/51879018
type: Answer
upvote count: 1

http://stackoverflow.com/comment/90835198
has text: Please point out the similarities between your solution proposals and the other ones. Thanks. Removed the downvote so far.
comment on: http://stackoverflow.com/a/51942717
type: AnswerComment
score: 1
type: Comment

http://stackoverflow.com/comment/90872193
score: 0
comment on: http://stackoverflow.com/q/51844665
has text: @Merlin1896 I found the problem it is because I'm using Jupyter notebook
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51939703
tagged with: python
answer count: 0
downvote count: 0
has title: Group Months in string type to quarters in string type and add values on pandas df column
type: UnansweredQuestion
type: Question
score: 1
tagged with: dataframe
upvote count: 1
favorite count: 0
has body: I want to sum the values of every quarter, and rename it to 2000q1 format. This is returning a value, but I am not sure if it is the right one. To test it I am running a sum between the original columns and checking the values. What do you think about the method below? homes = homes[['State', 'RegionName', '2000-01', '2000-02', '2000-03', '2000-04', '2000-05', "2000-06", "2000-07", "2000-08", "2000-09", "2000-10", "2000-11", "2000-12", "2001-01", "2001-02", "2001-03","2001-04","2001-05","2001-06","2001-07","2001-08","2001-09","2001-10","2001-11","2001-12","2002-01","2002-02","2002-03","2002-04","2002-05","2002-06","2002-07","2002-08","2002-09","2002-10","2002-11","2002-12","2003-01","2003-02","2003-03","2003-04","2003-05","2003-06","2003-07","2003-08","2003-09","2003-10","2003-11","2003-12","2004-01","2004-02","2004-03","2004-04","2004-05","2004-06","2004-07","2004-08","2004-09","2004-10","2004-11","2004-12","2005-01","2005-02","2005-03","2005-04","2005-05","2005-06","2005-07","2005-08","2005-09","2005-10","2005-11","2005-12","2006-01","2006-02","2006-03","2006-04","2006-05","2006-06","2006-07","2006-08","2006-09","2006-10","2006-11","2006-12","2007-01","2007-02","2007-03","2007-04","2007-05","2007-06","2007-07","2007-08","2007-09","2007-10","2007-11","2007-12","2008-01","2008-02","2008-03","2008-04","2008-05","2008-06","2008-07","2008-08","2008-09","2008-10","2008-11","2008-12","2009-01","2009-02","2009-03","2009-04","2009-05","2009-06","2009-07","2009-08","2009-09","2009-10","2009-11","2009-12","2010-01","2010-02","2010-03","2010-04","2010-05","2010-06","2010-07","2010-08","2010-09","2010-10","2010-11","2010-12","2011-01","2011-02","2011-03","2011-04","2011-05","2011-06","2011-07","2011-08","2011-09","2011-10","2011-11","2011-12","2012-01","2012-02","2012-03","2012-04","2012-05","2012-06","2012-07","2012-08","2012-09","2012-10","2012-11","2012-12","2013-01","2013-02","2013-03","2013-04","2013-05","2013-06","2013-07","2013-08","2013-09","2013-10","2013-11","2013-12…
tagged with: pandas

http://stackoverflow.com/comment/90739721
type: AnswerComment
comment on: http://stackoverflow.com/a/51893730
score: 0
has text: The g.setDepthValue(10) is only for the grid, right? I tried increasing it just now, and also added p4.setDepthValue(1000). Sadly both didn't solve the problem
type: Comment

http://stackoverflow.com/comment/90846185
type: AnswerComment
has text: *"When you are defining `b = a[1]` it's a new object"* – What? That sounds wrong. Cannot tell if it's badly expressed or factually false. Overall, I don't know how this answers the question.
comment on: http://stackoverflow.com/a/51948169
score: 0
type: Comment

http://stackoverflow.com/comment/90644418
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51845504
has text: No. It is not possible.
score: 5

http://stackoverflow.com/a/51955257
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/51955228
upvote count: 2
has comment: http://stackoverflow.com/comment/90861670
score: 2
has comment: http://stackoverflow.com/comment/90861550
has body: It's easier to aggregate your columns with agg and then just remove the extras later, using str.replace. name_cols = ['PREFIX', 'FIRST_NAME', 'MIDDLE_NAME', 'LAST_NAME', 'SUFFIX'] df['FULLNAME'] = df[name_cols].agg(' '.join, axis=1).str.replace('\s+', ' ')
answers question: http://stackoverflow.com/q/51955228

http://stackoverflow.com/comment/90794143
has text: I got it working! It's a shame that `integers=True` doesn't apply when I zoom in too far, but I couldn't find a way to work around that. Thanks for your help!
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51910321
type: Comment

http://stackoverflow.com/a/51933280
answers question: http://stackoverflow.com/q/51919033
score: 0
has body: I had the similar issue but it was a race condition. the driver has to wait for the particular event to show up in the page before accessing or sending keys. try this code try{ Thread.Sleep(5000); }catch(Expression ex){ system.out.print(ex.getmessage()); } before sendkeys or just put Thread.sleep(5000); at first Note: 5000 as in 5 seconds or 5000 milliseconds try a larger number at first like 10000 milliseconds, then reduce the time.
has comment: http://stackoverflow.com/comment/90818041
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/90818323
has comment: http://stackoverflow.com/comment/90817437
has comment: http://stackoverflow.com/comment/90817257
accepted answer of: http://stackoverflow.com/q/51919033

http://stackoverflow.com/comment/90656421
type: QuestionComment
has text: What does `print(tokens)` or `print(len(tokens))` show? `tokens` is probably an empty list.
comment on: http://stackoverflow.com/q/51851780
score: 0
type: Comment

http://stackoverflow.com/comment/90593162
comment on: http://stackoverflow.com/a/51819046
type: AnswerComment
score: 0
type: Comment
has text: This looks great! When I try it out in regex101 it works (only issue is that it doesn't just capture the first occurrence). For some reason however, my python code finds a match in each email with this regex that captures only None for each of the values. I'm not sure why though.

http://stackoverflow.com/comment/90778155
has text: @DavidMaze: https://meta.stackoverflow.com/questions/372756/why-was-this-question-put-on-hold-as-too-broad
type: Comment
comment on: http://stackoverflow.com/q/51902100
score: 0
type: QuestionComment

http://stackoverflow.com/comment/90819029
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/51934451
has text: `board` is currently an attribute of the `Board` class. That means that each `Board` instance will share a single `board`.
type: Comment

http://stackoverflow.com/q/51899442
duplicate of: http://stackoverflow.com/q/40675781
has answer: http://stackoverflow.com/a/51899522
score: 0
has comment: http://stackoverflow.com/comment/90749807
has answer: http://stackoverflow.com/a/51899526
has comment: http://stackoverflow.com/comment/90749928
accepted answer: http://stackoverflow.com/a/51899518
has answer: http://stackoverflow.com/a/51899508
tagged with: python
has title: separate words in a sentence that has comma between them
linked to: http://stackoverflow.com/q/4998629
answer count: 4
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51899508
duplicate of: http://stackoverflow.com/q/4998629
type: Question
has comment: http://stackoverflow.com/comment/90750292
has body: I want to remove commas from one sentence and separate all the other words(a-z) and print them one by one. a = input() b=list(a) //to remove punctuations for item in list(b): //to prevent "index out of range" error. for j in range(len(l)): if(item==','): b.remove(item) break c="".join(b) //sentence without commas c=c.split() print(c) My input is : The university was founded as a standard academy,and developed to a university of technology by Habib Nafisi. and when I remove the comma: ... founded as a standard academyand developed to a university... and when I split the words: The university . . . academyand . . . what can I do to prevent this? I already tried replace method and it doesn't work.
has answer: http://stackoverflow.com/a/51899518
has comment: http://stackoverflow.com/comment/90750253

http://stackoverflow.com/comment/90809427
type: QuestionComment
score: 1
has text: This should help: https://discuss.elastic.co/t/how-to-call-python-script-from-logstash-to-process-partialy-logs/40009/2
comment on: http://stackoverflow.com/q/51929904
type: Comment

http://stackoverflow.com/comment/90723303
type: Comment
comment on: http://stackoverflow.com/q/51834467
score: 0
type: QuestionComment
has text: I think you can combine your pools into a single pool?

http://stackoverflow.com/a/51857546
downvote count: 0
type: Answer
score: 4
accepted answer of: http://stackoverflow.com/q/51857468
has body: Once you have your data downloaded into local_download_path you can use glob.glob to get files by extension: import glob images = glob.glob(local_download_path + '/*.jpg')
answers question: http://stackoverflow.com/q/51857468
upvote count: 4
type: AcceptedAnswer

http://stackoverflow.com/q/51921004
upvote count: 1
tagged with: tox
answer count: 1
favorite count: 0
has title: tox don't read setup.cfg
tagged with: python
type: AnsweredQuestion
downvote count: 0
tagged with: setup.py
has answer: http://stackoverflow.com/a/51921040
has body: I'm new to python and have some problems with tox. My tox.ini [tox] envlist = py36 [testenv] passenv = TOXENV CI TRAVIS TRAVIS_* usedevelop = True install_command = pip install -U {opts} {packages} deps = -r{toxinidir}/test-requirements.txt -r{toxinidir}/requirements.txt commands = python -V py.test -vvv -s [testenv:docs] commands = python setup.py build_sphinx My setup.cfg [build_sphinx] source-dir = docs/source build-dir = docs/build all_files = 1 [upload_sphinx] upload-dir = docs/build/html python setup.py build_sphinx works just fine, but /Users/ben/development/python/test/.tox/docs/bin/python setup.py build_sphinx says error: invalid command 'build_sphinx' My environment $ python --version Python 3.6.0 $ /Users/ben/development/python/test/.tox/docs/bin/python --version Python 3.6.0
score: 1
accepted answer: http://stackoverflow.com/a/51921040
type: Question

http://stackoverflow.com/q/51810828
type: Question
downvote count: 0
has answer: http://stackoverflow.com/a/51812930
answer count: 2
tagged with: pygame
favorite count: 0
tagged with: python-3.x
tagged with: python
has body: I need to add an icon on the bottom of the Sprite worker and then change this icon randomly at each iteration. Please notice that the Sprite worker has 2 states: RUNNING and IDLE. In each of these states, the worker has a specific image. What I need now is to put an additional small image on the bottom of worker that will specify emotional state: HAPPY or ANGRY. In the class Worker I create the array emo_images and also specify the variable emo_state. This variable denotes an emotional state of the worker: happy or angry. Each emotional state has its image stored in emotional_images. In the code I randomly generate the variable state_indicator. If it's greater than 9, then the emotional state of the worker is changed to ANGRY. Otherwise, it's happy. state_indicator = random.randint(0,10) if state_indicator &gt; 9: print(state_indicator) self.alert_notif_worker() def alert_notif_worker(self): self.emo_state = Worker.ANGRY However I don't not know how to put the emotional image on the bottom of the worker image, because I don't want to replace the worker image (IDLE, RUNNING). I only need to add another image on the bottom and this additional image should move together with the worker. If it's very difficult to do, then it would be also fine to have rectangles of two colours: red and green, instead of images, in order to indicate emotional states. Complete code: import sys import pygame, random from pygame.math import Vector2 from scipy.optimize import minimize import math WHITE = (255, 255, 255) GREEN = (20, 255, 140) GREY = (210, 210 ,210) BLACK = (0, 0 ,0) RED = (255, 0, 0) PURPLE = (255, 0, 255) SCREENWIDTH=1000 SCREENHEIGHT=578 # Create point vectors for the corners. corners = [ Vector2(0, 0), Vector2(SCREENWIDTH, 0), Vector2(SCREENWIDTH, SCREENHEIGHT), Vector2(0, SCREENHEIGHT) ] ABS_PATH = "/Users/sb/Desktop/" IMG_BACKGROUND = ABS_PATH + "images/background.jpg" IMG_WORKER_RUNNING = ABS_PATH + "images/workers/worker_1.png" IMG_WORKER_IDLE = ABS_PATH + "images/wor…
possible better answer: http://stackoverflow.com/a/51812930
type: AnsweredQuestion
score: 3
has title: How to put an additional image or rectangle on the bottom of Sprite?
upvote count: 3
has answer: http://stackoverflow.com/a/51813210
accepted answer: http://stackoverflow.com/a/51813210

http://stackoverflow.com/q/51932057
tagged with: npm
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/24514936
has answer: http://stackoverflow.com/a/51937247
type: Question
has body: I have a python application which I am deploying through Flask using the render_template() function onto a webpage. At the same time, I am trying to use npm to incorporate some javascript modules into my code. Whilst I have correctly installed the needed modules within the static folder with all my other javascript files, the code refuses to recognize these modules. My Flask CLI shows that my local development server has correctly located the module file but if I run var module = require('module') the code shows no indication of having worked if run through the browser. This goes for whether I include this script inside my html template in the template folder, or an external javascript file in the static folder. Interestingly enough, if I run the same external javascript file through the npm CLI using node script.js, the script will execute. Can someone explain what I'm doing wrong and why this is so? I'm completely new to node.js, npm and have just started today so any help would be appreciated. I am currently basing my work off of the answer with 6 upvotes here: How can I serve NPM packages using Flask?
downvote count: 0
has title: How to use NPM Modules with Flask?
tagged with: javascript
tagged with: flask
score: 6
favorite count: 0
has answer: http://stackoverflow.com/a/51934938
answer count: 3
tagged with: python
upvote count: 6
has answer: http://stackoverflow.com/a/59699217
tagged with: node.js

http://stackoverflow.com/comment/90713792
type: QuestionComment
has text: urls.csv d short_cod long_url created_ti creator_id premium country 1 GTq6Bl https://w 2018-07-2 78 FALSE CA 2 EmazTI https://as 2018-07-2 124 FALSE GB visits.csv browser_t visit_time short_cod country platform ip_address Chrome 2018-07-2 GTq6Bl IT Windows 78.110.51.215 Firefox 2018-07-2 GTq6Bl IT Linux 27.243.245.232 Chrome 2018-07-2 GTq6Bl JP Mac OS 97.155.155.73 Chrome 2018-07-2 GTq6Bl RU Linux 85.201.130.148
comment on: http://stackoverflow.com/q/51868723
score: 0
type: Comment

http://stackoverflow.com/comment/137934677
has text: The question is specifically about SQL Server and PyODBC. MySQL and MySQL Connector are entirely irrelevant here.
type: Comment
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/72598063

http://stackoverflow.com/q/51839778
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90633591
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has body: Is there a better (faster) way to remove stopwords from a csv file? Here is the simple code, and over an hour later I am still waiting for the results (so I don't even know if it's actually working): import nltk from nltk.corpus import stopwords import csv import codecs f = codecs.open("agenericcsvfile.csv","r","utf-8") readit = f.read() f.close() filtered = [w for w in readit if not w in stopwords.words('english')] The csv-file has 50.000 rows and a total of ~15 million words. Why does it take so long? Sadly, this is only a subcorpora. I will have to do this with over 1 million rows and over 300 million words. So is there a way to speed things up? Or a more elegant code? CSV-file sample: 1 text,sentiment 2 Loosely based on The Decameron, Jeff Baena's subversive film takes us behind the walls of a 13th century convent and squarely in the midst of a trio of lustful sisters, Alessandra (Alison Brie), Fernanda (Aubrey Plaza), and Ginerva (Kate Micucci) who are "beguiled" by a new handyman, Massetto (Dave Franco). He is posing as a deaf [...] and it is coming undone from all of these farcical complications.,3 3 One might recommend this film to the most liberally-minded of individuals, but even that is questionable as [...] But if you are one of the ribald loving few, who likes their raunchy hi-jinks with a satirical sting, this is your kinda movie. For me, the satire was lost.,5 4 [...] [...] 50.000 The movie is [...] tht is what I ahve to say.,9 The desired output would be the same csv-file without the stop-words.
has answer: http://stackoverflow.com/a/51840236
tagged with: stop-words
score: 1
has answer: http://stackoverflow.com/a/51840387
upvote count: 1
has comment: http://stackoverflow.com/comment/90632764
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/90633003
has title: Speed up removing stopwords from huge csv-file
downvote count: 0
has comment: http://stackoverflow.com/comment/90633463
favorite count: 0

http://stackoverflow.com/q/51823778
has title: $http.get response is undefined
score: 0
has comment: http://stackoverflow.com/comment/90622164
answer count: 1
has answer: http://stackoverflow.com/a/51826220
has comment: http://stackoverflow.com/comment/90602190
has body: I am working on an front end at the moment,and using python for back end. Front end is html and i am using angularJs for the communications. My issue is that I cannot get the response from python backend, though it is called properly, a list is generated and i write result as following (in my python code) self.write({"success":True, "data":list}) But, angular code does not recieve any responses. Just success (http 200OK) status code is returned. How can I make the backend successfully send the list as response? Btw, angular code is $scope.init = function () { //Take the list of applications from database var req = { method: 'GET', url: 'http://localhost:8888/app', headers: { 'Content-Type': "application/json;charset=UTF-8" } } $http(req).success(function(data) { $scope.results = response.data // response is undefined?? } ) .error (.......);
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90602067
tagged with: angularjs
tagged with: frontend
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/90602875
tagged with: backend
has comment: http://stackoverflow.com/comment/90638460

http://stackoverflow.com/a/51938909
downvote count: 0
score: 3
upvote count: 3
has body: The problem is that you're trying to treat UTF-16-LE data—from files, or powershell pipes, or something else—as UTF-8 or Latin-1 or cp1252 or similar. The solution is probably something like this: current_file = open(input_file, encoding='utf-16') More generally, you're supposed to know what kind of files you're reading. A UTF-16-with-BOM text file, a UTF-8 text file, and a whatever-my-OEM-code-page-is text file are all different things, and you need to pass the right encoding. Otherwise, you're just asking Python to pick a default and crossing your fingers. To understand why this happens: You only have plain English characters, which are all encodable in ASCII. In UTF-16, each of those characters takes two bytes. One byte is the same as the ASCII value of that character, the other is 0. In UTF-8, Latin-1, or another ASCII-compatible encoding, each of these characters takes one byte, the same one byte as in ASCII. So, if you try to read the UTF-16 as if it were UTF-8 or Latin-1, every even byte is the character you want, and every odd byte is a 0, which means the NUL character. Depending on how you print things out, this NUL characters may be invisible, or print as spaces, or even truncate the string. The extra two characters at the start are the two bytes from BOM—which is how you're supposed to distinguish UTF-16-LE from UTF-16-BE—being read as Latin-1 characters. The BOM is a special character U+FEFF, which shows up as the two bytes \xFF and \xFE in UTF-16-LE, but \xFE and \xFF in UTF-16-BE. But those same bytes, in Latin-1, are the y-with-umlaut and thorn characters that you're seeing.
answers question: http://stackoverflow.com/q/51938771
type: Answer

http://stackoverflow.com/a/51898128
answers question: http://stackoverflow.com/q/51897455
upvote count: 5
score: 5
type: AcceptedAnswer
downvote count: 0
has body: Using blockSignals in this case is a double-edged sword because I think you're using it to avoid an infinite loop. but this also does not generate that the model is updated, besides that it is unnecessary since setCurrentRow() only updates if it is different from its previous value avoiding that problem. The solution is to use QTimer.singleShot() to update the change: import sys from functools import partial from PyQt5.QtWidgets import QApplication, QListWidget from PyQt5.QtCore import QTimer app = QApplication(sys.argv) l = QListWidget() l.setSelectionMode(QListWidget.SingleSelection) l.addItems(list('abcde')) row = 3 def onCurrentRowChanged(): QTimer.singleShot(0, partial(l.setCurrentRow, row)) l.currentRowChanged.connect(onCurrentRowChanged) l.show() sys.exit(app.exec_()) Note: the logic does not change if the currentRowChanged signal is changed to currentItemChanged.
has comment: http://stackoverflow.com/comment/90800394
accepted answer of: http://stackoverflow.com/q/51897455
type: Answer

http://stackoverflow.com/a/51918673
type: AcceptedAnswer
upvote count: 1
type: Answer
downvote count: 0
score: 1
has body: The following seems to work for me (on Windows). It uses subprocess.Popen() to execute the other script because this gives more control over what goes on. It turns buffering off to eliminate any delays that might cause, plus it redirects stderr to stdout to so all output can be retrieved from a single source.. Also note it also includes the correction @Ketan Mukadam mentions is his answer tregarding the value of __name__ in your first script. main_script.py: def main(): # Function that takes a long time (in my actual code) x += 1 # this raises an error if __name__ == '__main__': print("start") main() print("end") run.py: import subprocess import sys def run(): kwargs = dict(bufsize=0, # No buffering. stdout=subprocess.PIPE, stderr=subprocess.STDOUT, # Redirect stderr to stdout. universal_newlines=True) args = [sys.executable, 'main_script.py'] with subprocess.Popen(args, **kwargs).stdout as output: for line in output: print(line, end='') # Process the output... if __name__ == '__main__': run() Output from executing run.py: start Traceback (most recent call last): File "main_script.py", line 10, in &lt;module&gt; main() File "main_script.py", line 6, in main x += 1 # this raises an error UnboundLocalError: local variable 'x' referenced before assignment
accepted answer of: http://stackoverflow.com/q/51918012
answers question: http://stackoverflow.com/q/51918012

http://stackoverflow.com/a/54294932
type: Answer
has body: To remove this warning, you could replace the argument 'event' by '_', or just do something with the object, like printing it to console. Even though the argument of the function seems useless, it cannot be removed: It belongs to the signature of a valid event function.
upvote count: 10
answers question: http://stackoverflow.com/q/51857315
score: 10
downvote count: 0

for-loop
tags question: http://stackoverflow.com/q/51910888
tags question: http://stackoverflow.com/q/51828178
tags question: http://stackoverflow.com/q/51947200
tags question: http://stackoverflow.com/q/51937095
tags question: http://stackoverflow.com/q/51901590
tags question: http://stackoverflow.com/q/51820939
tags question: http://stackoverflow.com/q/51827635
tags question: http://stackoverflow.com/q/51936434
tags question: http://stackoverflow.com/q/51933830
tags question: http://stackoverflow.com/q/51812933
tags question: http://stackoverflow.com/q/51887163
tags question: http://stackoverflow.com/q/51829008
tags question: http://stackoverflow.com/q/51927682
tag name: for-loop
tags question: http://stackoverflow.com/q/51856120
tags question: http://stackoverflow.com/q/51830722
tags question: http://stackoverflow.com/q/51813600
tags question: http://stackoverflow.com/q/51876523
tags question: http://stackoverflow.com/q/51940525
tags question: http://stackoverflow.com/q/51805718
tags question: http://stackoverflow.com/q/51888423
tags question: http://stackoverflow.com/q/51828392
tags question: http://stackoverflow.com/q/51845056
tags question: http://stackoverflow.com/q/51860382
tags question: http://stackoverflow.com/q/51944790
type: Tag
tags question: http://stackoverflow.com/q/51919344
tags question: http://stackoverflow.com/q/51864925
tags question: http://stackoverflow.com/q/51907562
tags question: http://stackoverflow.com/q/51851410
tags question: http://stackoverflow.com/q/51860247
tags question: http://stackoverflow.com/q/51919448
tags question: http://stackoverflow.com/q/51856948
tags question: http://stackoverflow.com/q/51886089
tags question: http://stackoverflow.com/q/51918444
tags question: http://stackoverflow.com/q/51801265

http://stackoverflow.com/q/51922751
type: Question
has comment: http://stackoverflow.com/comment/90795232
has answer: http://stackoverflow.com/a/51922758
tagged with: function
duplicate of: http://stackoverflow.com/q/26045779
answer count: 1
has title: How do you switch a negative to a positive and a postive to a negative in a list?
type: UnansweredQuestion
score: 0
has body: How do you switch a negative to a positive and a postive to a negative in a list? I want to make a function to do this. For example [1,-3, 5] would become [-1, 3, -5]
has comment: http://stackoverflow.com/comment/90795087
tagged with: python
tagged with: list
linked to: http://stackoverflow.com/q/26045779

http://stackoverflow.com/q/51819441
type: AnsweredQuestion
score: 3
downvote count: 0
tagged with: file
type: Question
has body: I have this folder structure, within edi_standards.py I want to open csv/transaction_groups.csv But the code only works when I access it like this os.path.join('standards', 'csv', 'transaction_groups.csv') What I think it should be is os.path.join('csv', 'transaction_groups.csv') since both edi_standards.py and csv/ are on the same level in the same folder standards/ This is the output of printing __file__ in case you doubt what I say: &gt;&gt;&gt; print(__file__) ~/edi_parser/standards/edi_standards.py
has comment: http://stackoverflow.com/comment/90592630
upvote count: 3
answer count: 2
tagged with: operating-system
favorite count: 0
possible better answer: http://stackoverflow.com/a/51840228
has answer: http://stackoverflow.com/a/51819512
accepted answer: http://stackoverflow.com/a/51819512
has answer: http://stackoverflow.com/a/51840228
tagged with: python
has title: Weird python file path behavior

http://stackoverflow.com/a/51930672
has comment: http://stackoverflow.com/comment/90811172
has comment: http://stackoverflow.com/comment/90811259
upvote count: 7
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/90811063
has body: Building on my naive approach comment: a = [(1, 2), (3, 4), (5, 6), (7, 8)] b = [(x[1], y[0]) for x, y in zip(a, a[1:]+a[:1])] # [(2, 3), (4, 5), (6, 7), (8, 1)] This pairs elements from adjacent pairs and thus guarantees no pair is in the original list
downvote count: 0
score: 7
accepted answer of: http://stackoverflow.com/q/51930542
answers question: http://stackoverflow.com/q/51930542
has comment: http://stackoverflow.com/comment/90811225

database-security
type: Tag
tag name: database-security
tags question: http://stackoverflow.com/q/51860075

http://stackoverflow.com/q/51809544
tagged with: arrays
answer count: 1
downvote count: 0
has title: Minimum Sum, Revisited. (Not Minimum Subarray Sum)
score: 1
tagged with: sorting
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/51811752
type: UnansweredQuestion
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/90577581
has body: Given a number n, an array arr I will like to pull the smallest number of integers to reach n, and also remove the numbers I used from arr. It is better explained with an example. Given n = 13 and arr = [8,0,2,2,3,1,1,3,1] I have to remove the smallest number of integers from arr that will sum up to 13. My strategy is to sort arr in decreasing order, arr will hence be [8,3,3,2,2,1,1,1,0], then I start iterating from the first to the last number and break out when I reach n, 13 in this case. Given our example, I will end with 8,3,3 since it I will be at 13 already. But here comes the problem, Just behind 3 is 2 and I will be saving more if I choose 2 instead of 3 (8 + 3 + 2 = 13). I say saving more because this problem is part of another huge problem and to implement it successfully, I need to get the minimum possible. If at the place of two, I had say 5, my sorting method will have been just fine. And also, I will like to remove the numbers I used to get the sum and keep them in another array, call it a arr1. SO for this example, the result should be arr = [3,2,1,1,1,0] and arr1 = [8,3,2]. Can Anyone help me Please? My Python Code Looks something like this (assuming the list is already sorted): n = 13 arr1 = [] arr = [8,3,3,2,2,1,1,1,0] for i in xrange(len(arr)): if sum(arr1) &lt; n: arr1.append(arr[0]) del arr[0] else: break print arr,arr1 This will print [2,2,1,1,1,0] [8,3,3]. But I would like it to print [8,3,2] [3,2,1,1,1]

http://stackoverflow.com/q/51852864
has body: env VPS : ubuntu 16.04 Python 3.5 Local: Mac project structure inkedNewsCrawler .git / inkedNewsCrawler / (all directory down from here includes "_ init _.py") _ init _.py custom_crawler / spiders / utils / ect.... readme.md requirements.txt Here is how to reproduce. Work on local machine, push via git. Pull from server set up VENV (including pip install..). run the script (&gt;&gt; from inkedNewsCrawler.custom_crawler import x). Works fine on local machine but will raise ImportError: No module named 'inkedNewsCrawler' BUT when i change as from custom_crawler import x ON LOCAL ModuleNotFoundError: No module named 'custom_crawler' ON VPS Works Fine!!! ??? Things I've tried added project root to PYTHONPATH triple checked pip, venv settings tested on local jupyter notebook (import project worked)
has title: Python module not found <project> only on VPS. works fine on local machine
type: Question
has comment: http://stackoverflow.com/comment/90658388
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/90658595
has answer: http://stackoverflow.com/a/51853160
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/90773279
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51911391
has text: @JohnGordon thanks, that makes alot of sense.

http://stackoverflow.com/q/51800323
has body: I am trying to create a script that will check if there is an event expected to happen today and then, it will send a mail. Unfortunately, I am stuck with something quite stupid. I don't know why my code is not returning anything from the database when it should. # Enviar correu Python 3.6 (NO ANOMENAR EMAIL.PY) import smtplib, pymysql.cursors, secrets, re, datetime from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from time import strftime def dbb(): connection = pymysql.connect(host='X', user='root', password='X', db='deuresc', charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor) try: with connection.cursor() as cursor: # Llegim tots els recordatoris dataactual = strftime('%Y-%m-%d') data = datetime.datetime.strptime(dataactual, "%Y-%m-%d") datafinal = data + datetime.timedelta(days=1) sql = "SELECT * FROM `deures` WHERE `data`=%s" cursor.execute(sql, datafinal) resultat = cursor.fetchall() for row in resultat: data = str(row['data']) print(data) tasca = str(row['tasca']) print(tasca) fromaddr = "X" PASSWORD = "X" welcome = ['Jefe', 'Gery', 'Boss', 'Gary'] # Misstage del correu SUBJECT = "Recordatori deures " + data body = "Bon dia " + secrets.choice(welcome) + ',' + '\n' + 'Tens les següents tasques programades per demà: ' + '\n' + data + ' ' + tasca toaddr = "X" try: msg = MIMEMultipart() msg['From'] = fromaddr msg['To'] = toaddr msg['Subject'] = SUBJECT msg.attach(MIMEText(body, 'plain')) # Detalles del servidor de correu (Gmail, SMTP, Port: 587, TLS) server = smtplib.SMTP('smtp.gmail.com', 587) server.starttls() server.login(fromaddr, PASSWORD) text = msg.as_string() server.sendmail(fromaddr, toaddr, text) server.quit() print("S'ha enviat el recordatori a '" + toaddr + "' satisfactoriament!") except: print("S'ha produït un error!") finally: connection.close() dbb() DB rows at the moment: NEW CODE WORKING edited
type: Question
tagged with: pymysql
has comment: http://stackoverflow.com/comment/90557092
has title: Pymysql not returning anything
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/90558695
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/90558563
tagged with: mysql
upvote count: 1

http://stackoverflow.com/comment/90707087
comment on: http://stackoverflow.com/q/51877618
score: 0
type: Comment
type: QuestionComment
has text: @mamad this is not working, it kinda tuple of list

http://stackoverflow.com/q/51918136
favorite count: 0
has answer: http://stackoverflow.com/a/51918191
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51918171
has answer: http://stackoverflow.com/a/51918154
tagged with: python
answer count: 4
has body: just started learning python. trying to change a columns data type from object to float to take out the mean. I have tried to change [] to () and even the "". I dont know whether it makes a difference or not. Please help me figure out what the issue is. thanks!! My code: df["normalized-losses"]=df["normalized-losses"].astype(float) error which i see: attached as imageenter image description here
has comment: http://stackoverflow.com/comment/90786076
score: 1
upvote count: 1
has title: not able to change object to float in pandas dataframe
has answer: http://stackoverflow.com/a/51918316
type: Question
tagged with: object
tagged with: pandas
linked to: http://stackoverflow.com/q/21771133
tagged with: types
downvote count: 0
has comment: http://stackoverflow.com/comment/90786924

http://stackoverflow.com/q/51831219
has comment: http://stackoverflow.com/comment/90616691
tagged with: python
tagged with: design-patterns
type: AnsweredQuestion
has title: Know all baseclass's implementations
type: Question
accepted answer: http://stackoverflow.com/a/51831771
score: 0
has body: Problem: I am trying to simulate a boids particle system with python for an addon I am creating for Blender 3D, something quite complex and will be done from scratch. Its the third time I try to design a maintainable code structure for it. I tried to come up with pythonic design that allow for fast prototyping of different classes of particles interacting with each other, such that I can just create a new particle implementation and have it to interact with the other particles in the system. see the example: class ParticleSystem: def __init__(self): self.particles = [] def add_particle(self, particle): self.particles.append(particle) def step_frame(self, speed): for p in self.particles: p.step(speed) class Particle: def __init__(self, system) self.location = Vector(0,0,0) self.system = system def step(speed): for particle in self.system.particles: #random interatcion formula self.location = particle.location + self.location system = ParticleSystem() p = Particle(system) system.add_particle(p) As you can see this my best aproach but it gets quite messy when I have multiple classes of particles and I have to pass the system to the particle and then the particle to the system. question Is there a way so I can detect when the creation of a class implementation like: Class Baseball(Particle): and have the system class to know all the existing types so I can just call system.create_baseball(location)?
answer count: 1
has answer: http://stackoverflow.com/a/51831771

http://stackoverflow.com/a/51933725
downvote count: 0
answers question: http://stackoverflow.com/q/51933565
type: Answer
has body: Try using a dictionary, if it serves the purpose. wind_data_list = { 'date': [], 'time': [], 'ws': [], 'd': [], 't': [] } wind_data_list['date'].append(date_data) wind_data_list['time'].append(time_data) wind_data_list['ws'].append(wind_speed_data) wind_data_list['d'].append(direction) wind_data_list['t'].append(temperature)
score: 3
upvote count: 3
accepted answer of: http://stackoverflow.com/q/51933565
type: AcceptedAnswer

http://stackoverflow.com/comment/90616770
type: Comment
has text: Therefore your solution will not get the desired output, see [here](https://regex101.com/r/oTPv8q/1).
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51831264

http://stackoverflow.com/comment/90635740
comment on: http://stackoverflow.com/a/51807319
score: 0
type: AnswerComment
type: Comment
has text: Hey Jerin I almost got what I was Expecting..... Thanks a Lot..... Now the only problem is that Image of `watermark_pic` is not stored in /media which I had set default for Storing all Images and Uploads.....Thanks again

http://stackoverflow.com/a/51834832
downvote count: 1
has comment: http://stackoverflow.com/comment/90623770
has comment: http://stackoverflow.com/comment/90623522
has comment: http://stackoverflow.com/comment/90623441
answers question: http://stackoverflow.com/q/51834311
score: -1
upvote count: 0
type: Answer
has body: You will need to get indexes that are not present in first one, so use just sets without symmetric_difference. Use enumerate() to get indexes easier. oldCol1 = [1, 2, 3, 4, 5] oldCol2 = ['A', 'B', 'C', 'D', 'E'] newCol1 = [1, 2, 3, 4, 5, 6] newCol2 = ['A', 'B', 'C', 'D', 'E', 'A'] indexes = [i for i, v in enumerate(newCol1) if v not in set(oldCol1)] resultCol1 = [newCol1[i] for i in indexes] resultCol2 = [newCol2[i] for i in indexes] print(resultCol1, resultCol2)

http://stackoverflow.com/a/56283693
upvote count: 16
has comment: http://stackoverflow.com/comment/125882245
type: Answer
has body: Adding this for people with the same issue. OP was able to find the answer here (his answer on another forum): https://python-forum.io/Thread-Fatal-Python-error-init-sys-streams-can-t-initialize-sys-standard-streams-Attribute?page=3 Just in case if someone again faces this exact same issue I would clarify what was the problem and how it was solved. Initially it seemed like known python bug which happens when a file is named io.py which causes conflict with standard module io, this was clearly not case here. Member @Gribouillis here pointed out to try executing python -E and it worked. Afterwards @metulburr again pointed out this behavior is not normal for fresh python installations. This clearly meant something was wrong with PYTHONPATH in environment variables. What I did next was to remove all python paths from paths in environment variables(check @snippsat's screenshot for reference). Then uninstalled current python version. It is important to get rid of all paths to python installation before reinstalling because error occurred due to a invalid (likely due to change in installation directory) python path in paths. This completely solved the problem. Also to reiterate what @gribouillis said it was probably bad idea to add PYTHONPATH to system in first place.
downvote count: 0
score: 16
answers question: http://stackoverflow.com/q/51950533

http://stackoverflow.com/q/51820746
has title: AttributeError: 'numpy.ndarray' object has no attribute 'powers_'
has answer: http://stackoverflow.com/a/51820974
has body: Here is my program using sklearn. X = np.array([[1, 2, 4],[2, 3, 9]]).T print(X) y = np.array([1, 4, 16]) X_poly = PolynomialFeatures(degree=2).fit_transform(X) print(X_poly) model = LinearRegression(fit_intercept = False) model.fit(X_poly,y) print('Coefficients: \n', model.coef_) print('Others: \n', model.intercept_) print(X_poly.powers_) X_predict = np.array([[3,3]]) print(model.predict(feats.transform(X_predict))) I have these errors: ---&gt; 17 print(X_poly.powers_) 18 19 X_predict = np.array([[3,3]]) AttributeError: 'numpy.ndarray' object has no attribute 'powers_' Any help please ?
type: Question
has answer: http://stackoverflow.com/a/51820949
tagged with: numpy
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/51820997
tagged with: scikit-learn
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/31290976
tagged with: python

http://stackoverflow.com/comment/90761149
score: 1
comment on: http://stackoverflow.com/q/51905191
type: Comment
has text: I don't want to use exceptions because I want to have an opportunity to keep the generated code readable.
type: QuestionComment

http://stackoverflow.com/comment/90570308
type: QuestionComment
has text: Please see the section starting "Another usage of the `*l` idiom is to unpack argument lists when calling a function." in the accepted answer of the linked question.
score: 1
comment on: http://stackoverflow.com/q/51807522
type: Comment

http://stackoverflow.com/q/51841441
tagged with: keras
has title: Pad_Sequences getting multiple arguments for max_len (Keras)
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51843022
accepted answer: http://stackoverflow.com/a/51843022
has body: I'm attempting to use a Keras Model in a Genetic Algorithm for text classification, however i'm getting an error with pad_sequences where it claims that: TypeError: pad_sequences() got multiple values for argument 'maxlen' The actual pad_sequences variable assignment is: data = self.pad_sequences(sequences, maxlen=MAX_SEQUENCE_LENGTH) Which is found within: def get_data(self): """Retrieve the dataset and process the data.""" batch_size = 128 VALIDATION_SPLIT = 0.2 MAX_SEQUENCE_LENGTH = 1000 MAX_NUM_WORDS = 20000 csv = 'VocabCSV.csv' my_df = self.pd.read_csv(csv,index_col=0,encoding = 'latin-1') my_df.dropna(inplace=True) my_df.reset_index(drop=True,inplace=True) print(my_df.info()) texts = my_df.Text # list of text samples labellist = my_df.Target # list of labels label_vals = [] # label values list labels_index = {} # dictionary mapping label name to numeric id labels = [] # list of label ids for label in labellist: if label not in label_vals: label_vals.append(label) for idx, text in enumerate(texts): for label in label_vals: if label == labellist[idx]: label_id = label_vals.index(label) labels_index[text] = label_id labels.append(label_id) print("labels index {}".format(len(labels_index))) print("labels size: %s " % len(labels)) print("found %s texts." % len(texts)) # finally, vectorize the text samples into a 2D integer tensor tokenizer = self.Tokenizer(num_words=MAX_NUM_WORDS) tokenizer.fit_on_texts(texts) sequences = tokenizer.texts_to_sequences(texts) word_index = tokenizer.word_index print('Found %s unique tokens.' % len(word_index)) data = self.pad_sequences(sequences, maxlen=MAX_SEQUENCE_LENGTH) print(self.np.asarray(labels).shape) labels = self.to_categorical(labels) print('Shape of data tensor:', data.shape) print('Shape of label tensor:', labels.shape) # split the data into a training set and a validation set indices = self.np.arange(data.shape[0]) self.np.random.shuffle(indices) data = data[indices] labels = labels[indices] num_validation_samples = int…
type: Question
score: 0
answer count: 1

http://stackoverflow.com/q/51820208
score: 0
has comment: http://stackoverflow.com/comment/90594246
upvote count: 1
answer count: 1
downvote count: 1
accepted answer: http://stackoverflow.com/a/51820338
has title: Slice a list of objects
has comment: http://stackoverflow.com/comment/90594487
has answer: http://stackoverflow.com/a/51820338
tagged with: python
has comment: http://stackoverflow.com/comment/90594621
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90594394
has body: I have a class Card: class Card: def __init__(self, rank, suit): self.rank = rank self.suit = suit self.value = VALUES[self.rank] def __str__(self): return f'{self.rank} of {self.suit} with value of {self.value}' and I'm creating a list: ls = [Card('Nine','Diamonds'),Card('Ten','Diamonds'),Card('Eight','Diamonds')] When I print: print(ls[1:]) I get: [Card object at 0x000001884AAF3400, Card object at 0x000001884AB147B8] as I've read I should implement: def __getitem__: but I'm not sure how. Expected output is a list with string representation of card objects.
type: Question
has comment: http://stackoverflow.com/comment/90596070
favorite count: 0
tagged with: slice

http://stackoverflow.com/q/51839766
upvote count: 1
answer count: 1
has body: I'm trying to create a payment related to an invoice via XML RPC (Odoo11) and I can't figure how. Can you give me an example of a payment insertion via XML RPC ? Which method should I call &amp; with what arguments ? Thanks !
tagged with: python
tagged with: odoo-11
downvote count: 0
type: UnansweredQuestion
type: Question
has answer: http://stackoverflow.com/a/51930071
score: 1
favorite count: 0
tagged with: xml-rpc
has title: How to insert a payment related to an invoice via Odoo API RPC [Odoo11] [python]?

http://stackoverflow.com/comment/90593356
type: QuestionComment
has text: Btw: asking on Stackoverflow is not considered research but if you need a resource to learn about python control flow: there you go [for-loops](https://docs.python.org/3/tutorial/controlflow.html#for-statements)
comment on: http://stackoverflow.com/q/51819773
score: 5
type: Comment

http://stackoverflow.com/comment/90721845
type: QuestionComment
score: 1
has text: @mm_nieder otherwise, in your code, for `check_time_2`, in the `return`, if you replace `&` (and) by `|` (or) it should work better because the hour is either under 6 or above 18, can't be both like in `check_time` where it has to be both above 6 and under 18
comment on: http://stackoverflow.com/q/51883687
type: Comment

http://stackoverflow.com/comment/90631740
type: Comment
comment on: http://stackoverflow.com/q/51838887
has text: Are you sure you want Django to serve these static files during development? Talk to your frontend guys, they might have a better solution..
score: 0
type: QuestionComment

http://stackoverflow.com/a/51894390
answers question: http://stackoverflow.com/q/51894145
score: 1
has body: Not knowing which Anti-Virus program you use... see this link. We request you to disable AVG Protection temporarily by following the instructions as mentioned in this article: http://avgread.me/1GnMD3N and then reinstall the Python application. Once done with that please enable AVG Protection and add the installed path of Python application to AVG's exception. Python is no malware, however, I also don't know where you downloaded your python distribution. Feel free to download it from the official repositories for windows.
upvote count: 1
downvote count: 0
type: Answer

http://stackoverflow.com/comment/90841950
comment on: http://stackoverflow.com/q/51944827
score: 0
type: Comment
type: QuestionComment
has text: Not only for Col4 but for all columns where is negative sign.

http://stackoverflow.com/a/51932287
answers question: http://stackoverflow.com/q/51931138
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/90845693
has body: Your for loop does the job: it did replace the text correctly. The change is in your root variable. You can verify that by adding the following line right after the for loop: ElementTree.dump(root) Now that you have the XML updated, you will need to write that into a file: tree.write('newfile.xml') Where tree is the result of ElementTree.parse(). So, to put everything together: tree = ElementTree.parse('messages.xml') root = tree.getroot() for elem in root: for subelem in elem: if 'RequestNo' in subelem.tag: subelem.text = '41194813' break tree.write('messages-new.xml') Dealing with Namespaces Your XML document contains namespaces, so if you plan to search for a tag, you need to include the namespaces in the tag names. Here is an alternative solution which deals with namespaces: tree = ElementTree.parse('messages.xml') root = tree.getroot() namespaces = {'xxx': 'URL/sampleMessages-v1'} node = root.find('xxx:Header/xxx:RequestNo', namespaces) if node is not None: node.text = '41194813' tree.write('messages-new.xml') In the above example, I just gave your namespace the name 'xxx', it can be anything 'foo', 'bar', ... but should be used as prefix in the call to root.find(). Removing "ns0" from Output File In order to remove "ns0" from output file, you need to register the namespace before writing: ElementTree.register_namespace('', 'URL/sampleMessages-v1') tree.write('messages-new.xml')

http://stackoverflow.com/a/51896148
upvote count: 4
answers question: http://stackoverflow.com/q/51890210
downvote count: 0
has body: To put it all together: Python3: import socket socket.getaddrinfo(socket.gethostname(), 0, flags=socket.AI_CANONNAME)[0][3] Python2: import socket socket.getaddrinfo(socket.gethostname(), 0, 0, 0, 0, socket.AI_CANONNAME)[0][3] Credits: How do I get my computer&#39;s fully qualified domain name in Python?
score: 4
type: Answer

http://stackoverflow.com/a/51813117
upvote count: 1
has body: You need to call rashka.fullname() else you're comparing a method to a str.
downvote count: 0
answers question: http://stackoverflow.com/q/51813104
type: Answer
score: 1

http://stackoverflow.com/q/51904755
accepted answer: http://stackoverflow.com/a/51906984
type: Question
has answer: http://stackoverflow.com/a/51904801
tagged with: django-models
has answer: http://stackoverflow.com/a/51906984
score: 0
answer count: 3
possible better answer: http://stackoverflow.com/a/51904931
has title: One model object per user Django
tagged with: django
tagged with: python
has body: I don't want to extend my userprofile. I made a new model with name, contact and email. The problem : With createview the user is able to create multiple instances of the user_info model. Is there any chance we can limit user to make only one user_info and update the same everytime. models.py class user_info(models.Model): booked_by = models.CharField(max_length=100) Name = models.CharField(max_length=40) contact = models.IntegerField() email = models.EmailField() views.py class user_info_create(LoginRequiredMixin,CreateView): login_url = 'Mel:user_login' form_class = user_infoform template_name = 'Mel/user_info_form.html' def form_valid(self, form): form.instance.booked_by = self.request.user return super(user_info_create, self).form_valid(form) class user_info_detail(LoginRequiredMixin,DetailView): login_url = 'Mel:user_login' model = user_info context_object_name = "book" def get_queryset(self): return user_info.objects.filter(booked_by=self.request.user)
type: AnsweredQuestion
tagged with: django-views
has answer: http://stackoverflow.com/a/51904931

http://stackoverflow.com/comment/90864369
has text: If it is coming from Excel you can get any data at all in any cell, so you'll have to check the contents of your data. And yes, it would be nice if more information was given (which row/column caused the problem!). Feel free to create an issue in cx_Oracle requesting that.
comment on: http://stackoverflow.com/q/51950472
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51861577
has comment: http://stackoverflow.com/comment/90675528
answer count: 4
has comment: http://stackoverflow.com/comment/90675348
upvote count: 18
accepted answer: http://stackoverflow.com/a/51861670
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90675372
has comment: http://stackoverflow.com/comment/90675700
downvote count: 0
has answer: http://stackoverflow.com/a/51861874
favorite count: 0
possible better answer: http://stackoverflow.com/a/51861712
tagged with: python-3.x
type: Question
has comment: http://stackoverflow.com/comment/90675493
has answer: http://stackoverflow.com/a/51861712
tagged with: python
score: 18
has title: Python list function or list comprehension
has answer: http://stackoverflow.com/a/51862008
has body: Can anybody please explain to me the difference between these two ways of creating a list. Are they the same thing ? If not which one should I use ? squares1 = [x**2 for x in range(1, 11)] squares2 = list(x**2 for x in range(1, 11))
has comment: http://stackoverflow.com/comment/90675437
has comment: http://stackoverflow.com/comment/90675463
has answer: http://stackoverflow.com/a/51861670
has comment: http://stackoverflow.com/comment/90675396

http://stackoverflow.com/q/51842918
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/51843586
possible better answer: http://stackoverflow.com/a/51843447
has title: Tkinter - pass multiple scale value to a label
type: AnsweredQuestion
tagged with: user-interface
has answer: http://stackoverflow.com/a/51843447
accepted answer: http://stackoverflow.com/a/51843586
has body: I want to display the selected scale value on the label. Currently I have to create separate labels to print the values. Is there a clever way to pass all scale values I select to the same label to print? l1 = tk.Label(window, bg='yellow', width=50, text='empty') l1.pack() l2 = tk.Label(window, bg='yellow', width=50, text='empty') l2.pack() def print_selection1(v): l1.config(text='You have selected ' + v +' trucks') def print_selection2(v): l2.config(text='Truck Capacity is: ' + v + ' kg') s1 = tk.Scale(window, label='Number of 7.5t truck', from_=0, to=30, orient=tk.HORIZONTAL, length=400, showvalue=0, tickinterval=5, resolution=1, command=print_selection1) s1.pack() s2 = tk.Scale(window, label='Number of 12t truck', from_=0, to=30, orient=tk.HORIZONTAL, length=400, showvalue=0, tickinterval=5, resolution=1, command=print_selection2) s2.pack()
type: Question
tagged with: python
tagged with: tkinter

http://stackoverflow.com/a/51984088
has comment: http://stackoverflow.com/comment/90947435
has body: even if the solution pointed by @TonyMountax seems valid and made me discover something that i didn't know about SqlAlchemy, In the end i opted for something different. I figured out that the connection established by SqlAlchemy was durable since it was created from a pool of connection everytime, this somehow was causing the data to be stale. i added a NullPool to my code: from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker, scoped_session from sqlalchemy.pool import NullPool engine = create_engine(DB_URI, isolation_level="READ COMMITTED", poolclass=NullPool) Session = scoped_session(sessionmaker(bind=engine)) session = Session() and then i'm calling a session close for every query that i make: session.query("some query..") session.close() this will cause SqlAlchemy to create a new connection every time and get fresh data from the db. Hope that this is the correct way to use it and that might be useful to someone else.
accepted answer of: http://stackoverflow.com/q/51875333
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51875333
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/91018577

http://stackoverflow.com/a/51844737
type: Answer
has body: Question is unclear, but I assume all you want is to check that if the filename contains a date. So, I'll write a regex for that, forgive me if it's over-engineered. import re pattern = r'(\d{1,12})(\d{1,31})(\d{0001,2018})' array = ['not_supposed_to_match','labels08132018', 'clothli08132018','jonathan08122018','exam08092018'] matched_files = [] for line in array: match = re.search(pattern, line) if match != None: matched_files.append(line) print(matched_files) Hope this answers your question.
answers question: http://stackoverflow.com/q/51844239
score: 0

http://stackoverflow.com/q/51944727
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51944878
possible better answer: http://stackoverflow.com/a/51945732
upvote count: 1
type: Question
score: 1
has comment: http://stackoverflow.com/comment/90838940
answer count: 2
has answer: http://stackoverflow.com/a/51945732
has body: I am trying to generate a summarized dataframe (using groupby). While I have done basic aggregations before, this one has more complex aggregation conditions. I have tried the web help but unable to work my waythrough. sample data : df = pd.DataFrame({'indi_id': [1,1,1,2,2], 'co_id': [1,1,2,2,3], 'relationship': ['shareholder', 'signatory', 'shareholder', 'shareholder', 'director'], 'co_type': ['SP', 'SP', 'PT', 'PT', 'SP'], 'co_nw': [10,10,100,100,2], 'sh_perc': [100, np.nan, 3, 4, np.nan]}) What I need to do is generate a summary dataframe below (groupby: indi_id): indi_id: 'groupby field' num_cos_assoc: 'nunique'(co_ID) - no problems here num_companies_assoc_sh: nunique(co_ID) where relationship = 'shareholder' num_SP_companies_assoc: nunique(co_ID) where co_type = 'SP' total_nw_co_sh: sum(co_nw*sh_prec) where relationship = 'shareholder' sample Outcome below: Indi_ID num_cos_assoc num_companies_assoc_sh num_SP_companies_assoc total_nw_co_sh 1 2 2 1 1300 2 2 1 0 400
downvote count: 0
has title: groupby with conditions pandas
favorite count: 0
accepted answer: http://stackoverflow.com/a/51944878
tagged with: pandas-groupby
tagged with: pandas

http://stackoverflow.com/a/51850137
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51833444
answers question: http://stackoverflow.com/q/51833444
type: Answer
has body: You need to set the right type np.float32to the transitionMatrix to get rid of the error kf.transitionMatrix = np.array([[1, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0], [0, 0, 0, 1]],np.float32) kf.measurementMatrix = np.array([[1,0,0,0], [0,1,0,0]],np.float32) #cv2.setIdentity(kf.measurementMatrix) and for some reason I had to set the measurementMatrix in a similar way, even though I your variant should be OK.
has comment: http://stackoverflow.com/comment/129093167
score: 0

http://stackoverflow.com/comment/90794449
comment on: http://stackoverflow.com/q/51922283
score: 0
has text: I've tried all previous solution before open the post here. And even the solution in the post - Sort a List of string by Numeric Order that is exactly as mine. As you can see. It didn't work
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52021495
type: Answer
answers question: http://stackoverflow.com/q/51948425
downvote count: 1
upvote count: 0
score: -1
has body: in your config file. change command= to bash -c followed by the full path and file to execute this should do the trick

http://stackoverflow.com/a/51953935
upvote count: 18
accepted answer of: http://stackoverflow.com/q/51953869
type: AcceptedAnswer
score: 18
has body: Operations between series require non-duplicated indices, otherwise Pandas doesn't know how to align values in calculations. This isn't the case with your data currently. If you are certain that your series are aligned by position, you can call reset_index on each dataframe: wind = pd.DataFrame({'DATE (MM/DD/YYYY)': ['2018-01-01', '2018-02-01', '2018-03-01']}) temp = pd.DataFrame({'stamp': ['1', '2', '3']}, index=[0, 1, 1]) # ATTEMPT 1: FAIL wind['timestamp'] = wind['DATE (MM/DD/YYYY)'] + ' ' + temp['stamp'] # ValueError: cannot reindex from a duplicate axis # ATTEMPT 2: SUCCESS wind = wind.reset_index(drop=True) temp = temp.reset_index(drop=True) wind['timestamp'] = wind['DATE (MM/DD/YYYY)'] + ' ' + temp['stamp'] print(wind) DATE (MM/DD/YYYY) timestamp 0 2018-01-01 2018-01-01 1 1 2018-02-01 2018-02-01 2 2 2018-03-01 2018-03-01 3
downvote count: 0
answers question: http://stackoverflow.com/q/51953869
has comment: http://stackoverflow.com/comment/90912720
type: Answer

http://stackoverflow.com/q/51867550
tagged with: python
has title: PyMySQL - Escaping identifiers
upvote count: 3
answer count: 2
has body: I'm using PyMySQL, and as I write queries I need to escape certain identifiers that are user-provided (table names, etc.). For example, here's a bad example showing what I mean: sql = "SELECT * FROM {}".format(table_name) cursor.execute(sql) In this case table_name is user-provided, so the above code is clearly vulnerable to a SQL injection attack. I first tried to do something like this: sql = "SELECT * FROM %s" cursor.execute(sql, (table_name,)) It seems that the above code does not work when escaping identifiers, it only works with values. This isn't really surprising because I've seen similar behavior in other MySQL libraries in other languages. I've used other libraries, such as mysql in Node.js, that have a function for escaping identifiers. I can't see anything in the PyMySQL documentation that indicates similar functionality. I found this StackOverflow question asking a similar question, but the answer was something along the lines of "You shouldn't need to do that." Well I do need to do that! ;) What are my options for escaping identifiers when using MySQL in Python? Thanks!
tagged with: mysql
has answer: http://stackoverflow.com/a/64412951
linked to: http://stackoverflow.com/q/27618354
type: UnansweredQuestion
score: 3
downvote count: 0
tagged with: pymysql
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/90687437
tagged with: sql-injection
has answer: http://stackoverflow.com/a/51868068

http://stackoverflow.com/q/51841615
has body: I am currently working on creating a database where the tables are made from specific columns from an excel workbook. The algorithm iterates in a directory and saves the worksheet as a pandas dataframe and from there I select the columns: df1 = pd.read_excel(file, 'sheet1') From there I select the data I need with def create_list(df1): i = 0 list1 = [] while isinstance(df1['foo-bar'][i], int): list1.append(df1['foo-bar'][i]) i += 1 return list1 The problem I'm facing is that sometimes the name of the column isn't 'foo-bar' but 'foo.bar'. Is there a way to select this column just if it contains 'foo' for example? Or an 'or' operator, that selects 'foo-bar' or 'foo.bar'? I know that there should be a way with LIKE from sql, but I would prefer to do it with pandas.
has comment: http://stackoverflow.com/comment/90645751
has comment: http://stackoverflow.com/comment/90636558
tagged with: python
tagged with: excel
has answer: http://stackoverflow.com/a/51842113
has answer: http://stackoverflow.com/a/51842059
type: Question
has comment: http://stackoverflow.com/comment/90636975
has comment: http://stackoverflow.com/comment/90645688
has title: how to find a pandas dataframe index with a similar keyword?
has comment: http://stackoverflow.com/comment/90646144
score: 0
answer count: 2
tagged with: pandas
type: UnansweredQuestion

http://stackoverflow.com/comment/111858852
comment on: http://stackoverflow.com/q/51828671
score: 0
has text: I need your email. We used to room together in Summerville
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90839525
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51944891
type: Comment
has text: Thanks, I'll read up on comprehensions more because that seems to be the best method for these type of problems.

http://stackoverflow.com/q/51830687
score: 3
has comment: http://stackoverflow.com/comment/90615911
answer count: 3
has comment: http://stackoverflow.com/comment/90616519
downvote count: 0
tagged with: django-rest-framework
linked to: http://stackoverflow.com/q/41105294
has title: How to take slice of string when serializing a field (Django/DRF)
favorite count: 0
has answer: http://stackoverflow.com/a/51830848
accepted answer: http://stackoverflow.com/a/51830848
tagged with: python
has answer: http://stackoverflow.com/a/51831098
has answer: http://stackoverflow.com/a/64806045
type: AnsweredQuestion
has body: First time asking here, I'll try to sound smart! So, I've got a model called 'Article', and I've populated its 'text' field with 1000+ chars of text. How can I make it so I only send the first 200 chars of the 'text' field when I send an 'Article' serialized object through an endpoint? views.py class ArticleScrape(generics.ListAPIView): queryset = Article.objects.all() serializer_class = ArticleSerializer def list(self,request): serializer = ArticleSerializer(queryset, many=True) return Response(serializer.data) serializers.py class ArticleSerializer(serializers.ModelSerializer): authors = EachAuthorSerializer(many=True,read_only=True) tags = EachTagSerializer(many=True,read_only=True) text = serializers.CharField(max_length=200) class Meta: model = Article exclude=('id',) Do I need to perform this operation in the queryset? in the serializer? Do I annotate a field? I've tried many of this with no succes. Thanks in advance for the help!
upvote count: 3
possible better answer: http://stackoverflow.com/a/51831098
tagged with: django
linked to: http://stackoverflow.com/q/31920853
type: Question

http://stackoverflow.com/comment/90708673
type: QuestionComment
comment on: http://stackoverflow.com/q/51878628
has text: I also don't see any whitespace in `''.join(result)`
score: 0
type: Comment

http://stackoverflow.com/comment/90676008
score: 1
comment on: http://stackoverflow.com/a/51845989
type: AnswerComment
has text: yeah～I just accept it.Thanks a lot.This is the first time I post question on stackoverflow and I feel so good
type: Comment

http://stackoverflow.com/q/51846670
has title: Export the contents of a dictionary to a m x n matrix
favorite count: 0
has answer: http://stackoverflow.com/a/51846719
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51848007
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/90646628
downvote count: 0
score: 1
has body: I have a dictionary where the number of objects can change. The type of each object will always be a 3 element ND array. For example: exampleDict = {u'A': array([ 1, 2, 3]), u'B': array([ 2, 3, 4]), u'C': array([ 3, 4, 5]), u'D': array([ 4, 5, 6])} Using a for loop, I would like to be able to create a matrix that looks like this: exampleMatrix = array([[ 1, 2, 3], [ 2, 3, 4], [ 3, 4, 5], [ 4, 5, 6]]) I'm able to create a 0 matrix of the correct dimensions using: exampleMatrix = np.zeros((len(exampleDict), 3)) But, I don't know how to fill that matrix appropriately. I was trying to use a for loop. I'm open to other suggestions. Thanks!
type: Question
tagged with: numpy
tagged with: python-2.7
answer count: 2
upvote count: 1
tagged with: matrix

http://stackoverflow.com/a/51872949
answers question: http://stackoverflow.com/q/51869713
downvote count: 0
has body: I assume that your data are biological time-series like EEG, is this correct? If so, you can use the MNE library. You have to install it first. Since it is not a standard library, take a look here. Then, you can use the read_raw_edf() method. For example: import mne file = "my_path\\my_file.edf" data = mne.io.read_raw_edf(file) raw_data = data.get_data() # you can get the metadata included in the file and a list of all channels: info = data.info channels = data.ch_names See documentation in the links above for other properties of the data object
has comment: http://stackoverflow.com/comment/130255787
has comment: http://stackoverflow.com/comment/127318054
type: AcceptedAnswer
score: 27
has comment: http://stackoverflow.com/comment/90763140
has comment: http://stackoverflow.com/comment/90728966
type: Answer
accepted answer of: http://stackoverflow.com/q/51869713
upvote count: 27

http://stackoverflow.com/q/51824736
tagged with: dataframe
has answer: http://stackoverflow.com/a/51825365
type: Question
tagged with: apache-spark-sql
possible better answer: http://stackoverflow.com/a/62506565
tagged with: pyspark
downvote count: 0
answer count: 6
has answer: http://stackoverflow.com/a/51838926
has comment: http://stackoverflow.com/comment/90604421
tagged with: apache-spark
has answer: http://stackoverflow.com/a/63638142
has body: I'm new to PySpark, So apoloigies if this is a little simple, I have found other questions that compare dataframes but not one that is like this, therefore I do not consider it to be a duplicate. I'm trying to compare two dateframes with similar structure. The 'name' will be unique, yet the counts could be different. So if the count is different I would like it to produce a dataframe or a python dictionary. just like below. Any ideas on how I would achieved something like this? DF1 +-------+---------+ |name | count_1 | +-------+---------+ | Alice| 1500 | | Bob| 1000 | |Charlie| 150 | | Dexter| 100 | +-------+---------+ DF2 +-------+---------+ |name | count_2 | +-------+---------+ | Alice| 1500 | | Bob| 200 | |Charlie| 150 | | Dexter| 10 | +-------+---------+ To produce the outcome: Mismatch +-------+-------------+--------------+ |name | df1_count | df2_count | +-------+-------------+--------------+ | Bob| 1000 | 200 | | Dexter| 100 | 10 | +-------+-------------+--------------+ Match +-------+-------------+--------------+ |name | df1_count | df2_count | +-------+-------------+--------------+ | Alice| 1500 | 1500 | |Charlie| 150 | 150 | +-------+-------------+--------------+
accepted answer: http://stackoverflow.com/a/51825365
favorite count: 0
score: 9
has answer: http://stackoverflow.com/a/51840423
tagged with: python
has title: PySpark - Compare DataFrames
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/73884147
upvote count: 9
has answer: http://stackoverflow.com/a/62506565

http://stackoverflow.com/comment/90831703
type: QuestionComment
comment on: http://stackoverflow.com/q/51927948
score: 1
has text: This question may also be useful: Choosing the correct upper and lower HSV boundaries for color detection with`cv::inRange` (OpenCV) https://stackoverflow.com/questions/10948589/choosing-the-correct-upper-and-lower-hsv-boundaries-for-color-detection-withcv/48367205#48367205
type: Comment

http://stackoverflow.com/comment/90880516
type: Comment
type: AnswerComment
has text: @J.David - Check email.
score: 0
comment on: http://stackoverflow.com/a/51894772

http://stackoverflow.com/q/51904378
has comment: http://stackoverflow.com/comment/90863366
has comment: http://stackoverflow.com/comment/98541501
favorite count: 0
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/66921231
has comment: http://stackoverflow.com/comment/90824592
has comment: http://stackoverflow.com/comment/90902537
has comment: http://stackoverflow.com/comment/101073542
type: Question
has comment: http://stackoverflow.com/comment/90933512
score: 5
tagged with: visual-studio-code
upvote count: 5
has comment: http://stackoverflow.com/comment/90864998
answer count: 1
downvote count: 0
has title: VSCode-Python Outline view for Python in VSCode on Linux not working
has body: Running VSCode on Ubuntu 16.04.3 VSCode Version: 1.26.1 Microsoft Python Extension: 2018.7.1 When I view a python file the outline view shows No symbols found in document. Same file in VSCode on Windows shows all the symbols Any help?

http://stackoverflow.com/q/51854509
score: 2
has answer: http://stackoverflow.com/a/51854706
has title: Reset Password in django?
favorite count: 0
tagged with: python-3.x
type: Question
answer count: 2
has body: I am following a blog to reset the password in django. It states to add : EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' # During development only in settings.py file. But I want to deploy my web application in production. So what steps should I take care about? Will this tutorial is safe for the production too? The blog link is given below: https://simpleisbetterthancomplex.com/tutorial/2016/09/19/how-to-create-password-reset-view.html
tagged with: django
tagged with: python
upvote count: 3
downvote count: 1
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51855268

http://stackoverflow.com/a/51803342
answers question: http://stackoverflow.com/q/51800678
downvote count: 0
has comment: http://stackoverflow.com/comment/90567287
accepted answer of: http://stackoverflow.com/q/51800678
type: Answer
score: 3
has body: after delete you need commit conn = cx_Oracle.connect(...) cur = db.cursor() sql = "DELETE FROM customers where IMAGE_ID like 'SCH%'" cur.execute(sql) conn.commit() cur.close() conn.close()
upvote count: 3
type: AcceptedAnswer

http://stackoverflow.com/comment/90617469
has text: Right, so I want the order to be maintained from the original list given. In other words, the expected output should be ['7', '8'] instead... However, I need to to be applied to strings as well (maintain order of list) and not "sorted" numerically.
type: Comment
comment on: http://stackoverflow.com/q/51831653
score: 0
type: QuestionComment

http://stackoverflow.com/comment/90601237
type: Comment
score: 0
type: AnswerComment
has text: My final goal is to multiply multivariate finite power series. at some point I have to increase the degree of the serie for specific variable. Although doing so manually is possible it will be inefficient. It would be ideal to construct the Convolve function to take `A` and `B` and gives the result.
comment on: http://stackoverflow.com/a/51822929

http://stackoverflow.com/q/51902481
upvote count: 1
has answer: http://stackoverflow.com/a/51902527
answer count: 1
has title: pandas shift inside apply function
accepted answer: http://stackoverflow.com/a/51902527
downvote count: 0
tagged with: pandas
type: AnsweredQuestion
tagged with: python
score: 1
favorite count: 0
type: Question
has body: I am trying to fill some of the NaN values with values from another column and the row above. For example, I get a dataframe that looks like this: Distance Down firstDownYards secondDownYards 1 10.0 1.0 NaN NaN 2 8.0 2.0 2.0 NaN 3 8.0 3.0 2.0 0.0 4 19.0 3.0 -9.0 -11.0 5 19.0 4.0 -9.0 -11.0 6 10.0 1.0 NaN NaN 7 5.0 2.0 5.0 NaN 8 5.0 3.0 5.0 0.0 9 10.0 1.0 NaN NaN 10 9.0 2.0 1.0 NaN 11 11.0 3.0 -1.0 -2.0 12 12.0 4.0 -2.0 -3.0 13 10.0 1.0 NaN NaN 14 5.0 2.0 5.0 NaN 15 10.0 1.0 NaN NaN 16 8.0 2.0 2.0 NaN 17 8.0 3.0 2.0 0.0 18 10.0 1.0 NaN NaN 19 10.0 2.0 0.0 NaN 20 6.0 3.0 4.0 4.0 In the secondDownYards, I would like to fill the NaN where down is lower than 2 with the opposite of the next row of column firstDownYards. Here is an example of what the column would look like: Distance Down firstDownYards secondDownYards 1 10.0 1.0 NaN -2 # Change here 2 8.0 2.0 2.0 NaN 3 8.0 3.0 2.0 0.0 4 19.0 3.0 -9.0 -11.0 5 19.0 4.0 -9.0 -11.0 6 10.0 1.0 NaN -5 # Change here 7 5.0 2.0 5.0 NaN 8 5.0 3.0 5.0 0.0 9 10.0 1.0 NaN -1 # Change here 10 9.0 2.0 1.0 NaN 11 11.0 3.0 -1.0 -2.0 12 12.0 4.0 -2.0 -3.0 13 10.0 1.0 NaN -5 # Change here 14 5.0 2.0 5.0 NaN 15 10.0 1.0 NaN -2 # Change here 16 8.0 2.0 2.0 NaN 17 8.0 3.0 2.0 0.0 18 10.0 1.0 NaN 0 # Change here 19 10.0 2.0 0.0 NaN 20 6.0 3.0 4.0 4.0 I have tried creating a function that looks like this, but when I try and print x.shift(), it simply prints the same thing as x. I would then use df.apply(getLastCol,args=(....),axis=1). downNb is the condition, in this example being 2. currentCol and lastCol are the names of the current column and the previous column. def getLastCol(x,downNb,currentCol,lastCol): if x['Down'] &lt; downNb: print(x.shift()) value = x.shift(-1)[lastCol] else: value = x[currentCol] return value

http://stackoverflow.com/comment/90823198
type: QuestionComment
comment on: http://stackoverflow.com/q/51936526
has text: You may better aks this kind of questions at https://codereview.stackexchange.com/
score: 0
type: Comment

http://stackoverflow.com/q/51885802
type: Question
linked to: http://stackoverflow.com/q/36629963
has answer: http://stackoverflow.com/a/51887092
answer count: 2
has comment: http://stackoverflow.com/comment/90723386
has comment: http://stackoverflow.com/comment/90723702
downvote count: 0
has comment: http://stackoverflow.com/comment/90723590
has answer: http://stackoverflow.com/a/72752386
favorite count: 0
has comment: http://stackoverflow.com/comment/90723542
tagged with: postgresql
has comment: http://stackoverflow.com/comment/90723487
type: UnansweredQuestion
tagged with: windows
tagged with: python
tagged with: psycopg2
has comment: http://stackoverflow.com/comment/90723582
has body: I'm trying to do a connection to PostgreSQL 9.6 from Python 3.6 with Pycharm 2018.1.4 on Windows 10 with the connector psycopg2 in the version 2.7.5. I have the following code: import os, psycopg2, psycopg2.extras conexion = psycopg2.connect("dbname=Seguritec_BD user=SU host=localhost password=root port=5432") psycopg2.OperationalError cursor = conexion.cursor() cursor.execute("Select * from Ejecutivos") filas = cursor.fetchall() It throws the next error: Traceback (most recent call last): File "D:/Documentos/Proyectos Pycharm/Graficos Drones/Login.py", line 3, in &lt;module&gt; conexion = psycopg2.connect("dbname=Seguritec_BD user=SU host=localhost password=root port=5432") File "D:\Documentos\Proyectos Python 3.5\lib\site-packages\psycopg2\__init__.py", line 130, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError It's an empty OperationalError, there's no description of the error. Can you help me to understand and fix this error, please?
has comment: http://stackoverflow.com/comment/90723413
has comment: http://stackoverflow.com/comment/90724062
score: 1
has comment: http://stackoverflow.com/comment/90723901
has comment: http://stackoverflow.com/comment/90724018
has title: Connection from python to postgresql
upvote count: 1

http://stackoverflow.com/comment/90755460
comment on: http://stackoverflow.com/q/51902156
has text: Please include an example of your data. (Say, for the included graph.)
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90674049
has text: @jpp Since for my case, I need only those tokens which are present in second list and with no variants, I can filter out all tokens that are not in range of min_len and max_len. So both of the solution mentioned by you as well as by tobias_k works great for me.
type: Comment
score: 1
comment on: http://stackoverflow.com/a/51857859
type: AnswerComment

http://stackoverflow.com/comment/90818585
score: 1
comment on: http://stackoverflow.com/a/51928911
type: AnswerComment
type: Comment
has text: thank you so much again for all the trouble!! i appreciate you going through it in iteractions, it made me think more.

http://stackoverflow.com/q/51889591
type: Question
tagged with: google-drive-shared-drive
score: 0
answer count: 1
has body: I was trying to access google team drive with the service account 1) I went to team drive and add as member service account email, and granted him full access 2) I'm not sure which permission have to be granted (inside the console ) to this service account to be able to connect to google team drive This is the coode which I'm using def initialize_analyticsreporting(): print("Wait for Initialising") credentials = ServiceAccountCredentials.from_json_keyfile_name( "key.json", "https://www.googleapis.com/auth/drive") # Build the service object. analytics = build('drive', 'v3', credentials=credentials) print(analytics) print("Service for Google Drive - Initialised") return analytics def main(analytics): page_token = '1' while True: response = analytics.files().list(q="mimeType='image/jpeg'", spaces='drive', fields='nextPageToken, files(id, name)', pageToken=page_token).execute() for file in response.get('files', []): # Process change print 'Found file: %s (%s)' % (file.get('name'), file.get('id')) page_token = response.get('nextPageToken', None) if page_token is None: print("Token not initilied") break return response if __name__ == '__main__': analytics = initialize_analyticsreporting() main(analytics) Authentication part is working fine. It failed as I'm not sure what is page_token. WHAT I NEED: I need to connect to the Team Drive with this service account and get the number of files for each category, like how many videos, pictures and so on, if it possible
tagged with: google-drive-api
tagged with: python
type: AnsweredQuestion
tagged with: google-drive-realtime-api
tagged with: service-accounts
has title: PYTHON Connect to Google Team Drive
has answer: http://stackoverflow.com/a/51891064
accepted answer: http://stackoverflow.com/a/51891064

http://stackoverflow.com/q/51954482
has comment: http://stackoverflow.com/comment/90859881
tagged with: python
has body: I'm pretty lost. Not going to lie. I'm trying to figure out how to parse JSON data from the college scorecard API into an HTML file. I used Python to store the JSON data in a dictionary, but other than that, I'm pretty dang lost. How would you write an example sending this data to an HTML file? def main(): url = 'https://api.data.gov/ed/collegescorecard/v1/schools.json' payload = { 'api_key': "api_key_string", '_fields': ','.join([ 'school.name', 'school.school_url', 'school.city', 'school.state', 'school.zip', '2015.student.size', ]), 'school.operating': '1', '2015.academics.program_available.assoc_or_bachelors': 'true', '2015.student.size__range': '1..', 'school.degrees_awarded.predominant__range': '1..3', 'school.degrees_awarded.highest__range': '2..4', 'id': '240444', } data = requests.get(url, params=payload).json() for result in data['results']: print result main() Output: {u'school.city': u'Madison', u'school.school_url': u'www.wisc.edu', u 'school.zip': u'53706-1380', u'2015.student.size': 29579, u'school.st ate': u'WI', u'school.name': u'University of Wisconsin-Madison'} Edit: For clarification, I need to insert the return data to an HTML file that formats and removes data styling and places it onto a table. Edit II: Json2html edit data = requests.get(url, params=payload).json() for result in data['results']: print result data_processed = json.loads(data) formatted_table = json2html.convert(json = data_processed) index= open("index.html","w") index.write(formatted_table) index.close() Edit: Json2html output: Output image here
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90859608
score: 0
accepted answer: http://stackoverflow.com/a/51954737
type: Question
tagged with: api
answer count: 1
has comment: http://stackoverflow.com/comment/90860250
tagged with: http://stackoverflow.com/tag/html
has answer: http://stackoverflow.com/a/51954737
has title: Python JSON data into HTML table

http://stackoverflow.com/a/51940625
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51940581
has body: class Klass: def __init__(self, **kwargs): self.func(**kwargs) def func(self, variable=True, **kwargs): print(variable) if __name__ == '__main__': Klass(variable=False) This should work. You are setting a default value 'True' and passing a parameter 'False' to one keyword 'variable'.

http://stackoverflow.com/q/51894849
has comment: http://stackoverflow.com/comment/90741067
has body: So, the basic idea is to make get request to certain list URLs and parse text from those page sources by removing HTML tags and scripts using beautifulsoup. python version 2.7 The problem, at every request, parser function keep adding memory at every request. size increasing gradually. def get_text_from_page_source(page_source): soup = BeautifulSoup(open(page_source),'html.parser') # soup = BeautifulSoup(page_source,"lxml") # kill all script and style elements for script in soup(["script", "style"]): script.decompose() # rip it out # get text text = soup.get_text() # break into lines and remove leading and trailing space on each lines = (line.strip() for line in text.splitlines()) # break multi-headlines into a line each chunks = (phrase.strip() for line in lines for phrase in line.split(" ")) # drop blank lines text = '\n'.join(chunk for chunk in chunks if chunk) # print text return text even at local text file for parsing memory leaks. for example: #request 1 response = requests.get(url,timeout=timeout) parsed_string_from_html_source = get_text_from_page_source(response.content) #100 MB #request 2 response = requests.get(url,timeout=timeout) parsed_string_from_html_source = get_text_from_page_source(response.content) #150 MB #request 3 response = requests.get(url,timeout=timeout) parsed_string_from_html_source = get_text_from_page_source(response.content) #300 MB
type: UnansweredQuestion
tagged with: python
upvote count: 7
linked to: http://stackoverflow.com/q/11284643
tagged with: python-requests
has comment: http://stackoverflow.com/comment/90740752
score: 7
has comment: http://stackoverflow.com/comment/90740925
type: Question
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/90741006
has answer: http://stackoverflow.com/a/51895523
tagged with: memory-leaks
has title: Memory Leak while parsing html page source with BeautifulSoup & Requests
has answer: http://stackoverflow.com/a/51895496
favorite count: 0
tagged with: beautifulsoup

http://stackoverflow.com/comment/90847496
has text: What is `variable` before? Can we make it `None` or `False` or something like that? `variable = myDict and myDict.get('thisKey')` should set it to `False` if undefined, `None` if key not in dict, and the value that you want otherwise.
type: Comment
comment on: http://stackoverflow.com/q/51948860
score: 0
type: QuestionComment

heroku
tags question: http://stackoverflow.com/q/51818387
tags question: http://stackoverflow.com/q/51804202
tags question: http://stackoverflow.com/q/51954574
tags question: http://stackoverflow.com/q/51800774
tags question: http://stackoverflow.com/q/51869524
tags question: http://stackoverflow.com/q/51948753
type: Tag
tags question: http://stackoverflow.com/q/51902483
tags question: http://stackoverflow.com/q/51905791
tags question: http://stackoverflow.com/q/51881911
tag name: heroku

http://stackoverflow.com/comment/90718402
score: 0
type: AnswerComment
has text: I was trying to code it while I was at class just for mock a friend hahaha, but I liked how python works (Even not understanding at all sometimes), and I will put some effort in it.
type: Comment
comment on: http://stackoverflow.com/a/51883257

http://stackoverflow.com/comment/90590680
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/51817573
has text: For the *fastest* way, you need to tell us more about `my_function`. Your calculation may be vectorisable.

http://stackoverflow.com/comment/90770759
has text: Thanks it works great.
type: Comment
comment on: http://stackoverflow.com/a/51910297
score: 0
type: AnswerComment

http://stackoverflow.com/q/51876482
has title: How to specify os-specific wheel files in the Pipfile
tagged with: python
tagged with: pytorch
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/58292468
tagged with: pip
tagged with: pipfile
type: Question
tagged with: pipenv
score: 7
has body: I'm trying to use the pipenv and pytorch. To install pytorch in windows, I have to write following codes into the Pipfile: [packages] torch = {file = "http://download.pytorch.org/whl/cpu/torch-0.4.1-cp37-cp37m-win_amd64.whl"} However, the wheel file is different for the linux. [packages] torch = {file = "http://download.pytorch.org/whl/cpu/torch-0.4.1.post2-cp37-cp37m-linux_x86_64.whl "} How to specify both of them in Pipfile?
upvote count: 7
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/90658234
has text: Your second and third conditionals are unreachable: an input of 'update' or 'delete' matches the first conditional (`!= 'all'`), and gets interpreted as a site to look up.
type: Comment
comment on: http://stackoverflow.com/q/51852682
type: QuestionComment
score: 0

http://stackoverflow.com/a/57631341
has body: You can downgrade using the --upgrade flag it works both ways e.g pip install --upgrade numpy==1.10.1
has comment: http://stackoverflow.com/comment/138662833
score: 31
answers question: http://stackoverflow.com/q/51912284
type: Answer
upvote count: 32
has comment: http://stackoverflow.com/comment/139841821
downvote count: 1

http://stackoverflow.com/comment/90644334
comment on: http://stackoverflow.com/q/51832038
score: 0
type: Comment
type: QuestionComment
has text: Ok why am I getting downvoted for this question? I genuinely couldn't figure it out and I find that a question like mine is helpful.

http://stackoverflow.com/comment/90788772
score: 0
has text: However, I still meet this problem if I define a class in a submodule and inherit from it in the same submodule. There should be a way around this.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51881692

http://stackoverflow.com/comment/90699345
score: 0
comment on: http://stackoverflow.com/q/51871101
type: Comment
type: QuestionComment
has text: @user5963022, can you please edit the code in your comment in more readable format, please use the code option provided in the comment section.

http://stackoverflow.com/comment/90607910
has text: If this is a python question, why is there a javascript library on the tags?
comment on: http://stackoverflow.com/q/51826426
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90605903
type: Comment
has text: Things aren't so simple. First you'd have to define the `gsl_vector` type (using `ctypes.Structure`) and all the custom inner types (e.g. `gsl_block`), then create one (via e.g.: `gsl_vector_alloc`). And for all functions involved, you'll have to also define their `argtypes`. I don't have *libgsl* installed, and I'd avoid posting code without running it.
comment on: http://stackoverflow.com/q/51824794
score: 0
type: QuestionComment

http://stackoverflow.com/comment/90644227
type: QuestionComment
comment on: http://stackoverflow.com/q/51845385
type: Comment
has text: I didn't give a definition of the function. I just meant to indicate that the definition of such a function is what I'm looking for. As to what I've tried: repr(eval()) but that goes in the wrong direction. The dictionary may be the answer: I need to think about how it would work here.
score: 0

http://stackoverflow.com/q/51831616
downvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90619941
score: 1
type: Question
has body: I would like to solve the following problem using pandas. I would like to delete rows that have the same id and y value and have a different z column. Here is a simple example: id y z 0 a 0 3 1 a 0 1 2 a 0 3 3 b 3 4 4 b 0 2 5 b 0 2 I would like to obtain the following result id y z 0 b 3 4 1 b 0 2 2 b 0 2 Someone has an idea ?
upvote count: 1
answer count: 1
favorite count: 0
tagged with: python-2.7
tagged with: pandas
tagged with: python
has title: pandas dataframe delete duplicates on 2 columns if the third is different
has answer: http://stackoverflow.com/a/51831991

http://stackoverflow.com/comment/90656863
comment on: http://stackoverflow.com/q/51852040
has text: Strings are immutable, loop variables don't work like that at all, and you really need a basic tutorial.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51840150
type: UnansweredQuestion
tagged with: pyqt5
has answer: http://stackoverflow.com/a/51840855
type: Question
tagged with: qlabel
has title: -1073740791 (0xC0000409) Error when setting Pixmap on QLabel
tagged with: opencv3.0
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/90633562
favorite count: 0
tagged with: qpixmap
has body: As sadly as Python/PyQt does not give give specific error messages about things like these, I am only getting this error code when running my code. Process finished with exit code -1073740791 (0xC0000409) I am using PyQt and OpenCV to build an app that displays a webcam feed. import sys import cv2 from PyQt5.QtCore import QTimer from PyQt5.QtGui import QImage, QPixmap from PyQt5.QtWidgets import QApplication, QDialog from PyQt5.uic import loadUi from qtpy import QtGui class MainUI(QDialog): read=0; def __init__(self): super(MainUI,self).__init__() loadUi('MainUI.ui',self) self.image=None self.btnPlay.clicked.connect(self.start_webcam) self.btnStop.clicked.connect(self.stop_webcam) def start_webcam(self): self.capture=cv2.VideoCapture(0) self.capture.set(cv2.CAP_PROP_FRAME_HEIGHT,480) self.capture.set(cv2.CAP_PROP_FRAME_WIDTH,640) self.timer=QTimer(self) self.timer.timeout.connect(self.update_frame()) self.timer.start(5) def stop_webcam(self): self.timer.stop() def update_frame(self): #Take image from video feed ret,self.image = self.capture.read() self.image=cv2.flip(self.image,1) self.displayImage(self.image,1) def displayImage(self,img,window=1): qformat=QImage.Format_Indexed8 if(len(img.shape)==3): #[0]rows,[1]=cols,[2]=channels if img.shape[2]==4 : qformat=QImage.Format_RGBA8888 else: qformat=QImage.Format_RGB888 outImage=QImage(img,img.shape[1],img.shape[0],img.strides[0],qformat) #BGR&gt;&gt;RGB outImage = outImage.rgbSwapped() if window==1: #Problem occurs here V self.imgLabel.setPixmap(QPixmap.fromImage(outImage)) self.imgLabel.setScaledContents(True) if __name__=='__main__': app=QApplication(sys.argv) window = MainUI() window.setWindowTitle('PYQt Webcam feed') window.show() sys.exit(app.exec_()) I've tried using a different approach to this, and I've done my research but I really don't understand what I'm doing wrong. :( I am studying this code from: OpenCV Python GUI Development Tutorial 10: Display WebCam Video Feed on QLabel https://www.youtube.com/watch…
tagged with: python
has comment: http://stackoverflow.com/comment/90633654
score: 2
has comment: http://stackoverflow.com/comment/90633293
upvote count: 2

http://stackoverflow.com/q/51888221
favorite count: 0
tagged with: rules
type: UnansweredQuestion
tagged with: python
score: 3
tagged with: odoo
upvote count: 3
has answer: http://stackoverflow.com/a/53541084
type: Question
downvote count: 0
answer count: 1
has title: Getting an error as "Wrong python code defined for salary rule" odoo 11
has body: I am getting an error while calling a function from ODOO 11 Payslip, when calling a function that is defined in my code. The error says, "Wrong python code defined for salary rule Overtime Pay (OT)." The code I wrote is as below - class SalaryRuleFunctions(models.Model): _inherit = 'hr.payslip' @api.multi def get_overtime_salary(self): emp_id = self.employee_id dt_from = self.date_from dt_to = self.date_to emp_rec = self.env['x_attendance_summary'].search([('employee_id', '=', emp_id), ('start_date', '=', dt_from), ('end_date', '=', dt_to)])[0] g_sal = (self.contract_id.x_ctc_gross / emp_rec.max_days) o_day = emp_rec.x_overtime_days_normal result = g_sal * o_day return result The code inside the Salary Rule for Overtime Pay is as below - result = payslip.env['hr.payslip'].get_overtime_salary() I am not sure if the function is ever called. I tried putting in some messages also in my function to know if there is an error on function code. But, none of those messages show up, indicating that the function has never been called and the error is thrown from the salary rule itself. Is it that env variable is not available in Odoo 11? Or something else? Thanks in advance for all the help.

http://stackoverflow.com/comment/90642970
score: 0
has text: @DanielPryden I know I can pass command line arguments.. but for an executable???
comment on: http://stackoverflow.com/q/51843974
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/90699715
score: 0
comment on: http://stackoverflow.com/q/51874054
type: Comment
type: QuestionComment
has text: Can you also mention the line where it throws the error?

http://stackoverflow.com/a/51898725
score: 1
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51893854
accepted answer of: http://stackoverflow.com/q/51893854
type: Answer
upvote count: 1
has body: You can try to use twisted reverse proxy. Look here for https reverse proxy example: Python-Twisted: Reverse Proxy to HTTPS API: Could not connect You should change it to start on 443 port (use ssl) and add some logic. For example: class LocalResource(Resource): def render(self, request): return "Banned" class HTTPSReverseProxyResource(proxy.ReverseProxyResource, object): def proxyClientFactoryClass(self, *args, **kwargs): """ Make all connections using HTTPS. """ return TLSMemoryBIOFactory( ssl.optionsForClientTLS(self.host.decode("ascii")), True, super(HTTPSReverseProxyResource, self) .proxyClientFactoryClass(*args, **kwargs)) def getChild(self, path, request): if any([re.match(url, path) for url in banned_urls]): return LocalResource() else: child = super(HTTPSReverseProxyResource, self).getChild(path, request) return HTTPSReverseProxyResource(child.host, child.port, child.path, child.reactor) To use https (start proxy on 443 port), try this snippet (from here https://github.com/fmoo/twisted-connect-proxy): if __name__ == '__main__': import argparse ap = argparse.ArgumentParser() ap.add_argument('port', default=8080, nargs='?', type=int) ap.add_argument('--ssl-cert', type=str) ap.add_argument('--ssl-key', type=str) ns = ap.parse_args() if ns.ssl_cert: from twisted.internet import ssl with open(ns.ssl_cert, 'rb') as fp: ssl_cert = fp.read() if ns.ssl_key: from OpenSSL import crypto with open(ns.ssl_key, 'rb') as fp: ssl_key = fp.read() ftype = crypto.FILETYPE_PEM k = ssl.KeyPair.load(ssl_key, ftype) certificate = ssl.PrivateCertificate.load(ssl_cert, k, ftype) else: certificate = ssl.PrivateCertificate.loadPEM(ssl_cert) srv = HTTPSReverseProxyResource('your_main_server', 443 , '') reactor.listenSSL(ns.port, srv, certificate.options()) reactor.run()

http://stackoverflow.com/comment/90707182
has text: @IlyaLinetski If you pick arbitrary integers to categorise your data, is it logical that you will get meaningful correlations? I'm not aware of any way to get a result other than what you have
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51877292

http://stackoverflow.com/comment/90789229
score: 0
type: AnswerComment
has text: When I do df[df.index.duplicated(keep=False)] I do not see any duplicate indexes
comment on: http://stackoverflow.com/a/51919380
type: Comment

http://stackoverflow.com/comment/90713994
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51875030
has text: @toti08 It works, thanks ! :)

http://stackoverflow.com/comment/90702064
type: Comment
type: QuestionComment
has text: okay, one min, i am trying it
comment on: http://stackoverflow.com/q/51869402
score: 0

http://stackoverflow.com/comment/90769142
comment on: http://stackoverflow.com/q/51909512
type: Comment
type: QuestionComment
score: 1
has text: I'm pretty sure it'll work correctly if you change `26 - best_shift` to `best_shift`.

http://stackoverflow.com/a/51943819
accepted answer of: http://stackoverflow.com/q/51943574
type: AcceptedAnswer
downvote count: 0
has body: Everytime you call LeftPaddle(), you create a new instance of LeftPaddle. You want to create an instance once and then call methods on that very instance, like: ... self.boundaries() leftpaddle = LeftPaddle() leftpaddle.blit(self.background) running = True ... if event.key == pygame.K_w: if leftpaddle.pos == 0: continue else: leftpaddle.pos += 10 leftpaddle.blit(self.background) ...
type: Answer
answers question: http://stackoverflow.com/q/51943574
score: 1
upvote count: 1

http://stackoverflow.com/comment/90825990
score: 0
type: Comment
type: QuestionComment
has text: An IAM user can have: 1. inline policies, 2. managed policies and 3. IAM groups attached to it. You need to invoke a bunch of APIs to get all the info. Some of the APIs are: `get_user_policy`, `list_groups_for_user` (lists groups attached to user) and `list_attached_user_policies` (lists managed policies attached to user). From these, you need to invoke the respective APIs to get the permissions attached to them.
comment on: http://stackoverflow.com/q/51930111

http://stackoverflow.com/comment/90804730
type: Comment
has text: I want a convolve function, just like [NumPy convolve](https://docs.scipy.org/doc/numpy/reference/generated/numpy.convolve.html) which takes two ndarrays and spits out the result, sparing the user from panning and other tidius considerations.
comment on: http://stackoverflow.com/a/51822929
type: AnswerComment
score: 0

http://stackoverflow.com/q/51875932
tagged with: stdin
has comment: http://stackoverflow.com/comment/90704256
tagged with: python
type: AnsweredQuestion
has title: how to slice dates from a dataframe using standard input function?
downvote count: 1
type: Question
score: -1
has answer: http://stackoverflow.com/a/51876675
accepted answer: http://stackoverflow.com/a/51876675
has comment: http://stackoverflow.com/comment/90703274
has body: I saw the documentation in the Indexing and selecting data which involves hardcore scripting method to slice a range of data from a dataframe. import pandas as pd import matplotlib.pyplot as plt df = pd.read_csv('d1.csv') df['time']=pd.to_datetime(df['time'], unit='ns') df = df.drop('name', 1) df['Time'] = df['time'].dt.time df['date'] = df['time'].dt.date df['date'] = pd.to_datetime(df['date']) df = df.set_index(['date']) df= df.loc['2018-07-04':'2018-07-05'] But I need to select a range of data from standard input function, How it can be done: Rather than using df= df.loc['2018-07-04':'2018-07-05']say in the form at the console it will be asked to Enter the start date : and Enter the stop date : and by doing so I will get the data of the selected date ranges only. I actually tried it doing as: import pandas as pd import matplotlib.pyplot as plt df = pd.read_csv('d1.csv') df['time']=pd.to_datetime(df['time'], unit='ns') df = df.drop('name', 1) df['Time'] = df['time'].dt.time df['date'] = df['time'].dt.date df['date'] = pd.to_datetime(df['date']) df = df.set_index(['date']) Starting_Date = input(" Please Enter the Starting_Date : ") Ending_Date = input(" Please Enter the Ending_Date : ") data = df[Starting_Date:Ending_Date] But this doesn't work...kindly have a look upon it.
tagged with: pandas
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/90703696
favorite count: 0

http://stackoverflow.com/q/51949091
score: 0
has comment: http://stackoverflow.com/comment/90850076
has comment: http://stackoverflow.com/comment/90849939
answer count: 1
tagged with: javascript
tagged with: beautifulsoup
has body: I am trying to scrape some weather data from wunderground.com using beautifulsoup 4. I was able to find a tutorial on how to do this, however it is showing how to do it using an HTML source code. Wunderground.com used to be in HTML when the tutorial was made, however it is now in js. I was able to obtain the code and manipulate it to my specific data retrieval needs, but I am stuck on how to get it pulling javascript instead of HTML. Can anyone help with this? The code is below and I sourced it from kiengiv from SAS Business Analytics on youtube. from bs4 import BeautifulSoup import urllib3, csv, os, datetime, urllib3.request, re, sys for vYear in range(2016, 2019): for vMonth in range(1, 13): for vDay in range(1, 32): # go to the next month, if it is a leap year and greater than the 29th or if it is not a leap year # and greater than the 28th if vYear % 4 == 0: if vMonth == 2 and vDay &gt; 29: break else: if vMonth == 2 and vDay &gt; 28: break # go to the next month, if it is april, june, september or november and greater than the 30th if vMonth in [4, 6, 9, 11] and vDay &gt; 30: break # defining the date string to export and go to the next day using the url theDate = str(vYear) + "/" + str(vMonth) + "/" + str(vDay) # the new url created after each day theurl = "https://www.wunderground.com/history/daily/us/ma/cambridge/KBOS/" + theDate + "date.html" # extract the source data for analysis http = urllib3.PoolManager() thepage = http.request('GET', theurl) soup = BeautifulSoup(thepage, "html.parser") MaxWindSpeed = Visibility = SeaLevelPressure = Precipitation = High_Temp = Low_Temp = Day_Average_Temp = "N/A" for temp in soup.find_all('tr'): if temp.text.strip().replace('\n', '')[:6] == 'Actual' or temp.text.strip().replace('\n', '')[-6:] == "Record": pass elif temp.text.replace('\n', '')[-7:] == "RiseSet": break elif temp.find_all('td')[0].text == "Day Average Temp": if temp.find_all('td')[1].text.strip() == "-": Mean = "N/A" else: Mean = temp.find_all('td')[1].find…
tagged with: http://stackoverflow.com/tag/html
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90849015
tagged with: web-scraping
has comment: http://stackoverflow.com/comment/90849921
type: Question
has title: using beautiful soup 4 to scrape weather data (site is coded in javascript)
has answer: http://stackoverflow.com/a/51951324

http://stackoverflow.com/q/51946818
score: 3
favorite count: 0
tagged with: memory-management
has title: How to delete objects to increase free memory in python?
type: Question
has comment: http://stackoverflow.com/comment/90964821
has comment: http://stackoverflow.com/comment/90844746
has answer: http://stackoverflow.com/a/51946841
tagged with: python
has answer: http://stackoverflow.com/a/51947003
downvote count: 1
upvote count: 4
has comment: http://stackoverflow.com/comment/90964940
answer count: 4
has answer: http://stackoverflow.com/a/51947423
type: UnansweredQuestion
has body: My python application reads data from files and stores these data in dictionaries during start up (dictionaries are properties of data reader classes). Once the application starts and the read data is used, these data in the dictionaries are no longer needed. However, they consume large amount of memory. How do I delete these dictionaries to free the memory? For example: class DataReader(): def __init__(self, data_file): self.data_file = data_file def read_data_file_and_store_data_in_dictionary(): self.data_dictionary = {} for [data_name, data] in self.data_file: self.data_dictionary[data_name] = data class Application(): def __init__(self, data_file): self.data_reader = DataReader() self.data_reader.read() def start_app(self): self.use_read_data() After application is started, self.data_dictionary is no longer needed. How do I delete self.data_dictionary permanently?
has answer: http://stackoverflow.com/a/51947463
linked to: http://stackoverflow.com/q/3021264

http://stackoverflow.com/a/51833758
has body: in your code you are deleting the temp list each time del temp_list[:] instead of a, b = map(int, input().split()) you can simply use it like a, b = map(int, input()) and enter the input like 3,4 python will automatically get it as a tuple and will assign it to variable a,b respectively a, b = map(int, input()) #3,4 list_of_lists = [] for i in range(b): temp_list = list(map(float, input())) print(temp_list, i) list_of_lists.append(temp_list) print (list_of_lists)
has comment: http://stackoverflow.com/comment/90641456
answers question: http://stackoverflow.com/q/51832301
has comment: http://stackoverflow.com/comment/90657805
score: 0
has comment: http://stackoverflow.com/comment/90658497
type: Answer

http://stackoverflow.com/a/51829664
type: Answer
accepted answer of: http://stackoverflow.com/q/51829478
answers question: http://stackoverflow.com/q/51829478
score: 1
upvote count: 1
has body: you could also be more condense if you "merge" your two regex into one: for lines in f: value = re.search('((?:et|xe)-\d\\/\d\\/\d)', lines) if value: interfaces = value.group(1) # print interfaces smic_dict.setdefault(pfe, []).append(interfaces) pfe_interfaces.append(interfaces) The question mark creates a so called non-capturing group and the pipe combines both alternatives.
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90615297

http://stackoverflow.com/q/51861790
has answer: http://stackoverflow.com/a/51864695
tagged with: tensorflow
type: Question
score: 0
answer count: 1
has body: By this piece of code from the documentation, we can create multiple features to feed batches of data into a DNN model: my_feature_columns = [] for key in train_x.keys(): my_feature_columns.append(tf.feature_column.numeric_column(key=key)) But the problem is what is the proper way to transform the original features before they are fed to the input layer? Typical transformations that I can think of include normalization and clipping. tf.feature_column.numeric_column does have a parameter specifying the normalization function. But the example in the doc only demonstrate a scenario where the normalization factors are pre-defined and fixed, like lambda x: (x-3.2)/1.5. How can I perform normalization (e.g. MinMaxScaler in sklearn) across all those features without knowing its maximum and minimum beforehand. Also, is there any pipeline implementation where it's possible to do all sorts of feature transformations before they go into the input layer? Is creating a custom estimator tf.estimator.Estimator the answer to this problem? or anything else I'm not aware of.
type: UnansweredQuestion
tagged with: python
has title: How to preprocess features before training a TensorFlow model end-to-end in TF graph

http://stackoverflow.com/comment/90685859
comment on: http://stackoverflow.com/a/51866873
type: Comment
score: 1
type: AnswerComment
has text: @user3483203 `first_1`... aren't arrays, they are numbers lol

http://stackoverflow.com/comment/90793519
score: 0
type: Comment
type: QuestionComment
has text: Possibly `class Grid`? and define a `get(x,y)` function? What do you mean "split"?
comment on: http://stackoverflow.com/q/51921906

http://stackoverflow.com/q/51871907
score: 0
tagged with: chatbot
answer count: 2
has body: Is there any limit to the number of training phrases I can use in Dialogflow? Because generally all other platforms have such limit
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51885634
tagged with: python
tagged with: artificial-intelligence
has title: Maximum training phrases in dialogflow
tagged with: dialogflow-es
type: Question
has answer: http://stackoverflow.com/a/53076268

http://stackoverflow.com/a/51932004
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51930566
has body: To answer your main question of "How does this work?": From a conceptual standpoint, you are initially creating a fully-connected, or Dense, neural network with 3 layers: an input layer with 4 nodes, a hidden layer with 4 nodes, and an output layer with 3 nodes. Each node in the input layer has a connection to every node in the hidden layer, and same with the hidden to the output layer. In your second example, you just increased the number of nodes in the hidden layer from 4 to 8. A larger network can be good, as it can be trained to "look" for more things in your data. But too large of a layer and you may overfit; this means the network remembers too much of the training data, when it really just needs a general idea of the training data so it can still recognize slightly different data, which is your testing data. The reason you may not have seen an increase in performance is likely either overfitting or your activation function; Try a function other than relu in your hidden layer. After trying a few different function combinations, if you don't see any improvement, you are likely overfitting. Hope this helps.
answers question: http://stackoverflow.com/q/51930566
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/comment/90816463
has text: Thanks , its working
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51933137

http://stackoverflow.com/comment/90759513
type: AnswerComment
has text: That's it! Thank you!
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51884373

http://stackoverflow.com/q/51916181
tagged with: tkinter
tagged with: loops
type: Question
has title: Python Tkinter Run in a loop entries x times defined in a variable
has answer: http://stackoverflow.com/a/51918843
has comment: http://stackoverflow.com/comment/90786990
score: 0
has body: I would like to create one Python script using Tkinter that defines the number of the networks and, using the value inserted by the user in entry field, create in the next page x times networks to define. Then the values inserted by the user to create a file which has a pattern like this: --- # networks: - { cloud: cloud1, network: } - { cloud: cloud1, network: } - { cloud: cloud1, network: } - { cloud: cloud1, network: } ... Example: If the user enters 20 on the "Define the number of networks" page, then we should have 20 entry fields in the "Define the networks" page and 20 rows like this in the file: - { cloud: cloud1, network: } @AXK helped me for accomplishing this, thanks a lot. I would also like to have a scroll when I have more than 10 networks to introduce, for example. I have tried on AXK code to change it as it follows: import Tkinter as tk import tkFont as tkfont import sys from Tkinter import * class SampleApp(tk.Tk): def __init__(self, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) self.title_font = tkfont.Font( family="Helvetica", size=18, weight="bold", slant="italic" ) container = tk.Frame(self) container.pack(side="top", fill="both", expand=True) container.grid_rowconfigure(0, weight=1) container.grid_columnconfigure(0, weight=1) self.container = container self.current_frame = None self.num_networks = tk.IntVar() # Var shared between pages self.show_frame("StartPage") def show_frame(self, page_name): """Show a frame for the given page name""" if self.current_frame: self.current_frame.destroy() self.current_frame = None frame_class = globals()[page_name] # Ugly, but works. frame = frame_class(parent=self.container, controller=self) frame.grid(row=0, column=0, sticky="nsew") frame.tkraise() self.current_frame = frame class StartPage(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller label = tk.Label(self,text="This is the start page",font=controller.title_font) label.pack(side="top…
answer count: 1
tagged with: tkinter-entry
has comment: http://stackoverflow.com/comment/90787235
has comment: http://stackoverflow.com/comment/90787063
accepted answer: http://stackoverflow.com/a/51918843
tagged with: python
has comment: http://stackoverflow.com/comment/90786709
type: AnsweredQuestion

http://stackoverflow.com/q/51818167
favorite count: 0
type: Question
tagged with: tensorboard
has answer: http://stackoverflow.com/a/51819545
tagged with: python
has title: Why is my tensorboard graph like a Sawtooth waveform instead of a continuous line?
upvote count: 1
answer count: 1
tagged with: tensorflow
accepted answer: http://stackoverflow.com/a/51819545
type: AnsweredQuestion
has body: Here is a code that I implemented to plot an array on tensorboard: import tensorflow as tf a = [100, 80, 50, 40, 30, 15, 10, 7, 5, 9, 3, 1] writer = tf.summary.FileWriter('./log') summary = tf.Summary() for i in range (0, len(a)): summary.value.add(tag='x', simple_value=a[i]) writer.add_summary(summary, i) writer.flush() writer.close() I get a plot like this: Tensorbaord plot I want something like the blue line but instead I get the orange line. Please help me spot a mistake in my code and also state a reason for such behaviour? Thanks.
downvote count: 0
score: 1

http://stackoverflow.com/comment/90834643
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51878499
score: 0
has text: I added an example and some information about my actual status, thank you! :)

http://stackoverflow.com/comment/90677907
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51862401
has text: It will probably be very easy to fix your problem **IF** you follow @Prune's advice and provide a complete example that doesn't rely on missing variables and functions (`resultList`, `data`, and `convert_bytes`), and you show us exactly what you tried and the exact error message you saw. (For example, one error message probably resulted from using `resultList.getKey` when `resultList` was a list; another probably resulted from a different `resultList` that was a `DataScript` object. Providing a consistent example will help us help you.)
score: 0

http://stackoverflow.com/comment/90850972
type: Comment
has text: How do I chose specific category from inside view?
type: QuestionComment
comment on: http://stackoverflow.com/q/51950416
score: 0

http://stackoverflow.com/a/79020255
score: 3
downvote count: 0
answers question: http://stackoverflow.com/q/51833310
upvote count: 3
has body: In my case, I found that my Golang version was v1.22.0 when running go install and running the binaries that it produced resulted in either Killed: 9 or would hang indefinitely. I never figured out why, but pointing to a more recent Golang v1.22.7 and re-running go install resolved the issue and the resulting binaries ran fine after the upgrade.
type: Answer

http://stackoverflow.com/q/51813954
has comment: http://stackoverflow.com/comment/90582761
downvote count: 0
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90582859
tagged with: python
tagged with: linked-list
answer count: 0
type: UnansweredQuestion
score: 1
has body: I receive the AttributeError only after the value is successfully deleted - Please suggest if there is anything wrong in the way the values are printed. The function prints correctly prior to a Delete class Node: def __init__(self, value=None, l_next=None): self.value = value self.l_next = l_next def get_value(self): return self.value def set_value(self, val): self.value = val def get_next_node(self): return self.l_next def set_next_node(self, n_next): self.l_next = n_next class LinkedList: def __init__(self, head=None): self.head = head def add_node(self, value): new_node = Node(value, self.head) self.head = new_node def find_node(self, value): curr = self.head while curr: if curr.get_value() == value: return True curr = curr.get_next_node() return False def del_node(self, val): curr = self.head prev = None while curr: if curr.get_value() == val: if prev: prev.set_next_node(curr.get_next_node) else: self.head = curr.get_next_node print("Item Deleted") return True prev = curr curr = curr.get_next_node() print("Item not available for Delete") return False def print_list(self): item_list = [] curr = self.head while curr: item_list.append(curr.get_value()) curr = curr.get_next_node() return item_list List1 = LinkedList() List1.add_node(4) List1.add_node(5) List1.add_node(1) List1.add_node(19) List1.add_node(41) List1.add_node(25) List1.add_node(40) List1.add_node(51) print(List1.print_list()) print(List1.find_node(20)) print(List1.find_node(5)) List1.del_node(20) List1.del_node(5) print(List1.print_list()) Output : [51, 40, 25, 41, 19, 1, 5, 4] False True Item not available for Delete Item Deleted Error: print(List1.print_list()) File "C:/Users/sv4/PycharmProjects/Sample/LinkedList.py", line 55, in print_list item_list.append(curr.get_value()) AttributeError: 'function' object has no attribute 'get_value' Process finished with exit code 1
has title: AttributeError: 'function' object has no attribute 'get_value'
upvote count: 1
type: Question

http://stackoverflow.com/comment/90696936
comment on: http://stackoverflow.com/q/51872721
type: Comment
type: QuestionComment
has text: @akashkarothiya I just want to do it the most efficient way. Could you post your proposal for that use of 2 regex? Thx.
score: 0

http://stackoverflow.com/q/51946345
tagged with: random
has body: Ultimately I am trying to visualise the copula between two PDFs which are estimated from data (both via a KDE). Suppose, for one of the KDEs, I have discrete x,y data sorted in a tuple called data. I need to generate random variables with this distribution in order to perform the probability integral transform (and ultimately to obtain the uniform distribution). My methodology to generate random variables is as follows: import scipy.stats as st from scipy import interpolate, integrate pdf1 = interpolate.interp1d(data[0], data[1]) class pdf1_class(st.rv_continuous): def _pdf(self,x): return pdf1(x) pdf1_rv = pdf1_class(a = data[0][0], b= data[0][-1], name = 'pdf1_class') pdf1_samples = pdf1_rv.rvs(size=10000) However, this method is extremely slow. I also get the following warnings: IntegrationWarning: The maximum number of subdivisions (50) has been achieved. If increasing the limit yields no improvement it is advised to analyze the integrand in order to determine the difficulties. If the position of a local difficulty can be determined (singularity, discontinuity) one will probably gain from splitting up the interval and calling the integrator on the subranges. Perhaps a special-purpose integrator should be used. warnings.warn(msg, IntegrationWarning) IntegrationWarning: The occurrence of roundoff error is detected, which prevents the requested tolerance from being achieved. The error may be underestimated. warnings.warn(msg, IntegrationWarning) Is there a better way to generate the random variables?
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/90843303
tagged with: statistics
has answer: http://stackoverflow.com/a/51947128
has comment: http://stackoverflow.com/comment/90842377
tagged with: python
has comment: http://stackoverflow.com/comment/90843089
upvote count: 3
has title: stats.rv_continuous slow when when using custom pdf
tagged with: scipy
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51947128
score: 3
type: Question

http://stackoverflow.com/comment/90742588
type: AnswerComment
score: 0
type: Comment
has text: Cool, now it works for example 1, but the example 2 is not working. I get: ValueError: Format specifier missing precision
comment on: http://stackoverflow.com/a/51895558

http://stackoverflow.com/comment/90708016
has text: Means only which is configured in the application
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51878330

http://stackoverflow.com/comment/90814400
has text: Thank you Gsk, it works :) !
comment on: http://stackoverflow.com/q/51930019
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90788636
has text: `i` is the value of the item you're looping over in the array... so if you had 3 items `[10, 11, 12]` you're trying on the first iteration of accessing `ar[10]` which won't work... You could just use the builtin `sum`, eg: `sum(ar)` ?
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/51919448

unit-testing
tags question: http://stackoverflow.com/q/51846824
tags question: http://stackoverflow.com/q/51912317
tags question: http://stackoverflow.com/q/51900622
tags question: http://stackoverflow.com/q/51842371
tags question: http://stackoverflow.com/q/51807060
tags question: http://stackoverflow.com/q/51948505
tags question: http://stackoverflow.com/q/51888196
tags question: http://stackoverflow.com/q/51889049
tags question: http://stackoverflow.com/q/51909747
tags question: http://stackoverflow.com/q/51915625
type: Tag
tags question: http://stackoverflow.com/q/51832484
tags question: http://stackoverflow.com/q/51863721
tag name: unit-testing
tags question: http://stackoverflow.com/q/51915622
tags question: http://stackoverflow.com/q/51867106
tags question: http://stackoverflow.com/q/51813104
tags question: http://stackoverflow.com/q/51885525
tags question: http://stackoverflow.com/q/51816361

http://stackoverflow.com/comment/90610231
type: AnswerComment
has text: I tried this actually `plt.savefig("~/Documents/folder/age.pdf")` but it says file does not exist
type: Comment
comment on: http://stackoverflow.com/a/51827871
score: 0

datetime
tags question: http://stackoverflow.com/q/51918629
tags question: http://stackoverflow.com/q/51842381
tags question: http://stackoverflow.com/q/51882472
tags question: http://stackoverflow.com/q/51952311
tags question: http://stackoverflow.com/q/51835442
tags question: http://stackoverflow.com/q/51953942
tags question: http://stackoverflow.com/q/51949683
tags question: http://stackoverflow.com/q/51853132
tags question: http://stackoverflow.com/q/51799339
tags question: http://stackoverflow.com/q/51949660
tags question: http://stackoverflow.com/q/51929238
tags question: http://stackoverflow.com/q/51940862
tags question: http://stackoverflow.com/q/51840167
tags question: http://stackoverflow.com/q/51886090
tags question: http://stackoverflow.com/q/51800165
tags question: http://stackoverflow.com/q/51851301
tags question: http://stackoverflow.com/q/51846544
tags question: http://stackoverflow.com/q/51926983
tags question: http://stackoverflow.com/q/51911124
tags question: http://stackoverflow.com/q/51898826
tags question: http://stackoverflow.com/q/51815511
tags question: http://stackoverflow.com/q/51915475
tags question: http://stackoverflow.com/q/51813129
tags question: http://stackoverflow.com/q/51951223
tags question: http://stackoverflow.com/q/51889375
tags question: http://stackoverflow.com/q/51885478
tags question: http://stackoverflow.com/q/51904101
tag name: datetime
tags question: http://stackoverflow.com/q/51872533
tags question: http://stackoverflow.com/q/51935610
tags question: http://stackoverflow.com/q/51880774
tags question: http://stackoverflow.com/q/51953869
tags question: http://stackoverflow.com/q/51881460
tags question: http://stackoverflow.com/q/51827134
tags question: http://stackoverflow.com/q/51913695
tags question: http://stackoverflow.com/q/51901488
tags question: http://stackoverflow.com/q/51907336
tags question: http://stackoverflow.com/q/51810888
tags question: http://stackoverflow.com/q/51863147
tags question: http://stackoverflow.com/q/51887687
type: Tag
tags question: http://stackoverflow.com/q/51823928
tags question: http://stackoverflow.com/q/51843395
tags question: http://stackoverflow.com/q/51950845
tags question: http://stackoverflow.com/q/51945430
tags question: http://stackoverflow.com/q/51837002
tags question: http://stackoverflow.com/q/51872721
tags question: http://stackoverflow.com/q/51926466
tags question: http://stackoverflow.com/q/51802047
tags question: http://stackoverflow.com/q/51920013
tags question: http://stackoverflow.com/q/51837462

http://stackoverflow.com/comment/90640080
has text: Was just formatting error on here, it’s in my code
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51842980

http://stackoverflow.com/q/51912067
has comment: http://stackoverflow.com/comment/90775458
favorite count: 0
tagged with: python-3.x
answer count: 0
has body: I am looking for some pointers and resources on whether the following can be efficiently done in Python. I have a custom function: def outerfunc(innerfunc(&lt;inputs&gt;), arg1, arg2): computing outerfunc returns a numeric value, let's call it result innerfuncaccepts a few arguments, one of which is a list of numbers, [x1,x2,x3]and returns an object which is used to perform the calculation objective: calculate the sensitivity of result to a perturbation (finite amount) of each of [x1,x2,x3] so as to obtain a vector of 3 elements - the partial derivatives of result w.r.t. x1, x2, and x3 any resources, examples, advice would be appreciated! edit: i should elaborate that innerfunc in this example could come from a third-party source and is not directly built on numpy or edit-able. this is where i am not able to find much references online
type: UnansweredQuestion
upvote count: 1
has title: partial derivative of a custom function
linked to: http://stackoverflow.com/q/9876290
score: 1
type: Question
tagged with: function
downvote count: 0
has comment: http://stackoverflow.com/comment/90774197
tagged with: optimization
tagged with: python
has comment: http://stackoverflow.com/comment/90788399

http://stackoverflow.com/a/51857360
has comment: http://stackoverflow.com/comment/90666985
has body: by using the MasterAgreementid, i used duplicated to populate another column which is giving me false and true values against each of the rows and now i am trying to calculate the identical and difference against them
answers question: http://stackoverflow.com/q/51856249
has comment: http://stackoverflow.com/comment/90798157
score: 0
has comment: http://stackoverflow.com/comment/90692184
type: Answer

http://stackoverflow.com/q/51898042
tagged with: python
tagged with: cmd
possible better answer: http://stackoverflow.com/a/51898802
accepted answer: http://stackoverflow.com/a/51898861
has answer: http://stackoverflow.com/a/51898802
tagged with: subprocess
has title: Run a script from different folder with arguments in python (like in cmd)
score: 0
has answer: http://stackoverflow.com/a/51898909
has comment: http://stackoverflow.com/comment/90747584
has comment: http://stackoverflow.com/comment/90748076
type: Question
has comment: http://stackoverflow.com/comment/90748347
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51898861
has comment: http://stackoverflow.com/comment/90748354
has body: I guess I have to use either use os.system or subprocess.call, but I can't figure out how to use it. I don't have the permission to edit the original folder. subprocess.Popen('file.py', cwd=dirName) gives me 'The system cannot find the file specified' even though the file clearly exists If I was typing in cmd, cd directory file.py -arg Edit: Just to be clear I want to run another script using a python script
has comment: http://stackoverflow.com/comment/90747203
answer count: 3

http://stackoverflow.com/a/78445545
answers question: http://stackoverflow.com/q/51824628
score: 0
type: Answer
has body: I found the solution to my problem was to copy the Crypto folder from C:\Users\&lt;UserName&gt;\Documents\mypy\.venv\Lib to &lt;path_to_virtual_environment\.venv\Lib\site-packages. When installing the module using pip from inside my activate virtual environment, it appears as though it's being installed to my Documents location, and not to the root virtual environment folder. From the command line, the module was discoverable inside the virtual environment, but not when running from inside VS Code.

http://stackoverflow.com/q/51893013
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51893099
has answer: http://stackoverflow.com/a/51893108
type: Question
possible better answer: http://stackoverflow.com/a/51893099
has comment: http://stackoverflow.com/comment/90736932
has comment: http://stackoverflow.com/comment/90737389
accepted answer: http://stackoverflow.com/a/51893662
has body: I have the following string inputs: "11A4B" "5S6B" And want the following outputs: ["11A", "4B"] ["5S", "6B"] Eg after each delimiter A, B or S split and keep the delimiter. I can do with split from re (putting parenthesis on the delimiter pattern returns also the delimiter used): re.split("([ABS])", "11A4B") #['11', 'A', '4', 'B', ''] And can play around to have the wanted solution but I wonder if there is a pure regex solution?
has answer: http://stackoverflow.com/a/51893127
score: 2
has title: Splitting by multiple separator and keep separator
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/90737021
upvote count: 2
has comment: http://stackoverflow.com/comment/90736987
tagged with: python
tagged with: regex
has answer: http://stackoverflow.com/a/51893662
answer count: 4
has comment: http://stackoverflow.com/comment/90736983

http://stackoverflow.com/q/51948446
type: Question
has answer: http://stackoverflow.com/a/51951295
has title: Pygame KEYUP, KEYDOWN causing ghost movement
tagged with: python
tagged with: pygame
has body: I took a stab at learning KEYUP and KEYDOWN. Bascily, after the user crashes into any side of the window the game resets like intended. What is not intended is for the square to begin moving again even though no key has been pressed or released. Ideal series of events: - User Crashes - Game resets with square in the original starting potion (stationary) - press a movement key and square moves Any insight into why this is happening would be great. Thanks import pygame import time pygame.init() display_width = 800 display_height = 600 black = (0, 0, 0) white = (255, 255, 255) red = (255, 0, 0) car_width = 75 gameDisplay = pygame.display.set_mode((display_width, display_height)) pygame.display.set_caption('A bit Racey') clock = pygame.time.Clock() def text_objects(text, font): textSurface = font.render(text, True, black) return textSurface, textSurface.get_rect() def message_display(text): largeText = pygame.font.Font('freesansbold.ttf', 115) TextSurf, TextRect = text_objects(text, largeText) TextRect.center = ((display_width / 2), (display_height / 2)) gameDisplay.blit(TextSurf, TextRect) pygame.display.update() time.sleep(2) game_loop() def crash(): message_display('You Crashed') def game_loop(): x = 200 y = 200 x_change = 0 y_change = 0 gameExit = False while not gameExit: # Movement logic for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_RIGHT: x_change += 5 if event.key == pygame.K_LEFT: x_change += -5 if event.type == pygame.KEYUP: if event.key == pygame.K_RIGHT: x_change += -5 if event.key == pygame.K_LEFT: x_change += 5 if event.type == pygame.KEYDOWN: if event.key == pygame.K_UP: y_change += -5 if event.key == pygame.K_DOWN: y_change += 5 if event.type == pygame.KEYUP: if event.key == pygame.K_UP: y_change += 5 if event.key == pygame.K_DOWN: y_change += -5 x += x_change y += y_change gameDisplay.fill(white) pygame.draw.rect(gameDisplay, red, [x, y, 75, 75]) # Check if b…
has answer: http://stackoverflow.com/a/51948821
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/51951085
type: UnansweredQuestion
tagged with: python-3.x

http://stackoverflow.com/comment/139742154
has text: mind that this is outdated -- 'M' will raise an error (see https://stackoverflow.com/a/78075544/5533078)
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/59988779
type: Comment

http://stackoverflow.com/comment/90830841
type: QuestionComment
has text: @imsaiful I don't think this problem is raising due to *Django*. I didn't have any experience with aws environment :(
score: 0
comment on: http://stackoverflow.com/q/51937219
type: Comment

http://stackoverflow.com/comment/90653602
has text: BTW, is your input really JSON, or is it JSONL? Trying to call `json.loads(line)` for each line in a file will only work for a JSONL file (that is to say, a file for which *each line is a separate valid JSON document*), not a JSON file.
comment on: http://stackoverflow.com/q/51850163
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90597187
has text: You're welcome. Please consider accepting this answer (by clicking on Accept) if you find it the most appropriate for you.
comment on: http://stackoverflow.com/a/51821574
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/90648546
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51847520
has text: Whats your expected output exactly?

http://stackoverflow.com/a/51947693
type: Answer
downvote count: 0
has body: to install package for a specific python installation, you need a package installer shipped with that installation, in your case, pip is installed by an anaconda installation, use pip.exe or easy_install.exe from this python3.6 installation's Scripts directory instead.
score: 1
has comment: http://stackoverflow.com/comment/90845197
answers question: http://stackoverflow.com/q/51947506
upvote count: 1

http://stackoverflow.com/q/51890755
has body: I have a silly code with a library called logging. I want to put a resume of debug mode in a file inside a specific path ./logs/. In the middle of the code I have INFO to save in the .log file, but not works already. I think I'm wrong in something very basic, but I do not see it. # coding=utf-8 import re import os import csv import datetime, timedelta import logging import logging.config def configure_logging(logger): # Configure logger with custom formatter. logger.setLevel(logging.DEBUG) formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") # Create file handler which logs DEBUG messages. now = datetime.now().strftime('%Y%m%d-%Hh%M') logname = './logs/' + now + '.log' fh = logging.FileHandler(logname) fh.setLevel(logging.DEBUG) fh.setFormatter(formatter) # Create console handler with a higher log level. ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) ch.setFormatter(formatter) # Add handlers to the logger logger.addHandler(fh) logger.addHandler(ch) def between(value, a, b): pos_a = value.find(a) # Find and validate before-part. if pos_a == -1: return "" # Find and validate after part. pos_b = value.rfind(b) if pos_b == -1: return "" # Return middle part. adjusted_pos_a = pos_a + len(a) if adjusted_pos_a &gt;= pos_b: return "" return value[adjusted_pos_a:pos_b] def main(): logger = logging.getLogger('Main') configure_logging(logger) module_logger = logging.getLogger('Extract Information') def scan_folder(): path = '/Users/anna/PycharmProjects/extractData/DiarioOficial' with open('All.csv', 'w') as csvFile: headers = ['COMPANY NAME', 'CVE'] writer = csv.writer(csvFile, delimiter=';') writer.writerow(headers) for (path, dirnames, file_names) in os.walk(path): for file_name in file_names: if file_name.endswith(".txt"): file_path=os.path.join(path, file_name) mensaje = open(file_path).read() module_logger.info('File is opened correct') # Company Name keywords_cap = ['SpA', 'SPA', 'LIMITADA', 'LTDA', 'S.A.', 'E.I.R.L.', 'S.L.'] # …
has title: import logging: file resume code with python
has answer: http://stackoverflow.com/a/51891146
score: 0
answer count: 1
linked to: http://stackoverflow.com/q/415511
tagged with: path
accepted answer: http://stackoverflow.com/a/51891146
tagged with: python
tagged with: logging
type: AnsweredQuestion
tagged with: file
has comment: http://stackoverflow.com/comment/90732845
type: Question

concurrency
tag name: concurrency
tags question: http://stackoverflow.com/q/51953712
type: Tag
tags question: http://stackoverflow.com/q/51885246

http://stackoverflow.com/comment/90751046
has text: This isn't exactly what I want, but it compiles: `var_list = ['x','y'] def f(vec): return vec[0]+vec[1] exec(''' def g({0}): return f([{0}]) '''.format(','.join(var_list))) print(f([2,3])) print(g(2,3))`
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51887570

http://stackoverflow.com/q/51889378
has comment: http://stackoverflow.com/comment/90730122
downvote count: 0
has body: I am training a keras sequential model. I want the learning rate to be reduced when training is not progressing. I use ReduceLROnPlateau callback. After first 2 epoch with out progress, the learning rate is reduced as expected. But then its reduced every 2 epoch's, causing the training to stop progressing. Is that a keras bug ? or I use the function the wrong way ? The code: earlystopper = EarlyStopping(patience=8, verbose=1) checkpointer = ModelCheckpoint(filepath = 'model_zero7.{epoch:02d}-{val_loss:.6f}.hdf5', verbose=1, save_best_only=True, save_weights_only = True) reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.2, patience=2, min_lr=0.000001, verbose=1) history_zero7 = model_zero.fit_generator(bach_gen_only1, validation_data = (v_im, v_lb), steps_per_epoch=25,epochs=100, callbacks=[earlystopper, checkpointer, reduce_lr]) The output: Epoch 00006: val_loss did not improve from 0.68605 Epoch 7/100 25/25 [==============================] - 213s 9s/step - loss: 0.6873 - binary_crossentropy: 0.0797 - dice_coef_loss: -0.8224 - jaccard_distance_loss_flat: 0.2998 - val_loss: 0.6865 - val_binary_crossentropy: 0.0668 - val_dice_coef_loss: -0.8513 - val_jaccard_distance_loss_flat: 0.2578 Epoch 00007: val_loss did not improve from 0.68605 Epoch 00007: ReduceLROnPlateau reducing learning rate to 0.000200000009499. Epoch 8/100 25/25 [==============================] - 214s 9s/step - loss: 0.6865 - binary_crossentropy: 0.0648 - dice_coef_loss: -0.8547 - jaccard_distance_loss_flat: 0.2528 - val_loss: 0.6860 - val_binary_crossentropy: 0.0694 - val_dice_coef_loss: -0.8575 - val_jaccard_distance_loss_flat: 0.2485 Epoch 00008: val_loss improved from 0.68605 to 0.68598, saving model to model_zero7.08-0.685983.hdf5 Epoch 9/100 25/25 [==============================] - 208s 8s/step - loss: 0.6868 - binary_crossentropy: 0.0624 - dice_coef_loss: -0.8554 - jaccard_distance_loss_flat: 0.2518 - val_loss: 0.6860 - val_binary_crossentropy: 0.0746 - val_dice_coef_loss: -0.8527 - val_…
tagged with: keras
has comment: http://stackoverflow.com/comment/90730236
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/90730492
tagged with: keras-2
score: 19
has answer: http://stackoverflow.com/a/57323479
has answer: http://stackoverflow.com/a/51894901
accepted answer: http://stackoverflow.com/a/51894901
type: AnsweredQuestion
upvote count: 19
type: Question
has answer: http://stackoverflow.com/a/66555114
tagged with: neural-network
possible better answer: http://stackoverflow.com/a/57323479
has comment: http://stackoverflow.com/comment/90738892
tagged with: deep-learning
answer count: 3
has title: How to use keras ReduceLROnPlateau

http://stackoverflow.com/a/51912111
score: 0
has body: Use an event object like this post, and check that event in your target functoin. Also, you need a new thread each time you re-start. The code shown below adds some debugging that should be useful. (Another approach is to build a custom stop function.) import logging import threading import time as t var = 0 logging.basicConfig(level=logging.DEBUG, format='[%(levelname)s] (%(threadName)-10s) %(message)s', ) def testDef(stop_event): global var print 'Thread Running', var # inThread.stop() while not stop_event.isSet(): var += 1 logging.debug('Var is %i' % var) t.sleep(1) # Use an event to track user input testStopEvent = threading.Event() testStopEvent.clear() test = threading.Thread(name = 'test', target=testDef, args=((testStopEvent,))) test.setDaemon(True) while True: menu = input("On = 1, Off = 2, Show Var = 3") if menu == 1: test.start() elif menu == 2: testStopEvent.set() test.join() # Wait for the thread to finish test = threading.Thread(target=testDef, args=((testStopEvent,))) # "re-start" thread testStopEvent.clear() # Reset the stop event elif menu == 3: print(var)
type: Answer
answers question: http://stackoverflow.com/q/51911554

http://stackoverflow.com/a/51841861
has comment: http://stackoverflow.com/comment/90714966
type: Answer
has comment: http://stackoverflow.com/comment/90664288
downvote count: 0
has body: I'm not sure if I understood your problem correctly, but just writing: print(result) and running your code from the command line gives: [list([])], and changing the value of distance from 0.1 (no points so close) to 1.0 gives [list([0L])], where 0 is the position of the nearest neighbour in your list. BTW, the construction of the array npA seems strange to me. You could get the same result just writing: [pA[0]].
accepted answer of: http://stackoverflow.com/q/51841318
score: 1
answers question: http://stackoverflow.com/q/51841318
has comment: http://stackoverflow.com/comment/90734048
has comment: http://stackoverflow.com/comment/90692347
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/q/51810193
score: 0
tagged with: blogs
answer count: 1
has body: I am currently working on a blog for a project, and i want to add in a comment section for each post in the DetailView. My code seems fine, however i keep getting a "Page not Found(404) error". I am thinking it may be my url pattern but i cannot seem to figure out what i am doing wrong. error given url.py urlpatterns[ path('blog/post/&lt;int:pk&gt;/', views.PostDetailView.as_view(),name='post_detail'), path('blog/post/&lt;int:pk&gt;/comment/', views.MyFormView.as_view(), name='my_form_view_url'), ] forms.py class CommentForm(forms.ModelForm): class Meta(): model = Comment fields = ('text',) widgets = { 'text': forms.Textarea(attrs={'class':'ediable medium-editor-textarea'}) } views.py class PostDetailView(DetailView): model = Post template_name = 'carsforsale/post_detail.html' def get_context_data(self, **kwargs): context = super(PostDetailView, self).get_context_data(**kwargs) context['form'] = CommentForm() return context class MyFormView(SingleObjectMixin,FormView): template_name = 'carsforsale/post_detail.html' form_class = CommentForm model = Comment def post(self, request, *args, **kwargs): self.object = self.get_object() return super().post(request, *args, **kwargs) def get_success_url(self): return reverse('carsforsale:post_detail', kwargs={'pk': self.object.pk}) post_detail.html this is the form inside of the post_detail.html &lt;form method="POST" action="{% url 'carsforsale:my_form_view_url' pk=post.pk %}"&gt; {% csrf_token %} &lt;div class="form-group"&gt; {% render_field form.text class="form-control text" rows=3 %} &lt;/div&gt; &lt;input type="submit" class="btn btn-primary" value="Comment" /&gt; &lt;/form&gt; These are my Post and Comment models class Post(models.Model): author = models.ForeignKey('auth.User', on_delete= models.CASCADE) title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) def publish(self): self.publishe…
accepted answer: http://stackoverflow.com/a/51810411
tagged with: django
tagged with: python
type: AnsweredQuestion
type: Question
has answer: http://stackoverflow.com/a/51810411
has title: Django SingleObjectMixin: Page not found(404)

http://stackoverflow.com/a/51992300
type: Answer
has body: Couldn't a simple For loop work? Scan each "across" line of your bitmap looking for... X pos where from Black meets White = new start point. Also in same scanned line now look for a new X-pos: where from White meets Black = new end point. Either put dots at start/end points for "outline" effect, or else put dots in "center" effect by dot.x = (end_point - start_point) / 2
has comment: http://stackoverflow.com/comment/90936003
answers question: http://stackoverflow.com/q/51805471
has comment: http://stackoverflow.com/comment/90935813
score: 0

http://stackoverflow.com/a/51829888
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51829791
accepted answer of: http://stackoverflow.com/q/51829791
has body: From the stack trace it looks like when the printer is initialized, the Adafruit library wakes up the printer by writing the integer 255 over serial to the printer. It does this by calling the Serial class's write() method (inside its own write_bytes() method) on line 189: super(Adafruit_Thermal, self).write(chr(arg)) It's able to do this since the Adafruit_Thermal class inherits from Serial, as you can see in the class definition. Well as @abarnert pointed out, chr() returns a string, but it sounds like write() is expecting binary data. So I'd try both the suggestions in the comments to your question. First try changing line 189 to: super(Adafruit_Thermal, self).write(arg) If that doesn't work try: super(Adafruit_Thermal, self).write(bytes([arg]))
type: Answer
has comment: http://stackoverflow.com/comment/90616605
has comment: http://stackoverflow.com/comment/90615359
has comment: http://stackoverflow.com/comment/90687131
has comment: http://stackoverflow.com/comment/90614902
score: 0

http://stackoverflow.com/comment/90822020
has text: Maybe consider threading or multiprocessing instead - the Odroid has 4/8 cores. You could just acquire continuously on core 1 and then process frame 1 on core 2, process frame 2 on core 3, frame 3 on core 4 and frame 4 back on core 2 again.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51934382

http://stackoverflow.com/a/51835801
type: Answer
has body: Try adding an assert to len(str(guess)) == 4 so it is assert len(str(guess)) == 4. The reason why is that just having len(str(guess)) == 4 is useless - that is run but you haven't told Python to do anything with the result. If you assert, it basically means verify the next code is true, otherwise throw an exception.
has comment: http://stackoverflow.com/comment/90625216
score: 0
answers question: http://stackoverflow.com/q/51835755

http://stackoverflow.com/q/51916745
favorite count: 0
tagged with: python-3.x
answer count: 5
type: UnansweredQuestion
tagged with: python
duplicate of: http://stackoverflow.com/q/10048069
upvote count: 0
has body: Is there a single command to randomly sample an item for a list and remove it? let say the command named cmd, I want something like that? l = [1,2,4,6] r = cmd(l) r = 4 l = [1,2,6]
tagged with: list
linked to: http://stackoverflow.com/q/10048069
has answer: http://stackoverflow.com/a/51916826
type: Question
has answer: http://stackoverflow.com/a/51916766
has answer: http://stackoverflow.com/a/51916763
has title: Python sample and remove item from list
has answer: http://stackoverflow.com/a/51916840
score: -1
has answer: http://stackoverflow.com/a/51916856
tagged with: random
downvote count: 1

http://stackoverflow.com/comment/90671843
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51859373
has text: @nicksheen it expects 11 fields if I not set delimiter='\t' . Do you think it shouldn't do that even if I not set delimiter ?

http://stackoverflow.com/comment/91049508
type: Comment
score: 0
type: AnswerComment
has text: @RonZhang: no, you can not set parameters of `pack` to force the widget to a specific size, but you can set the widget itself to a specific size. You have to give it an image (and you'll need to use the `compound` option. If there's an image, the `width` and `height` attributes represent the width and height in pixels.
comment on: http://stackoverflow.com/a/51869204

http://stackoverflow.com/q/51935769
favorite count: 0
has body: I am using Airflow to run a set of tasks inside for loop. The purpose of the loop is to iterate through a list of database table names and perform the following actions: for table_name in list_of_tables: if table exists in database (BranchPythonOperator) do nothing (DummyOperator) else: create table (JdbcOperator) insert records into table (JdbcOperator, Trigger on One Success) On the Web UI, this appears like: Currently, Airflow executes the tasks in this image from top to bottom then left to right, like: tbl_exists_fake_table_one --> tbl_exists_fake_table_two --> tbl_create_fake_table_one, etc. However, the insert statement for fake_table_two depends on fake_table_one being updated, a dependency not captured by Airflow currently. (Technically this dependency is captured by the order of the list_of_table_names, but I believe this will be prone to error in a more complex situation) I want all tasks related to fake_table_one to run, followed by all tasks related to fake_table_two. How can I accomplish this in Airflow? Full code below: for tbl_name in list_of_table_names: # Check if table exists by querying information tables def has_table(tbl_name=tbl_name): p = JdbcHook('conn_id') sql =""" select count(*) from system.tables where name = '{}' """.format(tbl_name.upper()) count = p.get_records(sql)[0][0] #unpack the list/tuple # If the query didn't return rows, branch to Create Table Task # otherwise, branch to Dummy Operator (Airflow requires that both branches have a task) if count == 0: return 'tbl_create_{}'.format(tbl_name) else: return 'dummy_{}'.format(tbl_name) # run has_table python function exists = BranchPythonOperator( task_id='tbl_exists_{}'.format(tbl_name), python_callable=has_table, depends_on_past=False, dag=dag ) # Dummy Operator dummy = DummyOperator(task_id='dummy_{}'.format(tbl_name),dag=dag,depends_on_past=False) # Run create table SQL script create = JdbcOperator( task_id='tbl_create_{}'.format(tbl_name), jdbc_conn_id='conn_id', sql = sql_parse(…
type: Question
tagged with: python
has title: Airflow - how to set task dependencies between iterations of a for loop?
upvote count: 3
tagged with: etl
answer count: 1
has answer: http://stackoverflow.com/a/51936069
tagged with: airflow
accepted answer: http://stackoverflow.com/a/51936069
type: AnsweredQuestion
score: 3
downvote count: 0

http://stackoverflow.com/a/51953392
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/90874747
has body: An easier way might be to use astroquery's SkyView module. For example: import matplotlib.pyplot as plt from astroquery.skyview import SkyView from astropy.coordinates import SkyCoord from astropy.wcs import WCS # Query for SDSS g images centered on target name hdu = SkyView.get_images("M13", survey='SDSSg')[0][0] # Tell matplotlib how to plot WCS axes wcs = WCS(hdu.header) ax = plt.gca(projection=wcs) # Plot the image ax.imshow(hdu.data) ax.set(xlabel="RA", ylabel="Dec") plt.show() which produces an image like this: You can replace "M13" with your target name, or coordinates -- see the SkyView.get_images docs for all of the finer knobs you can tune. Then, if you want to flip the directions of either axis, you can call ax.invert_xaxis() or ax.invert_yaxis()
answers question: http://stackoverflow.com/q/51952436
type: Answer
downvote count: 0

http://stackoverflow.com/q/51935797
has comment: http://stackoverflow.com/comment/90822411
favorite count: 0
tagged with: arcgis
tagged with: field
has answer: http://stackoverflow.com/a/51937671
type: UnansweredQuestion
has body: I am currently working on a project in ArcGIS where I have a bunch of feature classes that all contain a date field that represents the dates that the samples in the feature classes were taken. I need to convert each of those dates (the field type is "date" not string or integer) in each of those feature classes into the day of the year and then add the day of the year into an empty field called DOY. The dates are in the mm/dd/yyyy format but there are no leading zeros (7/4/15 instead of 07/04/15). The sample date field in each feature class are either named Date, Sample_Dat or T0_Date, but each feature class only contains one of those fields. The code that I have attached is what I have so far. NOTE: The arcpy.calculateField_management should align with the rows.updateRows above it in each of the 3 cases but there was formatting issues when I copied the code over to this website that I could not fix. EDIT: Whenever I try to run this code it does nothing and does not add the day of year to the DOY field. Also, instead of giving a red X or a green check it will give a yellow triangle signaling a warning which is due to the fact that about 80% of the feature classes already have a "DOY" field but I included the addfield_management part at the beginning to account for the 20% that don't have a DOY field. I thought by adding the elif statements it wouldn't give a warning sign and instead it would just loop until it reached a relevant statement. import arcpy import datetime fcList = arcpy.ListFeatureClasses() for fc in fcList: if "DOY" not in arcpy.ListFields(fc): arcpy.AddField_management(fc,"DOY","SHORT") elif "DOY" in arcpy.ListFields(fc) and "Date" in arcpy.ListFields(fc): with arcpy.da.UpdateCursor(fc, "Date") as rows: for row in rows: rows.updateRow([datetime.datetime.strptime(row, '%m/%d/%Y')]) arcpy.CalculateField_management(fc,"DOY",row.timetuple().tm_yday) elif "DOY" in arcpy.ListFields(fc) and "Sample_Dat" in arcpy.ListFields(fc): with arcpy.da.UpdateCursor(fc…
tagged with: python
has title: Converting a date field into the day of the year and then adding it into an empty field arcpy python arcgis
has comment: http://stackoverflow.com/comment/90825411
downvote count: 2
type: Question
has comment: http://stackoverflow.com/comment/90825050
tagged with: arcpy
has comment: http://stackoverflow.com/comment/90824441
score: -2
tagged with: date
has comment: http://stackoverflow.com/comment/90825492
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/91122540

http://stackoverflow.com/a/51913301
has comment: http://stackoverflow.com/comment/90776961
downvote count: 1
has comment: http://stackoverflow.com/comment/90776944
type: Answer
upvote count: 22
has comment: http://stackoverflow.com/comment/90776927
has comment: http://stackoverflow.com/comment/99886830
answers question: http://stackoverflow.com/q/51912284
has body: You are likely confused between python2, python3, and different python virtual environments. This is the most reliable source, in your case $ python &gt;&gt;&gt; import numpy &gt;&gt;&gt; numpy.__version__ '1.14.5' To upgrade/downgrade numpy, you need to use pip that corresponds to the python that you are using. I think you are using python 2.7. Look around for a pip executable that corresponds to the installed package at /usr/local/lib/python2.7/dist-packages/pip. This is not the "right" way, but it will work python -m pip install numpy==x.y.z python will just correspond to python interpreter you are using -m pip will find the right pip that corresponds to your installation of python 2.7 numpy==x.y.z will force the downgrade Now, you will probably run into permissions problems that will tempt you to use sudo. At that point, you can either try adding the --user flag ... but if you really have to use sudo, then consider creating a virtualenv. (Please.) Probably The Right Thing to Do Others have commented on this: maybe your indices are actually not integers. (Related: Slice indices must be integers or None or have __index__ method) Find the places in your code that is indexing into a list, and make sure that are actually integers. assert isinstance(a, int), 'a must be an int' assert isinstance(b, int), 'b must be an int' x = y[a:b] Keep adding those type assertions until you find the bug.
score: 21
has comment: http://stackoverflow.com/comment/90776923

http://stackoverflow.com/comment/90787202
type: QuestionComment
has text: You're not actually writing anything to the file in the code shown. Please post code that reproduces your error.
score: 7
comment on: http://stackoverflow.com/q/51918652
type: Comment

http://stackoverflow.com/q/51805869
type: AnsweredQuestion
upvote count: 2
downvote count: 2
tagged with: openpyxl
has answer: http://stackoverflow.com/a/51806306
accepted answer: http://stackoverflow.com/a/51806306
type: Question
score: 0
answer count: 1
favorite count: 0
has body: Hi I am working on setting the font style to automate the stuff and I can't get the results I want. I want to change the font of column A but I cannot find the correct command for it. Thanks for your time! import openpyxl from openpyxl.styles import Font wb = openpyxl.Workbook() sheet = wb["Sheet"] italic24Font = Font( size = 24, italic = True) sheet['A'] #I do not know the command here wb.save( 'test.xlsx' )
tagged with: python
has title: Change font style in openpyxl

http://stackoverflow.com/comment/90820579
comment on: http://stackoverflow.com/q/51935179
has text: you can debug with the `%debug` command in a jupyter notebook after an exception has been raised; have you considered using `ipywidgets.interact` to get the behavior you describe?
score: 1
type: Comment
type: QuestionComment

text-classification
tags question: http://stackoverflow.com/q/51907189
tags question: http://stackoverflow.com/q/51925123
tag name: text-classification
tags question: http://stackoverflow.com/q/51859091
type: Tag
tags question: http://stackoverflow.com/q/51949736
tags question: http://stackoverflow.com/q/51928856
tags question: http://stackoverflow.com/q/51802752

http://stackoverflow.com/a/51923432
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51923190
has body: OR: def repl(d,s): d={k:v for k,v in d.items() if k in s} return s.replace(next(iter(d)),next(iter(d.values()))) inp = input("Sentence: ") print(repl(BRANDS,inp)) Example Output: Sentence: I bought some Velcro shoes I bought some hook and loop fastener shoes

http://stackoverflow.com/q/51835831
accepted answer: http://stackoverflow.com/a/51835905
has body: I am trying to group a dataframe in Pandas (Python2.7) depending on a progressive count that resets every time a condition is not met anymore. It looks like: date condition count 01,01,2018 08:00 A 1 01,01,2018 08:01 A 2 01,01,2018 08:03 A 3 01,01,2018 08:04 B 1 01,01,2018 08:07 B 2 01,01,2018 08:10 B 3 01,01,2018 08:13 B 4 01,01,2018 08:14 C 1 01,01,2018 08:16 C 2 01,01,2018 08:18 C 3 01,01,2018 08:20 C 4 01,01,2018 08:21 C 5 01,01,2018 08:22 A 1 01,01,2018 08:24 A 2 01,01,2018 08:25 B 1 01,01,2018 08:27 B 2 01,01,2018 08:29 B 3 01,01,2018 08:30 C 1 I am trying to obtain: date condition count 01,01,2018 08:00 A 3 01,01,2018 08:04 B 4 01,01,2018 08:14 C 5 01,01,2018 08:22 A 2 01,01,2018 08:25 B 3 01,01,2018 08:30 C 1 As you can see, it is not possible to group just by A,B,C...because the groups depend on the fact that the condition is changing, rather than the condition itself. That's why I have created the count, that could help in this purpose. I have tried df2=df.groupby(['condition', 'date']).where(df['count']&lt;df['count'].shift(1), for cycles...but I get errors of syntax, or definition, or key, or "Cannot access callable attribute 'where' of 'DataFrameGroupBy' objects, try using the 'apply' method", and many others depending on the attempt. I hope some of you can suggest how to solve this, thank you in advance.
favorite count: 0
tagged with: python
has title: Pandas: Grouping depending on conditional count
score: 4
type: AnsweredQuestion
type: Question
upvote count: 4
has answer: http://stackoverflow.com/a/51835905
tagged with: python-2.7
tagged with: pandas
answer count: 1
downvote count: 0

http://stackoverflow.com/q/51945478
answer count: 0
tagged with: pycharm
score: 1
has comment: http://stackoverflow.com/comment/90861171
upvote count: 1
type: Question
has body: I just started to learn python 3 few months ago, and I having problems in the pycharm IDE... it is very annoying and i wish someone could help to fix that. when I run any code, PRINT: Fatal Python error: Py_Initialize: unable to load the file system codec ModuleNotFoundError: No module named 'encodings' Current thread 0x00000228 (most recent call first): Process finished with exit code -1073740791 (0xC0000409) Thanks
duplicate of: http://stackoverflow.com/q/5694706
has title: python 3 - ModuleNotFoundError: No module named 'encodings'
downvote count: 0
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90840380
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/5694706
tagged with: python

http://stackoverflow.com/comment/90555498
has text: Thanks a lot! Really should've played around a bit more.
score: 1
comment on: http://stackoverflow.com/a/51799468
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/90876308
score: 0
type: AnswerComment
has text: Thanks a lot - now everything is ok
type: Comment
comment on: http://stackoverflow.com/a/51921769

http://stackoverflow.com/a/51861324
upvote count: 4
type: AcceptedAnswer
downvote count: 0
score: 4
has body: Upgrade to Pika 0.12.0 and follow the example in this code, or do something similar: link. I realize the example using a different connection type, but you get the idea. Pika's ioloop must be running in one thread, and your time intensive task can carry on in another thread.
type: Answer
accepted answer of: http://stackoverflow.com/q/51844852
answers question: http://stackoverflow.com/q/51844852

http://stackoverflow.com/q/51923309
favorite count: 0
has answer: http://stackoverflow.com/a/51923342
linked to: http://stackoverflow.com/q/16522111
tagged with: python
answer count: 4
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51923534
has body: So, I am working on a small project. I am making a text-based temperature calculator but I have run into a problem with an if statement in the program, just as the title of this question suggests. This is the code that I am having issues with. running = True fahr = "fahrenheit" cel = "celsius" kel = "kelvin" temperatures = [fahr, cel, kel] while running == True: try: temperature_type = str.lower(input("What is the current temperature unit you are using? \nFahrenheit, Celsius, or Kelvin?\n")) except ValueError: print("I do not understand. Please try again.") continue if temperature_type == any(temperatures) and not all(temperatures): break else: print("Please enter a valid input.") continue It seems that there is something wrong with the logic that I am not seeing, and I have tried multiple combinations, even ones that are suggested from this post and none of them seem to work the way I want it to. The way I want it to work is to let the variable temperature_type be equal to only one of the temperatures such as Fahrenheit and then ask another question (which is not shown here). If the variable temperature_type does not equal any of the three, then I want to loop to repeat. The issue I am having is that no matter what I input, it always asks for the temperature. If anyone has an answer I would be thrilled to know what I am doing wrong and I would also love an explanation of the logic because I am not the best with this sort of logic yet. Thanks again for any answers and/or guidance!
upvote count: 1
has title: How to have if statement accept any one of three arguments without all being true in Python
accepted answer: http://stackoverflow.com/a/51923342
type: AnsweredQuestion
tagged with: if-statement
score: 1
has answer: http://stackoverflow.com/a/51923344
type: Question
has answer: http://stackoverflow.com/a/51923341
downvote count: 0
possible better answer: http://stackoverflow.com/a/51923341

http://stackoverflow.com/comment/90566040
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51804930
has text: @Marat ........ it is. Did you bother reading the question? I'm hoping it can be done in python (or wrapped in python somehow) so that I can use `argparse` to do options flags.

http://stackoverflow.com/q/51916580
upvote count: 3
has comment: http://stackoverflow.com/comment/90783030
has comment: http://stackoverflow.com/comment/90783178
has comment: http://stackoverflow.com/comment/90783163
has comment: http://stackoverflow.com/comment/90783088
favorite count: 0
has title: How to make subprocess to press a key
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90783056
has comment: http://stackoverflow.com/comment/90783075
has comment: http://stackoverflow.com/comment/90783049
type: UnansweredQuestion
has body: I'm making a script and my app.py looks like this; import subprocess subprocess.call(["sudo", "apt-get", "update"]) subprocess.call(["sudo", "apt-get", "upgrade"]) And you might already know that this apt-gets are asking for a confirmation. I know I can put an extra -y at the end but I need to know how to make it so it presses enter when prompted. There are several prompts that doesn't accept -y so that's why I'm asking. For example; adding a repository or this screen when you run apt-get upgrade on Ubuntu 18.04 So I need to press Enter automatically for these prompts. Which should be something like in this concept; import subprocess subprocess.call(["sudo", "apt-get", "update"]) (PRESS ENTER HERE WHEN PROMPTED) subprocess.call(["sudo", "apt-get", "upgrade"]) (PRESS ENTER HERE WHEN PROMPTED WHICH ASKS YOU ABOUT 3 TIMES)
tagged with: python
has comment: http://stackoverflow.com/comment/90784387
score: 3
answer count: 0
tagged with: subprocess
downvote count: 0
linked to: http://stackoverflow.com/q/6264596
linked to: http://stackoverflow.com/q/31535592
type: Question
has comment: http://stackoverflow.com/comment/90783100
has comment: http://stackoverflow.com/comment/90784445

http://stackoverflow.com/q/51889346
upvote count: 3
type: Question
tagged with: opencv
tagged with: matplotlib
has title: Update matplotlib Pie in realtime
score: 3
answer count: 1
downvote count: 0
has body: This is my loop to detect and show gender and age. I am trying to plot this on matplotlib pie chart but everytime it runs the loop it opens up a different chart for every predictions. How do I update the same chart in realtime. Here I am updating the complete code The complete code for detecting age and gender of a person using Python and OpenCV. ``` import os import cv2 import dlib import numpy as np import argparse import inception_resnet_v1 import tensorflow as tf from imutils.face_utils import FaceAligner from imutils.face_utils import rect_to_bb import matplotlib.pyplot as plt def get_args(): parser = argparse.ArgumentParser(description="This script detects faces from web cam input, " "and estimates age and gender for the detected faces.", formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument("--weight_file", type=str, default=None, help="path to weight file (e.g. weights.18-4.06.hdf5)") parser.add_argument("--depth", type=int, default=16, help="depth of network") parser.add_argument("--width", type=int, default=8, help="width of network") args = parser.parse_args() return args def draw_label(image, point, label, font=cv2.FONT_HERSHEY_SIMPLEX, font_scale=1, thickness=2): size = cv2.getTextSize(label, font, font_scale, thickness)[0] x, y = point cv2.rectangle(image, (x, y - size[1]), (x + size[0], y), (255, 0, 0), cv2.FILLED) cv2.putText(image, label, point, font, font_scale, (255, 255, 255), thickness) def main(sess,age,gender,train_mode,images_pl): args = get_args() depth = args.depth k = args.width # for face detection detector = dlib.get_frontal_face_detector() predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat") fa = FaceAligner(predictor, desiredFaceWidth=160) # load model and weights img_size = 160 # cap video cap = cv2.VideoCapture(0) cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640) cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480) while True: # get video frame ret, img = cap.read() if not ret: print("error: failed to capture image…
favorite count: 0
has comment: http://stackoverflow.com/comment/90732144
has comment: http://stackoverflow.com/comment/90732025
has answer: http://stackoverflow.com/a/51889879
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90731768
tagged with: python

http://stackoverflow.com/q/51843474
tagged with: python
has title: What the most efficient way to search substring through a Pandas DataFrame?
upvote count: 4
answer count: 4
type: AnsweredQuestion
downvote count: 0
possible better answer: http://stackoverflow.com/a/51843947
has comment: http://stackoverflow.com/comment/90640548
has body: I have a Pandas Dataframe containing 75k rows of text (approx. 350 chars per row). I need to search the occurrences of a list of 45k substrings within that dataframe. Expected output is a authors_data dict containing the list of authors and the number of occurrences. Following code assumes I have a dataframe['text'] column and a list of substrings named authors_list. authors_data = {} for author in authors_list: count = 0 for i, row in df.iterrows(): if author in row.text: count += 1 authors_data[author] = count print(author, authors_data[author]) I ran some initial tests, 10 authors took me about 50 seconds. The complete table will take me a few days to run. So I'm looking at more time efficient ways to run the code. Is df.iterrows() fast enough? Are there any specific libraries that I should look into? Let me know!
linked to: http://stackoverflow.com/q/1374457
has comment: http://stackoverflow.com/comment/90640875
has answer: http://stackoverflow.com/a/51844355
linked to: http://stackoverflow.com/q/48541444
type: Question
has answer: http://stackoverflow.com/a/51843947
tagged with: dataframe
score: 4
has answer: http://stackoverflow.com/a/51844032
accepted answer: http://stackoverflow.com/a/51844032
has answer: http://stackoverflow.com/a/51844574
tagged with: pandas
tagged with: string
favorite count: 0
tagged with: series
has comment: http://stackoverflow.com/comment/90640177

http://stackoverflow.com/comment/90754945
type: QuestionComment
comment on: http://stackoverflow.com/q/51880227
score: 0
type: Comment
has text: @RolfofSaxony I found a selection method(answer below), but it makes an error. I explained the error under my answer.

http://stackoverflow.com/comment/90782420
type: AnswerComment
comment on: http://stackoverflow.com/a/51916148
score: 0
type: Comment
has text: @N.E Edited mine

visualization
tags question: http://stackoverflow.com/q/51927723
tags question: http://stackoverflow.com/q/51909715
tag name: visualization
tags question: http://stackoverflow.com/q/51824053
tags question: http://stackoverflow.com/q/51846948
type: Tag

http://stackoverflow.com/comment/90554668
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51799014
has text: there is a way for that

http://stackoverflow.com/comment/90769174
comment on: http://stackoverflow.com/q/51900158
score: 0
has text: Sorry, it is still not clear and your explanation in the comment above does not help.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51926091
tagged with: database-connection
upvote count: 2
type: UnansweredQuestion
tagged with: django
tagged with: python
has body: I'm trying to get my Django project running on a Windows 10 computer and it throws a very unspecific error when trying to establish a database connection. In this SO-post the problem was with the authentication, but in that post details about the error is displayed instead of &lt;\NULL> which gives very little to go on. The entire error looks like this: Unhandled exception in thread started by &lt;function check_errors.&lt;locals&gt;.wrapper at 0x0000018C3B8761E0&gt; Traceback (most recent call last): File "D:\Program\LiquidMarket\venv\lib\site-packages\django\db\backends\base\base.py", line 216, in ensure_connection self.connect() File "D:\Program\LiquidMarket\venv\lib\site-packages\django\db\backends\base\base.py", line 194, in connect self.connection = self.get_new_connection(conn_params) File "D:\Program\LiquidMarket\venv\lib\site-packages\django\db\backends\mysql\base.py", line 236, in get_new_connection return Database.connect(**conn_params) File "D:\Program\LiquidMarket\venv\lib\site-packages\MySQLdb\__init__.py", line 85, in Connect return Connection(*args, **kwargs) File "D:\Program\LiquidMarket\venv\lib\site-packages\MySQLdb\connections.py", line 204, in __init__ super(Connection, self).__init__(*args, **kwargs2) _mysql_exceptions.OperationalError: (2059, &lt;NULL&gt;) The above exception was the direct cause of the following exception: Traceback (most recent call last): File "D:\Program\LiquidMarket\venv\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "D:\Program\LiquidMarket\venv\lib\site-packages\django\core\management\commands\runserver.py", line 120, in inner_run self.check(display_num_errors=True) File "D:\Program\LiquidMarket\venv\lib\site-packages\django\core\management\base.py", line 364, in check include_deployment_checks=include_deployment_checks, File "D:\Program\LiquidMarket\venv\lib\site-packages\django\core\management\base.py", line 351, in _run_checks return checks.run_checks(**kwargs) File "D:\P…
has comment: http://stackoverflow.com/comment/90802830
score: 2
has answer: http://stackoverflow.com/a/53183955
tagged with: mysql
has comment: http://stackoverflow.com/comment/90801770
type: Question
has comment: http://stackoverflow.com/comment/90802023
downvote count: 0
linked to: http://stackoverflow.com/q/50469587
has comment: http://stackoverflow.com/comment/90802738
linked to: http://stackoverflow.com/q/51920779
answer count: 1
favorite count: 0
has title: Django mysqlclient backend produces django.db.utils.OperationalError: (2059, <NULL>) in Windows
tagged with: python-3.x

http://stackoverflow.com/q/51818807
has answer: http://stackoverflow.com/a/51819046
has answer: http://stackoverflow.com/a/51819101
has comment: http://stackoverflow.com/comment/90592142
answer count: 2
downvote count: 0
tagged with: string
favorite count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: python
tagged with: regex
tagged with: string-matching
score: 2
has body: I am building a regex to extract the header values from a forwarded email in Python. I am only interested in the first appearance of these kinds of headers in an email and I only want to capture the text parts appearing after the colons. From: ... Sent: ... To: ... Subject: ... The following regex works fine using re.search for most variations of the above format: (?:From\s*:\s*)(.*)(?:\n*)(?:Sent\s*:\s*)(.*)(?:\n*)(?:To\s*:\s*)(.*)(?:\n*)(?:Subject\s*:\s*) but sometimes, the different header parts are ordered differently and have missing elements, such as below: Sent: ... From: ... Subject: ... I thought I could use a positive lookahead to match the header format in any order but I could not get this to work. Does anyone have any idea how this can be done efficiently? Any help is greatly appreciated.
has title: Regex to capture different elements in unknown order of appearance in Python
type: Question
tagged with: regex-lookarounds
has comment: http://stackoverflow.com/comment/90593591

http://stackoverflow.com/a/51814218
score: 3
upvote count: 3
has body: Using a range-replacement gives a succinct piece of code: somestuff[-1:] = somestuff[-1].split('n') The trick is telling python that you want to replace a range of elements with a different range of elements. The question's example replaces a single element with a range.
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51814155
type: Answer
answers question: http://stackoverflow.com/q/51814155

http://stackoverflow.com/a/51921611
answers question: http://stackoverflow.com/q/51887958
accepted answer of: http://stackoverflow.com/q/51887958
upvote count: 1
type: AcceptedAnswer
type: Answer
downvote count: 0
has body: I finally found the answer. I have implemented a custom Lambda layer to handle reshaping. This layer has difficulties loading. Specifically, it reshapes one dimension into two dimensions on an arbitrary interval. The interval was defaulting to one specific value every time I loaded the model, even though it was incorrect. When I force it to be the correct interval, it works.
score: 1

networkx
tags question: http://stackoverflow.com/q/51798738
tag name: networkx
tags question: http://stackoverflow.com/q/51869509
tags question: http://stackoverflow.com/q/51935565
tags question: http://stackoverflow.com/q/51916525
tags question: http://stackoverflow.com/q/51813775
tags question: http://stackoverflow.com/q/51817984
tags question: http://stackoverflow.com/q/51902156
type: Tag
tags question: http://stackoverflow.com/q/51933046
tags question: http://stackoverflow.com/q/51933464
tags question: http://stackoverflow.com/q/51912187
tags question: http://stackoverflow.com/q/51865003
tags question: http://stackoverflow.com/q/51914087
tags question: http://stackoverflow.com/q/51912481

http://stackoverflow.com/comment/90831950
has text: @Kristada673 Is the expected plot: [This plot](https://i.sstatic.net/IwnRW.png)
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51941038

http://stackoverflow.com/comment/90666241
type: QuestionComment
has text: Is there a question you want to ask? We are not going to write the code for you
score: 1
type: Comment
comment on: http://stackoverflow.com/q/51856849

http://stackoverflow.com/q/51809854
has title: Python Pillow upsize using bar lines
type: UnansweredQuestion
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/90575089
has comment: http://stackoverflow.com/comment/90574960
type: Question
has body: I am looking if there is a possible way to inside of python's pillow (I would be open to using others if it is needed) to upscale/resize a photo that is smaller than what is needed (or wrong aspect ratio). Without having the loss on the actual resolution on the original photo. Ex if the original photo was 720 high but I needed it a total of 1080 high it would add two different white bars on the top and bottom at 180 pixels high each. If it is possible it would help if the bar lines were white, as it would blend into a site I am uploading them onto. Thanks in Advance!
tagged with: python-imaging-library
score: 0
linked to: http://stackoverflow.com/q/30227466

http://stackoverflow.com/comment/90707553
type: Comment
comment on: http://stackoverflow.com/a/51878007
has text: Worth noting this solution requires your input to be sorted.
type: AnswerComment
score: 1

http://stackoverflow.com/q/51954806
tagged with: pandas
tagged with: python
has answer: http://stackoverflow.com/a/51954944
has comment: http://stackoverflow.com/comment/90860277
score: 0
answer count: 1
has title: How to do columnwise operations in pandas?
has body: I have a dataframe that looks something like: sample parameter1 parameter2 parameter3 A 9 6 3 B 4 5 7 C 1 5 8 and I want to do an operation that does something like: for sample in dataframe: df['new parameter'] = df[sample, parameter1]/df[sample, parameter2] so far I have tried: df2.loc['ratio'] = df2.loc['reads mapped']/df2.loc['raw total sequences'] but I get the error: KeyError: 'the label [reads mapped] is not in the [index]' when I know well that it is in the index, so I figure I am missing some concept somewhere. Any help is much appreciated! I should add that the parameter values are floats, just in case that is a problem as well!
tagged with: dataframe
accepted answer: http://stackoverflow.com/a/51954944
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/36619631
has comment: http://stackoverflow.com/comment/90860171
has comment: http://stackoverflow.com/comment/90861396
type: Question

http://stackoverflow.com/a/51965664
downvote count: 0
answers question: http://stackoverflow.com/q/51932783
accepted answer of: http://stackoverflow.com/q/51932783
has body: The answer was simple even when i searched for two days: files = dbutils.fs.ls('mnt/dbfolder1/projects/clients') for fi in files: print(fi.path)
score: 20
type: AcceptedAnswer
upvote count: 20
type: Answer

http://stackoverflow.com/q/51953082
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/90856642
tagged with: python
has answer: http://stackoverflow.com/a/51955656
score: -1
has comment: http://stackoverflow.com/comment/90856912
upvote count: 2
downvote count: 3
has title: preserve unicode characters with json.loads() or convert them back to when doing a json.dumps()
answer count: 1
tagged with: http://stackoverflow.com/tag/json
type: UnansweredQuestion
has body: I have a json file that contains the unicode characters \u003c and \u003e. When loading the file with json.load() these characters get converted to &lt; and &gt;. Consider the following experiment: d = json.loads('"Foo \u003cfoo@bar.net\u003e"') Which then prints like: 'Foo &lt;foo@bar.net&gt;' Say that I need to dump this back to a file and need to have the characters &lt; and &gt; converted back to \u003c and \u003e. I am currently using f.write(json.dumps(d)) but that does not seem to work. I have searched for hours but am just not able to figure this out.
has comment: http://stackoverflow.com/comment/90856627

http://stackoverflow.com/comment/90699848
score: 0
type: AnswerComment
type: Comment
has text: @THEODOROPOULOSDIMITRIS I have little experience in neural network, But I think you can initialize it with `None`
comment on: http://stackoverflow.com/a/51871743

http://stackoverflow.com/comment/90805913
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51927912
has text: I just edited it. I added sentence.split() because before it was checking each character rather than each word.

http://stackoverflow.com/q/51935097
has title: Is it okay to have non-trainable params in machine learning?
tagged with: keras
favorite count: 0
linked to: http://stackoverflow.com/q/47312219
type: Question
tagged with: python
accepted answer: http://stackoverflow.com/a/51935438
has comment: http://stackoverflow.com/comment/90820313
has body: When building a model for machine learning, is it okay to have non-trainable params? Or does this create errors in the model? I'm confused as to what non-trainable params actually are and how to fix your model based on that.
has comment: http://stackoverflow.com/comment/91409122
answer count: 2
downvote count: 2
tagged with: machine-learning
has comment: http://stackoverflow.com/comment/90821197
upvote count: 5
tagged with: hyperparameters
has answer: http://stackoverflow.com/a/51935438
possible better answer: http://stackoverflow.com/a/51935221
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/51935221

http://stackoverflow.com/a/51845643
upvote count: 1
downvote count: 1
has body: One way of doing it would be to do this: all_res = pd.DataFrame() file_list = ['C:/file1_USA_Car_1d.txt', 'C:/file3_USA_Car_1m.txt', 'etc'] for file_name in file_list: tmp = pd.read_csv(file_name) tmp['file_name'] = file_name all_res = all_res.append(tmp) all_res = all_res.reset_index()
type: Answer
answers question: http://stackoverflow.com/q/51845613
has comment: http://stackoverflow.com/comment/90644812
score: 0

http://stackoverflow.com/q/51851404
tagged with: pandas
has comment: http://stackoverflow.com/comment/90665977
has comment: http://stackoverflow.com/comment/90656516
type: UnansweredQuestion
has title: Python Pandas Importing XML File
tagged with: python
has body: Situation: I have a ".txt" file that contains xml data. I want to read this file in python. I am using the following: df = pd.read_csv("name_of_file.txt", sep='lasagna', header=None) The file contains 3242 rows. The dataframe contains 3181 rows. I made my the sep value equal to lasagna because I wanted the delimiter to not actually work and import everything as 1 column. What could I be doing wrong?
answer count: 0
type: Question
score: 0

http://stackoverflow.com/comment/90727509
type: Comment
comment on: http://stackoverflow.com/a/51888190
score: 0
type: AnswerComment
has text: I have updated the question kindly have a look on split `time` approach @user2906838

http://stackoverflow.com/comment/90690949
type: QuestionComment
has text: Why do you print your information? You should yield a dictionary with all of the items and then you can save it all data as json or csv file: `scrapy crawl spider -o output.json`
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51867348

http://stackoverflow.com/a/51990324
score: 1
downvote count: 0
type: Answer
has body: There are 2 issues. First, you need to add .async(callback_function_here) to your publish line. Also, your channel name contains spaces, which is invalid. Channel name constraints are listed here: Valid PubNub Channel Names This code should work: from pubnub.callbacks import SubscribeCallback from pubnub.enums import PNStatusCategory from pubnub.pnconfiguration import PNConfiguration from pubnub.pubnub import PubNub pnconfig = PNConfiguration() pnconfig.subscribe_key = '&lt;sub key&gt;' pnconfig.publish_key = '&lt;pub key&gt;' pnconfig.ssl = False pubnub = PubNub(pnconfig) def publish_callback(result, status): pass # Handle PNPublishResult and PNStatus pubnub.publish().channel('MyDemoChannel').message({"text": "Message from my_view()"}).async(publish_callback)
upvote count: 1
answers question: http://stackoverflow.com/q/51924095

http://stackoverflow.com/comment/90797531
score: 0
comment on: http://stackoverflow.com/a/51865989
type: AnswerComment
type: Comment
has text: .describe is autodataframe of values shown in thr poc above how can I apply round into the .describe func?

http://stackoverflow.com/q/51915150
score: 0
has comment: http://stackoverflow.com/comment/90781279
tagged with: jquery
has comment: http://stackoverflow.com/comment/90785182
has title: django datatable with Ajax print all data of queryset in webpage
tagged with: ajax
type: UnansweredQuestion
tagged with: django
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/90781494
type: Question
has body: I am shifting from plain html datatable to datatable with ajax in django (because after loading large data, page with stretch and take time to fetch all data) here are my codes : model.py : class myModel(models.Model): date = models.CharField(max_length=8) rnc = models.CharField(max_length=8,primary_key=True) mo = models.CharField(max_length=100) parameterid = models.CharField(max_length=100) before_value = models.CharField(max_length=40) class Meta: db_table = "changed_para" urls.py urlpatterns = [ path('changed_para_json', views.changed_para_json, name='my_ajax_url'), ] views.py from django.http import HttpResponse from django.core import serializers from polls.models import myModel def changed_para_json(request): if request.POST.get("fetchdata"): Date=request.POST["Date"] RNC=request.POST["RNC"] MO=request.POST["MO"] parameterid=request.POST["parameterid"] else: Date='2018-07-20' RNC='RRRNCH02' MO='CORRMALGOSWITCH' parameterid='DRASWITCH_DRA_VOICE_SAVE_CE_SWITCH' current_time=datetime.date.today() para = myModel.objects.using('rnc_parameters').all() json = serializers.serialize('json', para) object_list = myModel.objects.using('rnc_parameters').all() #or any kind of queryset json = serializers.serialize('json', object_list) return HttpResponse(json, content_type='application/json') changed_para_json.html Date RNC MO parameterid value Before Issue is that , I am getting all serialized json output from views.py in the output. this is the output in web : [{"model": "polls.myModel", "pk": "KRRNCH03", "fields": {"date": "2018-07-09", "mo": "FRC", "parameterid": "ECN0THSFOR2MSTO10MS", "before_value": "37"}}, {"model": "polls.myModel", "pk": "KRRNCH03", "fields": {"date": "2018-07-09", "mo": "FRC", "parameterid": "ECN0THSFOR2MSTO10MSCSPS", "before_value": "37"}}, {"model": "polls.myModel", "pk": "RRRNCH02", "fields": {"date": "2018-07-11", "mo": "INTERRATHOCOV", "parameterid": "INTERRATCSTHD2DECN0", "before_value": "-17"}}, {"model": "polls.myModel", "pk": "RRRNCH02", "…
tagged with: javascript
has comment: http://stackoverflow.com/comment/90785336

http://stackoverflow.com/comment/90790436
comment on: http://stackoverflow.com/a/51920270
has text: Thanks, i'll take a look on this.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/90861500
comment on: http://stackoverflow.com/q/51955466
score: 2
has text: Well did you expect this function to work exactly the same regardless of the arguments you pass to it? Have you looked at the [corresponding docs](https://docs.python.org/3.7/library/timeit.html#timeit.timeit)? What do they say about the number argument?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90725226
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/51886652
has text: @juanpa.arrivillaga actually, it _was_ a statement. It has been made into a function in Python 3.x. Thanks for the reminder. Old habits die young, like they say.

http://stackoverflow.com/a/52170125
answers question: http://stackoverflow.com/q/51873510
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51873510
type: Answer
score: 0
has body: Sorry for the late reply, but I didn't have time to work on it before. The problem was caused by numba. I was using it with the parallel=True flag to parallelise one of the loops and that caused the error.

http://stackoverflow.com/comment/90699648
score: 0
type: Comment
type: QuestionComment
has text: Alright. fixed.
comment on: http://stackoverflow.com/q/51874026

http://stackoverflow.com/q/51857030
has body: So I'm trying to share data between two threads in a continuous way. The program should keep running until asked to stop. The problem I have is with the queue. Normally it should be inside the while loop in the get_ratio function. But when I put it there I get the error: 'numpy.complex128' object has no attribute 'get'. Also when I put it before the while loop it treats only part of the data because it's before the loop. I don't know how to keep getting data from the queue. Any ideas? import time import random import threading as th import Queue import numpy as np import matplotlib.pyplot as plt import bluetooth import scipy.fftpack from MindwaveDataPoints import RawDataPoint from MindwaveDataPointReader import MindwaveDataPointReader def get_data(q): mindwaveDataPointReader = MindwaveDataPointReader() mindwaveDataPointReader.start() data=[] while(1): dataPoint = mindwaveDataPointReader.readNextDataPoint() if (dataPoint.__class__ is RawDataPoint): data.append(dataPoint) q.put(data) #data keeps going into the queue def get_ratio(q): M = [[],[],[],[],[],[],[],[]] fft_avg = [] fft_avg_mod = [] #loop to cover all the data j=0 k=0 l=0 data = q.get() #HERE while(1): #data = q.get() #HERE if k &gt; 7 : fft_avg[:] = [] fft_avg_mod[:] = [] fft_avg = [(x+y+z+t+u+v+w+q)/8 for x,y,z,t,u,v,w,q in zip(M[0],M[1],M[2],M[3],M[4],M[5],M[6],M[7])] fft_avg_mod = [ abs(x) for x in fft_avg] if fft_avg_mod: d=random.randint(8,14) e=random.randint(14,20) alpha=fft_avg_mod[d] beta=fft_avg_mod[e] ratio=beta/alpha print 'ratio' , ratio f=k%8 M[f] = np.fft.fft(data[j:j+32]) j = j + 32 k = k + 1 if __name__ == '__main__': q = Queue.Queue(maxsize=0) try: threadLock = th.Lock() threads=[] thread1=th.Thread( target=get_data, args=(q,)) thread2=th.Thread( target=get_ratio, args=(q,)) thread1.start() print 'T1 started' time.sleep(10) thread2.start() print 'T2 started' threads.append(thread1) threads.append(thread2) for t in threads: t.join() except: print "Error: unable to start thread"
tagged with: python
type: UnansweredQuestion
tagged with: multithreading
has answer: http://stackoverflow.com/a/51857113
type: Question
tagged with: queue
has title: Python: Sharing continuous data between threads
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/90667701
has answer: http://stackoverflow.com/a/51857103
has comment: http://stackoverflow.com/comment/90666420

http://stackoverflow.com/comment/90795168
type: AnswerComment
has text: Of course I can, but that's not the point. I was wondering if it is possible via .css or .xpath. So, do you think Pandas will get it done?
comment on: http://stackoverflow.com/a/51922740
type: Comment
score: 0

http://stackoverflow.com/a/51810361
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51809957
has body: A recursive function call is just another function call, there is nothing special about such calls, really. You call a function, and when it returns, you use the result of that call. With recursion, what happens is that there is a stack of calls, one calling another calling another until eventually a function returns a result, and thus the first, outer calls may have to wait a while before it can continue with the result given. In your example, permute1() always returns a list (return [seq] at the top, or return res further down), so for x in ... loops over that result (once the recursive call returns) and uses each tuple in the result to prepend a single-element tuple to it (res[i:i + 1] slices a tuple to contain just a single element, the one at index i). When you call the function with an empty tuple, the function return immediately: &gt;&gt;&gt; permute1(()) [()] This is the one stage where there is no recursive call, and that's important! It's how recursion ends! The other block creates a new list of elements from seq, using rest = seq[:i] + seq[i+1:]. That's a tuple with one element removed, that at index i: &gt;&gt;&gt; seq (1, 2, 3) &gt;&gt;&gt; seq[:1] + seq[2:] # if i is 1, then.. (1, 3) If you call permute1() with a single element tuple, then for i in range(len(seq)) loops just once, with i = 0. That means that res is set to an empty tuple (a tuple of length one with 1 element removed is an empty tuple), and thus there is a single permute1(()) call made. We saw above that that just returns [()], and you end up with seq[i:i+1] + x added to res, and the function returns. So a call with a single element in it makes one recursive call, and returns a list with a single tuple, essentially the same as what you started with: &gt;&gt;&gt; permute1((1,)) [(1,)] With 2 elements, the loop iterates twice, calls permute1() twice with a single element tuple, which does the above. Those two calls each result in a list with 1 element, so you end up with res with two new t…
type: Answer
accepted answer of: http://stackoverflow.com/q/51809957
score: 0

http://stackoverflow.com/q/51875012
has answer: http://stackoverflow.com/a/51877241
tagged with: python
has title: Matching string from one dataframe which is a partial string in the 2nd dataframe
score: 0
tagged with: match
answer count: 1
has body: I have two dataframes and I'm trying to find if a partial string (filename) from one dataframe g exists in a full string (full filename) in dataframe d and update a match column in the original dataframe g. g = pd.DataFrame([['c:\\ythisFile.pdf', 'thisFile.pdf'], ['c:\\ythatFile.exe', 'thatFile.exe'], ['c:\\ytheOtherFile.zip', 'theOtherFile.zip']], columns=['FULL_FILE', 'FILENAME']) d = pd.DataFrame([['c:\\zthis_File.pdf', 'this_File.pdf'], ['c:\\zthatFile.exe', 'thatFile.exe'], ['c:\\ztheOtherFile.zip', 'ssss.zip']], columns=['FULL_FILE', 'FILENAME']) e.g. I'm essentially trying to do a look up of d.FILENAME in g.FULL_FILE I've tried d[d.FILENAME.isin(g.FULL_FILE)] but this gives an error, I assume because it's looking for a full match I've tried the below but that seems to match more than all of g.FILENAME in d.FULL_FILE. g = g.merge(d, left_on = g.FILENAME.str.extract('(\d+)', expand = False), right_on = d.FULL_FILE.str.extract('(\d+)', expand = False), how = 'inner') The overall aim is to:- 1. Match the g.FULL_FILE against d.FULL_FILE column. 2. If no match, match g.FILENAME if it exists as partial string match in d.FULL_FILE column 3. If no match still, check last 10 chars for match from g.FILENAME column in d.FULL_FILE column (incase there are special characters in the g.FULL_FILE) Please help. I've done hours of research and can find solutions for some similar solutions but not exactly this and having trouble adapting those to this problem.
type: UnansweredQuestion
tagged with: dataframe
tagged with: pandas
has comment: http://stackoverflow.com/comment/90701548
tagged with: partial
type: Question

http://stackoverflow.com/a/51898557
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51898361
answers question: http://stackoverflow.com/q/51898361
type: Answer
has body: If you just want to convert the str to int s.astype(float).astype(int) Out[213]: 0 312 dtype: int32
score: 2
downvote count: 0
upvote count: 2

http://stackoverflow.com/comment/90997103
score: 0
comment on: http://stackoverflow.com/a/51941129
type: AnswerComment
type: Comment
has text: Thank you for the information .. I am going to work on KUDU i ll update soon. Just a thought how DSVM ?

http://stackoverflow.com/comment/90714692
comment on: http://stackoverflow.com/q/51881603
score: 0
type: Comment
type: QuestionComment
has text: You don't have an array of classes, you have a list of instances.

http://stackoverflow.com/q/51804202
has comment: http://stackoverflow.com/comment/90564551
downvote count: 0
tagged with: flask
has body: I am working on a web application with a create-react-app frontend and a Flask API backend with Flask-RESTful. I built the app locally and it works on my computer, but now I am unsuccessfully trying to deploy it to Heroku. I deployed the Flask backend and the React frontend as two different Heroku dynos, so each one has their own URL. When I go to the URL for the frontend, it appears to be working fine, and the backend URL seems to work too. However, the app relies on API calls to the backend, and I am having trouble successfully sending requests to my backend. When I was working locally, I would run the flask backend with the gunicorn --bind 0.0.0.0:8000 app:app and the frontend with the npm start command. The app worked fine with relative calls in my Axios function calls as long as I put "proxy": "https://localhost:8000" in my package.json file in my frontend app. In general, I followed this tutorial: https://www.fullstackreact.com/articles/using-create-react-app-with-a-server/. I thought I could simply edit the proxy field in the package.json file to point to the URL of my backend Heroku app, and then I wouldn't have to change anything else. However, when I deploy using this, I find that the requests to my endpoint are being made to https://my-frontend-app.herokuapp.com/&lt;endpoint&gt; instead of https://my-backend-app.herokuapp.com/&lt;endpoint&gt;. Here is my package.json: { "name": "heroku-app", "version": "0.1.0", "private": true, "dependencies": { "axios": "^0.18.0", "bootstrap": "^4.1.2", "plotly.js": "^1.39.2", "react": "^16.4.1", "react-dom": "^16.4.1", "react-plotly.js": "^2.2.0", "react-scripts": "1.1.4", "reactstrap": "^6.3.0" }, "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test --env=jsdom", "eject": "react-scripts eject" }, "proxy": "https://star-employees-api.herokuapp.com" } My requests look like this: axios.get('/analyze', data) .then((response) =&gt; { // Handle request response here }; Can …
favorite count: 0
answer count: 1
has answer: http://stackoverflow.com/a/51869342
has comment: http://stackoverflow.com/comment/90579049
tagged with: create-react-app
has comment: http://stackoverflow.com/comment/90564408
upvote count: 3
accepted answer: http://stackoverflow.com/a/51869342
has title: Proxying API request from React frontend to Flask backend on two separate Heroku apps
tagged with: python
tagged with: heroku
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/90564363
type: Question
tagged with: reactjs

http://stackoverflow.com/q/51866324
has answer: http://stackoverflow.com/a/51902012
downvote count: 0
favorite count: 0
upvote count: 2
tagged with: seaborn
type: UnansweredQuestion
has title: How to edit the median line and add an average to seaborn.boxenplot() using subplots?
tagged with: python
score: 2
has body: I am using the seaborn boxenplot / letter-value plot inside two subplots like this data = np.random.randn(100, 5) fig, ax = plt.subplots(figsize=(12,8), ncols=1, nrows=2, gridspec_kw={'height_ratios':[len(mat_cat), 1]}) sns.set_style('whitegrid') sns.boxenplot(data=data[:][:4], ax=ax[0], orient='h') sns.boxenplot(data=data[:][5], ax=ax[1], orient='h') ax[0].set_xlim(-3, 3) ax[1].set_xlim(-2, 2) Now I would like to edit the appearance of the median dash (e.g. a red line instead of black) and also add the mean (e.g. as a dashed blue line) inside the plots. However I cannot figure out how to do that. For instance, when I do something like ax[0].plot() the boxes get plotted on top of each other. Any ideas? Update I figured out how to edit the existing median. If I add the following code the median dash of the upper sub-plot will become dashed, red, and 20% transparent. for l in ax[0].lines: l.set_linestyle('--') l.set_color('r') l.set_alpha(0.8)
tagged with: matplotlib
type: Question
answer count: 1

http://stackoverflow.com/q/51902317
has answer: http://stackoverflow.com/a/51909018
has answer: http://stackoverflow.com/a/51903560
tagged with: python
tagged with: c++
type: UnansweredQuestion
upvote count: 1
tagged with: stl
score: 1
type: Question
has title: c++ stl - manually using standard gdb pretty printers
answer count: 2
tagged with: gdb
has body: How can i use StdVectorPrinter of https://github.com/gcc-mirror/gcc/blob/gcc-6_3_0-release/libstdc%2B%2B-v3/python/libstdcxx/v6/printers.py to create my own output style? I.e. use the existing tools for element access, but drive the output on my own. E.g. for #include &lt;string&gt; #include &lt;vector&gt; #include &lt;iostream&gt; int main(int, char**) { std::vector&lt;std::string&gt; data = { "hello", "world", "all", "is", "fine" }; for ( auto &amp;&amp; i : data) { std::cout &lt;&lt; i &lt;&lt; std::endl; } return 0; } The output shall not be (gdb) p data $2 = std::vector of length 5, capacity 5 = {"hello", "world", "all", "is", "fine"} But (gdb) p data $2 = "hello|world|all|is|fine" Where is the skeleton code for the generic printer, that uses the StdVectorPrinter (e.g.)?
downvote count: 0
favorite count: 0

file
type: Tag
tags question: http://stackoverflow.com/q/51851986
tags question: http://stackoverflow.com/q/51809684
tags question: http://stackoverflow.com/q/51884992
tags question: http://stackoverflow.com/q/51912655
tags question: http://stackoverflow.com/q/51889248
tags question: http://stackoverflow.com/q/51819441
tags question: http://stackoverflow.com/q/51933929
tag name: file
tags question: http://stackoverflow.com/q/51919806
tags question: http://stackoverflow.com/q/51808908
tags question: http://stackoverflow.com/q/51849100
tags question: http://stackoverflow.com/q/51949660
tags question: http://stackoverflow.com/q/51923891
tags question: http://stackoverflow.com/q/51900524
tags question: http://stackoverflow.com/q/51890755
tags question: http://stackoverflow.com/q/51894182
tags question: http://stackoverflow.com/q/51937252
tags question: http://stackoverflow.com/q/51847992
tags question: http://stackoverflow.com/q/51901789
tags question: http://stackoverflow.com/q/51902250
tags question: http://stackoverflow.com/q/51890834
tags question: http://stackoverflow.com/q/51950380
tags question: http://stackoverflow.com/q/51821988
tags question: http://stackoverflow.com/q/51951604
tags question: http://stackoverflow.com/q/51804592
tags question: http://stackoverflow.com/q/51880258
tags question: http://stackoverflow.com/q/51823337
tags question: http://stackoverflow.com/q/51808970
tags question: http://stackoverflow.com/q/51885092
tags question: http://stackoverflow.com/q/51821166
tags question: http://stackoverflow.com/q/51924729
tags question: http://stackoverflow.com/q/51805159
tags question: http://stackoverflow.com/q/51801213

http://stackoverflow.com/comment/90729334
score: 0
has text: thanks @mcoav, but i am having a issue there, while i am printing to postscript file the nodes of tree are populated with some numbers and values in leaves are also some strange words, i will upload output in question , please have a look on it
type: AnswerComment
comment on: http://stackoverflow.com/a/51880916
type: Comment

http://stackoverflow.com/comment/90622185
type: Comment
type: QuestionComment
score: 0
has text: The file itself is not semi-colon separated. I just copy and pasted from the file.
comment on: http://stackoverflow.com/q/51833922

http://stackoverflow.com/comment/91657593
has text: @TimPeters, incredible work!!! I worked on this problem for far too long and when I came back to the post (I lied since I promised I would not return until I had completed a working implementation (see my comment Leon's post)), to my delight, you had put together a beautiful array of ideas. Even if we still don't have the _perfect_ solution, your work here has laid a strong foundation for such a solution.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51887027
type: Comment

http://stackoverflow.com/a/51958766
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/51953748
score: 1
has body: seems that np.einsum could do this x = np.arange(5*12).reshape(5,4,3) np.einsum("nik, njk-&gt;nij", x, x)
downvote count: 0

http://stackoverflow.com/comment/90817320
type: Comment
has text: What do you mean by 'email ID'? right now you are connecting user objects as foreign keys and those contain every information about the user connected. Perhaps are you referring to the pk, primary key, of the user?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51933362

urllib
tags question: http://stackoverflow.com/q/51941638
tags question: http://stackoverflow.com/q/51881490
type: Tag
tags question: http://stackoverflow.com/q/51900020
tag name: urllib
tags question: http://stackoverflow.com/q/51846955
tags question: http://stackoverflow.com/q/51846867
tags question: http://stackoverflow.com/q/51915941
tags question: http://stackoverflow.com/q/51879954
tags question: http://stackoverflow.com/q/51948191
tags question: http://stackoverflow.com/q/51805104
tags question: http://stackoverflow.com/q/51815528
tags question: http://stackoverflow.com/q/51826131
tags question: http://stackoverflow.com/q/51863740
tags question: http://stackoverflow.com/q/51890074
tags question: http://stackoverflow.com/q/51819667

http://stackoverflow.com/comment/90574035
type: QuestionComment
has text: Also, have a look at [formatting](https://stackoverflow.com/editing-help).
score: 0
comment on: http://stackoverflow.com/q/51809437
type: Comment

http://stackoverflow.com/comment/90683185
has text: It is a Python Script which performs certain action on my computer. Sometimes, the script continues to next step before the previous step is fully complete. So, I want to add time delay at every step so that it executes correctly. It is working with time delay, but I will end up adding 'time.sleep(2)' at every line. Just wondering if there is a better way?
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51865326

http://stackoverflow.com/q/51891651
has comment: http://stackoverflow.com/comment/90734391
tagged with: python
score: 0
accepted answer: http://stackoverflow.com/a/51892544
has comment: http://stackoverflow.com/comment/90734376
upvote count: 1
downvote count: 1
answer count: 1
has body: There are two dataframes, df_A and df_B df_A Out[61]: A B 0 1 10 1 2 60 2 3 40 df_B Out[62]: A B D 0 1 5 10 1 1 10 25 2 1 20 60 3 2 5 10 4 2 10 25 5 2 20 60 6 3 10 20 7 3 15 40 8 3 25 80 Now I need to left join df_A and df_B on column A and B, the tricky part is df_B is to be considered as follows df_B Out[64]: A B D 0 1 [5,10) 10 1 1 [10,20) 25 2 1 [20:) 60 3 2 [5,10) 10 4 2 [10,20) 25 5 2 [20:) 60 6 3 [10,15) 20 7 3 [15,25) 40 8 3 [25:) 80 So for values of B greater than equal to 5 and less than 10, value '10' should be returned when df_A['A'] == 1 My output dataframe should be like this df_C Out[66]: A B D 0 1 10 25 1 2 60 60 2 3 40 80
has title: Interval look-up on pandas DataFrame
has comment: http://stackoverflow.com/comment/90734789
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51892544
favorite count: 0
type: Question
tagged with: pandas

http://stackoverflow.com/a/51887297
answers question: http://stackoverflow.com/q/51887004
accepted answer of: http://stackoverflow.com/q/51887004
type: AcceptedAnswer
score: 0
type: Answer
has body: Your code would work fine when you use the below. It is a pycharm issue and you can solve the pycharm issue by doing this from django.db import models from book.models import Book class Cart: books = models.ManyToManyField(Book)

http://stackoverflow.com/comment/90828346
type: QuestionComment
has text: TIF supports *"min is black"* or *"min is white"* in its *Photometric Interpretation* tag. It may be that Python `imageio` does not respect that. Try using `tiffump` on your input and output files, or **ImageMagick** `identify -verbose image.tif` to check.
score: 0
comment on: http://stackoverflow.com/q/51939014
type: Comment

http://stackoverflow.com/comment/90781000
comment on: http://stackoverflow.com/a/51866819
has text: Solved. Problem was that the .children couldn't find the id_pk field because it was a child of a p tag, so I just added another .children() to the script and it worked. Thanks again!
type: AnswerComment
type: Comment
score: 1

http://stackoverflow.com/q/51935179
has answer: http://stackoverflow.com/a/63110422
type: AnsweredQuestion
score: 10
has comment: http://stackoverflow.com/comment/90851826
upvote count: 10
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/90820507
has comment: http://stackoverflow.com/comment/90820579
tagged with: pandas
linked to: http://stackoverflow.com/q/44603119
downvote count: 0
favorite count: 0
possible better answer: http://stackoverflow.com/a/63110422
has comment: http://stackoverflow.com/comment/90823332
tagged with: data-visualization
has title: Best way to show interactive table with python (columns adjustably by user)
tagged with: python
has body: What are some good options to show a nice interactive table (2d) with python3? Id like the user to be able to sort the rowns (eg by clicking a column header), show/hide columns etc. Ideally without having to use (undebuggable) jupyter notebooks. If Im not incorrect it seems a lot easier to do this with jupyter notebooks than with "regular" python. Why is this? Calling something like pandas.head() automatically displays a proper gui if you set %matplotlib inline ? Thanks in advance
has answer: http://stackoverflow.com/a/51951364
accepted answer: http://stackoverflow.com/a/51951364
has comment: http://stackoverflow.com/comment/90821986

http://stackoverflow.com/a/51803443
has comment: http://stackoverflow.com/comment/90576187
type: Answer
score: 6
answers question: http://stackoverflow.com/q/51803008
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51803008
has body: You can submit values from the HTML form only using &lt;input&gt; elements. So, you need to either convert your &lt;td name="..."&gt; elements to &lt;input&gt;s or add a hidden input near each &lt;td&gt;: ... &lt;td name="bookid"&gt;{{ book.id }}&lt;/td&gt; &lt;input type="hidden" name="bookid" value="{{ book.id }}" /&gt; &lt;td name="bookisbn"&gt;{{ book.isbn }}&lt;/td&gt; &lt;input type="hidden" name="bookisbn" value="{{ book.isbn }}" /&gt; ...
type: AcceptedAnswer
upvote count: 6

http://stackoverflow.com/comment/90691849
comment on: http://stackoverflow.com/q/51870168
has text: http://prntscr.com/kj6new Nazar Khan, This is where it says i am getting my errors.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/51914151
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/90796360
downvote count: 0
has body: Python has a csv module which might make things easier. If you're running into memory problems, I'd suggest doing a forced garbage collection. You do import gc and then in the loop, a gc.collect(). It's probably not required every loop, and would even slow things down if done too frequently. You could keep a counter variable (rowcount would do) and do it less frequently (every 10,000 loops, say. Experiment.). Consider adding a print statement indicating the collection happening and the row number. That way you can tell if the script is still running or if it has locked up. if rowcount % 10000 == 0: print 'collecting', rowcount gc.collect() If you can install external Python modules, you could also try using Pandas to load the csv file. It probably performs better for very large files, but you might have to specify a chunksize if you're still running out of memory.
score: 1
answers question: http://stackoverflow.com/q/51914080
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51914080

http://stackoverflow.com/a/51882666
has comment: http://stackoverflow.com/comment/90717268
has comment: http://stackoverflow.com/comment/90717779
upvote count: 1
has comment: http://stackoverflow.com/comment/90735402
has comment: http://stackoverflow.com/comment/90717913
score: 1
has comment: http://stackoverflow.com/comment/90717994
has comment: http://stackoverflow.com/comment/90717353
has comment: http://stackoverflow.com/comment/90718382
has comment: http://stackoverflow.com/comment/90717519
downvote count: 0
answers question: http://stackoverflow.com/q/51882486
has comment: http://stackoverflow.com/comment/90717220
has comment: http://stackoverflow.com/comment/90717153
type: Answer
has comment: http://stackoverflow.com/comment/90718839
has comment: http://stackoverflow.com/comment/90717338
has body: thread and multiprocessing are not at all interchangeable. thread still uses the Global Interpreter Lock behind the scenes and thus it is much easier to share variables between threads whereas multiprocessing does not use the GIL and thus can run into conflicts much easier. A better way to do this would be returning result of do_stuff then compiling the results together. Look at the documentation here: https://docs.python.org/2/library/multiprocessing.html#using-a-pool-of-workers In your case it looks like you should use it like this: from multiprocessing import Pool def do_stuff(idx): for i in items[idx:idx+20]: # do stuff with idx items = # a huge nested list pool = Pool(5) multiple_results = [pool.apply_async(do_stuff, i) for i in range(0, len(items), 20)] multiple_results = [res.get(timeout=1) for res in multiple_results] edit on basis of comment: from multiprocessing import Pool def do_stuff(items): for i in items: # do stuff with idx items = # a huge nested list pool = Pool(5) pool.map(do_stuff, [x for x in items[::20]]) #generating a list of lists of twenty items for each thread to work on pool.close() pool.join()

http://stackoverflow.com/comment/90576804
has text: First you need to understand how functions work... it makes no sense to have a `width` and a `height` parameter in that function.
comment on: http://stackoverflow.com/q/51810877
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/comment/90814693
type: Comment
comment on: http://stackoverflow.com/q/51931752
type: QuestionComment
score: 0
has text: @BearBrown This actually works, stupid me. Thanks!

http://stackoverflow.com/a/51940461
score: 1
upvote count: 1
has body: Category.html {% block content %} {{ Categories }} Topics: {% for topic in topics %} {{ topic }} {% empty %} No categories entered yet. {% endfor %} {% endblock content %} it's topic.id not entry.id,there is not var named entry in Category.html.
accepted answer of: http://stackoverflow.com/q/51940415
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51940415
type: Answer
has comment: http://stackoverflow.com/comment/90830833

http://stackoverflow.com/q/51805471
type: UnansweredQuestion
has title: Tranform HSV mask into a set of points
tagged with: python
tagged with: video-processing
has body: I created a HSV mask from the image. The result is like the following: I hope that this mask can be represented by a set of points. My original idea was to use Skimage Skeletonize to create a line and then use the sliding window to calculate the local mean for point creation. However, skeletonize takes too long. It requires 0.4s for each frame. This is not a good idea for video processing.
type: Question
tagged with: opencv
tagged with: algorithm
tagged with: image-processing
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/90568169
has answer: http://stackoverflow.com/a/51992300
has answer: http://stackoverflow.com/a/51992486

http://stackoverflow.com/comment/90750102
has text: You should use a custom template tag - an [inclusion tag](https://docs.djangoproject.com/en/2.0/howto/custom-template-tags/#inclusion-tags) that renders the rank template with the context it needs.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51899546

http://stackoverflow.com/comment/90575305
comment on: http://stackoverflow.com/a/51800659
type: AnswerComment
type: Comment
score: 0
has text: @ubuntu_noob You can replace `d = rolling_window(df['B'].values, N)[c] print (d)` to `d = rolling_window(df. index.values, N)[c] print (d)` and then `e = d[:, 1].tolist() print (e)`

http://stackoverflow.com/a/51874619
accepted answer of: http://stackoverflow.com/q/51874176
type: Answer
answers question: http://stackoverflow.com/q/51874176
downvote count: 0
has body: It is really simple, you can decorate your method with api.onchange, @api.onchange('half_pension') def synchroHalfPension(self): if self.half_pension: print "half_pension is on" else: print "half_pension is off" above function will be called whenever the boolean will change. hope this helps!
has comment: http://stackoverflow.com/comment/90702305
score: 1
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90703738
has comment: http://stackoverflow.com/comment/90704080

http://stackoverflow.com/a/51819438
score: 5
answers question: http://stackoverflow.com/q/51819213
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 5
has body: If you want to set the weights on Embedding layers you might add them to the constructor like this: from keras.layers import Embedding embedding_layer = Embedding(len(word_index) + 1, EMBEDDING_DIM, weights=[embedding_matrix], input_length=MAX_SEQUENCE_LENGTH, trainable=False) https://blog.keras.io/using-pre-trained-word-embeddings-in-a-keras-model.html Later then you can hand over merge_ip: x = embedding_layer(merge_ip)
accepted answer of: http://stackoverflow.com/q/51819213

http://stackoverflow.com/comment/90707650
type: QuestionComment
comment on: http://stackoverflow.com/q/51876949
has text: the field "importid_SmartBambi" don't exist in res.partner model
score: 0
type: Comment

http://stackoverflow.com/q/51941175
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51942007
type: Question
answer count: 2
accepted answer: http://stackoverflow.com/a/51942007
possible better answer: http://stackoverflow.com/a/51941238
has title: unable to read file from external location in python
has answer: http://stackoverflow.com/a/51941238
tagged with: python-3.x
has body: I am trying to read a txt file(kept in another location) in python, but getting error. FileNotFoundError in () ----> 1 employeeFile=open("C:‪/Users/xxxxxxxx/Desktop/python/files/employee.txt","r") 2 print(employeeFile.read()) 3 employeeFile.close() FileNotFoundError: [Errno 2] No such file or directory:'C:\u202a/Users/xxxxxxxx/Desktop/python/files/employee.txt' Code used: employeeFile=open("C:‪/Users/xxxxxxxx/Desktop/python/files/employee.txt","r") print(employeeFile.read()) employeeFile.close() I tried using frontslash(/) and backslash(). But getting the same error.Please let me know what is missing in code.
score: 0

http://stackoverflow.com/comment/90787728
type: Comment
comment on: http://stackoverflow.com/a/51918974
has text: This doesn't compare the choices in order, which was the second part of the question. They're effectively asking you to write the whole game for them. Also, you'd be better using a `for` loop if you have a pre-defined number of iterations.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/90671192
comment on: http://stackoverflow.com/q/51859373
has text: 2 things, 1) try giving the full path of the file, 2) try removing the delimiter and encoding argument
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90586114
comment on: http://stackoverflow.com/q/51815744
has text: @U9-Forward Sorry. I should write Jupyter notebook instead of IPython.
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/90842239
score: 0
has text: How about you run some itterations with different wait times to optimize the wait time? Also does it add a .txt file into the directory or does it overwrite an already present file?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51942083

http://stackoverflow.com/comment/90600389
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51822820
score: 1
has text: Not quite what you asked for, but creating the Entry with `justify='center'` will keep the text away from the sides unless you actually need the full width to hold it all.

http://stackoverflow.com/comment/90818873
comment on: http://stackoverflow.com/a/51931947
has text: Thank you, I have read this page already before, it is not saying anything about how to load joblib in this process from bucket after dumping, so the question still is remained
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/90792070
has text: Possible duplicate of [Python OpenCV: draw outer contours inside a specific contour](https://stackoverflow.com/questions/51919841/python-opencv-draw-outer-contours-inside-a-specific-contour)
comment on: http://stackoverflow.com/q/51920907
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51897822
tagged with: complex-numbers
type: Question
tagged with: arrays
score: 0
has answer: http://stackoverflow.com/a/51897872
has comment: http://stackoverflow.com/comment/90746641
answer count: 1
has title: Assigning Complex Values to an Int Array in Python
has comment: http://stackoverflow.com/comment/90749173
tagged with: python
accepted answer: http://stackoverflow.com/a/51897872
type: AnsweredQuestion
has body: everyone. I want to create a random array with a size of 1x1000 and it will have random integers from 0 to 3. Then I want to assign those numbers in different locations in a 2-D cartesian plane. I use real and imaginary axis as my x and y axis. When I try to assign it to 1j or -1j I have an error message: TypeError("can't convert complex to float") Can you help me please? import numpy as np from math import * M = 4 N = 1000 firstsymbols = np.random.randint(M, size=N) symbols = np.zeros(N) for i in range(1,N): if (firstsymbols[i] == 0): symbols[i] = 1 elif (firstsymbols[i] == 1): symbols[i] = 1j elif (firstsymbols[i] == 2): symbols[i] = -1 else: symbols[i] = -1j print(symbols)

http://stackoverflow.com/q/51902851
tagged with: protocol-buffers
accepted answer: http://stackoverflow.com/a/51902905
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51902905
has title: Repeated fields return AttributeError - type object 'Foo' has no attribute 'nums'
type: Question
has body: I am following this tutorial for using protocol buffers in python. Here is my main.proto file: syntax = "proto2" message Foo { repeated int32 nums = 1; } I cannot access foo.nums. Here is the python script which fails: import main_pb2 foo = main_pb2.Foo foo.nums.append(1) This is what I get when I run it: AttributeError: type object 'Foo' has no attribute 'nums'. To make it even more confusing, I can see that Foo has an attribute called foo.NUMS_FIELD_NUMBER. What is going on?
score: 0
has comment: http://stackoverflow.com/comment/90757228
answer count: 1
tagged with: python-3.x

http://stackoverflow.com/comment/90802925
score: 1
has text: added as suggested
comment on: http://stackoverflow.com/q/51926494
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90728254
has text: Where it fails?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51888423
type: Comment

http://stackoverflow.com/comment/90845255
has text: @Mavrick. Try `print( json.loads(re.sub(r"\n", "", s.replace(r"“", "'"))) )`
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51947472

http://stackoverflow.com/comment/90796175
comment on: http://stackoverflow.com/a/51880542
type: AnswerComment
score: 0
type: Comment
has text: @Teddy I think the only thing you have done wrong is the URL

http://stackoverflow.com/a/51845213
type: Answer
has body: There are many ways to write an infinite loop, but I think the most straightforward is using while True:, for example: import time while True: btcPriceDetect() time.sleep(60) # suspend thread for one minute
answers question: http://stackoverflow.com/q/51838134
score: 0

http://stackoverflow.com/a/51815638
answers question: http://stackoverflow.com/q/51815511
downvote count: 1
has comment: http://stackoverflow.com/comment/90586544
has comment: http://stackoverflow.com/comment/90586303
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/51815511
upvote count: 2
has body: use freq = 'B' for business day frequency. import pandas as pd dt = pd.date_range(start=datetime.date.today(), periods=10, freq='B') dt which gives you : DatetimeIndex(['2018-08-13', '2018-08-14', '2018-08-15', '2018-08-16', '2018-08-17', '2018-08-20', '2018-08-21', '2018-08-22', '2018-08-23', '2018-08-24'], dtype='datetime64[ns]', freq='B') you check name of day also by: dt.weekday_name Index(['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'], dtype='object')
score: 1

http://stackoverflow.com/comment/90834035
type: Comment
type: QuestionComment
has text: `glob.glob(r"D:\data files\*.csv")` might be better suited for your case since it will only list `.csv` files.
score: 0
comment on: http://stackoverflow.com/q/51942260

http://stackoverflow.com/q/51811387
type: Question
tagged with: python-pptx
tagged with: python
has answer: http://stackoverflow.com/a/51846794
score: 0
answer count: 1
has body: 1)How I can to set color for each series in column chart as posted below? 2) do exist a way to set distance between columns and their width? Below an sample of code from pptx import Presentation from pptx.chart.data import ChartData from pptx.enum.chart import XL_CHART_TYPE from pptx.util import Inches # create presentation with 1 slide ------ prs = Presentation() slide = prs.slides.add_slide(prs.slide_layouts[5]) # define chart data --------------------- chart_data = ChartData() chart_data.categories = ['East', 'West', 'Midwest'] chart_data.add_series('Q1 Sales', (19.2, 21.4, 16.7)) chart_data.add_series('Q2 Sales', (22.3, 28.6, 15.2)) chart_data.add_series('Q3 Sales', (20.4, 26.3, 14.2)) graphic_frame = slide.shapes.add_chart( XL_CHART_TYPE.COLUMN_CLUSTERED, x, y, cx, cy, chart_data ) chart = graphic_frame.chart
has title: How to set column colors and distance in chart
accepted answer: http://stackoverflow.com/a/51846794
type: AnsweredQuestion

http://stackoverflow.com/comment/106100102
has text: Thank you so much for this update (+1), I had exactly the same problem and also thought that `https://www.googleapis.com/auth/calendar` would be a superset of `https://www.googleapis.com/auth/calendar.events` but it is not. This could be better explained in the docs, to be honest. Thanks again.
type: AnswerComment
comment on: http://stackoverflow.com/a/51954834
score: 0
type: Comment

http://stackoverflow.com/q/51923846
upvote count: 1
has body: I wish someone could help me answer why Correlation result computed by numpy.cov() and np.std() is different from the result computed directly by np.corrcoef(). the following code show the difference import numpy as np import pandas as pd import matplotlib.pyplot as plt X = np.random.rand(50) Y = np.random.rand(50) plt.scatter(X,Y) plt.xlabel('X Value') plt.ylabel('Y Value') # taking the relevant value from the matrix returned by np.cov print 'Correlation: ' + str(np.cov(X,Y)[0,1]/(np.std(X)*np.std(Y))) # Let's also use the builtin correlation function print 'Built-in Correlation: ' + str(np.corrcoef(X, Y)[0, 1]) One Example output: Correlation: -0.0972430699897 Built-in Correlation: -0.0952982085899
answer count: 1
tagged with: numpy
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51925018
downvote count: 0
score: 1
favorite count: 0
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/90797326
has title: why correlation computed by nump.cov() and np.std() is different from the result computed by np.corrcoef()

http://stackoverflow.com/q/51830966
answer count: 1
has title: How to transformation 'string' to 'variable' Python 2.7?
tagged with: string
has comment: http://stackoverflow.com/comment/90616204
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90616229
linked to: http://stackoverflow.com/q/1373164
tagged with: python
duplicate of: http://stackoverflow.com/q/1373164
score: 0
has answer: http://stackoverflow.com/a/51831135
type: Question
has comment: http://stackoverflow.com/comment/90616276
tagged with: variables
tagged with: python-2.7
has body: i need help, please. The code is more big but i show you the idea with a example. How to transformation 'string union' to 'variable union' Thanks dictionary1 = {'a':1,'b':2} p1 = 'dictionary' p2 = 1 union = p1+str(p2) vars()[union] = union for key,value in union.items(): print key,value

http://stackoverflow.com/comment/90675894
comment on: http://stackoverflow.com/q/51861153
has text: @darc: That is a just a definition of the C function `round()`, the Python function `round()` for `float` is defined in https://github.com/python/cpython/blob/master/Objects/floatobject.c and it is a bit more complicated so it can get the correct result.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/56521465
has body: I wrote the python code for multi channel attribution model. https://www.linkedin.com/pulse/multi-channel-attribution-model-python-sheranga-gamwasam/ Here is the dataset link:https://docs.google.com/spreadsheets/d/11pa-eQDHEX63uSEA4eWiDTOZ7lbO6Vwt-dHkuhuhbSo/edit?usp=sharing import time import pandas as pd import numpy as np import collections from itertools import chain import itertools from scipy.stats import stats import statistics def unique(list1): unique_list = [] for x in list1: if x not in unique_list: unique_list.append(x) return(unique_list) def split_fun(path): return path.split('&gt;') def calculate_rank(vector): a={} rank=0 for num in sorted(vector): if num not in a: a[num]=rank rank=rank+1 return[a[i] for i in vector] def transition_matrix_func(import_data): z_import_data=import_data.copy() z_import_data['path1']='start&gt;'+z_import_data['path'] z_import_data['path2']=z_import_data['path1']+'&gt;convert' z_import_data['pair']=z_import_data['path2'].apply(split_fun) zlist=z_import_data['pair'].tolist() zlist=list(chain.from_iterable(zlist)) zlist=list(map(str.strip, zlist)) T=calculate_rank(zlist) M = [[0]*len(unique(zlist)) for _ in range(len(unique(zlist)))] for (i,j) in zip(T,T[1:]): M[i][j] += 1 x_df=pd.DataFrame(M) np.fill_diagonal(x_df.values,0) x_df=pd.DataFrame(x_df.values/x_df.values.sum(axis=1)[:,None]) x_df.columns=sorted(unique(zlist)) x_df['index']=sorted(unique(zlist)) x_df.set_index("index", inplace = True) x_df.loc['convert',:]=0 return(x_df) def simulation(trans,n): sim=['']*n sim[0]= 'start' i=1 while i&lt;n: sim[i] = np.random.choice(trans.columns, 1, p=trans.loc[sim[i-1],:])[0] if sim[i]=='convert': break i=i+1 return sim[0:i+1] def markov_chain(data_set,no_iteration=10,no_of_simulation=10000,alpha=5): import_dataset_v1=data_set.copy() import_dataset_v1=(import_dataset_v1.reindex(import_dataset_v1.index.repeat(import_dataset_v1.conversions))).reset_index() import_dataset_v1['conversions']=1 import_dataset_v1=import_dataset_v1[['path…
type: Answer
upvote count: 4
downvote count: 0
answers question: http://stackoverflow.com/q/51817219
score: 4

http://stackoverflow.com/comment/90632035
has text: Do you need all the objects at once? If not, then `for obj in needed_with_params(): with obj as o: ... ` may suffice
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51839514

http://stackoverflow.com/q/51931804
has body: This is my Pandas Frame: istat cap Comune 0 1001 10011 AGLIE' 1 1002 10060 AIRASCA 2 1003 10070 ALA DI STURA I want to reproduce the equivalent SQL query: Select cap from DataFrame where Comune = 'AIRASCA' Obtaining: cap 10060 I tried to achieve this with dataframe.loc() but i cannot retrieve what i need. And this is my Python code: import pandas as pd from lxml import etree from pykml import parser def to_upper(l): return l.upper() kml_file_path = '../Source/Kml_Regions/Lombardia.kml' excel_file_path = '../Source/Milk_Coverage/Milk_Milan_Coverage.xlsx' zip_file_path = '../Source/ZipCodes/italy_cap.csv' # Read zipcode csv zips = pd.read_csv(zip_file_path) zip_df = pd.DataFrame(zips, columns=['cap', 'Comune']).set_index('Comune') zips_dict = zips.apply(lambda x: x.astype(str).str.upper()) # Read excel file for coverage df = pd.ExcelFile(excel_file_path).parse('Comuni') x = df['City'].tolist() cities = list(map(to_upper, x)) #-----------------------------------------------------------------------------------------------# # Check uncovered # parse the input file into an object tree with open(kml_file_path) as f: tree = parser.parse(f) # get a reference to the "Document.Folder" node uncovered = tree.getroot().Document.Folder # iterate through all "Document.Folder.Placemark" nodes and find and remove all nodes # which contain child node "name" with content "ZONE" for pm in uncovered.Placemark: if pm.name in cities: parent = pm.getparent() parent.remove(pm) else: pass # convert the object tree into a string and write it into an output file with open('../Output/Uncovered_Milkman_LO.kml', 'w') as output: output.write(etree.tostring(uncovered, pretty_print=True)) #---------------------------------------------------------------------------------------------# # Check covered with open(kml_file_path) as f: tree = parser.parse(f) covered = tree.getroot().Document.Folder for pmC in covered.Placemark: if pmC.name in cities: pass else: parentCovered = pmC.getparent() parentCovered.…
has answer: http://stackoverflow.com/a/51931864
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51931918
possible better answer: http://stackoverflow.com/a/51931827
has answer: http://stackoverflow.com/a/51931827
type: Question
accepted answer: http://stackoverflow.com/a/51931918
tagged with: dataframe
linked to: http://stackoverflow.com/q/44890713
tagged with: python-2.7
score: 0
answer count: 3
tagged with: pandas
duplicate of: http://stackoverflow.com/q/44890713
tagged with: data-science
has title: Pandas extract informations

http://stackoverflow.com/comment/90734267
score: 0
has text: I don't think it's possible to run the event loop in a separate thread.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51890625

http://stackoverflow.com/q/51893520
has comment: http://stackoverflow.com/comment/90737919
answer count: 2
has body: I am trying to execute a bash script from python code. The bash script has some grep commands in a pipe inside a for loop. When I run the bash script itself it gives no errors but when I use it within the python code it says: grep:write error. The command that I call in python is: subprocess.call("./change_names.sh",shell=True) The bash script is: #!/usr/bin/env bash for file in *.bam;do new_file=`samtools view -h $file | grep -P '\tSM:' | head -n 1 | sed 's/.\+SM:\(.\+\)/\1/' | sed 's/\t.\+//'`;rename s/$file/$new_file.bam/ $file;done What am I missing?
has comment: http://stackoverflow.com/comment/90738343
favorite count: 0
has comment: http://stackoverflow.com/comment/90741360
tagged with: bash
accepted answer: http://stackoverflow.com/a/51895430
tagged with: grep
has title: Inserting bash script in python code
has comment: http://stackoverflow.com/comment/90738802
downvote count: 1
has comment: http://stackoverflow.com/comment/90740936
tagged with: python
upvote count: 0
has comment: http://stackoverflow.com/comment/90738319
has answer: http://stackoverflow.com/a/51895430
possible better answer: http://stackoverflow.com/a/51893934
has answer: http://stackoverflow.com/a/51893934
has comment: http://stackoverflow.com/comment/90738806
has comment: http://stackoverflow.com/comment/90741646
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90737810
tagged with: pipe
score: -1
has comment: http://stackoverflow.com/comment/90738135
type: Question

http://stackoverflow.com/comment/98461325
comment on: http://stackoverflow.com/a/52030988
score: 0
type: AnswerComment
has text: I dont think that was me, but I'm a noob here anyway & don't know if it was a freak mouse click ;)I've voted you one up JIC.
type: Comment

http://stackoverflow.com/q/51849433
tagged with: flask
has answer: http://stackoverflow.com/a/51851398
answer count: 1
favorite count: 0
type: UnansweredQuestion
score: 0
has body: I am using flask to deploy my deep learning model. But when I am running my model I got this following error. Method Not Allowed The method is not allowed for the requested URL And when I activate debug mode I got this flask.cli.NoAppException flask.cli.NoAppException: While importing "app", an ImportError was raised: Traceback (most recent call last): File "c:\users\tab\anaconda3\lib\site-packages\flask\cli.py", line 235, in locate_app import(module_name) File "C:\Chatbot-Flask-Server-master\Chatbot-Flask-Server-master\app.py", line 3, in import tensorflow as tf ModuleNotFoundError: No module named 'tensorflow' I had installed my tensorflow and the model can running well without flask, an error still appears when I activate virtual environment. And here my code : ## webapp app = Flask(__name__, template_folder='./') @app.route('/prediction', methods=['POST', 'GET']) def prediction(): response = pred(str(request.json['message'])) return jsonify(response) @app.route('/') def main(): return render_template('index.html') if __name__ == '__main__': app.run(debug=True) And the index Text
upvote count: 1
tagged with: python
downvote count: 1
has title: Python flask Method Not Allowed The method is not allowed for the requested URL
tagged with: tensorflow
type: Question

http://stackoverflow.com/a/51822758
answers question: http://stackoverflow.com/q/51822589
score: 7
has comment: http://stackoverflow.com/comment/137697749
has body: Not particularly fancy but a list comprehension will work: [A &gt; b for b in B] [array([ True, False, True, True], dtype=bool), array([False, False, False, True], dtype=bool)] You can also use np.greater(), which requires the dimension-adding trick that Brenlla uses in the comments: np.greater(A, B[:,np.newaxis]) array([[ True, False, True, True], [False, False, False, True]], dtype=bool)
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90600116
accepted answer of: http://stackoverflow.com/q/51822589
type: Answer
has comment: http://stackoverflow.com/comment/90600367
has comment: http://stackoverflow.com/comment/90600156
upvote count: 7

http://stackoverflow.com/q/51950281
tagged with: nvidia
favorite count: 0
tagged with: pycharm
tagged with: python
has answer: http://stackoverflow.com/a/51965374
has title: Tensorflow not running on GPU in PyCharm
downvote count: 1
has body: I installed Tensorflow GPU and I can see it in Terminal on Ubuntu 18.04. >>> from tensorflow.python.client import device_lib >>> print(device_lib.list_local_devices()) And result is: 2018-08-21 16:34:49.867482: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1484] Adding visible gpu devices: 0 2018-08-21 16:34:49.867602: I tensorflow/core/common_runtime/gpu/gpu_device.cc:965] Device interconnect StreamExecutor with strength 1 edge matrix: 2018-08-21 16:34:49.867627: I tensorflow/core/common_runtime/gpu/gpu_device.cc:971] 0 2018-08-21 16:34:49.867650: I tensorflow/core/common_runtime/gpu/gpu_device.cc:984] 0: N 2018-08-21 16:34:49.867979: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1097] Created TensorFlow device (/device:GPU:0 with 6863 MB memory) -> physical GPU (device: 0, name: GeForce GTX 1070 Ti, pci bus id: 0000:01:00.0, compute capability: 6.1) [name: "/device:CPU:0" device_type: "CPU" memory_limit: 268435456 locality { } incarnation: 10929943929948782169 , name: "/device:GPU:0" device_type: "GPU" memory_limit: 7196478669 locality { bus_id: 1 links { } } incarnation: 1784950594023049308 physical_device_desc: "device: 0, name: GeForce GTX 1070 Ti, pci bus id: 0000:01:00.0, compute capability: 6.1" ] But when I run it in PyCharm I get /usr/lib/python3.6/importlib/_bootstrap.py:219: RuntimeWarning: numpy.dtype size changed, may indicate binary incompatibility. Expected 96, got 88 return f(*args, **kwds) /usr/lib/python3.6/importlib/_bootstrap.py:219: RuntimeWarning: numpy.dtype size changed, may indicate binary incompatibility. Expected 96, got 88 return f(*args, **kwds) [name: "/device:CPU:0" device_type: "CPU" memory_limit: 268435456 locality { } incarnation: 12856835725849494278 ] 2018-08-21 16:38:54.238307: I tensorflow/core/platform/cpu_feature_guard.cc:141] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 FMA Process finished with exit code 0
linked to: http://stackoverflow.com/q/19885821
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/90854327
duplicate of: http://stackoverflow.com/q/19885821
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/90871941
type: Question
upvote count: 4
accepted answer: http://stackoverflow.com/a/51965374
has comment: http://stackoverflow.com/comment/90851351
answer count: 1
linked to: http://stackoverflow.com/q/40845304
has comment: http://stackoverflow.com/comment/90873655

http://stackoverflow.com/comment/90643641
comment on: http://stackoverflow.com/a/51824637
type: Comment
has text: Thank you for the reply. It was exactly as you said. It is solved now.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/90777842
comment on: http://stackoverflow.com/a/51913815
has text: I'll call it a "feature" of my answer :) but that's a good point, I will clarify
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/90661070
type: QuestionComment
has text: Thanks Kevin, I have changed that, it now shows just as systems.csv in the file. How would I split the file name so it only shows systems?
score: 0
comment on: http://stackoverflow.com/q/51854107
type: Comment

django-serializer
tags question: http://stackoverflow.com/q/51805867
type: Tag
tag name: django-serializer

http://stackoverflow.com/q/51863982
has comment: http://stackoverflow.com/comment/90680165
linked to: http://stackoverflow.com/q/240178
tagged with: memoization
tagged with: dynamic-programming
tagged with: python
has title: Why is my recursive function updating a list (calculating fibonacci of n)
favorite count: 0
score: 2
has answer: http://stackoverflow.com/a/51864133
upvote count: 2
has body: I'm trying to learn about dynamic programming. I've gone through an example of how to find the Fibonacci number of an inputn, while caching the result of each "new" call as I go. I understand the order in which the function recursively calls: fib(5) -> fib(4) -> fib(3) -> fib(2) -> fib(1) -> fib(0) -> fib(1) -> fib(2) "Cache found" -> fib(3) "Cache found" for n = 5 I'm struggling to understand how the final fib(2) and fib(3) calls have access to the updated cache, as each call only returns an integer, not the list, and I don't think I have the list declared as a global variable. I originally expected the list to behave like the integer x in my code, so would welcome explanations for how the values have been passed back up. Code: def fib(n, cache, x): print(n, cache) print("x: ", x) x += 1 if n == 0 or n == 1: return n if cache[n] == 0: cache[n] = fib(n-1, cache, x) + fib(n-2, cache, x) else: print("Cache called on", n) return cache[n] def main(): n = 5 x = 0 cache = [0 for _ in range(n+1)] print(fib(n, cache, x)) print(cache) print("x: ", x) if __name__ == "__main__": main() Output: 5 [0, 0, 0, 0, 0, 0] x: 0 4 [0, 0, 0, 0, 0, 0] x: 1 3 [0, 0, 0, 0, 0, 0] x: 2 2 [0, 0, 0, 0, 0, 0] x: 3 1 [0, 0, 0, 0, 0, 0] x: 4 0 [0, 0, 0, 0, 0, 0] x: 4 1 [0, 0, 1, 0, 0, 0] x: 3 2 [0, 0, 1, 2, 0, 0] x: 2 Cache called on 2 3 [0, 0, 1, 2, 3, 0] x: 1 Cache called on 3 5 [0, 0, 1, 2, 3, 5] x: 0
has comment: http://stackoverflow.com/comment/90680089
type: AnsweredQuestion
tagged with: recursion
tagged with: fibonacci
possible better answer: http://stackoverflow.com/a/51864038
accepted answer: http://stackoverflow.com/a/51864133
type: Question
has answer: http://stackoverflow.com/a/51864038
answer count: 2
downvote count: 0

http://stackoverflow.com/q/51835078
upvote count: 1
answer count: 1
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90623790
downvote count: 0
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/90623798
has answer: http://stackoverflow.com/a/51836010
has body: inp = raw_input("Input a EAN-13 number.") aaa = False bbb = False if len(inp) == 13: bbb = True else: print "Error input" exit ean_number = int(inp) def ean13(value_1): mult_of_ten = 0 sum_of_digits = 0 done = False for z in len(value_1): if not z == 0: if z % 2 == 0: value_1[z] *= 3 elif not z % 2 == 0: value_1[z] *= 1 for a in len(value_1): sum_of_digits += value_1[a] if sum_of_digits % 10 == 0: result = 0 elif not sum_of_digits % 10 == 0: while done == False: mult_of_ten = sum_of_digits for d in True: mult_of_ten += d if sum_of_digits % 10 == 0: done == True result = mult_of_ten - sum_of_digits if result == value_1[12]: print "True" if bbb == True: ean13(ean_number) I really don't see why teacher can't help either. I need to make a EAN-13 number validity checker in Python2. I don't see why this doesn't work. Can anyone help?
type: Question
has title: I need to make a EAN-13 number validity checker in Python2. I don't see why this doesn't work
tagged with: python

http://stackoverflow.com/comment/90777029
type: QuestionComment
has text: @juanpa.arrivillaga `return self.x + other.x, self.y + other.y` returns a tuple though.
comment on: http://stackoverflow.com/q/51913177
score: 0
type: Comment

http://stackoverflow.com/q/51846867
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/90647072
upvote count: 2
type: UnansweredQuestion
has body: Code below. Explanation of what I’m doing: I have a list of keywords. I need to identify if these keywords are present on any given web page (which I input). The issue I am running into is with keywords that are more than two words. For example, if you look at the results below, you will see that “Star” and “Wars” do not appear in the list. “Star Wars” is a phrase on my keywords list and I need the result to show as “Star Wars” as opposed to two separate items. Currently, I have the text from bs4 converting to a string then a list, which I know is incorrect because it separates based on the " " which, by default, will split the phrases I am searching for. Is there a way for me to search the string directly for phrases that exist on the imported list? from bs4 import BeautifulSoup from urllib.request import Request, urlopen import re import pandas as pd #Wikipedia Adress here site= "website.html" hdr = {'User-Agent': 'Mozilla/5.0'} req = Request(site,headers=hdr) page = urlopen(req) soup = BeautifulSoup(page,'lxml') #Company Website Here site = "website.html" hdr = {'User-Agent': 'Mozilla/5.0'} req = Request(site,headers=hdr) page = urlopen(req) soup2 = BeautifulSoup(page,'lxml') #Extracts text from soup and saves as souptext variable gettext = soup.get_text() gettext2 = soup2.get_text() #converts to string souptext = str(gettext) souptext2 = str(gettext2) #converts to list split = souptext.split(' ') split2 = souptext2.split(' ') #combines both splits to one single list combined = split + split2 #combines both strings to one string combinedstr = souptext.lower() + souptext2.lower() #Imports Excel File containing keywords df = pd.read_csv('Movies.csv') #Extracts desired column variables as keywords mylist = df['Titles'].tolist() liststr = str(mylist) intersection = [i for i in mylist if i in combined] results = list() results.append(intersection) print(results) 'Avatar', 'Goodfellas', 'Saw', 'Crash', 'Gladiator', 'Scarface' Input was requested so here is an examp…
downvote count: 3
has comment: http://stackoverflow.com/comment/90647121
tagged with: urllib
type: Question
has answer: http://stackoverflow.com/a/51849006
answer count: 2
tagged with: pandas
has title: Searching a string using a list and returning multi-word variables.
has comment: http://stackoverflow.com/comment/90647160
favorite count: 0
tagged with: beautifulsoup
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51846928

http://stackoverflow.com/comment/90734024
has text: Thanks a ton, Sir, you solved my problem in which I was stuck from last week.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51887541
type: Comment

http://stackoverflow.com/comment/90579671
comment on: http://stackoverflow.com/a/51810938
type: AnswerComment
has text: Or sub_df it is just a parameter? I will be grateful if you let me know what is inside sub_df ?Thanks
type: Comment
score: 0

http://stackoverflow.com/comment/90975844
comment on: http://stackoverflow.com/a/51965157
type: AnswerComment
score: 0
type: Comment
has text: I don't understand. What solution? Doesn't this work? So at the end are you using *Python 2* or *3?

http://stackoverflow.com/a/51920174
score: 67
has comment: http://stackoverflow.com/comment/121088824
has comment: http://stackoverflow.com/comment/116690735
answers question: http://stackoverflow.com/q/51911927
has comment: http://stackoverflow.com/comment/121095875
has comment: http://stackoverflow.com/comment/121089080
has comment: http://stackoverflow.com/comment/90792638
accepted answer of: http://stackoverflow.com/q/51911927
has comment: http://stackoverflow.com/comment/90796476
has comment: http://stackoverflow.com/comment/90834203
has body: Updated Answer - based on updated question statement You can update attributes in a nested map using update expressions such that only a part of the item would get updated (ie. DynamoDB would apply the equivalent of a patch to your item) but, because DynamoDB is a document database, all operations (Put, Get, Update, Delete etc.) work on the item as a whole. So, in your example, assuming User is the partition key and that there is no sort key (I didn't see any attribute that could be a sort key in that example), an Update request might look like this: table.update_item( Key={ 'User': 'test' }, UpdateExpression="SET #inv[0].#loc = :locVal", ExpressionAttributeNames={ '#inv': 'inventory', '#loc': 'location' }, ExpressionAttributeValues={ ':locVal': 'in place three', }, ) That said, you do have to know what the item schema looks like and which attributes within the item should be updated exactly. DynamoDB does NOT have a way to operate on sub-items. Meaning, there is no way to tell Dynamo to execute an operation such as "update item, set 'location' property of elements of the 'inventory' array that have a property of 'name' equal to 'opel'" This is probably not the answer you were hoping for, but it is what's available today. You may be able to get closer to what you want by changing the schema a bit. If you need to reference the sub-items by name, perhaps storing something like: { "inventory": { "opel": { "location": "in place one", # I want to update this "tags": [ "x1", "f3" ] }, "abc": { "location": "in place two", "tags": [ "a3", "f5" ] } }, "User" :"test" } Then your query would be: table.update_item( Key={ 'User': 'test' }, UpdateExpression="SET #inv.#brand.#loc = :locVal", ExpressionAttributeNames={ '#inv': 'inventory', '#loc': 'location', '#brand': 'opel' }, ExpressionAttributeValues={ ':locVal': 'in place three', }, ) But YMMV as even this has limitations because you are limited to identifying inventory items by name (ie. you still can't say "update inventory …
has comment: http://stackoverflow.com/comment/90833819
upvote count: 68
type: AcceptedAnswer
downvote count: 1
type: Answer

http://stackoverflow.com/comment/90724747
score: 1
comment on: http://stackoverflow.com/a/51884581
type: AnswerComment
type: Comment
has text: " Thank you for that information. I was able to add the Coach, Player, and Team users in the django admin. Can you clarify the second part of your answer for me? Where should I put the "player = Player.objects.get(...) players_coach = player.team.coach" ? Under views.py? Should I use the same view_profile function as I stated above and incorporate your information, or should I define a new function? I am trying to get it to work where I can now view the roster of Coach 1 when I log in."

http://stackoverflow.com/a/76729998
score: 0
type: Answer
has body: I have also encountered this problem once OSError: Access is denied in my python path. I'm using windows OS, I solved it by using gsudo. You can install gsudo from github https://github.com/gerardog/gsudo. After successfully installing gsudo. gsudo pip3 install --upgrade tensorflow-gpu
answers question: http://stackoverflow.com/q/51912999

http://stackoverflow.com/comment/109058658
type: AnswerComment
comment on: http://stackoverflow.com/a/51807745
type: Comment
has text: I did follow this same order and now I am getting: `TypeError: batch must contain tensors, numbers, dicts or lists; found <class 'PIL.PngImagePlugin.PngImageFile'>`
score: 0

http://stackoverflow.com/a/51814712
score: 2
downvote count: 0
upvote count: 2
answers question: http://stackoverflow.com/q/51814567
has body: According to SymPy's documentation you have to evaluate the value of the function after substituting x with the desired value: &gt;&gt;&gt; dx.evalf(subs={x: 2}) 4.00000000000000 or &gt;&gt;&gt; dx.evalf(2, subs={x: 2}) 4.0 to limit the output to two digits.
type: Answer

http://stackoverflow.com/comment/90600932
type: AnswerComment
comment on: http://stackoverflow.com/a/51802436
has text: I'm not sure about what you are asking for. Can you show an input and corresponding output you are expecting? If you look , `count` and `speciality` are already tuples after the `zip` operation.
type: Comment
score: 0

http://stackoverflow.com/q/51879319
type: Question
upvote count: 2
tagged with: python
tagged with: pass-by-reference
answer count: 1
tagged with: linked-list
linked to: http://stackoverflow.com/q/986006
score: 2
has answer: http://stackoverflow.com/a/51880117
downvote count: 0
has title: Weird Python behavior when setting an object's variable from another object's variable
type: AnsweredQuestion
tagged with: variable-assignment
favorite count: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/51880117
has body: I created a function that will reverse a Linked List, but there is something weird going on, and I haven't been able to figure it out. I am trying to edit the list in place to save space, so the method changes the original list object and doesn't return anything. Which means the last lines if the reverse_list method are (variables renamed here for clarity): original_first_node.val = new_first_node.val original_first_node.next = new_first_node.next But for some reason, the node chain on original_first_node.next looks different than that of new_first_node.next, and it's also cyclical now. Here is some runnable code with a failing unit test (see the comments in the reverse_list function): import unittest class Node(object): def __init__(self, x): self.val = x self.next = None def create_list(list): if not list: return None sentinel = Node(None) current = sentinel for item in list: current.next = Node(item) current = current.next return sentinel.next def convert_list(head): ret = [] if head: current = head while current: ret.append(current.val) current = current.next return ret def is_list_cyclic(head): if not head: return False tortoise = hare = head while hare.next and hare.next.next: tortoise = tortoise.next hare = hare.next.next if tortoise == hare: return True return False def reverse_list(head): if not head or not head.next: return current = head prev = None while current: static_next = current.next current.next = prev prev = current current = static_next # At this point, prev.next looks great head.val = prev.val head.next = prev.next # head.next is cyclical now for some reason ?? class TestSuite(unittest.TestCase): def test_reverse_list(self): head = create_list([1, 2, 3, 4]) reverse_list(head) self.assertFalse(is_list_cyclic(head)) self.assertEqual([4, 3, 2, 1], convert_list(head)) if __name__ == "__main__": unittest.main()

http://stackoverflow.com/q/51887331
answer count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
tagged with: exif
score: 1
has body: import exifread f = open('manu.JPEG', 'rb') tags = exifread.process_file(f) tags['EXIF SceneType'] = "Manu" tags['EXIF ExposureMode'] = "Prakash" tags['Image Make'] = "Georgian" tags.save('mjp.jpg', 'jpeg', exif=exif_bytes) --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) &lt;ipython-input-22-48afdf003b60&gt; in &lt;module&gt;() 2 tags['EXIF ExposureMode'] = "Prakash" 3 tags['Image Make'] = "Georgian" ----&gt; 4 tags.save('mjp.jpg', 'jpeg', exif=exif_bytes) AttributeError: 'dict' object has no attribute 'save' I converted a jpeg image file to a dictionary and made some changes to its metadata. I now want to download the image file with the new changes in its meta data. I tried using ".save" method but it is throwing an error.
type: Question
has title: Modifying the EXIF meta data and exporting it
tagged with: image
downvote count: 0
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/comment/90627474
score: 0
has text: Go through this documentation, https://www.jetbrains.com/help/pycharm/creating-and-running-your-first-django-project.html
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51837124

http://stackoverflow.com/comment/90789123
type: QuestionComment
comment on: http://stackoverflow.com/q/51918990
has text: Also, each figure needs it's own animation function, and the function should *update* the plot using `line.set_data`, not make a new plot.
score: 0
type: Comment

http://stackoverflow.com/comment/90831788
type: Comment
comment on: http://stackoverflow.com/q/51940997
has text: which lines yields an error? seems ike your column has different names than the ones your input.. maybe you have whitespaces around them? Print `df2.columns` and check
score: 0
type: QuestionComment

http://stackoverflow.com/comment/90554504
score: 1
has text: Hi reinaldo, can you posts a sample of `df'tipo', 'resumo', 'nome'.head(5).to_dict()` ? (with the data masked so not to disclose the real information)? Just wanted to know how the rows look like
comment on: http://stackoverflow.com/q/51798913
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51810658
answers question: http://stackoverflow.com/q/51810328
score: 1
upvote count: 1
has body: the Peewee author was so kind to answer himself. I think using a factory method is the cleanest solution, to avoid conflicting with the way peewee uses __init()__ You can still put it in __init__() with the caveat that __init__() is going to be called not just when instantiating objects yourself, but also every time a Car instance is read from a database cursor. I think you probably could make a classmethod on your Car object and use that as a factory for complex logic? Refer to this.
downvote count: 0
type: Answer

http://stackoverflow.com/a/51919391
type: Answer
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/51918954
upvote count: 2
has body: Two approaches come to my mind. First, is to use the scipy cdist. But it has a couple of issues. Since, it expects the output of the custom distance function to be a scalar, so we need to calculate the x and y coordinates of the force separately. Second, it will do the calculations for all the pairs i,j and j,i again. So, as mentioned in the question we can reduce the calculation to n^2/2. On N = 1000, it takes 14.141 sec. For N = 10000, takes forever. Calculations made on 8 GB, 8 core mac. import time import numpy as np from scipy.spatial import distance N = 1000 r = np.random.rand(N, 2) def force(a, b): def V(dist): #Here, dist is a float return np.exp(-dist)/(dist+1) r_rel = a - b #Relative position dist_rel = np.sqrt(r_rel[0]**2 + r_rel[1]**2) return V(dist_rel)*r_rel def force_x(a, b): return force(a,b)[0] def force_y(a, b): return force(a, b)[1] t1 = time.time() # Calculate x and y coordinates separately F_x = distance.cdist(r, r, metric=force_x) F_y = distance.cdist(r, r, metric=force_y) print("Time taken is = ", time.time() - t1) # takes 14.141s Second, method which takes care of the n^2/2 optimization is to use the n^2 loop but to speed up the calculations using numba. If you have a gpu, you can further speed up by numba vectorize. On N = 1000, it takes 0.240 sec. For N = 10000, takes ~25 sec. import numba as nb @nb.jit(nb.float64[:,:,:](nb.float64[:,:]), nopython=True, cache=True) def distance(r): N = r.shape[0] F = np.zeros((N,N,2)) for i in range(N): for j in range(i): r_rel = r[i] - r[j] #Relative position dist_rel = np.sqrt(r_rel[0] ** 2 + r_rel[1] ** 2) V = np.exp(-dist_rel) / (dist_rel+1) F[i,j] = V * r_rel F[j,i] = -1 * F[i,j] return F t1 = time.time() F = distance(r) print("Time taken is = ", time.time() - t1) # takes 0.240s So, apart from making the O(n logn) method described in the link in the comments, the numba method seems to work for the example size in the question under acceptable time.

http://stackoverflow.com/comment/90699196
type: Comment
has text: You can try something like this `python -m pip install https://files.pythonhosted.org/packages/42/1e/5b6608faf3462cb0b396fe4c19a8a1fb690e3a0f4b03d34174c16774a98c/pygame-1.9.4-cp27-cp27m-win32.whl`
comment on: http://stackoverflow.com/q/51873465
score: 0
type: QuestionComment

http://stackoverflow.com/comment/90561438
comment on: http://stackoverflow.com/a/51801634
score: 0
type: Comment
has text: @albo22 you're probably using `plt.colorbar` rather than `mpl.colorbar`. I have no experience with adding colorbars like that, though.
type: AnswerComment

http://stackoverflow.com/a/51866872
has comment: http://stackoverflow.com/comment/90694605
upvote count: 1
has body: It looks to me like you only need to enable sending to a broadcast address. That's done with client.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1). I changed your send_ls as shown below and I'm able to communicate with a UDP echo program listening on port 4343. Here 192.168.40.255 is the subnet broadcast address. def send_ls(self): host = '192.168.40.255' port=4343 address=host,port client=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) client.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) while (True): msg=input("Controller 1 :") client.sendto(bytearray(msg,"utf-8"),address) reply=client.recvfrom(1000) recved=str(reply) print("Main Controller: %s " %(recved)) Sample output shown below. Note that the server side didn't specify an address in the bind. So the server is able to receive messages sent to the broadcast address, but when it sends back, the response comes from the unicast address of the server's network adapter. Controller 1 :Hello there Main Controller: (b'Hello there', ('192.168.40.128', 4343)) Controller 1 :You still there? Main Controller: (b'You still there?', ('192.168.40.128', 4343)) Controller 1 : One more note: If your client code here remembers the address it gets back from the reply, then subsequent messages it sends don't need to go to the broadcast address. That is, simply assign reply[1] to address after the recvfrom, and then you won't be sending broadcasts after the first message (which is better for the performance of your network).
score: 1
answers question: http://stackoverflow.com/q/51860231
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/90694151

http://stackoverflow.com/q/51911245
has comment: http://stackoverflow.com/comment/90772919
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/10745138
score: -3
has answer: http://stackoverflow.com/a/51911352
tagged with: python
has comment: http://stackoverflow.com/comment/90773945
downvote count: 3
type: Question
tagged with: server
has title: Execute bash script at remote node and controlled via python from server
tagged with: linux
tagged with: bash
upvote count: 0
has body: I have two devices one is Server and another one is Linux NODE. NODE does not have a python interpreter. Server &lt;------> NODE I want to execute bash script remotely in the NODE triggered by Python program from the Server. And I should get the output of the bash script back to my Python script. Pls. let me know how to do this.
answer count: 1
favorite count: 0

http://stackoverflow.com/q/51878833
downvote count: 0
answer count: 0
score: 1
tagged with: translation
type: Question
tagged with: format
tagged with: date
duplicate of: http://stackoverflow.com/q/18593661
has title: Parsing date with german month names
upvote count: 1
has body: I try to read a csv-file with german month days like 'Mai' etc. When I try: datetime.date.strptime('Mai 2009','%B %Y')) it results in a ValueError: time data 'Mai 2009' does not match format '%B %Y' The defaultlocale ist 'de_DE' Is there an easy solution for translation ?
favorite count: 0
has comment: http://stackoverflow.com/comment/90709122
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/18593661
has comment: http://stackoverflow.com/comment/90709030

http://stackoverflow.com/a/51868741
upvote count: 2
has body: Use map: arr = [2, 4, 6, 8, 10] out = list(map(lambda x: x/arr[0], arr)) And if you don't like the lambda expression, you can use the truediv (or floordiv) method in operator, but two parameters are required so here I used a little trick. from operator import truediv from itertools import starmap arr = [2, 4, 6, 8, 10] arr = zip(arr, [arr[0]]*len(arr)) out = list(starmap(truediv, arr)) print(out) I first build a new iterable according to the question, and then use starmap which can map multiple parameters to a function. truediv in operator has exactly the same functionality as operator / but just make it run in a function way and accept two parameters and return the div result between them.
type: Answer
answers question: http://stackoverflow.com/q/51868686
score: 2
has comment: http://stackoverflow.com/comment/90689275
downvote count: 0

http://stackoverflow.com/a/51871159
has comment: http://stackoverflow.com/comment/90693772
score: 1
has body: The easiest solutions are: def f(): x=np.array(([1.2],[3,4],[5,6])) return x x = f() x_shape = x.shape or def f(): x=np.array(([1.2],[3,4],[5,6])) x_shape = x.shape return x, x_shape x, x_shape = f() or, if you do not want to modify the function, AND get both on the same line you can do: def f(): x=np.array(([1.2],[3,4],[5,6])) return x x, x_shape = f(), f().shape
upvote count: 1
answers question: http://stackoverflow.com/q/51871042
has comment: http://stackoverflow.com/comment/90693968
has comment: http://stackoverflow.com/comment/90695153
downvote count: 0
has comment: http://stackoverflow.com/comment/90693791
type: Answer

http://stackoverflow.com/a/51899113
type: Answer
answers question: http://stackoverflow.com/q/51898575
score: 1
upvote count: 1
downvote count: 0
has body: Ok, found the answer: response = instance.modify_attribute(Groups=['sg-123'])

http://stackoverflow.com/q/51852091
tagged with: sockets
tagged with: python
type: AnsweredQuestion
score: 1
tagged with: java
upvote count: 1
linked to: http://stackoverflow.com/q/18491416
accepted answer: http://stackoverflow.com/a/51864893
type: Question
has body: Im working on an Application were I get an image in Opencv Mat format from a Webcam in a Java Client and have to process this image on a python server. Therefore I`m sending a bytearray to the python server. I´m encoding the Image in Java like this: private VideoCapture capture = new VideoCapture(); ... this.capture.read(frame); if (!frame.empty()) { byte[] return_buff = new byte[(int) (frame.total() * frame.channels())]; frame.get(0, 0, return_buff); ... After that I send it through a Socket using a DataOutputStream. When I echo it back to the Java Client the bytedata seems to have been transferred correctly and entirely. In Python I then tried to decode it with PIL img = Image.open(BytesIO(data)) And yes I already import PIL like suggested here: PIL: Convert Bytearray to Image But Im still getting this Error: img = Image.open(BytesIO(data)) File "/root/.local/lib/python2.7/site-packages/PIL/Image.py", line 2590, in open % (filename if filename else fp)) IOError: cannot identify image file Do I have to change the way I assembled my bytearra or do I have to encode it in a different way?
tagged with: python-imaging-library
has title: Bytearray converted from Mat in Java to Image from Socket in Python
tagged with: arrays
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/51864893

http://stackoverflow.com/comment/90992473
comment on: http://stackoverflow.com/a/51855478
type: AnswerComment
score: 0
type: Comment
has text: i am trying to stream audio into the python app to send to IBM Watson, convert the stream to text, send that to my conversation bot, have it respond and sent the text back to python and convert that to an audio (and play it). That's what I am aiming for.

http://stackoverflow.com/a/51879905
upvote count: 3
answers question: http://stackoverflow.com/q/51879380
downvote count: 0
has body: You are stuck in your while loop because in your second iteration you do not enter the first if-condition and hence never add 1 to run and check_in. To solve this you need to change the indentation: while Done == False: if i &lt;= numbers[check_in]: print("Compare "+str(i)+" with "+str(numbers[check_in])+" round:"+str(run)) run += 1 check_in += 1 With this your algorithm will terminate.
type: Answer
score: 3

http://stackoverflow.com/comment/90785559
type: Comment
has text: ok FIXED AT LAST! I wrote : `{% url 'event_update' pk=object.id %}` and its working. dont know why it needs `object` instead of `event`. Can you elaborate this on your answer?
comment on: http://stackoverflow.com/a/51917599
type: AnswerComment
score: 0

http://stackoverflow.com/q/51946051
upvote count: 8
type: Question
accepted answer: http://stackoverflow.com/a/51946126
answer count: 2
tagged with: python
has body: This question may already been asked but I couldn't find a proper way to assign multiple variables to one value without linking them to it, so bear with me. Example 1: a = b = [] a.append('x') &gt; a = ['x'] &gt; b = ['x'] Since I append 'x' to a I don't want to have it in b. Example 2: a, b = [[], []] a.append('x') &gt; a = ['x'] &gt; b = [] Works as expected but with multiple variables it becomes really ugly: a, b, c, d, e, f, g, h, i j = [[], [], [], [], [], [], ...] Example 3: The default way a = [] b = [] ... Same as example 2, it's not pretty with multiple variables. I was wondering if something like this exists like in javascript? a, b, c = [] #this actually gives a ValueError: not enough values to unpack Any suggestions or am I limited to this? Note: for some reason I have to avoid using dictionaries for this task. (limitation...)
score: 8
has title: Most elegant way to assign multiple variables to the same value?
downvote count: 0
has answer: http://stackoverflow.com/a/51946126
possible better answer: http://stackoverflow.com/a/51946184
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51946184
tagged with: variable-assignment
favorite count: 0

http://stackoverflow.com/comment/90677172
type: QuestionComment
has text: i have a df that contains: a numeric variable (mark1 - float) and a categorical variable (gender). All i wish to do is to create on the same dataframe a column calculated as the mean(mark1) . would be greater to calculate that mean groupped by gender. thx a lot!
comment on: http://stackoverflow.com/q/51862276
score: 0
type: Comment

http://stackoverflow.com/q/51828828
has body: my apologizes if this question exists and was clarified (i have already search and eventually i've not find answers). so, i have an array of integers a = [1,2,2,2,3,4] and i want to get stats (in this case mean) of each interval using the bins = [0,1.5) ; [1.5,2.5) ; [2.5,5). As you can see there are NOT same-length intervals. i try to do that: from scipy.stats import binned_statistic data = [1,2,2,2,3,4] bin_means = binned_statistic(data, data, bins=3, range=(0, 5)) in "bin_means" store the following : BinnedStatisticResult(statistic=array([1. , 2.25, 4. ]), bin_edges=array([0. , 1.66666667, 3.33333333, 5. ]), binnumber=array([1, 2, 2, 2, 2, 3], dtype=int32)) what i understand? that the bins are: [0,1.66..7) ; [1.66..7,3.33..) ; [3.33...,5) not the intervals i want. i do not want theese same-length intervals. can someone explainme how can i do that? plus can someone explainme the two main parameters of stats.binned_statics ("x" and "values")? it would be usefull. thanks in advance.
tagged with: python
upvote count: 1
has answer: http://stackoverflow.com/a/51829887
type: Question
type: AnsweredQuestion
score: 1
has title: given the scipy.stats.binned_statistic function ... how to work with diferent sizes of bins?
tagged with: scipy
answer count: 1
accepted answer: http://stackoverflow.com/a/51829887
downvote count: 0
favorite count: 0
tagged with: statistics

http://stackoverflow.com/a/51824469
upvote count: 25
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51822129
type: Answer
answers question: http://stackoverflow.com/q/51822129
score: 25
downvote count: 0
has body: Flask's docs about the CLI discuss this. @app.cli.command() automatically ensures there's an app context when the command runs. However, this is less convenient to use when using an app factory because you don't have access to the app when defining the command. When using the app factory, you use @click.command() and app.cli.add_command() to separate defining and registering the command, but @click.command doesn't know about the app context. Use the @with_appcontext decorator to ensure the command runs in an app context. @click.command() @with_appcontext def my_command(): config = current_app.config click.echo(config["TEST_VARIABLE"]) def create_app(): app = Flask(__name__) ... app.cli.add_command(my_command) ... return app $ flask my-command TESTVALUE

http://stackoverflow.com/q/51802421
has comment: http://stackoverflow.com/comment/90563903
answer count: 3
downvote count: 0
accepted answer: http://stackoverflow.com/a/51802616
favorite count: 0
tagged with: python-3.x
upvote count: 2
possible better answer: http://stackoverflow.com/a/51802517
tagged with: python
tagged with: regex
has answer: http://stackoverflow.com/a/51802517
score: 2
type: AnsweredQuestion
has title: Regex to find last two places in a group of numbers
has answer: http://stackoverflow.com/a/51802616
type: Question
has body: I have numbers with the following form: 02R-01240-250A 02R-01242-250 15-09110-200X 15-09110-212 I can capture the middle 5 digits (always 5) with: ([^-]+[0-9]{4}) but I really want to grab the last two digits of this 5 number set and make a new column in my Pandas dataframe. I also need be able to grab the middle for a new column as well.
has answer: http://stackoverflow.com/a/51802440

http://stackoverflow.com/comment/90793359
has text: Hi Don. You are asking some very basic questions here, and I think you should take a look at some basic python/pandas tutorials first, because the explanations envolve lots of basic concepts that are quite hard to highlight/write here.... In a nutshell, 1. You can access columns like `df['col']` or `df.col`, both are fine; 2. `apply` in a groupby is described in the [documentation with examples](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.apply.html), and there is written what it takes as argument, what it returns and how it works.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51914318

http://stackoverflow.com/comment/90574038
type: Comment
type: QuestionComment
has text: `set(list_1).issubset(list_2)` gives you true or false, efficiently, provided duplicates don't matter.
comment on: http://stackoverflow.com/q/51809437
score: 0

http://stackoverflow.com/a/52062392
type: Answer
upvote count: 3
answers question: http://stackoverflow.com/q/51921278
score: 3
accepted answer of: http://stackoverflow.com/q/51921278
type: AcceptedAnswer
downvote count: 0
has body: This looks like an issue in architecture. First, you are generating your data on the go, which despite being a commonly employed technique, is not always the most reasonable choice. This is because: One of the downsides of Dataset.from_generator() is shuffling the resulting dataset with a shuffle buffer of size n requires n examples to be loaded. This will either create periodic pauses in your pipeline (large n) or result in potentially poor shuffling (small n). It might be a good idea to convert your data into numpy arrays, and then store the numpy arrays on disk to use as your data set like so: def array_to_tfrecords(X, y, output_file): feature = { 'X': tf.train.Feature(float_list=tf.train.FloatList(value=X.flatten())), 'y': tf.train.Feature(float_list=tf.train.FloatList(value=y.flatten())) } example = tf.train.Example(features=tf.train.Features(feature=feature)) serialized = example.SerializeToString() writer = tf.python_io.TFRecordWriter(output_file) writer.write(serialized) writer.close() This will take the Dataset.from_generator component out of the issue. The data can then be read with: def read_tfrecords(file_names=("file1.tfrecord", "file2.tfrecord", "file3.tfrecord"), buffer_size=10000, batch_size=100): dataset = tf.contrib.data.TFRecordDataset(file_names) dataset = dataset.map(parse_proto) dataset = dataset.shuffle(buffer_size) dataset = dataset.repeat() dataset = dataset.batch(batch_size) return tf.contrib.data.Iterator.from_structure(dataset.output_types, dataset.output_shapes) This should ensure your data is thoroughly shuffled and give better results. Additionally, I believe that you would benefit from a little data preprocessing. For starters, try converting all the files in your dataset into a standardized WAVE form and then saving that data to a TFRecord. Currently you are converting them into WAVE and standardizing the sample rate with librosa, but that doesn't standardize the channels. Instead try using a function like: from pydub import AudioSeg…

http://stackoverflow.com/q/51881192
has title: custom widget triggers another custom widget's on_touch_down event
has body: Whenever I press any area in MyWidget then it trigger the first MyButton 's on_touch_down event inside MyLayout class. I am new to kivy and don't understand why this is happening. &lt;MyButton@Button&gt;: background_normal: '' background_color: [1,0,1,1] font_size: "44dp" color:[1,1,0,1] border:(1,1,1,1) text_size:self.size &lt;MyWidget@Widget&gt;: id:customwidget canvas.before: Color: rgba:0.2,0.44,0.66,1 Rectangle: pos:self.pos size:self.size &lt;MyLayout&gt;: MyWidget: id:mywidget MyButton: id:button1 text: "User Name" spacing: "10dp" on_touch_down: button1.text= self.text + "?" opacity: .8 MyButton: text: "ikinci" on_touch_down: root.export_to_png("filename.png") MyButton: text: "ucuncu" And this is python: import kivy from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.uix.button import Button from kivy.uix.widget import Widget class MyLayout(BoxLayout): pass class KivyApp(App): def build(self): return MyLayout() if __name__ == "__main__": KivyApp().run()
accepted answer: http://stackoverflow.com/a/51882070
answer count: 2
downvote count: 0
favorite count: 0
tagged with: python
tagged with: kivy
has answer: http://stackoverflow.com/a/51882070
type: AnsweredQuestion
tagged with: kivy-language
score: 1
possible better answer: http://stackoverflow.com/a/51882100
upvote count: 1
has answer: http://stackoverflow.com/a/51882100
type: Question

http://stackoverflow.com/q/51814615
type: UnansweredQuestion
has title: Merge dataframe where column has default values and overrides
tagged with: python
has comment: http://stackoverflow.com/comment/90583917
type: Question
has answer: http://stackoverflow.com/a/51815091
tagged with: dataframe
score: 0
tagged with: pandas
linked to: http://stackoverflow.com/q/23668427
answer count: 1
has body: I have a Pandas dataframe listing threshold values for various systems: METRIC SYSTEM_NAME YELLOW RED 16 pagins NaN 500.0 1000.0 17 preadsec NaN 5000.0 10000.0 18 swapins NaN 250.0 500.0 19 cpupcent foo 30.0 90.0 20 pagins bar 456.0 123.0 I want to merge this df into another containing samples for these metrics. The thresholds are contained within the configuration as a set of default values with per-system overrides, as for rows 16 and 20 above. I'd like this to be reflected in the resulting join - if there is an override, it should take precedence over the default - however, I can only see this working by performing 2 merge ops - one for the default, another for the overrides - then a third to produce the final table. I believe in SQL i could do this using an OR clause, but I can't find a way to do so in Pandas. Does such a thing exist? Edit: For clarity, the other DF has this structure: SYSTEM_NAME METRIC CVAL 19886 foo cpupcent 89.281734 19887 bar swapins 41.799927 19888 bar pagins 123.92355 19889 quux preadsec 28.837423 19890 quux pagins 232.30303 So in the hypothetical merge, the resulting output would look like this: SYSTEM_NAME METRIC CVAL YELLOW RED 19886 foo cpupcent 89.281734 30.0 90.0 19887 bar swapins 41.799927 250.0 500.0 19888 bar pagins 123.92355 456.0 123.0 19889 quux preadsec 28.837423 5000.0 10000.0 19890 quux pagins 232.30303 500.0 1000.0 Here, bar's pagins has been overriden, while quux has taken the default value for YELLOW and RED. Since the override is only for pagins, bar's swapins is the default.
has comment: http://stackoverflow.com/comment/90583820

http://stackoverflow.com/a/51893414
answers question: http://stackoverflow.com/q/51893225
has comment: http://stackoverflow.com/comment/90738403
has comment: http://stackoverflow.com/comment/90738340
downvote count: 0
has comment: http://stackoverflow.com/comment/90738037
has body: Usually it is better not to store things as an array. First of all, not all databases have arrays, and furthermore, it usually will only create more trouble to do (efficient) querying, especially if the elements in the array refer to other objects. You usually store many-to-relations in a separate table. Django has support for this: a ManyToManyField [Django-doc]. Furthermore the code probably already has a problem: you store users as a CharField. Now imagine that a user changes their username, then there is no longer a link here. If you want to refer to objects in (another) model, you should use relations, like a ForeignKey, OneToOneField, or ManyToManyField. So we can probably rewrite it to: from django.db import models from django.conf import settings class Contexts(models.Model): context_name = models.CharField(max_length=50) context_description = models.TextField() users = ManyToManyField(settings.AUTH_USER_MODEL) The nice thing is, we no longer need to care about how Django represents this (efficiently), we can simply obtain all the Users of a some_context with some_context.users.all(). Those are then User objects (or other model objects if you later change the user model). We can then add a User to an objects as follows: @csrf_exempt def context_operation(request): user_request = json.loads(request.body.decode('utf-8')) if request.method == "POST": try: if user_request.get("action") == "add": print("add") conv = Contexts.objects.create( context_name=user_request.get("context_name"), context_description=user_request.get("context_description"), ) my_user = User.objects.get(username=user_request.get("user")) conv.users.add(my_user) except Exception as e: print("Context saving exception", e) return HttpResponse(0) return HttpResponse(1) So we can fetch the user, and add it to the field. If you user_request.get('user') contains the primary key of the user, we can even omit fetching the User object, and use: @csrf_exempt def context_operation(request): user_request…
has comment: http://stackoverflow.com/comment/90737986
type: Answer
score: 3
upvote count: 3

http://stackoverflow.com/q/51862123
tagged with: python
score: -2
has answer: http://stackoverflow.com/a/51862216
answer count: 1
has body: I have two variables x1=123.12 and y1=123.45 which holds user entered values .Now I have a text file in which I have to change current 245.42 and 130.32 with the variable x1 and y1 which holds user entered values.So how can I modify text file in python? #text file: var char12 name andy jordan home illino w1 345 3456 p1 346 2123 addmoney 245.42 netmoney 130.32
has comment: http://stackoverflow.com/comment/90676664
has title: Edit specific line at specific position in Text file in Python
accepted answer: http://stackoverflow.com/a/51862216
has comment: http://stackoverflow.com/comment/90676688
has comment: http://stackoverflow.com/comment/90676527
type: AnsweredQuestion
upvote count: 0
favorite count: 0
type: Question
downvote count: 2

http://stackoverflow.com/q/51863976
has answer: http://stackoverflow.com/a/51864221
score: 3
has body: I want to set the parent cage value to the value that has_highest_owner == 'Yes' Based on the grouping by the id column. id has_highest_owner parent_cage 834951691 3TNF2 834951691 4D149 834951691 Yes 4TMM7 In my case I want to set the parent cage of all rows to 4TMM7 id has_highest_owner parent_cage 834951691 4TMM7 834951691 4TMM7 834951691 Yes 4TMM7
type: Question
has answer: http://stackoverflow.com/a/51864343
tagged with: pandas
downvote count: 0
favorite count: 0
has title: Pandas Set value in a group based on condition
answer count: 3
tagged with: python
has comment: http://stackoverflow.com/comment/90680210
type: UnansweredQuestion
upvote count: 3
has answer: http://stackoverflow.com/a/51864228

insertion-sort
tags question: http://stackoverflow.com/q/51914767
tag name: insertion-sort
type: Tag

http://stackoverflow.com/comment/90791570
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51920697
type: Comment
has text: How do I do that specifically?

http://stackoverflow.com/comment/90902037
type: Comment
has text: Quick question Kunchur, what about if I want to use time_binned column data as my xsticks, do you know what will be the good method to do that?
comment on: http://stackoverflow.com/a/51939085
type: AnswerComment
score: 0

http://stackoverflow.com/a/51834816
accepted answer of: http://stackoverflow.com/q/51834217
answers question: http://stackoverflow.com/q/51834217
type: AcceptedAnswer
downvote count: 0
has body: you can use syntax Rakesh said data_list = [data_list[i:min(i+3, len(data_list)] for i in xrange(0, len(data_list_, 3)] also you can change your syntax in your template like this {% for i in a %} {% if forloop.counter0|divisibleby:3 %} {% endif %} {{ k }} {% if forloop.counter0|add:2|divisibleby:3 %} {% endif %} {% endfor %} {% ifequal a|length|divisibleby:3 False %} {% endifnotequal %} and here you dont want to split content to list of lists.
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/90624280
score: 1

http://stackoverflow.com/comment/90795794
type: QuestionComment
comment on: http://stackoverflow.com/q/51923086
has text: You say you have Spark at `/home/rxie/Downloads/spark`... but what is `SPARK_HOME=/home/rxie/spark/`?
score: 0
type: Comment

http://stackoverflow.com/comment/90831255
type: AnswerComment
type: Comment
score: 1
has text: This is the right way to do so , I think I am in the wrong direction to combine all x rather than a , which will create the problem with agg .
comment on: http://stackoverflow.com/a/51940430

http://stackoverflow.com/a/51836743
type: AcceptedAnswer
has body: I would recommend using pythons ArgumentParser (https://docs.python.org/2/howto/argparse.html) and just set a default= value for your argument. import argparse parser = argparse.ArgumentParser() parser.add_argument("argument", default="foobar") args = parser.parse_args() print arg print "Hello World!" You can also restructure your called python script to implement a "main" method with the arguments you need: def main(argument): print argument print "Hello World!" For your specific executables just create separate wrapper-scripts: foobar.py from test import main test("foobar") anotherfoobar.py from test import main test("anotherfoobar") Now you can use pyinstaller to create executables of foobar.py and anotherfoobar.py separatly.
has comment: http://stackoverflow.com/comment/90627696
upvote count: 2
type: Answer
score: 2
answers question: http://stackoverflow.com/q/51836628
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51836628

http://stackoverflow.com/comment/90819102
type: QuestionComment
type: Comment
score: 1
has text: Moreover, why use an external tool such as `curl` when Python has a built-in HTTP client library (though you'll probably want to use the third-party convenience library `requests`)?
comment on: http://stackoverflow.com/q/51934363

http://stackoverflow.com/a/51904878
score: 2
upvote count: 2
has body: It's because bool object are not iterable, even if bool object where iterable, it will do the same thing as the second example. Example: for i in True: print(i) Raises and error: Traceback (most recent call last): File "C:\Users\rep\Desktop\code\so.py", line 3517, in &lt;module&gt; for i in True: TypeError: 'bool' object is not iterable But: for i in 'True': print(i) Returns: T r u e And also: to solve them do: a,b = f(),f() And as @ggorlen says,do: def f(): return "Tr" Then: a, b = f()
answers question: http://stackoverflow.com/q/51904836
downvote count: 0
type: Answer

http://stackoverflow.com/q/51834411
has answer: http://stackoverflow.com/a/51834687
accepted answer: http://stackoverflow.com/a/51834687
score: 0
answer count: 1
tagged with: python-3.x
has body: I am extracting frames from a few videos in a directory using Open cv. While iterating through files, I am naming the frames obtained as frame0, frame1, and so on. But as the loop moves to the next video, it again starts naming the frames 0,1,2... and so all the old frames get overwritten. Here is what I did: #To make a list of paths to all files in dir f=[] for dirpath, subdir, files in os.walk(r'C:\Users\user\Desktop\Files'): for x in files: f.append(os.path.join(dirpath, x)) Function to extract frames: def extractFrames(pathIn, pathOut): cap = cv.VideoCapture(pathIn) count = 0 while (cap.isOpened()): ret, frame = cap.read() if ret == True: print('Read %d frame: ' % count, ret) cv.imwrite(os.path.join(pathOut, "frame{:d}.jpg".format(count)), frame) count += 1 else: break cap.release() cv.destroyAllWindows() Then i execute the code: pathOut=r'C:\Users\User\Desktop\Frames' def main(): for i in f: extractFrames(i, pathOut) if __name__=="__main__": main() How do I rectify so that when the loop encounters the next video after creating n frames, it starts naming them n+1, n+2,.... instead of starting again from 0 and overwriting ?
has title: Loop resets the count and overwrites the file
tagged with: python
tagged with: opencv
type: AnsweredQuestion
type: Question

http://stackoverflow.com/q/51843395
favorite count: 0
has comment: http://stackoverflow.com/comment/90640180
tagged with: timezone
has title: How to get weather report for a particular date using weatherbit.io api even timezone changes?
tagged with: datetime
has body: I am using weatherbit api to get historical weather report. It responds based on UTC or GMT time. But my timezone is different. For example api_values_call = requests.get('https://api.weatherbit.io/v2.0/history/hourly?key=yourapikey&amp;city=seattle,WA&amp;start_date=2018-08-12:00&amp;end_date=2018-08-12:24&amp;units=I') api_values = api_values_call.json() It returns weather report GMT/UTC 2018-08-12:00 to 2018-08-12:23 with timestamp. If i convert the utctimestamp to datetime with timezone('America/Los_Angeles') It starts previous day time (i.e) Los_Angels time is GMT-7:00 Hours. So I am getting report from 2018-08-11:17 since GMT-7 is applied to given timestamp. But i need weather report for full day. How can i get weather report from 2018-08-12:00 to 2018-08-12:23 even the timezone changes.
tagged with: python
has answer: http://stackoverflow.com/a/51870096
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90690493
score: 1
tagged with: http://stackoverflow.com/tag/json
upvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/51870096
tagged with: weather-api
downvote count: 0
answer count: 1

http://stackoverflow.com/comment/90787413
type: QuestionComment
score: 0
has text: No problems when using the default interpreter, just on virtual envs, dunno why pycharm can't detect it.
comment on: http://stackoverflow.com/q/51918167
type: Comment

http://stackoverflow.com/comment/90679370
type: Comment
comment on: http://stackoverflow.com/q/51862332
type: QuestionComment
has text: https://gist.github.com/LEvinson2504/c59fd08f4bec5f20792593ae498a0b70 the correct code(with identation) running in python can be found here
score: 0

http://stackoverflow.com/comment/90775939
has text: yeah, i ve closed env, reloaded data, and seems to works fine. on the first try i ve made some joins, reset on index and other changes on dataframe, one of those cases when 'something' went wrong
type: Comment
score: 0
comment on: http://stackoverflow.com/q/51912848
type: QuestionComment

http://stackoverflow.com/comment/90802113
type: Comment
comment on: http://stackoverflow.com/q/51924976
score: 0
type: QuestionComment
has text: What are alpha and lambda and what is the range of x? Note that the PDF should integrate to one over there range of the distribution.

http://stackoverflow.com/comment/90580824
type: QuestionComment
has text: Haven't you asked this already?
comment on: http://stackoverflow.com/q/51812972
score: 1
type: Comment

http://stackoverflow.com/comment/90598471
has text: this is a list comprehension
comment on: http://stackoverflow.com/q/51822269
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51879812
downvote count: 0
has title: How to detect and remove outliers from each column of pandas dataframe at one go?
favorite count: 0
upvote count: 8
has answer: http://stackoverflow.com/a/51880329
has body: I've a pandas data frame with six columns and i know there are some outliers in each column.So i have these two lines of code which is pretty much doing what i want to do. But it's removing outliers from only one column of the dataframe. so what if i want to remove outliers from each column together?? df = pd.DataFrame({'stlines':np.random.normal(size=533)}) df = df[np.abs(df.stlines-df.stlines.mean()) &lt;= (2*df.stlines.std())] what would be the elegant way to do this?
possible better answer: http://stackoverflow.com/a/51880063
tagged with: python
score: 8
accepted answer: http://stackoverflow.com/a/51880087
duplicate of: http://stackoverflow.com/q/23199796
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51880087
has answer: http://stackoverflow.com/a/51880063
tagged with: dataframe
type: Question
answer count: 3
tagged with: pandas
linked to: http://stackoverflow.com/q/23199796

vb6
type: Tag
tags question: http://stackoverflow.com/q/51872499
tag name: vb6

http://stackoverflow.com/comment/90867727
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51845170
has text: Hi,any updates ?Does my answer helps you?

http://stackoverflow.com/comment/90778062
comment on: http://stackoverflow.com/q/51913931
type: Comment
type: QuestionComment
score: 0
has text: Possible Duplicate: [Python TypeError: unsupported operand type(s) for -: 'int' and 'function'](https://stackoverflow.com/questions/12923264/python-typeerror-unsupported-operand-types-for-int-and-function)

boto
tags question: http://stackoverflow.com/q/51870479
type: Tag
tags question: http://stackoverflow.com/q/51893481
tags question: http://stackoverflow.com/q/51953557
tags question: http://stackoverflow.com/q/51828454
tags question: http://stackoverflow.com/q/51830623
tag name: boto
tags question: http://stackoverflow.com/q/51947006

http://stackoverflow.com/q/51829190
has answer: http://stackoverflow.com/a/66677889
has comment: http://stackoverflow.com/comment/90612969
has answer: http://stackoverflow.com/a/51829465
has comment: http://stackoverflow.com/comment/90613123
has body: I'm developing an expression to validate all possible phone number formats. I have 50%, it is not validating me the admitted characters by means of * . - whitespace These are the rules It can contain open and close parenthesis ex. (55) It can contin or not '+' char ex. (+52) It can contain 2 or 3 numbers inside parenthesis ex. (+555) o (+55) It can contain whitespace between close parenthesis and the next numbers ex. (55) 44332211 The consecutive numbers to the parenthesis must be 6 or 8 numbers ex. (55)443322 o (55)44332211 The consecutive numbers to the parenthesis can contain whitespaces, dashes, asterisks, or colons. ex.(55)44-33-22-11 o (55)44 33 22 11 o (55)44*33*22*11 o (55)44.33.22.11 The consecutive numbers to the parenthesis can be divided in groups of 2, 3 or 4 numbers ex. (55)5544-3322 o (55)55 44 33 22 o (555)444*333 The number format can come in a row of 8, 10 o 12 numbers ex. 55443322 o 5544332211 o 554433221100 This is the regular expression [\(]?[\+]?(\d{2}|\d{3})[\)]?[\s]?((\d{6}|\d{8})|(\d{3}[\*\.\-\s]){3}|(\d{2}[\*\.\-\s]){4}|(\d{4}[\*\.\-\s]){2})|\d{8}|\d{10}|\d{12} This is a map of the regular expression What am I doing wrong? I leave an example script, the regex I'm doing for Python, I do not know if I change a lot with JS $(function(){ $('ul li').each(function(){ let number = $(this).text(); let regex = /^[\(]?[\+]?(\d{2}|\d{3})[\)]?[\s]?((\d{6}|\d{8})|(\d{3}[\*\.\-\s]){3}|(\d{2}[\*\.\-\s]){4}|(\d{4}[\*\.\-\s]){2})|\d{8}|\d{10}|\d{12}$/; let res = regex.test( number ); $(this).text( $(this).text() + ' is: ' + res); }); }) Telephone numbers test (55)test (55)333-test (55)test 22 554433221100 5544332211 55443322 (55)443322 (55)44332211 (+55)443322 (+55)44332211 (55)4433*2211 (55)444.333 (55)44-33-22-11 (55)4433-2211 (+55)443 322
has title: Telephone number regex all formats
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90612885
downvote count: 0
has comment: http://stackoverflow.com/comment/90613253
has answer: http://stackoverflow.com/a/55368267
favorite count: 0
has comment: http://stackoverflow.com/comment/90613427
type: Question
score: 3
accepted answer: http://stackoverflow.com/a/51829465
possible better answer: http://stackoverflow.com/a/55368267
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/90613561
upvote count: 3
answer count: 3

http://stackoverflow.com/q/51868967
answer count: 1
has body: I'm aware that you can override the egg cache directory with the environment variable PYTHON_EGG_CACHE, and that you can look that override up in os.envrion. It looks like the default for Python 2.7 on Ubuntu 16 is /.cache/Python-Eggs. How would you log the location of the egg cache when there is no PYTHON_EGG_CACHE provided in the environment?
accepted answer: http://stackoverflow.com/a/51869400
has title: How do you determine the current Python egg cache directory?
tagged with: python
type: AnsweredQuestion
score: 0
type: Question
has answer: http://stackoverflow.com/a/51869400

http://stackoverflow.com/q/51804780
tagged with: python
type: AnsweredQuestion
tagged with: introspection
tagged with: reflection
upvote count: 3
tagged with: collections
has title: Python + MongoDB, how to dynamically choose DB Collection
has answer: http://stackoverflow.com/a/51804929
type: Question
tagged with: mongodb
has body: How can I dynamically point to a particular collection name in MongoDB with Python? I receive data from any 1 of a few dozen sensors in my network, and I want to store the raw data into a db collection named for the sensor. # Server Parameters host = '1.2.3.4' port = 27017 client = MongoClient(host, port) db = client.myDB # use database myDB # receive data from sensors # {"sensorName":"...", "x":"...", "y":"...", "z":"...", "time":"..."} db.SensorA.insert_one({...}) # record raw data in the collection for SensorA db.SensorB.insert_one({...}) db.SensorC.insert_one({...}) Instead of explicitly writing db.SensorName.insert_one({...}), I'd like to somehow reference the given sensor/collection name. Thanks
score: 3
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/51804929
favorite count: 0

http://stackoverflow.com/a/56568830
has body: @Willem Van Onsem's answer worked for me. On an implementation note, if you rather keep your view code separate from urls (also if you have some processing to do), you would write your urls.py like this (based on a per-app urls.py file in your app folder which means you have to include it in the overall urlpatterns of the project's urls.py file which is in the same folder as your settings.py file, with the syntax path('', include('users.urls')),): from django.urls import path from .views import ( login_view ) app_name = "userNamespace" urlpatterns = [ path('login/', loginView.as_view(), name="login-view"), ] and over in your views.py file you would have something like this: from django.shortcuts import render from django.contrib.auth.views import ( LoginView, ) from users.models import User class login_view(LoginView): # The line below overrides the default template path of &lt;appname&gt;/&lt;modelname&gt;_login.html template_name = 'accounts/login.html' # Where accounts/login.html is the path under the templates folder as defined in your settings.py file
upvote count: 1
answers question: http://stackoverflow.com/q/51906428
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/comment/90762687
score: 0
type: AnswerComment
type: Comment
has text: Thank You so much for your suggestion. It is helpful.
comment on: http://stackoverflow.com/a/51905868

http://stackoverflow.com/q/51913147
has comment: http://stackoverflow.com/comment/90778065
has comment: http://stackoverflow.com/comment/90776884
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90776566
has comment: http://stackoverflow.com/comment/90776606
type: Question
has comment: http://stackoverflow.com/comment/90776504
tagged with: numpy
has title: Numpy add outer, string change?
has body: I have a dataframe df1= HPE FRE UNE 0 S0 S0 S0 1 S1 S1 S1 using the below code("reduce" is a functool function, sta is a list containing the columns of df1): reduce(lambda x,y:np.add.outer(x,y),sta).reshape(-1) I reduced my dataframe to numpy array like this: ['S0S0S0' 'S0S0S1' 'S0S1S0' 'S0S1S1' 'S1S0S0' 'S1S0S1' 'S1S1S0' 'S1S1S1'] but I want my output to look like below: ['S0|S0|S0' 'S0|S0|S1' 'S0|S1|S0' 'S0|S1|S1' 'S1|S0|S0' 'S1|S0|S1' 'S1|S1|S0' 'S1|S1|S1'] How can I do?
has answer: http://stackoverflow.com/a/51914068
tagged with: functools
accepted answer: http://stackoverflow.com/a/51914068
tagged with: arrays
tagged with: string
score: 0
answer count: 1

http://stackoverflow.com/a/51913965
score: 0
type: Answer
has body: Functions are type of function you need to first call it So need: giventhing = Thing() print(giventhing.sumit()/2) So totally need parentheses Here's an example: &gt;&gt;&gt; class A: def __init__(self,a): self.a=a def out(self): return self.a &gt;&gt;&gt; A &lt;class '__main__.A'&gt; &gt;&gt;&gt; a=A(1) &gt;&gt;&gt; a.out &lt;bound method A.out of &lt;__main__.A object at 0x0000005F9D177EB8&gt;&gt; &gt;&gt;&gt; a.out() 1 &gt;&gt;&gt;
answers question: http://stackoverflow.com/q/51913931

http://stackoverflow.com/a/52180634
answers question: http://stackoverflow.com/q/51840815
has body: One possible way is using a classifier to remove unwanted images from your dataset but this way is useful only for huge datasets and it is not as reliable as the normal way (manual cleansing). For example, an SVM classifier can be trained to extract images from each class. More details will be added after testing this method.
score: 0
type: Answer

http://stackoverflow.com/q/51842166
score: 2
tagged with: tensorflow-lite
tagged with: tensorflow
type: Question
downvote count: 0
has title: Convert TensorFlow model with boolean input placeholder to TensorFlow Lite
has comment: http://stackoverflow.com/comment/90755573
has body: I have a ResNet model which I trained with Ubuntu 16.04 and TensorFlow v1.10.0. I want to convert this model for use in TensorFlow Lite. The model has two input placeholders. First, the image (1 x 512 x 512 x 3) and then a boolean placeholder which is defined as is_training = tf.placeholder_with_default(False, shape=(), name="is_training") I convert the model to a standalone GraphDef file as follows: bazel run -c opt tensorflow/python/tools:freeze_graph -- --input_graph=/home/user/model/graph.pbtxt --input_checkpoint=/home/user/model/model-checkpoint --output_graph=/home/user/model/frozen.pb --output_node_names=output which works. In a second step, I want to convert the standalone GraphDef file to the TFLite format: bazel run -c opt //tensorflow/contrib/lite/python:tflite_convert -- --output_file=/home/user/model/model.lite --graph_def_file=/home/user/model/frozen_model.pb --input_arrays=model_input/input --output_arrays=output --input_shape=1,512,512,3 which fails with the following error message: RuntimeError: TOCO failed see console for info. b'2018-08-14 10:10:00.486547: I tensorflow/core/platform/cpu_feature_guard.cc:141] Your CPU supports instructions that this TensorFlow binary was not compiled to use: SSE4.1 SSE4.2 AVX 2018-08-14 10:10:00.680867: I tensorflow/contrib/lite/toco/import_tensorflow.cc:1096] Converting unsupported operation: Iterator 2018-08-14 10:10:00.680949: I tensorflow/contrib/lite/toco/import_tensorflow.cc:1096] Converting unsupported operation: IteratorGetNext 2018-08-14 10:10:00.804511: I tensorflow/contrib/lite/toco/graph_transformations/graph_transformations.cc:39] Before Removing unused ops: 1662 operators, 2722 arrays (0 quantized) 2018-08-14 10:10:00.860103: I tensorflow/contrib/lite/toco/graph_transformations/graph_transformations.cc:39] After Removing unused ops pass 1: 1551 operators, 2558 arrays (0 quantized) 2018-08-14 10:10:00.933723: I tensorflow/contrib/lite/toco/graph_transformations/graph_transformations.cc:39] Before gener…
has comment: http://stackoverflow.com/comment/90639570
favorite count: 0
has comment: http://stackoverflow.com/comment/90639748
answer count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/51932870
type: AnsweredQuestion
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/51933510
linked to: http://stackoverflow.com/q/37031456
type: Question
has comment: http://stackoverflow.com/comment/90816481
has title: Create Python Package with Single PYD File
upvote count: 1
answer count: 1
favorite count: 0
tagged with: python-3.x
has body: I have a single pyd file (dynamically linked library), say MyPackage.pyd. When putting it in the same folder as my py scripts I can simply do import MyPackage and then use its functions via MyPackage.FUNC (where FUNC is any function name). How do I package this pyd file up into a folder under \PYTHONPATH\Lib\site-packages\ so that I can do import MyPackage without having to have the pyd file in the same folder as my scripts anymore? My guess is I need to create a folder \PYTHONPATH\Lib\site-packages\MyPackage\, copy MyPackage.pyd into it, and then create a __init__.py file in there. But I am unsure what to write into this file? Question Include *.pyd files in Python Packages didn't help, unfortunately.
tagged with: package
tagged with: windows
accepted answer: http://stackoverflow.com/a/51933510
tagged with: python
has comment: http://stackoverflow.com/comment/90817023

http://stackoverflow.com/q/51879564
has answer: http://stackoverflow.com/a/51879813
has title: How do I fill in the column names of an insert statement in python
has body: I want to use Python to insert some data into a db. Skipping a ton of code, I use something like this: cursor.execute('insert into table_name (column1, column2) values (%s, %s)', variable1, variable2) All well and good. I am fetching data from multiple endpoints of an API which all return data in a fairly flat format, for example: [ { "LearnerId": 123456, "LearnerCode": "654321", "Date": "2018-07-02", "Session": "AM", "AttendanceCode": "/\\", "AttendanceCodeId": 1, "MinutesLate": null, "Notes": null, "ClassDateRollId": 347514, "GroupCode": "7A", "EnteredDate": "2018-07-02 10:10:24" }, { "LearnerId": 778832, "LearnerCode": "837478", "Date": "2018-07-02", "Session": "AM", "AttendanceCode": "/\\", "AttendanceCodeId": 1, "MinutesLate": null, "Notes": null, "ClassDateRollId": 347514, "GroupCode": "9E", "EnteredDate": "2018-07-02 10:12:34" } ] The actual data and key:value pairs differ from endpoint to endpoint, but the basic structure (I.E. a single 'level' of a dictionary per item in the list) is the same for each endpoint. Each endpoint is basically dropping data into a table where the column names exactly replicate the Keys in the JSON, so I would really like a single insert function that simply iterates over the json and builds the insert statement from that, filling in the column names using the keys and values using the values. I can do that for the values like so: a = [ { 'foo':'one', 'bar':'two' } ] cursor.execute('insert into table_name (foo, bar) values (%s, %s)', tuple(a[0].values())) But I can't manage to programatically fill in the '(foo, bar)' bit so that I don't have to type out the column names manually. How do I do that bit, please?
score: 0
tagged with: sql
tagged with: mysql-connector-python
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/51879813
possible better answer: http://stackoverflow.com/a/51879820
has answer: http://stackoverflow.com/a/51879820
tagged with: python
type: AnsweredQuestion
tagged with: mysql
type: Question
answer count: 2

http://stackoverflow.com/a/51876710
has body: The problem is in your display function, where you need to switch the order of extracting data and moving on to the next node. Otherwise you won't hit the first node that you've entered in your list. while current_node.next is not None: node_elements.append(current_node.data) current_node = current_node.next
score: 0
has comment: http://stackoverflow.com/comment/90706574
type: Answer
answers question: http://stackoverflow.com/q/51875669

http://stackoverflow.com/a/51927796
has comment: http://stackoverflow.com/comment/90805700
has body: import sys while True: operation = input("how long has your company been operating for?: ") if operation.isdigit(): operation = int(operation) if operation &gt; 5: print("Wow your company has gone on for quite some time now, huh?") break else: print("Sorry your company does not fit into our criteria") exit() else: print("please enter a number")
has comment: http://stackoverflow.com/comment/90805944
accepted answer of: http://stackoverflow.com/q/51927724
type: Answer
answers question: http://stackoverflow.com/q/51927724
upvote count: 1
has comment: http://stackoverflow.com/comment/90805627
score: 1
has comment: http://stackoverflow.com/comment/90807252
has comment: http://stackoverflow.com/comment/90805901
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90805541

http://stackoverflow.com/comment/90621060
has text: @Reblochon Masque. Yes. Thank you.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51833145
type: Comment

http://stackoverflow.com/comment/90581269
comment on: http://stackoverflow.com/a/51812915
has text: you should import it form `django.contrib.auth.views` not `django.contrib.views`
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/90771163
comment on: http://stackoverflow.com/q/51910372
has text: @roganjosh The question says _I'm trying to identify index positions that contain the character '1'_ That's a boolean property; either a given index position contains '1', or it does not. It's immaterial if it happens once, twice, or ten times. Also, the code itself is behaving this way. So that's two-for-two.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/115425796
type: Comment
has text: Your solution would work. But creating new CLI app for this task is an overkill. Inno Setup can create text files directly. See [Write serial to file using Inno Setup](https://stackoverflow.com/q/25870729/850848).
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/51855686

http://stackoverflow.com/comment/90835757
type: QuestionComment
has text: @ParthS007. I have try it but it is not same as the desired output.
comment on: http://stackoverflow.com/q/51942945
score: 0
type: Comment

http://stackoverflow.com/q/51801917
has answer: http://stackoverflow.com/a/51801991
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python
tagged with: unicode-normalization
has body: I'm having problem in Python when met composition unicode instead of built-in unicode. Here is reproduce code: # encoding=utf8 a = ["Địa"] b = ["Địa"] print(a) # ['\xc4\x90i\xcc\xa3a'] print(b) # ['\xc4\x90\xe1\xbb\x8ba'] print("Địa" in a) # False print("Địa" in b) # True How can I convert/normalize them into the same encoder?
type: AnsweredQuestion
score: 1
upvote count: 1
has title: Different encoding when using unicode character in Python
accepted answer: http://stackoverflow.com/a/51801991
type: Question
tagged with: python-unicode

http://stackoverflow.com/q/51844916
has comment: http://stackoverflow.com/comment/90643525
has title: Pandas: conditional dataframe splitting in regular periods
type: Question
has comment: http://stackoverflow.com/comment/90801599
has comment: http://stackoverflow.com/comment/90643295
has comment: http://stackoverflow.com/comment/90643932
tagged with: python-2.7
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/90659717
has body: I have a dataframe where there is a datetime column indicating the beginning of a certain condition (A,B, or C), the value associated to that condition (value) and a counter equal to the sum of minutes between the beginning and the end of the condition. It looks like this: date Value Condition count 0 2018-05-01 06:29:00 0.0 A 1 1 2018-05-01 06:30:00 0.2116250035663446 A 2 2 2018-05-01 06:31:00 2.5572083791097007 A 3 3 2018-05-01 06:32:00 3.4874167144298553 A 4 4 2018-05-01 06:33:00 3.542041709025701 A 5 5 2018-05-01 06:34:00 3.517166723807653 A 6 6 2018-05-01 06:35:00 3.9571250875790915 A 7 7 2018-05-01 06:36:00 5.0706249078114825 B 1 8 2018-05-01 06:37:00 5.062458336353302 B 2 9 2018-05-01 06:38:00 5.051083226998647 B 3 10 2018-05-01 06:39:00 5.049999952316284 B 4 11 2018-05-01 06:40:00 5.061791678269704 B 5 12 2018-05-01 06:41:00 5.025291681289673 B 6 13 2018-05-01 06:42:00 5.065833310286204 B 7 14 2018-05-01 06:43:00 5.051874856154124 B 8 15 2018-05-01 06:44:00 5.073999881744385 B 9 16 2018-05-01 06:45:00 5.04304164648056 B 10 17 2018-05-01 06:46:00 5.090916752815247 B 11 18 2018-05-01 06:47:00 5.045083403587341 B 12 19 2018-05-01 06:48:00 5.036874949932098 B 13 20 2018-05-01 06:49:00 5.047999858856201 B 14 21 2018-05-01 06:50:00 5.048500041166942 B 15 22 2018-05-01 06:51:00 5.031458218892415 B 16 23 2018-05-01 06:52:00 5.036749978860219 B 17 24 2018-05-01 06:53:00 5.057374894618988 B 18 25 2018-05-01 06:54:00 5.065375049908956 B 19 26 2018-05-01 06:55:00 5.101583381493886 B 20 27 2018-05-01 06:56:00 5.064416746298472 B 21 28 2018-05-01 06:57:00 5.0727916558583575 B 22 29 2018-05-01 06:58:00 5.059083342552185 B 23 30 2018-05-01 06:59:00 5.067666749159495 B 24 31 2018-05-01 07:00:00 5.063124974568685 B 25 32 2018-05-01 07:01:00 5.068083385626475 B 26 33 2018-05-01 07:02:00 5.06870836019516 B 27 34 2018-05-01 07:03:00 5.083666622638702 B 28 35 2018-05-01 07:04:00 5.065375069777171 B 29 36 2018-05-01 07:05:00 5.0842918157577515 B 30 37 2018-05-01 07:06:00 5.0976250…
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90712695
tagged with: python
has comment: http://stackoverflow.com/comment/90801533

http://stackoverflow.com/a/51915421
score: 0
accepted answer of: http://stackoverflow.com/q/51915379
type: Answer
has comment: http://stackoverflow.com/comment/90780813
has comment: http://stackoverflow.com/comment/90780881
has body: Static files are for stylesheets javascript and other static documents. you can add a template as view in your urls.py from django.urls import include, path from django.views.generic import TemplateView urlpatterns = [ path('sub/', TemplateView.as_view(template_name='sub.html'), name='sub') ] Then in your index.html template: Next
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90780894
answers question: http://stackoverflow.com/q/51915379

variables
tag name: variables
tags question: http://stackoverflow.com/q/51830966
tags question: http://stackoverflow.com/q/51904984
tags question: http://stackoverflow.com/q/51924485
tags question: http://stackoverflow.com/q/51805718
type: Tag
tags question: http://stackoverflow.com/q/51902830
tags question: http://stackoverflow.com/q/51879112
tags question: http://stackoverflow.com/q/51799746
tags question: http://stackoverflow.com/q/51888774
tags question: http://stackoverflow.com/q/51828012

http://stackoverflow.com/a/51803116
type: AcceptedAnswer
downvote count: 0
score: 6
has body: Duplicate expressions are not "somehow optimized away". Use a local variable to capture and re-use a result that is 'known not to change' and 'takes some not-insignificant time' to create; or where using a variable increases clarity. In this case, it's impossible for Python to know that 'text.split()' is pure - a pure function is one with no side-effects and always returns the same value for the given input. Trivially: Python, being a dynamically-typed language, doesn't even know the type of 'text' before it actually gets a value, so generalized optimization of this kind is not possible. (Some classes may provide their own internal 'cache optimizations', but digressing..) As: even a language like C#, with static typing, won't/can't optimize away general method calls - as, again, there is no basic enforceable guarantee of purity in C#. (ie. What if the method returned a different value on the second call or wrote to the console?) But: a Haskell, a Purely Functional language, has the option to not 'evaluate' the call twice, being a different language with different rules...
answers question: http://stackoverflow.com/q/51803046
accepted answer of: http://stackoverflow.com/q/51803046
type: Answer
upvote count: 6

http://stackoverflow.com/comment/90746212
has text: Why do you think you need to convert the path? Did you try to use the path and get an error? If so, what's the error?
type: QuestionComment
comment on: http://stackoverflow.com/q/51888460
score: 0
type: Comment

http://stackoverflow.com/comment/90682906
comment on: http://stackoverflow.com/q/51865271
score: 0
type: QuestionComment
has text: Sound like an good application for a `property`.
type: Comment

http://stackoverflow.com/comment/90625443
type: AnswerComment
has text: @rabbitholefinder - hmmm, last 2 columns are float and int, so it should be aggregated.
score: 0
comment on: http://stackoverflow.com/a/51835582
type: Comment

http://stackoverflow.com/q/51872486
has title: Why I am getting invalid result?
has answer: http://stackoverflow.com/a/51872577
type: Question
answer count: 1
favorite count: 0
score: 0
has body: #input is of type U-1011-13-F-CS-498 where U 1011 AND F is fixed and all are varying import re def validateEnrollment(eno): match_obj=re.findall(r'("U")\-("1011")\-("[0-99]")\-("F")\-(["CS|EC|BT"])\-("[000-999]")',eno,re.I|re.M) if match_obj: print("Your eno is valid",match_obj) else: print("Invalid eno") eno=input("enter your enrollment number") print("the enrollment number is",validateEnrollment(eno))
tagged with: python
type: UnansweredQuestion
upvote count: 1
downvote count: 1

http://stackoverflow.com/a/54067285
downvote count: 0
has body: Try going to https://www.hackerrank.com/challenges/python-loops/problem where the single input line is already there in the starter code for you. If you select Python 3 from the language dropdown, and then -- without entering any code of your own at all -- click Run Code, you should get a Wrong Answer "no response on stdout" response. Do you get that, or do you still get an EOFError? I'm assuming you don't get the EOFError and that perhaps there's a problem with where/how you're entering your code into their editor. If you're getting an error like that with InterviewBit, I'd say it's because with InterviewBit you're not supposed to be reading from stdin at all -- the starter code will have a function that their test cases call, and then you complete the function code to return the desired output.
score: 1
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51799737
accepted answer of: http://stackoverflow.com/q/51799737
type: Answer

http://stackoverflow.com/a/51859787
has comment: http://stackoverflow.com/comment/90672202
has comment: http://stackoverflow.com/comment/90672501
type: Answer
has body: Looking at your bigger picture directly, normal python logic operators can help you with this, the and stops at the first False. So this works just fine: nissan and nissan.get_owner() or None
answers question: http://stackoverflow.com/q/51859708
score: 0

http://stackoverflow.com/comment/114885064
type: AnswerComment
has text: "However, it seems they cannot be edited directly while they are being iterated through." sure they can. It's just that in this particular case the list contains `int` object which don't expose any mutator methods, i.e., they are *immutable*.
comment on: http://stackoverflow.com/a/51804807
type: Comment
score: 3

http://stackoverflow.com/q/51858476
type: Question
has body: I want to stream a complete playlist (m3u) using libvlc with Python. I was able to stream a single video using the following code: inst = vlc.Instance() param=[ "test.mp4" ,"sout=#rtp{dst=224.1.1.10,port=10100,mux=ts}" ] Media = inst.media_new(*param) player = Media.player_new_from_media() player.play() The problem is, it seems there is no way to pass options to a playlist. I tried to pass them when creating the vlc instance but that doesn't work. inst = vlc.Instance('--sout=#gather:rtp{dst=224.1.1.10,port=10100,mux=ts}') Media_list = inst.media_list_new(['test.m3u']) list_player = inst.media_list_player_new() list_player.set_media_list(Media_list) list_player.play() The same code works correctly when playing locally. Thanks,
tagged with: python
answer count: 1
tagged with: vlc
tagged with: libvlc
score: 0
tagged with: video-streaming
has answer: http://stackoverflow.com/a/52004530
type: AnsweredQuestion
has title: Streaming a playlist using libvlc with Python
accepted answer: http://stackoverflow.com/a/52004530

http://stackoverflow.com/comment/90674604
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51857973
has text: https://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.nditer.html#numpy.nditer seems to have an option for "contiguous operands" but is not clear what it means. I have tried `for x in np.nditer(_a, op_flags='readonly','contig'): print(x)` but it just prints them in the regular way
score: 0

http://stackoverflow.com/a/54471718
score: 0
type: Answer
has body: There's no need to create a token in both sides. Use JWT strategy with a pub priv key algorithm like RS256. With this you can sign the JWT token in one API and able to verify with a public key in your other API.
answers question: http://stackoverflow.com/q/51832272
has comment: http://stackoverflow.com/comment/96124272

http://stackoverflow.com/a/51886937
accepted answer of: http://stackoverflow.com/q/51886802
score: 2
has comment: http://stackoverflow.com/comment/90830152
has comment: http://stackoverflow.com/comment/90753346
has comment: http://stackoverflow.com/comment/90830044
upvote count: 2
has comment: http://stackoverflow.com/comment/90749472
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90753121
has comment: http://stackoverflow.com/comment/90829767
has comment: http://stackoverflow.com/comment/90750880
has body: Something like this: def nmonthaccuracy(basefilenumber, n): basefileread = pd.read_csv(str(basefilenumber)+'.csv', encoding='Latin-1') basefilevalue = basefileread.loc[basefileread['Customer'].str.contains('Lam DepT', na=False), 'Jun-16\nQty'] nmonthread = pd.read_csv(str(basefilenumber-n)+'.csv', encoding = 'Latin-1') nmonthvalue = nmonthread.loc[nmonthread['Customer'].str.contains('Lam DepT', na=False), 'Jun-16\nQty'] return int(nmonthvalue)/int(basefilevalue) N = 2 total_by_month = [0] * N total_aggregate = 0 for basefilenumber in range(20,30): for n in range(N): a = nmonthaccuracy(basefilenumber, n) total_by_month[n] += a total_aggregate += a In case you are wondering what the following code does: N = 2 total_by_month = [0] * N It sets N to the number of months desired (2, but you could make it 12 or another value) and it then creates a total_by_month array that can store N results, one per month. It then initializes total_by_month to all zeroes (N zeroes) so that each of the N monthly totals starts at zero.
type: Answer
has comment: http://stackoverflow.com/comment/90829971
answers question: http://stackoverflow.com/q/51886802
has comment: http://stackoverflow.com/comment/90750269
has comment: http://stackoverflow.com/comment/90725334

http://stackoverflow.com/q/51925504
score: 0
answer count: 1
tagged with: alfresco
has answer: http://stackoverflow.com/a/51990447
accepted answer: http://stackoverflow.com/a/51990447
tagged with: python
type: AnsweredQuestion
tagged with: cmis
type: Question
has body: How do I update a existing file in alfresco using CMis through Python Below is the method i use to upload files def alfresco_post_file(url, user, pwd, root_folder, post_folder, post_file, file_name, logger): client = CmisClient(url, user, pwd) repo = client.defaultRepository try: folder = repo.getObjectByPath('/'+root_folder) if post_folder: folder = repo.getObjectByPath('/'+post_folder) contents = open(post_file, 'r') file = folder.createDocument(file_name, contentFile = contents) except Exception as e: sys.exc_clear() if type(e).__name__ == 'ObjectNotFoundException': folder = repo.getObjectByPath('/'+root_folder) createfolder = folder.createFolder(post_folder.replace(root_folder+'/','')) folder = repo.getObjectByPath('/'+post_folder) contents = open(post_file, 'r') file = folder.createDocument(file_name, contentFile = contents) #elif type(e).__name__ == 'UpdateConflictException': #folder = repo.getObjectByPath('/'+post_folder) #contents = open(post_file, 'r') #file = folder.updateDocument(file_name, contentFile = contents) else: print("(alfresco_post_file) Execution failed:", e) logger.info('(alfresco_post_file) Execution failed:' + str(e));
has title: Update a existing file in alfresco using Python

http://stackoverflow.com/comment/90687371
has text: What if you pad your substitute value with whitespace before it gets substituted?
type: QuestionComment
comment on: http://stackoverflow.com/q/51867748
score: 1
type: Comment

http://stackoverflow.com/comment/90825667
type: Comment
type: QuestionComment
has text: Can you please post the code you used and show what it returns? That way we can see how it differs from your expectations
score: 0
comment on: http://stackoverflow.com/q/51937709

http://stackoverflow.com/comment/90834040
comment on: http://stackoverflow.com/q/51942198
type: Comment
score: 0
type: QuestionComment
has text: @metatoaster thankyou, but I cannot have my program sleep for a full second, which is why i reckoned it is not a duplicate of the linked question. Please advice if Im mistaken here

http://stackoverflow.com/comment/90765465
type: Comment
type: QuestionComment
score: 1
has text: Because patching is done after the entity-to-patch is imported? Patching will not effect the code executed on module import. If you want `Cat` to be mocked when the line `cat = Cat('kitty')` is executed, patching `cat.Cat` should help.
comment on: http://stackoverflow.com/q/51898886

http://stackoverflow.com/comment/90620052
comment on: http://stackoverflow.com/a/51832952
score: 0
type: AnswerComment
has text: Just the last thing. why i'm getting this 10.11.1.250 <built-in function all> 10.11.1.251 <built-in function all> i want to remove built-in function.. And can you please tell me why we use %d????
type: Comment

http://stackoverflow.com/q/51877005
tagged with: pycharm
answer count: 0
has body: 1. What does Pycharm do when I run a python script? My hypothesis - in the default configuration PyCharm does the following: Adds source and content roots to the PYTHONPATH. Switch working directory to the directory of the script. Run the script. Because that project root is a content root, it will be added to the PYTHONPATH and relative imports will work (relative to the project root). 2. Is there a way to easily replicate this from a terminal? Ideas: Run python -m scripts.some_script from the project root. Relative imports will work, but the working directory will be the project root. Permamently project root to PYTHONPATH, run the script from its folder. 3. Alternatively, change PyCharm configuration? I guess there is a good reason why PyCharm configuration is exactly what it is now, but if not, maybe it makes sense to always set working directory to the root of the project? My motivation: I am doing a small scientific project. I want to run my simulations on a remote machine using SSH, and I cannot spend too much time to set it up. The project code is constantly updated via git. New parts (new simulations) are frequently added to the project.
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90707260
tagged with: python
has comment: http://stackoverflow.com/comment/90712079
type: Question
score: 0
has title: What are PyCharm actions when it runs a python script?

http://stackoverflow.com/comment/90714375
comment on: http://stackoverflow.com/q/51881487
score: 0
type: QuestionComment
has text: Try `print(variable_one + "\t\t-\tAge:\t40")`
type: Comment

http://stackoverflow.com/q/51895999
accepted answer: http://stackoverflow.com/a/51901214
score: 0
answer count: 1
tagged with: keras
has comment: http://stackoverflow.com/comment/90742615
has title: Flatten() Layer in Keras with variable input shape
tagged with: python
has answer: http://stackoverflow.com/a/51901214
type: AnsweredQuestion
has body: I am working with a CNN implemented in Keras which at some point has a flatten layer. Now, my goal is to allow different input shaped images. So my first conv. layer looks something like: model.add(Conv2D(...., input_shape=(None, None, 1)) Well in this setup my flatten layer becomes unhappy and tells me to specify the input shape. As such, I am using a GlobalMaxPooling layer currently, which I would like to avoid. After all, why does the flatten layer bother about the width and height? Background: I try to train a net for classification (smaller resolution) and afterwards use this net for object detection (higher resolution) Thanks
tagged with: tensorflow
type: Question

http://stackoverflow.com/q/51811088
has comment: http://stackoverflow.com/comment/90577192
answer count: 3
possible better answer: http://stackoverflow.com/a/51811133
has comment: http://stackoverflow.com/comment/90577329
downvote count: 0
has answer: http://stackoverflow.com/a/51811133
favorite count: 0
has answer: http://stackoverflow.com/a/51811247
has answer: http://stackoverflow.com/a/51811405
has comment: http://stackoverflow.com/comment/90577246
linked to: http://stackoverflow.com/q/15197673
has body: '[[[-2048 -2048 -2048 ... -2048 -2048 -2048]\r\n [-2048 -2048 -2048 ... -2048 -2048 -2048]\r\n [-2048 -2048 -2048 ... -2048 -2048 -2048]\r\n ...\r\n [-2048 -2048 -2048 ... -2048 -2048 -2048]\r\n [-2048 -2048 -2048 ... -2048 -2048 -2048]\r\n [-2048 -2048 -2048 ... -2048 -2048 -2048]]\r\n\r\n [[-2048 -2048 -2048 ... -2048 -2048 -2048]\r\n [-2048 -2048 -2048 ... -2048 -2048 -2048]\r\n [-2048 -2048 -2048 ... -2048 -2048 -2048]\r\n ...\r\n [-2048 -2048 -2048 ... -2048 -2048 -2048]\r\n [-2048 -2048 -2048 ... -2048 -2048 -2048]\r\n [-2048 -2048 -2048 ... -2048 -2048 -2048]]\r\n\r\n [[-2048 -2048 -2048 ... -2048 -2048 -2048]\r\n [-2048 -2048 -2048 ... -2048 -2048 -2048]\r\n [-2048 -2048 -2048 ... -2048 -2048 -2048]\r\n ...\r\n [-2048 -2048 -2048 ... -2048 -2048 -2048]\r\n [-2048 -2048 -2048 ... -2048 -2048 -2048]\r\n [-2048 -2048 -2048 ... -2048 -2048 -2048]]\r\n\r\n ...\r\n\r\n [[-2048 -2048 -2048 ... -2048 -2048 -2048]\r\n [-2048 -2048 -2048 ... -2048 -2048 -2048]\r\n [-2048 -2048 -2048 ... -2048 -2048 -2048]\r\n ...\r\n [-2048 -2048 -2048 ... -2048 -2048 -2048]\r\n [-2048 -2048 -2048 ... -2048 -2048 -2048]\r\n [-2048 -2048 -2048 ... -2048 -2048 -2048]]\r\n\r\n [[-2048 -2048 -2048 ... -2048 -2048 -2048]\r\n [-2048 -2048 -2048 ... -2048 -2048 -2048]\r\n [-2048 -2048 -2048 ... -2048 -2048 -2048]\r\n ...\r\n [-2048 -2048 -2048 ... -2048 -2048 -2048]\r\n [-2048 -2048 -2048 ... -2048 -2048 -2048]\r\n [-2048 -2048 -2048 ... -2048 -2048 -2048]]\r\n\r\n [[-2048 -2048 -2048 ... -2048 -2048 -2048]\r\n [-2048 -2048 -2048 ... -2048 -2048 -2048]\r\n [-2048 -2048 -2048 ... -2048 -2048 -2048]\r\n ...\r\n [-2048 -2048 -2048 ... -2048 -2048 -2048]\r\n [-2048 -2048 -2048 ... -2048 -2048 -2048]\r\n [-2048 -2048 -2048 ... -2048 -2048 -2048]]]' I have an string array like above. How can i remove all that " ' " (i mean i want it converts into just array type not String-array.) I want an array looks like this: [[[-2048, -2048,-2048, ..., -2048, -2048, -2048], [-2048, -2048, -2048, ..., -2048, -…
tagged with: python
accepted answer: http://stackoverflow.com/a/51811405
has comment: http://stackoverflow.com/comment/90577194
type: AnsweredQuestion
score: 1
has title: Convert String-array into just Array Python
upvote count: 1
type: Question

http://stackoverflow.com/a/51881810
score: 1
upvote count: 1
has body: Since you measure the lenght of the list before the for loop, and you remove items during the for loop, your len(list) becomes wrong during iteration. That's why you run out of range. A simple way would be to iterate the list in reverse eg for i in reversed(range(len(mylist))). That way, when you are removing an element, it does not affect your remaining (previous) elements. However, it would be better to use a list comprehension, as other users have pointed out.
has comment: http://stackoverflow.com/comment/90715168
answers question: http://stackoverflow.com/q/51881728
has comment: http://stackoverflow.com/comment/90715247
downvote count: 0
type: Answer

http://stackoverflow.com/a/51856759
type: Answer
has comment: http://stackoverflow.com/comment/90671208
has comment: http://stackoverflow.com/comment/90668510
has comment: http://stackoverflow.com/comment/90779558
has body: I'm not sure whether TkinterDnD2 library will return a stream of paths in a single string or single path in a string. If it is single path in a string the solution is simple: &gt;&gt;&gt; str1="{mypath/to/file}" &gt;&gt;&gt; str1[1:-1] The output would be 'mypath/to/file' But I suppose your problem is multiple paths coming in single string. You can implement code as below. Consider str1 to be string with multiple paths: str1="{mypath1/tofile1}{mypath3/tofile3}{mypath2/tofile2}" i=0 patharr=[] while(str1.find('{',i)&gt;=0): strtIndex=str1.find('{',i) if(str1.find('}',strtIndex+1)&gt;0): endIndex=str1.find('}',strtIndex+1) patharr.append(str1[strtIndex+1:endIndex]) print(str1[strtIndex:endIndex+1]) i=endIndex+1 print(patharr) Now the output would be as follows: ['mypath1/tofile1', 'mypath3/tofile3', 'mypath2/tofile2'] So as per your question in comment below is code for file paths which are having curly braces with in the file paths. str1 = "{mypath}}}}1/tofil{{{e1}{mypath3/tofile3}{mypath2/tofile2}}}}}}" i = 0 patharr = [] while (str1.find('{', i) &gt;= 0): strtIndexfirst = str1.find('{', i) notFound = True strtIndex = strtIndexfirst while (notFound and strtIndex &lt; len(str1)): if (str1.find('}', strtIndex + 1) &gt; 0): findInd = str1.find('}', strtIndex + 1) if (findInd == len(str1) - 1): endIndex = str1.find('}', strtIndex + 1) patharr.append(str1[strtIndexfirst + 1:endIndex]) print(str1[strtIndex:endIndex + 1]) i = endIndex + 1 break if (str1[findInd + 1] == '{'): endIndex = str1.find('}', strtIndex + 1) patharr.append(str1[strtIndexfirst + 1:endIndex]) print(str1[strtIndex:endIndex + 1]) i = endIndex + 1 notFound = False else: strtIndex = findInd else: strtIndex = str1.find('}', strtIndex + 1) print(patharr) For above string output was ['mypath}}}}1/tofil{{{e1', 'mypath3/tofile3', 'mypath2/tofile2}}}}}'] If str1 is str1="{{{mypath1/tofil}}e1}{mypath3/tofile3}{mypath2/tofile2}}}}}}" Output is ['{{mypath1/tofil}}e1', 'mypath3/tofile3', 'mypath2/tofile2}}}}}'] Wor…
upvote count: 1
answers question: http://stackoverflow.com/q/51853581
downvote count: 1
score: 0
has comment: http://stackoverflow.com/comment/90779896
has comment: http://stackoverflow.com/comment/90779926

http://stackoverflow.com/a/51858387
answers question: http://stackoverflow.com/q/51856523
upvote count: 1
type: Answer
downvote count: 0
score: 1
has body: In your render_template statement you pass along the wrong name for user_image_2. As there is no name_image_3, jinja just ignores it return render_template("hello.html",user_image=name_img_1,user_image_2=name_img_3,form=form) Try return render_template("hello.html",user_image=name_img_1,user_image_2=name_img_2,form=form)

http://stackoverflow.com/comment/90714230
score: 0
type: Comment
has text: @confetti: what is `jsonobject`. instance of your own class? a libraries class? a dict?
type: QuestionComment
comment on: http://stackoverflow.com/q/51881324

http://stackoverflow.com/a/51893769
score: 4
upvote count: 4
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51893702
type: Answer
has body: If order is not important, you can use numpy.unique: import numpy as np def label_items(arr): return np.unique(arr, return_inverse=True) vals, labels = label_items(['a', 'a', 'c', 'd', 'e', 'b', 'e', 'e', 'd', 'c']) print(vals) ['a' 'b' 'c' 'd' 'e'] print(labels) [0 0 2 3 4 1 4 4 3 2]
answers question: http://stackoverflow.com/q/51893702

http://stackoverflow.com/q/51850919
answer count: 1
tagged with: python-3.6
tagged with: console
favorite count: 0
has comment: http://stackoverflow.com/comment/90655392
tagged with: terminal
score: 0
has comment: http://stackoverflow.com/comment/90655211
has title: Python3.6 |- Check if string is True or False -|
has answer: http://stackoverflow.com/a/52157810
has comment: http://stackoverflow.com/comment/90655422
has comment: http://stackoverflow.com/comment/90655101
has comment: http://stackoverflow.com/comment/90655455
has comment: http://stackoverflow.com/comment/90655384
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90655346
has body: Hello! I wanna check if user typed string is True or False, my program creates a new variable when the user type data.create {name} {value} and this variable is stored in a list called "data", with some script it gets the name and the value and can print using type $data.{name}. To not make any problems or make the program more hard, it formats the string, so think that I created a data: data.create hllw Hello World and then I typed it on the console: type $data.hllw, the first thing that is executed is the formater because if it detect an $data in the string, it separates by a dot and get the name and check if the variable exists on the list. So type $data.hllw turns into type Hello World Now, I want to make an if command, that do this: if $data.hllw == Hello World (If hllw var is "Hello World" it return True, else return False), but I don't know do this, I thinked that eval() can help, but no: if eval(args): (args = the arguments of if). If I try: if args: print('True!') else: print('False!') it returns always "True!" :( Anyone that can help? I will be happy ;)
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/116559599
downvote count: 1
has comment: http://stackoverflow.com/comment/90689677
has comment: http://stackoverflow.com/comment/90655397
tagged with: if-statement
has comment: http://stackoverflow.com/comment/90655146
has comment: http://stackoverflow.com/comment/90655372
has comment: http://stackoverflow.com/comment/90655153
type: Question
has comment: http://stackoverflow.com/comment/116558573
has comment: http://stackoverflow.com/comment/90655170

http://stackoverflow.com/comment/90752178
comment on: http://stackoverflow.com/a/51899978
type: AnswerComment
has text: If you dislike having it as a file on the disk, you can always store it as a string in your code and use `cadata` in `load_verify_locaions()` instead of `cafile`. Of course, you will then need to maintain it...
type: Comment
score: 2

http://stackoverflow.com/comment/90704739
comment on: http://stackoverflow.com/q/51876184
score: 0
has text: Search if there is any point which is smaller than it's previous point: `[y[i] for i in range(1,len(y[106:197])) if y[i]<y[i-1]]`, between those two maximas (There is no).
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/90659134
has text: @coldspeed, thank you so much for your help. I needed to upgrade my pandas package was the issue, all is running!
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51852850
score: 0

http://stackoverflow.com/comment/90798743
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51917969
has text: Your Mongo code has to wait before the python code is complete? Is that your requirement. If so, try 'callbacks','promises' or 'async functions'
score: 0

http://stackoverflow.com/comment/91712649
type: QuestionComment
comment on: http://stackoverflow.com/q/51856041
has text: The solution in this case was that even though the tensor was of the correct type (int32), values were encoded as float. This created problems with in_top_k
score: 0
type: Comment

http://stackoverflow.com/a/51824720
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/98642673
has comment: http://stackoverflow.com/comment/90622086
accepted answer of: http://stackoverflow.com/q/51823289
type: Answer
answers question: http://stackoverflow.com/q/51823289
has body: For your case, you have the following possible solutions: keyPressEvent: use the keyPressEvent method but for this you must create a class that inherits from QTableView and overwrite that method. class TableView(QtWidgets.QTableView): def keyPressEvent(self, event): if event.key() == QtCore.Qt.Key_Delete: print("DELETE") super(TableView, self).keyPressEvent(event) ... def setupUi(self, SOME): ... self.tblview_data_sources = TableView(self.groupBox_2) # change QtWidgets.QTableView to TableView eventFilter: Use eventFilter and for this you must use installEventFilter but for this your class must inherit from some class that inherits from QObject, and if you are using Qt Designer the class is not, which also involves many lines of code so I will omit the example. QShortcut: And my preferred solution for its simplicity, use QShortcut: QtWidgets.QShortcut(QtCore.Qt.Key_Delete, self.tblview_data_sources, activated=self.someSlot) ... def someSlot(self): print("DELETE")
upvote count: 5
has comment: http://stackoverflow.com/comment/98642659
score: 5

http://stackoverflow.com/a/51948180
score: 0
type: Answer
has body: Potentially you could try "pip3 install flask"? I'm not sure what version you are using though.
has comment: http://stackoverflow.com/comment/90846592
answers question: http://stackoverflow.com/q/51948012

http://stackoverflow.com/a/51827485
answers question: http://stackoverflow.com/q/51827377
downvote count: 1
has comment: http://stackoverflow.com/comment/90612286
score: 3
accepted answer of: http://stackoverflow.com/q/51827377
has comment: http://stackoverflow.com/comment/90609288
upvote count: 4
type: AcceptedAnswer
type: Answer
has body: IIUC, You can pass the values of the series to np.min as an np.array, and you get the behaviour you would expect from np.min: &gt;&gt;&gt; np.min(df2.values,axis=0) array([nan, nan, nan, 0., nan]) &gt;&gt;&gt; np.min(df1.values,axis=0) array([nan, nan, nan, 0., nan]) You can also apply the argument skipna=False to pands.DataFrame.min, to consider NaN values as well: &gt;&gt;&gt; df1.min(axis=0, skipna=False) 0 NaN 1 NaN 2 NaN 3 0.0 4 NaN dtype: float64 &gt;&gt;&gt; df2.min(axis=0, skipna=False) 0 NaN 1 NaN 2 NaN 3 0.0 4 NaN dtype: float64

http://stackoverflow.com/comment/90815785
comment on: http://stackoverflow.com/q/51873988
score: 0
type: Comment
type: QuestionComment
has text: @benvc yes, it does includes, I have a hierarchy, that looks like this `{ "TERMITE_RESULT" : [{ "RESP_META" : {"JSON_PRODUCER": "EFFICIENT"...}, "RESP_WARNINGS" : null ,"RESP_PAYLOAD": {} ,"RESP_MULTIDOC_PAYLOAD": { "Row_20" : { "COMPANY": [ {...]`

http://stackoverflow.com/a/51911175
has comment: http://stackoverflow.com/comment/90793521
has comment: http://stackoverflow.com/comment/90793612
has comment: http://stackoverflow.com/comment/90793418
type: Answer
has comment: http://stackoverflow.com/comment/90793907
answers question: http://stackoverflow.com/q/51910978
has body: Both Timer and Memoize are implemented as classes, in such way that they return an instance of their own class when they decorate a function. Because of that, it is not possiblle to use functools.wrap or to set the __name__ on the returned function (because there is no returned function). Instead, I suggest implementing __repr__ on Timer and Memoize, which will represent the decorated function better. That function will be called by Python interpreter when it needs to get the string representation of the object. This is the current situation and the problem: def pass_and_square_time(seconds): time.sleep(seconds) return seconds**2 print(pass_and_square_time) # &lt;function pass_and_square_time at 0x00000000029A1620&gt; print(Memoize(pass_and_square_time)) # &lt;Memoize object at 0x000000000295BDA0&gt; Now, if you add to Memoize this: class Memoize(object): ... def __repr__(self): return repr(self._fcn) Then it works as expected: print(pass_and_square_time) # &lt;function pass_and_square_time at 0x00000000029A1620&gt; print(Memoize(pass_and_square_time)) # &lt;function pass_and_square_time at 0x00000000029A1620&gt; Then do the same for Memoize, and even this will work: print(Timer(Memoize(pass_and_square_time))) # &lt;function pass_and_square_time at 0x00000000029A1620&gt; Note that Timer(Memoize(pass_and_square_time)) is exactly what the decorators do here: @Timer @Memoize def pass_and_square_time(seconds): time.sleep(seconds) return seconds**2
has comment: http://stackoverflow.com/comment/90792413
score: 0

http://stackoverflow.com/q/51881958
possible better answer: http://stackoverflow.com/a/51882085
tagged with: arrays
has answer: http://stackoverflow.com/a/51882085
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/51882201
favorite count: 0
has comment: http://stackoverflow.com/comment/90715782
tagged with: memory-management
has answer: http://stackoverflow.com/a/51882061
upvote count: 2
tagged with: python-internals
has title: How does array.array() use such little memory space?
downvote count: 2
tagged with: python
has body: I'm not sure why the array.array() class uses so little memory than reported by sys.getsizeof: from array import array a = array('f') for i in range(500000): a.append(float(i)) sys.getsizeof(a) # 2100228 sum(sys.getsizeof(i) for i in a) # 12000000 (makes sense, 24 bytes * 500K) # 2100228 + 12000000 = 14100228 # 14100228 / 1000 = 14,100.228KB # 14,100.228 / 1000 = 14.1MB However, examining the process in the task manager, the programs memory only increases by 3MB. So how is the process only using 3MB more but the object takes up 14.1MB?
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51882201
has comment: http://stackoverflow.com/comment/90715866
type: Question

py2exe
tags question: http://stackoverflow.com/q/51836628
tags question: http://stackoverflow.com/q/51948219
tags question: http://stackoverflow.com/q/51826460
tag name: py2exe
type: Tag

http://stackoverflow.com/q/51906052
has body: I was trying to take 3 integer inputs on the same line using split, but it throws an error int() argument must be a string, a bytes-like object or a number, not 'list' Here is my code n,a,k = int(input().split())
upvote count: 3
has answer: http://stackoverflow.com/a/51906066
has answer: http://stackoverflow.com/a/51906231
answer count: 5
type: UnansweredQuestion
has title: Taking 3 inputs in the same line in Python 3.5
has answer: http://stackoverflow.com/a/51906073
score: 3
downvote count: 0
favorite count: 0
tagged with: python-3.x
type: Question
has answer: http://stackoverflow.com/a/51906292
tagged with: python
has answer: http://stackoverflow.com/a/51906667

http://stackoverflow.com/q/51911383
has body: I have the following code text_file = open("up2017.txt", "r") amount=[] for line in text_file: fields = line.strip().split(" ") amount.append(fields[-1]) list(map(float,amount)) And I get the following error ValueError: could not convert string to float: '50.000,00' The text files looks like 13.10 Ovf 12.10 50.000,00 50.000,00 30.10 Bgs 30.10 12.000,00 62.000,00 30.11 Bgs 30.11 12.000,00 74.000,00 15.12 Bgs 15.12 53.528,36 127.528,36 30.12 Bgs 30.12 12.000,00 139.528,36
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51911421
accepted answer: http://stackoverflow.com/a/51911421
type: AnsweredQuestion
has title: Conversion types in Python
type: Question
answer count: 2
tagged with: string
possible better answer: http://stackoverflow.com/a/51911536
score: 0
has answer: http://stackoverflow.com/a/51911536
tagged with: python
tagged with: dictionary

http://stackoverflow.com/comment/130182190
comment on: http://stackoverflow.com/q/51844317
score: 0
has text: I'm hitting the same issue - did you figure this out?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90848456
has text: If your class is already defined, redefining it will annulate previous definition for the scope of your function. So the object that your function returns has none of the attributes / methods of the definition outside your function
type: AnswerComment
comment on: http://stackoverflow.com/a/51944749
score: 1
type: Comment

http://stackoverflow.com/a/51890330
score: 0
type: Answer
has body: As @MatrixTai has suggested in the comments, you could make utils.py like this: import tensorflow as tf def load_image(.........): ............ and in main.py, you could import util as you want to.
answers question: http://stackoverflow.com/q/51889794

http://stackoverflow.com/comment/90605503
comment on: http://stackoverflow.com/q/51824817
type: Comment
type: QuestionComment
has text: Well, you're specifying the file name with `outputfile=output_dir + 'test_doc.md'`. If you want a different file name, you need to specify something other than `test_doc.md`.
score: 0

http://stackoverflow.com/a/51949743
has body: Your code will ommit the first two lines of your csv. If you want the second line to be ommitted (but the first one included) just do this minor change: imdb_data = pd.read_csv('IMDB_data.csv', encoding = "ISO-8859-1",skiprows = [1])
has comment: http://stackoverflow.com/comment/121893417
accepted answer of: http://stackoverflow.com/q/51949545
downvote count: 0
score: 21
answers question: http://stackoverflow.com/q/51949545
type: AcceptedAnswer
upvote count: 21
type: Answer
has comment: http://stackoverflow.com/comment/107363902

http://stackoverflow.com/a/51876264
has comment: http://stackoverflow.com/comment/90728786
has comment: http://stackoverflow.com/comment/90803593
has comment: http://stackoverflow.com/comment/90801267
type: Answer
has comment: http://stackoverflow.com/comment/90803134
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/90803819
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51875822
has body: all you need is to create the Lawyer, also you should set allow null to true for the laweyer field. class SessionSerializer(serializers.ModelSerializer): email = serializers.SerializerMethodField() lawyer = serializers.IntegerField(allow_null=True, required=False) fields=['name', 'lawyer','email'] def create(self, validated_data): user = User.objects.create(email=validated_data.get('email')) lawyer = Lawyer.objects.create(user=user) name = validated_data.get('name') instance = Session.objects.create(lawyer=lawyer, name=name) return instance
has comment: http://stackoverflow.com/comment/90802760
accepted answer of: http://stackoverflow.com/q/51875822
has comment: http://stackoverflow.com/comment/90727578
downvote count: 0

http://stackoverflow.com/q/51826611
has answer: http://stackoverflow.com/a/51828300
tagged with: python
downvote count: 1
tagged with: primes
possible better answer: http://stackoverflow.com/a/51828300
upvote count: 3
has body: The main question here is: is there a better way that using "all" in Python? I have read that it goes through every condition and then comes back to see if any are true. I want to check one condition at a time and then quit as soon as one doesn't work. I believe this is called "Short Circuit.....". I can't use a series of "and"s because they change by input and there could be millions of conditions. I'm looking for Carmichael numbers. One definition for a Carmichael Number is that b^n = b (mod n) for all 1 &lt; b &lt; n. If a number n fails the test then it's composite. If it passes the test it may be either prime or Carmichael. I then checked if it was prime or not. I used the code: def Carm(num): if all(gcd(k,num) == 1 for k in range(3,int(round(num**0.5)),2)) and gcd(2,num) == 1: print(num,'is a Prime Number') elif all(pow(b,num,num)==b for b in range(1,num)) and gcd(num,2)==1: print(num,'is a Carmichael Number') else: print(num,'is not a Carmichael Number')
has comment: http://stackoverflow.com/comment/90608760
has title: Speed up a search for Carmichael numbers?
has comment: http://stackoverflow.com/comment/90607609
score: 2
has answer: http://stackoverflow.com/a/51827976
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90607645
has comment: http://stackoverflow.com/comment/90609533
favorite count: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/51827976
type: Question
answer count: 2

http://stackoverflow.com/a/65822624
answers question: http://stackoverflow.com/q/51954234
score: 0
has body: It may be helpful, I solved a similar problem by reading the username and password from the configuration file. Try: # config.ini [my_app] USERNAME = enter_username PASSWORD = enter_password Install configparser from Python 3.8 for Python 2.6+: pip install configparser. See the great documentation for more details. from pygerrit2 import GerritRestAPI, HTTPBasicAuth import configparser config = configparser.RawConfigParser() config.read('config.ini') my_user = config.get('my_app', 'USERNAME') my_pass = config.get('my_app', 'PASSWORD') auth = HTTPBasicAuth(my_user, my_pass) print auth rest = GerritRestAPI(url='https://tech.company.com', auth=auth) changes = rest.get("/changes/?q=owner:self%20status:open")
type: Answer

http://stackoverflow.com/comment/128343166
comment on: http://stackoverflow.com/a/67538655
has text: The question's title was misleading, I have just updated it to reflect the real question. However, this response is exactly what I have been looking for: md5 a numpy array.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/90652591
type: QuestionComment
has text: Possible duplicate of [Installing mysqlclient in Python 3.6 in windows](https://stackoverflow.com/questions/51146117/installing-mysqlclient-in-python-3-6-in-windows)
type: Comment
comment on: http://stackoverflow.com/q/51840644
score: 0

http://stackoverflow.com/q/51825893
linked to: http://stackoverflow.com/q/35040724
tagged with: flask-sqlalchemy
favorite count: 0
has title: What could be the cause of "Dependency rule tried to blank-out primary key column"
type: Question
tagged with: python
accepted answer: http://stackoverflow.com/a/51827704
score: 4
answer count: 2
tagged with: sqlalchemy
has body: When im trying to delete category instance identified by 'id' with its category_image and files instances the way like this: c = Category.query.get(id) for ci in c.images: db.session.delete(ci) db.session.flush() for ci in c.images: db.session.delete(ci.file) db.session.flush() # if i type here db.session.commit() all is fine db.session.delete(c) db.session.commit() i'm getting a AssertionError: Dependency rule tried to blank-out primary key column 'category_image.id_category' on instance ''. But when i replace flush which is after deleting category_image.files with commit, then it works. I've notice it after i changed CategoryImage table to intermediary. Before changes it has it's own pk that wasn't combined and all was working properly. Here're my current models definitions. class File(db.Model): __tablename__ = 'file' id_file = Column(Integer, Sequence('seq_id_file'), primary_key=True, nullable=False) name = Column(Text, nullable=False) path = Column(Text, nullable=False, unique=True) protected = Column(Boolean, nullable=False, default=False) class Category(db.Model): __tablename__ = 'category' id_category = Column(Integer, Sequence('seq_id_category'), primary_key=True, nullable=False) name = Column(UnicodeText, nullable=False, unique=True) images = relationship('CategoryImage', backref='images') class CategoryImage(db.Model): __tablename__ = 'category_image' __table_args__ = ( PrimaryKeyConstraint('id_category', 'id_file', name='seq_id_category_image'), ) id_category = Column(Integer, ForeignKey(Category.id_category), nullable=False) id_file = Column(Integer, ForeignKey(File.id_file), nullable=False) id_size_type = Column(Integer, nullable=) file = relationship(File) Now i'm trying to figure out what just happened. Correct me if i'm using things wrong.
linked to: http://stackoverflow.com/q/23699651
has comment: http://stackoverflow.com/comment/90607550
possible better answer: http://stackoverflow.com/a/51826304
has answer: http://stackoverflow.com/a/51826304
has answer: http://stackoverflow.com/a/51827704
upvote count: 4
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/q/51882902
favorite count: 0
tagged with: series
tagged with: python
possible better answer: http://stackoverflow.com/a/51883006
score: 2
type: AnsweredQuestion
downvote count: 0
type: Question
has body: If I have a dataframe like so: id latitude longitude a -99 48 b -97 44 c -96 52 and I have a dictionary mapping the ids to new latitude+longitude values new_lat_lon = { 'a':(-99, 58), 'b':(...), 'c':(...) } is there a quick and dirty way to use .map to change the latitude/longitude columns at once? e.g. df'latitude', 'longitude' = df['id'].map(new_lat_lon) this doesn't work of course, but if there's a way I'd like to know. I am aware that I can simply separate the dictionary into two separate ones, but I am interested if there is a more compact solution. If I need to modify the dictionary a bit (e.g. change the tuples to lists or something) that's cool too, as long as it's one dictionary. Thank you!
accepted answer: http://stackoverflow.com/a/51882945
has answer: http://stackoverflow.com/a/51883006
has title: Use one .map call to change values for multiple Series/columns in dataframe using one dictionary
upvote count: 2
answer count: 2
tagged with: pandas
has answer: http://stackoverflow.com/a/51882945

http://stackoverflow.com/comment/90701440
type: QuestionComment
comment on: http://stackoverflow.com/q/51845472
score: 1
has text: Thanks, although that helps translating the flash messages, the login page itself still stays in English.
type: Comment

http://stackoverflow.com/a/51867913
answers question: http://stackoverflow.com/q/51867868
type: Answer
has comment: http://stackoverflow.com/comment/90687864
downvote count: 0
has comment: http://stackoverflow.com/comment/90690947
score: 3
has body: We can use some regex and recode from dplyr library(dplyr) newColumn &lt;- recode(sub(".*(3850|7200|3560|Data Center).*", "\\1", data[,1]), `3850` = 50, `7200` = 2, `3560` = 60, `Data Center` = 240) cbind(data, newColumn) newColumn [1,] "Cisco Catalyst 3850 Series Ethernet Stackable Switch" "ports" "50" [2,] "Cisco 7200 Series Routers" "Ports" "2" [3,] "Cisco Catalyst 3560-CX Series Switches" "Ports" "60" [4,] "Data Center Switches" "Ports" "240" [5,] "SW_3560_IDF1d_1879.ccs.ccctov.org" "Ports" "60" A slightly different way to do it: codes &lt;- sub(".*(3850|7200|3560|Data Center).*", "\\1", data[,1]) newCodes &lt;- list(`3850` = 50, `7200` = 2, `3560` = 60, `Data Center` = 240) cbind(data, recode(codes, !!!newCodes))
has comment: http://stackoverflow.com/comment/90687836
upvote count: 3
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51867868
has comment: http://stackoverflow.com/comment/90687728

http://stackoverflow.com/a/51823586
type: Answer
upvote count: 2
has body: Check if this works for b in a: name = stockdf[b]['name'] price = stockdf[b]['price'] time = stockdf[b]['time'] if not b in phistory: phistory[b] = {} phistory[b][dataentries] = {time:price} c = phistory.keys() #print c dataentries = dataentries + 1 save() This should result in the kind of behavior you are looking for. Please run tests on smaller samples of your database, it will make debugging this much quicker. Interestingly, since we're rewriting/updating phistory every time we call the function, we may actually WANT to use 'w' instead of 'a' here. Otherwise we'll basically end up with the history of every iteration of phistory stored in one file, which could get massive. I recommend making the above change, and then testing both 'w' and 'a' separately, as I think 'w' might actually give you what you want here. EDIT: Answering final question So this is the way you were creating the dict and updating it. update() does what it says on the tin, it updates a (k,v) pair in a dict. It doesn't append things unless they don't exist already. Since the top-level key "EVL" already exists, all of its values are overwritten when you pass in update({'EVL' : some_values}) The way I did it was creating an empty entry if there wasn't one, then updating it by basically telling it what value to put in that new key. the syntax dict[key] = X will either update that key or create a new one if that key doesn't exist, but dict[key][key2] = X relies on dict[key] existing, because otherwise it won't know what the parent of [key2] is to add it in the first place. That's why we had to explicitly create the top-level key if it didn't exist. Then after that dict[key_that_exists][key2] = X will either update the (key2, v) pair or create it if it doesn't exist. Hope that helps :)
answers question: http://stackoverflow.com/q/51823498
score: 2
accepted answer of: http://stackoverflow.com/q/51823498
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/90645262
score: 0
comment on: http://stackoverflow.com/q/51836242
type: Comment
type: QuestionComment
has text: The documentation says `x` and `y` can both either be Tensors or sequences of Tensors. Did this not work for you?

http://stackoverflow.com/comment/90628128
type: Comment
comment on: http://stackoverflow.com/q/51837462
score: 2
type: QuestionComment
has text: Can you show how you called the `striptime`, etc.?

http://stackoverflow.com/comment/90814101
type: QuestionComment
comment on: http://stackoverflow.com/q/51931582
score: 2
has text: As far as I can tell, each row in your dataset contains only a single comment, so by "average" you mean the average over all rows? If so, there is only a single average number of words or characters for the whole dataset, and it doesn't seem to make sense to add this average to every single row.
type: Comment

http://stackoverflow.com/q/51842688
has answer: http://stackoverflow.com/a/53361541
upvote count: 5
tagged with: docker
tagged with: google-cloud-platform
answer count: 1
downvote count: 0
tagged with: gcloud
favorite count: 0
accepted answer: http://stackoverflow.com/a/53361541
tagged with: python
has body: TL,DR; What Linux Docker image would be fastest / lightest to run the Python gRPC plugin when generating API descriptor files? Should the aforementioned API descriptor become a Cloud Build artifact and saved to a Cloud Storage Bucket? ...in order to use gcloud to deploy the API to Cloud Endpoints. Detail I run a Python gRPC service and ESP in Docker containers running on Google Compute Engine. About gRPC > API management shows a diagram of my application architecture: My high-level build steps: 1) Create the descriptor file, api_descriptor.pb, using the protoc protocol buffers compiler. python -m grpc_tools.protoc \ --include_imports \ --include_source_info \ --proto_path=. \ --descriptor_set_out=api_descriptor.pb \ --python_out=generated_pb2 \ --grpc_python_out=generated_pb2 \ bookstore.proto 2) Deploy the proto descriptor file (api_descriptor.pb) and the configuration file using the gcloud command-line tool: gcloud endpoints services deploy api_descriptor.pb api_config.yaml 3) Generate gRPC code using Python plugin: python -m grpc_tools.protoc -I../../protos --python_out=. --grpc_python_out=. ../../protos/helloworld.proto 4) Build the final Docker image to deploy on Google Compute Engine. Resulting Docker image should include: Generated gRPC code from step 3). Any additional Python packages required by the gRPC server. Step 4) builds the 'gRPC Server' (rightmost blue box in the accompanying diagram) using the following Dockerfile: FROM gcr.io/google_appengine/python:latest WORKDIR . EXPOSE 8081 ENTRYPOINT ["python", "server.py"] ADD requirements.txt . ADD protos ./protos RUN mkdir out RUN apt-get update &amp;&amp; \ apt-get install -y python2.7 python-pip &amp;&amp; \ pip install -r requirements.txt RUN python \ -m grpc_tools.protoc \ --python_out=out \ --grpc_python_out=out \ --proto_path=. \ bookstore.proto I'm migrating these build steps to Google's Cloud Build. AFAICT my high-level build steps should map onto Cloud Builder official builder images. 1) ??? 2) Us…
tagged with: google-cloud-build
type: AnsweredQuestion
has title: How to use the gRPC Python Plugin with Docker and Google Cloud Builds?
type: Question
score: 5

http://stackoverflow.com/comment/90840798
type: Comment
has text: To be honest, I've heard of "snaplogic" the first time in my life.
comment on: http://stackoverflow.com/a/51943072
type: AnswerComment
score: 0

http://stackoverflow.com/q/51877154
type: UnansweredQuestion
tagged with: python
answer count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/106201837
tagged with: tensorflow
type: Question
has title: Tensorflow detection model zoo
downvote count: 0
has body: I managed to train a CNN with the ssd_mobilenet_v1_coco model which has to detect shards in static, grayscale slow motion camera images. I read that this model is fast but has a low accuracy. So I wonder if there is a model better suited for my problem. Here are 6 images, which are tested by tensorflow. As you can see the model can't detect the last 2 images. The shards on the last 2 images can barely or not at all be seen by human eye but they are there. Tensorflow provides these open source models: https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/detection_model_zoo.md Which model of the tensorflow zoo would you recommend for this job. Does a documentation of all models exist that I can look up? Also: If this is the wrong place to ask this question, would you please recommend me a better place?
favorite count: 0

http://stackoverflow.com/comment/90817756
has text: *[This](https://stackoverflow.com/questions/18648626/for-loop-with-two-variables)* might help?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51933830
score: 0

http://stackoverflow.com/a/51813384
type: Answer
has comment: http://stackoverflow.com/comment/90581652
has body: Update using pandas 0.25.0+ with explode df['category'].explode().value_counts() Output: Barbeque 3 Mexican 3 Fusion 2 Thai 2 American 2 Bars 2 Asian 2 Hawaiian 1 New 1 Brunch 1 Pizza 1 Traditional 1 Pubs 1 Korean 1 Pakistani 1 Burgers 1 Diners 1 Indian 1 Desserts 1 Halal 1 Nightlife 1 Breakfast 1 Name: Places, dtype: int64 And with plotting: df['category'].explode().value_counts().plot.pie(figsize=(8,8)) Output: For older verions of pandas before 0.25.0 Try: df['category'].apply(pd.Series).stack().value_counts() Output: Mexican 3 Barbeque 3 Thai 2 Fusion 2 American 2 Bars 2 Asian 2 Pubs 1 Burgers 1 Traditional 1 Brunch 1 Indian 1 Korean 1 Halal 1 Pakistani 1 Hawaiian 1 Diners 1 Pizza 1 Nightlife 1 New 1 Desserts 1 Breakfast 1 dtype: int64 With plotting: df['category'].apply(pd.Series).stack().value_counts().plot.pie() Output: Per @coldspeed's comments from itertools import chain from collections import Counter pd.DataFrame.from_dict(Counter(chain(*df['category'])), orient='index').sort_values(0, ascending=False) Output: Barbeque 3 Mexican 3 Bars 2 American 2 Thai 2 Asian 2 Fusion 2 Pizza 1 Diners 1 Halal 1 Pakistani 1 Brunch 1 Breakfast 1 Burgers 1 Hawaiian 1 Traditional 1 Pubs 1 Korean 1 Desserts 1 New 1 Nightlife 1 Indian 1
downvote count: 1
has comment: http://stackoverflow.com/comment/90582020
accepted answer of: http://stackoverflow.com/q/51813266
upvote count: 26
answers question: http://stackoverflow.com/q/51813266
score: 25
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90581870

http://stackoverflow.com/comment/90825492
type: QuestionComment
comment on: http://stackoverflow.com/q/51935797
has text: Nevermind I just saw your post i will try that now.
score: 0
type: Comment

http://stackoverflow.com/a/51848295
score: 5
upvote count: 5
downvote count: 0
type: Answer
has body: Setup df = pd.DataFrame({'a': [5,0,1,0,6], 'b': [5,7,0,4,4]}) mat = np.random.rand(5,3) Using join: df.join(pd.DataFrame(mat)) a b 0 1 2 0 5 5 0.884061 0.803747 0.727161 1 0 7 0.464009 0.447346 0.171881 2 1 0 0.353604 0.912781 0.199477 3 0 4 0.466095 0.136218 0.405766 4 6 4 0.764678 0.874614 0.310778 If there is the chance of overlapping column names, simply supply a suffix: df = pd.DataFrame({0: [5,0,1,0,6], 1: [5,7,0,4,4]}) mat = np.random.rand(5,3) df.join(pd.DataFrame(mat), rsuffix='_') 0 1 0_ 1_ 2 0 5 5 0.783722 0.976951 0.563798 1 0 7 0.946070 0.391593 0.273339 2 1 0 0.710195 0.827352 0.839212 3 0 4 0.528824 0.625430 0.465386 4 6 4 0.848423 0.467256 0.962953
answers question: http://stackoverflow.com/q/51848161

http://stackoverflow.com/comment/93307735
score: 0
type: Comment
has text: @LegendaryDude Never figured it out.
type: AnswerComment
comment on: http://stackoverflow.com/a/51810411

http://stackoverflow.com/a/62385809
answers question: http://stackoverflow.com/q/51853018
type: Answer
score: 2
downvote count: 0
has body: As a reference it might help someone... On Debian system I hard to do the following: apt-get install -y libsm6 libxext6 libxrender-dev pip3 install opencv-python python3 -c "import cv2"
upvote count: 2

http://stackoverflow.com/comment/90783030
has text: Have you tried `--force-yes` ?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51916580
score: 0

http://stackoverflow.com/comment/90831623
comment on: http://stackoverflow.com/q/51940695
score: 0
type: Comment
type: QuestionComment
has text: @cricket_007 what do you mean exactly? No new function is created when you use `str.lower`, if that's what you mean

http://stackoverflow.com/q/51845860
type: Question
possible better answer: http://stackoverflow.com/a/51845995
accepted answer: http://stackoverflow.com/a/51845938
has answer: http://stackoverflow.com/a/51868770
has comment: http://stackoverflow.com/comment/90645029
has body: I am a beginner in Python programming. When I write my code, it gets really lengthy because I keep using a print('') under paragraphs to create space. So far my programming is with making simple tests for my sister who is a teacher for the upcoming school year. Is there a cleaner, shorter way to make spaces? Example: print('What is the answer for this question?') print('') print('') print('answer')
score: 0
answer count: 3
has comment: http://stackoverflow.com/comment/90644958
has answer: http://stackoverflow.com/a/51845938
has answer: http://stackoverflow.com/a/51845995
tagged with: python
type: AnsweredQuestion
has title: Python-How to create spaces between paragraphs?

http://stackoverflow.com/q/51896458
linked to: http://stackoverflow.com/q/47692566
answer count: 2
has body: I am trying to use multiprocessing for a task that is very slow when done as a single process. As you can see in the code below, each process is supposed to return some results (return_dict). I initially tested this code with a 10K row dataset (the data stored in the docs.txt file, about 70mb), and the code ran as expected. However, when I used the script for the full data set (approx. 5.6gb), I got an AssertionError as shown at the bottom of my question. I wonder if anyone knows what may have caused it and how I may be able to avoid it. Thanks. from multiprocessing import Process, Manager import os, io, numpy from gensim.models.doc2vec import Doc2Vec def worker(i, data, return_dict): model = Doc2Vec.load("D:\\Project1\\doc2vec_model_DM_20180814.model") results = numpy.zeros((len(data), model.vector_size)) for id, doc in enumerate(data): results[id,:] = model.infer_vector(doc, alpha = 0.01, steps = 100) return_dict[i] = results if __name__ == '__main__': import time a = time.time() path = "D:\\Project1\\docs.txt" # &lt;&lt;=== data stored in this file data = [] manager = Manager() jobs = [] return_dict = manager.dict() with io.open(path, "r+", encoding = "utf-8") as datafile: for id, row in enumerate(datafile): row = row.strip().split('\t')[0].split() data.append(row) step = numpy.floor(len(data)/20) intervals = numpy.arange(0, len(data), step = int(step)).tolist() intervals.append(len(data)) for i in range(len(intervals) - 1): p = Process(target=worker, args=(i, data[intervals[i]:intervals[i+1]], return_dict)) jobs.append(p) p.start() for proc in jobs: proc.join() results = numpy.zeros((len(data), 1000)) start = 0 end = 0 for _, result in return_dict.items(): #&lt;&lt;===Where error happens end = end + result.shape[0] results[start:end,:] = result[:,:] start = end print(time.time() - a) Error message: Traceback (most recent call last): File "D:\Project1\multiprocessing_test.py", line 43, in &lt;module&gt; for _, result in return_dict.items(): File "&lt;string&gt;",…
score: 0
tagged with: python-multithreading
has title: Python multiprocessing.Processgetting generates AssertionError when attempting to get results returned?
has answer: http://stackoverflow.com/a/51896605
tagged with: python
has comment: http://stackoverflow.com/comment/90745589
tagged with: python-3.x
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/57305756
has comment: http://stackoverflow.com/comment/90746348
has comment: http://stackoverflow.com/comment/90744927
tagged with: multiprocessing
has comment: http://stackoverflow.com/comment/91231733
type: Question

http://stackoverflow.com/comment/90619062
comment on: http://stackoverflow.com/a/51832308
type: Comment
has text: It still is not working. Even if you put the right values and files it still is not valid. I was thinking if I maybe I can fix my project_form in my get() maybe it will work. I think I am not doing it correct in my get(). But I do not know what to do
score: 0
type: AnswerComment

http://stackoverflow.com/a/51837099
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/90627827
has body: If I understood you correctly, you can try something like: l = [] for link in soup.findAll('a'): print link.get('href') l.append(link.get('href')) l = [x for x in l if "www" not in x] #or 'https'
accepted answer of: http://stackoverflow.com/q/51836884
answers question: http://stackoverflow.com/q/51836884
has comment: http://stackoverflow.com/comment/90627898
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90629423
score: 1

http://stackoverflow.com/a/75012808
has body: Adding a real browser user-agent header works for me: user_agent = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36' chrome_options.add_argument('user-agent={0}'.format(user_agent))
score: 4
type: Answer
upvote count: 4
downvote count: 0
answers question: http://stackoverflow.com/q/51890887

http://stackoverflow.com/comment/90575895
has text: A many to many is not a specific field: it generates an *extra* table, a table with two foreign keys: one to the "origin" of the m2m, and one to the "target" of the m2m.
score: 0
comment on: http://stackoverflow.com/q/51810439
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90580373
type: Comment
has text: i defined it, now it just not working.
comment on: http://stackoverflow.com/q/51812634
score: 0
type: QuestionComment

http://stackoverflow.com/q/51881618
has body: I have a dataframe similar to this one containing an enumerated date, and ID, and number of items sold for given date and ID: Date ID num_sold 0 1 0 2 13 1 1 6 2 0 2 1 0 2 0 3 1 5 2 4 For each ID, I want to compute the Date when last sale happened. So I have the following dataframe: Date ID num_sold last_sale 0 1 0 -1 2 13 -1 1 1 6 -1 2 0 0 2 1 0 1 2 0 0 3 1 5 1 2 4 0 I want to compute the column last_sale, where 1 and 0 are the date values when given an ID, num_sold was last non-zero. If there is no such last date (e.g. first month in dataset), it is -1 (or could be nan). In the given example, At date 1, ID 1 was not sold ever before so we set last_sale to -1. ID 2 was last sold in month 0, so we set last_sale to 0. Similarly, at date 3, ID 1 was last sold in month 1 so last_sale is 1, and ID 2 was last sold in month 0, so last_sale is 0. What's the most efficient and concise way to accomplish this?
has title: Get the value of another column when current column was last non-zero (Pandas dataframe)
downvote count: 0
has answer: http://stackoverflow.com/a/51883799
type: Question
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90714802
has comment: http://stackoverflow.com/comment/90745514
upvote count: 2
answer count: 2
has comment: http://stackoverflow.com/comment/90750573
possible better answer: http://stackoverflow.com/a/51883253
has comment: http://stackoverflow.com/comment/90714757
favorite count: 0
has comment: http://stackoverflow.com/comment/90714938
has answer: http://stackoverflow.com/a/51883253
tagged with: pandas
accepted answer: http://stackoverflow.com/a/51883799
tagged with: python

http://stackoverflow.com/comment/90726635
type: Comment
has text: That was the entire script I've used.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51887687

http://stackoverflow.com/q/51828996
has answer: http://stackoverflow.com/a/78128520
downvote count: 0
favorite count: 0
tagged with: python
type: AnsweredQuestion
upvote count: 3
has title: Setting markers colour on seaborn
tagged with: seaborn
has answer: http://stackoverflow.com/a/51829939
has body: everybody, I am trying to do an lmplot but I want for the markers to differ between them only in format, not colour. I want them all to be black. I also tried to use a grey-scale palette such as 'Greys' or 'binary', but then some markers get very light, if there is a way of making them more apparent I'd also take it! I am using lmplot with fit_reg=False just because I'd like to use hue and as far as I know scatter does not have that function. The code I am using is: sns.set_style("whitegrid") sns.lmplot(data=data,x='Day',y='Temperature',hue='Site',fit_reg=False,markers=['o','+','x','s','p']).fig.set_size_inches(15,5) And this is the resulting figure (ignore the black background): Thanks!
type: Question
score: 3
accepted answer: http://stackoverflow.com/a/51829939
answer count: 2
possible better answer: http://stackoverflow.com/a/78128520

http://stackoverflow.com/a/51887466
answers question: http://stackoverflow.com/q/51887356
downvote count: 0
has body: One way to do this would be to set the index to ['Date', 'Dept'] and unstack() but you have multiple values for each Dept for the date 2018-12-03. Note sure if that is expected but one way to resolve that issues is to groupby().first() to take the first value and then unstack(), e.g.: In []: df.set_index(['Date', 'Dept']).groupby(level=[0, 1]).first().unstack() Out []: Sales Dept Automotive/News Paper Beverages Cigarettes Coffee International Food Lottery - Machine Lottery - Scratch Milk Prepared Foods Snack/Grocery Solaray Sweets Tobacco Total Whl-Sales/Gift-Card Date 2018-12-01 10.47 160.97 426.889 29.72 65.00 191.00 1397.0 11.56 3.99 198.57 9.99 0.0 43.84 2549.00 0.0 2018-12-02 13.16 135.28 374.010 33.76 3.98 211.00 651.0 9.57 20.98 178.01 17.99 0.0 89.29 1738.03 0.0 2018-12-03 70.17 126.01 463.540 30.47 21.98 461.00 1046.0 8.57 0.00 164.19 17.99 0.0 35.26 2445.18 0.0 2018-12-04 47.00 163.11 291.910 32.17 6.98 112.75 762.0 3.99 5.00 207.87 40.98 0.0 42.93 1716.69 NaN 2018-12-05 46.24 87.94 255.720 15.95 17.73 151.00 540.0 9.77 8.98 212.94 11.98 0.0 81.52 1439.77 NaN 2018-12-06 32.92 235.73 377.960 29.32 9.99 194.00 509.0 0.00 27.37 281.83 12.99 5.0 129.07 1845.18 NaN 2018-12-07 31.06 183.59 526.910 16.22 1.99 61.50 300.0 2.79 24.98 202.27 5.99 0.0 65.71 1423.01 0.0 But this is almost identical to df.pivot_table(index='Date', columns='Dept', values='Sales'): Dept Automotive/News Paper Beverages Cigarettes Coffee International Food Lottery - Machine Lottery - Scratch Milk Prepared Foods Snack/Grocery Solaray Sweets Tobacco Total Whl-Sales/Gift-Card Date 2018-12-01 10.47 160.97 426.889 29.72 65.00 191.00 1397.0 11.56 3.99 198.57 9.99 0.0 43.84 2549.00 0.0 2018-12-02 13.16 135.28 374.010 33.76 3.98 211.00 651.0 9.57 20.98 178.01 17.99 0.0 89.29 1738.03 0.0 2018-12-03 70.17 126.01 463.540 30.47 21.98 461.00 1046.0 8.57 0.00 164.19 17.99 0.0 35.26 2445.18 0.0 2018-12-04 47.00 163.11 291.910 32.17 6.98 112.75 762.0 3.99 5.00 207.87 40.98 0.0 42.93 1716.69 NaN 2018-12-05…
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/a/51848866
answers question: http://stackoverflow.com/q/51848532
has body: You should convert your int to the type which the API expects df.id=df.id.astype('int32') With your current url string API is trying to convert 'row' which is a string to an integer which is not possible. update your url string url = 'https://url.com/path/to?username=string&amp;password=string&amp;leadId={}'.format(row)
type: Answer
has comment: http://stackoverflow.com/comment/90651161
has comment: http://stackoverflow.com/comment/90668743
has comment: http://stackoverflow.com/comment/90651616
has comment: http://stackoverflow.com/comment/90651251
accepted answer of: http://stackoverflow.com/q/51848532
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/90651431
upvote count: 1
has comment: http://stackoverflow.com/comment/90671105
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90651240
has comment: http://stackoverflow.com/comment/90651336

http://stackoverflow.com/a/51803275
upvote count: 1
downvote count: 0
answers question: http://stackoverflow.com/q/51802974
type: Answer
has body: For your specific case, the boolean or operator looks more pythonic, and also a very simple benchmark shows that it is slightly more efficient: import timeit setup = "account = {'first_name': None, 'last_name': 'Bloggs'}" statements = { 'ternary conditional operator': "first_name = account['first_name'] if account['first_name'] else ''", 'boolean or operator': "first_name = account['first_name'] or ''", } for label, statement in statements.items(): elapsed_best = min(timeit.repeat(statement, setup, number=1000000, repeat=10)) print('{}: {:.3} s'.format(label, elapsed_best)) Output: ternary conditional operator: 0.0303 s boolean or operator: 0.0275 s Taking into account that the numbers above are the total execution times in seconds (1000000 evaluations per each statement), in practice, there is no significant difference in efficiency at all.
score: 1

http://stackoverflow.com/comment/90602429
type: QuestionComment
has text: what kind of output do you expect?
comment on: http://stackoverflow.com/q/51824174
score: 0
type: Comment

http://stackoverflow.com/comment/90705452
has text: And the issue probably is with input function. Please change `input` to `raw_input`.
type: AnswerComment
comment on: http://stackoverflow.com/a/51876675
score: 0
type: Comment

http://stackoverflow.com/comment/90640491
comment on: http://stackoverflow.com/q/51826478
score: 0
type: Comment
type: QuestionComment
has text: instead of an edition I invite you to post an answer and mark it as correct.

http://stackoverflow.com/comment/90738403
type: AnswerComment
type: Comment
has text: @SouvikRay: I think it is better to first try to fix the migration problem (effectively) than trying to "circumvent" the problem by using a different column type. Sure it might for now work, but it will cause a lot of problem later by not solving the "core issue".
comment on: http://stackoverflow.com/a/51893414
score: 0

http://stackoverflow.com/comment/92198644
has text: I think the issue is in the role type you've selected, for IAM I would use the role Dialogflow API Admin or Owner.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51855169
score: 0

http://stackoverflow.com/comment/90653789
has text: Do you get an error or it just doesn't save the data?
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51850065

http://stackoverflow.com/comment/90659242
type: AnswerComment
comment on: http://stackoverflow.com/a/51841712
score: 0
type: Comment
has text: Thanks, but the issue wasn't the definition of the error, it was how to determine why since it doesn't actually return an error object. For instance, resuming media only is possible if when it breaks, an object is returned that lets you know where the break happens. Since nothing gets returned, it's impossible to continue.

http://stackoverflow.com/comment/90805700
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51927796
has text: So if the user writes a random response such as letters or presses enter I am getting a traceback error highlighted in red in the instructions it says our code should counteract that and tell the user to type in a valid input and keep repeating this untill he does it

http://stackoverflow.com/comment/90618773
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51818982
has text: dear, added HTML part, i will do this next time @JeffC thanks !

http://stackoverflow.com/q/51885171
tagged with: deep-learning
has title: LSTM for session based prediction
favorite count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/90722103
has comment: http://stackoverflow.com/comment/90722050
answer count: 0
score: 1
type: Question
has body: I'm trying to build an LSTM model according to that picture. I'm a beginner in deep learning particulary WITH RNN structure, so i require your advice to lead me so, for that i'm dealing with a dataframe of 70k users and 12k animes, my dataframe contains : user id user rating anime id genre : a list of tags associated with anime like : action, comedy, school ...etc. users_tags : a list of 15 unique tags for unique user that i built thanks to tfifd method and some text data related to users My dataframe looks like : anime_id user_id user_rating name tags genre 0 1 234 9.0 Cowboy Bebop drama , fi , mal action , military , sci fi , ... Action, Adventure, Comedy, Drama, Sci-Fi, Space 1 1 382 10.0 Cowboy Bebop life , shiki , tv , thriller , movie short , c... Action, Adventure, Comedy, Drama, Sci-Fi, Space 2 1 160 9.0 Cowboy Bebop fantasy , action , supernatural , tv , mystery... Action, Adventure, Comedy, Drama, Sci-Fi, Space 3 1 341 8.0 Cowboy Bebop action , school , romance , new , short , mal ... Action, Adventure, Comedy, Drama, Sci-Fi, Space 4 1 490 9.0 Cowboy Bebop mal adventure , movie short , school , strange... Action, Adventure, Comedy, Drama, Sci-Fi, Here parameters i use for my model : #parameters users = interactions_full_df.user_id.unique() animes = interactions_full_df.anime_id.unique() animes_tags = " ".join(interactions_full_df["genre"].unique()).split(",") n_animes_tags = len(animes_tags) n_users = len(users) n_animes = len(animes) n_users_tags = 15 I put 250 for my "latent dim" for embedding layer. Here, my attempt to build this model """ Users Tags : FIXED INPUT """ Users_Tags_input = Input(shape=[1],name='Users_tags') Users_embedding_tags = Embedding(n_users + 1, latent_dim, name='Users-Embeddings-MLP')(Users_Tags_input) Users_vec_TAGS = Flatten(name='FlattenUsers-TAGS')(Users_embedding_tags) """ Users embedding""" Users_input = Input(shape=[1],name='Users') Users_embedding_mlp = Embedding(n_users + 1, latent_dim, name='Users-Embeddings-MLP')(Users_i…
downvote count: 0
tagged with: keras
tagged with: lstm

http://stackoverflow.com/tag/csv
type: Tag
tags question: http://stackoverflow.com/q/51819416
tags question: http://stackoverflow.com/q/51932123
tags question: http://stackoverflow.com/q/51868410
tags question: http://stackoverflow.com/q/51920569
tags question: http://stackoverflow.com/q/51806264
tags question: http://stackoverflow.com/q/51855777
tags question: http://stackoverflow.com/q/51808662
tags question: http://stackoverflow.com/q/51875463
tags question: http://stackoverflow.com/q/51866059
tag name: csv
tags question: http://stackoverflow.com/q/51940441
tags question: http://stackoverflow.com/q/51847892
tags question: http://stackoverflow.com/q/51861326
tags question: http://stackoverflow.com/q/51871136
tags question: http://stackoverflow.com/q/51916823
tags question: http://stackoverflow.com/q/51850512
tags question: http://stackoverflow.com/q/51903086
tags question: http://stackoverflow.com/q/51911391
tags question: http://stackoverflow.com/q/51829209
tags question: http://stackoverflow.com/q/51826748
tags question: http://stackoverflow.com/q/51800100
tags question: http://stackoverflow.com/q/51811096
tags question: http://stackoverflow.com/q/51858064
tags question: http://stackoverflow.com/q/51953233
tags question: http://stackoverflow.com/q/51896905
tags question: http://stackoverflow.com/q/51953630
tags question: http://stackoverflow.com/q/51823419
tags question: http://stackoverflow.com/q/51935399
tags question: http://stackoverflow.com/q/51904037
tags question: http://stackoverflow.com/q/51914391
tags question: http://stackoverflow.com/q/51816546
tags question: http://stackoverflow.com/q/51875916
tags question: http://stackoverflow.com/q/51882581
tags question: http://stackoverflow.com/q/51845113
tags question: http://stackoverflow.com/q/51873354
tags question: http://stackoverflow.com/q/51919344
tags question: http://stackoverflow.com/q/51924068
tags question: http://stackoverflow.com/q/51845613
tags question: http://stackoverflow.com/q/51803508
tags question: http://stackoverflow.com/q/51884044
tags question: http://stackoverflow.com/q/51839778
tags question: http://stackoverflow.com/q/51845977
tags question: http://stackoverflow.com/q/51864192
tags question: http://stackoverflow.com/q/51880360
tags question: http://stackoverflow.com/q/51822965
tags question: http://stackoverflow.com/q/51881144
tags question: http://stackoverflow.com/q/51853149
tags question: http://stackoverflow.com/q/51861569
tags question: http://stackoverflow.com/q/51889613
tags question: http://stackoverflow.com/q/51815633
tags question: http://stackoverflow.com/q/51834311
tags question: http://stackoverflow.com/q/51886576
tags question: http://stackoverflow.com/q/51899774
tags question: http://stackoverflow.com/q/51866285
tags question: http://stackoverflow.com/q/51886541
tags question: http://stackoverflow.com/q/51809507
tags question: http://stackoverflow.com/q/51886802
tags question: http://stackoverflow.com/q/51943479
tags question: http://stackoverflow.com/q/51925830
tags question: http://stackoverflow.com/q/51850368
tags question: http://stackoverflow.com/q/51928786
tags question: http://stackoverflow.com/q/51926983
tags question: http://stackoverflow.com/q/51824207
tags question: http://stackoverflow.com/q/51867911
tags question: http://stackoverflow.com/q/51923395
tags question: http://stackoverflow.com/q/51917393
tags question: http://stackoverflow.com/q/51936513
tags question: http://stackoverflow.com/q/51856875
tags question: http://stackoverflow.com/q/51922410
tags question: http://stackoverflow.com/q/51878601
tags question: http://stackoverflow.com/q/51897241

http://stackoverflow.com/a/51899140
has body: A simple way to achieve what I think you want is the following: mainText = ['6005,280', '6005,2751', '6005,260'] target_list = [elem.split(',') for elem in mainText]
downvote count: 0
answers question: http://stackoverflow.com/q/51899072
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/q/51951644
answer count: 2
score: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/51951883
accepted answer: http://stackoverflow.com/a/51951996
tagged with: python-3.x
has body: I am not sure I have a great title, so if anyone has a suggestion, I am up for it. Let's say I have the following scenario: Searching for "where" Input: &lt;Dave likes cake.&gt; &lt;Dave goes to school.&gt; &lt;Where is dave today, after school?/&gt;&lt;I do not know where dave is&gt; &lt;Cindy reads a book&gt;&lt;Where is my shoe asked cindy.&gt;&lt;Cindy likes bacon.&gt;&lt;Cindy goes to the park.&gt;&lt;where did cindy go?&gt; &lt;Sally drinks wine.&gt;&lt;The lake is where I am from commented Sally&gt;&lt;Cindy watches day time television while watching the kids.&gt;&lt;Cindy makes great sandwiches&gt;&lt;where is the sandwich cindy made?&gt; Desired Output: &lt;Where is dave today, after school?/&gt;&lt;I do not know where dave is&gt; &lt;Where is my shoe asked cindy.&gt;&lt;where did cindy go?&gt; &lt;The lake is where I am from commented Sally&gt;&lt;where is the sandwich cindy made?&gt; I want to keep everything starting at the first character within another set of characters that contain the phrase I am searching for. I also want to remove everything before the first character that contained the phrase I am looking for as well as remove everything after the last character that contained the phrase. Any suggestions? I am unsure how to approach this, but I am thinking about using some sort of regular expression with look aheads/behinds maybe? Edit #1: Context added to what I am doing This relates to pandas because I had stored an XML file as text inside of a pandas data frame. The XML file was an SSIS package that I needed to search for specific words and phrases. I did a join to concatenate all of the xml into 1 single line. Edit #2: More Context I had a problem with multi line SQL statements in the XML data I was looking at, that was the reason I used ' '.join everything to 1 line. I need to not only find where in the XML, but return all of the SQL statement if what I am looking for is part of a multi line SQL statement. Edit #3: This solution (provided fro…
tagged with: python
has answer: http://stackoverflow.com/a/51951996
has comment: http://stackoverflow.com/comment/90854056
has title: Pandas Removing Text Before and After Certain Characters
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90853880
has comment: http://stackoverflow.com/comment/90854117
possible better answer: http://stackoverflow.com/a/51951883
has comment: http://stackoverflow.com/comment/90853960
type: Question

http://stackoverflow.com/comment/104597746
type: AnswerComment
comment on: http://stackoverflow.com/a/51894302
score: 0
type: Comment
has text: hi, I'm having the same issue. could you please provide more info?

http://stackoverflow.com/q/51886943
has comment: http://stackoverflow.com/comment/90749179
tagged with: lstm
tagged with: deep-learning
score: 2
downvote count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51901071
tagged with: keras
has title: Keras LSTM Input Transpose
favorite count: 0
has comment: http://stackoverflow.com/comment/90749567
type: Question
has comment: http://stackoverflow.com/comment/90730429
has comment: http://stackoverflow.com/comment/90748607
tagged with: python
has body: I'm training a timeseries LSTM model using Keras. I understand that the input to the model has to be in the format: [samples, timesteps, features]. However, when I reverse transpose each input element, so the input now is in the format: [samples, features, timesteps] my model accuracy improves significantly, and training time is reduced quite a bit as well. Does anyone have an explanation as to why? For reference, here are the stats on my training data: samples: 720 timesteps: 256 features: 4 So my input tensor should have the shape [720, 256, 4] but reshaping to [720, 4, 256] produces better results. Why?
upvote count: 2
has comment: http://stackoverflow.com/comment/90749317
has comment: http://stackoverflow.com/comment/90749689
has comment: http://stackoverflow.com/comment/90748964
answer count: 1
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/90726192
has comment: http://stackoverflow.com/comment/90753505

http://stackoverflow.com/q/51822861
has body: I would like to read a STEP file generated from a CAD software and extract the equations that define geometry. SolidWorks has a similar functionality that recognizes geometric features form generic CAD formats such as IGES or STEP. Is there a library in python or C++ which allows me to do this?
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/51823030
has comment: http://stackoverflow.com/comment/90599980
favorite count: 0
type: UnansweredQuestion
has title: Extracting parametric equations from STEP file
tagged with: python
score: 2
upvote count: 2
tagged with: cad
type: Question

http://stackoverflow.com/q/51819606
has comment: http://stackoverflow.com/comment/90593535
has comment: http://stackoverflow.com/comment/90593301
upvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/51820433
has comment: http://stackoverflow.com/comment/90593016
score: 1
has comment: http://stackoverflow.com/comment/90592985
downvote count: 0
has comment: http://stackoverflow.com/comment/90593497
tagged with: string
has comment: http://stackoverflow.com/comment/90593008
favorite count: 0
has answer: http://stackoverflow.com/a/51819816
has comment: http://stackoverflow.com/comment/90593523
answer count: 3
has comment: http://stackoverflow.com/comment/90594035
has comment: http://stackoverflow.com/comment/90593128
has comment: http://stackoverflow.com/comment/90593741
has comment: http://stackoverflow.com/comment/90593628
possible better answer: http://stackoverflow.com/a/51819752
tagged with: python
has title: Remove words with spaces or "-" in them Python
has comment: http://stackoverflow.com/comment/90594113
has answer: http://stackoverflow.com/a/51819752
has comment: http://stackoverflow.com/comment/90593540
linked to: http://stackoverflow.com/q/48992197
type: AnsweredQuestion
has body: This is an extension to the question here Now as in the linked question, the answer used a space? as a regex pattern to match a string with a space or no space in it. The Problem Statement: I have a string and an array of phrases. input_string = 'alice is a character from a fairy tale that lived in a wonder land. A character about whome no-one knows much about' phrases_to_remove = ['wonderland', 'character', 'noone'] Now what I want to do is to remove the last occurrences of the words in the array phrases_to_remove from the input_string. output_string = 'alice is a character from a fairy tale that lived in a. A about whome knows much about' Notice: the words to remove may or may not occur in the string and if they do, they may occur in either the same form {'wonderland' or 'character', 'noone'} or they may occur with a space or a hyphen (-) in between the words e.g. wonder land, no-one, character. The issue with the code is, I can't remove the words that have a space or a - mismatch. For example wonder land and wonderland and wonder-land. I tried the (-)?|( )? as a regex but couldn't get it to work. I need help
has answer: http://stackoverflow.com/a/51820433
has comment: http://stackoverflow.com/comment/90593096

http://stackoverflow.com/a/52173234
has body: I have this same issue. My script works fine in Python 3.6.5, but fails in 3.7.0
has comment: http://stackoverflow.com/comment/91327421
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/92674857
answers question: http://stackoverflow.com/q/51885734
accepted answer of: http://stackoverflow.com/q/51885734
has comment: http://stackoverflow.com/comment/91369295
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/q/51953855
type: Question
has body: For a school project I need get the web addresses of 200 companies (based on a list). My script is working fine, but when I'm around the company 80, I get blocked by google. This is the message that I'm getting. &gt; Our systems have detected unusual traffic from your computer network. &gt; This page checks to see if it's really you sending the requests, and &gt; not a robot. &lt;a href="#" &gt; onclick="document.getElementById('infoDiv').style.display='block' I tried two different ways to get my data: A simple one: for company_name in data: search = company_name results = 1 page = requests.get("https://www.google.com/search?q={}&amp;num={}".format(search, results)) soup = BeautifulSoup(page.content, "html5lib") and a more complex on: for company_name in data: search = company_name results = 1 s = requests.Session() retries = Retry(total=3, backoff_factor=0.5) s.mount('http://', HTTPAdapter(max_retries=retries)) s.mount('https://', HTTPAdapter(max_retries=retries)) page = s.get("https://www.google.com/search?q={}&amp;num={}".format(search, results)) #time.sleep(.600) soup = BeautifulSoup(page.content, "html5lib") But I'm getting the same mistake over and over. Is there a way I could overcome this issue? thanks!
answer count: 2
score: 5
upvote count: 6
has comment: http://stackoverflow.com/comment/90858204
favorite count: 0
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/90858744
has title: Google scraping using python - requests: How to avoid being blocked due to many requests?
downvote count: 1
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90858763
tagged with: web-scraping
tagged with: python
tagged with: python-requests
has answer: http://stackoverflow.com/a/51955893
has comment: http://stackoverflow.com/comment/90858094
has answer: http://stackoverflow.com/a/51954641

artificial-intelligence
tags question: http://stackoverflow.com/q/51867981
tags question: http://stackoverflow.com/q/51872781
tags question: http://stackoverflow.com/q/51871907
tags question: http://stackoverflow.com/q/51895192
tags question: http://stackoverflow.com/q/51832803
tags question: http://stackoverflow.com/q/51911751
tags question: http://stackoverflow.com/q/51952062
type: Tag
tags question: http://stackoverflow.com/q/51870095
tags question: http://stackoverflow.com/q/51815699
tags question: http://stackoverflow.com/q/51905199
tag name: artificial-intelligence

http://stackoverflow.com/q/51945989
has comment: http://stackoverflow.com/comment/90870341
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/90841397
has answer: http://stackoverflow.com/a/51961540
favorite count: 0
tagged with: python
type: AnsweredQuestion
score: 1
has body: I want to set up QMessageBox text format, but I can't find a valid method. QtGui.QMessageBox.information( self, "Confirm delete!", "Are you sure you want to delete file?\n %s" % filename, QtGui.QMessageBox.Yes | QtGui.QMessageBox.No, QtGui.QMessageBox.No ) I want to make bold, like: "Are you sure you want to delete file?\n %s" How can I do this?
accepted answer: http://stackoverflow.com/a/51961540
upvote count: 1
has title: How to set up QMessageBox text format?
type: Question
tagged with: pyside

http://stackoverflow.com/comment/90592422
type: Comment
comment on: http://stackoverflow.com/a/51817734
type: AnswerComment
has text: Perfect. I figured it out from a github source. `formataddr` was the solution from `email.utils` it takes a tuple of name and email. Thanks very much though for the other tips
score: 0

http://stackoverflow.com/q/51873758
has title: fail to install jupyter on mac
tagged with: pip
tagged with: python
has body: How can I solve this problem? $ pip3 install jupyter Collecting jupyter Could not fetch URL https://pypi.python.org/simple/jupyter/: There was a problem confirming the ssl certificate: [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:719) - skipping Could not find a version that satisfies the requirement jupyter (from versions: ) No matching distribution found for jupyter
score: 1
downvote count: 1
type: Question
linked to: http://stackoverflow.com/q/49768770
duplicate of: http://stackoverflow.com/q/49768770
answer count: 2
tagged with: jupyter
tagged with: macos
has answer: http://stackoverflow.com/a/51874178
favorite count: 0
has answer: http://stackoverflow.com/a/51873875
upvote count: 2
type: UnansweredQuestion

http://stackoverflow.com/a/51946184
has body: For a variable number of connected variables, a dictionary is one recommended solution. You can use a dictionary comprehension to ensure that list values are not linked. If your variables are genuinely letters, you can also utilize string.ascii_lowercase: from string import ascii_lowercase d = {i: [] for i in ascii_lowercase[:10]} d['a'].append(1) print(d) {'a': [1], 'b': [], 'c': [], 'd': [], 'e': [], 'f': [], 'g': [], 'h': [], 'i': [], 'j': []} In contrast, and for reference, note that using dict.fromkeys will ensure that the same list is used for each key: d = dict.fromkeys(ascii_lowercase[:10], []) d['a'].append(1) print(d) {'a': [1], 'b': [1], 'c': [1], 'd': [1], 'e': [1], 'f': [1], 'g': [1], 'h': [1], 'i': [1], 'j': [1]}
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51946051

http://stackoverflow.com/q/51878576
answer count: 3
has answer: http://stackoverflow.com/a/51878750
has answer: http://stackoverflow.com/a/51878862
tagged with: dry
has body: I want to create multiple functions that have similar structure. And typing them out one by one does not seem to be clever as it obviously violates the do not repeat yourself (DRY) principle. The situation is such that I have an array function_names = ["func1", "func2", … , "func10"]. Additionally I want an if, elif and else statement inside these functions with different actions. These functions are inside a class. The goal is to simplify this structure class MainClass: def func1(self): if condition_a: return action1(parameter1) elif condition_b: return random_action1(random_parameter1) else: print("There is something wrong inside func1") def func2(self): if condition_a: return action2(parameter2) elif condition_b: return random_action2(random_parameter2) else: print("There is something wrong inside func2") # Same structure of functions goes on The conditions condition_a and condition_b are invariant.
tagged with: python
has comment: http://stackoverflow.com/comment/90708609
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51878664
has comment: http://stackoverflow.com/comment/90708561
has title: Python generate functions from array
type: Question
tagged with: function
accepted answer: http://stackoverflow.com/a/51878664
possible better answer: http://stackoverflow.com/a/51878750
score: 0

http://stackoverflow.com/a/51824748
has body: Try the following code. It's achieved by creating a subplot for each level[0] index in your case year and using that as the x_label. And for each subplot we plot the data. def plot_function(x, ax): ax = graph[x] ax.set_xlabel(x, weight='bold') return serotype_df.xs(x).plot(kind='bar', stacked='True', ax=ax, legend=False) n_subplots = len(serotype_df.index.levels[0]) fig, axes = plt.subplots(nrows=1, ncols=n_subplots, sharey=True, figsize=(14, 8)) # width, height graph = dict(zip(serotype_df.index.levels[0], axes)) plots = list(map(lambda x: plot_function(x, graph[x]), graph)) ax.tick_params(axis='both', which='both', length=0) fig.subplots_adjust(wspace=0) plt.legend() plt.show() If you're not making much changes to each subplot you can always do the following: plots = list(map(lambda x: serotype_df.xs(x).plot(kind='bar', stacked='True', ax=graph[x], legend=False).set_xlabel(x, weight='bold'), graph)) That way you don't have to create or use the plot_function
upvote count: 14
score: 14
accepted answer of: http://stackoverflow.com/q/51818724
has comment: http://stackoverflow.com/comment/116901379
answers question: http://stackoverflow.com/q/51818724
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/130764366
type: Answer

http://stackoverflow.com/comment/90709377
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51878819
has text: What's wrong with JavaScript?

http://stackoverflow.com/comment/90572765
comment on: http://stackoverflow.com/q/51808715
has text: Cross-language dupe: [When to catch the Exception vs When to throw the Exceptions?](//stackoverflow.com/q/18679090)
score: 0
type: Comment
type: QuestionComment

postgresql
tags question: http://stackoverflow.com/q/51821428
tags question: http://stackoverflow.com/q/51869524
tags question: http://stackoverflow.com/q/51905337
tags question: http://stackoverflow.com/q/51890055
tags question: http://stackoverflow.com/q/51806240
tags question: http://stackoverflow.com/q/51827635
tags question: http://stackoverflow.com/q/51805104
tags question: http://stackoverflow.com/q/51839367
tags question: http://stackoverflow.com/q/51843857
tags question: http://stackoverflow.com/q/51814074
tags question: http://stackoverflow.com/q/51829008
tags question: http://stackoverflow.com/q/51810720
tags question: http://stackoverflow.com/q/51802694
tags question: http://stackoverflow.com/q/51941780
tags question: http://stackoverflow.com/q/51873708
tags question: http://stackoverflow.com/q/51850581
tags question: http://stackoverflow.com/q/51861651
tags question: http://stackoverflow.com/q/51810439
tag name: postgresql
tags question: http://stackoverflow.com/q/51858497
tags question: http://stackoverflow.com/q/51885802
tags question: http://stackoverflow.com/q/51850512
tags question: http://stackoverflow.com/q/51947561
type: Tag
tags question: http://stackoverflow.com/q/51854353
tags question: http://stackoverflow.com/q/51826165
tags question: http://stackoverflow.com/q/51944414
tags question: http://stackoverflow.com/q/51859331
tags question: http://stackoverflow.com/q/51851410
tags question: http://stackoverflow.com/q/51954285
tags question: http://stackoverflow.com/q/51858564
tags question: http://stackoverflow.com/q/51804513
tags question: http://stackoverflow.com/q/51902950
tags question: http://stackoverflow.com/q/51941149
tags question: http://stackoverflow.com/q/51853072

http://stackoverflow.com/comment/90823831
has text: IIUC, why don't you just read the file and send it to a dataframe and then conditionally filter the dataframe? You could run a test with a small subset of your data. Currently you are employing way too much indexing. Your file is already comma-delimited, use that to your advantage (`pd.read_csv()`).
score: 3
comment on: http://stackoverflow.com/q/51936513
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90576109
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51805206
has text: Nope, still getting the same error. Tried this with both the existing has_permission method and alone, still nothing. Any other thoughts?
score: 0

http://stackoverflow.com/a/51814284
score: 0
type: Answer
has body: I ended up modifying the function and got it to work. I instead used a nested if rather than making != np.NaN its own if. # Fill Basement Finishes def fills_na(cols): fin = cols[0] subclass = cols[1] if pd.isnull(fin): if subclass &lt; 60: return 'Unf' else: return 'GLQ' else: return fin all_data['BsmtFinType1'] = all_data'BsmtFinType1','MSSubClass'.apply(fills_na, axis = 1)
answers question: http://stackoverflow.com/q/51814180

http://stackoverflow.com/a/51928126
type: AcceptedAnswer
has body: You can use str.split Ex: l = ['238 236 237 238 240 240 239 241 241 243 240 239 231 212 190 173 148 122 104 92 143 136 132 127 124 119 110 104 112 119 78 20 17 19 20 23 26 31 30 30 32 33 29 30 34 39 49 62 70 75 90'] print( list(map(int, l[0].split())) ) Output: [238, 236, 237, 238, 240, 240, 239, 241, 241, 243, 240, 239, 231, 212, 190, 173, 148, 122, 104, 92, 143, 136, 132, 127, 124, 119, 110, 104, 112, 119, 78, 20, 17, 19, 20, 23, 26, 31, 30, 30, 32, 33, 29, 30, 34, 39, 49, 62, 70, 75, 90]
has comment: http://stackoverflow.com/comment/90805962
type: Answer
has comment: http://stackoverflow.com/comment/90806027
score: 2
answers question: http://stackoverflow.com/q/51928090
upvote count: 3
accepted answer of: http://stackoverflow.com/q/51928090
downvote count: 1

pyo
tag name: pyo
tags question: http://stackoverflow.com/q/51925947
type: Tag
tags question: http://stackoverflow.com/q/51893964

http://stackoverflow.com/a/51851445
type: Answer
has body: This might be way simpler as you think. Read your data: data = np.array(the array that u gave us above) and then you can read column by column using numpy formatting: min_0_indices.append(np.argmin(data[:, [0]])) the ":" means every line in column "0". Also with np.argmin we get the index of the minimum. And then we can set the value of data[index][0] = 100 so when we repeat the search for a minimum it doesn't get picked again. data[np.argmin(data[:, [0]])][0] = 100 Now we have the normal array min_0_indices which contains the top 10 minimum values if you repeat all that (except reading data) 10 times. To get other columns just replace the [0] with the columnnuber.
answers question: http://stackoverflow.com/q/51851016
score: 0

http://stackoverflow.com/a/73357134
score: -1
has comment: http://stackoverflow.com/comment/129641441
has comment: http://stackoverflow.com/comment/129640923
upvote count: 0
answers question: http://stackoverflow.com/q/51903204
type: Answer
has body: dct_01 = {'a': 1, 'b': 2, 'c': 3} dct_02 = {'a': 2, 'b': 1, 'c': 3, 'd': 4} dct_03 = {**dct_01,**dct_02} print(dct_03)
downvote count: 1

http://stackoverflow.com/comment/90788894
has text: I'm getting a Timeout Exception when trying to run this :/
comment on: http://stackoverflow.com/a/51905861
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/90815713
type: Comment
comment on: http://stackoverflow.com/a/51932269
score: 0
type: AnswerComment
has text: Perhaps one could add mentioning that `csv` isn't necessary here, as only full lines are copied or not depending on their beginning

http://stackoverflow.com/q/51851720
has title: Python regex extract number between forward slashes
tagged with: python
tagged with: regex
upvote count: 0
linked to: http://stackoverflow.com/q/22937618
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51851748
accepted answer: http://stackoverflow.com/a/51851769
score: -1
type: Question
has comment: http://stackoverflow.com/comment/90656347
possible better answer: http://stackoverflow.com/a/51851748
answer count: 2
has answer: http://stackoverflow.com/a/51851769
downvote count: 1
has comment: http://stackoverflow.com/comment/90656387
has body: New to python and need help with regex please. How do I extract the number 10000000000 from the string below /s-seller/John/10000000000/time/1 Please note the word John is dynamic and number 10000000000 can also be any random numbers. Thank you
favorite count: 0

http://stackoverflow.com/comment/90791889
comment on: http://stackoverflow.com/q/51920912
score: 1
has text: [This old post](https://stackoverflow.com/questions/25676835/signal-handling-in-multi-threaded-python) is probably relevant.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51928738
has comment: http://stackoverflow.com/comment/90807420
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90807713
has title: How do I get my code to show a certain number of characters from a text file
score: 1
type: Question
has comment: http://stackoverflow.com/comment/90807656
has body: In my assignment i'm expected to look for a word and only return a set number of characters (which is 80, and 40 on each side surrounding the word), without the use of nltk or regex. I've set my code up as so open = open("a2.txt", 'r') file2read = open.readlines() name = 'word' for line in file2read: s2 = line.split ("\n", 1) if name in line: i = line.find(name) half = (80 - len(name) - 2) // 2 left = line[i - half] right = line[i + len(word) + half] print(left + word + right) but then my print out looks like this(updated screenshot) instead of the 80 character lines which i'm hoping to find. Sorry if this is a really newbie error as i'm only 3 weeks into the program and i've been searching and can't seem to get the answer
answer count: 1
has comment: http://stackoverflow.com/comment/90807034
accepted answer: http://stackoverflow.com/a/51928911
upvote count: 1
has comment: http://stackoverflow.com/comment/90807356
tagged with: python
favorite count: 0
downvote count: 0
has answer: http://stackoverflow.com/a/51928911

http://stackoverflow.com/comment/90683342
has text: Also, @chundu: Could you [edit] the information from your most recent comment into your question? Without it, the question is easily misunderstood, and most of the answers you've received so far aren't really addressing your real problem as a result.
score: 1
comment on: http://stackoverflow.com/q/51865326
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90659301
has text: This is quite nice..Is it possible to disable just the unique value check and not every type of validation for that field ?
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51852931

http://stackoverflow.com/comment/128409276
type: AnswerComment
type: Comment
score: 1
has text: `abc` is confict with python's `abstract class` module
comment on: http://stackoverflow.com/a/72372036

http://stackoverflow.com/q/51940449
tagged with: python
accepted answer: http://stackoverflow.com/a/51940565
has title: Posting form data with requests and python
score: 0
linked to: http://stackoverflow.com/q/24535920
tagged with: python-requests
possible better answer: http://stackoverflow.com/a/51940947
has answer: http://stackoverflow.com/a/51940947
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51940565
has body: Posting form data isn't working and since my other post about this wasn't working, I figured I would try to ask the question again so maybe I can get another perspective. I am currently trying to get the requests.get(url, data=q) to work. When I print, I am getting a page not found. I have resorted just to set variables and join them to the entire URL to make it work but I really want to learn this aspect about requests. Where am I making the mistake? I am using the HTML tag attributes name=search_terms and name=geo_location_terms for the form. search_terms = "Bars" location = "New Orleans, LA" url = "https://www.yellowpages.com" q = {'search_terms': search_terms, 'geo_locations_terms': location} page = requests.get(url, data=q) print(page.url)
type: Question
answer count: 2

http://stackoverflow.com/comment/90727564
type: Comment
comment on: http://stackoverflow.com/a/51869895
score: 0
type: AnswerComment
has text: So the way I am implementing this is , defining a variable something like this file_to_search = re.search(r'^Weekly \d{2}[/.-]\d{2}[/.-]\d{4} Scores\.xlsx$') def search_file(): for file in os.listdir(source): if fnmatch.fnmatch(file, file_to_search): return True return False if search_file(): print('File exists') else: print('File not found')

http://stackoverflow.com/q/51926162
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/90868321
has comment: http://stackoverflow.com/comment/90801800
score: -3
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51926269
downvote count: 3
has body: I am trying to iterate column of alphabet in 'new.xlsx', and if the alphabet exists in 'original.xlsx', then copy the data and paste into new.xlsx. The code following is what I have done. import openpyxl dappend = openpyxl.load_workbook('C:/Users/User/Desktop/original.xlsx', data_only=True) dp1 = dappend.active consider = openpyxl.load_workbook('C:/Users/User/Desktop/new.xlsx', data_only=True) cd1 = consider.active li2 = [] for c in range(2,cd1.max_row+1): name = cd1.cell(row=c,column=4).value for d in range(2,dp1.max_row+1): if cd1.cell(row=c,column=4).value == dp1.cell(row=d,column=4).value: li2=[dp1.cell(row=d,column=4).value,dp1.cell(row=d,column=5).value,dp1.cell(row=d,column=6).value,dp1.cell(row=d,column=7).value] print(li2) d = d + 1 else: continue c = c + 1 My output is: ['A', None, 'Jonathan', None] ['A', '', 'Jonathan', ''] ['B', None, 'Cassandra', None] ['B', None, 'Rose', None] ['B', 'Tyler', None, None] ['B', '', 'Cassandra', ''] ['B', '', 'Rose', ''] ['B', 'Tyler', '', ''] ['C', 'Sam', None, None] ['C', 'Sam', '', ''] ['D', 'Jeremy', None, None] ['D', 'Jeremy', '', ''] but I expected the output to be like... ['A', '', 'Jonathan', ''] ['B', '', 'Cassandra', ''] ['B', '', 'Rose', ''] ['B', 'Tyler', '', ''] ['C', 'Sam', '', ''] ['D', 'Jeremy', '', ''] Please help...
type: Question
has answer: http://stackoverflow.com/a/51926269
upvote count: 0
answer count: 1
has title: Python-How to display the for loop only once?

http://stackoverflow.com/q/51830240
score: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/51830262
has title: run time check function
has body: I know I can use time module to track the run-time of my codes: For example if I have this fibonacci function with recursion def fib_gen_r(i): """ Fibonacci function generator generate the fibonacci number at 'i'th posistion """ if i == 0: return 0 elif i == 1: return 1 else: return fib_gen_r(i - 1) + fib_gen_r(i - 2) I can do this: import time start_time = time.time() print(fib_gen_r(35)) print(f"--- {time.time() - start_time}s seconds ---\n") # &gt;&gt;&gt; # 9227465 # --- 2.556117296218872s seconds --- But, if I don't want to write this everytime, I wrote a function: def time_spend(code_to_check): import time start_time = time.time() print(code_to_check) print(f"--- {time.time() - start_time}s seconds ---\n") time_spend(fib_gen_r(35)) # &gt;&gt;&gt; # check run-time: # 9227465 # --- 0.0s seconds --- Somehow, it is not reading the run-time, what did I do wrong? Thanks,
has comment: http://stackoverflow.com/comment/90618963
upvote count: 1
answer count: 1
tagged with: time
tagged with: python
has comment: http://stackoverflow.com/comment/90616210
has comment: http://stackoverflow.com/comment/90619014
accepted answer: http://stackoverflow.com/a/51830262
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/comment/90731029
score: 0
type: Comment
has text: Your right, I was leaning towards using split and join method since I had to use join for the regex either way.. but I was curious to see if it could be done better without it. anyway I think ill just stick with what you outlined here.
comment on: http://stackoverflow.com/a/51888966
type: AnswerComment

http://stackoverflow.com/comment/90603631
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51824512
has text: No other way around it?

http://stackoverflow.com/comment/90691340
score: 0
has text: perhaps this question is a better match for [codereview](https://codereview.stackexchange.com/), but consider reading their [how to ask](https://codereview.stackexchange.com/help/how-to-ask) before posting there.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51869907

http://stackoverflow.com/q/51832788
accepted answer: http://stackoverflow.com/a/51832912
linked to: http://stackoverflow.com/q/1850289
has body: In Python I'm making a graph class which I intend to design by creating a Node class, and then an Edge class which takes as arguments to the constructor two nodes, a source and target. I'd also like to check in the Edge class that the two inputs are in fact Nodes, so I'd like to include some lines like assert type(src) is Node and type(tgt) is Node However, this will not act as I expect it to. As I understand it, I would need to use something like src.__name__ is Node.__name__ but this just seems ugly. Is there a way to control the type name of a user-defined class so that the code reads a little more nicely? I tried following some of what I found here: Python: Change class type name and wrote the code class Node: ... __class__ = type("Node", (type,), {}) I'm not sure if I was mis-applying the lessons found in that link or if those lessons wouldn't accomplish what I'm trying to do--but one way or another, it didn't do what I was hoping for.
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51832912
tagged with: class
score: 0
has comment: http://stackoverflow.com/comment/90619741
answer count: 1
has title: Python: Changing the class name
tagged with: python
has comment: http://stackoverflow.com/comment/90620002

http://stackoverflow.com/a/51852754
type: AcceptedAnswer
has body: Your form action is pointing to create_post:retrieve_projects change it so it points to create_post:create_projects
upvote count: 2
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/51852574
answers question: http://stackoverflow.com/q/51852574
downvote count: 0

http://stackoverflow.com/q/51915418
has body: this is my current code def info_coin(bot, update, args): if args[-1] == '1': coin_list = args[:-1] opt = 1 else: coin_list = args opt = 0 for coin_name in coin_list: coin_call =requests.get("https://api.coingecko.com/api/v3/coins/" + str(coin_name)).json() coin_isd = coin_call ['description']['en'] print(coin_isd) update.message.reply_text(coin_isd) i would like to further select ['en'] to only take a select an amount of text from it. Reason being is my message is to long to send.
score: -1
tagged with: chatbot
answer count: 2
has answer: http://stackoverflow.com/a/51915458
has title: selecting small amounts from json output in python
downvote count: 1
favorite count: 0
tagged with: telegram
type: UnansweredQuestion
tagged with: python
upvote count: 0
tagged with: bots
has answer: http://stackoverflow.com/a/51915465
type: Question
has comment: http://stackoverflow.com/comment/90780858
tagged with: http://stackoverflow.com/tag/json

http://stackoverflow.com/comment/90664731
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/51856268
score: 0
has text: That also reminds me to make sure this does not happen. Thanks @tobias_k

http://stackoverflow.com/comment/117100550
score: 0
type: Comment
comment on: http://stackoverflow.com/a/56551502
has text: this answer is correct, do not know why it was unaccepted
type: AnswerComment

http://stackoverflow.com/q/51939716
has comment: http://stackoverflow.com/comment/90829468
score: -1
tagged with: date
answer count: 1
downvote count: 1
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90829701
tagged with: python
has answer: http://stackoverflow.com/a/51940001
accepted answer: http://stackoverflow.com/a/51940001
has comment: http://stackoverflow.com/comment/90829717
type: AnsweredQuestion
upvote count: 0
has body: I'm building an API for my college's timetable website. The default option is to look up today's timetable. However, the timetable system is using week numbering different to the one we normally use. One of the 2 things I need to build the URL is the week number. TIMETABLE_URL = 'http://timetable.ait.ie/reporting/textspreadsheet;student+set;id;{}?t=student+set+textspreadsheet&amp;days=1-5&amp;=&amp;periods=3-20&amp;=student+set+textspreadsheet&amp;weeks={}&amp;template=student+set+textspreadsheet' Week numbering should start at this date: 27 Aug 2018 - 2 Sep 2018. Following this, week 2 would be 3 Sep 2018-9 Sep 2018 and so on. This should carry over New Years, the date of 31 Dec 2018-6 Jan 2019 would be week 19. This 'year' would have 52 weeks total. I know how to check if a certain date is in between one of the ranges from above, but I want to avoid manually setting all the date ranges. How can I have a script know that, for example, it's in week 3 on 12 September?
has title: Non-standard week numbering
type: Question
has comment: http://stackoverflow.com/comment/90829413

http://stackoverflow.com/comment/90639943
comment on: http://stackoverflow.com/q/51821475
has text: I'm not sure how that would work?
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/a/56238748
has body: In your views.py you can access your logged user like this: from django.contrib.auth.models import AnonymousUser def acesso_consultausuario(request): my_user = request.user #If you want to know if the user is logged in is_user_logged = my_user.is_authenticated By the way, I am also a Spanish speaker but it is a good practice to code everything in English so you can share and get feedback with the world (even variable names). Hope this helps!
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/51849550
downvote count: 0
score: 1

http://stackoverflow.com/a/51855413
upvote count: 1
has body: There is no option to unwrap methods that are attached to the multi-line strings, but I will consider unwrapping that (or adding a new option to do so). Unwrapping nested routines where the inner one has a multi-line string is going to be more difficult. What currently IMO is the best approach is to assign the string to a variable, with a name short enough to not cause wrapping in the function call line: def main(): fmt_s = """\ first: {a} second: {b} third: {c} """ print(dedent(fmt_s.format(a=1, b=2, c=3)), end="") reformats the same (given you don't set the line-length to a very low value, and so does: def main(): fmt_s = dedent("""\ first: {a} second: {b} third: {c} """) print(fmt_s.format(a=1, b=2, c=3), end="") Please note that both these versions dedent before applying .format(). I find that his is almost always what you want as it prevents you from having to include as many spaces as your multi-line string has as leading spaces after any newlines that are part of your format-arguments. Your examples dedent after format-ting.
accepted answer of: http://stackoverflow.com/q/51854839
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51854839
type: Answer
score: 1

http://stackoverflow.com/q/51914610
downvote count: 0
has body: This weekend I've been leaning the sqlite3 stdlib module for python. I'm completely new to SQL. I was attempting to write a test for experimenting with foreign keys, but unfortunately the segments table does not seem to be populated, i.e fetchall() returns no results. I took a look at the db file, and the declarations of each table exist, but only the points appears to be populated. Could anyone provide some insight? import json import attr import random import pytest import datetime as dt import typing as typ import sqlite3 as sql @attr.s class Point: x: float = attr.ib(default=random.random()) y: float = attr.ib(default=random.random()) def adapt_point(point: Point) -&gt; str: data = attr.asdict(point) text = json.dumps(data) return text def convert_point(value: bytes) -&gt; Point: data = json.loads(value) value = Point(**data) return value sql.register_adapter(Point, adapt_point) sql.register_converter('point', convert_point) @pytest.fixture def connection(): con = sql.connect('tmpdb.sqlite', detect_types=sql.PARSE_DECLTYPES) cur = con.cursor() cur.execute( """ create table points( id integer primary key, pt point, at timestamp ); """ ) cur.execute( """ create table segments( id integer primary key, start integer, end integer, at timestamp, foreign key(start) references points(id), foreign key(end) references points(id) ); """ ) con.commit() yield con con.close() def test_insert_points(connection: sql.Connection): """ Test adding: * datetime object using builtin 'timestamp' adapter and converter * dataclass object using custom adapter and converter using :py:func:`attr.asdict` :param connection: sqlite fixture """ cur = connection.cursor() for i in range(5): cur.execute( "insert into points(id, pt, at) values (?, ?, ?)", (i, Point(), dt.datetime.now()) ) connection.commit() def test_insert_segments(connection: sql.Connection): """ Test adding: * datetime object using builtin 'timestamp' adapter and converter * foreign keys to other table :param connection: sqlite…
has comment: http://stackoverflow.com/comment/90799707
favorite count: 0
tagged with: foreign-keys
tagged with: sql
tagged with: sqlite
tagged with: python
has title: Table with foreign keys not populating
answer count: 0
type: UnansweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/90793481
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/90782172

http://stackoverflow.com/comment/90744907
has text: That is true, I actually found that the problem was related to numba and using the parallel = True flag, otherwise it works without problems. I'll simplify the code and updated when I get some time, in case someone has the same problem
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51873510

http://stackoverflow.com/comment/90601746
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51823780
has text: I am using Python v3.7

http://stackoverflow.com/comment/90640295
type: QuestionComment
has text: I've gone to localhost:8888 and nothing is running there.
score: 0
comment on: http://stackoverflow.com/q/51830963
type: Comment

http://stackoverflow.com/q/51858649
has answer: http://stackoverflow.com/a/51859641
tagged with: python
possible better answer: http://stackoverflow.com/a/51859473
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/51859473
tagged with: oop
upvote count: 3
has body: I stumbled across this behaviour, which suggests that you can use getattr to call methods on a class instance, as an alternative to the intuitively named operator.methodcaller: from operator import methodcaller class Foo(): def __init__(self, lst): self.lst = lst def summer(self): return sum(self.lst) my_obj = Foo(range(11)) res1 = methodcaller('summer')(my_obj) # 55 res2 = getattr(my_obj, 'summer')() # 55 assert res1 == res2 I'd like to understand, internally, why this works. Is it because all methods are also attributes? This seems to be the case because dir(Foo) or dir(my_obj) includes 'summer'. But I have never heard methods referred to as attributes of a class or class instance, e.g. this isn't mentioned in What is a “method” in Python? There is an explanation in the docs which mentions differentiation between "data attributes" and "non-data attributes" which I failed to understand. Update: Comments by @Amadan have clarified most of the above. The only remaining bit I do not understand is this excerpt from the docs: If you still don’t understand how methods work, a look at the implementation can perhaps clarify matters. When a non-data attribute of an instance is referenced, the instance’s class is searched. If the name denotes a valid class attribute that is a function object, a method object is created by packing (pointers to) the instance object and the function object just found together in an abstract object: this is the method object. So is a non-data attribute determined by checking whether it is callable, or is there some other way that's used to determine it's a function object? What does "packing pointers" to the instance object mean? What's an abstract object?
tagged with: methods
has comment: http://stackoverflow.com/comment/90670129
has comment: http://stackoverflow.com/comment/90670193
type: Question
answer count: 2
accepted answer: http://stackoverflow.com/a/51859641
linked to: http://stackoverflow.com/q/2307653
downvote count: 0
linked to: http://stackoverflow.com/q/3786881
has comment: http://stackoverflow.com/comment/90670040
has title: Accessing methods via getattr
tagged with: getattr
tagged with: attributes
favorite count: 0

http://stackoverflow.com/comment/90777520
type: QuestionComment
comment on: http://stackoverflow.com/q/51913744
score: 1
has text: The input also isn't valid, either as JSON or as a Python literal, for the same reason.
type: Comment

http://stackoverflow.com/comment/90555981
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51799737
has text: You appear to be calling `input()` more times than the number of lines being provided to your code.
score: 0

http://stackoverflow.com/comment/90578830
type: QuestionComment
comment on: http://stackoverflow.com/q/51811839
score: 0
type: Comment
has text: why don't you post your models code; because if they are related you should be using the ForeignKey or other related fields in your models, which makes finding related items quick!

http://stackoverflow.com/comment/90616977
type: Comment
comment on: http://stackoverflow.com/a/51812406
has text: Thanks abarnert— they didn’t ask me write the program. I just know how I WOULD theoretically do it, but it’s a lot of manual entry that can be avoided.
type: AnswerComment
score: 0

http://stackoverflow.com/q/51927792
has answer: http://stackoverflow.com/a/59143920
has title: how to write convert yuv array to rgb array?
type: UnansweredQuestion
tagged with: ndimage
upvote count: 1
tagged with: python
score: 1
type: Question
tagged with: numpy
has body: I have original data which is yuv420p frame data bytes. I want to convert it to rgb data using numpy and scipy. Here is my code: yuv = np.frombuffer(data, dtype='uint8') y = yuv[:1920*1080].reshape(1080, 1920) v = yuv[1920*1080::2].reshape(540, 960) u = yuv[1920*1080+1::2].reshape(540, 960) u = ndimage.zoom(u, 2, order=0) v = ndimage.zoom(v, 2, order=0) y = y.reshape((y.shape[0], y.shape[1], 1)) u = u.reshape((u.shape[0], u.shape[1], 1)) v = v.reshape((v.shape[0], v.shape[1], 1)) yuv = np.concatenate((y, u, v), axis=2) yuv[:, :, 0] = yuv[:, :, 0].clip(16, 235).astype(yuv.dtype) - 16 yuv[:, :, 1:] = yuv[:, :, 1:].clip(16, 240).astype(yuv.dtype) - 128 A = np.array([[1.164, 0.000, 1.793], [1.164, -0.213, -0.533], [1.164, 2.112, 0.000]]) rgb = np.dot(yuv, A.T).clip(0, 255).astype('uint8') I used PIL to open this output rgb array and the image wasn't the way I expected it to be. Is there anying wrong with my code?? Or is it wrong with my data?
downvote count: 0
answer count: 1
tagged with: yuv
favorite count: 0

http://stackoverflow.com/a/51800870
type: AcceptedAnswer
downvote count: 0
has body: To create a new password for each employee just include some code in the init() function that creates a random string and assigns it to an attribute of the class. When you need to access the password, just access the password attribute of that class instance ie. class employee(): def __init__(self, name): self.name = name self.pwd = ''.join([random.choice(alpha) for i in range(10)]) jane = employee('jane') print(jane.pwd)
type: Answer
score: 2
answers question: http://stackoverflow.com/q/51800808
upvote count: 2
accepted answer of: http://stackoverflow.com/q/51800808

http://stackoverflow.com/q/51810837
has comment: http://stackoverflow.com/comment/90576710
has answer: http://stackoverflow.com/a/51811631
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/90576675
favorite count: 0
tagged with: python-3.x
has title: Not counting correct characters from file
tagged with: python
accepted answer: http://stackoverflow.com/a/51811631
has comment: http://stackoverflow.com/comment/90577041
possible better answer: http://stackoverflow.com/a/51811132
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51811132
has body: I have the following code which runs as expected but has a few issues when counting the number of characters and the length of the longest line in characters. The follwoing is my code: def stats(file_name): n_chars = 0 n_words = 0 n_lines = 0 longest_line = 0 with open(file_name) as f: lines = f.readlines() n_lines = len(lines) longest_line = max([len(line) for line in lines]) words = [] line_words = [line.split() for line in lines] for line in line_words: for word in line: words.append(word) n_words = len(words) chars = [] line_chars = [list(word) for word in words] for line in line_chars: for char in line: chars.append(char) n_chars = len(chars) f.close() return n_chars, n_words, n_lines, longest_line Can you guys see anything that would make the code not count the correct number of characters. The longest line always appears as one more than the correct answer. The input is the following: BEAUTIFUL Soup, so rich and green, Waiting in a hot tureen! Who for such dainties would not stoop? Soup of the evening, beautiful Soup! Soup of the evening, beautiful Soup! Beau--ootiful Soo-oop! Beau--ootiful Soo-oop! Soo--oop of the e--e--evening, Beautiful, beautiful Soup! Beautiful Soup! Who cares for fish, Game, or any other dish? Who would not give all else for two Pennyworth only of Beautiful Soup? Pennyworth only of beautiful Soup? Beau--ootiful Soo-oop! Beau--ootiful Soo-oop! Soo--oop of the e--e--evening, Beautiful, beauti--FUL SOUP! The expected output is the following: Characters: 553 Words: 81 Lines: 21 Longest line: 38 The actual (failed) output: characters: 469 words: 81 lines: 21 longest: 39
upvote count: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/90576671

http://stackoverflow.com/q/51937193
linked to: http://stackoverflow.com/q/53727761
has body: I have a matplotlib Figure embedded in a QtAggFigureCanvas (PyQt4) with titles and axis labels (example shown below). I implemented a button to save the figure to a png file. The figure was created with: self.plkDpi = 100 self.plkFigure = Figure(dpi=self.plkDpi) ... self.plkAxes = self.plkFig.add_subplot(111) ... self.plkAxes.set_xlabel(...) self.plkAxes.set_ylabel(...) self.plkAxes.set_title(...) When I hit my save button, the following code is executed: self.plkFig.savefig('tmp.png', bbox_inches='tight', dpi=self.plkDpi) For some reason, the axes and plot title are omitted from the final plot. But they are not cropped - there is a bounding black box around the figure that is just blank (see below) No matter what I try, changing figsize, dpi, bounding box, etc. I cannot get the figure to save with the axis labels.
tagged with: pyqt4
tagged with: matplotlib
duplicate of: http://stackoverflow.com/q/53727761
tagged with: pyqt
downvote count: 0
favorite count: 0
has title: Matplotlib.savefig ignoring axes and plotting black border around image
type: UnansweredQuestion
tagged with: python
tagged with: savefig
upvote count: 6
answer count: 0
score: 6
has comment: http://stackoverflow.com/comment/90827198
type: Question

pytest
tags question: http://stackoverflow.com/q/51884531
tags question: http://stackoverflow.com/q/51879043
tag name: pytest
tags question: http://stackoverflow.com/q/51930556
tags question: http://stackoverflow.com/q/51890981
tags question: http://stackoverflow.com/q/51915625
tags question: http://stackoverflow.com/q/51863721
tags question: http://stackoverflow.com/q/51828644
tags question: http://stackoverflow.com/q/51950921
tags question: http://stackoverflow.com/q/51803167
tags question: http://stackoverflow.com/q/51900622
tags question: http://stackoverflow.com/q/51840787
tags question: http://stackoverflow.com/q/51885525
tags question: http://stackoverflow.com/q/51839452
tags question: http://stackoverflow.com/q/51883573
tags question: http://stackoverflow.com/q/51880272
tags question: http://stackoverflow.com/q/51912317
tags question: http://stackoverflow.com/q/51810471
type: Tag

http://stackoverflow.com/comment/90577608
comment on: http://stackoverflow.com/q/51811154
score: 0
has text: does it have to do something with the way I store the model? my custom dict?
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51845907
has body: You can use a list comprehension with zip and a custom function: def find_words(words, val): val_split = val.split() return any(x in val_split for x in words.split()) df['Match'] = [find_words(a, b) for a, b in zip(df['ColA'], df['ColB'])]
answers question: http://stackoverflow.com/q/51845815
score: 0
type: Answer

http://stackoverflow.com/comment/91080228
type: QuestionComment
has text: @TommasoBarbugli In this
comment on: http://stackoverflow.com/q/51939633
score: 0
type: Comment

http://stackoverflow.com/a/51915357
upvote count: 5
has comment: http://stackoverflow.com/comment/90792693
score: 4
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90788001
type: Answer
has comment: http://stackoverflow.com/comment/90792331
has comment: http://stackoverflow.com/comment/90791596
has body: Your file is losing its formatting because the original dump routine by default writes all leaf nodes in YAML flow-style, whereas your input is block style all the way. You are also losing the order of the keys, which is first because the JSON parser uses dict, and second because dump sorts the output. If you look at your intermediate JSON you already see that the key order is gone at that point. To preserve that, use the new API to load your YAML and have a special JSON encoder as a replacement for dump that can handle the subclasses of Mapping in which the YAML is loaded similar to this example from the standard Python doc. Assuming your YAML is stored in input.yaml: import sys import json from collections.abc import Mapping, Sequence from collections import OrderedDict import ruamel.yaml # if you instantiate a YAML instance as yaml, you have to explicitly import the error from ruamel.yaml.error import YAMLError yaml = ruamel.yaml.YAML() # this uses the new API # if you have standard indentation, no need to use the following yaml.indent(sequence=4, offset=2) input_file = 'input.yaml' intermediate_file = 'intermediate.json' output_file = 'output.yaml' class OrderlyJSONEncoder(json.JSONEncoder): def default(self, o): if isinstance(o, Mapping): return OrderedDict(o) elif isinstance(o, Sequence): return list(o) return json.JSONEncoder.default(self, o) def yaml_2_json(in_file, out_file): with open(in_file, 'r') as stream: try: datamap = yaml.load(stream) with open(out_file, 'w') as output: output.write(OrderlyJSONEncoder(indent=2).encode(datamap)) except YAMLError as exc: print(exc) return False return True yaml_2_json(input_file, intermediate_file) with open(intermediate_file) as fp: sys.stdout.write(fp.read()) which gives: { "inputs": { "webTierCpu": { "type": "integer", "minimum": 2, "default": 2, "maximum": 5, "title": "Web Server CPU Count", "description": "The number of CPUs for the Web nodes" } } } You see that your JSON has the appropriate key order, which we a…
has comment: http://stackoverflow.com/comment/90780728
accepted answer of: http://stackoverflow.com/q/51914505
downvote count: 1
answers question: http://stackoverflow.com/q/51914505

http://stackoverflow.com/comment/90591519
type: Comment
has text: At first glance, rename method: .rename('new_{}'.format(i)) causes problems under Python 2.7 (pandas 0.14.1), it returns following error: TypeError: 'str' object is not callable.
comment on: http://stackoverflow.com/a/51809970
score: 0
type: AnswerComment

http://stackoverflow.com/a/51921215
has comment: http://stackoverflow.com/comment/90792239
has body: Your dense layers only have 1 unit each. Except the first layer, rest of the layers are just passing the values along. Hence, all the outputs are same. As for your second question, the activation function on the last layer is sigmoid, which gives an output in the range of 0-1. You will have to convert them based on a threshold. For example, y_pred = [1 if x&gt;0.5 else 0 for x in y_pred], in which 0.5 is the threshold.
answers question: http://stackoverflow.com/q/51921075
has comment: http://stackoverflow.com/comment/90792261
has comment: http://stackoverflow.com/comment/90792436
has comment: http://stackoverflow.com/comment/90792347
score: 0
type: Answer

http://stackoverflow.com/q/51813766
accepted answer: http://stackoverflow.com/a/51814546
upvote count: 1
tagged with: python
has title: kivy layout: want to set the ratio of height of components to be 5:1
type: AnsweredQuestion
has body: i want to make a layout such that the height of TextInput block is 5 times to that of the button. I have tried several times but failed. The layout code follows: Builder.load_string(""" &lt;VQCIA_SUMMARY&gt;: BoxLayout: TextInput: pos:200,100 size:400,500 font_size: '25sp' multiline: True text: 'Summary:' BoxLayout: Button: pos:200,0 size:400,100 text: "Back Home" font_size: '25sp' """) while i've set the height of Textinput to be 500 and that of button to be 100, the result retains to be 1:1. what happens?
score: 1
type: Question
has answer: http://stackoverflow.com/a/51814546
tagged with: layout
answer count: 1
downvote count: 0
favorite count: 0
tagged with: kivy

http://stackoverflow.com/q/51898026
upvote count: 4
has title: How to make dict element value as list in Python
tagged with: python-2.7
possible better answer: http://stackoverflow.com/a/51898063
downvote count: 0
has answer: http://stackoverflow.com/a/51898211
has answer: http://stackoverflow.com/a/51898063
has answer: http://stackoverflow.com/a/51898049
score: 4
has comment: http://stackoverflow.com/comment/90747217
favorite count: 0
has body: I have a list. Let's say [3,4,2,3,4,2,1,4,5]. I need to create a dictionary from the indexes of the elements. Here in this case, I need to create a dict as follows: { '3':[0,3], '4':[1,4,7], '2':[2,5], '1':[6], '5':[8] } where the element values are the indexes of the keys in list provided. I've tried. But was able to change the values as integers only. But unable to make them as list. Is there any way to do this with just 1 for loop? The code I've tried: d=dict() ll=[1,2,1,2,1,2,3,4,5,5,4,2,4,6,5,6,78,3,2,4,5,7,8,9,4,4,2,2,34,5,6,3] for i,j in enumerate(ll): d[j].append(i) print(d)
tagged with: python
tagged with: dictionary
answer count: 4
linked to: http://stackoverflow.com/q/34884402
tagged with: python-3.x
tagged with: list
accepted answer: http://stackoverflow.com/a/51898049
has comment: http://stackoverflow.com/comment/90747223
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90747035
has comment: http://stackoverflow.com/comment/90747327
has answer: http://stackoverflow.com/a/51898111

http://stackoverflow.com/q/51864808
answer count: 0
type: Question
has comment: http://stackoverflow.com/comment/90713829
tagged with: hwnd
score: 0
tagged with: pyqt
has title: How to use PyQt method QWindow.fromWinId(id) on linux?
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90699466
tagged with: qt
has body: I'm trying to embed a foreign executable inside of a Python GUI (PyQt) just like this post describes: Run a foreign exe inside a Python GUI (PyQt) but the answer requires the win32gui module, which doesn't seem to be available on linux systems. The PyQt method (http://doc.qt.io/qt-5/qwindow.html): --> QWindow.fromWinId(id) does what I need, but I'm not sure how to get the handle id (hwnd) of the window of my executable (for the record, I'm trying to embed saods9 within my GUI) on linux (Ubuntu). Everything I'm finding looks to be geared toward a Windows operating system, not Linux. So I'm thinking that this Qt method can't be used on a Linux operating system? That would be my question: How do you get the handle id of a native window within Linux to be used in the Qt method QWindow.fromWinId(id)?
linked to: http://stackoverflow.com/q/41474647

http://stackoverflow.com/comment/90613129
score: 0
type: Comment
type: QuestionComment
has text: @barciewicz Perhaps you just forgot to load the app in INSTALLED_APPS? Or maybe the list of INSTALLED_APPS has some errors, like missing comma and similar.
comment on: http://stackoverflow.com/q/51829185

http://stackoverflow.com/comment/90682288
score: 0
comment on: http://stackoverflow.com/a/51849244
type: Comment
has text: The issue is that Algolia checks for `{{ jewelry_style }}` to put in the real values -- i.e. `reverse()` doesn't directly insert the real values. A workaround I was considering is to simply hardcode the urls, but `reverse()` exists for a reason.
type: AnswerComment

http://stackoverflow.com/comment/90568382
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51806306
has text: Hello, thanks for replying! After I run the code, I opened the file test.xlsx and the whole of column A seems to have disappeared. What went wrong
type: Comment

http://stackoverflow.com/q/51905808
tagged with: angular5
score: 1
has answer: http://stackoverflow.com/a/51905903
upvote count: 1
type: Question
has body: I am downloading file from Hadoop to Django backend and storing the file using the code below: import shutil import requests url = 'http://112.138.0.12:9870/webhdfs/v1/user/username/1.jpg?op=OPEN&amp;user.name=username' response = requests.get(url, stream=True) with open('img.png', 'wb') as out_file: shutil.copyfileobj(response.raw, out_file) del response I don't need to store the file in backend local system since I want to send this file to Angular 5 frontend where user will save this file in their local system. I'm getting the following error UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte. Can someone suggest me what would be the right way to do download large files in a short time? DJANGO: views.py: class DownloadFileView(GenericAPIView): serializer_class = UserNameSerializer def get(self, request): key = request.META.get('HTTP_AUTHORIZATION').split()[1] user_id = Token.objects.get(key=key).user_id user_name = User.objects.get(id=user_id).username response = download_files(user_name) return Response(response) def download_files(user_name): response = requests.get('http://112.138.0.12:9870/webhdfs/v1/user/' + user_name + '/1.jpg?op=OPEN&amp;user.name=username', stream=True) return response.raw ANGULAR: DownloadFile(){ this.userService.DownloadFiles().subscribe((data : any) =&gt; { const blob = new Blob([data], { type: 'application/octet-stream'}); fileUrl = this.sanitizer.bypassSecurityTrustResourceUrl(window.URL.createObjectURL(blob)); } } DownloadFiles() { this.token = localStorage.getItem('userToken') var reqHeader = new HttpHeaders({ 'Content-Type': 'application/octet-stream', 'Authorization': 'token ' + this.token }); console.log(reqHeader) return this.http.get(this.rootURL + 'download/', { headers: reqHeader}); }
accepted answer: http://stackoverflow.com/a/51905903
tagged with: angular
answer count: 1
downvote count: 0
tagged with: django-rest-framework
favorite count: 0
has title: How can I send data from HDFS through Django backend to Angular 5 frontend?
tagged with: django
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/90716171
type: Comment
comment on: http://stackoverflow.com/a/51880043
has text: Thanks Wen, I appreciate your help :) @SirGianmarcoD Glad I could help
type: AnswerComment
score: 0

http://stackoverflow.com/a/51895350
has body: You can use "Silence" threshold to identify need of sending request to google, with that approach you will avoid sending to match requests. For code sample see Python record audio on detected sound. Alternatively you can use open sourced speech recognition packages and end up with independent application, see The Ultimate Guide To Speech Recognition With Python article for that approach. However, if you still prefer using of the remote API, you can combine approaches above, and use SpeechRecognition to understand the Hey, Robot phrase and after that, switch application to use Google API for speech recognition for some small short period of time, of course the threshold check shall be used to avoid querying Google API when client don't continue to speak after saying Hey, Robot. Good Luck !
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 2
answers question: http://stackoverflow.com/q/51895192
score: 2
accepted answer of: http://stackoverflow.com/q/51895192

http://stackoverflow.com/q/51810649
has comment: http://stackoverflow.com/comment/90576678
has title: Python School Project issues, whitespace problems
has comment: http://stackoverflow.com/comment/90576452
has comment: http://stackoverflow.com/comment/90576267
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/90576684
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/90576552
score: 0
tagged with: whitespace
has comment: http://stackoverflow.com/comment/90576343
downvote count: 1
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90576270
has body: So I've been messing about with this code for almost two days now and I cannot get zybooks to accept it due to a single whitespace error. Here's the code: def main(): movie_collection = {"Munich":[2005, "Steven Spielberg"], "The Prestige": [2006, "Christopher Nolan"], "The Departed": [2006, "Martin Scorsese"], "Into the Wild": [2007, "Sean Penn"], "The Dark Knight": [2008, "Christopher Nolan"], "Mary and Max": [2009, "Adam Elliot"], "The King\'s Speech": [2010, "Tom Hooper"], "The Artist": [2011, "Michel Hazanavicius"], "The Help": [2011, "Tate Taylor"], "Argo": [2012, "Ben Affleck"], "12 Years a Slave": [2013, "Steve McQueen"], "Birdman": [2014, "Alejandro G. Inarritu"], "Spotlight": [2015, "Tom McCarthy"], "The BFG": [2016, "Steven Spielberg"]} prompt_year = True while prompt_year: user_year = int(input("Enter a year between 2005 and 2016:\n")) if user_year&lt;2005 or user_year&gt;2016: print("N/A") else: for key, value in movie_collection.items(): if value[0] == user_year: print(key + ", " + str(value[1]) ) prompt_year = False menu = "MENU" \ "\nSort by:" \ "\ny - Year" \ "\nd - Director" \ "\nt - Movie title" \ "\nq - Quit\n" prompt_user = True while prompt_user: prev_val = '' print("\n" + menu) user_choice = input("Choose an option:") if user_choice == "q": prompt_user = False elif user_choice == "y": for key, value in sorted(movie_collection.items(), key=lambda item: (item[1], item[0])): if(prev_val!=value[0]): print ("\n",value[0],end=':\n',sep='') prev_val = value[0] print("\t"+key + ", " + str(value[1])) elif user_choice == "d": for key, value in sorted(movie_collection.items(), key=lambda key_value: key_value[1][1]): if(prev_val!=value[1]): print("\n",value[1],end=':\n',sep='') prev_val = value[1] print("\t" + key + ", " + str(value[0])) elif user_choice == "t": for key, value in sorted(movie_collection.items(), key=lambda item: (item[0], item[1])): if(prev_val!=key): print("\n",key,end=':\n',sep='') prev_val = key print("\t" + str(value[1]) + ", " + str(v…

http://stackoverflow.com/comment/90571012
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51807560
has text: I do not see any phase in your `sin,cos` ... (like `atan2(im,re)`) for each Nyquist frequency ...
score: 0

http://stackoverflow.com/a/51936041
has body: The docs explain that if you don't want to use find_all, you can do this: for sibling in soup.a.next_siblings: print(repr(sibling))
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51935973

http://stackoverflow.com/comment/90705122
has text: This is so elegant and simple, thank you! 'defaultdict' is new for me.. seems useful
type: Comment
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/51876892

http://stackoverflow.com/a/58070132
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/51817865
has body: Double check that your lambda function basic settings does not have a timeout less than 5 seconds. I think it defaults to 3.
downvote count: 0
type: Answer

http://stackoverflow.com/q/51908642
has comment: http://stackoverflow.com/comment/90767417
upvote count: 1
downvote count: 1
tagged with: random-walk
has comment: http://stackoverflow.com/comment/90772874
favorite count: 0
has comment: http://stackoverflow.com/comment/90772572
type: UnansweredQuestion
has body: I have been given the mean and variance. I need to produce a deterministic random walk from the given variables. These are the expected properties for the time series data: Mean: 27.57020098 Median: 27.815 Std Dev.:5.106888439 Variance:26.08030952 Maximum: 43.92 Minimum: 0 Range: 43.92 I've tried the following, steps = np.random.normal(loc=0, scale=5.034, size=1000) #std =5.304 steps[0]=0 P = 27.50 + np.cumsum(steps) #mean =27.5 plt.plot(P) plt.title("Simulated Random Walk") plt.show() Which produces,
has comment: http://stackoverflow.com/comment/90769231
tagged with: python
has comment: http://stackoverflow.com/comment/90768277
has comment: http://stackoverflow.com/comment/90770557
has comment: http://stackoverflow.com/comment/90770672
has comment: http://stackoverflow.com/comment/90768962
has comment: http://stackoverflow.com/comment/90771960
has comment: http://stackoverflow.com/comment/90768330
has title: How to produce a time series data with deterministic random walk and drift, given the mean and variance for the series?
type: Question
tagged with: time-series
has answer: http://stackoverflow.com/a/51911534
has comment: http://stackoverflow.com/comment/90768683
has comment: http://stackoverflow.com/comment/90771646
has answer: http://stackoverflow.com/a/51910759
has comment: http://stackoverflow.com/comment/90772080
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/90767800

http://stackoverflow.com/q/51909663
has comment: http://stackoverflow.com/comment/90769425
accepted answer: http://stackoverflow.com/a/51909689
has comment: http://stackoverflow.com/comment/90769558
score: 0
tagged with: regex
possible better answer: http://stackoverflow.com/a/51909835
favorite count: 0
has answer: http://stackoverflow.com/a/51909835
upvote count: 2
downvote count: 2
has body: I want to check if this set of number appears in a string in an exact pattern or not: String I want to check: \4&amp;2096297&amp;0 My code a = "SCSI\DISK&amp;VEN_MICRON&amp;PROD_1100\4&amp;2096297&amp;0&amp;000200" print(bool(re.match(r"\4&amp;2096297&amp;0+", a))) It returns False instead of true. If I try same thing on print(bool(re.match(r"hello[0-9]+", 'hello1'))). I get true. Where am I going wrong?
has title: Python regex to check if a string has particular set of numbers
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51909689
type: Question
answer count: 2

http://stackoverflow.com/comment/126693390
has text: You can also create a figure with a given dpi via `fig = plt.figure(dpi=100)`
type: AnswerComment
type: Comment
score: 8
comment on: http://stackoverflow.com/a/67088442

http://stackoverflow.com/comment/90688148
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51868053
has text: Hope some of the clues will help! I'd just save some typing by naming `guiclasses` just `gui`, classes part looks redundant to me.
score: 0

http://stackoverflow.com/q/51881734
has comment: http://stackoverflow.com/comment/90715132
type: Question
linked to: http://stackoverflow.com/q/3389574
has body: I want to when I input a string, if words in string is contain in a list of words, delete words in the strings
score: -1
has answer: http://stackoverflow.com/a/51881780
answer count: 1
downvote count: 1
has title: check strings of a list
favorite count: 0
type: UnansweredQuestion
tagged with: python
duplicate of: http://stackoverflow.com/q/3389574
upvote count: 0
tagged with: list

http://stackoverflow.com/q/51936217
answer count: 2
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/51936342
tagged with: django
tagged with: python
has title: Arithmetic operations between Django fields belonging to the same class model. Is it possible?
type: AnsweredQuestion
score: 2
upvote count: 2
has body: I have the need to divide a class field (Value) in Django-admin model with a fixed value (coefficient) in the same class. The result of this operation should populate another field (Points) of the same class. Both values are of same type (integers). For example a user enter a value of '180', then he leaves coefficient to its default '10'. When it saves the new entry it should show up Points = 18 So for the moment I defined 'coefficient' field in Django models.py which defaults to 10. 'Value' field is editable as I said above. I thought to use F() to perform math operations between fields however I am not sure if this is the correct tool or there's something simpler. When I set up the following expression on my model I see alot complaints when I make db migrations. Points = Visits.objects.all().annotate(div=F('Value') / F('Coefficient')) Since I am new to Django I appreciate any help on this, maybe I am misunderstanding something obvious.
type: Question
accepted answer: http://stackoverflow.com/a/51936342
has answer: http://stackoverflow.com/a/51936288
possible better answer: http://stackoverflow.com/a/51936288

http://stackoverflow.com/a/51919524
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51912187
answers question: http://stackoverflow.com/q/51912187
type: Answer
has body: If I understood your question, what you want to do is to customize the shape and the labels of the nodes. The shape can be customized with the node_shape parameters in the draw_networkx_nodes function. To customize the labels you can use the label parameter in draw_networkx_labels function. Consider the following example: import networkx as nx import matplotlib.pyplot as plt graph = nx.grid_graph(dim=[2,2]) labels = {} labels[(0,0)] = "a1:1\nb1:1" labels[(0,1)] = "a2:2\nb2:2" labels[(1,0)] = "a3:3\nb3:3" labels[(1,1)] = "a4:4\nb4:4" pos = nx.spring_layout(graph) nx.draw_networkx_nodes(graph, pos=pos, node_shape="s", node_size=500) nx.draw_networkx_edges(graph, pos=pos) nx.draw_networkx_labels(graph, pos=pos,labels=labels, font_size=8) plt.axis('off') plt.show() which outputs:
downvote count: 0
score: 1
type: AcceptedAnswer

http://stackoverflow.com/q/51932858
has comment: http://stackoverflow.com/comment/90864889
has body: I'm looking for a way get a console output from Google Chrome into my python program. I have a script coded in JS that finishes in around 1 second, but my python implementation (exactly same logic, etc., the only difference is that it's in python and not JS) takes about 15 seconds to run. Therefore I'm looking for a way to get the printout in Chrome console to my python program. This is the current way I'm doing it: Python program uses pyautogui to click and does what it needs to do inside to trigger the function running in JS. JS completes the function in 1s and prints to console, something like: (22) [6, 4, 4, 6, 0, 1, 1 2, 4, 4, 6, 4, 2, 4, 4, 6, 0, 0, 2, 4, 4, 6, 0] I would like to find a way to get this output into python as I have another script that takes the output and does further calculations to it. I've thought of using Selenium but that'd introduce too much overhead (probably requiring 3s+ for waiting for chrome to open up).
score: 0
has comment: http://stackoverflow.com/comment/90816207
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90857805
has title: Exporting chrome output to python
answer count: 0
has comment: http://stackoverflow.com/comment/90816383
has comment: http://stackoverflow.com/comment/90816281
type: Question
has comment: http://stackoverflow.com/comment/90816338
tagged with: javascript

http://stackoverflow.com/comment/90756070
type: Comment
type: QuestionComment
has text: At least in the code you've provided above, you're missing indentation for the body of the function. What errors are you getting when you try to run this?
comment on: http://stackoverflow.com/q/51902453
score: 0

http://stackoverflow.com/a/51936300
has comment: http://stackoverflow.com/comment/90829327
accepted answer of: http://stackoverflow.com/q/51936227
answers question: http://stackoverflow.com/q/51936227
score: 4
upvote count: 4
type: AcceptedAnswer
downvote count: 0
has body: merge df on the pivotted df2: df.merge(df2.pivot('Name', 'Category', 'Score'), left_on='Name', right_index=True) Name Total Score Category A Category B 0 Charles 67 4 9 1 Peter 98 3 1 2 Mark 78 3 3
type: Answer

http://stackoverflow.com/comment/90580005
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51812312
has text: However, I just tried it again and it's loading up again and I didn't change a thing.

http://stackoverflow.com/q/51802109
type: Question
has comment: http://stackoverflow.com/comment/90569086
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/51802661
favorite count: 0
has title: Why is dataclasses.astuple returning a deepcopy of class attributes?
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/51802661
tagged with: python
tagged with: python-dataclasses
upvote count: 7
has body: In the code below the astuple function is carrying out a deep copy of a class attribute of the dataclass. Why is it not producing the same result as the function my_tuple? import copy import dataclasses @dataclasses.dataclass class Demo: a_number: int a_bool: bool classy: 'YOhY' def my_tuple(self): return self.a_number, self.a_bool, self.classy class YOhY: def __repr__(self): return (self.__class__.__qualname__ + f" id={id(self)}") why = YOhY() print(why) # YOhY id=4369078368 demo = Demo(1, True, why) print(demo) # Demo(a_number=1, a_bool=True, classy=YOhY id=4369078368) untrupled = demo.my_tuple() print(untrupled) # YOhY id=4369078368 trupled = dataclasses.astuple(demo) print(trupled) # YOhY id=4374460064 trupled2 = trupled print(trupled2) # YOhY id=4374460064 trupled3 = copy.copy(trupled) print(trupled3) # YOhY id=4374460064 trupled4 = copy.deepcopy(trupled) print(trupled4) # YOhY id=4374460176 Footnote As Anthony Sottile's excellent response makes clear this is the behavior coded into Python 3.7. Anyone expecting astuple to unpack the same way as collections.namedtuple will need to replace it with a method similar to Demo.my_tuple. The following code is less fragile than my_tuple because it will not need modification if the fields of the dataclass are changed. On the other hand it won't work if __slots__ are in use. Both versions of the code pose a threat whenever a __hash__ method is present in the class or its superclasses. See the Python 3.7 documentation for unsafe_hash in particular the two paragraphs beginning 'Here are the rules governing implicit creation of a __hash__() method'. def unsafe_astuple(self): return tuple([self.__dict__[field.name] for field in dataclasses.fields(self)])
type: AnsweredQuestion
score: 7
has comment: http://stackoverflow.com/comment/116452101

http://stackoverflow.com/comment/90646144
has text: it works perfectly with `df.filter(like = 'foo' and 'bar) `
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51841615

http://stackoverflow.com/a/51876736
score: 0
has body: You can use JSONEncoder import json class ComplexEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, set): return [el for el in obj] return json.JSONEncoder.default(self, obj) print(json.dumps({'Team Coffe': {'Garfield Foster': {('Scrum Master', 100)}}}, cls=ComplexEncoder))
answers question: http://stackoverflow.com/q/51876466
type: Answer

http://stackoverflow.com/a/51931901
type: AcceptedAnswer
has body: We should only need to read the file once, and then just save our modifications to the file when we need to. I didn't notice any logical errors that would lead to the behavior described, so it may be a permissions issue regarding what messages your bot is allowed to see. To facilitate debugging, I've simplified your code and added some prints to track what's going on. I also added a guard in on_message to stop the bot from responding to itself. import json import discord client = discord.Client() try: with open("users.json") as fp: users = json.load(fp) except Exception: users = {} def save_users(): with open("users.json", "w+") as fp: json.dump(users, fp, sort_keys=True, indent=4) def add_points(user: discord.User, points: int): id = user.id if id not in users: users[id] = {} users[id]["points"] = users[id].get("points", 0) + points print("{} now has {} points".format(user.name, users[id]["points"])) save_users() def get_points(user: discord.User): id = user.id if id in users: return users[id].get("points", 0) return 0 @client.event async def on_message(message): if message.author == client.user: return print("{} sent a message".format(message.author.name)) if message.content.lower().startswith("!points"): msg = "You have {} points!".format(get_points(message.author)) await client.send_message(message.channel, msg) add_points(message.author, 1) client.run("token")
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51922926
type: Answer
answers question: http://stackoverflow.com/q/51922926
upvote count: 1
has comment: http://stackoverflow.com/comment/90907281
score: 1

http://stackoverflow.com/a/51877660
accepted answer of: http://stackoverflow.com/q/51876526
answers question: http://stackoverflow.com/q/51876526
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: The problem is simple: you have never used the proxy, so it was never going to filter, in the next part I show you a more elegant solution: from PyQt5 import QtCore, QtGui, QtWidgets, QtSql def createConnection(): db = QtSql.QSqlDatabase.addDatabase("QSQLITE") db.setDatabaseName("imenik.db") if not db.open(): QtWidgets.QMessageBox.critical(None, "Cannot open database", "Unable to establish a database connection.\n" "This example needs SQLite support. Please read " "the Qt SQL driver documentation for information how " "to build it.\n\n" "Click Cancel to exit.", QtWidgets.QMessageBox.Cancel) return False return True class MySortFilterProxyModel(QtCore.QSortFilterProxyModel): def filterAcceptsRow(self, sourceRow, sourceParent): ixs = [self.sourceModel().index(sourceRow, i, sourceParent) for i in range(3)] return any(self.filterRegExp().indexIn(ix.data()) &gt;= 0 for ix in ixs) class Klasa(QtWidgets.QWidget): def __init__(self, parent=None): super(Klasa, self).__init__(parent) #podesavanje velicine okvira ujedno i velicine treevjuva jer se tri vjuv razvlaci do ivica Boksa self.proxyModel = MySortFilterProxyModel(self) #dodjeljuje tri vjuv prethodno definisanom okviru lay = QtWidgets.QVBoxLayout(self) #kreira liniju za unos teksta za pretragu self.lineEdit = QtWidgets.QLineEdit() self.lineEdit.textChanged.connect(self.textFilterChanged) self.tableView = QtWidgets.QTableView() #dodjeljuje okviru self.tableView lay.addWidget(self.lineEdit) lay.addWidget(self.tableView) #pravi promjenjivu za pretragu baze podataka self.model = QtSql.QSqlQueryModel() self.model.setQuery("SELECT Lokacija,Kancelarija,Prezime,Ime,Telefon,Lokal,Fax,Oblast FROM telImenik") #upisuje rezultate pretrage baze u self.tableView self.proxyModel.setSourceModel(self.model) self.tableView.setModel(self.proxyModel) #odredjuje sirinu kolona u self.tableView-u prva kolona je 0-nulta,id nema potrebe dodavati jer ga sam odredjuje for i, width in enumerate([150, 65, 100, 80, 90, 40, 80, 340]): self.tableView.se…
has comment: http://stackoverflow.com/comment/90707413
score: 3
upvote count: 3

http://stackoverflow.com/q/51948860
tagged with: python
possible better answer: http://stackoverflow.com/a/51948911
type: AnsweredQuestion
tagged with: python-3.x
upvote count: 2
has title: checking whether variable is not None and is a dict containing specific key
downvote count: 1
has comment: http://stackoverflow.com/comment/90847700
type: Question
score: 1
has body: I currently find myself to write a few times code like if myDict is not None: if 'thisKey' in myDict: variable = myDict['thisKey'] where I first check whether myDict is defined and then access the key, if it is defined. Is there a shortcut or more pythonic way for these kinds of tests? I'm mostly looking to combine the two if clauses; I'm aware I didn't (yet) make use of the get methode, e.g. like variable = myDict.get('thisKey'), so it can be simplified / shortened to if myDict is not None: variable = myDict.get('thisKey') Yet, can it be made more concise / easier? Querying 'None' for a key raises an error. We can safely assume for this purpose here that the variable WILL be a dict, if it is defined at all.
has answer: http://stackoverflow.com/a/51948911
has comment: http://stackoverflow.com/comment/90847822
has comment: http://stackoverflow.com/comment/90847496
has answer: http://stackoverflow.com/a/51949127
accepted answer: http://stackoverflow.com/a/51949127
has answer: http://stackoverflow.com/a/51948913
favorite count: 0
answer count: 3
has comment: http://stackoverflow.com/comment/90847599

http://stackoverflow.com/comment/90646796
type: Comment
score: 2
comment on: http://stackoverflow.com/q/51846590
type: QuestionComment
has text: @ScalaBoy I would say you are getting downvoted mostly because you just asked for "how to do this?", rather than showing what you did and asking why some part of it does not work. Also, it would be easier to understand the question if it was further simplified. You already know ho to fetch the sub-dict, so the question would be much simpler if you asked e.g. "how to find the key in dict corresponding to the minimum value"

http://stackoverflow.com/a/51903334
has body: kstest ends up calling lognorm.cdf which takes the following arguments according to doc: cdf(x, s, loc=0, scale=1) So you need to pass: my_args = [my_s, 0, my_scale] ks = stats.kstest(samples, 'lognorm', args=my_args)[0] which outputs: ks: 0.007790356168134116
type: Answer
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/51902996
answers question: http://stackoverflow.com/q/51902996
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/90774371
type: QuestionComment
comment on: http://stackoverflow.com/q/51912131
has text: @heemayl - The following thread https://stackoverflow.com/questions/35529520/how-to-convert-a-wav-file-bytes-like-object does that . But, I am don't know how to convert that back to a json file
score: 0
type: Comment

http://stackoverflow.com/q/51826710
upvote count: 0
score: -2
answer count: 1
tagged with: sql-server
has comment: http://stackoverflow.com/comment/90607761
has answer: http://stackoverflow.com/a/51827449
has title: Microsoft SQL Server Won't Connect Through Python
tagged with: python
favorite count: 0
type: UnansweredQuestion
downvote count: 2
has body: I've looked through some other things but haven't been able to find a working solution. Here is my code: conn = db.connect("Driver={SQL Server}; Server='Server';Database='Database_DW'; uid='uid'; pwd = 'pwd'") I run this code and I get the following error: DatabaseError: ('08001', '[08001] [Microsoft][ODBC SQL Server Driver][DBNETLIB]SQL Server does not exist or access denied.') I'm really at a loss here. I can log in fine through the SQL Server Client with the exact some credentials.
has comment: http://stackoverflow.com/comment/90607848
has comment: http://stackoverflow.com/comment/90608877
tagged with: odbc
type: Question

http://stackoverflow.com/a/51852081
has body: You should always use your system package manager when possible. There is a safe way to get newer versions of Python on CentOS/RHEL, as proper RPM packages. It is called the IUS project, and we offer multiple versions of Python. After setting up the repo, you can get Python 3.5 by running the command yum install python35u. You will then have the command python3.5 available, as well as the pyvenv-3.5 command for creating virtual environments.
upvote count: 0
score: -3
type: Answer
downvote count: 3
answers question: http://stackoverflow.com/q/51852055

http://stackoverflow.com/comment/90557831
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51800698
type: QuestionComment
has text: @roganjosh, of course: https://www.youtube.com/watch?v=EgnyWxKFwjs&list=PLillGF-RfqbbbPz6GSEM9hLQObuQjNoj_&index=5&t=0s

http://stackoverflow.com/a/51831540
downvote count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/132751650
has body: To allow only one instance to run, go to "Run" in the top bar, then "Edit Configurations...". Finally, check "Single instance only" at the right side. This will run only one instance and restart every time you run.
answers question: http://stackoverflow.com/q/51831152
type: Answer
score: 2

http://stackoverflow.com/q/51942580
type: Question
has body: I am trying to do some transformation and I’m stuck. Here goes the problem description. Below is the pipe delimited file. I have masked data! AccountancyNumber|AccountancyNumberExtra|Amount|ApprovedBy|BranchCurrency|BranchGuid|BranchId|BranchName|CalculatedCurrency|CalculatedCurrencyAmount|CalculatedCurrencyVatAmount|ControllerBy|Country|Currency|CustomFieldEnabled|CustomFieldGuid|CustomFieldName|CustomFieldRequired|CustomFieldValue|Date|DateApproved|DateControlled|Email|EnterpriseNumber|ExpenseAccountGuid|ExpenseAccountName|ExpenseAccountStatus|ExpenseGuid|ExpenseReason|ExpenseStatus|ExternalId|GroupGuid|GroupId|GroupName|IBAN|Image|IsInvoice|MatchStatus|Merchant|MerchantEnterpriseNumber|Note|OwnerShip|PaymentMethod|PaymentMethodGuid|PaymentMethodName|ProjectGuid|ProjectId|ProjectName|Reimbursable|TravellerId|UserGUID|VatAmount|VatPercentage|XpdReference|VatCode|FileName|CreateTstamp 61470003||30.00|null|EUR|168fcea9-17d4-45a1-8b6f-bfb249cdbea6|BEL|BEL|USD,INR,EUR|35.20,2420.11,30.00|null,null,null|null|BE|EUR|true|0d4b767b-0988-47e8-9144-05e607169284|careertitle|false|FE|2018-07-24T00:00:00|null|null|abc_def@xyz.com||c32f03c6-31df-4fd8-8cc2-1c5f3a580aad|Meals - In Office|true|781d10d2-2f3b-43bc-866e-a653fefacbbe||Approved|70926|40ac7117-c7e2-42ea-b34f-96330c9380b6|BEL-FSP-Users|BEL-FSP-Users|||false|None|in office meal #1|||Personal|Cash|1ee44666-f4c7-44b3-acd3-8ecd7127480a|Cash|2cb4ccb7-634d-4386-af43-b4572ec72098|00AA06|00AA06|true||6c5a835f-5152-46db-923a-3ebd08c7dad3|null|null|XPD012245802||1820711.xml|2018-08-07 05:42:10.46 In this file, we have got CalculatedCurrency field where we have multiple values delimited by a comma. The file also has field CalculatedCurrencyAmount which too has multiple values delimited by a comma. But I need to pick up only that currency value from CalculatedCurrency field which belongs to BranchCurrency (another field in the file) and of course corresponding CalculatedCurrencyAmount for that Currency. Required output : - Accountanc…
tagged with: snaplogic
score: 0
has answer: http://stackoverflow.com/a/51943072
has comment: http://stackoverflow.com/comment/90836558
tagged with: snaplogic-script-snap
has comment: http://stackoverflow.com/comment/92747266
answer count: 4
has answer: http://stackoverflow.com/a/51942808
has comment: http://stackoverflow.com/comment/90835098
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90834688
has title: File parsing using Unix Shell Scripting
has answer: http://stackoverflow.com/a/51942936
has answer: http://stackoverflow.com/a/52918912

http://stackoverflow.com/q/51954444
favorite count: 0
tagged with: pyinstaller
has title: pyinstaller: Determine hidden imports for socket.io and aiohttp in Windows Service
tagged with: python
type: UnansweredQuestion
upvote count: 1
score: 1
has answer: http://stackoverflow.com/a/54564079
type: Question
answer count: 1
downvote count: 0
has body: I've been using python to build a Windows service that runs socket.io and aiohttp. The program runs perfectly in the interpreter, but once I use pyinstaller to package it into an exe file, the code fails with the exception: Traceback (most recent call last): File "autocoreserver.py", line 24, in __init__ File "site-packages\socketio\asyncio_server.py", line 67, in __init__ File "site-packages\socketio\server.py", line 89, in __init__ File "site-packages\engineio\server.py", line 123, in __init__ ValueError: Invalid async_mode specified In my program, the exception being thrown is when it tries to create the AsyncServer (File "autocoreserver.py", line 24, in init). try: self.sio = socketio.AsyncServer() except: rootLogger.exception("AsyncServer init") I've researched online and know this is a common problem typically solved using the hiddenimports argument in the spec file. However, after adding all the recommendations I could find online, there is no change to the error. To try and find the modules missing, I built the exe with the "-v" option. However, there are dozens of modules listed, almost none of them having to do with socket.io or aiohttp. For instance, there are many Qt modules missing, but this is a service with no user interface and I'm not using Qt. Tying to pinpoint an actual list of modules I needed, I instead added this code to my program, which makes a list of all modules in use and writes them out to a file. f = open('c:\\modulereport.log','w') f.write('hiddenimports=[\n') mods = [m.__name__ for m in sys.modules.values() if m] for m in mods: f.write( ' \'{0}\',\n'.format(m) ) f.write("],") f.close() This gave me a list of what was supposed to be every module in use by the program, but it was missing several. When I added back all the modules I knew to be missing, I was back to the same error. I'm new to pyinstaller and python, and I'm guessing there is a better way pinpoint missing modules. Can anyone please tell me the best way to find the modules …

http://stackoverflow.com/a/51867129
score: 2
answers question: http://stackoverflow.com/q/51867074
has comment: http://stackoverflow.com/comment/90686486
has comment: http://stackoverflow.com/comment/90686351
downvote count: 0
has body: Assuming that your list is always monotonically increasing, and you just want to know the values: for i in range(1, len(my_list)): if my_list[i] - my_list[i - 1] != 1: print(my_list[i - 1], my_list[i]) You can use a list comprehension to speed things up and retain a copy of the values: pairs = [(my_list[i - 1], my_list[i]) for i in range(1, len(my_list)) if my_list[i] - my_list[i - 1] != 1] If you want the pair with the max difference, apply max to the result: max(pairs, key=lambda x: x[1] - x[0]) Numpy is generally a more elegant solution for dealing with numerical values. In particular, the diff function is useful for comparing neighbors: my_array = np.array(my_list) mask = np.diff(my_array) Most numpy functions will convert numeric lists into arrays on input, and diff is no exception. The mask computed here is a boolean array that tells you the locations of edges. It is much easier to apply the mask if your data is in array format, so I did the transformation explicitly: left = my_array[:-1][mask] right = my_array[1:][mask] Again, if you want the max, use np.argmax: index = np.argmax(right - left) print((left[index], right[index]))
upvote count: 2
type: Answer

http://stackoverflow.com/comment/138041798
has text: Good solution but this would overwrite any `Date` that does not exist in your `d`.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/66233791
type: Comment

http://stackoverflow.com/a/51832947
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51831091
accepted answer of: http://stackoverflow.com/q/51831091
type: Answer
downvote count: 0
score: 1
has body: You need to return the Request object in your function. Since you are generating multiple ones, you can use yield, like this: yield scrapy.Request(tag, callback=self.parse) "In the callback function, you parse the response (web page) and return either dicts with extracted data, Item objects, Request objects, or an iterable of these objects." See scrapy documentation

http://stackoverflow.com/a/51809088
has body: a=7 for a1 in range(0,a): print('-',end ='') print("Welcome",end ='') for a2 in range(0,a): print('-',end ='',flush=True)
type: Answer
answers question: http://stackoverflow.com/q/51808770
score: 0

http://stackoverflow.com/comment/90702174
type: Comment
has text: Ah right :) Anyway, the second, better approach described in the last paragraph should work transparently and fast with full-text search.
type: AnswerComment
comment on: http://stackoverflow.com/a/51875370
score: 0

http://stackoverflow.com/comment/90749788
type: AnswerComment
score: 0
has text: in your post you say you want "indexes of the descending bits", but here you say you just want "indexes of this array where it *starts* descending". which is it?
type: Comment
comment on: http://stackoverflow.com/a/51899185

http://stackoverflow.com/comment/90642048
type: Comment
has text: @DanielPryden but how would this work? Like, I have a main.py that calls wrapper.py. I could change the `Popen` call to use the `.exe` instead of `.py`, but in my case, I have parameters being passed... can I pass parameters to a `.exe` with `Popen`?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51843974

http://stackoverflow.com/a/51927202
has body: Something like this: import pandas as pd import datetime current_date = datetime.datetime.now() filename = str(current_date.day)+str(current_date.month)+str(current_date.year) df.to_csv(str(filename + '.csv'))
answers question: http://stackoverflow.com/q/51926983
downvote count: 0
has comment: http://stackoverflow.com/comment/90804116
type: Answer
score: 3
upvote count: 3

http://stackoverflow.com/comment/90649435
has text: @KunC selenium has advantages and disadvantages. If the javascript is simple enough, it is better to write python code to simulate it since it will probably perform better than launching a full-fledged web browser and executing the javascript. For that bitmex page in your quesiton I wouldn't use selenium because the data is already easily available in javascript/json format and python can read json easily
comment on: http://stackoverflow.com/a/51847687
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/90655503
type: Comment
has text: I was about to say the same as @RafaelC
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51851165

http://stackoverflow.com/comment/90761120
has text: Your pip packages might have been installed to ~/.local
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51853175
score: 0

http://stackoverflow.com/a/51940939
upvote count: 7
has body: SparkSession provides a single point of entry to interact with underlying Spark functionality and allows programming Spark with DataFrame and Dataset APIs. Most importantly, it curbs the number of concepts and constructs a developer has to juggle while interacting with Spark. SparkSession, without explicitly creating SparkConf, SparkContext or SQLContext, encapsulates them within itself. SparkSession has merged SQLContext and HiveContext in one object from Spark 2.0+. When building a session object, for example: val spark = SparkSession .builder() .appName("SparkSessionExample").config( "spark.sql.warehouse.dir", warehouseLocation).enableHiveSupport().getOrCreate() .enableHiveSupport() provides HiveContext functions. so you will be able to access Hive tables since spark session is initialized with HiveSupport. So, there is no difference between "sqlContext.sql" and "spark.sql", but it is advised to use "spark.sql", since spark is single point of entry for all the Spark API's.
downvote count: 0
score: 7
answers question: http://stackoverflow.com/q/51940744
type: Answer

http://stackoverflow.com/comment/90640463
comment on: http://stackoverflow.com/a/51843257
has text: Thank you for this code. It all works except when i add the Yes for the takeaway it makes the total 0 and doesnt add it together. Ill try figure this out myself. Its 10pm my time and i have school tomorrow so i need to go to sleep. bye and thanks very much.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/51846759
type: UnansweredQuestion
tagged with: python
score: 1
has answer: http://stackoverflow.com/a/51847272
upvote count: 1
type: Question
has title: No module named email_preprocess error when using Atom
has body: I am currently experiencing some difficulties with using Atom to run my python code, that otherwise works when launched through the command prompt. For those unfamiliar with Udacity's Introduction to Machine Learning, the "email preprocess" module is located in "...\naive_bayes\tools" directory. Code: import sys from time import time sys.path.append("../tools/") from email_preprocess import preprocess Whenever i run the nb_author_id.py file through the command prompt with the following command: python2 nb_author_id.py in the D:\Misiek\Pulpit\python\ud120-projects-master\naive_bayes directory, it works fine. But, if want to run the nb_author_id.py file through Atom (using atom-runner) I get the error message: Traceback (most recent call last): File "D:\Misiek\Pulpit\python\ud120-projects-master\naive_bayes\nb_author_id.py", line 17, in &lt;module&gt; from email_preprocess import preprocess ImportError: No module named email_preprocess Any ideas why it works through the command prompt, but not through Atom?
tagged with: atom-editor
answer count: 2
has answer: http://stackoverflow.com/a/51847775
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/109759442
type: Comment
score: 0
has text: The flask backend will be open-sourced soon.
type: AnswerComment
comment on: http://stackoverflow.com/a/62058562

http://stackoverflow.com/a/51913366
has body: Wow, that took some time. If you look at the back propagation code, look closely at these lines: dLdb_c = cp.empty([channels_hidden, M, N]) dLdb_i = cp.empty([channels_hidden, M, N]) dLdb_f = cp.empty([channels_hidden, M, N]) dLdb_o = cp.empty([channels_hidden, M, N]) However, notice how the code proceeds to use the += operator on these empty arrays. Simply change the arrays to cp.zeros, and the code gives consistent loss.
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/51814651
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51814651
upvote count: 1
type: Answer

http://stackoverflow.com/a/51831869
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51831687
has body: First, create series containing your month, year, as well as the last digit of your TradeDate column. m = df.RIC.str[2].map(month_codes_to_int) y = df.RIC.str[3].astype(int) s = df.TradeDate.dt.year.mod(10) Then calculate your offset: offset = np.where(y==s, 0, 10+y-s) Finally, create your new column: pd.to_datetime((df.TradeDate.dt.year + offset).astype(str) + m, format='%Y%m') Output: 0 1990-03-01 1 1990-03-01 2 1990-03-01 3 1990-03-01 4 1990-03-01 dtype: datetime64[ns]
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51831687

http://stackoverflow.com/q/51857870
linked to: http://stackoverflow.com/q/36641557
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/51858017
upvote count: 1
downvote count: 1
has body: i have written python function that imports several packages to detect and interps barcode in a pic. and know i want to use this function in C#. and my question is how can i compile .py to .dll
has title: How can I compile .py to .dll
has answer: http://stackoverflow.com/a/51858038
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90668045
type: Question
tagged with: dll

http://stackoverflow.com/comment/90784052
comment on: http://stackoverflow.com/q/51916845
has text: You should never use a hash as a primary key. Hashes are not unique. What is wrong with autoincremented index? That is the best choice for practically every primary key.
type: QuestionComment
type: Comment
score: 1

http://stackoverflow.com/q/51810242
has title: Not able to import libraries in anaconda
score: 0
linked to: http://stackoverflow.com/q/47557385
type: Question
has comment: http://stackoverflow.com/comment/90602312
has body: I have installed the the library num2words by pip install num2words from the command prompt. But when I try to use num2words in anaconda jupyter notebook. It says: ModuleNotFoundError: No module named 'num2words'". I don't know how to get the external installed library in the jupyter notebook.
has comment: http://stackoverflow.com/comment/90575456
tagged with: jupyter-notebook
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90578257
tagged with: python
tagged with: anaconda

http://stackoverflow.com/comment/90607200
has text: This also doesn't run. p throws an error.
comment on: http://stackoverflow.com/q/51826422
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51816709
type: Question
has comment: http://stackoverflow.com/comment/90589484
tagged with: image-segmentation
has comment: http://stackoverflow.com/comment/90590546
downvote count: 0
favorite count: 0
has body: I have a receipt image and I am trying to use Pytesseract in order to draw bounding boxes around paragraphs of text of the receipt . The problem is that Tesseract is identifying the regions for bounding boxes as per letter not per block. I am also aware of the different page segmentation modes of Tesseract , though I have tried them all and nothing worked. Is there something that I am missing ? This is what I have tried so far : import cv2 import pytesseract import matplotlib.pyplot as plt filename = 'optimized_scanned_images/test1.jpg' img = cv2.imread(filename) h, w, _ = img.shape boxes = pytesseract.image_to_boxes(img, config='-psm 5 load_system_dawg = False load_freq_dawg=False') for b in boxes.splitlines(): b = b.split(' ') img = cv2.rectangle(img, (int(b[1]), h - int(b[2])), (int(b[3]), h - int(b[4])), (0, 255, 0), 1) fig, ax = plt.subplots(figsize=(10, 6)) ax.imshow(img) ax.set_axis_off() plt.tight_layout() plt.show()
has comment: http://stackoverflow.com/comment/90591456
tagged with: python
has title: Paragraph bounding boxes using pytesseract
tagged with: python-tesseract
answer count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: tesseract
score: 1

http://stackoverflow.com/a/51808347
downvote count: 0
score: 28
upvote count: 28
type: Answer
answers question: http://stackoverflow.com/q/51804692
accepted answer of: http://stackoverflow.com/q/51804692
has body: It's a simple container. From the docs of nn.Module Base class for all neural network modules. Your models should also subclass this class. Modules can also contain other Modules, allowing to nest them in a tree structure. You can assign the submodules as regular attributes. Submodules assigned in this way will be registered, and will have their parameters converted too when you call .cuda(), etc. From the tutorial: All network components should inherit from nn.Module and override the forward() method. That is about it, as far as the boilerplate is concerned. Inheriting from nn.Module provides functionality to your component. For example, it makes it keep track of its trainable parameters, you can swap it between CPU and GPU with the .to(device) method, where device can be a CPU device torch.device("cpu") or CUDA device torch.device("cuda:0"). A module is a container from which layers, model subparts (e.g. BasicBlock in resnet in torchvision) and models should inherit. Why should they? Because the inheritance from nn.Module allows you to call methods like to("cuda:0"), .eval(), .parameters() or register hooks easily. why not just call the 'module' a model, and call the layers 'layers'? I suppose maybe it's just semantics and splitting hairs, but still... That's an API design choice and I find having only a Module class instead of two separate Model and Layers to be cleaner and to allow more freedom (it's easier to send just a part of the model to GPU, to get parameters only for some layers...).
type: AcceptedAnswer

http://stackoverflow.com/q/51909070
has comment: http://stackoverflow.com/comment/90768281
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51909190
downvote count: 3
linked to: http://stackoverflow.com/q/15112125
type: Question
has comment: http://stackoverflow.com/comment/90768328
has comment: http://stackoverflow.com/comment/90768390
upvote count: 0
duplicate of: http://stackoverflow.com/q/15112125
score: -3
answer count: 2
has answer: http://stackoverflow.com/a/51909208
has body: Whenever I run this function, the output is You found emerald! Why? With a tiny 3/999 chance of finding emerald, I should usually find something else. It cannot be pure chance. I have reviewed the code and I can't find the issue. block=randint(1,1000) if block==456 or 742 or 327: print('You found emerald!') elif block==275 or 467 or 234 or 978 or 10 or 3 or 256 or 475 or 103 or 701 or 124 or 9: print('You found diamond!') elif block==range(900,930): print('You found iron!') elif block==range(800,870): print('You found coal!') else: print('You found stone...')
favorite count: 0
tagged with: python-3.x
has title: Why is the rarest output always displayed? (Python 3)

http://stackoverflow.com/comment/90723542
has text: Thank you a lot Andras!. @hygorxaraujo Yes, the BD has been created, but about the postgres server How can I make sure of that?
score: 0
comment on: http://stackoverflow.com/q/51885802
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90790476
score: 2
comment on: http://stackoverflow.com/q/51920278
type: Comment
type: QuestionComment
has text: If there's a common set of stuff functions do - then you move that into another function and put the common stuff in that that the functions need that they share... etc...

confluent-platform
tags question: http://stackoverflow.com/q/51817529
tag name: confluent-platform
type: Tag

http://stackoverflow.com/q/51893239
has comment: http://stackoverflow.com/comment/90737663
downvote count: 0
has answer: http://stackoverflow.com/a/51893344
favorite count: 0
has title: How to place a the label/description of a django char field above the textbox
has comment: http://stackoverflow.com/comment/90738000
has answer: http://stackoverflow.com/a/51894920
tagged with: http://stackoverflow.com/tag/html
tagged with: django
tagged with: python
tagged with: css
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/90737477
upvote count: 3
type: Question
possible better answer: http://stackoverflow.com/a/51893555
accepted answer: http://stackoverflow.com/a/51894920
has body: I have a django form displayed like this in a template: &lt;div&gt; &lt;form method="post"&gt;{% csrf_token %} {{ form.as_p }} &lt;input type="submit" value="Submit"&gt; &lt;/form&gt; &lt;/div&gt; Which contains a field like this: class CreateArticle(forms.Form): organization = forms.ModelChoiceField(queryset=models.Organization.objects.all()) introduction_text = forms.CharField(widget=forms.Textarea) As you can see in the screenshot below the field description (Introduction text) ends up to the left of the textfield, I would like it to be placed above. Is there a way to do this in the field definition in the form, without changing the projects css files and/or making the template file more complicated?
has answer: http://stackoverflow.com/a/51893555
answer count: 3

http://stackoverflow.com/comment/90883668
comment on: http://stackoverflow.com/a/51825324
score: 1
type: AnswerComment
has text: Despite the number of upvotes this answer has received, I'm not awarding this answer **anything** due to the technical inaccuracies present, even after they were pointed out days before.
type: Comment

http://stackoverflow.com/q/51904877
upvote count: 1
has comment: http://stackoverflow.com/comment/90764048
tagged with: tensorflow
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90906672
has title: multiple CNN inputs with generator.flow_from_directory ??
downvote count: 0
answer count: 0
tagged with: keras
favorite count: 0
type: Question
tagged with: deep-learning
tagged with: convolution
has body: I'm trying to train a two streams CNN architecture, but unfortunately, I got an unexpected result which is almost the same as one of the two streams (I have already trained every one separately). My idea is to merge two streams CNN from two different images folder (two sources) and combining them to get more accurate results. here is my code, please tell me what I'm doing wrong : ## Arch def fusionNet(nb_classes, inputs=(3, 224, 224)): input_img = Input(shape=inputs, name='RGB_input') conv1 = Conv2D(96, (7, 7), activation="relu", name="conv1", strides=(2, 2), padding="same", ## .... ## .... ## .... firstCNN_output = BatchNormalization(name='firstCNN_output_BN')(last_dropout) ## print(firstCNN_output._keras_shape) # I got here (None, 512, 13, 13) input_img2 = Input(shape=inputs, name='depth_input') conv12 = Conv2D(96, (7, 7), activation="relu", name="conv12", strides=(2, 2), padding="same", kernel_initializer="glorot_uniform")(input_img2) #.... #.... #... SecondCNN_output = BatchNormalization(name='SecondCNN_output_BN2')(last_dropout2) print(SecondCNN_output._keras_shape) # I got here (None, 512, 13, 13) # merge2CNN = merge([firstCNN_output, SecondCNN_output], mode='concat', concat_axis=1) ### got here (None, 1024, 13, 13) conv10 = Conv2D( nb_classes, (1, 1),init='glorot_uniform', border_mode='valid', name='conv10')(merge2CNN) avgpool10 = AveragePooling2D((13, 13), name='avgpool10')(conv10) flatten = Flatten(name='flatten')(avgpool10) softmax = Activation("softmax", name='softmax')(flatten) return Model(inputs=[input_img,input_img2], output=softmax) ## Training sn = fusionNet(nb_classes=24) sgd = SGD(lr=0.001, decay=0.0002, momentum=0.9, nesterov=True) sn.compile( optimizer=sgd, loss='categorical_crossentropy', metrics=['accuracy') train_datagen = ImageDataGenerator( rescale=1./255, zoom_range=0.01, rotation_range=2., featurewise_center=True, featurewise_std_normalization=True,) test_datagen = ImageDataGenerator(rescale=1./255) def generate_generator_multiple(generat…
tagged with: python
score: 1

http://stackoverflow.com/comment/90568612
score: 0
comment on: http://stackoverflow.com/q/51806549
has text: You define `costoforder` as a tuple, with two items: `"$"` and the rest of the string. Note that the comma makes the tuple, even without parentheses.
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/90688647
type: QuestionComment
has text: According to Bad Request exception, it means that the request is not correct. I assume that `term = params.get('term') `the value of `term` is null or empty. You could set `term` with hard code value and test it again.
score: 0
comment on: http://stackoverflow.com/q/51829184
type: Comment

http://stackoverflow.com/comment/90777050
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51912125
has text: @Code I don't think that can be done. The code should work even with large number of negative descriptors.
type: Comment

http://stackoverflow.com/q/51916533
score: 0
tagged with: twisted
type: UnansweredQuestion
tagged with: python
answer count: 0
has title: Python LoopingCall freezes
has comment: http://stackoverflow.com/comment/90783560
type: Question
has body: Im trying to create a game server for learning purposes and I've ran into a problem where my updating function that runs every (0.05) seconds, isn't calling any functions that pass variables. def update(self): print("Match update: %s" % (str(self))) if (self.pendingShutdown): cancelShutdown = True for player in self.players: if player.protocol == None: cancelShutdown = False if (time() &gt; self.shutdownTime): print("Time elapsed, shutting down match") #self.quit() else: self.sendlocations() def sendlocations(self): print("ran new send locations") for player in self.players: print(player.posX) for r in range(0, len(self.players)): matchPlayer = self.players[r] #equation for distance between players x = (player.posX - matchPlayer.posX)**2 y = (player.posY - matchPlayer.posY)**2 distance = math.sqrt(x+y) #ending equation if (distance &lt;= 1000): if (matchPlayer.protocol): #finding the player index(SENDING PLAYER) index = 0 for i in matchPlayer.match.players: if(i.playerId == player.playerId): matchPlayer.protocol.sendPlayerMoved(index, player.posX, player.posY, player.posZ) index = index + 1 print("Player moved %s " % (index)) def sendPlayerMoved(self, playerIndex, posX, posY, posZ): message = MessageWriter() message.writeByte(MESSAGE_PLAYER_MOVED) message.writeInt(playerIndex) message.writeInt(posX) message.writeInt(posY) message.writeInt(posZ) #self.log("Sent PLAYER_MOVED %d %d" % (playerIndex, posX)) self.sendMessage(message) I'm able to called "self.sendlocations()" and when I do not have the lines passed if(distance&lt;=) the function properly prints out the line "ran new send locations" but with this line added it does not anymore. After adding the lines the "update" function also freezes up. Im clueless as to why this is happening.
has comment: http://stackoverflow.com/comment/90783529

http://stackoverflow.com/a/51939810
answers question: http://stackoverflow.com/q/51939708
type: AcceptedAnswer
has body: The problem is the way your organized the or in your if statement: if x-1 or x/2 in losing_numbers: This means: if (x-1) or (x/2 in losing_numbers): Since for all integer values of x except for 1, x-1 is truthy, this will always evaluate to true and x will be appended to winning_numbers. You should rewrite it as: if x-1 in losing_numbers or x/2 in losing_numbers: or: if any(k in theQuestion for k in (x-1, x/2))
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/51939708

http://stackoverflow.com/q/51900679
has comment: http://stackoverflow.com/comment/90753742
tagged with: python
tagged with: python-3.x
answer count: 0
has title: update particular option in section in ".ini" file using ConfigParser
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90753653
type: Question
tagged with: configparser
has comment: http://stackoverflow.com/comment/90769694
has body: I am trying to update a particular option in my config.ini file using ConfigParser. This is my config.ini file: [remote-server-details] MACHINE_NAME = MACHINE_USERNAME = MACHINE_PASSWORD = Welcome!23 And this is my step file in Python: @step('I change the following config options in section "{section_name}" in the {config_file_type} config file') def set_dag_config_section_values(context, section_name, config_file_type): parameters = ast.literal_eval(context.text) context.conf[config_file_type].read(context.dag_config_file[config_file_type]) context.conf[config_file_type].remove_section(section_name) context.conf[config_file_type].add_section(section_name) for option, value in parameters.iteritems(): context.conf[config_file_type].set(section_name, option, value) with open(context.dag_config_file[config_file_type], 'w+') as configfile: context.conf[config_file_type].write(configfile) context.conf[config_file_type].read(context.dag_config_file[config_file_type]) readin_parameters = dict(context.conf[config_file_type].items(section_name)) sort_dict(parameters) sort_dict(readin_parameters) assert readin_parameters == parameters, 'Value could not be set. %s does not match config contents %s' % (parameters, readin_parameters) I need to update only MACHINE_NAME and MACHINE_USERNAME, as MACHINE_PASSWORD is already contained in the config file, but I'm getting this error: INFO - Subtask: remote_server_details['MACHINE_PASSWORD'], [2018-08-17 17:40:04,723] {{base_task_runner.py:98}} INFO - Subtask: KeyError: 'MACHINE_PASSWORD'
score: 0

http://stackoverflow.com/comment/90810447
type: Comment
comment on: http://stackoverflow.com/q/51929096
type: QuestionComment
has text: @ganeshs this is a really basic and largely documented feature of Django's ORM. if you don't take some time doing the official tutorial and browsing the doc so you get the big picture and know where to look for for more in-depth details, you will spend even more time asking basic questions (which will be systematically downvoted) and you can be sure your code will be of very low quality since you won't have learned all of the useful features and how/when to use them.
score: 0

http://stackoverflow.com/comment/90603856
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51824799
type: AnswerComment
has text: @NoorAliJafri it works for both, provided what version of python he has installed. If he has installed both all he has to do is use pip3 instead of pip.

http://stackoverflow.com/a/51890196
type: Answer
score: 1
upvote count: 1
downvote count: 0
has body: Given your code (regardless your description); you can shorten your code by doing the math, e.g.: def bill_generator(units): firstSum = min(units, 150) * 2.5 if units &lt;= 300: secondSum = firstSum + units * 3.60 - 540.0 elif units &lt;= 450: firstSum += 540 secondSum = firstSum + units * 4.75 - 1425.0 elif units &lt;= 600: firstSum = 540 + units * 4.75 - 1425.0 secondSum = firstSum + units * 5.0 - 2250.0 else: firstSum = 150.0 * 11.1 + units * 4.75 - 1425.0 secondSum = firstSum + units * 6.0 - 3600.0 print("FirstSum:-{}".format(firstSum)) if units &gt; 150: print(secondSum) if __name__ == '__main__': inp_units = int(input("Enter the units: ")) while inp_units &lt; 1: print("invalid input, units must be greater than zero") inp_units = int(input("Enter the units")) Tested the border cases: def bill_generator(units): firstSum = min(units, 150) * 2.5 if units &lt;= 300: secondSum = firstSum + units * 3.60 - 540.0 elif units &lt;= 450: firstSum += 540.0 secondSum = firstSum + units * 4.75 - 1425.0 elif units &lt;= 600: firstSum += 540.0 + units * 4.75 - 1425.0 secondSum = firstSum + units * 5.0 - 2250.0 else: firstSum = 1665.0 + units * 4.75 - 1425.0 secondSum = firstSum + units * 6.0 - 3600.0 print("FirstSum:-{}".format(firstSum)) if units &gt; 150: print(secondSum) if __name__ == '__main__': for ii in [1, 150, 151, 300, 301, 450, 451, 600, 601, 1200]: print('Testing for unit input "{}"'.format(ii)) bill_generator(ii) ''' Testing for unit input "1" FirstSum:-2.5 Testing for unit input "150" FirstSum:-375.0 Testing for unit input "151" FirstSum:-375.0 378.6 Testing for unit input "300" FirstSum:-375.0 915.0 Testing for unit input "301" FirstSum:-915.0 919.75 Testing for unit input "450" FirstSum:-915.0 1627.5 Testing for unit input "451" FirstSum:-1632.25 1637.25 Testing for unit input "600" FirstSum:-2340.0 3090.0 Testing for unit input "601" FirstSum:-3094.75 3100.75 Testing for unit input "1200" FirstSum:-5940.0 9540.0 '''
answers question: http://stackoverflow.com/q/51889218

http://stackoverflow.com/comment/90717627
score: 1
type: AnswerComment
has text: The key part of the docs for this is here: https://python-pptx.readthedocs.io/en/latest/user/autoshapes.html#adjusting-an-autoshape
type: Comment
comment on: http://stackoverflow.com/a/51882843

http://stackoverflow.com/comment/90801628
has text: impressive, but it's not working in Ipython (perfectly good in standard ide)
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51925959
type: AnswerComment

http://stackoverflow.com/q/51810944
accepted answer: http://stackoverflow.com/a/51811192
upvote count: 1
tagged with: python
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/90576934
has comment: http://stackoverflow.com/comment/90577108
has comment: http://stackoverflow.com/comment/90577330
type: Question
tagged with: numpy
tagged with: casting
has comment: http://stackoverflow.com/comment/90580737
has comment: http://stackoverflow.com/comment/90576942
has title: Convert all the values of the text to int while reading in python
has comment: http://stackoverflow.com/comment/90578346
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/90576882
has answer: http://stackoverflow.com/a/51811192
has comment: http://stackoverflow.com/comment/90577417
favorite count: 0
has comment: http://stackoverflow.com/comment/90577123
has body: When I'm trying to convert values to int I'm getting this error in python. invalid literal for int() with base 10: '0,72367,72565,73005,73087,73113,73129,73313,73661,74049,74222,74350,74403,74501\n' instead of this i want something like 0,72367,72565,73005,73087,73113,73129,73313,73661,74049,74222,74350,74403,74501 stored in numpy array of int My code is f = open('points.txt') # reading the lines of the file line = f.readline() while line: points = np.array([], dtype=int) #print("voxel", voxel_label, " : ", line) points = np.append(points, line) line = f.readline() voxel_label += 1 When I convert points to int it gives me error. I want to read lines from text file and put that into numpy array points as int values. points array(['0,1883,1965,2176,2236,2273,2502,2528,2542,2963,2979,3288,3519\n'], dtype='&lt;U62') I want to convert this 'points' numpy array to int type. I'm not able to understand why there is \n at the end. How can i convert 'points' numpy to int.

http://stackoverflow.com/comment/90640335
has text: I'll try it.. Thanks
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51840739
score: 0

http://stackoverflow.com/comment/90727045
type: QuestionComment
comment on: http://stackoverflow.com/q/51887864
score: 0
has text: Can you give an example of a medium case? You mean like RoBot?
type: Comment

http://stackoverflow.com/comment/90758546
has text: It might be easier to follow if you used `xor` (`from operator import xor`) instead of `!=`. They're the same, but `xor` is a lot easier to parse if you're not familiar with the not-equal-to trick.
type: AnswerComment
type: Comment
score: 0
comment on: http://stackoverflow.com/a/51903720

http://stackoverflow.com/q/51915345
tagged with: sqlite
answer count: 1
has title: Python int too large to put in SQLite
favorite count: 0
has comment: http://stackoverflow.com/comment/90790934
has comment: http://stackoverflow.com/comment/90781027
tagged with: python
type: AnsweredQuestion
score: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/90940294
has comment: http://stackoverflow.com/comment/90780721
has answer: http://stackoverflow.com/a/63831535
accepted answer: http://stackoverflow.com/a/63831535
tagged with: sqlalchemy
type: Question
has body: I am getting the error OverflowError: Python int too large to convert to SQLite INTEGER from the following code block. The file is about 25gb, so it must be read in parts. length = 6128765 # Works on partitions of the dataset def work(path, fields, partitions, rows, fn): import numpy as np div = rows // partitions parts = np.arange(0, rows, div) for i in parts: df = pd.read_csv(path, sep='|', names=fields, skiprows=i, nrows=div, encoding='latin-1') fn(df) del df def to_sql(df): # We can use the pandas.to_sql command to put the data in our SQLlite database: df.to_sql("main", sqlite_engine, if_exists='append', index=False) work("path_to.txt', column_names, 105, length, to_sql) I am using SQLite3 through a sqlalchemy object to interact with it. All columns in the database are TEXT types because I was trying to alleviate this problem. Anyone have any guidance?
upvote count: 3
has comment: http://stackoverflow.com/comment/90792629

http://stackoverflow.com/comment/90605748
has text: @thor I am using Python 3.6. What about you? Did you import numpy like I did?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51825644
type: AnswerComment

http://stackoverflow.com/q/51805104
linked to: http://stackoverflow.com/q/606191
answer count: 1
linked to: http://stackoverflow.com/q/4981977
has answer: http://stackoverflow.com/a/51805129
accepted answer: http://stackoverflow.com/a/51805129
tagged with: python
has title: urllib request.urlopen(url).read() with SQLAlchemy is storing a hex string instead of HTML
has body: I'm trying to store some HTML in postgres using urllib and SQLAlchemy but it seems like something is getting garbled in the process when the html is being inserted\retrieved using: SQLAlchemy 1.2, Python 3.6, postgres 10, urllib class ParksTxState(Base): __tablename__ = 'parks_tx_state' id = Column(Integer, primary_key=True) park_name = Column(Text) url = Column(Text) html = Column(Text) engine = create_engine("postgresql://&lt;user&gt;:&lt;pass&gt;@localhost/&lt;db&gt;", echo=False) Session = sessionmaker(bind=engine) session = Session() url = 'https://tpwd.texas.gov/state-parks/abilene' html = request.urlopen(url).read() print(html) # b'&lt;!DOCTYPE html&gt;\n&lt;html xmlns="http://www.w3.org/1999/xhtml"&gt;\n&lt;head&gt;\n... # so far so good... newpark = ParksTxState() newpark.html = html print(newpark.html) # b'&lt;!DOCTYPE html&gt;\n&lt;html xmlns="http://www.w3.org/1999/xhtml"&gt;\n&lt;head&gt;\n... # so we're still good here before committing.... session.add(newpark) session.commit() print(newpark.html) # \x3c21444f43545950452068746d6c3e0a3... # and here is where the garbage comes in. For some reason the HTML is being stored as a long string of characters.. \x3c21444f43545950452068746d6c3e0a3c68746d6c20786d6c6e733d22687474703a2f2f7777772e7... I've even set echo=True and saw that the insert statement was correct. What am I doing wrong?
type: AnsweredQuestion
tagged with: sqlalchemy
tagged with: urllib
type: Question
duplicate of: http://stackoverflow.com/q/4981977
tagged with: postgresql
score: 0

http://stackoverflow.com/comment/90621305
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51823150
has text: Thank You sir, but is there any way to get the subratings? 1. Work/Life Balance 2. Culture & Values 3. Career Opportunities 4. Comp & Benifit 5. Senior Management

http://stackoverflow.com/q/51851217
answer count: 1
favorite count: 0
tagged with: python-3.x
upvote count: 5
linked to: http://stackoverflow.com/q/42263946
has title: How to create a table with clickable hyperlink to a local file in pandas & Jupyter Notebook
tagged with: python
tagged with: jupyter-notebook
type: AnsweredQuestion
downvote count: 0
type: Question
has body: I learned from this post that I can link to a website in a Jupyter Notebook: How to create a table with clickable hyperlink in pandas &amp; Jupyter Notebook So, I tried to adapt the code to create a dataframe with links to local files. However, when I click on the hyperlinks from the code below, nothing happens. How do I fix the code below for the hyperlinks to work? import os import pandas as pd data = [dict(name='file1', filepath='C:/Users/username/Documents/file1.docx'), dict(name='file2', filepath='C:/Users/username/Documents/file2.docx')] df = pd.DataFrame(data) def make_clickable(url): name= os.path.basename(url) return '&lt;a href="file:///{}"&gt;{}&lt;/a&gt;'.format(url,name) df.style.format({'filepath': make_clickable})
has answer: http://stackoverflow.com/a/51855581
score: 5
accepted answer: http://stackoverflow.com/a/51855581
tagged with: pandas

http://stackoverflow.com/comment/90640177
comment on: http://stackoverflow.com/q/51843474
type: QuestionComment
type: Comment
has text: Can you show us an example of your dataframe? A few rows should suffice, including rows with multiple authors.
score: 1

http://stackoverflow.com/comment/90557959
comment on: http://stackoverflow.com/q/51800772
score: 0
has text: Also, why do use define a method `str` instead of overriding `__str__` or `__repr__`?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90854518
type: QuestionComment
comment on: http://stackoverflow.com/q/51951904
score: 0
type: Comment
has text: I know that you won't debug. I do not get an error but I get an output that is quite different from how it looks when i see other examples of the `append` or `concat` functions. You can see my example above. I do not get why I get that 3 upper rows and the first column, like i explain in my example. Do you have any idea?

currency
tag name: currency
tags question: http://stackoverflow.com/q/51891791
type: Tag

http://stackoverflow.com/a/51864695
has comment: http://stackoverflow.com/comment/90686918
upvote count: 1
answers question: http://stackoverflow.com/q/51861790
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/90719315
type: Answer
has body: I can actually answer a part of your question: But the example in the doc only demonstrate a scenario where the normalization factors are pre-defined and fixed, like lambda x: (x-3.2)/1.5. you can simply use .min and .max class members of a Pandas dataframe to obtain the minimum and maximum of the desired array. Let's say you want to normalize some columns in diabetes dataset, you can do the following: diabetes = pd.read_csv('pima-indians-diabetes.csv', names=new_cols) # Normalize the columns cols_to_norm = ['Number_pregnant', 'Glucose_concentration', 'Blood_pressure', 'Triceps', 'Insulin', 'BMI', 'Pedigree'] diabetes[cols_to_norm] = diabetes[cols_to_norm].apply(lambda x: (x - x.min()) / (x.max() - x.min()))

http://stackoverflow.com/comment/90838208
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51937382
has text: I have perception that at end of base64 result there is "=" sign but in python result it doesnot exist.
score: 0

http://stackoverflow.com/comment/139549176
type: AnswerComment
has text: @wholevinski OK I got it working by declaring the resource above `main`, but fetching the client as `dynamodb.meta.client` within `main`. Any idea on the nuance here? Huge thanks in advance for any and all assistance!
type: Comment
comment on: http://stackoverflow.com/a/51857915
score: 0

http://stackoverflow.com/a/51933627
has body: You should be able to use a loop to iterate through [1, n]. For example: import math n = 4 r = 4 for i in range(1, n + 1): theta = math.radians((360 / n) * i) x = round(r * math.cos(theta), 2) y = round(r * math.sin(theta), 2)
type: Answer
answers question: http://stackoverflow.com/q/51933517
score: 0

http://stackoverflow.com/comment/90711024
has text: I'm not sure I follow exactly.
comment on: http://stackoverflow.com/q/51879403
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/90742756
type: QuestionComment
type: Comment
has text: Consider doing some research on creating your own TensorFlow variables for that purpose.
comment on: http://stackoverflow.com/q/51893694
score: 0

http://stackoverflow.com/a/51913844
score: 0
has body: It's your odd syntax that is failing you. The interpreter interprets this as if (answer=='n') and 'N': Note that non-empty strings are evaluated as True regardless of contents, so this is equivalent to if (answer=='n') To fix this, replace this line with if answer=='n' and answer=='N': Note that this line should never evaluate to be true. If you want it to work, you should try if answer=='n' or answer=='N':
type: Answer
accepted answer of: http://stackoverflow.com/q/51913822
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51913822

http://stackoverflow.com/comment/90767186
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51908256
has text: You are mixing other problems together. Why are you using docker-compose for building? i think it's a bad practice. simply build with `docker build -f Dockerfile -t flask-example .` and use the `flask-example` within `docker-compose.yml` with `image` tag instead of `build` tag.
type: AnswerComment

http://stackoverflow.com/comment/90771254
has text: Possible duplicate of: https://stackoverflow.com/questions/16180428/can-selenium-webdriver-open-browser-windows-silently-in-background
comment on: http://stackoverflow.com/q/51910530
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51826614
possible better answer: http://stackoverflow.com/a/51826782
type: Question
has comment: http://stackoverflow.com/comment/90607623
tagged with: python
has comment: http://stackoverflow.com/comment/90607755
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/51826814
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/90607699
accepted answer: http://stackoverflow.com/a/51826814
has answer: http://stackoverflow.com/a/51826782
type: AnsweredQuestion
has body: I don't know what to do here. I'm writing a scraper where I need to scrape some data and the code is getting kinda long because of the copy+paste I'm making in my 'for loop', problem is I feel the code is a lot slower when I make a function I call with arguments instead of calling the same lines. Can someone help me explain if it's just me or is there some reasoning behind it? Also, what is most preferable in general? Option 1 (without function, but copy+pasting the code): for i in soup.find("div", class_="bets betCols2"): """ 0.5 """ if i.find('span', 'bet_type').text == 'Total Over 0.5': odd = i.find('span', 'koeff').text mylist.append(odd) if i.find('span', 'bet_type').text == 'Total Under 0.5': odd = i.find('span', 'koeff').text mylist.append(odd) Option 2 (with function): def find_info(soup, betinfo, mylist): for i in soup.find("div", class_="bets betCols2"): if i.find('span', 'bet_type').text == betinfo: odd = i.find('span', 'koeff').text mylist.append(odd) return mylist find_info(soup, 'Total Over 0.5', mylist) find_info(soup, 'Total Under 0.5', mylist)
has title: Python: Copy+paste the same lines or call a function instead?
favorite count: 0

http://stackoverflow.com/comment/90578132
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51811510
has text: I get: RuntimeError: dataset.__iter__() is only supported when eager execution is enabled.
score: 0

http://stackoverflow.com/a/51903062
has comment: http://stackoverflow.com/comment/90767226
score: 9
has comment: http://stackoverflow.com/comment/131717950
has comment: http://stackoverflow.com/comment/90767149
type: AcceptedAnswer
has body: This assumes that the entries are in such an order that a parent node was always introduced as a child of another node beforehand (root excluded). With that in mind, we can then iterate over the lines, split them (I used split, regex would work too) and create the new nodes. For how to get a reference to the parent by name, I came up with two solutions: First, find the parent by name using anytrees find_by_attr from anytree import Node, RenderTree, find_by_attr with open('input.txt', 'r') as f: lines = f.readlines()[1:] root = Node(lines[0].split(" ")[0]) for line in lines: line = line.split(" ") Node("".join(line[1:]).strip(), parent=find_by_attr(root, line[0])) for pre, _, node in RenderTree(root): print("%s%s" % (pre, node.name)) Second, just cache them in a dict while we create them: from anytree import Node, RenderTree, find_by_attr with open('input.txt', 'r') as f: lines = f.readlines()[1:] root = Node(lines[0].split(" ")[0]) nodes = {} nodes[root.name] = root for line in lines: line = line.split(" ") name = "".join(line[1:]).strip() nodes[name] = Node(name, parent=nodes[line[0]]) for pre, _, node in RenderTree(root): print("%s%s" % (pre, node.name)) input.txt Parent Child A A1 A A2 A2 A21 Output: A ├── A1 └── A2 └── A21
has comment: http://stackoverflow.com/comment/115529109
upvote count: 9
has comment: http://stackoverflow.com/comment/90767196
accepted answer of: http://stackoverflow.com/q/51902250
type: Answer
answers question: http://stackoverflow.com/q/51902250
downvote count: 0

http://stackoverflow.com/a/51823765
has body: From what the error states, discord.ClientUser.friends does not seem to have "unpackable" data. For example, "abcdefg" would iterate as "a", "b", "c", etc. [1, 2, 3, 4] would iterate as 1, 2, 3, 4 The value stored in discord.ClientUser.friends appears to be an object and cannot be iterated. Try doing print discord.ClientUser.friends to confirm this.
score: -1
downvote count: 1
type: Answer
upvote count: 0
answers question: http://stackoverflow.com/q/51823648

http://stackoverflow.com/a/51930008
type: Answer
has body: Seems that image_to_text doesn't accept white list parameter, please use SetVariable for that, see the solution of the setting white list over the tesseroct base api below: api = tesserocr.PyTessBaseAPI() api.ReadConfigFile('digits') # Consider having string with the white list chars in the config_file, for instance: "0123456789" while_list = open(config_file_path).read() api.SetVariable("tessedit_char_whitelist", while_list)
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/51929916
upvote count: 2
accepted answer of: http://stackoverflow.com/q/51929916
type: AcceptedAnswer

http://stackoverflow.com/q/51883766
has answer: http://stackoverflow.com/a/51884090
has answer: http://stackoverflow.com/a/51884731
has answer: http://stackoverflow.com/a/51884032
answer count: 3
tagged with: pandas
downvote count: 0
favorite count: 0
has title: Apply try/except with df.loc in pandas
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90721084
has comment: http://stackoverflow.com/comment/90719506
score: 1
has body: I want to apply a filter in python with try/except. How can I do it? I mean something like 'try to filter de csv, if you can't because 'ON' or 'OFF' are not in rows df_ok = df' import pandas as pd df = pd.read_csv('a.csv') try: df_ok = df.loc[df['Precio'] != 'ON'] df_ok = df_ok.loc[df_ok['Precio'] != 'OFF'] csv: Espacio País Precio 0 4083496 * ON 1 4083554 * OFF 2 4083368 * ON 3 4083194 * OFF 4 4083194 * ON 5 4083194 * OFF 6 4083194 * ON 7 4083194 * ON 8 MARTIN * 0.5 9 MARTIN * 89 10 MARTIN * 198
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/90719744

http://stackoverflow.com/q/51884186
answer count: 1
accepted answer: http://stackoverflow.com/a/51884290
has comment: http://stackoverflow.com/comment/90720440
favorite count: 0
has title: error with tkinter python always recive error but no correct conditions
tagged with: tkinter
tagged with: python
has comment: http://stackoverflow.com/comment/90720169
has body: why does this code fail im trying to summon a window when the settings button is pressed that allows users to change the forground and background colours i get the radio buttons but recive an error every time i submit the colours even though their value is not 0 how do i fix this and why does it happen? from tkinter import * import os from tkinter import messagebox as mgb import tkinter.ttk as tk2 global colour_1, colour_2 colour_1 = "pink" colour_2 = "purple" #background def sayclick() : btn.configure(text = "saying") text = txt.get() os.system("""PowerShell -Command "Add-Type –AssemblyName System.Speech; (New-Object System.Speech.Synthesis.SpeechSynthesizer).Speak('""" + text + """ ');" """) btn.configure(text = "say") def colourmenu(): window = Tk() window.title("colour menu") selected = IntVar() selected2 = IntVar() rad11 = tk2.Radiobutton(window,text='blue ', value=1, variable=selected)# set 1 rad21 = tk2.Radiobutton(window,text='green', value=2, variable=selected)# rad31 = tk2.Radiobutton(window,text='red ', value=3, variable=selected)# rad41 = tk2.Radiobutton(window,text='black', value=4, variable=selected)# rad12 = tk2.Radiobutton(window,text='blue ', value=1, variable=selected2) rad22 = tk2.Radiobutton(window,text='green', value=2, variable=selected2) rad32 = tk2.Radiobutton(window,text='red ', value=3, variable=selected2) rad42 = tk2.Radiobutton(window,text='black', value=4, variable=selected2) def submitbut(): if selected.get() == 0 : mgb.showinfo("error", "error: invalid colour choise") elif selected2.get() == 0 : mgb.showinfo("error", "error: invalid colour choise") else : for n in range(1,3): if n == 1 : val = selected.get() rep = 1 else : val = selected2.get() rep = 2 if val == 1: colour = "blue" elif val == 2 : colour = "green" elif val == 3 : colour = "red" else : colour = "black" if rep == 1 : bg = colour else : fg = colour submit = Button(window, text="submit", command=submitbut) txt1 = Label(window, text = "background") txt1.grid(column = 0, row …
downvote count: 1
type: AnsweredQuestion
score: -1
has answer: http://stackoverflow.com/a/51884290
type: Question
has comment: http://stackoverflow.com/comment/90720003
has comment: http://stackoverflow.com/comment/90729265
tagged with: radio-button
upvote count: 0
tagged with: user-interface
has comment: http://stackoverflow.com/comment/90719978
tagged with: windows

http://stackoverflow.com/comment/90845712
type: QuestionComment
type: Comment
has text: What have you tried so far?
score: 4
comment on: http://stackoverflow.com/q/51948103

http://stackoverflow.com/comment/90644416
score: 1
comment on: http://stackoverflow.com/q/51845017
type: Comment
type: QuestionComment
has text: @gyx-hh After running it again with the `quotechar='"', quoting=0` specified, I get the same issue. I think the leading parentheses is the issue. See the edit for clarification on what exactly went wrong in the header name parsing.

http://stackoverflow.com/comment/115427690
type: Comment
comment on: http://stackoverflow.com/a/51855686
has text: Ok, @MartinPrikryl.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/90855051
type: Comment
has text: yes I have an init. The issue is that hamiltonian is used also by command as well
comment on: http://stackoverflow.com/q/51951332
score: 0
type: QuestionComment

http://stackoverflow.com/q/51865429
tagged with: beautifulsoup
has body: While parsing the Bitmex site, I noticed that the results of parsing using bs4 were slightly different from what I actually saw in my web browser. When I used the Devtools and continually refresh, I realized it took some time that the window we were looking at was opened, and the BS4 immediately took html and seemed to differ between the two results. The site URL is 'https://www.bitmex.com/app/trade/XBTUSD' You can see the difference just checking the tag ... . When I use bs4, they give me the result BitMEX | Bitcoin Mercantile Exchange But when I see them in Chrome, they give me the result ▼ 6486.0 (XBTUSD) 거래 - BitMEX like this. How can I bring to Python the same code that I saw at the Chorme? Of course, Using selenium, I can bring them to Python....but I wonder there is no way to bring them using bs4. My programming knowledge and its ability is not good, Question can seem to be odd. If you can't understand my question I'd appreciate it if you could ask me again. Thank you for reading it.
downvote count: 2
tagged with: python
type: AnsweredQuestion
tagged with: selenium
has answer: http://stackoverflow.com/a/51865527
has comment: http://stackoverflow.com/comment/90683121
linked to: http://stackoverflow.com/q/43668384
type: Question
has comment: http://stackoverflow.com/comment/90683088
has comment: http://stackoverflow.com/comment/90683293
upvote count: 0
score: -2
has title: The result is different between what I see in Web browser
answer count: 1
accepted answer: http://stackoverflow.com/a/51865527
favorite count: 0
tagged with: parsing

http://stackoverflow.com/q/51853581
tagged with: python
linked to: http://stackoverflow.com/q/14267900
has answer: http://stackoverflow.com/a/51856759
has answer: http://stackoverflow.com/a/51915007
tagged with: tkinter
upvote count: 1
possible better answer: http://stackoverflow.com/a/77834313
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/77834313
accepted answer: http://stackoverflow.com/a/51915007
has comment: http://stackoverflow.com/comment/90661781
type: Question
has comment: http://stackoverflow.com/comment/90662059
tagged with: user-interface
downvote count: 0
has title: How to get filepaths properly from tkinterDND2 event object
score: 1
favorite count: 0
has body: I'm trying to implement "drop files here" feature in a simple GUI application using tkinter in python It uses the TkinterDnD2 which is ended up by seeing this stackoverflow answer Upon dropping the file event.data returns file name surrounded with curly braces Example: {d:/test/sample1.pdf} However when multiple files are dropped in the target each path is surrounded by curly braces Example: {D:/test/sample1.pdf} {D:/test/sample2.pdf} How to properly parse the file paths from this string?
answer count: 3

http://stackoverflow.com/q/51883762
accepted answer: http://stackoverflow.com/a/51884373
tagged with: scikit-learn
favorite count: 0
has comment: http://stackoverflow.com/comment/90733163
has answer: http://stackoverflow.com/a/51884373
tagged with: python
has comment: http://stackoverflow.com/comment/90721357
upvote count: 5
type: AnsweredQuestion
has title: Group/Cluster K-Fold CV with Sklearn
tagged with: cross-validation
type: Question
has comment: http://stackoverflow.com/comment/90723500
score: 5
has body: I need to do a K-fold CV on some models, but I need to ensure the validation (test) data set is clustered together by a group and t number of years. GroupKFold is close, but it still splits up the validation set (see second fold). For example, if I have a set of data with years from 2000-2008 and I want to K-fold into 3 groups. The appropriate sets would be: Validation: 2000-2002, Train: 2003-2008; V:2003-2005, T:2000-2002 &amp; 2006-2008; and V: 2006-2008, T: 2000-2005). Is there a way to group and cluster the data using K-Fold CV where the validation set is clustered by t years? from sklearn.model_selection import GroupKFold X = [0.1, 0.2, 2.2, 2.4, 2.3, 4.55, 5.8, 8.8, 9, 10, 0.1, 0.2, 2.2] y = ["a", "b", "b", "b", "c", "c", "c", "d", "d", "d", "a", "b", "b"] groups = [1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4] gkf = GroupKFold(n_splits=2) for train_index, test_index in gkf.split(X, y, groups=groups): print("Train:", train_index, "Validation:",test_index) Output: Train: [ 0 1 2 3 4 5 10 11 12] Validation: [6 7 8 9] Train: [3 4 5 6 7 8 9] Validation: [ 0 1 2 10 11 12] Train: [ 0 1 2 6 7 8 9 10 11 12] Validation: [3 4 5] Desired Output (assume 2 years for each group): Train: [ 7 8 9 10 11 12 ] Validation: [0 1 2 3 4 5 6] Train: [0 1 2 10 11 12 ] Validation: [ 3 4 5 6 7 8 9 ] Train: [ 0 1 2 3 4 5 ] Validation: [6 7 8 9 10 11 12] Although, the test and train subsets are not sequential along and can select more years to group.
answer count: 1
downvote count: 0

http://stackoverflow.com/a/51811505
score: 0
accepted answer of: http://stackoverflow.com/q/51808941
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51808941
has body: Based on this very helpful question, you can make use of Keras' broadcasting properties. I'm assuming here you run Keras on the TensorFlow backend. From the TF docs on broadcasting: A special case arises, and is also supported, where each of the input arrays has a degenerate dimension at a different index. In this case, the result is an "outer operation". A reproducible example of your numpy code is the following: import numpy as np import itertools # Generate 100 random points in a 5-D space n_dim = 5 matrix = np.random.rand(1000, 5) # List all possible combinations combinations = list(itertools.combinations(matrix.tolist(), 2)) def mse(tup): """MSE between first and second element of a tuple of lists""" return np.mean((np.array(tup[0]) - np.array(tup[1]))**2) avg_mse = np.mean([mse(c) for c in combinations]) print('Average mse: {:.3f}'.format(avg_mse)) This returns, in my case, Average mse: 0.162 Based on the question cited above, you could construct your loss function as follows: import keras.backend as K # Wrap our random matrix into a tensor tensor = K.constant(value=matrix) def loss_function(x): x_ = K.expand_dims(tensor, axis=0) x__ = K.expand_dims(tensor, axis=1) # Compute mse for all combinations, making use of broadcasting z = K.mean(K.square(x_ - x__), axis=-1) # Return average mse return(K.mean(z)) with K.get_session() as sess: print('Average mse: {:.3f}'.format(loss_function(tensor).eval())) Which returns for me Average mse: 0.162. Note that this implementation does not exactly replicate the behaviour from your numpy example. The difference is that all combinations of rows with itself are also considered (not the case with itertools.combinations) and combinations are considered twice: mse((row1, row2)) and mse((row2, row1)) will both be calculated, which is again not the case with your itertools code. For matrices with a large number of rows, this should not make too much of a difference, as my example shows.
type: Answer

http://stackoverflow.com/a/51832417
upvote count: 7
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51832063
has comment: http://stackoverflow.com/comment/90619004
answers question: http://stackoverflow.com/q/51832063
type: Answer
has comment: http://stackoverflow.com/comment/90619019
has comment: http://stackoverflow.com/comment/90618991
downvote count: 0
score: 7
has comment: http://stackoverflow.com/comment/90619045
has body: del doesn't actually handle any de-allocation of memory, it merely unbinds a value from a name, and then decrements the reference count of that object by one. There is no way to systematically unbind all names from an object given a single reference. An object is not garbage collected until some point after the reference count drops to 0. You can see an object's reference count by using the sys.getrefcount method (which is typically one higher than it actually is because of the temporary reference within the method itself). We can demonstrate del in practice using this method and the __del__ method (which is called only when the reference count for the object is decremented to 0): &gt;&gt;&gt; # print something when refcount == 0 and object is about to be collected &gt;&gt;&gt; class Deleted: ... def __del__(self): ... print("actually deleted") ... &gt;&gt;&gt; a = Deleted() &gt;&gt;&gt; # just a &gt;&gt;&gt; sys.getrefcount(a) - 1 1 &gt;&gt;&gt; b = a &gt;&gt;&gt; # a and b &gt;&gt;&gt; sys.getrefcount(a) - 1 2 &gt;&gt;&gt; del a &gt;&gt;&gt; # now it's just b &gt;&gt;&gt; sys.getrefcount(b) - 1 1 &gt;&gt;&gt; del b actually deleted If you're curious to read more about how all of this works internally, check out the C API documentation on the internal calls for reference counting, and check out the gc module, which is the high level python interface for introspecting the garbage collection sub-system. Given your specific problem, since you are working with dictionaries which are mutable types, you could just clear the dictionary: &gt;&gt;&gt; a = {"a": 1} &gt;&gt;&gt; b = a &gt;&gt;&gt; # will clear the dict that both a and b are referencing &gt;&gt;&gt; b.clear() &gt;&gt;&gt; a {} Alternatively you can use the equivalent range syntax to clear the dictionary del a[:].

http://stackoverflow.com/a/51953595
type: Answer
has body: It depends on how you want to read the data from the Elasticsearch. Is it incremental reading i.e. reading new data that comes to you every day or is it like a bulk reading. For the latter, you need to use the bulk API of Elasticsearch in python and for the former, you can restrict yourself to a simple range query. Schematic code for reading bulk data: https://gist.github.com/dpkshrma/04be6092eda6ae108bfc1ed820621130 How to use bulk API of ES: How to use Bulk API to store the keywords in ES by using Python https://elasticsearch-py.readthedocs.io/en/master/helpers.html#elasticsearch.helpers.bulk How to use the range query for incremental inserts: https://martinapugliese.github.io/python-for-(some)-elasticsearch-queries/ How to have Range and Match query in one elastic search query using python? Since you want your data to be inserted in different intervals, you will require to perform date aggregations as well. https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-bucket-datehistogram-aggregation.html How to perform multiple aggregation on an object in Elasticsearch using Python? Once you issue your Elasticsearch query, your data will be collected in a temporary variable, you can use the python library over NOSQL database such as PyMongo to insert into Elasticsearch data into it.
has comment: http://stackoverflow.com/comment/90859429
score: 0
answers question: http://stackoverflow.com/q/51949872

http://stackoverflow.com/comment/123799894
has text: @d_kennetz Yes Thanks, I got that later from a community member in my original [query here](https://stackoverflow.com/questions/69999080/replace-an-arrow-character-repeating-headers-and-blank-lines-in-text-file-and-p/70001731?noredirect=1#comment123793297_70001731).
type: AnswerComment
comment on: http://stackoverflow.com/a/51828911
score: 0
type: Comment

http://stackoverflow.com/a/52648656
accepted answer of: http://stackoverflow.com/q/51843523
has body: I finally found some example library that is working: jaraco It does exactly what I am trying to achive and uses some elements from DirectShow (see here): from comtypes.gen.DirectShowLib import (FilterGraph, CaptureGraphBuilder2, ...) jaraco.video claims to be "a port of the VideoCapture module in pure Python using ctypes and comtypes." It is using a DirectShow.tlb file (whatever that is) to get the definitions into comtypes A type library (.tlb) is a binary file that stores information about a COM or DCOM object's properties and methods in a form that is accessible to other applications at runtime. The imports are auto-generated in __init__.py and can be used easily: from api.objects import ..., IMediaControl, IAMVideoProcAmp, IAMCameraControl, ... and can be used def _get_camera_control(self): return self._get_graph_builder_interface(IAMCameraControl) def get_camera_control_property(self, i): video_properties = self._get_camera_control() return video_properties.Get(i) Then you can use the functions in combination with the enum stated in the docs, e.g. # CameraControl_Exposure = 4 print(d.get_camera_control_property(4))
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 1
has comment: http://stackoverflow.com/comment/110047573
upvote count: 1
answers question: http://stackoverflow.com/q/51843523

http://stackoverflow.com/q/51953688
type: Question
has comment: http://stackoverflow.com/comment/90857831
score: 0
has body: I've been working on a script to scrap replies of a single tweet on a log now, i haven't work on this all by myself, and finally make it almost work but i found a index error almost at the end, a "List index out of range" i'm a little bit confuse 'cause i don't see what's the problem here... can somebody explain? ._. def tweet_url(t): return "https://twitter.com/%s/status/%s" % (t.user.screen_name, t.id) def get_tweets(filename): for line in open(filename): yield twitter.Status.NewFromJsonDict(json.loads(line)) def get_replies(tweet): user = tweet.user.screen_name tweet_id = tweet.id max_id = None logging.info("looking for replies to: %s" % tweet_url(tweet)) while True: q = urllib.parse.urlencode({"q": "to:%s" % user}) try: replies = t.GetSearch(raw_query=q, since_id=tweet_id, max_id=max_id, count=100) except twitter.error.TwitterError as e: logging.error("caught twitter api error: %s", e) time.sleep(60) continue for reply in replies: logging.info("examining: %s" % tweet_url(reply)) if reply.in_reply_to_status_id == tweet_id: logging.info("found reply: %s" % tweet_url(reply)) yield reply # recursive magic to also get the replies to this reply for reply_to_reply in get_replies(reply): yield reply_to_reply max_id = reply.id if len(replies) != 100: break if __name__ == "__main__": logging.basicConfig(filename="replies.log", level=logging.INFO) tweets_file = sys.argv[1] for tweet in get_tweets(tweets_file): for reply in get_replies(tweet): print(reply.AsJsonString()) So... is on the bottom line, the list (sys.argv [1]) is causing the problem here but i don't see why the out of range index error appear, any idea?
answer count: 3
has answer: http://stackoverflow.com/a/51953907
has title: Python - list index out of range? Twitter Replies
possible better answer: http://stackoverflow.com/a/51953787
has answer: http://stackoverflow.com/a/51953787
tagged with: python
tagged with: tweepy
type: AnsweredQuestion
tagged with: list
tagged with: twitter
has answer: http://stackoverflow.com/a/51953807
accepted answer: http://stackoverflow.com/a/51953807

http://stackoverflow.com/comment/90872822
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51943435
has text: @KurtisRader The problem is that `foo` may be recomputed before `bar` can unblock and return it, and `bar` needs to return the value of `foo` that was being computed when it was called. What I may do, however, is store the last few values of `foo` in a dictionary. Whenever `foo` is computed, it gets a unique ID. If `foo` is being computed when `bar` is called in another thread, it simply gets the ID of the value that is currently being computed and just retrieves that value using the ID whenever it gets unblocked.
score: 0

http://stackoverflow.com/q/51940641
answer count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: python
score: 2
has title: pygame.mask doesn't work on renpy
type: Question
downvote count: 0
tagged with: renpy
has body: I'm making physics mini game with renpy. I need a collision detection between rotating object (stick/paddle) and a falling object (ball) so I'm using masking for it, here's the code I used: pic_alpha = renpy.load_surface(stick).convert_alpha() pic_mask = pygame.mask.from_surface(pic_alpha) but this doesn't work, it says : AttributeError: 'module' object has no attribute 'mask' in python it should be codes below and it works well: obstacle = pygame.image.load("stick.png").convert_alpha() obstacle_mask = pygame.mask.from_surface(obstacle) So basically the game is about keeping a ball on a moving paddle from falling for a certain time, user controls the paddle's rotation with mouse movement (imagine seesaw) and the ball is sliding on top of it, you need to keep the balance to hinder the ball from falling. Please help. Thank you.
favorite count: 0

http://stackoverflow.com/q/51897241
has title: Importing Large csv (175 GB) to MySQL Server with Unusual Delimeters
has body: I have a 175 GB csv that I am trying to pull into MySQL. The table is set up and formatted. The problem is, the csv uses unorthodox delimeters and line seperators (both are 3 character strings, @%@ and @^@). After a lot of trial and error I was able to get the process to start in HeidiSQL, but it would freeze up and never actually populate any data. I would ideally like to use Python, but the parser only accepts 1-character line separators, making this tricky. Does anyone have any tips on getting this to work?
type: UnansweredQuestion
tagged with: heidisql
tagged with: pandas
has comment: http://stackoverflow.com/comment/90746012
has answer: http://stackoverflow.com/a/51897688
has comment: http://stackoverflow.com/comment/90746524
type: Question
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has comment: http://stackoverflow.com/comment/90746257
score: 0
has comment: http://stackoverflow.com/comment/90745831
tagged with: mysql
answer count: 1

http://stackoverflow.com/comment/90795315
comment on: http://stackoverflow.com/q/51922673
has text: Meanwhile, why not just call `close`? [The docstring examples all do it](https://github.com/Zulko/moviepy/blob/master/moviepy/video/VideoClip.py#L250), so presumably it's expected that you'll do it as well.
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/a/51864330
has comment: http://stackoverflow.com/comment/90685469
score: 2
upvote count: 2
has body: If you'd like to slide along the borders instead of bouncing, you can set the rect's top, etc. attributes to the border coords when it leaves the screen and then set the pos_red vector to the rect.center coords. The velocity will be unaffected. To change the initial rotation of the car image, you need to pg.transform.rotate with the desired angle: redcar = pg.transform.rotate(REDCAR_ORIGINAL, redangle). And the x component of the vel_red vector should be negative (point to the left) at the program start: vel_red = Vector2(-redspeed, 0). import pygame as pg from pygame.math import Vector2 pg.init() screen = pg.display.set_mode((1150, 800)) clock = pg.time.Clock() REDCAR_ORIGINAL = pg.Surface((50, 30), pg.SRCALPHA) pg.draw.polygon( REDCAR_ORIGINAL, (255, 0, 0), [(0, 30), (50, 20), (50, 10), (0, 0)]) redangle = 180 # Rotate the image/surface before the game starts. redcar = pg.transform.rotate(REDCAR_ORIGINAL, redangle) redspeed = 5 pos_red = Vector2(800, 500) # -redspeed means the vector points to the left. vel_red = Vector2(-redspeed, 0) redrect = redcar.get_rect(center=pos_red) mask_red = pg.mask.from_surface(redcar) run = True while run: for event in pg.event.get(): if event.type == pg.QUIT: run = False elif event.type == pg.KEYDOWN: if event.key == pg.K_r: # Reset the car to the start position. redangle = 180 redcar = pg.transform.rotate(REDCAR_ORIGINAL, redangle) pos_red = Vector2(800, 500) vel_red = Vector2(-redspeed, 0) redrect = redcar.get_rect(center=pos_red) mask_red = pg.mask.from_surface(redcar) keys = pg.key.get_pressed() if keys[pg.K_LEFT]: redangle += 5 vel_red.rotate_ip(-5) redcar = pg.transform.rotate(REDCAR_ORIGINAL, redangle) redrect = redcar.get_rect(center=redrect.center) mask_red = pg.mask.from_surface(redcar) elif keys[pg.K_RIGHT]: redangle -= 5 vel_red.rotate_ip(5) redcar = pg.transform.rotate(REDCAR_ORIGINAL, redangle) redrect = redcar.get_rect(center=redrect.center) mask_red = pg.mask.from_surface(redcar) elif keys[pg.K_UP]: vel_red.scale_to_…
answers question: http://stackoverflow.com/q/51857329
accepted answer of: http://stackoverflow.com/q/51857329
has comment: http://stackoverflow.com/comment/90681672
has comment: http://stackoverflow.com/comment/90681735
has comment: http://stackoverflow.com/comment/90685348
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90681261
type: Answer
has comment: http://stackoverflow.com/comment/90684841

http://stackoverflow.com/q/51937444
answer count: 1
favorite count: 0
has title: with python sqlalchemy, how do define multiple-column primary key
upvote count: 5
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/63334342
downvote count: 0
tagged with: sqlalchemy
has comment: http://stackoverflow.com/comment/90825350
type: Question
has body: I am following the tutorial at https://docs.sqlalchemy.org/en/latest/core/tutorial.html I see an example for primary key, it seems to use just one column &gt;&gt;&gt; users = Table('users', metadata, ... Column('id', Integer, primary_key=True), ... Column('name', String), ... Column('fullname', String), ... ) how do define primary key with a sequence of columns?
score: 5
linked to: http://stackoverflow.com/q/9034271
has comment: http://stackoverflow.com/comment/90825003
tagged with: sql

http://stackoverflow.com/q/51891791
has answer: http://stackoverflow.com/a/51891968
type: Question
score: 0
answer count: 3
has comment: http://stackoverflow.com/comment/90734882
has answer: http://stackoverflow.com/a/51892859
tagged with: currency
has body: I try to find the amounts in euros in receipts. I extract the values, but the currency can appear in different ways: "EUR", "E" or"€". I do not succeed in specifying these different forms within the regex. In addition, the "E" must not raise words that also begin with "E" such as "Eggs". Currently my regex is \d+[\.+\,+]\d*\s*[(e|eur|euros|€)]+\W but the brackets don't work correctly because it retrieves all the words that contains E... My goal: find the amounts if we find the form amount + EUR or amount + € or amount + E See here an example : https://regex101.com/r/F3Zm9M/2 Thank you
has answer: http://stackoverflow.com/a/51892610
type: UnansweredQuestion
tagged with: python
tagged with: regex
has title: Regex python : find different forms of currency with amount

http://stackoverflow.com/a/72908627
answers question: http://stackoverflow.com/q/51944836
downvote count: 0
type: Answer
score: 1
upvote count: 1
has body: Setting trainable = False dint worked for me This worked for me : As i have set trainable = True from keras import models def freeze(model): """Freeze model weights in every layer.""" for layer in model.layers: layer.trainable = True if isinstance(layer, models.Model): freeze(layer) model.save("./model.h5") model = models.load_model("./model.h5") freeze(model) Now this saved model was error free And then i could do all operation like save_weights, load_weights etc Note: Do these all exp on same envs or same keras/tf version where your model was first saved

http://stackoverflow.com/comment/90780151
comment on: http://stackoverflow.com/q/51888101
score: 1
has text: Are your strings literally "parameterA", etc? Do they ever change? Numpy works best on homogeneous arrays of numbers. It can deal with strings, but it's much better if you can keep your strings and numbers separate.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51930205
downvote count: 0
type: Answer
score: 2
has body: There is a difference between a method and the value a method returns. Here in your Wine model, we see: from django.db.models import Avg class Wine(models.Model): name = models.CharField(max_length=200) def average_rating(self): return self.review_set.aggregate( mean=Avg('rating') )['mean'] def __unicode__(self): return self.name (I rewrote it to make an efficienty query, instead of Python/Django/Numpy let do the work). If you now have a Wine object named some_wine, then you do not get the average rating here with some_wine.average_rating, since this will return a method, but by calling the function, so some_wine.average_rating(). There are some options here: calling the function in the lambda expression: wine_list = sorted( list(Wine.objects.filter(id__in=other_users_reviews_wine_ids)), key=lambda x: x.average_rating(), reverse=True ) define the method as a property, in that case, you no longer call the function, it is the called behind the curtains, so: from django.db.models import Avg class Wine(models.Model): name = models.CharField(max_length=200) @property def average_rating(self): return self.review_set.aggregate( mean=Avg('rating') )['mean'] def __unicode__(self): return self.name use Wine.average_rating as key, since then it is a function that is called with instances: wine_list = sorted( list(Wine.objects.filter(id__in=other_users_reviews_wine_ids)), key=Wine.average_rating, reverse=True ) order the Wine objects already by the database, by using .annotate(..): wine_list = Wine.objects.filter( id__in=other_users_reviews_wine_ids ).annotate( mean=Avg('rating') ).order_by('-rating') The latest approach is probably the most efficient, since a database typically is optimized for such queries, furthermore this will get done by a single query.
upvote count: 2
answers question: http://stackoverflow.com/q/51929887

http://stackoverflow.com/q/51820964
score: 2
tagged with: compatibility
has answer: http://stackoverflow.com/a/51821211
answer count: 1
favorite count: 0
tagged with: hash
type: UnansweredQuestion
tagged with: python
tagged with: php
has title: Same hash of PHP object in Python
has body: I have a little problem: On one hand I have a parser, which takes a string, wraps it into a PHP object and returns a hashed string of this object. On the other hand a new version of parser is written on Python and new parser take a string, hash it and return also as a string. And there I have a compability issue. The same string hashed as PHP object and hashed as string returns a different result. Is there a way to get PHP object in python, to obtain exact same result as in PHP-parser? Here a bites of code: PHP: function num_converter() { $string_1 = '1234'; $string_2 = '567890'; $hash = String_to_hash::stringHash((object)array( 'number'=&gt;$string_1.' '.$string_2, 'number2'=&gt;$number3, )); return array_push($Reply, $hash); } And here is same functionality code in Python: def num_converter(): string_1 = '1234' string_2 = '567890' number3 = digits # type of int string_to_hash = string_1 + " " + string_2 + str(number3) return hashlib.md5(string_to_hash.encode()).hexdigest().upper()
upvote count: 3
has comment: http://stackoverflow.com/comment/90595888
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/90595743

http://stackoverflow.com/comment/90622139
type: Comment
comment on: http://stackoverflow.com/a/51834187
has text: I can't use pandas.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/90653600
has text: Raksha, try using `Savitzky-Golay filter`. Here is a sample: https://stackoverflow.com/questions/20618804/how-to-smooth-a-curve-in-the-right-way
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51849871

http://stackoverflow.com/comment/90802097
type: AnswerComment
score: 0
type: Comment
has text: This code accounts for the cases where the user enters something like "abcd." Do you mean you want to check every time the user hits any key, before even hitting Enter?
comment on: http://stackoverflow.com/a/51925900

http://stackoverflow.com/comment/90760647
comment on: http://stackoverflow.com/q/51904950
type: Comment
has text: There is no `Foo` on the line where you attempt to define the default parameter value. The name `Foo` becomes known when the class body is successfully parsed and compiled, which won't happen until the blank line. Why do you want to do to this at all?
score: 1
type: QuestionComment

http://stackoverflow.com/a/51823708
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51823427
downvote count: 0
has comment: http://stackoverflow.com/comment/90601796
type: Answer
has body: Try the following: def main(): parser = argparse.ArgumentParser() parser.add_argument('-r', '--restore', nargs=2, metavar=('path-to-dump-file', 'db-name'), help='Restore specified dump file as dbname. Must supply &lt;pathtodumpfile&gt; and &lt;dbname&gt;') args = parser.parse_args() if args.restore: restore_db_dump(args.restore[0], args.restore[1]) if __name__ == '__main__': main() Notes: I have removed const=, because it's not clear whether you want a default. There is now a nargs=2 parameter, so the -r option requires two values to be given. the metavar parameter sets the names of the arguments to -r in the help text.
upvote count: 2
answers question: http://stackoverflow.com/q/51823427
score: 2

http://stackoverflow.com/q/51809017
type: Question
linked to: http://stackoverflow.com/q/24731035
score: 8
tagged with: matplotlib
has answer: http://stackoverflow.com/a/51890132
has body: My python script below adds a picture (a generated rectangle on this simple example) and GPS track on a map generated with Basemap module. Now I would like to make both track an rectangle transparent. No problem for the track via alpha kwarg but I cannot figure how to do it for the picture. import matplotlib.pyplot as plt from PIL import Image from matplotlib.offsetbox import AnnotationBbox, OffsetImage from mpl_toolkits.basemap import Basemap lats = [ 45, 15 ] lons = [ 0 , 100 ] fig = plt.figure( dpi = 300 ) ax = plt.subplot(111) myBaseMap = Basemap( projection='ortho', lat_0=lats[-1], lon_0=lons[-1] ) myBaseMap.bluemarble() planeImg = Image.new('RGB', (600, 300), color = 'red') planeXY = myBaseMap( lons[-1], lats[-1] ) x,y = myBaseMap( lons, lats ) plt.plot( x, y, color='r', alpha=0.5, linewidth=3 ) imagebox = OffsetImage( planeImg , zoom=.4 ) ab = AnnotationBbox( imagebox, myBaseMap( lons[-1], lats[-1] ), xybox=( 0., 0. ), xycoords='data', boxcoords='offset points', frameon=False ) ax.add_artist(ab) plt.show() This code produces the picture below with a transparent line. Now I would like to make the red rectangle transparent in the same fashion. I tried to use set_alpha method on the annotation box and ax but didn't work. Any ideas ? Thanks.
tagged with: image
has comment: http://stackoverflow.com/comment/90584803
answer count: 2
downvote count: 0
linked to: http://stackoverflow.com/q/15160123
tagged with: matplotlib-basemap
favorite count: 0
has comment: http://stackoverflow.com/comment/90580595
has answer: http://stackoverflow.com/a/51920786
upvote count: 8
has comment: http://stackoverflow.com/comment/90573908
accepted answer: http://stackoverflow.com/a/51890132
has comment: http://stackoverflow.com/comment/90577568
tagged with: python
possible better answer: http://stackoverflow.com/a/51920786
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/34458251
has title: Add transparent picture over plot

http://stackoverflow.com/a/51847757
type: AcceptedAnswer
score: 4
has body: The script runs faster than pasting each line in the shell - Since the element is created dynamically in the page, when pasting each line you gave enough time for the browser to run the javascript code and generate the element. When running the script, the line that searches for the element is reached before the element is created, so you get the error. There are many possible solutions, which usually involve using a selenium wait method, or time.sleep, or a combination of those.
accepted answer of: http://stackoverflow.com/q/51847670
has comment: http://stackoverflow.com/comment/90648990
type: Answer
upvote count: 4
answers question: http://stackoverflow.com/q/51847670
downvote count: 0

http://stackoverflow.com/q/51888819
has answer: http://stackoverflow.com/a/51889122
tagged with: arrays
score: 0
has body: I have a global array: buffer = [] I am trying to assign the values of this array from a function: def data(): temp1=5 temp2=6 global buffer buffer[0]=temp1 buffer[1]=temp2 However, this doesn't seem to work and the values aren't getting updated in the global array. Eclipse doesn't even seem to parse these statements. Any help? Thanks in advance :)
answer count: 2
has title: How to fill up global arrays inside a function in Python?
has comment: http://stackoverflow.com/comment/90728737
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51889012
tagged with: python
has comment: http://stackoverflow.com/comment/90728762
has comment: http://stackoverflow.com/comment/90728912
type: Question

http://stackoverflow.com/comment/90653764
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51849725
has text: Is flask pip installed on the server? If so, is the python executable pointing to the right `site-packages`? It could be a default python installation that doesn't share the same config as say a `virtualenv` or `conda env`

http://stackoverflow.com/a/51918343
type: Answer
upvote count: 2
answers question: http://stackoverflow.com/q/51918305
score: 2
has body: You cannot turn Hello! into an int. Get rid of the int(...) around input. Note: You can turn strings into ints if the string is a valid number.
accepted answer of: http://stackoverflow.com/q/51918305
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90786644

http://stackoverflow.com/a/51801083
answers question: http://stackoverflow.com/q/51800994
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90565283
type: Answer
score: 1
accepted answer of: http://stackoverflow.com/q/51800994
upvote count: 1
has body: The =... part gives a parameter a default value. Here that's None, and that does mean the parameter is optional when calling the function. If you don't specify it, the default is used. See Default Argument Values in the Python tutorial, as well as the reference documentation for function definitions: When one or more parameters have the form parameter = expression, the function is said to have “default parameter values.” For a parameter with a default value, the corresponding argument may be omitted from a call, in which case the parameter’s default value is substituted. When calling such a function, you could pass in the same value as the default, to this specific function that makes no difference; so when there is no starting_date, you can pass in None: start_date = starting_date or None # when determining the starting date, default to None requested_report=report_api.request_report( report_type=report_name, start_date=starting_date ) Another option is to set any optional keyword arguments in a dictionary, then pass those in with the ** call syntax to unpack the dictionary as keyword arguments: kwargs = {} if ...: # test that decides if start_date is needed kwargs['start_date'] = starting_date # expression to set the start date requested_report=report_api.request_report( report_type=report_name, **kwargs) It is fine for the kwargs dictionary to be empty.

http://stackoverflow.com/comment/111715914
type: AnswerComment
score: 0
type: Comment
has text: Dear Dinesh, since most of your covariates return constant horizontal lines in the Partial dependency plots, should'nt you be dropping them off from your analysis? It would also help better depict the main features of your model.
comment on: http://stackoverflow.com/a/51833876

http://stackoverflow.com/comment/90790655
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51920426
has text: Ah I see, maybe I should add `/Users/myusername/anaconda3/bin` to PATH.

http://stackoverflow.com/q/51934520
tagged with: regex
answer count: 0
linked to: http://stackoverflow.com/q/31915018
has body: Seems to be an easy question, but I miss something in regex groups I guess. I have a string and I need to find how many occurrences of three patterns it has. string="AGTGCTGGCCGATATGCNYGGAATATATGCAGTGGTGNTT" pattern1="GGCCTATATGC" pattern2="GGAANATATGC" pattern3="GGCCGATATGC" The idea is to use regular expressions. I tried: re.findall(r"GG[C,A]{2}[A-Z](AT){2}GC", string) However, I do something wrong in (AT){2}, because with just writing ATAT it works. Is it somehow related to groups in regex? Would appreciate if someone can explain. Thanks,
type: Question
has comment: http://stackoverflow.com/comment/90819224
has title: find patterns in a string using python regex
score: 0
has comment: http://stackoverflow.com/comment/90819328
duplicate of: http://stackoverflow.com/q/31915018
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/90830959
has text: What i mean is.. grab the element of html you want to. If it is text then you will need to c.text. Whatever it is.. append it in the dictionary. Yes you will need to append the data in dictionary, which you will eventually save in excel sheet.
type: AnswerComment
comment on: http://stackoverflow.com/a/51913162
score: 0
type: Comment

http://stackoverflow.com/q/51946967
type: Question
answer count: 2
has body: Python 3 requests.get().text returns unencoded string. If I execute: import requests request = requests.get('https://google.com/search?q=Кто является президентом России?').text.lower() print(request) I get kind of this: &amp;#1050;&amp;#1090;&amp;#1086; &amp;#1103;&amp;#1074;&amp;#1083;&amp;#1103;&amp;#1077;&amp;#1090;&amp;#1089;&amp;#1103; &amp;#1087;&amp;#1088;&amp;#1077;&amp;#1079;&amp;#1080;&amp;#1076; I've tried to change google.com to google.ru If I execute: import requests request = requests.get('https://google.ru/search?q=Кто является президентом России?').text.lower() print(request) I get kind of this: d0%9a%d1%82%d0%be+%d1%8f%d0%b2%d0%bb%d1%8f%d0%b5%d1%82%d1%81%d1%8f+%d0%bf%d1%80%d0%b5%d0%b7%d0%b8%d0%b4%d0%b5%d0%bd%d1%82%d0%be%d0%bc+%d0%a0%d0%be%d1%81%d1%81%d0%b8%d0 I need to get an encoded normal string.
score: 0
tagged with: python
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python-requests
has answer: http://stackoverflow.com/a/51947647
has title: Python 3 requests.get().text returns unencoded string
has answer: http://stackoverflow.com/a/51948625

http://stackoverflow.com/comment/90706966
type: QuestionComment
comment on: http://stackoverflow.com/q/51877618
score: 0
has text: I added the output I got from your code. @JonasAdler
type: Comment

http://stackoverflow.com/q/51922923
possible better answer: http://stackoverflow.com/a/51922968
accepted answer: http://stackoverflow.com/a/51922950
has title: Return values in dictionary of lists
has body: I am using Python 3.6 I have a list of dictionaries (below) and would like to return the following values: id, name, color for every record in my data. I cannot seem to figure out how to iterate through all the "pages" in my dataset to return all values. I have gotten as far as the for loop included below, but that only returns data for the first page and none of the others. The end-state I'm looking for would return the data in the structure I have in my for loop but for all pages. My data and for loop: mydict = [ { "page": 1, "data":[ { "id": 11111, "name": "smith", "color": "orange", "subsidiary": "no" }, { "id": 22222, "name": "smith", "color": "orange", "subsidiary": "yes", "subsidiaries": [ { "id": 33333, "name": "alpha", "color": "blue" }, { "id": 44444, "name": "alpha", "color": "blue" } ], "last_updated": 123456789 } ] }, { "page": 2, "data":[ { "id": 55555, "name": "smith", "color": "orange", "subsidiary": "no" }, { "id": 66666, "name": "smith", "color": "orange", "subsidiary": "yes", "subsidiaries": [ { "id": 77777, "name": "alpha", "color": "blue" }, { "id": 88888, "name": "alpha", "color": "blue" } ], "last_updated": 987654321 } ] } ] for i in mydict[0]['data']: print ({"cust_id": i['id'], "cust_name": i['name'], "fabric_color": i['color']}) Returns: {'cust_id': 11111, 'cust_name': 'smith', 'fabric_color': 'orange'} {'cust_id': 22222, 'cust_name': 'smith', 'fabric_color': 'orange'}
type: AnsweredQuestion
downvote count: 0
score: 1
favorite count: 0
tagged with: python-3.x
type: Question
answer count: 2
upvote count: 1
tagged with: python
tagged with: dictionary
tagged with: list
has answer: http://stackoverflow.com/a/51922950
has answer: http://stackoverflow.com/a/51922968

http://stackoverflow.com/comment/90577744
has text: You could move the validator function into your models.py.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51811269

http://stackoverflow.com/comment/96461947
score: 0
type: AnswerComment
type: Comment
has text: Old post but if you want to use functions still, you could create 10 of them, each processing 1GB of bytes range, if applicable. E.g. if blob is 6GB, function7, 8, 9 and 10 will just give up. Nice thing is that there run in parallel.
comment on: http://stackoverflow.com/a/51880265

http://stackoverflow.com/a/51869139
has comment: http://stackoverflow.com/comment/90691050
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51868804
has body: Assuming that your goal is to find the first unique character in a single string you can do the following: (You don't actually have to iterate over the whole alphabet) class Solution: def firstUniqChar(self, s): """ :type s: str """ assert isinstance(s,str), "Please insert a valid string" s=s.lower() counter = {} for key in s: counts = s.count(key) if counts == 1 and key.isAlpha(): counter[key] = counts return min(counter, key=counter.get) if len(counter) &gt; 0 else -1 sol = Solution() print(sol.firstUniqChar('toobad')) &gt;t this will return the first character appearing uniquely in the string itself. If you want the first alphabet letter appearing uniquely you do (there are ways of not iterating I just did like because probably is not what you want): class Solution: def firstUniqChar(self, s): """ :type s: str """ assert isinstance(s,str), "Please insert a valid string" s=s.lower() counter = {} for key in 'abc......': counts = s.count(key) if counts == 1: counter[key] = counts return min(counter, key=counter.get) if len(counter) &gt; 0 else -1 sol = Solution() print(sol.firstUniqChar('toobad')) &gt;a
has comment: http://stackoverflow.com/comment/90691459
has comment: http://stackoverflow.com/comment/90691099
has comment: http://stackoverflow.com/comment/90690423

http://stackoverflow.com/comment/90683677
score: 1
type: Comment
type: QuestionComment
has text: If you need this to hand-weave scraping code, you'll have better results with an interactive session: you'll be able to interact with the browser both by hand (to get XPaths, ids and such) and with commands.
comment on: http://stackoverflow.com/q/51865300

http://stackoverflow.com/a/67235612
type: Answer
answers question: http://stackoverflow.com/q/51912999
downvote count: 1
has body: I opened in admin mode and wrote python -m pip install tensorflow==2.3.0
score: -1
upvote count: 0

http://stackoverflow.com/comment/90836558
type: Comment
type: QuestionComment
has text: Python, Javascript or Ruby is also fine
comment on: http://stackoverflow.com/q/51942580
score: 0

http://stackoverflow.com/comment/104823268
has text: That's right! I've tried to install it using `sudo apt install python3-gunicorn` but it didn't create executable on path, and this command did! Thanks!
type: Comment
comment on: http://stackoverflow.com/a/58574653
score: 1
type: AnswerComment

http://stackoverflow.com/a/51897055
downvote count: 0
has body: Almost the same logic like Jez , change your string to list , then unnest the list , then we just groupby and create the count newdf=df.set_index(['nome','tipo'])['resumo'].str.split(',').apply(pd.Series).stack().to_frame('resumo').reset_index(level=[0,1]) newdf['count']=newdf.groupby(['nome','tipo','resumo'])['resumo'].transform('size') newdf Out[172]: nome tipo resumo count 0 CÉSAR MESSIAS INQ Desvio de verbas públicas 1 0 CÉSAR MESSIAS AP Desvio de verbas públicas 1 0 FLAVIANO MELO INQ Prestação de contas rejeitada 1 0 FLAVIANO MELO AP Peculato 1 1 FLAVIANO MELO AP Gestão fraudulenta 1
answers question: http://stackoverflow.com/q/51896621
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/comment/90846908
type: QuestionComment
has text: https://www.tensorflow.org/extend/tool_developers/#text_or_binary
score: 5
comment on: http://stackoverflow.com/q/51948262
type: Comment

tuples
tags question: http://stackoverflow.com/q/51900020
tags question: http://stackoverflow.com/q/51901920
tags question: http://stackoverflow.com/q/51938903
tags question: http://stackoverflow.com/q/51882110
tags question: http://stackoverflow.com/q/51946256
tags question: http://stackoverflow.com/q/51853203
tags question: http://stackoverflow.com/q/51897708
tags question: http://stackoverflow.com/q/51809512
tags question: http://stackoverflow.com/q/51914562
tag name: tuples
tags question: http://stackoverflow.com/q/51837249
tags question: http://stackoverflow.com/q/51955391
tags question: http://stackoverflow.com/q/51808662
tags question: http://stackoverflow.com/q/51935610
type: Tag

http://stackoverflow.com/a/51833106
has body: In most situations the best solution is to rely on the so-called "user site" location by running: pip install --user package_name If that doesn't work, you need the admin rights. So just run the cmd as an administrator. Or better yet create a virtualenv and then install. Instructions can be found on: https://virtualenv.pypa.io/en/stable/installation/
has comment: http://stackoverflow.com/comment/90620394
answers question: http://stackoverflow.com/q/51833041
downvote count: 0
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/a/52482295
has body: For those who have the same issue, I recommend the use of the Bob library, which supports big data processing and even offers parallel processing. In my use-case Bob was a great fit for the development of GMM-UBM systems, as all the relevant functionalities are already implemented.
accepted answer of: http://stackoverflow.com/q/51935550
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51935550
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/comment/90865248
comment on: http://stackoverflow.com/a/51955864
type: AnswerComment
score: 0
has text: @PYN No, period.
type: Comment

http://stackoverflow.com/a/51809930
upvote count: 2
accepted answer of: http://stackoverflow.com/q/51809769
type: AcceptedAnswer
type: Answer
has body: Seems like win32api.pyd (which really is DLL) is not a win32 application. So I think it's loading 64bit drivers to 32bit runtime. In this case, I will try to uninstall 64bit python, delete it's folder and install a 32bit version. I believe this will solve your problem, since you don't really need 64bit python. Now the problem is in win32*.pyds, so it seems like your pyttsx3 is 32bit. According to pypi.org, you can try pip install pypiwin32 to fix both win32 and win32api errors.
has comment: http://stackoverflow.com/comment/90574874
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/90574792
has comment: http://stackoverflow.com/comment/90575782
has comment: http://stackoverflow.com/comment/90574989
answers question: http://stackoverflow.com/q/51809769

http://stackoverflow.com/q/51799746
duplicate of: http://stackoverflow.com/q/44616882
has answer: http://stackoverflow.com/a/51799839
type: Question
score: 5
upvote count: 5
tagged with: variables
has comment: http://stackoverflow.com/comment/90555798
linked to: http://stackoverflow.com/q/44616882
tagged with: scope
tagged with: environment-variables
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/90556212
favorite count: 0
has comment: http://stackoverflow.com/comment/90556255
has comment: http://stackoverflow.com/comment/90555829
has title: why the inner function can't get variable in outer scope in python
type: UnansweredQuestion
tagged with: python
has body: def foo(): m = 3 def bar(): print(m) # code 1 m=4 # code 2 bar() foo() UnboundLocalError: local variable 'm' referenced before assignment Why do I get the UnboundLocalError? I know bar can't change the value of m, but shouldn't barjust be able to get the value of m? And when I try the code 1/code 2 separately, it all works.

http://stackoverflow.com/comment/90867529
comment on: http://stackoverflow.com/q/51951256
type: Comment
type: QuestionComment
score: 0
has text: No dice. Command "find .idea/ -iname '\*Python\*'" returned nothing. What do you mean by the per-user settings directory? Is that the .Pycharm2018.2 folder in my home folder? If so, that also returned nothing besides python.decorator files

http://stackoverflow.com/comment/90764048
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51904877
has text: What is the unexpected result? Are you getting any error message?

http://stackoverflow.com/q/51859880
has title: Memory Error TFIDF cosine similarity in python
upvote count: 1
type: Question
tagged with: cosine-similarity
accepted answer: http://stackoverflow.com/a/55363614
score: 1
answer count: 1
downvote count: 0
tagged with: sparse-matrix
favorite count: 0
tagged with: out-of-memory
tagged with: python
has answer: http://stackoverflow.com/a/55363614
type: AnsweredQuestion
has body: There's a large dataset with items descriptions. It contains item ID's and text description of it. One can build a cosine similarity matrix for tf_idf values for terms in descriptions. My dataset contains descriptions for 300336 items. I've got a MemmoryError when try to execute my python code: from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.metrics.pairwise import * tf = TfidfVectorizer(analyzer='word', ngram_range=(1, 1), min_df=0) tfidf_mx = tf.fit_transform(df.text) cosine_similarities = linear_kernel(tfidf_mx) I've tried also another way sim_mx = cosine_similarity(tfidf_mx, dense_output=False) But it gives me a MemoryError too. May be there's upper limit even on sparse matrix for cosine similarities computation? Do you know why MemoryError occurs and how to treat it?

cluster-analysis
tags question: http://stackoverflow.com/q/51822779
tags question: http://stackoverflow.com/q/51941269
tag name: cluster-analysis
type: Tag

http://stackoverflow.com/comment/90837181
type: AnswerComment
comment on: http://stackoverflow.com/a/51942808
has text: @SubhasreeMitra No need for loop. `awk` will apply this script for each line of the input file.
score: 0
type: Comment

http://stackoverflow.com/q/51950195
answer count: 0
has title: Powershell command to get Owner or drive in windows
type: Question
tagged with: powershell
tagged with: winrm
has comment: http://stackoverflow.com/comment/90850477
score: 0
has comment: http://stackoverflow.com/comment/90850949
has comment: http://stackoverflow.com/comment/90852955
type: UnansweredQuestion
tagged with: python
has body: I am a new bee to Powershell. I am trying to get owner and access for a NAS drive in windows. I tried with get-acl via python(using winrm) but somehow its failing saying the drive which am trying to work on is does not exist. Example : get-acl 'V:' However when I try the same command for C: drive it works fine. For NAS it says - "Error">get-acl : Cannot find drive. A drive with the name \'V\' does not exist Someone knows any other alternative command? This command works fine when i login to that remote machine and execute, however gives above error when I execute through python using winrm.

http://stackoverflow.com/comment/90771681
score: 0
comment on: http://stackoverflow.com/q/51910136
type: QuestionComment
has text: It may not be exposed through the root cherrypy module, did you try importing it from the lib submodule where it's defined per [the docs](https://docs.cherrypy.org/en/latest/_modules/cherrypy/lib/covercp.html)?
type: Comment

http://stackoverflow.com/q/51949919
has title: How to separate column values by different rows in pandas?
answer count: 0
duplicate of: http://stackoverflow.com/q/12680754
type: UnansweredQuestion
tagged with: python
tagged with: dataframe
has comment: http://stackoverflow.com/comment/90850106
type: Question
has comment: http://stackoverflow.com/comment/90850709
score: 0
has body: I have the following structure of a dataframe in pandas A | B | C | --- Z columns ------------------------------ 12,35 | x,y | google | 115 | z | google | 1,88,35 | x,y,w | FB | I want to convert it into the following format A | B | C | --- Z columns ------------------------------ 12 | x | google | 35 | y | google | 115 | z | google | 1 | x | FB | 88 | y | FB | 35 | w | FB | What'd be the best way to go about it? The split in my case is dependent on other column while the answers in other questions just simply split a column's values
tagged with: pandas
has comment: http://stackoverflow.com/comment/90850260
linked to: http://stackoverflow.com/q/12680754
has comment: http://stackoverflow.com/comment/90849869

linux-mint
type: Tag
tag name: linux-mint
tags question: http://stackoverflow.com/q/51843015

http://stackoverflow.com/a/59192271
upvote count: 12
has comment: http://stackoverflow.com/comment/129913191
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/124258866
answers question: http://stackoverflow.com/q/51831559
has comment: http://stackoverflow.com/comment/124090192
type: Answer
accepted answer of: http://stackoverflow.com/q/51831559
has body: You can write a wrapper for OpenSSL's MD5() function that accepts NumPy arrays. Our baseline will be a pure Python implementation. Create a builder # build.py import cffi ffi = cffi.FFI() header = r""" void md5_array(uint64_t* buffer, int len, unsigned char* out); """ source = r""" #include <stdint.h> #include <openssl/md5.h> void md5_array(uint64_t * buffer, int len, unsigned char * out) { int i = 0; for(i=0; i<len; i++) { MD5((const unsigned char *) &buffer[i], 8, out + i*16); } } """ ffi.set_source("_md5", source, libraries=['ssl']) ffi.cdef(header) if __name__ == "__main__": ffi.compile() and a wrapper # md5.py import numpy as np import _md5 def md5_array(data): out = np.zeros(data.shape, dtype='|S16') _md5.lib.md5_array( _md5.ffi.from_buffer(data), data.size, _md5.ffi.cast("unsigned char *", _md5.ffi.from_buffer(out)) ) return out and a script compare the two: # run.py import numpy as np import hashlib import md5 data = np.arange(16, dtype=np.uint64) out = [hashlib.md5(i).digest() for i in data] out2 = md5.md5_array(data) print(data) # [ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15] print(out) # [b'}\xea6+?\xac\x8e\x00\x95jIR\xa3\xd4\xf4t', ... , b'w)\r\xf2^\x84\x11w\xbb\xa1\x94\xc1\x8c8XS'] print(out2) # [b'}\xea6+?\xac\x8e\x00\x95jIR\xa3\xd4\xf4t', ... , b'w)\r\xf2^\x84\x11w\xbb\xa1\x94\xc1\x8c8XS'] print(all(out == out2)) # True To compile the bindings and run the script, run python build.py python run.py For large arrays it's about 15x faster (I am a bit disappointed by that honestly...) data = np.arange(100000, dtype=np.uint64) %timeit [hashlib.md5(i).digest() for i in data] 169 ms ± 3.14 ms per loop (mean ± std. dev. of 7 runs, 10 loops each) %timeit md5.md5_array(data) 12.1 ms ± 144 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) If you want to put the bindings in a library and compile them at install time, put the following in your setup.py: setup( ..., setup_requires=["cffi>=1.0.0"], cffi_modules=["package/build.py:ffi"], install_requires=["cffi>=1.0…
score: 11
has comment: http://stackoverflow.com/comment/124263080
downvote count: 1
has comment: http://stackoverflow.com/comment/124088728
has comment: http://stackoverflow.com/comment/105201114
has comment: http://stackoverflow.com/comment/129898374
has comment: http://stackoverflow.com/comment/105201308

http://stackoverflow.com/comment/90646784
comment on: http://stackoverflow.com/a/51845873
has text: My point is either you leave out the line with `set_major_formatter` or the one with `set_xticklabels`. Whatever comes last, overwrites the former.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/51912875
tagged with: pandas
has answer: http://stackoverflow.com/a/51912932
tagged with: python
has title: Lagged Sales for every product
type: AnsweredQuestion
type: Question
accepted answer: http://stackoverflow.com/a/51912932
answer count: 2
possible better answer: http://stackoverflow.com/a/51912919
score: 0
has answer: http://stackoverflow.com/a/51912919
has body: Good Evening, I have the following dataframe: print(dd) dt_op quantity product_code 20/01/18 1 613 21/01/18 8 611 21/01/18 1 613 ... I am trying to get the lagged Sales, but the following code does not compute them by product_code as well: dd["Lagged_Sales"] = [dd.loc[dd['dt_op'].between(d - pd.Timedelta(days = 15), d), 'quantity'].sum() \ for d in dd['dt_op']] I would like to define dd["Lagged_Sales"] as sum of "quantity" sold in the past 15 days, for **every different product in stock; ultimately, for i in "dt_op" and "product_code". print(final_dd) dt_op quantity product_code Lagged Sales 20/01/18 1 613 1 21/01/18 8 611 8 21/01/18 1 613 2 ... Thanks

http://stackoverflow.com/q/51933144
score: 1
has comment: http://stackoverflow.com/comment/90820055
has title: picamera mmal error (One script works vs. another one does not)
upvote count: 1
has comment: http://stackoverflow.com/comment/90817971
type: Question
tagged with: raspberry-pi
tagged with: camera
downvote count: 0
has comment: http://stackoverflow.com/comment/90821773
has comment: http://stackoverflow.com/comment/90821232
favorite count: 0
has comment: http://stackoverflow.com/comment/90819211
has comment: http://stackoverflow.com/comment/90820901
has comment: http://stackoverflow.com/comment/90820163
type: UnansweredQuestion
tagged with: python
has body: So I have two version of taking pics with picamera. This one works when I run. import cameraTrigger as ct from picamera import PiCamera import time n=1 TOTAL_PICS=30 while n &lt;= TOTAL_PICS: img = ct.takePic() n+=1 cameraTrigger.py import time import socket import pickle as p import numpy as np import cv2 from picamera import PiCamera from common import constantSource as cs camera = PiCamera() size = cs.getImageSize() camera.resolution = size def takePic(path=None): if path is not None: start = time.time() camera.capture(path) end = time.time() print("Trigger time: " + str(end-start)) data = None elif path is None: start = time.time() data = np.empty((size[1], size[0], 3), dtype=np.uint8) camera.capture(data, "bgr") end = time.time() print("Trigger time: " + str(end-start)) return data However, this one (an integrated script) does not work. It stops in line 3 (camera = PiCamera()). from picamera import PiCamera import time camera = PiCamera() camera.resolution = (720,560) time.sleep(2.0) n=1 TOTAL_PICS=30 while n &lt;= TOTAL_PICS: img = np.empty((560,720,3),dtype=np.uint8) camera.capture(img,"bgr") n+=1 with this error mmal: mmal_vc_port_enable: failed to enable port vc.null_sink:in:0(OPQV): ENOSPC mmal: mmal_port_enable: failed to enable connected port (vc.null_sink:in:0(OPQV))0x10ad0a0 (ENOSPC) mmal: mmal_connection_enable: output port couldn't be enabled Traceback (most recent call last): File "stereoCalibration_pi.py", line 17, in &lt;module&gt; left = PiCamera() File "/home/pi/.virtualenvs/cv/local/lib/python3.5/site-packages/picamera/camera.py", line 433, in __init__ self._init_preview() File "/home/pi/.virtualenvs/cv/local/lib/python3.5/site-packages/picamera/camera.py", line 513, in _init_preview self, self._camera.outputs[self.CAMERA_PREVIEW_PORT]) File "/home/pi/.virtualenvs/cv/local/lib/python3.5/site-packages/picamera/renderers.py", line 558, in __init__ self.renderer.inputs[0].connect(source).enable() File "/home/pi/.virtualenvs/cv/local/lib/python3.5/…
answer count: 0

http://stackoverflow.com/q/51917930
tagged with: gitlab
tagged with: gitlab-ci
has title: Unable to setup "sphinx" on gitlab-ci
has body: Unable to setup sphinx on gitlab-ci I'm trying to setup and run sphnix on gitlab-ci. It's installed on my local machine and server works fine. But not at gitlab-ci Here's a part of my gitlab-ci: before_script: - apt-get update -qq &amp;&amp; apt-get install -yqq [......] python-pip - pip install sphinx # .......... - bundle exec rake ts:index - bundle exec rake ts:start The output of installing sphinx: $ pip install sphinx Downloading/unpacking sphinx [................] Installing collected packages: sphinx, babel, [.............] Compiling /tmp/pip-build-V2Tzes/Jinja2/jinja2/asyncfilters.py ... File "/tmp/pip-build-V2Tzes/Jinja2/jinja2/asyncfilters.py", line 7 async def auto_to_seq(value): ^ SyntaxError: invalid syntax Compiling /tmp/pip-build-V2Tzes/Jinja2/jinja2/asyncsupport.py ... File "/tmp/pip-build-V2Tzes/Jinja2/jinja2/asyncsupport.py", line 22 async def concat_async(async_gen): ^ SyntaxError: invalid syntax Running setup.py install for MarkupSafe building 'markupsafe._speedups' extension x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fno-strict-aliasing -D_FORTIFY_SOURCE=2 -g -fstack-protector-strong -Wformat -Werror=format-security -fPIC -I/usr/include/python2.7 -c markupsafe/_speedups.c -o build/temp.linux-x86_64-2.7/markupsafe/_speedups.o markupsafe/_speedups.c:12:20: fatal error: Python.h: No such file or directory #include &lt;Python.h&gt; ^ compilation terminated. ========================================================================== WARNING: The C extension could not be compiled, speedups are not enabled. Failure information, if any, is above. Retrying the build without the C extension now. ========================================================================== WARNING: The C extension could not be compiled, speedups are not enabled. Plain-Python installation succeeded. ========================================================================== Successfully installed sphinx babel sphinxcontrib-websupport Jinja2 …
type: UnansweredQuestion
tagged with: python
tagged with: sphinx
has comment: http://stackoverflow.com/comment/90798097
has answer: http://stackoverflow.com/a/51922053
type: Question
tagged with: continuous-integration
answer count: 1
has comment: http://stackoverflow.com/comment/90800295
has comment: http://stackoverflow.com/comment/90801927
score: 0
has comment: http://stackoverflow.com/comment/90801542
has comment: http://stackoverflow.com/comment/90800354

http://stackoverflow.com/a/51930937
has body: Use: d1 = {k: pd.DataFrame(list(zip(*v)), columns=['Start','End']) for k, v in d.items()} df = pd.concat(d1).reset_index(level=1, drop=True) print (df) Start End 871 2018-01-31 2018-02-28 871 2018-02-28 2018-03-31 871 2018-03-31 2018-04-30 872 2018-02-28 2018-03-31 872 2018-03-31 2018-04-30
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/51930669
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51930669
has comment: http://stackoverflow.com/comment/90811841
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/90811814

http://stackoverflow.com/comment/90594189
type: QuestionComment
has text: did you define a function in the first two lines that are not in the code?
comment on: http://stackoverflow.com/q/51820177
score: 0
type: Comment

http://stackoverflow.com/comment/90618630
score: 2
comment on: http://stackoverflow.com/q/51832207
has text: You trying assign array of shape `n` to the column with shape `m`.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51880741
score: 4
answers question: http://stackoverflow.com/q/51879805
type: Answer
has body: You can use the property's fset function: class Child(Parent): @Parent.x.setter def x(self, val): Parent.x.fset(self, val) print('all set')
upvote count: 4
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51879805

http://stackoverflow.com/q/51918305
has body: I am in an intro to programming class which is using zyBooks so I'm not sure (due to the way this interpreter works) if my problem is just me doing something stupid or just not working properly with the zyBooks thing. Its asking me to do a basic user input string. These are the instructions: Assign user_str with a string from user input, with the prompt: 'Enter a string: ' Hint -- Replace the ? in the following code: user_str = ?('Enter a string: ') I believe i've followed the instructions its given me but I'm getting this error. Thanks for any help!!! 1 2 '''Your Solution Goes here ''' 3 user_str = int(input'Enter a string: ')) 4 print() 5 6 print(user_str) The error I'm getting: Exited with return code 1 Traceback (most recent call last): File "main.py", line 3, in <module> user_str = int(input('Enter a string: ')) ValueError: invalid literal for int() with base 10: 'Hello!'
has comment: http://stackoverflow.com/comment/90786614
accepted answer: http://stackoverflow.com/a/51918343
upvote count: 1
tagged with: python
downvote count: 1
possible better answer: http://stackoverflow.com/a/51918663
has comment: http://stackoverflow.com/comment/90786547
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51918343
has title: ValueError with input and int
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/51918663
has comment: http://stackoverflow.com/comment/90786407
favorite count: 0
score: 0

http://stackoverflow.com/q/51909459
score: 0
has body: How to add InDesign special characters like auto-page-numbers to textframes when using Python for scripting InDesign? With JS you could do: aTextFrame.contents = SpecialCharacters.autoPageNumber
tagged with: adobe-indesign
accepted answer: http://stackoverflow.com/a/51927651
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90769619
type: Question
answer count: 1
has comment: http://stackoverflow.com/comment/90769188
has title: How to add special characters while scripting InDesign with Python
has answer: http://stackoverflow.com/a/51927651

http://stackoverflow.com/a/51826253
downvote count: 0
has comment: http://stackoverflow.com/comment/98799657
type: Answer
has comment: http://stackoverflow.com/comment/98805094
score: 2
has body: It is because your file contains NULL characters and that causes the error and it looks like Postgres doesn't allow these characters To solve this problem just remove those bad characters from your file with this simple script. fi = open('shuttle.jpg', 'rb') data = fi.read() fi.close() fo = open('new_shuttle.jpg', 'wb') fo.write(data.replace('\x00', '')) fo.close()
upvote count: 2
answers question: http://stackoverflow.com/q/51826165

http://stackoverflow.com/comment/90706829
type: Comment
type: QuestionComment
score: 0
has text: @NilsWerner The libraries don't give any error per se, in fact the tiff generated by those libraries is a valid file. The problem is that the tool (ASAP) only accepts generic-tiff (with pyramid structure) and throws "Unknown format" error when other tiffs are open with it.
comment on: http://stackoverflow.com/q/51861860

http://stackoverflow.com/comment/90758012
type: QuestionComment
comment on: http://stackoverflow.com/q/51903394
score: 0
has text: To user: Where is my logic wrong? Set a variable to True or False. Then use the not operator on it. Isn't the not operator used when a condition is checked for, but you want the opposite?
type: Comment

http://stackoverflow.com/comment/90647963
type: Comment
has text: [Any use of `__*__` names, in any context, that does not follow explicitly documented use, is subject to breakage without warning.](https://docs.python.org/3/reference/lexical_analysis.html#reserved-classes-of-identifiers)
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51846828

http://stackoverflow.com/q/51890883
has comment: http://stackoverflow.com/comment/90734719
has answer: http://stackoverflow.com/a/51892084
has comment: http://stackoverflow.com/comment/90733743
tagged with: python
has comment: http://stackoverflow.com/comment/90733836
has comment: http://stackoverflow.com/comment/90734933
tagged with: classification
has comment: http://stackoverflow.com/comment/90733541
tagged with: machine-learning
upvote count: 1
has answer: http://stackoverflow.com/a/51892068
type: Question
has body: I have a numpy array like this: [[0. 1. 1. ... 0. 0. 1.] [0. 0. 0. ... 0. 0. 1.] [0. 0. 1. ... 0. 0. 0.] ... [0. 0. 0. ... 0. 0. 1.] [0. 0. 0. ... 0. 0. 1.] [0. 0. 0. ... 1. 0. 1.]] I transform it like this to reduce the memory demand: x_val = x_val.astype(np.int) resulting in this: [[0 1 1 ... 0 0 1] [0 0 0 ... 0 0 1] [0 0 1 ... 0 0 0] ... [0 0 0 ... 0 0 1] [0 0 0 ... 0 0 1] [0 0 0 ... 1 0 1]] However, when I do this: x_val = to_categorical(x_val) I get: in to_categorical categorical = np.zeros((n, num_classes), dtype=np.float32) MemoryError Any ideas why? Ultimately, the numpy array contains the labels for a binary classification problem. So far, I have used it as float32 as is in a Keras ANN and it worked fine and I achieved pretty good performance. So is it actually necessary to run to_categorical?
has title: memory issues when transforming np.array using to_categorical
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51892084
possible better answer: http://stackoverflow.com/a/51892068
has comment: http://stackoverflow.com/comment/90733440
tagged with: numpy
answer count: 2
has comment: http://stackoverflow.com/comment/90732949
downvote count: 0
score: 1
tagged with: keras
favorite count: 0
has comment: http://stackoverflow.com/comment/90732902

http://stackoverflow.com/comment/90706598
has text: @cgohlke The tiff should be tiled and have multiple levels of zoom/magnification like a pyramid. You can get some idea from this description: https://camelyon16.grand-challenge.org/data/
type: QuestionComment
comment on: http://stackoverflow.com/q/51861860
score: 0
type: Comment

http://stackoverflow.com/a/51903225
answers question: http://stackoverflow.com/q/51819834
has comment: http://stackoverflow.com/comment/90832505
has comment: http://stackoverflow.com/comment/90979660
has body: Look at https://www.youtube.com/watch?v=RxqZ_2fz-ZI My speculation: you did not structure correctly your application. Look at video 4 and 5 and you will understand how to structure. a) python file creation with import at the top. so call it application.py and include import gi # gi.require_version('Gtk', '3.0') from gi.repository import Gtk as gtk, Gdk as gdk, GLib, GObject as gobject gobject.threads_init() import string # not used for now import os # not used for now from datetime import datetime, timedelta import time import threading.. b) class GUI (called "foo" in the video) hereunder called GUIclass c) several def linked to the glade file within that class d) init with import of the glade file e) main see few extracts below. look at few applications done with glade / pygtk on github. class GUIclass: # def exit_action(self, widget, data=None): self.exitdialog.show() def exit_confirmed(self, widget, data=None): self.exitdialog.hide() game_not_cancelled = False ... gtk.main_quit() return True def exit_aborted(self, widget, data=None): self.exitdialog.hide() def watch_stop_yes(self, widget, data=None): # def deactivate_event_mode(self, widget, data=None): ... def __init__(self): ... number_of_period = 2 watch_stop_default = True add_time_seconds = 0 # # define all relations between labels and entries and combobox and spinbutton and python variables builder = gtk.Builder() builder.add_from_file("/home/family/glade/scoreboard_uwr_180815.glade") # # load all windows self.controlwindow = builder.get_object("scoreboard_control_window") self.viewwindow = builder.get_object("scoreboard_view_window") self.logdialog = builder.get_object("scoreboard_log_dialog") self.logoffdialog = builder.get_object("scoreboard_logoff_confirm") self.logcanceldialog = builder.get_object("scoreboard_logcancel_confirm") self.resetdialog = builder.get_object("scoreboard_resetconfirm") self.exitdialog = builder.get_object("scoreboard_exitconfirm") # # declaration of all data from the "scoreboard…
score: 0
type: Answer

http://stackoverflow.com/comment/90755367
comment on: http://stackoverflow.com/a/51901919
score: 0
has text: @AChampion thank you for the suggestion made the edit, with due credits :)
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/90646910
type: AnswerComment
has text: Thank you! I'm not necessarily looking for it to be "sorted", but rather, I want to keep the ordering consistent, so this works perfectly. For my own understanding, what does "v for _," do? I'm unfamiliar with that term?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51846719

google-colaboratory
tags question: http://stackoverflow.com/q/51940596
tags question: http://stackoverflow.com/q/51870056
tags question: http://stackoverflow.com/q/51803371
tags question: http://stackoverflow.com/q/51845319
tags question: http://stackoverflow.com/q/51829274
tags question: http://stackoverflow.com/q/51913641
tags question: http://stackoverflow.com/q/51936789
tags question: http://stackoverflow.com/q/51920753
type: Tag
tags question: http://stackoverflow.com/q/51940146
tags question: http://stackoverflow.com/q/51939618
tags question: http://stackoverflow.com/q/51845480
tags question: http://stackoverflow.com/q/51935694
tags question: http://stackoverflow.com/q/51835926
tag name: google-colaboratory

http://stackoverflow.com/comment/90850178
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51949714
type: Comment
has text: This only answers one part of the question and I believe Bear Brown was the first to point to the problem with how `dob` was misspelled. I would call this unethical stealing of the points, @marin.

http://stackoverflow.com/comment/90594716
has text: mydictionary[1] = [variable0[0]]; this line solves the problem. And i referred Python dict as JSON Object. Thanks for notifying the error.
comment on: http://stackoverflow.com/a/51820093
type: Comment
score: 0
type: AnswerComment

pip
tags question: http://stackoverflow.com/q/51813624
tags question: http://stackoverflow.com/q/51833041
tags question: http://stackoverflow.com/q/51921966
tags question: http://stackoverflow.com/q/51842961
tags question: http://stackoverflow.com/q/51864477
tags question: http://stackoverflow.com/q/51934918
tags question: http://stackoverflow.com/q/51915174
tags question: http://stackoverflow.com/q/51873465
tags question: http://stackoverflow.com/q/51915917
tags question: http://stackoverflow.com/q/51921014
tags question: http://stackoverflow.com/q/51880687
tags question: http://stackoverflow.com/q/51881295
tags question: http://stackoverflow.com/q/51821725
tags question: http://stackoverflow.com/q/51826830
tags question: http://stackoverflow.com/q/51883206
tags question: http://stackoverflow.com/q/51912999
tags question: http://stackoverflow.com/q/51902738
tags question: http://stackoverflow.com/q/51912305
tags question: http://stackoverflow.com/q/51887721
tags question: http://stackoverflow.com/q/51826721
tags question: http://stackoverflow.com/q/51813278
tags question: http://stackoverflow.com/q/51807743
tag name: pip
tags question: http://stackoverflow.com/q/51846073
tags question: http://stackoverflow.com/q/51873758
tags question: http://stackoverflow.com/q/51874974
tags question: http://stackoverflow.com/q/51884098
tags question: http://stackoverflow.com/q/51840644
tags question: http://stackoverflow.com/q/51898337
tags question: http://stackoverflow.com/q/51862083
tags question: http://stackoverflow.com/q/51880013
tags question: http://stackoverflow.com/q/51902483
tags question: http://stackoverflow.com/q/51803593
tags question: http://stackoverflow.com/q/51940703
tags question: http://stackoverflow.com/q/51913361
tags question: http://stackoverflow.com/q/51859100
tags question: http://stackoverflow.com/q/51948562
tags question: http://stackoverflow.com/q/51892710
tags question: http://stackoverflow.com/q/51842125
tags question: http://stackoverflow.com/q/51922364
type: Tag
tags question: http://stackoverflow.com/q/51907479
tags question: http://stackoverflow.com/q/51859533
tags question: http://stackoverflow.com/q/51890657
tags question: http://stackoverflow.com/q/51876482
tags question: http://stackoverflow.com/q/51862475
tags question: http://stackoverflow.com/q/51864774
tags question: http://stackoverflow.com/q/51941916
tags question: http://stackoverflow.com/q/51851950
tags question: http://stackoverflow.com/q/51866914
tags question: http://stackoverflow.com/q/51947506
tags question: http://stackoverflow.com/q/51853175
tags question: http://stackoverflow.com/q/51846274
tags question: http://stackoverflow.com/q/51852055
tags question: http://stackoverflow.com/q/51886342

http://stackoverflow.com/q/51845319
type: UnansweredQuestion
score: 1
upvote count: 1
has body: I'm trying to run a theano code on the gpu using google colab but it doesn't work. Here is my code which is picked up from the Tutorial and expected to print out Used the gpu while it is out put is Used the cpu. I used this Stack overflow question to configure gpu in run time mode. Here is my code and it's out put: (Just in case, I have configured my notebook to use the gpu) code: import os os.environ["THEANO_FLAGS"] = "mode=FAST_RUN,device=gpu,floatX=float32" import theano from theano import function, config, shared, tensor import numpy import time vlen = 10 * 30 * 768 # 10 x #cores x # threads per core iters = 1000 rng = numpy.random.RandomState(22) x = shared(numpy.asarray(rng.rand(vlen), config.floatX)) f = function([], tensor.exp(x)) print(f.maker.fgraph.toposort()) t0 = time.time() for i in range(iters): r = f() t1 = time.time() print("Looping %d times took %f seconds" % (iters, t1 - t0)) print("Result is %s" % (r,)) if numpy.any([isinstance(x.op, tensor.Elemwise) and ('Gpu' not in type(x.op).__name__) for x in f.maker.fgraph.toposort()]): print('Used the cpu') else: print('Used the gpu') OUt put: [Elemwise{exp,no_inplace}(&lt;TensorType(float64, vector)&gt;)] Looping 1000 times took 4.432506 seconds Result is [1.23178032 1.61879341 1.52278065 ... 2.20771815 2.29967753 1.62323285] Used the cpu
tagged with: theano
linked to: http://stackoverflow.com/q/33988334
type: Question
downvote count: 0
has title: theano gpu not working on the google colab
tagged with: google-colaboratory
favorite count: 0
tagged with: gpu
has comment: http://stackoverflow.com/comment/95533474
tagged with: python
answer count: 0

http://stackoverflow.com/comment/90870771
comment on: http://stackoverflow.com/a/51954071
score: 0
type: AnswerComment
type: Comment
has text: Very clearly explanation!! I now understand it, thanks again :)

http://stackoverflow.com/q/51911439
downvote count: 1
type: Question
score: 0
has comment: http://stackoverflow.com/comment/90778445
answer count: 1
has answer: http://stackoverflow.com/a/51924579
has title: beautifulsoup - Multiple for for multiple values and how to save them into JSON
favorite count: 0
tagged with: beautifulsoup
has body: I'm using selenium + beautifulsoup. I need to store the data I find, I initially thought of array, but now I'm thinking json might be better, but I have no idea how to write it from what I grab. doc = [] spec = [] for i in range(1, 2): driver.get('https://local.data/doctors/%d' % i) driver.execute_script("$('mark').remove()") time.sleep(3) html = driver.page_source soup = BeautifulSoup(html, 'html.parser') for doctors in soup.find_all('a', attrs={"data-ga-label": "profile_name"}): doc.append(doctors.text) for specialties in soup.find_all('p', attrs={"class": "specialities"}): spec.append(specialties.text.strip()) for cities in soup.find_all('span', class_="city"): c = cities.text.split('-')[0].replace(":", "") print(c) Instead of writing an array for it, I'd like to write a single json entry for all the values I found on the doctor, specialties and cities. So that would be something like: { doctor_name: "john hopkins", specialty: "surgeon", city: "new york" } for each of the values I grab with beautifulsoup. How can I do that?
type: UnansweredQuestion
tagged with: python
tagged with: selenium
upvote count: 1

http://stackoverflow.com/comment/90725777
has text: Hi @Josef, I followed through your recommendation and it seems to be working. Still have some questions, I wonder if you can help me. I edited my question with updated information and as you can see, I had to set `initial_state` to zero and `state_shocks` to a normal. Do you know why this is necessary or what it means? I followed the unit tests and it seems to be working but don't quite understand why.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51881148
score: 0

http://stackoverflow.com/comment/90617566
has text: What if original lists contain duplicates?
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51831706
score: 1

http://stackoverflow.com/comment/90668581
type: Comment
type: QuestionComment
has text: @NamsuKhan I didn't follow any tutorials because I did not found any. The graph presented was drawn manually.
comment on: http://stackoverflow.com/q/51857910
score: 0

http://stackoverflow.com/q/51869434
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90708349
has comment: http://stackoverflow.com/comment/90691926
type: Question
has answer: http://stackoverflow.com/a/51881758
answer count: 1
tagged with: url
favorite count: 0
score: 0
tagged with: http://stackoverflow.com/tag/html
accepted answer: http://stackoverflow.com/a/51881758
has body: So I have been trying to access a project post that I have created for my website, but every time I click on it the url can't be found. I am not sure why. My code is below: mywebsite/urls.py from django.contrib import admin from django.urls import re_path, include from django.conf import settings from django.conf.urls.static import static #re_path(r'^admin/', admin.site.urls), urlpatterns = [ re_path(r'^admin/', admin.site.urls), re_path(r'^', include('home.urls')), re_path(r'^projects/', include('projects.urls', namespace="create_post")), re_path(r'^contact/', include('contact.urls')), ] projects/urls.py from django.urls import re_path, include from . import views # urls for projects page app_name = 'create_post' urlpatterns = [ re_path(r'^$', views.retrieve_projects, name="retrieve_projects"), #re_path(r'^create/$', views.CreateProjectsView.as_view(), name="create_projects"), re_path(r'^create/$', views.CreateProjectsView.as_view(), name="create_projects"), re_path(r'^(?P<slug>[\w-]+)/$', views.details_of_project, name="details_of_project"), re_path(r'^(?P<slug>[\w-]+)/update/$', views.update_projects, name="update_projects"), re_path(r'^(?P<slug>[\w-]+)/delete/$', views.delete_projects, name="delete_projects"), ] # To make images work if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) projects/views.py # Function to retrieve all different projects def retrieve_projects(request): # Retrieves objects based on latest publish date projects_list = Projects.objects.all().order_by("-publish_date") context = { 'projects_list': projects_list, } return render(request, 'projects/projects.html', context) projects/projects.html asdasdasdasdasdasdas {% if projects_list %} {% for project in projects_list %} {{project.title}} {{project.description}} {{ project.publish_date }} {% endfor %} {% endif %} The error returns page not found
tagged with: django
upvote count: 1
tagged with: python
has title: Django url page not found
downvote count: 1

http://stackoverflow.com/comment/91274955
has text: @MelvynSopacua I want to do **logging**. You say "without an exception there's no python backtrace.". Are you sure there is no way?
score: 0
comment on: http://stackoverflow.com/q/51873708
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51879805
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/77850988
has comment: http://stackoverflow.com/comment/90748628
upvote count: 7
type: Question
score: 7
has comment: http://stackoverflow.com/comment/90748578
has body: I have a situation where I am overriding just the setter on a property: class Parent: @property def x(self): return self.__dict__['x'] @x.setter def x(self, val): self.__dict__['x'] = f'P{val}' class Child(Parent): @Parent.x.setter def x(self, val): super().x = val print('all set') Here, the print statement represents the processing I want to do after invoking the parent's setter. You can just ignore it. super().x = y is my native attempt at invoking said setter. It fails with Attribute error: 'super' object has no attribute 'x' What is the correct way to use the property setter from the parent class in the child? I'd prefer to avoid the following, even though it works just fine, since it involves explicitly calling dunder methods: Parent.x.__set__(self, val) As a bonus, is there any way to use super() in the body of the child's setter?
has comment: http://stackoverflow.com/comment/90711343
answer count: 2
has title: Use parent property setter when overriding in child class
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/51880741
tagged with: python-3.x
linked to: http://stackoverflow.com/q/77728680
accepted answer: http://stackoverflow.com/a/51880741
tagged with: python
possible better answer: http://stackoverflow.com/a/77850988
has comment: http://stackoverflow.com/comment/90712625

http://stackoverflow.com/comment/90719646
type: Comment
comment on: http://stackoverflow.com/a/51880117
has text: @mattalxndr, added another edit to the answer with suggested solution.
score: 0
type: AnswerComment

http://stackoverflow.com/a/51904231
downvote count: 0
answers question: http://stackoverflow.com/q/51904141
has body: Instead of using cursor.fetchall(), storing all the data in the client side, you should use an SSCursor to leave the result set on the server side: import pymysql import pymysql.cursors as cursors conn = pymysql.connect(..., cursorclass=cursors.SSCursor) so that you can fetch the rows one by one: cursor = conn.cursor() cursor.execute('SELECT UserId, Username, Type FROM Users') for db_user in cursor: user_details = User() user_details.name = db_user[1] user_details.type = db_user[2] ... And depending on what you want to do with the all_users dict, you may not need to store all user info in a dict either. If you can process each user one by one, do it directly inside the for loop above instead of building up a huge dict.
type: Answer
score: 1
upvote count: 1

querying
type: Tag
tag name: querying
tags question: http://stackoverflow.com/q/51826748

http://stackoverflow.com/a/51857680
score: 0
answers question: http://stackoverflow.com/q/51849509
has body: I don't know why do you need to do such replacing, but let's imagine that you have the strings above as templates. In that case I would suggest that you do formatting (str.format()), not replacing. Here is how would your code look like: new_name = 'MeshNew' l = ['{name}.vtx{{12}}', '{name}.vtx{{13}}'] formatted = [s.format(name=new_name) for s in l] print(','.join(formatted)) Note that curly braces need to be repeated when using format() function.
type: Answer

http://stackoverflow.com/a/51916530
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51916321
has body: Change the URL to https://api.ipify.org?format=json and your code would work. Alternatively, you can still use the https://api.ipify.org URL, but since it outputs the IP directly, you should skip the JSON parsing and return render(request, 'catalog/home.html', {'ip': response.content}) instead.
type: Answer
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/90783314
has comment: http://stackoverflow.com/comment/90783661
has comment: http://stackoverflow.com/comment/90783507
answers question: http://stackoverflow.com/q/51916321
has comment: http://stackoverflow.com/comment/90783200

http://stackoverflow.com/comment/90763587
has text: the .xticks line is still getting invalid syntax
comment on: http://stackoverflow.com/q/51906522
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/51899452
favorite count: 0
has body: I´m using some library using ctypes. This library has its own methods to handle heap memory, so in C i would do something like this: #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include "intcall.h" int main(void) { long status = -1; char host[10] = "xx.x.x.xx"; char user[7] = "xxxxxx"; char pass[7] = "xxxxxx"; char acc[10] = "xxxxxxxxx"; long sess = ic_universe_session(host, user, pass, acc, &amp;status, NULL); if (status == 0) { char sub_name[14] = "PRUEBA_XXXXXX"; long sub_name_len = 13; unsigned char param1_txt[5] = "AAAA"; long size1 = 5; long num_params = 2; //void * FAR PASCAL ic_malloc ic_proto((LPLONG)); char* param1 = ic_malloc(&amp;size1); memcpy(param1, param1_txt, size1); /* typedef struct icstring { long len; unsigned char * text; } ICSTRING; */ ICSTRING icstr1; icstr1.len = size1; icstr1.text = param1; ICSTRING icstr2; icstr2.len = 0; ic_subcall(sub_name, &amp;sub_name_len, &amp;status, &amp;num_params, &amp;icstr1, &amp;icstr2); //void FAR PASCAL ic_free ic_proto((void *)); ic_free(icstr1.text); ic_free(icstr2.text); } return EXIT_SUCCESS; } The library can free and remalloc the pointer I passed to it so this is why I need to free icstr1.text and not param1, the return pointer from ic_malloc. In python a similar example would be like this: subrutina = 'PRUEBA_XXXXXX' argumento = 'AAAA' num_params = 2 argumentos_tipo = [c_char_p, POINTER(c_long), POINTER(c_long), POINTER(c_long)] self.__U2_C_INTERFACE.ic_calloc.argtypes = [POINTER(c_long)] self.__U2_C_INTERFACE.ic_free.argtypes = [ctypes.c_voidp] self.__U2_C_INTERFACE.ic_subcall.argtypes = argumentos_tipo sub_name_in = c_char_p(bytes(subrutina, self.__sistema_codificacion)) sub_name_len_in = c_long(len(subrutina)) num_params_len_in = c_long(num_params) code = c_long(0) p_in = [None] * num_params mem_alloc = [c_char_p(0)] * num_params byte_param = bytes(argumento, self.__sistema_codificacion) byte_size = len(byte_param) p_in[0] = ICString(c_long(0)) p_in[0].len = c_long(…
tagged with: memory-leaks
score: 1
tagged with: python-3.x
has title: Possible memory leak with ctypes
answer count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
type: Question
tagged with: ctypes
downvote count: 0

http://stackoverflow.com/comment/90848027
comment on: http://stackoverflow.com/q/51949122
has text: You using python 3. Right?
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/90852840
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51942309
has text: @ddd Yes, somehow. So if you are using the third method, all warnings inside the with block will be ignored. This means, that you can just wrap this block around the `keras` code which generates the warnings. Then only these will be ignored.
score: 0

http://stackoverflow.com/q/51933936
tagged with: python
has answer: http://stackoverflow.com/a/51934279
accepted answer: http://stackoverflow.com/a/51934279
has comment: http://stackoverflow.com/comment/90818500
has title: Python 3.6 type checking: numpy arrays and use defined classes
has comment: http://stackoverflow.com/comment/90818515
type: AnsweredQuestion
type: Question
has body: I'd think this has already been asked, but I can't find it How can one check for non-builtin types in Python 3.6? For example, let's say I want to have a function foo() that takes a numpy array as an arg, and returns an instance of my class Bah def foo(a: np.array) -&gt; Bah Can I do something like this? How do I add those types to checking?
possible better answer: http://stackoverflow.com/a/51934435
upvote count: 6
favorite count: 0
answer count: 3
tagged with: python-typing
has answer: http://stackoverflow.com/a/51934435
has answer: http://stackoverflow.com/a/51934147
downvote count: 0
score: 6

http://stackoverflow.com/a/51866826
downvote count: 0
has body: From the PostgreSQL Manual: COPY naming a file or command is only allowed to database superusers, since it allows reading or writing any file that the server has privileges to access. So the PostgreSQL user doing the copying must be a database superuser. You can do this with the ALTER ROLE command: ALTER ROLE &lt;rolename&gt; WITH SUPERUSER Also: COPY with a file name instructs the PostgreSQL server to directly read from or write to a file. The file must be accessible by the PostgreSQL user (the user ID the server runs as) and the name must be specified from the viewpoint of the server. ... Files named in a COPY command are read or written directly by the server, not by the client application. Therefore, they must reside on or be accessible to the database server machine, not the client. The default system user that PostgreSQL runs on is postgres. Ensure that that user has access to the files you want to copy. You can test this by using the command sudo -i -u postgres to become the postgres user and then trying to view the files.
type: Answer
answers question: http://stackoverflow.com/q/51850512
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/90716724

http://stackoverflow.com/q/51944179
upvote count: 1
type: Question
linked to: http://stackoverflow.com/q/44521931
downvote count: 0
linked to: http://stackoverflow.com/q/1050222
has comment: http://stackoverflow.com/comment/90838596
answer count: 1
has comment: http://stackoverflow.com/comment/90838109
favorite count: 0
has comment: http://stackoverflow.com/comment/90839145
type: UnansweredQuestion
tagged with: multithreading
has comment: http://stackoverflow.com/comment/90838816
has comment: http://stackoverflow.com/comment/90839469
tagged with: python
has comment: http://stackoverflow.com/comment/90838215
has answer: http://stackoverflow.com/a/51944397
has comment: http://stackoverflow.com/comment/90838362
score: 1
has title: Multi threading code which doesn't act like multi threading?
has body: I have the following code (Python 2.7): from concurrent.futures import ThreadPoolExecutor, as_completed from multiprocessing import cpu_count NUM_WORKERS = cpu_count() c = 0 while True: results = [] pages = [i for i in range(c, c + NUM_WORKERS)] with ThreadPoolExecutor(NUM_WORKERS) as executor: futures = [executor.submit(bro.get_content, page) for page in pages] for future in as_completed(futures): results.extend(future.result()) if len(results) &lt; 1: break print("Get batch {0} with {1} results".format(c, len(results))) df = DataFrame(results) df.to_sql(sql_table_stage, engine, sql_schema, if_exists='append', index=False) print("Pages {0} to {1} was insert".format(c, c + NUM_WORKERS)) c += NUM_WORKERS The code runs and the action is executed as expected (Tough incredibly slow!). The thing is that when I look over my logs I see: [2018-08-21 01:06:54,513] {base_task_runner.py:98} INFO - Subtask: [2018-08-21 01:06:54,513] {bash_operator.py:70} INFO - Tmp dir root location: [2018-08-21 01:06:54,513] {base_task_runner.py:98} INFO - Subtask: /tmp [2018-08-21 01:06:54,514] {base_task_runner.py:98} INFO - Subtask: [2018-08-21 01:06:54,514] {bash_operator.py:80} INFO - Temporary script location: /tmp/airflowtmpGyRCX2//tmp/airflowtmpGyRCX2/importwQaRgB [2018-08-21 01:06:54,514] {base_task_runner.py:98} INFO - Subtask: [2018-08-21 01:06:54,514] {bash_operator.py:88} INFO - Running command: python /home/ubuntu/airflow/scripts/import.py [2018-08-21 01:06:54,519] {base_task_runner.py:98} INFO - Subtask: [2018-08-21 01:06:54,518] {bash_operator.py:97} INFO - Output: [2018-08-21 05:45:48,758] {base_task_runner.py:98} INFO - Subtask: [2018-08-21 05:45:48,758] {bash_operator.py:101} INFO - Get batch 0 with 20000 results [2018-08-21 05:45:48,759] {base_task_runner.py:98} INFO - Subtask: [2018-08-21 05:45:48,758] {bash_operator.py:101} INFO - Pages 0 to 4 was insert [2018-08-21 05:45:48,759] {base_task_runner.py:98} INFO - Subtask: [2018-08-21 05:45:48,758] {bash_operator.py:101} INF…

http://stackoverflow.com/comment/90600913
type: QuestionComment
comment on: http://stackoverflow.com/q/51819259
score: 0
has text: Try the following on the Python prompt (but *not* in the meshpy source directory): `import meshpy; print(meshpy.__path__); print(meshpy.__file__)` (replace `;` by <enter> as wanted). That should show what meshpy module/package you're actually trying to import.
type: Comment

http://stackoverflow.com/comment/90760862
type: Comment
type: QuestionComment
has text: @wwii The weird thing here is, it might be surprising that you have to use a different access pattern for default argument. The equivalent writing of the above code is to check `arg1` in the method body and assign with `Foo.bar` if it's empty. However if you are writing this as a default argument, then you have discard the quantifier `Foo.`.
score: 0
comment on: http://stackoverflow.com/q/51904950

http://stackoverflow.com/a/51922003
has comment: http://stackoverflow.com/comment/90793937
accepted answer of: http://stackoverflow.com/q/51921949
type: Answer
has comment: http://stackoverflow.com/comment/90795000
upvote count: 1
has comment: http://stackoverflow.com/comment/90794231
score: 1
has body: I think you are making this more difficult than necessary. Instead of the for loop, you can do print(data) Or if you want each dictionary from the list to be on its own line, instead of print(','.join(result.values())) Just do print(result)
has comment: http://stackoverflow.com/comment/90793727
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90793888
answers question: http://stackoverflow.com/q/51921949
has comment: http://stackoverflow.com/comment/90793853

http://stackoverflow.com/q/51824188
score: 0
has title: Creating a dataset in the form of two half semi circle arcs in python
tagged with: python
has answer: http://stackoverflow.com/a/51824687
favorite count: 0
upvote count: 2
downvote count: 2
has body: There are two semi-circles of width thk with inner radius rad, separated by sep as shown (red is -1 and blue is + 1). The center of the top semi-circle is aligned with the middle of the edge of the bottom semi-circle. This task is linearly separable when sep &gt;= 0, and not so for sep &lt;0. Set rad = 10, thk = 5 and sep = 5 . Then, generate 2,000 examples uniformly, which means you will have approximately 1,000 examples for each class. Figure Describing the problem: Can someone help me in generating such a dataset?
type: AnsweredQuestion
tagged with: matplotlib
accepted answer: http://stackoverflow.com/a/51824687
type: Question
answer count: 1
tagged with: dataset

http://stackoverflow.com/comment/90803797
has text: @Marlin, check updated answer. I hope that solve your problem=)
type: AnswerComment
comment on: http://stackoverflow.com/a/51907922
score: 0
type: Comment

http://stackoverflow.com/q/51810322
score: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/51810664
type: Question
has comment: http://stackoverflow.com/comment/90576273
tagged with: python
has title: Pandas loc is returning series not df
has comment: http://stackoverflow.com/comment/90575727
upvote count: 2
has comment: http://stackoverflow.com/comment/90576045
has body: The following code returns a series for y when I want a df. Ultimately I am pulling rows out of a larger raw df (df) to create a smaller df (Cand) of results. I have created Cand as the new empty df to be populated. Cand = pd.DataFrame(columns=['SR','Hits','Breaks']) x = df.loc[df['Breaks'] == 0] y = x.loc[x['Hits'].idxmax()] Cand.append(y) x is correctly reflected as a df, but y becomes a series and so does not populate Cand. I have looked around but cannot find a similar problem. Thanks in advance.
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/90576582
has answer: http://stackoverflow.com/a/51810664
has comment: http://stackoverflow.com/comment/90576139
tagged with: pandas
type: AnsweredQuestion

http://stackoverflow.com/a/51864376
score: 6
answers question: http://stackoverflow.com/q/51864326
upvote count: 6
has comment: http://stackoverflow.com/comment/90680974
has comment: http://stackoverflow.com/comment/90680942
has body: Same as you'd do with the standard regex, using the i flag. df = df.replace('(?i)Number', 'NewWord', regex=True) Granted, df.replace is limiting in the sense that flags must be passed as part of the regex string (rather than flags). If this was using str.replace, you could've used case=False or flags=re.IGNORECASE.
has comment: http://stackoverflow.com/comment/120906925
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/90680953

http://stackoverflow.com/comment/90683693
has text: I see why you asked, I forgot I renamed this class to `SocketComm` from `Communicate`, and when I did that I did not refactor the class name in the commented example. It is fixed now.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51865497

http://stackoverflow.com/q/51798993
tagged with: celery
type: Question
upvote count: 2
has title: Python + Celery + SQLAlchemy(sqlite) -> does not work as expected
has comment: http://stackoverflow.com/comment/90555686
tagged with: sqlite
downvote count: 0
favorite count: 0
has body: i currently have problems running celery or celery-worker in with SQLAlchemy problably (sqlite memory db). Here is my simple setup: proj/db.py: (simple db with sqlalchemy and scoped_sessions) from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session from sqlalchemy.orm import sessionmaker from sqlalchemy import Column, Integer, String from sqlalchemy.ext.declarative import declarative_base engine = create_engine('sqlite:///:memory:', convert_unicode=True, pool_recycle=3600, pool_size=10, echo=False) db_session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=engine)) Base = declarative_base() class User(Base): __tablename__ = 'users' id = Column(Integer, primary_key=True) name = Column(String) fullname = Column(String) password = Column(String) def __repr__(self): return "&lt;User(name='%s', fullname='%s', password='%s')&gt;" % (self.name, self.fullname, self.password) Base.metadata.create_all(engine) proj/celery.py (celery config, including proj.tasks) from __future__ import absolute_import from celery import Celery import config celery = Celery('app', broker='redis://{}:{}/{}'.format(config.R_HOST, config.R_PORT, config.R_DB), backend='redis://{}:{}/{}'.format(config.R_HOST, config.R_PORT, config.R_DB), include=["proj.tasks"]) if __name__ == '__main__': celery.start() proj/tasks.py (simple tasks to read and write to db) from __future__ import absolute_import from proj.celery import celery from proj.db import db_session, User from celery import Task class SqlAlchemyTask(Task): abstract = True def after_return(self, status, retval, task_id, args, kwargs, einfo): db_session.remove() @celery.task(base=SqlAlchemyTask) def setdb(): u = User(id=10, name="NAME", fullname="FULL", password="PASS") db_session.add(u) db_session.commit() print("INSERT") @celery.task(base=SqlAlchemyTask) def get_from_db(): print(db_session.query(User).all()) config.py (config-file) R_HOST = "127.0.0.1" R_PORT = 6379 R_DB = 0 run.py (the file that is exe…
type: UnansweredQuestion
tagged with: python
score: 2
answer count: 0
tagged with: sqlalchemy

performance
tags question: http://stackoverflow.com/q/51932428
tags question: http://stackoverflow.com/q/51867433
tags question: http://stackoverflow.com/q/51856120
tags question: http://stackoverflow.com/q/51929446
tags question: http://stackoverflow.com/q/51869268
tags question: http://stackoverflow.com/q/51934227
tags question: http://stackoverflow.com/q/51874355
tags question: http://stackoverflow.com/q/51860382
tags question: http://stackoverflow.com/q/51804034
tags question: http://stackoverflow.com/q/51900138
tags question: http://stackoverflow.com/q/51903350
tags question: http://stackoverflow.com/q/51828752
tags question: http://stackoverflow.com/q/51913145
tags question: http://stackoverflow.com/q/51919344
tags question: http://stackoverflow.com/q/51947860
tags question: http://stackoverflow.com/q/51806731
tags question: http://stackoverflow.com/q/51837387
tag name: performance
tags question: http://stackoverflow.com/q/51911197
type: Tag
tags question: http://stackoverflow.com/q/51856333
tags question: http://stackoverflow.com/q/51897251
tags question: http://stackoverflow.com/q/51804537
tags question: http://stackoverflow.com/q/51923891

http://stackoverflow.com/comment/90754633
score: 0
comment on: http://stackoverflow.com/q/51901676
type: Comment
has text: Try this [lib](https://docs.python.org/3/library/inspect.html) for retrieving the interpreter stack.
type: QuestionComment

cd
tag name: cd
tags question: http://stackoverflow.com/q/51886429
tags question: http://stackoverflow.com/q/51896866
type: Tag

http://stackoverflow.com/q/51887104
tagged with: http://stackoverflow.com/tag/json
has answer: http://stackoverflow.com/a/51887160
type: Question
accepted answer: http://stackoverflow.com/a/51887160
has title: How to format JSON data to have commas?
has body: I have a chat bot that displays information from a call to an API. def btcChange(bot, update): """Send a message when the command /btc24 is issued.""" btcChangeCallJson = requests.get("https://min-api.cryptocompare.com/data/pricemultifull?fsyms=BTC&amp;tsyms=USD,EUR").json() btcChange = btcChangeCallJson['RAW']['BTC']['USD']['CHANGE24HOUR'] btcVol = btcChangeCallJson ['RAW']['BTC']['USD']['TOTALVOLUME24HTO'] btcPrice = btcChangeCallJson ['RAW']['BTC']['USD']['PRICE'] update.message.reply_text("Price change over 24H: $" + str (btcChange)+ " Volume for 24 hours : ${}".format(btcVol)+ " The price of the coin is: ${}".format(btcPrice)) I would like to display the following information more clearly: Having it break and skip to the next line Have (btcChange), (btcVol), (btcPrice) proper commas like 100,000.
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-3.x
upvote count: 1
tagged with: python
type: AnsweredQuestion
score: 1

http://stackoverflow.com/comment/90831192
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51940520
has text: perfect. thanks so much
type: Comment

http://stackoverflow.com/a/51852000
answers question: http://stackoverflow.com/q/51851867
upvote count: 2
has body: From the point-of-view of iteration, there is no difference, since the iter method returns the same type of iterator for both. This makes sense since viewkeys returns a view: &gt;&gt;&gt; d = {} &gt;&gt;&gt; iter(d.viewkeys()) &lt;dictionary-keyiterator object at 0x102567cb0&gt; &gt;&gt;&gt; iter(d) &lt;dictionary-keyiterator object at 0x102567d08&gt; &gt;&gt;&gt; The only difference is the small, constant-time overhead of creating the view object. .viewkeys is useful if you want the set-like behavior, e.g.: &gt;&gt;&gt; d1 = {'a':1,'b':2} &gt;&gt;&gt; d2 = {'a':2, 'b':1, 'c':3} &gt;&gt;&gt; d1.viewkeys() | d2.viewkeys() set(['a', 'c', 'b']) &gt;&gt;&gt; If you want to iterate over the keys of a dictionary, just iterate over the dictionary directly.
type: AcceptedAnswer
type: Answer
score: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51851867

http://stackoverflow.com/comment/90777803
has text: You're right that `else: pass` can be removed entirely—and it almost always should be. You're also right that an `if …: pass` can always be rewritten as `if not …:` to swap the `if` and `else` bits (at which point you can remove the `else: pass`), and _often_ it should be—but sometimes it just reads better with the positive condition instead of the negative one, and if your condition is pushing the bounds of easy readability, that small difference can be worth it.
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/51913755

http://stackoverflow.com/q/51916094
has body: I am trying to create a program that references data from many Excel files. So this program should turn the Excel file on and off multiple times. Initially it was made using win32com.client.Dispatch("Excel.Application").Workbooks.Open("fileaddress") and close() but, error TypeError: 'bool' object is not callable was occurred. So I used the 'with' statement. with excel.Workbooks.Open("file_address"+"file_name") as c_wb: Then an error occurred after the file was turned on. AttributeError: __enter__ How can this be solved?
favorite count: 0
has comment: http://stackoverflow.com/comment/90787135
has comment: http://stackoverflow.com/comment/90821418
has comment: http://stackoverflow.com/comment/90796686
answer count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
downvote count: 1
tagged with: excel
has comment: http://stackoverflow.com/comment/90788937
has comment: http://stackoverflow.com/comment/90786277
has title: I'm making Programs that open and close Excel files sequentially in sequence
has comment: http://stackoverflow.com/comment/90794860
tagged with: anaconda
has comment: http://stackoverflow.com/comment/90788929
has comment: http://stackoverflow.com/comment/90788797
type: Question
has comment: http://stackoverflow.com/comment/90787650
score: 0
has comment: http://stackoverflow.com/comment/90795207
has comment: http://stackoverflow.com/comment/90811467

http://stackoverflow.com/comment/90856234
type: QuestionComment
comment on: http://stackoverflow.com/q/51952860
score: 0
has text: You are passing a `list` not a `str`... you even have comments that say you are aware of this... although you say "array" (when it is really a `list)`. As an aside, `[character for character in string]` is a verbose way of saying `list(string)`
type: Comment

http://stackoverflow.com/comment/90648664
score: 0
comment on: http://stackoverflow.com/a/51847211
type: Comment
has text: I'm just wondering now: won't adding a column to an otherwise huge df add unnecessary strain om my working memory?
type: AnswerComment

http://stackoverflow.com/q/51956181
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/62945088
score: 0
linked to: http://stackoverflow.com/q/49685923
has body: I have a few queries regarding the Tensorflow Object Detection API. While training, only the previous 5 check-points are stored. I want to store more than that, say the previous 10 check points. How can this be done? (I think it should be one of the parameters of train.proto in object_detection/protos.) By default, the check points are stored every 10 minutes (600 seconds). To change this frequency, I believe it is one of these two parameters that have to be changed, please confirm which one it is: from learning.py in /home/user/tensorflow-gpu/lib/python3.5/site-packages/tensorflow/contrib/slim/python/slim save_summaries_secs=600 or save_interval_secs=600 While training my model (ssd_mobilenet_v2_coco_2018_03_29), I also run the evaluation simultaneously. The latest checkpoint represented in the eval graph always lags the latest one saved in object_detection/training folder. For example, in the case below, the latest checkpoint shown on graph is 29.437k, while the model is already trained till the checkpoint 32.891k (and saved in the training folder). What is the reason for this lag (20 minutes lag) Why isn't one step (10 minutes) enough to perform evaluation on the trained model?
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52021572
tagged with: python
tagged with: object-detection
has title: Queries regarding checkpoints of Object Detection API
tagged with: object-detection-api
has comment: http://stackoverflow.com/comment/111629039
tagged with: image-processing
has comment: http://stackoverflow.com/comment/90993538
tagged with: tensorflow

http://stackoverflow.com/comment/90844209
has text: Problem with the edit is that it just chucks out 50 results but I want the top 50 sessions for EACH landing page. Unfortunately this edit limits it to the top 50 sessions overall which just stops at the first landing page
type: Comment
comment on: http://stackoverflow.com/a/51947104
score: 0
type: AnswerComment

http://stackoverflow.com/a/51846531
type: Answer
answers question: http://stackoverflow.com/q/51846229
score: 0
has body: Change the next template tag: {% load staticfiles %} for: {% load static %}

http://stackoverflow.com/comment/90753496
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51901068
has text: Sorry I didn't make it clear. A 'NaN' would be good.
type: Comment

http://stackoverflow.com/q/51912599
has title: Get records for a list of multiple entities on Wikidata
tagged with: python
tagged with: sparql
type: AnsweredQuestion
score: 3
downvote count: 0
accepted answer: http://stackoverflow.com/a/51913045
tagged with: pseudocode
type: Question
has answer: http://stackoverflow.com/a/51913045
has comment: http://stackoverflow.com/comment/90780397
has body: I am mapping multiple entities (Q entries) in Wikidata for which I need the same record of properties (P entries). For sake of this question, say I have a list of five Wikidata entities (Q1, Q2, Q3, Q4, Q5) for which I want to retrieve the same property records (say, P1, P2, and P3). I know all Q and P in advance. I understand how to pose a SPARQL query for an individual record (say for Q1), and I also understand how to specify the return of labels using the special SERVICE wikibase:label function for P1, P2, and P3. First question, is there a way to loop over a list of entities (Q1 to Q5) with a given SPARQL query using only SPARQL? If the answer is No, does any example Python or pseudocode exist for issuing single SPARQL queries looping over a list of external identifiers (Q1 to Q5), say provided as an external text or CSV file? If there is a simple way to approach this, I'd love to hear.
upvote count: 3
has comment: http://stackoverflow.com/comment/90789116
tagged with: records
tagged with: wikidata
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/90868812
has text: When you update to cx_Oracle 6, note that cx_Oracle installation is significantly different, and also that macOS SIP means DYLD_LIBRARY_PATH isn't useful. See https://cx-oracle.readthedocs.io/en/latest/installation.html#installing-cx-oracle-on-macos
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51957803

http://stackoverflow.com/q/51932504
tagged with: tensorflow
type: Question
score: 0
tagged with: keras-layer
has body: I have an input layer of size 32x32. Then I apply a 2d convolution with stride (4,4) and with 16 filters each having kernel size 4x4. Hence, the resulting shape will be 8 x 8 x 16. Now I want to reshape the result back to the input shape so that the channel dimension will turn back into 4x4 squares in the corresponding places, i.e. if we define the result of the convolution as T and the desired result as D, then I want D[i * 4 + k, j * 4 + l] = T [i , j , k * 8 + l], with i,j = 0,..,7 and k,l = 0,..,3. Is there a way to do this? import numpy as np from keras.layers import Input, Conv2D from keras.initializers import Constant input = Input(( 32, 32), dtype = 'float32') filters = np.ndarray((4, 4, 16), dtype=np.float32) # Initialization of the filter filter_layer = Conv2D(16, 4, strides =(4,4), kernel_initialzer=Constant(filters), trainable = False)(input) # no idea how to reshape the filter back
tagged with: keras
has comment: http://stackoverflow.com/comment/91463920
has title: Keras: how to reshape last channel into squares
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90817156
tagged with: python
answer count: 0

http://stackoverflow.com/q/51868926
has comment: http://stackoverflow.com/comment/90689733
type: Question
tagged with: upstart
score: 0
has answer: http://stackoverflow.com/a/51869214
answer count: 1
has title: Why upstart service does not stop when sys.exit is called by Python
tagged with: system-services
tagged with: linux
tagged with: python
has body: I set up a Python application as a Linux service using Upstart script. description "AAE client app" start on runlevel [2345] stop on runlevel [!2345] respawn env PATH=/home/ec2-user/aae_client/env/bin env PROGRAM_NAME="aae" env USERNAME="ec2-user" # Main script to be run script echo "[`date -u +%Y-%m-%dT%T.%3NZ`] (sys) Ready to run..." &gt;&gt; /var/log/$PROGRAM_NAME.sys.log export HOME="/home/ec2-user" echo $$ &gt; /var/run/$PROGRAM_NAME.pid cd /home/ec2-user/aae_client exec python -m app.run &gt;&gt; /var/log/$PROGRAM_NAME.sys.log 2&gt;&amp;1 end script I want to stop the service when sys.exit is called inside the python code due to some exception being caught. if not config_path: logger.error('Environment variable AAE_CLIENT_CONFIG_PATH is not set') sys.exit() As it turns out, sys.exit did terminate the current process, but somehow the service keeps getting respawned. If I run status [service] again and again, it would show the service running every time with a new PID. Is there a way to kill the service completely within the code?
accepted answer: http://stackoverflow.com/a/51869214
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90689763

http://stackoverflow.com/a/51848647
has body: Personally I prefer gevent, bottle or Flask, and some front end framework like bootstrap or framework7. Gevent easily makes it asynchronous and has websockets built right in, and bottle is the easiest (and fastest) way to build a web app or api.
type: Answer
has comment: http://stackoverflow.com/comment/90652143
score: 1
downvote count: 1
accepted answer of: http://stackoverflow.com/q/51848143
upvote count: 2
answers question: http://stackoverflow.com/q/51848143
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90651495

http://stackoverflow.com/q/51866914
answer count: 4
score: 2
has comment: http://stackoverflow.com/comment/90685895
upvote count: 2
tagged with: pip
has answer: http://stackoverflow.com/a/51868188
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51866942
type: Question
has answer: http://stackoverflow.com/a/51866940
accepted answer: http://stackoverflow.com/a/51866986
linked to: http://stackoverflow.com/q/2812520
has title: How to install pip packages to specific Python version?
downvote count: 0
has answer: http://stackoverflow.com/a/51866942
favorite count: 0
has answer: http://stackoverflow.com/a/51866986
has body: I have Python 3.7 and Python 3.6. How to I chose to which version of Python I want my PIP packages?
tagged with: python

http://stackoverflow.com/q/51880972
has body: I have a 36 rows x 36 columns dataframe of pivot table which I transform using code below: df_pivoted = pd.pivot_table(df,index='From',columns='To',values='count') df_pivoted.fillna(0,inplace=True) I transpose the same dataframe using this code: df_trans = df_pivoted.transpose() and want to substract those two dataframes with this code: new_pivoted = df_pivoted - df_trans It gives me 72 rows x 72 columns dataframe with NaN value in all cell. Then I try to use other code: delta = df_pivoted.subtract(df_trans, fill_value=0) However, it yields 72 rows x 72 columns with dataframe that looks like this: Please help me to find the difference between the original dataframe with the transpose dataframe.
score: 2
tagged with: dataframe
type: Question
has answer: http://stackoverflow.com/a/51881219
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/90714712
tagged with: pandas
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/90714154
upvote count: 2
tagged with: pivot-table
type: UnansweredQuestion
has title: pandas - Subtract 2 similar pivot table of data frame
has comment: http://stackoverflow.com/comment/90714010

http://stackoverflow.com/comment/107613734
comment on: http://stackoverflow.com/a/51950571
type: AnswerComment
has text: "It is important to note that the temporary tuple is created using values of variables (de facto copies of values), not references to the variables (you can read here about the difference between passing by value and by reference)." This is not true at all. Python **never** uses call by reference, and that isn't relevant here, because that is about how function arguments work. Furthermore, there are no "reference" types in Python. All objects have the exact same semantics, regardless of type.
score: 0
type: Comment

seq2seq
tag name: seq2seq
type: Tag
tags question: http://stackoverflow.com/q/51917160

http://stackoverflow.com/comment/90806764
type: AnswerComment
has text: @user2293224 My bad, check the final code, you need to put the sleep inside the loop so that it waits for some time when the new page loads. Its working on my side.
comment on: http://stackoverflow.com/a/51928396
score: 0
type: Comment

http://stackoverflow.com/a/51926223
upvote count: 2
has body: Before I go into more details: I am assuming that you are referring to batch_size when talking about element_size? If I am wrong in that assumption, please correct me here. As the other answer mentioned, one potential reason could be overfitting, i.e. you are trying "too hard with your training data". One general way to resolve this would be to keep track of the performance on unseen training data with held-back validation samples. I.e., instead of splitting two-ways (train/test), you have a third validation set (usually around the same size of the testing data), and check every now and then during training how your model performs on this validation data. A common observation is the following curve: As you can see, the model improves constantly on the training data, but it does so, since it sacrifices the ability to generalize to unseen data. Generally, you try to stop training at the point where the error on the validation set would be minimal - even if that does not guarantee optimal results on your training data. We expect it to then perform best on the (completely unknown) previous test set. As a quick side note, if you are doing this in TensorFlow (which I am not 100% familiar with): Generally, you have to "switch" your model from training to evaluation to get the actual results on your validation set (and not accidentally train on them as well), but you can find plenty of actual implementations of this online. Furthermore, overfitting might be an issue if you have too many neurons! In your case, you have only 800 examples, but already 80 neurons, which is IMO a ratio that is way too high. You could try using less neurons, and see if that improves the accuracy on your test set, even if that might reduce the accuracy on training data, too. In the end, you want to have a compact descriptor of your problem, and not a network that "learns" to recognize every single of your training instances. Furthermore, if you actually do work with mini batches, you could try and…
has comment: http://stackoverflow.com/comment/91049658
score: 2
accepted answer of: http://stackoverflow.com/q/51914632
answers question: http://stackoverflow.com/q/51914632
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/q/51808229
has comment: http://stackoverflow.com/comment/90571958
score: 9
has answer: http://stackoverflow.com/a/54266097
has comment: http://stackoverflow.com/comment/90578605
has comment: http://stackoverflow.com/comment/94195977
possible better answer: http://stackoverflow.com/a/56672825
has answer: http://stackoverflow.com/a/73199843
downvote count: 0
has comment: http://stackoverflow.com/comment/99686552
has comment: http://stackoverflow.com/comment/90571791
favorite count: 0
accepted answer: http://stackoverflow.com/a/51811884
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90571969
tagged with: pyqt5
has title: pyuic5 - ModuleNotFoundError: No module named PyQt5.sip
type: Question
has comment: http://stackoverflow.com/comment/90571932
has comment: http://stackoverflow.com/comment/90572005
has body: I have just installed Anaconda 5.2 with Python 3.6 on my windows system. Also installed pyqt5 and pyqt5-tools via pip with administrator privilege. Now when I run pyuic5.exe for converting ui files it shows following error: Traceback (most recent call last): File "C:\Users\AshfaqurRahman\Anaconda3\lib\runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "C:\Users\AshfaqurRahman\Anaconda3\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "C:\Users\AshfaqurRahman\AppData\Roaming\Python\Python36\site-packages\PyQt5\uic\pyuic.py", line 26, in &lt;module&gt; from PyQt5 import QtCore ModuleNotFoundError: No module named 'PyQt5.sip' I have tried installing PyQt5-sip package using pip. Buts its already installed in my system. Why this problem is occurring? How can I solve this problem?
has comment: http://stackoverflow.com/comment/90571864
tagged with: anaconda
upvote count: 9
has answer: http://stackoverflow.com/a/62940228
has answer: http://stackoverflow.com/a/51811884
has answer: http://stackoverflow.com/a/56672825
has answer: http://stackoverflow.com/a/57855412
answer count: 6

http://stackoverflow.com/comment/121816295
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/57466119
has text: @FMFF I think because Python Software Foundation is a nonprofit organization
score: 0

http://stackoverflow.com/comment/137381653
has text: I just found out that this restart causes a second or so hiccup where gunicorn resets the connection of clients causing some error noise when traffic is high. So if you use it, make it a high number (10K+), add a large jitter (20%) and keep in mind that Benoit doesn't recommend it in production: https://github.com/benoitc/gunicorn/issues/3038#issuecomment-1887073067
score: 1
comment on: http://stackoverflow.com/a/53431762
type: AnswerComment
type: Comment

http://stackoverflow.com/a/51824223
downvote count: 0
type: Answer
has body: Testing by trial and error, I finally found out what was causing the problem: In admin.py, this line was the problem ordering = ('name', 'trainer',) By removing the ordering by 'trainer', Django show each training only once. ordering = ('name',)
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51802848
answers question: http://stackoverflow.com/q/51802848
type: AcceptedAnswer

http://stackoverflow.com/q/51891406
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/90733846
accepted answer: http://stackoverflow.com/a/51891460
has title: decorator 'NoneType' object is not callable
answer count: 1
has body: I'm trying to write a simple decorator that adds try/except to any function printing the error. import random def our_decorator(func): def function_wrapper(*args, **kwargs): try: func(*args, **kwargs) except Exception as e: print(e) @our_decorator def test(): for a in range(100): if a - random.randint(0,1) == 0: print('success count: {}'.format(a)) pass else: print('error count {}'.format(a)) 'a' + 1 I keep getting the error: TypeError: 'NoneType' object is not callable What am I doing wrong?
favorite count: 0
has comment: http://stackoverflow.com/comment/90733797
tagged with: python
has answer: http://stackoverflow.com/a/51891460
tagged with: python-decorators
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/14536242
upvote count: 2
score: 1
has comment: http://stackoverflow.com/comment/90734020
duplicate of: http://stackoverflow.com/q/14536242

http://stackoverflow.com/q/51910919
has body: I have the following code: class Point: """Two-Dimensional Point(x, y)""" def __init__(self, x=0, y=0): # Initialize the Point instance self.x = x self.y = y @property def magnitude(self): # """Return the magnitude of vector from (0,0) to self.""" return math.sqrt(self.x ** 2 + self.y ** 2) def __str__(self): return 'Point at ({}, {})'.format(self.x, self.y) def __repr__(self): return "Point(x={},y={})".format(self.x, self.y) The class has a function called magnitude. I want to create a function which can tell the magnitude distance between two points. The following is an expected output: point1 = Point(2, 3) point2 = Point(5, 7) print(point1.magnitude) 3.605551275463989 print(point1.distance(point2)) 5.0 I tried doing something like this: @classmethod def distance(self, self1, self2): pointmag1 = self1.magnitude pointmag2 = self2.magnitude bsmag = pointmag1 - pointmag2 bsmag2 = pointmag2 - pointmag1 if pointmag2 &gt; pointmag1: return combsmag2 else: return combmag This code always gives me the TypeError: distance() missing 1 required positional argument: 'self2'. Any way to fix this?
has comment: http://stackoverflow.com/comment/90834187
score: 0
has title: TypeError: distance() missing 1 required positional argument: 'self2'
answer count: 1
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90772184
tagged with: python
has answer: http://stackoverflow.com/a/51911342
has comment: http://stackoverflow.com/comment/90773001
type: Question

http://stackoverflow.com/a/51848044
answers question: http://stackoverflow.com/q/51847896
has comment: http://stackoverflow.com/comment/90649480
has comment: http://stackoverflow.com/comment/90650160
type: Answer
has body: The error tells you everything you need to know about what is going wrong, which is that you cannot call the get() function on a list. In Python, the get() function can only be used with dictionaries, which are different from lists. Instead of using the get() function, call a specific index of the list and your program should work. For example: for sample in list[10:11] which returns the 11th element of the list.
has comment: http://stackoverflow.com/comment/90651426
has comment: http://stackoverflow.com/comment/90650055
score: 0
has comment: http://stackoverflow.com/comment/90652101

http://stackoverflow.com/q/51936789
score: 1
has comment: http://stackoverflow.com/comment/90824322
type: Question
has comment: http://stackoverflow.com/comment/91207225
tagged with: google-colaboratory
has comment: http://stackoverflow.com/comment/90823846
has comment: http://stackoverflow.com/comment/90823957
upvote count: 1
answer count: 1
tagged with: keras
favorite count: 0
has title: Can't save Keras model
has body: I'm using Colab to create a simple Keras model, compile it, train it, run predictions and then try to save the model as described here The problem is that I get this error: FailedPreconditionError: Attempting to use uninitialized value input/kernel [[Node: _retval_input/kernel_0_1 = _Retval[T=DT_FLOAT, index=1, _device="/job:localhost/replica:0/task:0/device:CPU:0"](input/kernel)]] Here is my model: locModel = Sequential() locModel.add(Conv2D(32, (3, 3), activation='relu', input_shape=(240, 130,1), name='input')) locModel.add(MaxPooling2D(pool_size=(2, 2))) locModel.add(Conv2D(64, (3, 3), activation='relu')) locModel.add(MaxPooling2D(pool_size=(2, 2))) locModel.add(Conv2D(128, (2, 2), activation='relu')) locModel.add(MaxPooling2D(pool_size=(2, 2))) locModel.add(Flatten()) locModel.add(Dense(256, activation='relu')) locModel.add(Dense(8, name='predicted_corners')) sgd = SGD(lr=0.01, momentum=0.9, nesterov=True) locModel.compile(loss='mean_squared_error',metrics=['accuracy'], optimizer=sgd) Training: hist = locModel.fit(imageData, localization_labels, epochs=100, validation_split=0.2, callbacks=[tbCallBack]) Evaluation: predictions = locModel.predict(testImages) Then I try to save it, as described in the link above: import tensorflow as tf from keras import backend as K KERAS_MODEL_NAME = "keras.hdf5" # Save tf.keras model in HDF5 format. tf.keras.models.save_model(locModel, KERAS_MODEL_NAME) Any help appreciated! TensorFlow version: 1.10.0 Keras version: 2.1.6 Update 1: locModel.save_weights('weights.h5') completes without errors - my ultimate goal is to convert to TFLite, so I need the whole graph. Update 2: Added initialisers for the layers: locModel = Sequential() locModel.add(Conv2D(32, (3, 3), activation='relu', input_shape=(240, 130,1), name='input', kernel_initializer='random_uniform')) locModel.add(MaxPooling2D(pool_size=(2, 2))) locModel.add(Conv2D(64, (3, 3), activation='relu', kernel_initializer='random_uniform')) locModel.add(MaxPooling2D(pool_size=(2, 2)…
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52230183
has comment: http://stackoverflow.com/comment/90823861
has comment: http://stackoverflow.com/comment/90823927
has comment: http://stackoverflow.com/comment/90823691
downvote count: 0

http://stackoverflow.com/comment/90692867
type: QuestionComment
has text: Your user name have to acess for mysql database, so you have to provide access the username and host, please check this post that will hep https://stackoverflow.com/questions/6445917/connect-failed-access-denied-for-user-rootlocalhost-using-password-yes
score: 0
comment on: http://stackoverflow.com/q/51870699
type: Comment

http://stackoverflow.com/comment/90893093
score: 0
type: Comment
type: QuestionComment
has text: maybe you can try to use `(https://.+?(jpg|gif))` instead
comment on: http://stackoverflow.com/q/51919411

http://stackoverflow.com/a/51864112
score: -1
answers question: http://stackoverflow.com/q/51863302
type: Answer
downvote count: 1
has body: Try something like this import pygame pygame.init() #Colors white= (255,255,255) black=(0,0,0) red= (255,0,0) gameDisplay= pygame.display.set_mode((800,600)) pygame.display.set_caption('ALIEN') gameExit= False lead_x=300 lead_y=300 lead_x_change=0 while not gameExit: for event in pygame.event.get(): if event.type==pygame.QUIT: gameExit=True if event.type==pygame.KEYDOWN: if event.key== pygame.K_LEFT: lead_x_change =-1 if event.key==pygame.K_RIGHT: lead_x_change = 1 if event.type==pygame.KEYUP: if event.key== pygame.K_LEFT: lead_x_change = 0 if event.key== pygame.K_RIGHT: lead_x_change = 0 lead_x += lead_x_change gameDisplay.fill(white) pygame.draw.rect(gameDisplay,black,[lead_x,lead_y,10,10]) pygame.display.update() pygame.quit() quit()
has comment: http://stackoverflow.com/comment/90717159
has comment: http://stackoverflow.com/comment/90689039
upvote count: 0

http://stackoverflow.com/comment/90726693
score: 1
comment on: http://stackoverflow.com/q/51887721
has text: Possible duplicate of [pip install fails with "connection error: \[SSL: CERTIFICATE\_VERIFY\_FAILED\] certificate verify failed (\_ssl.c:598)"](https://stackoverflow.com/questions/25981703/pip-install-fails-with-connection-error-ssl-certificate-verify-failed-certi)
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51885731
has body: Choose a proper data structure e.g. a collections.defaultdict with list as the factory: In [1233]: out = collections.defaultdict(list) In [1234]: lst = ['2017-07-17', '2017-07-27', '2017-07-17;14', '2017-07-17;5', '2017-07-19;11', '2017-07-19;13', '2017-07-23;4', '2017-07-27;-1'] In [1235]: for i in lst: ...: m, _, n = i.partition(';') ...: if n: ...: out[m].append(n) ...: In [1236]: out Out[1236]: defaultdict(list, {'2017-07-17': ['14', '5'], '2017-07-19': ['11', '13'], '2017-07-23': ['4'], '2017-07-27': ['-1']}) In [1237]: out['2017-07-17'] Out[1237]: ['14', '5'] In [1238]: out['2017-07-23'] Out[1238]: ['4'] Here, we're iterating over the list, partitioning strings on ;, and using the date portion as the key to the out dictionary with values being the right sided substrings appended.
upvote count: 5
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/51885673
score: 5

http://stackoverflow.com/comment/90576746
type: Comment
has text: @Aakib - There is some problem?
comment on: http://stackoverflow.com/a/51806381
type: AnswerComment
score: 0

http://stackoverflow.com/q/51885739
upvote count: 11
type: UnansweredQuestion
tagged with: machine-learning
score: 11
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/99291820
has body: I've trained several models in Keras. I have 39, 592 samples in my training set, and 9, 899 in my validation set. I used a batch size of 2. As I was examining my code, it occurred to me that my generators may have been missing some batches of data. This is the code for my generator: train_datagen = ImageDataGenerator( rescale=1. / 255, shear_range=0.2, zoom_range=0.2, horizontal_flip=True) val_datagen = ImageDataGenerator(rescale=1. / 255) train_generator = train_datagen.flow_from_directory( train_dir, target_size=(224, 224) batch_size=batch_size, class_mode='categorical') validation_generator = val_datagen.flow_from_directory( val_dir, target_size=(224, 224), batch_size=batch_size, class_mode='categorical') I searched around to see how my generators behave, and found this answer: what if steps_per_epoch does not fit into numbers of samples? I calculated my steps_per_epoch and validation_steps this way: steps_per_epoch = int(number_of_train_samples / batch_size) val_steps = int(number_of_val_samples / batch_size) Using the code in this link with my own batch size and number of samples, I got these results: "missing the last batch" for train_generator and "weird behavior" for val_generator. I'm afraid that I have to retrain my models again. What values should I choose for steps_per_epoch and validation_steps? Is there a way to use exact values for these variables(Other than setting batch_size to 1 or removing some of the samples)? I have several other models with different number of samples, and I think they've all been missing some batches. Any help would be much appreciated. Two related question: 1- Regarding the models I already trained, are they reliable and properly trained? 2- What would happen if I set these variables using following values: steps_per_epoch = np.ceil(number_of_train_samples / batch_size) val_steps = np.ceil(number_of_val_samples / batch_size) will my model see some of the images more than once in each epoch during training and validation? or I…
has answer: http://stackoverflow.com/a/68115010
type: Question
linked to: http://stackoverflow.com/q/50643963
answer count: 2
downvote count: 0
tagged with: keras
favorite count: 0
tagged with: deep-learning
tagged with: python
has answer: http://stackoverflow.com/a/56739003
has title: How to properly set steps_per_epoch and validation_steps in Keras?

http://stackoverflow.com/comment/90639238
type: QuestionComment
has text: do you mean, you want to close the connection to firebase auth? this might help - `firebase.database().goOffline()`
comment on: http://stackoverflow.com/q/51843075
score: 0
type: Comment

http://stackoverflow.com/q/51891420
possible better answer: http://stackoverflow.com/a/51892866
has comment: http://stackoverflow.com/comment/90733967
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51893156
has comment: http://stackoverflow.com/comment/90735688
tagged with: python
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/51893199
has title: Loop through files removing stop-words
accepted answer: http://stackoverflow.com/a/51893156
type: Question
has comment: http://stackoverflow.com/comment/90736194
has body: I want to remove stop-words from multiple files in a local folder. I know how to do it for one file, but I can't get my head around doing it for all files in that folder. What I embarrassingly tried: import io from nltk.corpus import stopwords from nltk.tokenize import word_tokenize import glob import os import codecs stop_words = set(stopwords.words('english')) for afile in glob.glob("*.txt"): file1 = open(afile) line = file1.read() words = word_tokenize(line) words_without_stop_words = ["" if word in stop_words else word for word in words] new_words = " ".join(words_without_stop_words).strip() appendFile = open('subfolder/file1.txt','w') appendFile.write(new_words) appendFile.close() I don't even know how far I could get with this, because I get: Traceback (most recent call last): File "C:\Desktop\neg\sw.py", line 14, in line = file1.read() File "C:\Program Files\Python36\lib\encodings\cp1252.py", line 23, in decode return codecs.charmap_decode(input,self.errors,decoding_table)[0] UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 1757: character maps to &lt;undefined&gt; I tried using glob, but I can't find a good documentation. Maybe it is not necessary?
has answer: http://stackoverflow.com/a/51892866
has comment: http://stackoverflow.com/comment/90735506
answer count: 3

http://stackoverflow.com/a/51882835
type: Answer
has body: You have to iterate through the list, find the start and end position and then display. You can build on this. substring_list = ['good to have', 'must have','plus','must'] mystr = "C++ C, Standard Template Library, IOStreams, String Library and C++ Standard containers, the C Library C++, C#, Microsoft .NET frameworks, Winforms, WPF, Infragistics, TFS Inter-language integration, REST Must be very familiar with modern versions of Oracle databas SQL. good to have Core Java, Collections, multi-threading, Spring, JSON. Excellent communication skills. Familiarity with modern full software development lifecycle practices" for i in substring_list: if i in mystr: start=mystr.find(i) end=start + len(i) print('Substring found: "%s" Start: %s End %s' %(mystr[start:end], start, end)) else: print('Substring not found: "%s" ' %(i)) The output is like the following: Substring found: "good to have" Start: 271 End 283 Substring not found: "must have" Substring not found: "plus" Substring not found: "must"
has comment: http://stackoverflow.com/comment/90718726
answers question: http://stackoverflow.com/q/51882155
score: 0
has comment: http://stackoverflow.com/comment/90722589

http://stackoverflow.com/a/51854467
type: Answer
score: 1
has comment: http://stackoverflow.com/comment/90661862
upvote count: 1
has body: Try the below code: from datetime import datetime def calculateTime(frm, to): p = '%Y-%m-%d %H:%M:%S' epoch = datetime(1970, 1, 1) frmTime = (datetime.strptime(frm, p) - epoch).total_seconds() toTime = (datetime.strptime(to, p) - epoch).total_seconds() return toTime - frmTime def printTime(t, form='H:M'): h = int(t/(60*60)) m = int(60 * (t/(60*60) - h)) s = int(t - ((h * 60 * 60) + (m * 60))) if form == 'H:M': print h,'hrs ',m,'mins' if form == 'H:M:S': print h,'hrs ',m,'mins',s,' secs' #changed def totalActiveTime(lst): orders = [] activeTime = 0 prevTime = None for i in lst: if i[2] == 'pickup': orders.append(i[0]) if prevTime == None: prevTime = i[1] elif i[2] == 'dropoff': orders.remove(i[0]) if len(orders) == 0: activeTime += calculateTime(prevTime, i[1]) prevTime = None return activeTime s = [ [1, '2017-08-15 13:30:00', 'pickup'], [1, '2017-08-15 14:00:00', 'dropoff'], [2, '2017-08-15 14:30:00', 'pickup'], [3, '2017-08-15 14:35:00', 'pickup'], [2, '2017-08-15 15:00:00', 'dropoff'], [4, '2017-08-15 15:05:00', 'pickup'], [3, '2017-08-15 15:10:00', 'dropoff'], [4, '2017-08-15 15:40:00', 'dropoff'], ] printTime(totalActiveTime(s)) Output 1 hrs 40 mins
has comment: http://stackoverflow.com/comment/90661334
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51854001
downvote count: 0
answers question: http://stackoverflow.com/q/51854001

http://stackoverflow.com/q/51846548
tagged with: import
type: Question
has title: How do I implement this import statement for Python?
has comment: http://stackoverflow.com/comment/90646920
has comment: http://stackoverflow.com/comment/90646966
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/51847237
favorite count: 0
tagged with: python
type: UnansweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/90647038
has body: I have a python module for Affinity Propagation I found online. The code is found here at this link. https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/affinity_propagation_.py#L256 I have taken the code and have placed in a file called affinitypropagationlib.py. I am trying to create a "main" python module which imports the python file above but am receiving the following error. Warning (from warnings module): File "C:\Users\Br. David Klecker\Downloads\WPy-3701\python-3.7.0.amd64\lib\site-packages\sklearn\utils\__init__.py", line 4 from collections import Sequence DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working Traceback (most recent call last): File "C:\Users\Br. David Klecker\Downloads\WPy-3701\notebooks\ap.py", line 4, in &lt;module&gt; import affinitypropagationlib File "C:\Users\Br. David Klecker\Downloads\WPy-3701\notebooks\affinitypropagationlib.py", line 12, in &lt;module&gt; from ..base import BaseEstimator, ClusterMixin ImportError: attempted relative import with no known parent package The code I have for my ap.py (my main python module) is the following. import matplotlib.pyplot as plt import numpy as np #from sklearn.cluster import AffinityPropagation import affinitypropagationlib from sklearn import metrics from sklearn.datasets.samples_generator import make_blobs # generating sampl data centers = [[5, 5], [0, 0], [1, 5],[5, -1]] X, labels_true =make_blobs(n_samples=500, n_features=5, centers=centers, cluster_std=0.9, center_box=(1, 10.0), shuffle=True, random_state=0) # Compute Affinity Propagation af = AffinityPropagation(max_iter=150, preference =-120).fit(X) cluster_centers_indices = af.cluster_centers_indices_ labels = af.labels_ n_clusters_ = len(cluster_centers_indices) #print results print('Estimated number of clusters: %d' % n_clusters_) print("Homogeneity: %0.3f" % metrics.homogeneity_score(labels_true, labels)) print("Co…
has comment: http://stackoverflow.com/comment/90646799
upvote count: 1

http://stackoverflow.com/comment/90597155
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51820354
type: AnswerComment
has text: add four spaces(preferably) before every statement after the define line except the last one.

http://stackoverflow.com/comment/90844822
has text: It looks like that solution works for Python2, but not Python3. I can create the cipher using AES CBC, but I cannot for the life of me find out how to chunk long texts.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51943598

http://stackoverflow.com/comment/90784164
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51917132
has text: Then it is just `{% url 'register' %}` (so then it would have worked the way you wrote it).
type: Comment

http://stackoverflow.com/comment/90839980
type: Comment
comment on: http://stackoverflow.com/a/51944591
has text: However I found a way to do it... SUBMIT_ARGS = "--packages mysql:mysql-connector-java:5.1.39 pyspark-shell" os.environ["PYSPARK_SUBMIT_ARGS"] = SUBMIT_ARGS conf = SparkConf() sc = SparkContext(conf=conf)
score: 0
type: AnswerComment

http://stackoverflow.com/a/51973124
accepted answer of: http://stackoverflow.com/q/51948295
score: 0
type: AcceptedAnswer
type: Answer
has body: I found the answer my self, you can only put a label inside the button in the KV language, when using ButtonBehavior. Then you can just use Factory to access the button from the python file. The "text = StringProperty()" in the ImageButton class is needed cause there is some sort of bug that causes the firs button to be generated with out text. from kivy.app import App from kivy.uix.screenmanager import ScreenManager, Screen from kivy.properties import ObjectProperty from kivy.uix.boxlayout import BoxLayout from kivy.lang import Builder from kivy.clock import mainthread from kivy.uix.button import Button from kivy.uix.popup import Popup from kivy.uix.label import Label from kivy.uix.button import Button from kivy.properties import BooleanProperty, StringProperty from kivy.uix.image import AsyncImage from kivy.uix.behaviors import ButtonBehavior from kivy.uix.image import Image from kivy.factory import Factory Builder.load_file('main.kv') login_plz = Popup(title='Please login', content=Label(text='You need to login first'), size_hint=(None, None), size=(400, 400), auto_dismiss=True) class Menu(BoxLayout): access_denied = BooleanProperty(True) class ScreenLogIn(Screen): def verify_credentials(self): popup = Popup(title='Try again', content=Label(text='Wrong Email/Password'), size_hint=(None, None), size=(400, 400), auto_dismiss=True) try: if len(self.ids.login.text) &gt; 20 or len(self.ids.passw.text) &gt; 32: popup.open() elif self.ids.login.text == "a" and self.ids.passw.text == "a": App.get_running_app().root.access_denied = False self.manager.current = "match" else: App.get_running_app().root.access_denied = True popup.open() except Exception as e: pass class ScreenNearUsers(Screen): @mainthread def on_enter(self): if App.get_running_app().root.access_denied is True: self.manager.current = 'login' login_plz.open() else: for i in xrange(31): button = Button(text="B_" + str(i)) self.ids.grid.add_widget(button) class ScreenMatch(Screen): def on_enter(self, *args): if…
answers question: http://stackoverflow.com/q/51948295

http://stackoverflow.com/comment/90669365
type: AnswerComment
type: Comment
has text: This is fantastic thank you for the time and detail. I've not used dictionaries at all yet, but will go through each example you've laid out to see the best fit.
comment on: http://stackoverflow.com/a/51848712
score: 1

http://stackoverflow.com/q/51935840
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/16479029
duplicate of: http://stackoverflow.com/q/16479029
has comment: http://stackoverflow.com/comment/90821829
type: Question
score: 0
has comment: http://stackoverflow.com/comment/90821802
has comment: http://stackoverflow.com/comment/90821704
tagged with: python-cmd
tagged with: python
has body: I've built a simple cli app using cmd. I noticed that hitting the enter key seems to be rerunning the previous command. Is there a way to catch/prevent this?
has title: Python cmd module enter key
answer count: 0

http://stackoverflow.com/a/77279719
answers question: http://stackoverflow.com/q/51874486
has body: I had the same symptoms Upgrading the vscode fixed the problem. Download link : https://code.visualstudio.com/download Help -&gt; Info -&gt; Version Check it out!! Check New Version link : https://code.visualstudio.com/updates
score: 0
type: Answer

http://stackoverflow.com/comment/90582478
type: AnswerComment
score: 0
type: Comment
has text: Hmm, is there an easy way to switch from django templates to jinja2?
comment on: http://stackoverflow.com/a/51813619

http://stackoverflow.com/q/51885394
accepted answer: http://stackoverflow.com/a/51912712
has title: brew install doesn't link python3
has answer: http://stackoverflow.com/a/76455822
favorite count: 0
tagged with: python-2.7
answer count: 3
tagged with: python
tagged with: macos
upvote count: 29
score: 28
tagged with: python-3.x
has body: I'm having trouble linking python3 and making python3 the default python. MacOS 10.13.6 Here's what I did: $ python --version Python 2.7.15 $ python3 --version Python 3.7.0 $ xcode-select --version xcode-select version 2349. $ brew install python ... Python has been installed as /usr/local/bin/python3 Unversioned symlinks `python`, `python-config`, `pip` etc. pointing to `python3`, `python3-config`, `pip3` etc., respectively, have been installed into /usr/local/opt/python/libexec/bin ... It doesn't work. python is still 2.* $ python --version Python 2.7.15 $ python3 --version Python 3.7.0 $ pip --version pip 10.0.1 from /usr/local/lib/python2.7/site-packages/pip (python 2.7) $ pip3 --version pip 18.0 from /usr/local/lib/python3.7/site-packages/pip (python 3.7) So I did: $ brew link python3 Warning: Already linked: /usr/local/Cellar/python/3.7.0 To relink: brew unlink python &amp;&amp; brew link python $ python --version Python 2.7.15 $ brew install python3 ... Warning: python 3.7.0 is already installed and up-to-date To reinstall 3.7.0, run `brew reinstall python` $ brew reinstall python Also doesn't work $ brew link python3 Warning: Already linked: /usr/local/Cellar/python/3.7.0 To relink: brew unlink python &amp;&amp; brew link python $ python --version Python 2.7.15 $ python3 --version Python 3.7.0
downvote count: 1
has answer: http://stackoverflow.com/a/51912712
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/69459134
type: Question
possible better answer: http://stackoverflow.com/a/76455822

http://stackoverflow.com/comment/90786718
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51918012
type: Comment
has text: I do not think subprocess has a `run()` method, it should be `call()`, right?

http://stackoverflow.com/comment/90770181
score: 0
has text: okay tell me one thing ,does django support receiving email,I saw documentation on how to send email through django but their is nothing on how to recieve email in django.
type: Comment
comment on: http://stackoverflow.com/a/51909073
type: AnswerComment

http://stackoverflow.com/comment/90771756
comment on: http://stackoverflow.com/q/51910816
score: 3
has text: It sounds like your problem isn't in _calling_ the function but rather _importing_ it. Can you please show the full error message?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/121791612
type: AnswerComment
comment on: http://stackoverflow.com/a/57857176
has text: This worked for me to access images in google drive!! Thank you!
type: Comment
score: 1

http://stackoverflow.com/comment/90824665
comment on: http://stackoverflow.com/a/51936488
type: Comment
has text: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/178373/discussion-between-subodh-agrawal-and-wen).
score: 0
type: AnswerComment

http://stackoverflow.com/a/51904213
has comment: http://stackoverflow.com/comment/135101731
score: 5
upvote count: 5
downvote count: 0
answers question: http://stackoverflow.com/q/51904126
type: Answer
has body: Using Pandas, this is straightforward. You just need to make sure the array is 2-dimensional. import pandas as pd A = np.array([[[0. , 1], [0. , 1], [0. ,1]]]) # construct dataframe, index [0] to make 2d df = pd.DataFrame(A[0]) # save to Excel, exclude index and headers df.to_excel('file.xlsx', index=False, header=False)

http://stackoverflow.com/q/51806436
upvote count: 1
linked to: http://stackoverflow.com/q/51815802
answer count: 1
accepted answer: http://stackoverflow.com/a/51808413
has comment: http://stackoverflow.com/comment/90568486
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/html
downvote count: 0
has title: Python Selenium Dynamic table cell returning empty string
score: 1
favorite count: 0
type: Question
has body: I am trying to get value from a dynamic loading table, when I click on the TD element it works all ok. But when I am tryin to get the text from same TD , it is returning empity string. I have tried XPATH, CSS_Selector Below is the UI look, I want to get the amount Below is the HTML Snap amount = driver.find_element_by_xpath('//*[@id="Table_Cheque_Ref_Details"]/tbody/tr[2]/td[11]').click Working Fine amount=driver.find_element_by_xpath('//*[@id="Table_Cheque_Ref_Details"]/tbody/tr[2]/td[11]').text print amount returns empity string amount = WebDriverWait(driver, 10).until(EC.text_to_be_present_in_element((By.XPATH, '//*[@id="xfe38"]'), '0')) print amount Timeout Exception
tagged with: python
tagged with: selenium-webdriver
has answer: http://stackoverflow.com/a/51808413
tagged with: selenium

http://stackoverflow.com/comment/90696828
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51872534
has text: that is not how python works.

http://stackoverflow.com/comment/90844710
comment on: http://stackoverflow.com/q/51927973
score: 1
type: QuestionComment
has text: You should either close this question, or post your solution as an answer.
type: Comment

http://stackoverflow.com/comment/90577602
comment on: http://stackoverflow.com/a/51811102
type: AnswerComment
has text: Thanks @ImportanceOfBeingErnest! I found another post that goes into the details a bit more. Updated answer to include a link to that post, the link you provided to the docs, and a quick overview.
score: 0
type: Comment

http://stackoverflow.com/a/51920866
has comment: http://stackoverflow.com/comment/90791992
has comment: http://stackoverflow.com/comment/90791718
has comment: http://stackoverflow.com/comment/90791444
downvote count: 0
answers question: http://stackoverflow.com/q/51920827
upvote count: 2
has body: Use DataFrameGroupBy.agg with specify columns names with aggregation functions in dictionary: hr_df = (hr_df.groupby(['U_ID', 'Group', 'Location', pd.Grouper(key='Date', freq='MS')]) .agg({'Hours':'sum', 'People':'max'}) .reset_index(level=[0, 1, 2]) ) print (hr_df) U_ID Group Location Hours People Date 2014-11-01 149 17 USA 4.0 2 2014-11-01 149 18 UK 1.5 1 2014-11-01 149 19 Spain 2.0 4 2014-12-01 149 21 USA 3.0 2
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/90791797
has comment: http://stackoverflow.com/comment/90791896

http://stackoverflow.com/comment/90634777
type: Comment
has text: Please know how to create a [`Minimal, Complete, and Verifiable example`](https://stackoverflow.com/help/mcve)
score: 0
comment on: http://stackoverflow.com/q/51840708
type: QuestionComment

http://stackoverflow.com/q/51920912
has comment: http://stackoverflow.com/comment/90791889
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/51931667
tagged with: linux
has body: I want to create a python program which runs as a systemd service. I want to be able to stop it gracefully. I've come across a weird behavior: when I use threads, a python program does not receive a SIGTERM signal on systemctl stop example.service, but everything works fine if I do not use threads. The example is following: Without threads. (service receives SIGTERM signal and stops as expected): import signal import time import threading import sys RUN=True # catch SIGINT and SIGTERM and stop application def signal_handler(sig, frame): global RUN print("Got signal: "+str(sig)) RUN=False signal.signal(signal.SIGINT, signal_handler) signal.signal(signal.SIGTERM, signal_handler) # some working thread inside application def my_thread(): global RUN while RUN: print("sleep") time.sleep(1.0) my_thread() print("Done.") With threads. (program does not receive SIGTERM signal and is forcefully killed by SIGKILL after timeout): import signal import time import threading import sys RUN=True # catch SIGINT and SIGTERM and stop application def signal_handler(sig, frame): global RUN print("Got signal: "+str(sig)) RUN=False signal.signal(signal.SIGINT, signal_handler) signal.signal(signal.SIGTERM, signal_handler) # some working thread inside application def my_thread(): global RUN while RUN: print("sleep") time.sleep(1.0) # wait for thread to complete and exit t = threading.Thread(target=my_thread) t.start() t.join() print("Done.") Systemd service file: [Unit] Description=Example service [Install] WantedBy=multi-user.target [Service] ExecStart=/usr/bin/python /opt/program/main.py TimeoutSec=60 Restart=on-failure Type=simple User=mixo Group=mixo Just to be clear: my program requires multiple threads so I want to be able to stop service gracefully even if I use threads in my program. What am I doing wrong?
tagged with: multithreading
tagged with: python
linked to: http://stackoverflow.com/q/25676835
tagged with: systemd
type: AnsweredQuestion
has title: Systemd not receiving SIGTERM on stop when using threads in program
has answer: http://stackoverflow.com/a/51931667
type: Question

http://stackoverflow.com/comment/90689763
has text: @DanielPryden Instead of respawning right away, is there a way to wait for a certain period of time and respawn again?
comment on: http://stackoverflow.com/q/51868926
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90787899
comment on: http://stackoverflow.com/a/51918974
type: Comment
score: 1
has text: So when the OP turns this in as homework and then asks a similar question without any attempt next week, will you also answer that as well? By simply giving the OP an answer for this problem without the OP doing any work - you are actually preventing someone from learning (homework or not) and may cause the OP to get a low score in the class when he can't finish his final project or test or if the professor/TA/teacher actually searches SO - just so you know we do.
type: AnswerComment

http://stackoverflow.com/comment/90639010
has text: Okay, then you can use @Divakar's answer. I'll add it to mine
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51830057
type: Comment

http://stackoverflow.com/comment/90737810
comment on: http://stackoverflow.com/q/51893520
type: Comment
score: 1
type: QuestionComment
has text: Might help if you also post your bash script

http://stackoverflow.com/a/51929982
type: Answer
has comment: http://stackoverflow.com/comment/90833159
has comment: http://stackoverflow.com/comment/90844183
score: 1
accepted answer of: http://stackoverflow.com/q/51929798
upvote count: 1
has comment: http://stackoverflow.com/comment/90810239
has comment: http://stackoverflow.com/comment/90840014
has comment: http://stackoverflow.com/comment/90841314
has body: Try something like this. name = [] rank = [] for i in range(first_sheet.nrows): #print(first_sheet.cell_value(i,3)) if('Saxon' in first_sheet.cell_value(i,3)): name.append(first_sheet.cell_value(i,2)) rank.append(first_sheet.cell_value(i,8)) print('a') for j in range(len(name)): worksheet1.write(j+1,0,rank[j]) worksheet1.write(j+1,1,name[j]) workbook.save("saxons.xls")
answers question: http://stackoverflow.com/q/51929798
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90840766

http://stackoverflow.com/comment/90708718
comment on: http://stackoverflow.com/q/51878706
has text: Rather than be concerned with the "best" way, have you found any way to make this work? What are you unhappy about with your current approach?
type: QuestionComment
type: Comment
score: 7

http://stackoverflow.com/comment/90625954
comment on: http://stackoverflow.com/q/51835461
score: 1
type: Comment
type: QuestionComment
has text: http://idownvotedbecau.se/imageofcode and "ttps://i.sstatic.net/DOjFr.png" reveals a really careless question. You want us to take care to answer, so please take care on [how to ask](https://stackoverflow.com/help/how-to-ask).

http://stackoverflow.com/a/51871407
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/51871376
downvote count: 0
answers question: http://stackoverflow.com/q/51871376
type: AcceptedAnswer
upvote count: 2
has body: I think there is problem some bad values, solution is parameter errors='coerce' for convert them to NaT: timestamp = pd.to_datetime(strdate + ' ' + strtime, errors='coerce') You can check these values by: print (df1[pd.to_datetime(strdate + ' ' + strtime, errors='coerce').isnull()])

http://stackoverflow.com/q/51945962
tagged with: tcpclient
type: Question
has comment: http://stackoverflow.com/comment/91154131
tagged with: tcpserver
tagged with: tcpsocket
score: 0
has comment: http://stackoverflow.com/comment/90844324
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90876916
has body: My question is that how to call server and client sequentially in main method ? Problem is that python debugger waiting and be suck in line that calling the server(blocking the calling client line). I tried threading but not work . Thanks for your attention. IMPORTANT: Below codes using Python2 Main python file: import xClient import xServer import threading tempServer=xServer tempClient=xClient thrMain = threading.Thread(target=tempServer.innerClient.Main()) thrMain.start() thrMain.join() tempClient.innerClient.Main() xClient.py : # STANDARD Client code and works correctly import socket import time class innerClient: def Main(): time.sleep(2) host = '127.0.0.1' port = 12345 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((host, port)) message = "test message" while True: s.send(message.encode('ascii')) data = s.recv(1024) print('Received from the server :', str(data.decode('ascii'))) ans = raw_input('Continue(y/n) :') if ans == 'y': continue else: break s.close() xServer.py : # STANDARD Server code and works correctly import socket import threading class innerServer: print_lock = threading.Lock() # thread fuction def threaded(c): while True: data = c.recv(1024) if not data: print('See you later') print_lock.release() break data = data[::-1] c.send(data) c.close() def Main(): host = "" port = 12345 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((host, port)) print("socket binded to post", port) s.listen(5) print("socket is listening") while True: c, addr = s.accept() print_lock.acquire() print('Connected to :', addr[0], ':', addr[1]) thr = threading.Thread(target=threaded, args=(c,)) thr.start() thr.join() s.close() TCP Socket Diagram
tagged with: python
has title: Python Socket Call server.py and client.py in main.py
has comment: http://stackoverflow.com/comment/91194620
answer count: 0

http://stackoverflow.com/comment/90683386
type: Comment
type: QuestionComment
has text: Maybe you share the considerations you already had in order to solve this problem. SO is not a free homework machine.
score: 0
comment on: http://stackoverflow.com/q/51865268

http://stackoverflow.com/q/51869330
score: 1
upvote count: 1
accepted answer: http://stackoverflow.com/a/51869344
type: Question
duplicate of: http://stackoverflow.com/q/43268186
has title: Cannot figure out how to repeat processes in Python3
has answer: http://stackoverflow.com/a/51869344
answer count: 1
downvote count: 0
favorite count: 0
linked to: http://stackoverflow.com/q/43268186
tagged with: python-3.x
has body: Im making a game for a hobby, sort of an adventure text based game. I cant figure out how id make it so if they type anything other than "Get up", the process repeats and the code asks them again repeatedly until they get the right answer. getup = input("What is your action?: ") if getup == "Get Up": print("You stand up and get your bearings. You scan the enviroment. There is a small passage way to the north, and tight crevis to the east. Everywhere else is just cave wall") elif getup == "get up": print("You stand up and get your bearings. You scan the enviroment. There is a small passage way to the north, and tight crevis to the east. Everywhere else is just cave wall") elif getup == "Get up": print("You stand up and get your bearings. You scan the enviroment. There is a small passage way to the north, and tight crevis to the east. Everywhere else is just cave wall") elif getup == "GET UP": print("You stand up and get your bearings. You scan the enviroment. There is a small passage way to the north, and tight crevis to the east. Everywhere else is just cave wall") else: print("Celsia: You do not have time to waste,",name,"!!. You must Get Up")
tagged with: repeat
tagged with: python
type: AnsweredQuestion

pyalgotrade
tag name: pyalgotrade
type: Tag
tags question: http://stackoverflow.com/q/51924068

http://stackoverflow.com/q/51843314
has title: How to use hex color value in python reportlab pdf generation
upvote count: 5
type: UnansweredQuestion
tagged with: python
downvote count: 0
tagged with: reportlab
has body: I am trying to generate multi page pdf document reading some py files and other doc files. I am trying do it with SimpleDocTemplate instead of Canvas. Now I am trying to color the text with hex value. I tried following: from reportlab.lib.pagesizes import letter from reportlab.platypus import SimpleDocTemplate from reportlab.platypus.para import Paragraph from reportlab.lib.styles import getSampleStyleSheet doc_content = [] styles=getSampleStyleSheet() doc = SimpleDocTemplate("form_letter.pdf",pagesize=letter, rightMargin=72,leftMargin=72, topMargin=72,bottomMargin=18) titleFormat = '%s' def generateDoc(docName): paraTitle = Paragraph(titleFormat % 'Title', styles["Normal"]) doc_content.append(paraTitle) doc.build(doc_content) generateDoc("temp.pdf") But this gives me error AttributeError: module 'reportlab.lib.colors' has no attribute '#FF8100' I also tried 0xFF8100, but it was giving same error: AttributeError: module 'reportlab.lib.colors' has no attribute '0xFF8100' When I use some named color say red, it works fine. How can use hex color values?
type: Question
score: 5
has answer: http://stackoverflow.com/a/51865875
answer count: 1
favorite count: 0

http://stackoverflow.com/q/51930339
tagged with: python
linked to: http://stackoverflow.com/q/39740632
possible better answer: http://stackoverflow.com/a/59128961
has answer: http://stackoverflow.com/a/78456081
has comment: http://stackoverflow.com/comment/90811246
has comment: http://stackoverflow.com/comment/90810456
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90811110
has body: Consider the following example. The example is contrived but illustrates the point in a runnable example: class MultiplicatorMixin: def multiply(self, m: int) -&gt; int: return self.value * m class AdditionMixin: def add(self, b: int) -&gt; int: return self.value + b class MyClass(MultiplicatorMixin, AdditionMixin): def __init__(self, value: int) -&gt; None: self.value = value instance = MyClass(10) print(instance.add(2)) print(instance.multiply(2)) When executed this will give the following output: 12 20 The code works. But running mypy on it, yields the following errors: example.py:4: error: "MultiplicatorMixin" has no attribute "value" example.py:10: error: "AdditionMixin" has no attribute "value" I understand why mypy gives this result. But the mixin classes are never used by themselves. They are always used as additional superclasses. For context, this is a pattern which has been used in an existing application and I am in the process of adding type-hints. And in this case, the errors are false-positives. I am thinking about rewriting the part using the mixins as I don't particularly like it and the same could probably be done with reorganising the class hierarchy. But I still would like to know how something like this could be properly hinted.
has answer: http://stackoverflow.com/a/70706326
has answer: http://stackoverflow.com/a/79235603
has answer: http://stackoverflow.com/a/70711397
has title: How do I correctly add type-hints to Mixin classes?
type: Question
tagged with: mypy
has answer: http://stackoverflow.com/a/62823688
score: 76
has answer: http://stackoverflow.com/a/58007242
answer count: 11
has answer: http://stackoverflow.com/a/73210987
upvote count: 77
has answer: http://stackoverflow.com/a/70907644
accepted answer: http://stackoverflow.com/a/70907644
downvote count: 1
tagged with: multiple-inheritance
has comment: http://stackoverflow.com/comment/90811030
tagged with: python-typing
has answer: http://stackoverflow.com/a/52313062
favorite count: 0
has answer: http://stackoverflow.com/a/59128961
has answer: http://stackoverflow.com/a/51931254

http://stackoverflow.com/q/51854353
favorite count: 0
tagged with: postgresql
type: UnansweredQuestion
tagged with: python
score: -1
tagged with: psql
downvote count: 2
upvote count: 1
has body: Is there anyway I can use any pgsql driver without actually installing it? I see Psycopg2 is most commonly used for connecting to PGSQL database but that need installing and The issue I have here is I need to distribute the code but the we are not allowed to install anything on the server. Anything standalone (e.g. including the driver/library files in a directory along with my scripts) but that's the only thing I can do. Is there any way I can import psycopg2 from a local directory? Thanks in advance!
type: Question
has title: Use python PGSQL driver without installing it?
has comment: http://stackoverflow.com/comment/90666723
has answer: http://stackoverflow.com/a/51854883
answer count: 1

http://stackoverflow.com/q/51867052
downvote count: 0
has title: Logical expression building out of a list of tuples
tagged with: python
has comment: http://stackoverflow.com/comment/90686225
favorite count: 0
has body: I am trying to build a logical expression out of that list of tuples (a,b) where a is an operator and b is depth. Basically if second element in next tuple is greater than previous one insert '(' if less, insert ')' - if equal skip. Here is an example of what I am talking about: lst = [('a', 8), ('or', 7), ('b', 8), ('and', 6), ('c', 7), ('and', 5), ('d', 7), ('and', 6), ('e', 7)] with desired output being: ((((((((a) or ( b)) and ( c)) and ((d) and (e))))))) I have tried enumeration, looping while adding second list lst[1:] and so on but I am not able to get it. Any help is greatly appreciated. Thank you!
upvote count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51867172
tagged with: enumerate
score: 2
tagged with: loops
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/51867228

iterator
tags question: http://stackoverflow.com/q/51869152
tags question: http://stackoverflow.com/q/51938903
tag name: iterator
tags question: http://stackoverflow.com/q/51862462
tags question: http://stackoverflow.com/q/51880657
tags question: http://stackoverflow.com/q/51941307
tags question: http://stackoverflow.com/q/51848532
tags question: http://stackoverflow.com/q/51819743
tags question: http://stackoverflow.com/q/51941464
tags question: http://stackoverflow.com/q/51927652
tags question: http://stackoverflow.com/q/51891047
tags question: http://stackoverflow.com/q/51880052
tags question: http://stackoverflow.com/q/51822449
tags question: http://stackoverflow.com/q/51852174
type: Tag

http://stackoverflow.com/comment/90732826
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51880117
has text: If I return the object, I should not be leaving the input object such a mess. Any idea how I can actually pass the input node by value?
type: AnswerComment

http://stackoverflow.com/q/51889218
score: 1
possible better answer: http://stackoverflow.com/a/51889419
has answer: http://stackoverflow.com/a/51889387
type: Question
has answer: http://stackoverflow.com/a/51889902
has body: My use-case is as follows: I want to make an electric bill generator with different units having different prices. In below program, if the user enters units between 1-150 then for making price value it will do multiplication with 2.50 and make a price. If the user Units are between the 151-300 then it will multiply the first 150 units with 2.50 and left units will multiply with the 3.60 means to say If user entered 155 then for first 150 150 * 2.50 and for left units 5 it will do multiplication 5 * 3.60. like the above I said I'm making like this four variations given Below:- if units lies between 1-150 then it will multiplies with the 2.50 and calculates the price. if units lies between 151-300 then it will multiplies first 150 units with the price 2.50 and left units below the 300 will multiply with the 3.60 and calculates the price. if units lies between 301-450 then it will multiplies first 150 units with the price 2.50 and other 150 units will multiplies with the 3.60 and left units are multiplies with the 4.75 and calculates the price. if units lies between 451-600 then it will multiplies first 150 units with the price 2.50 and other 150 units will multiplies with the 3.60 and other 150 units are multiplies with the 4.75 and left units are multiplies with the 5 and calculates the price. if units lies above 600 then it will multiplies first 150 units with the price 2.50 and other 150 units will multiplies with the 3.60 and other 150 units are multiplies with the 4.75 and next 150 units are multiplies with the 5 and left units are multiplies with the 6 and calculates the price. Here is my code which is seek to optimize, i.e. shorten: units = int(input("Enter the units")) if(1&lt;=units and 150&gt;=units): firstSum = units * 2.50 print("First sum:-", firstSum) if(151&lt;=units and 300&gt;=units): firstSum = 150 * 2.50 subUnits = units - 150 secondSum = firstSum + (subUnits * 3.60) print(secondSum) if(301&lt;=units and 450&gt;=units): firstSum = 150 * 2.50 subUni…
downvote count: 0
answer count: 6
has comment: http://stackoverflow.com/comment/90730090
has answer: http://stackoverflow.com/a/51889786
tagged with: python
accepted answer: http://stackoverflow.com/a/51889902
has answer: http://stackoverflow.com/a/51890196
favorite count: 0
has answer: http://stackoverflow.com/a/51889362
upvote count: 1
has answer: http://stackoverflow.com/a/51889419
tagged with: calculation
has title: How to optimize (= shorten) my Python code?
type: AnsweredQuestion

http://stackoverflow.com/q/51801213
tagged with: big-o
type: AnsweredQuestion
tagged with: file
accepted answer: http://stackoverflow.com/a/51801410
score: 19
downvote count: 1
tagged with: fseek
type: Question
has body: Does f.seek(500000,0) go through all the first 499999 characters of the file before getting to the 500000th? In other words, is f.seek(n,0) of order O(n) or O(1)?
upvote count: 20
answer count: 2
possible better answer: http://stackoverflow.com/a/51801243
favorite count: 0
has answer: http://stackoverflow.com/a/51801243
linked to: http://stackoverflow.com/q/21658364
has answer: http://stackoverflow.com/a/51801410
has title: Complexity of f.seek() in Python
tagged with: io
tagged with: python

http://stackoverflow.com/comment/90651380
comment on: http://stackoverflow.com/q/51821725
has text: https://stackoverflow.com/questions/26664102/why-can-i-not-create-a-wheel-in-python
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51930714
has body: Problem description I have an instance of HDInsight cluster with which I'm connecting using Putty and CAPI Certificate. Once I'm trying to connect it asks me for a special PIN number(assigned to a card which needs to be plugged in during connection) which I need to enter manually and then I'm able to login, execute commands etc. But the problem is that I would like to have a possibility to run commands on HDInsight cluster from the code from my local machine. Question Is there a library for Python which enables me to do it from the code? Basically I would like to execute following scenario(written in pseudocode): login to HDInsight cluster execute i.e. "ls /path/to/directory" see the output of a command above in the console on my local machine Thanks a lot in advance for any suggestions!
tagged with: python
score: 0
tagged with: putty
type: Question
tagged with: azure
tagged with: azure-hdinsight
answer count: 1
has answer: http://stackoverflow.com/a/52615529
has title: How to run commands on HDInsight cluster from the code?
type: UnansweredQuestion

http://stackoverflow.com/q/51936781
has comment: http://stackoverflow.com/comment/90824102
has title: Calling Data from Named Arrays
has body: I'm using python and I'm trying to call and plot arrays from a data set. The data set is named and they data is in the format: "{'err': array([8.,8.,8.,....],dtype=float32), 'saa': array([239.93,242.02,242.28,...], dtype=float32)}" There are multiple datasets in the array. I'm trying to call them one by one. If you care how I formatted said arrays, they were formatted with the following code: rows=[{'amf':amf,'err':err,'unc':unc,'saa':saa,'time':time,'o3':o3,'sza':sza}] with open(outfile, 'a') as f: writer.writerow(rows) As requested, here is hypothetical plotting code: import csv import matplotlib.pyplot as plt import numpy as np np.set_printoptions(threshold=np.nan) inputfile = '/usr2/..../..../file' data = np.genfromtxt(inputfile,delimiter = '\t') Honestly, not sure where to go from here to call the list, but I would like to get an output of being able to call a single array at a time like so: output from calling single array function: [8., 8., 8.,....... 8., 8., 8.,] I'd also like to be able to plot one array against another. I'm just unsure how to call each array individually.
tagged with: python
accepted answer: http://stackoverflow.com/a/51937222
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90824230
downvote count: 1
type: Question
tagged with: database
tagged with: sorting
score: -1
has answer: http://stackoverflow.com/a/51937222
has comment: http://stackoverflow.com/comment/90824074
upvote count: 0
tagged with: arrays
answer count: 1
has comment: http://stackoverflow.com/comment/90824237
favorite count: 0

http://stackoverflow.com/comment/90824941
has text: Have you tried right click => open image ? It'll open it and you'll have more details.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51937381

http://stackoverflow.com/q/51858836
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51859131
has title: Python: How to kill command after timeout
upvote count: 1
type: Question
linked to: http://stackoverflow.com/q/1191374
score: 1
has body: I am using python command import commands tmp = "my command" #any command like ls status, output = commands.getstatusoutput(tmp) It works perfectly. Now i have few commands which may take more than 5 seconds or stuck forever. I want to kill such commands after 5 second. Any pointers.
answer count: 2
has comment: http://stackoverflow.com/comment/90670092
has answer: http://stackoverflow.com/a/51869037
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/90612657
comment on: http://stackoverflow.com/a/51828963
type: Comment
has text: This solution is misguiding. At least with regard to the actual question. This is not a file conversion. This is a "hint" to excel, to open a text file.
score: 5
type: AnswerComment

http://stackoverflow.com/comment/90620634
comment on: http://stackoverflow.com/q/51833379
score: 1
type: Comment
type: QuestionComment
has text: You're not actually calling the classes, you know

http://stackoverflow.com/comment/90651251
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51848866
has text: `for index,row in df.iterrows(): url = 'https://url.com/path/to?username=string&password=string&leadId=row' xml_data1 = requests.get(url).text lst.append(xml_data1) print(xml_data1)`
score: 0

http://stackoverflow.com/q/51804410
answer count: 2
tagged with: pandas
upvote count: 1
has answer: http://stackoverflow.com/a/51804878
has body: I have the following statement: &gt;&gt;&gt; df['result'] = df['value'].apply(myfunc, args=(x,y,z)) The Python function myfunc was written before I started using Pandas and is set up to take single values. The arguments x and z are fixed and can easily be passed as a variable or literal, but I have a column in my DataFrame that represents the y parameter, so I'm looking for a way to use that row's value for each row (they differ from row to row). i.e. df['y'] is a series of values that I'd like to send in to myfunc My workaround is as follows: values = list(df['value']) y = list(df['y']) df['result'] = pd.Series([myfunc(values[i],x,y[i],z) for i in range(0,len(values))]) Any better approaches? EDIT Using functools.partial has a gotcha that was able to work out. If your call does not stick to keyword arguments then it appears to resort to positional and then you may run into the 'myfunc() got multiple values for...' error. I modified the answer from coldspeed: # Function myfunc takes named arguments arg1, arg2, arg3 and arg4 # The values for arg2 and arg4 don't change so I'll set them when # defining the partial (assume x and z have values set) myfunc_p = partial(myfunc, arg2=x, arg4=z) df['result'] = [myfunc_p(arg1=w, arg3=y) for w, y in zip(df['value'], df['y'])]
has answer: http://stackoverflow.com/a/51804438
favorite count: 0
tagged with: python
downvote count: 0
score: 1
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51804878
has title: Pandas Series.apply - use arguments from another Series?
accepted answer: http://stackoverflow.com/a/51804438
type: Question

email
tags question: http://stackoverflow.com/q/51799650
tags question: http://stackoverflow.com/q/51857925
tags question: http://stackoverflow.com/q/51907836
tags question: http://stackoverflow.com/q/51913444
tags question: http://stackoverflow.com/q/51809083
tags question: http://stackoverflow.com/q/51812368
tags question: http://stackoverflow.com/q/51924767
type: Tag
tags question: http://stackoverflow.com/q/51922590
tag name: email

http://stackoverflow.com/comment/116527568
type: AnswerComment
score: 24
type: Comment
comment on: http://stackoverflow.com/a/52805231
has text: This is likely obvious to those that understand, but can someone elaborate on what the --user command is doing in the execution of the code?

http://stackoverflow.com/comment/90771610
type: QuestionComment
has text: First create an axis, and plot the data on it. It can be done through `f, ax = plt.subplots(1,1)`. Then you can either use the function `subplots_adjust()` or you can retrieve the x0, y0, width, height parameter of the axis and then modify them. I don't have a python environment on this laptop, but I think someone could provide you an example.
type: Comment
comment on: http://stackoverflow.com/q/51910697
score: 1

http://stackoverflow.com/q/51807391
has answer: http://stackoverflow.com/a/51815897
answer count: 2
has comment: http://stackoverflow.com/comment/90570317
has comment: http://stackoverflow.com/comment/90570582
tagged with: image-capture
has comment: http://stackoverflow.com/comment/90570612
tagged with: python
has body: There are certain libraries such as fswebcam, cv2 etc. But pip cant find a matching distribution for Python3 on Win7 64bit. Are there any other libraries or how can i use these two to capture images from Python
tagged with: webcam
type: UnansweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/90570149
linked to: http://stackoverflow.com/q/34588464
has answer: http://stackoverflow.com/a/51807770
type: Question
has title: How do I capture images using webcam in Python?
has comment: http://stackoverflow.com/comment/90577525

http://stackoverflow.com/a/51964802
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/51908166
answers question: http://stackoverflow.com/q/51908166
upvote count: 1
downvote count: 1
has body: In PIL, the rotation happens about the center of the image. So considering your center of the image is given by: cx = int(image_width / 2) cy = int(image_height / 2) a specified rotation angle: theta = 30 and given coordinates (px, py), The new coordinates can be obtained using the following equation: rad = radians(theta) new_px = cx + int(float(px-cx) * cos(rad) + float(py-cy) * sin(rad)) new_py = cy + int(-(float(px-cx) * sin(rad)) + float(py-cy) * cos(rad)) Please note that the angle must be specified in radians, not degrees. This answer is inspired from this following blog-post.
score: 0

http://stackoverflow.com/q/51934283
has body: I'm trying to create a layout where the user can click a combination of buttons, each button's click will add a 1 or a 0 to a certain position in a list which is the actual input I'd like to get out of it. However, I don't know how to manage a cluster of buttons, there are 48 buttons and managing them all individually is the antithesis of DRY. Here's an example attempt: num_buttons = 48 press_list = [None]*len(num_buttons) button_list = list() for button in range(num_buttons): some_btn = QtWidgets.QPushButton(SomeDialog) some_btn.setGeometry(QtCore.QRect(70, 90, 141, 28)) some_btn.setObjectName("button_%s" % (button,)) some_btn.clicked.connect(self.button_pressed(button)) def button_pressed(self, button_num): if press_list[button_num] == 1: press_list[button_num] = 0 else: press_list[button_num] = 1 (clicks turn buttons blue), is it possible to have a set geometry through the Qt designer and still do something like this, or will I have to calculate the setGeometry positions and add the buttons through the code?
tagged with: pyqt5
has comment: http://stackoverflow.com/comment/90819431
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/90819785
score: 1
has comment: http://stackoverflow.com/comment/90819541
accepted answer: http://stackoverflow.com/a/51935314
has title: PyQt5 managing a cluster of buttons without having to write cases for each individual one
tagged with: pyqt
downvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/90819918
tagged with: python
has comment: http://stackoverflow.com/comment/90818834
type: AnsweredQuestion
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90819657
has answer: http://stackoverflow.com/a/51935314

http://stackoverflow.com/q/51905796
tagged with: azure-cognitive-services
tagged with: python-3.x
type: UnansweredQuestion
has title: Trying to run Sample App in Microsoft Cognitive-Face Python SDK gives Syntax Error:invalid syntax on @util.async
tagged with: python
has comment: http://stackoverflow.com/comment/90763233
answer count: 0
has body: I've been trying to run the Sample Application given on https://github.com/Microsoft/Cognitive-Face-Python . I have downloaded all the required packages and modules.I've tried running the code on Git Bash and CMD and both give the same error: Traceback (most recent call last): File "C:\Users\aritrab507\AppData\Local\Programs\Python\Python37- 32\lib\runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "C:\Users\aritrab507\AppData\Local\Programs\Python\Python37- 32\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "sample\__main__.py", line 8, in &lt;module&gt; from view import MyApp File "sample\view\__init__.py", line 15, in &lt;module&gt; from view.panel_detection import DetectionPanel File "sample\view\panel_detection.py", line 90 @util.async ^ SyntaxError: invalid syntax Some idea about where I could have gone wrong would be much appreciated.
type: Question
has comment: http://stackoverflow.com/comment/90762201
score: 0

http://stackoverflow.com/comment/90715446
type: Comment
comment on: http://stackoverflow.com/q/51881911
type: QuestionComment
has text: You cannot have two applications listening on the same port at the same time. Perhaps you started the application twice, or some other application has taken the port.
score: 0

http://stackoverflow.com/q/51861904
tagged with: python
type: AnsweredQuestion
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/90676154
type: Question
has comment: http://stackoverflow.com/comment/90676185
tagged with: numpy
tagged with: arrays
upvote count: 2
tagged with: pandas
answer count: 1
has body: I have a pandas dataframe df. One column is a string of numbers (as characters) divided by blank space I need to convert it to multidim numpy array. I thought that : df.A.apply(lambda x: np.array(x.split(" "))).values would make the trick Actually it returns an array of array.... array([array(['70', '80', '82', ..., '106', '109', '82'], dtype='&lt;U3'), array(['151', '150', '147', ..., '193', '183', '184'], dtype='&lt;U3'), Which does not seem to be what I look what i am looking for whcih should rather look like array([[[['70', '80', '82', ..., '106', '109', '82'],['151', '150', '147', ..., '193', '183', '184'].... First: what shoudl I do to have my daya in the second format? Second: I am actually a bit confused about the difference between the 2 data structures. In the end of the day a multidimensional array is an array of arrays. From this perspective it would seem that the 2 are the same structure. But I am sure I am missing somthing EXAMPLE: df=pd.DataFrame({"A":[0,1,2,3],"B":["1 2 3 4","5 6 7 8","9 10 11 12","13 14 15 16"]}) A B 0 0 "1 2 3 4" 1 1 "5 6 7 8" 2 2 "9 10 11 12" 3 3 "13 14 15 16" This command df.B.apply(lambda x: np.array(x.split(" "))).values gives: array([array(['1', '2', '3', '4'], dtype='&lt;U1'), array(['5', '6', '7', '8'], dtype='&lt;U1'), array(['9', '10', '11', '12'], dtype='&lt;U2'), array(['13', '14', '15', '16'], dtype='&lt;U2')], dtype=object) instead of array([['1', '2', '3', '4'], ['5', '6', '7', '8'], ['9', '10', '11', '12'], ['13', '14', '15', '16']], dtype='&lt;U2') Question1: How do I get this last structure? Question2: what is the difference between the 2? Technically are both array of arrays...
favorite count: 0
has title: series of list to multidimensional np array
has answer: http://stackoverflow.com/a/51862188
accepted answer: http://stackoverflow.com/a/51862188

http://stackoverflow.com/q/51877097
favorite count: 0
accepted answer: http://stackoverflow.com/a/51877405
has comment: http://stackoverflow.com/comment/90705472
tagged with: python
has comment: http://stackoverflow.com/comment/90705597
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/35491274
has answer: http://stackoverflow.com/a/51877405
upvote count: 0
has answer: http://stackoverflow.com/a/51877363
has title: pandas series to csv
has body: I have following pandas series: 0 [[1, 11283, 01, 5], [2,5, 1, 1]] 1 [[6, 33, 21, 2], [11283, 01, 5,1]] 2 [[8430, 01, 2, 2],[2, 1, 1, 1]] I need to save this as csv but csv rows should be something similar to following: 1, 11283, 01, 5 2,5, 1, 1 6, 33, 21, 2 11283, 01, 5,1 8430, 01, 2, 2 2, 1, 1, 1
type: Question
tagged with: dataframe
score: -1
has comment: http://stackoverflow.com/comment/90705696
answer count: 2
tagged with: pandas
downvote count: 1
possible better answer: http://stackoverflow.com/a/51877363

ui-automation
tags question: http://stackoverflow.com/q/51932842
tag name: ui-automation
type: Tag
tags question: http://stackoverflow.com/q/51869254
tags question: http://stackoverflow.com/q/51897192
tags question: http://stackoverflow.com/q/51915039

http://stackoverflow.com/comment/90745147
comment on: http://stackoverflow.com/a/51890613
type: Comment
has text: @SimakisPanagiotis-Thanks for the suggestion, I am not using my google credential to sign in to the above website
score: 0
type: AnswerComment

http://stackoverflow.com/comment/90785261
type: Comment
type: QuestionComment
score: 2
has text: Why does the data type matter?
comment on: http://stackoverflow.com/q/51917757

http://stackoverflow.com/q/51883629
type: AnsweredQuestion
type: Question
tagged with: opencv
has title: Adding transparency on small numbers/letters with OpenCV in Python
has body: I'm working on overlapping some digits at the moment and I'm unsure of how to get rid of their white background so that I can overlay the numbers while still showing their whole character. img1: img2: (they're tiny letter pictures, not text) background: Example: import cv2 import numpy as np import matplotlib.pyplot as plt img1 = cv2.imread('img1.png') img2 = cv2.imread('img2.png') croppedbg = cv2.imread('background.png') characters = [img1, img2] movinginterval = [10, 45] height, width = croppedbg.shape[:2] rheight = round(height - (height / 3) * 2) times = 0 newres = np.array([]) for i in movinginterval: iterbg = croppedbg.copy() fullcharwidths = sum([t.shape[1] for t in characters])+i bgxsplitter = (iterbg.shape[1] - fullcharwidths*2)/(len(characters)) for t in characters: x_offset = round(fullcharwidths + (bgxsplitter*(times))) y_offset = rheight y1, y2 = y_offset, y_offset + t.shape[0] x1, x2 = x_offset, x_offset + t.shape[1] alpha_s = t[:, :, 2] / 255.0 alpha_l = 1.0 - alpha_s for c in range(3): iterbg[y1:y2, x1:x2, c] = (alpha_s * t[:, :, c] + alpha_l * iterbg[y1:y2, x1:x2, c]) times += 1 #decreases width interval difference between characters try: newres = np.concatenate((newres, iterbg), axis=0) #vertically stack both images except ValueError: newres = iterbg.copy() plt.imshow(newres) plt.show() Output: The top two numbers are working fine, but pushing them closer together as is for the bottom two numbers leads their backgrounds to overlap and cut off the other digits. I'd like the 0 and the 4 to be distinguishable by making their backgrounds disappear, while the characters remain overlapping for the bottom two digits.
score: 0
has answer: http://stackoverflow.com/a/51884027
accepted answer: http://stackoverflow.com/a/51884027
answer count: 1
tagged with: python

http://stackoverflow.com/comment/91018494
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51821413
has text: Thank You. I did as per your suggessgtion and it worked!
type: AnswerComment

amazon-elastic-beanstalk
tag name: amazon-elastic-beanstalk
type: Tag
tags question: http://stackoverflow.com/q/51801353
tags question: http://stackoverflow.com/q/51954052

http://stackoverflow.com/q/51875213
has answer: http://stackoverflow.com/a/75982351
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/90703062
score: 4
favorite count: 0
tagged with: python-2.7
answer count: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/51877266
tagged with: python
has title: Delete pandas rows if column values are close to each other within a certain range
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51887912
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90702801
has comment: http://stackoverflow.com/comment/90702714
downvote count: 1
has comment: http://stackoverflow.com/comment/90702592
has body: I would like to remove all pandas rows where values in two columns are close to each other within a certain pre-defined range. For example: df = pd.DataFrame({'a':[1,2,3,4,5,6], \ 'b':[20.02,19.96,19.98,20.10,26.75,56.12],\ 'c':[10.12,10.10,123.54,124.12,245.12,895.21]}) a b c 1 20.02 10.12 2 19.96 10.10 3 19.98 123.54 4 20.10 124.12 5 26.75 245.12 6 56.12 895.21 Filter rows based on column b and c: if the current values of b and c are close to (within 1% of) the previous accepted row's values: (0.99*previous_b &lt; b &lt; 1.01*previous_b) &amp;&amp; (0.99*previous_c &lt; c &lt; 1.01*previous_c) then they are excluded. Result a b c 1 20.02 10.12 3 19.98 123.54 5 26.75 245.12 6 56.12 895.21 I can use numpy.isclose for one number: df['b'].apply(np.isclose, b=20.02, atol=0.01 * 20.02) How can I generalize this so that I apply this iteratively running through all pandas columns and apply this condition on two different columns? Side note: I have two million rows in my pandas dataframe. Therefore, I would like to know the most efficient way to do this.
has comment: http://stackoverflow.com/comment/90703233
upvote count: 5

http://stackoverflow.com/comment/90664051
type: Comment
type: QuestionComment
has text: If working with very Sparse Matrix I suggest you read about how to work with Sparse Matrix. In particular you can read about `libsvm` data representation.
comment on: http://stackoverflow.com/q/51802054
score: 0

http://stackoverflow.com/comment/90884160
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51938429
has text: @JamesKent, Noted. Though it's worth pointing out there may be aesthetic reasons (stylistic, code maintenance, etc) why one might prefer to use `atof` instead of explicit `str.replace`.
type: Comment

http://stackoverflow.com/comment/90766857
type: AnswerComment
has text: @chitown88 If you have a subscription there are most likely better ways of getting the data (through API access) than scraping, but then again, it's always fun to use scraping :)
type: Comment
comment on: http://stackoverflow.com/a/51908188
score: 0

http://stackoverflow.com/q/51813254
score: 5
has answer: http://stackoverflow.com/a/51813303
has body: In python 3.6 and pandas 0.19.0 there is a dataframe "df" id abc abc def I am trying to create a dataframe with a id_count column, which is the same as SQL: SELECT id, COUNT(1) AS id_count FROM table group by id ideal returns: id id_count abc 2 def 1 I have tried: print (df.groupby(['id'])['id'].count()) returns id abc 2 def 1 print (df.groupby(['id'])['id'].transform('count')) returns 0 2 1 1 Any thoughts? Thank you!
upvote count: 5
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/51813303
tagged with: python
type: AnsweredQuestion
has title: Make a pandas dataframe group by count have a column name
type: Question

http://stackoverflow.com/a/52017252
type: Answer
has body: I think the python 3.7 still not supported, I'm having the problem too I think I need to downgrade to a stable version. Reference: https://github.com/skvark/opencv-python/issues/106
answers question: http://stackoverflow.com/q/51881545
score: 0

http://stackoverflow.com/q/51874191
possible better answer: http://stackoverflow.com/a/51874521
tagged with: dataframe
has title: Count all defined values in a DataFrame column where the corresponding values in another column are undefined in pandas
answer count: 2
tagged with: pandas
upvote count: 1
downvote count: 0
tagged with: nan
favorite count: 0
has body: I am working with a DataFrame with two columns constraint, such that when the first has a value defined, then the other should have the corresponding value defined as well. I would like to count the number of cases where this constraint is not holding. Example df = pd.DataFrame({'a': [np.nan, 2, np.nan, 4, 5, 6],'b': [11, 12 , np.nan, 14, 15, np.nan]}) a b 0 NaN 11 1 2 12 2 NaN NaN 3 4 14 4 5 15 5 6 NaN When the value in column a is defined, then the corresponding value in column b has to be defined as well. This does not hold for row with index 5, so the result in this case should be 1.
has answer: http://stackoverflow.com/a/51874521
tagged with: count
tagged with: python
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/51874272
accepted answer: http://stackoverflow.com/a/51874272
type: Question

http://stackoverflow.com/q/51954897
has answer: http://stackoverflow.com/a/51955167
tagged with: argparse
score: 3
has comment: http://stackoverflow.com/comment/90867047
tagged with: python
favorite count: 0
tagged with: command-line
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90860586
upvote count: 3
has title: Python argparse: optional two values argument
type: Question
answer count: 1
downvote count: 0
has body: Hello: I being trying to setup an argument, that when included in the command line will consume exactly two arguments, and when not presented will default to a list of two values. So far I have not found a way to do this. The following is my code: _version="1.0.0" _parser = argparse.ArgumentParser(description='Statmon: expandable server metrics retriever', usage=""" statmon.py [-a COUNT SECS] [-c CONFIG] [-o [FILE]] MODULE [PARAM ...] statmon.py -? [-c CONFIG] MODULE statmon.py -v""") _parser.add_argument('-?', '--show', dest='show', default=False, action='store_true', help='Request to show the metrics return by a statistics module.') _parser.add_argument('-a', '--avg', dest='avg_ms', default=[1, 0], action='store', type=int, nargs='*', help='Asks to display the average of COUNT samples within SECS time. Default one sample.') _parser.add_argument('-c', '--conf', dest='config', default="/etc/statmon.conf", action='store', type=str, nargs='+', help='Define the configuration file. Default is /etc/statmon.conf.') _parser.add_argument('-o', '--outfile', dest='outfile', default=None, const=None, action='store', type=str, nargs='?', help='Define the out file to write the stats. If not provided will biuld it.') _parser.add_argument('-v', '--version', dest='ver', default=False, action='store_true', help='Shows version of the command.') _parser.add_argument('module', default=[], action='store', type=str, nargs='*', help="The module that we should pull the metrics from and its parameters.") _args = _parser.parse_args() if _args.ver: print("{0}: {1}".format(_parser.description, _version)) exit(0) My issue is with option '-a'. I want it if provided to get the next two elements from the command line and lear the remaining for the other options. Right now I get no error. But, if I include it it will consume more than two elements of the command line. See the following examples: $ python statmon.py cpu Option -a: [1, 0] {"USER": 0.0, "NICE": 0.0, "SYS": 0.0, "IDLE": 0.0} Now provid…

http://stackoverflow.com/q/51821711
has body: I'm having difficulties in stacking different "types" of numpy arrays. array_1 is array([(3,111),(3,222)]) array_2 is array([(4,111),(4,222)]) array_3 is array([[5,111],[5,222]]) (notice the change in brackets in array_3). I can easily use np.hstack to combine array_1 and array_2, but how can I also combine array_3? Any help would be appreciated.
score: 0
tagged with: python
has title: Stacking different types of arrays in numpy
has comment: http://stackoverflow.com/comment/90597838
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90597301
has comment: http://stackoverflow.com/comment/90603209
has answer: http://stackoverflow.com/a/51821797
has comment: http://stackoverflow.com/comment/90597394
has comment: http://stackoverflow.com/comment/90597344
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/90597378
has comment: http://stackoverflow.com/comment/90605650
has comment: http://stackoverflow.com/comment/90597232
answer count: 1

http://stackoverflow.com/a/57447625
has body: Upgrading pip in windows with - python -m pip install --upgrade pip and then running pip install with --user option - pip install --user package_name solved my problem.
answers question: http://stackoverflow.com/q/51912999
score: 3
downvote count: 1
type: Answer
upvote count: 4

http://stackoverflow.com/a/51841793
upvote count: 1
has body: why we put 'entry' between square brackets? the thing in the square brackets is called a key. It is just a simplification for indexing: example code : a = {'a': 1, 'b': 2, 'c': [1, 2]} a["d"] = 5 in the machine it becomes: a.__setitem__("d",5) if "d" does not exists as a key, it will create one.If it does,the function assign a new value to it
downvote count: 0
answers question: http://stackoverflow.com/q/51840326
type: Answer
score: 1

http://stackoverflow.com/q/51799251
tagged with: google-chrome
type: Question
has answer: http://stackoverflow.com/a/51799372
accepted answer: http://stackoverflow.com/a/51799372
has title: urllib3.exceptions.ProtocolError: ('Connection aborted.', error(10054, 'An existing connection was forcibly closed by the remote host'))
tagged with: urllib3
upvote count: 7
answer count: 1
favorite count: 0
tagged with: python
type: AnsweredQuestion
tagged with: selenium-chromedriver
downvote count: 0
has body: I am trying to open a website on chrome using Python Selenium chromedriver. Chrome browser is opening (with warnings) and the url is not opening. Version details : Chrome : 68.0.3440.106 selenium : 3.14.0 chromedriver : 2.20 python : 2.7 I am using below code : import time from selenium import webdriver import selenium driver = webdriver.Chrome("C:/Python27/chromedriver.exe") driver.get("https://vancouver.craigslist.ca/") print(driver.title) time.sleep(8) driver.quit() I am getting below error: C:\Users\sohil7777\PycharmProjects\temp.py\venv\Scripts\python.exe C:/Users/sohil7777/.PyCharmCE2018.2/config/scratches/scratch.py Traceback (most recent call last): File "C:/Users/sohil7777/.PyCharmCE2018.2/config/scratches/scratch.py", line 6, in &lt;module&gt; driver = webdriver.Chrome("C:/Python27/chromedriver.exe") File "C:\Python27\lib\site-packages\selenium\webdriver\chrome\webdriver.py", line 75, in __init__ desired_capabilities=desired_capabilities) File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 156, in __init__ self.start_session(capabilities, browser_profile) File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 251, in start_session response = self.execute(Command.NEW_SESSION, parameters) File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 318, in execute response = self.command_executor.execute(driver_command, params) File "C:\Python27\lib\site-packages\selenium\webdriver\remote\remote_connection.py", line 375, in execute return self._request(command_info[0], url, body=data) File "C:\Python27\lib\site-packages\selenium\webdriver\remote\remote_connection.py", line 397, in _request resp = self._conn.request(method, url, body=body, headers=headers) File "C:\Python27\lib\site-packages\urllib3\request.py", line 72, in request **urlopen_kw) File "C:\Python27\lib\site-packages\urllib3\request.py", line 150, in request_encode_body return self.urlopen(method, url, **extra_kw) File…
score: 7
tagged with: selenium

lemmatization
type: Tag
tags question: http://stackoverflow.com/q/51943811
tag name: lemmatization
tags question: http://stackoverflow.com/q/51881089

http://stackoverflow.com/q/51919651
score: 0
tagged with: spotify
answer count: 1
tagged with: oauth
tagged with: django
has body: I have a django server, and I wish to perform the spotify Authorization code flow. Here is a basic skeleton I have created: The user opens the spotify/login url. The SpotifyLoginView redirects them to https://accounts.spotify.com/authorize url. The spotify servers callback to the spotify/callback endpoint. The SpotifyCallbackView makes a POST request to https://accounts.spotify.com/api/token to get the auth token. urls.py urlpatterns = [ path( "spotify/callback", views.SpotifyCallbackView.as_view(), name="spotify callback" ), path("spotify/login", views.SpotifyLoginView.as_view(), name="spotify login"), ] views.py def build_authorize_url(request): params = { "client_id": "&lt;my client id&gt;", "response_type": "code", "redirect_uri": request.build_absolute_uri( reverse("spotify callback") ), "scope": " ".join( [ "user-library-read", "user-top-read", "user-read-recently-played", "playlist-read-private", ] ), } print(params) url = ( furl("https://accounts.spotify.com/authorize") .add(params) .url ) print(url) return url AUTH_HEADER = { "Authorization": "Basic " + base64.b64encode( "&lt;my client id&gt;:&lt;my client secret&gt;".encode() ).decode() } def handle_callback(request): code = request.GET["code"] response = requests.post( "https://accounts.spotify.com/api/token", data={ "grant_type": "client_credentials", "code": code, "redirect_uri": request.build_absolute_uri( reverse("spotify callback") ), }, headers=AUTH_HEADER, ) return response.json() class SpotifyLoginView(RedirectView): query_string = True def get_redirect_url(self, *args, **kwargs): return build_authorize_url(self.request) class SpotifyCallbackView(TemplateView): template_name = "success.html" def get(self, request, *args, **kwargs): print(spotify.handle_callback(request)) return super().get(request, *args, **kwargs) However, the response returned by spotify doesn't contain the scope and refresh_token! So for these params: {'client_id': '&lt;my client id&gt;', 'response_type': 'code', 'redirect_uri'…
tagged with: python
has answer: http://stackoverflow.com/a/51919906
type: AnsweredQuestion
has title: Spotify Authorization Code Flow returns incomplete response
type: Question
accepted answer: http://stackoverflow.com/a/51919906

http://stackoverflow.com/a/51834946
has comment: http://stackoverflow.com/comment/90668008
type: AcceptedAnswer
downvote count: 0
score: 1
type: Answer
answers question: http://stackoverflow.com/q/51833699
accepted answer of: http://stackoverflow.com/q/51833699
upvote count: 1
has comment: http://stackoverflow.com/comment/90773492
has comment: http://stackoverflow.com/comment/90643311
has body: It took a few minutes to understand what you meant, but after refactoring the list of players as the code below shows, the rest sort of rolled itself: https://github.cm/rebelclause/python_legs/blob/master/pygame/roll_the_dice.py. If it works for you, buy me a beer ;) players = {'you': {'rolltotal': None, 'otherstuff': None }, 'me': {'rolltotal': None, 'otherstuff': None}} def reviewvals(): print('Number of players: ', len(players)) # only counts the primary keys, the players for player, attribdict in players.items(): for key, value in attribdict.items(): print(player, key, value) reviewvals()

http://stackoverflow.com/q/51937772
downvote count: 0
has body: I'm implementing a function that returns an object from the appropriate subclass. If I move SubClass from base.py, no subclasses appear for __subclasses__. Are they required to be in the same file? Perhaps the fact that I'm never importing directly subclass.py hides the subclass from python? What can I do? I have even checked the attribute __mro__ and get_subclass points to the right class. # project/main.py from project.src.base import get_subclass obj = get_subclass(cls,name) # Returns an object of a subclass of cls # project/src/subclass.py from project.src.base import BaseClass class SubClass(BaseClass): pass # project/src/base.py def get_subclass(cls,name): subclss = cls.__subclasses__ # This is returning an empty list pass class BaseClass(object): pass
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/51938404
has comment: http://stackoverflow.com/comment/90826352
has answer: http://stackoverflow.com/a/51938404
score: 12
tagged with: python-import
has title: __subclasses__ not showing anything
answer count: 1
has comment: http://stackoverflow.com/comment/90826699
tagged with: python
upvote count: 12
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90825903

http://stackoverflow.com/q/51867429
possible better answer: http://stackoverflow.com/a/51867651
tagged with: python
type: AnsweredQuestion
tagged with: tkinter
has comment: http://stackoverflow.com/comment/90701091
has answer: http://stackoverflow.com/a/51869204
accepted answer: http://stackoverflow.com/a/51869204
upvote count: 1
type: Question
score: 1
has answer: http://stackoverflow.com/a/51867651
answer count: 2
downvote count: 0
has body: I am making a Python program, and I am looking for ways to make a nice centre-aligned title at the top of inside my program. However, I am having trouble doing this because with the current tools I have, I would have to experiment my label spacing length to match how many characters I have for my title. Is there a way to make a Python label be certain amount of pixels long regardless of length of the text? I am specifically looking for a way of specifically making a label be a specific number of pixels long so I don't have to experiment with all these different lengths. I tried using the "padx" and "pady" parameters, but I have found that the lengths will always change depending on the length of the text of the label itself. I also tried the "width" parameter, but it only extends by a number of textlengths long. from tkinter import * root = Tk() root.geometry("960x600") label_toptitle = Label(root, text="Program Name", padx=40, pady=40, font=(None, 40), #height=2, #width=30 ) root.mainloop() This is my current code right here, but if I change the name "Program Name" to another name, the padx and pady and/or width or height functions will become not the same amount of pixels long. I need a way to make the label a fixed amount of pixels long.
has comment: http://stackoverflow.com/comment/90689977
favorite count: 0
has title: Set specific width for Python label as this many pixels long?
tagged with: python-3.x

http://stackoverflow.com/a/51909340
type: AcceptedAnswer
downvote count: 0
has body: You need to use dtype=torch.float: import torch x = torch.ones(2, 2, requires_grad=True) y = x + 2 z = y * y * 3 out = z.mean() # option 1 out.backward() print(x.grad) x = torch.ones(2, 2, requires_grad=True) y = x + 2 z = y * y * 3 out = z.mean() #option 2. Replace! do not leave one after the other out.backward(torch.tensor(1, dtype=torch.float)) print(x.grad) Output: tensor([[ 4.5000, 4.5000], [ 4.5000, 4.5000]]) tensor([[ 4.5000, 4.5000], [ 4.5000, 4.5000]])
upvote count: 2
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/51909270
answers question: http://stackoverflow.com/q/51909270

http://stackoverflow.com/q/51867348
tagged with: python
has title: Python/Scrapy How to go into a deeper link and go back
tagged with: scrapy
type: Question
answer count: 2
has body: I am trying to scrap information about every firm in from this website : www.canadianlawlist.com I have finished most of it, but I am running into a small problem. I am trying to get the results to display in the following order : -Firm Name and Information *Employees from the firm Information. But instead I am getting very random results. It will scrape information about 2 firms and then scrap the information of employees. Like that : -Firm Name and Information -Firm name and information *Employee from Firm 1 -Firm name and information *Employee from Firm 2 It goes something like that . I am not sure what i am missing in my code : def parse_after_submit(self, response): basicurl = "canadianlawlist.com/" products = response.xpath('//*[@class="searchresult_item_regular"]/a/@href').extract() for p in products: url = "http://canadianlawlist.com" + p yield scrapy.Request(url, callback=self.parse_firm_info) #process next page #for x in range(2, 6): # next_page_url = "https://www.canadianlawlist.com/searchresult?searchtype=firms&amp;city=montreal&amp;page=" + str(x) def parse_firm_info(self,response): name = response.xpath('//div[@class="listingdetail_companyname"]/h1/span/text()').extract_first() print name for info in response.xpath('//*[@class="listingdetail_contactinfo"]'): street_address = info.xpath('//div[@class="listingdetail_contactinfo"]/div[1]/span/div/text()').extract_first() city = info.xpath('//*[@itemprop="addressLocality"]/text()').extract_first(), province = info.xpath('//*[@itemprop="addressRegion"]/text()').extract_first(), postal_code = info.xpath('//*[@itemprop="postalCode"]/text()').extract_first(), telephone = info.xpath('//*[@itemprop="telephone"]/text()').extract_first(), fax_number = info.xpath('//*[@itemprop="faxNumber"]/text()').extract_first(), email = info.xpath('//*[@itemprop="email"]/text()').extract_first(), print street_address print city print province print postal_code print telephone print fax_number print email for people in response.…
has answer: http://stackoverflow.com/a/51889315
has answer: http://stackoverflow.com/a/51869723
score: 0
has comment: http://stackoverflow.com/comment/90690949
type: UnansweredQuestion

http://stackoverflow.com/q/51858816
tagged with: command-line-interface
tagged with: python-click
has body: Is there a way to get separate detailed help for click commands? For example to print the options/arguments for that command. Example for this cli: import click @click.group() def cli(): pass @cli.command() @click.argument('arg1') @click.option('--option1', default=1) def cmd1(arg1): print(arg1) if __name__ == '__main__': cli() The default help only gives this: &gt; python cli.py --help Usage: cli.py [OPTIONS] COMMAND [ARGS]... Options: --help Show this message and exit. Commands: cmd1 I would like something like this: &gt; python cli.py --help cmd1 ... Command cmd1 Arguments: arg1 Options: --option1 .... Is this possible?
answer count: 1
downvote count: 0
favorite count: 0
has title: python click detailed help for commands
accepted answer: http://stackoverflow.com/a/51860538
tagged with: python
type: AnsweredQuestion
score: 1
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51860538

http://stackoverflow.com/comment/104924150
comment on: http://stackoverflow.com/a/57466119
has text: All I had to do was `sudo pip install certifi` and that seemed to fix the issue for me.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/126583754
comment on: http://stackoverflow.com/a/52880211
type: AnswerComment
type: Comment
score: 2
has text: The superior answer would be to pick opencv-contrib-python as the package of preference to install.

http://stackoverflow.com/q/51816639
tagged with: yolo
tagged with: machine-learning
tagged with: python
type: AnsweredQuestion
has body: I've been trying to install IMGAUG package for an ML project. But the installation gets stuck when it tries to install scikit-image My input: pip install scikit-image output: Collecting imgaug Using cached https://files.pythonhosted.org/... Requirement already satisfied: scipy in c:\users\*&lt;username&gt;*\appdata\local\programs\python\python37\lib\site- packages (from imgaug) (1.1.0) Collecting scikit-image&gt;=0.11.0 (from imgaug) Using cached https://files.pythonhosted.org/packages/... Complete output from command python setup.py egg_info: ---------------------------------------- Command "python setup.py egg_info" failed with error code 3221225477 in C:\Users\&lt;name&gt;~1.&lt;name2&gt;\AppData\Local\Temp\pip-install-qmdp6ysz\scikit-image\ Note: I've already tried installing other versions of it, upgrading setuptools and pip. Error persists. PS: Now it's showing up on everything I try to install.
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/90595157
has comment: http://stackoverflow.com/comment/90587891
has comment: http://stackoverflow.com/comment/90588050
has title: setup.py egg_info error code 3221225477
accepted answer: http://stackoverflow.com/a/51817869
linked to: http://stackoverflow.com/q/2720014
score: 0
has comment: http://stackoverflow.com/comment/90587863
has comment: http://stackoverflow.com/comment/90588554
possible better answer: http://stackoverflow.com/a/56411037
has answer: http://stackoverflow.com/a/51817869
has answer: http://stackoverflow.com/a/56411037

http://stackoverflow.com/comment/90848225
type: Comment
type: QuestionComment
has text: @Bazingaa it's indented in my code, fixed it in the question
comment on: http://stackoverflow.com/q/51949122
score: 0

http://stackoverflow.com/q/51906514
type: Question
tagged with: mongodb
has answer: http://stackoverflow.com/a/51906644
accepted answer: http://stackoverflow.com/a/51906644
answer count: 1
downvote count: 0
has title: Pymongo aggregate() sort an array field
favorite count: 0
has body: I am doing an aggregate and on some stage i have following results: [{ "_id" : 1, "array_field": [1, 2, 3]}, { "_id" : 2, "array_field": [3, 2, 1]}] I want to get the array_field sorted on next stage: [{ "_id" : 1, "array_field": [1, 2, 3]}, { "_id" : 2, "array_field": [1, 2, 3]}] What is the possibilities? The $sort didnt helped me.
tagged with: python
type: AnsweredQuestion
score: 1
tagged with: pymongo
upvote count: 1

http://stackoverflow.com/q/51911954
answer count: 1
downvote count: 1
favorite count: 0
score: 0
tagged with: python
tagged with: selenium-webdriver
has body: I am getting below mentioned error. Please advise if i am not able to provide correct path to the element. selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//form[@id="extended-nav-search"]/input[1]"} Here is my complete code. from selenium import webdriver import time my_driver = webdriver.Chrome("C:\\chromedriver_win32\\chromedriver.exe") my_driver.get("https://www.linkedin.com/uas/login") my_driver.maximize_window() email = my_driver.find_element_by_xpath('//*[@id="session_key-login"]') email.send_keys('abc@gmail.com') time.sleep(2) password = my_driver.find_element_by_xpath('//*[@id="session_password-login"]') password.send_keys('XXXXXX') time.sleep(2) login = my_driver.find_element_by_xpath('//*[@id="btn-primary"]') login.click() time.sleep(2) search = my_driver.find_element_by_xpath('//form[@id="extended-nav-search"]/input[1]') search.send_keys("python programmer") button = my_driver.find_element_by_xpath('//*[@id="nav-search-controls-wormhole"]/button') button.click() Above code has error in Line 15th of code
type: Question
type: AnsweredQuestion
has title: Selenium WebDriver fails with NoSuchElementException
has answer: http://stackoverflow.com/a/51912537
accepted answer: http://stackoverflow.com/a/51912537
upvote count: 1

http://stackoverflow.com/comment/90777652
has text: I tried ":" and got invalid syntax. For "school.school_url", I received the "keyword can't be an expression" error.
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51913496

http://stackoverflow.com/comment/90720493
score: 0
comment on: http://stackoverflow.com/q/51884416
has text: Process from multiprocessing. I'll add it to the question
type: Comment
type: QuestionComment

exception
tags question: http://stackoverflow.com/q/51939023
tags question: http://stackoverflow.com/q/51827582
tags question: http://stackoverflow.com/q/51874042
type: Tag
tags question: http://stackoverflow.com/q/51826296
tags question: http://stackoverflow.com/q/51848398
tags question: http://stackoverflow.com/q/51911708
tags question: http://stackoverflow.com/q/51908424
tags question: http://stackoverflow.com/q/51799486
tag name: exception
tags question: http://stackoverflow.com/q/51859752

http://stackoverflow.com/q/51875020
type: UnansweredQuestion
tagged with: web-scraping
tagged with: scrapy
has answer: http://stackoverflow.com/a/51888652
has comment: http://stackoverflow.com/comment/90702637
type: Question
has body: The response url while scrolling down is: https://dir.dummymart.com/impcat/next?mcatId=20467&prod_serv=P&mcatName=laser-cutting-machines&srt=97&end=116&ims_flag=&cityID=&fcilp=0&pr=0&pg=5&frsc=28 The response data is in ajax like this: {"page_var":"<div id=\"page_variables................ My spider code is : import scrapy class DummymartSpider(scrapy.Spider): name = 'dummymart' allowed_domains = ['dir.dummymart.com'] start_urls = ['https://dir.dummymart.com/impcat/industrial-machinery.html', ] def parse(self, response): Company = response.xpath('//*[@class="lcname"]/text()').extract() product = response.xpath('//*[@class="pnm ldf cur"]/text()').extract() address = response.xpath('//*[@class="clg"]/text()').extract() phone = response.xpath('//*[@class="ls_co phn bo"]/text()').extract() for item in zip(Company,product,address,phone): scraped_info = { 'Company':item[0], 'Product': item[1], 'Address':item[2], 'phone':item[3] } yield scraped_info How do i scrape datas that are loaded after the page is scrolled down? Also the data is in ajax not json. Thanks
answer count: 1
has title: scrape data from infinite scrolling page using scrapy?
tagged with: ajax
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/90705156
has comment: http://stackoverflow.com/comment/90701518

http://stackoverflow.com/comment/90862483
type: Comment
has text: @СтепанБандера exactly :) - just input and press enter. The break would matter only if it was inside the while and that would give you just 1 game anyway. Note that this is your whole program + the additional choices that I skipped.
type: AnswerComment
comment on: http://stackoverflow.com/a/51955814
score: 0

http://stackoverflow.com/q/51908482
favorite count: 0
tagged with: python-3.x
linked to: http://stackoverflow.com/q/15121717
type: UnansweredQuestion
score: -3
tagged with: python
has answer: http://stackoverflow.com/a/51908684
upvote count: 0
has comment: http://stackoverflow.com/comment/90767158
type: Question
has body: I want to do simple addtion using argv in python. Here is my code: import sys x = int(sys.argv[1]) y = int(sys.argv[2]) z = x + y print(z) I am running this program in python 3.4, but it is throwing IndexError. Any suggestions?
answer count: 2
duplicate of: http://stackoverflow.com/q/4117530
has title: how to do simple addtion using argv function in python
linked to: http://stackoverflow.com/q/4117530
has answer: http://stackoverflow.com/a/51908699
downvote count: 3

http://stackoverflow.com/q/51939257
has comment: http://stackoverflow.com/comment/96304939
has comment: http://stackoverflow.com/comment/95702294
has title: How do you get the filename of a Python wheel when running setup.py?
answer count: 3
has comment: http://stackoverflow.com/comment/95636917
downvote count: 0
favorite count: 0
upvote count: 25
tagged with: setup.py
tagged with: python-wheel
possible better answer: http://stackoverflow.com/a/51943921
has body: I have a build process that creates a Python wheel using the following command: python setup.py bdist_wheel The build process can be run on many platforms (Windows, Linux, py2, py3 etc.) and I'd like to keep the default output names (e.g. mapscript-7.2-cp27-cp27m-win_amd64.whl) to upload to PyPI. Is there anyway to get the generated wheel's filename (e.g. mapscript-7.2-cp27-cp27m-win_amd64.whl) and save to a variable so I can then install the wheel later on in the script for testing? Ideally the solution would be cross platform. My current approach is to try and clear the folder, list all files and select the first (and only) file in the list, however this seems a very hacky solution.
has comment: http://stackoverflow.com/comment/90947535
tagged with: python
has answer: http://stackoverflow.com/a/51943921
linked to: http://stackoverflow.com/q/60643710
score: 25
has comment: http://stackoverflow.com/comment/95650631
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90939204
has answer: http://stackoverflow.com/a/60773383
tagged with: cross-platform
type: Question
has answer: http://stackoverflow.com/a/62351713
accepted answer: http://stackoverflow.com/a/60773383
has comment: http://stackoverflow.com/comment/116609542

http://stackoverflow.com/a/51948145
type: AcceptedAnswer
has body: I am not sure, but I think that the problem is that olefile has no understanding of Word documents, only OLE "streams". So I would guess that your extracted data has more than plain text in, control characters of some kind. So I guess that's why you can't decode the data you get as UTF-16. There are Python modules to convert from doc files, but they tend to work only on Linux where they make use of the command line utilities antiword or catdoc. I tried other solutions - if the issue is that you have no license for Word, but can otherwise install software, LibreOffice could be a path forward. With this command, I converted a Word test file with Chinese letters from doc format to HTML: "c:\Program Files\LibreOffice\program\swriter.exe" --convert-to html d.doc LibreOffice can also convert to many other formats, but HTML should be simple enough to process further. I also tried a port of catdoc to Windows but I couldn't get it to handle the Chinese letters. Too bad you don't have Word installed, or you could have made it do the work for you. Leaving that solution here in case someone else has use for it: import win32com.client app = win32com.client.Dispatch("Word.Application") try: app.visible = False wb = app.Documents.Open('c:/temp/d.doc') doc = app.ActiveDocument with open('out.txt', 'w', encoding = 'utf-16') as f: f.write(doc.Content.Text) except Exception as e: print(e) finally: app.Quit()
upvote count: 2
type: Answer
score: 1
downvote count: 1
accepted answer of: http://stackoverflow.com/q/51943121
has comment: http://stackoverflow.com/comment/90868510
answers question: http://stackoverflow.com/q/51943121
has comment: http://stackoverflow.com/comment/90883974

http://stackoverflow.com/comment/90826697
type: AnswerComment
type: Comment
has text: did it for you, tests looks fine :)
score: 1
comment on: http://stackoverflow.com/a/51938225

http://stackoverflow.com/comment/90828713
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51939224
has text: I see that you also consider the intersection of two straight lines as a point on the black line. Since you have same `x` axis but different `y` axis, you would definitely need some continuous curve or some sort of interpolation on a fine mesh with same number of `y` values so that you can use some loop or in built function to get the `min` and `max` at each `y` value. Having this, it's straightforward to fill the space between them.

http://stackoverflow.com/comment/90573617
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51808970
has text: Are you sure that your file and console are running in the same directory? It might very well be that there are two different `bookList0.txt` files.
score: 0

http://stackoverflow.com/comment/90624544
type: QuestionComment
comment on: http://stackoverflow.com/q/51835271
has text: Not impossible per se - just loss of data and doesn't make sense... not quite sure where *function composition* comes into this when the examples are updating `dict`s :)
score: 0
type: Comment

http://stackoverflow.com/comment/90762832
comment on: http://stackoverflow.com/a/51906180
score: 0
type: AnswerComment
type: Comment
has text: Or you can use `-lboost_python37` instead

http://stackoverflow.com/comment/90738559
score: 0
comment on: http://stackoverflow.com/q/51893873
type: Comment
type: QuestionComment
has text: Doesn't `str.replace(' ', r'%20')` work just as well? Unless it does something that's slower than `join()`

http://stackoverflow.com/q/51867912
has comment: http://stackoverflow.com/comment/90687906
type: Question
has comment: http://stackoverflow.com/comment/90687832
answer count: 1
downvote count: 0
has title: Splitting code into modules (conventions)
favorite count: 0
tagged with: python-3.x
tagged with: python
has answer: http://stackoverflow.com/a/51868053
has comment: http://stackoverflow.com/comment/90687944
accepted answer: http://stackoverflow.com/a/51868053
type: AnsweredQuestion
has body: So I've been searching for a bit and couldn't find anything on Google or PEP discussing this. I am doing a project with tkinter and I had a file, that is part of a project, that was only 200 lines of code (excluding all the commented out code). While the entire file was related to the GUI portion of the project, it felt a bit long and a bit broad to me. I ended up splitting the file into 4 different files that each has its own portion of the GUI. Basically, the directory looks like this: project/ guiclasses/ statisticsframe.py textframes.py windowclass.py main_gui.py ... statisticsframe has a class of a frame that shows statistics about stuff. textframes holds 3 classes of frames holding textareas, one of them inherits Frame, the others inherit the first one. windowclass basically creates the root of the window and all the general initialization for a tkinter GUI. main_gui isn't actually the name but it simply combines all the above three and runs the mainloop() Overall, each file is now 40-60 lines of code. I am wondering if there are any conventions regarding this. The rule of thumb in most languages is that if you can reuse the functions/ classes elsewhere then you should split, though in Python it is less of a problem since you can import specific classes and functions from modules. Sorry if it isn't coherent enough, nearly 3AM here and it is simply sitting in the back of my head.
has comment: http://stackoverflow.com/comment/90687851
score: 1
upvote count: 1
tagged with: conventions

http://stackoverflow.com/q/51909232
has answer: http://stackoverflow.com/a/51909694
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/51909694
favorite count: 0
linked to: http://stackoverflow.com/q/39556917
has title: Django - use template tags in if statement
has comment: http://stackoverflow.com/comment/90768925
tagged with: django
duplicate of: http://stackoverflow.com/q/39556917
tagged with: python
has comment: http://stackoverflow.com/comment/90770191
has comment: http://stackoverflow.com/comment/90768626
type: AnsweredQuestion
tagged with: django-templates
tagged with: django-tagging
upvote count: 10
has body: I saw similar questions but none of them solved my problem . I have a simple template tag like this : @register.simple_tag def liked_by_user(post_id, user): try: PostModel.objects.get(pk=post_id).like_set.get(user=user) return True except: return False and i want to use this in an if statement like this : {% if liked_by_user post.pk request.user %} doing somethin... {% else %} doing somethin... {% endif %} what can i do ?
type: Question
has comment: http://stackoverflow.com/comment/90769397
score: 10

http://stackoverflow.com/q/51826127
score: 0
tagged with: django
answer count: 1
accepted answer: http://stackoverflow.com/a/51826424
has body: I have a template view in django, On that template i have a download button: Download file URL: path('<int:pk>/edit/download/', smarts_cfg_views.CgfFileDownload.as_view(), name='template-download'), View: class CgfFileDownload(View): def get(self, request, pk): content = MODEL_NAME.objects.get(pk=pk).name response = HttpResponse(content, content_type='text/plain') response['Content-Disposition'] = 'attachment; filename=%s' % 'testing.txt' return response It works as intended. What i want to do is before pressing the button and downloading the file, i want user to fill a field on the template and i want to pass this information to the download view (without saving it in the database). What is the best way to do it? thanks!
type: AnsweredQuestion
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/51826424
has title: Django file download pass value from template view

http://stackoverflow.com/q/51801883
score: 0
has body: I am trying to write a big program where i do server client communication and everything works but when i am trying to store the client data into Mongodb which is connected at server-side, i am getting error as follows. Error: TypeError: document must be an instance of dict, bson.son.SON, bson.raw_bson.RawBSONDocument, or a type that inherits from collections.MutableMapping At client side my data type shows as string and at server side when i printed the type it says its bytes. But why bytes are not storing in the database. Please post your ideas, I am also new to python. Thanks ServerSide: import re #getting ip address from machine and bd it to the client class C(): if __name__ == "__main__": ethernet_card = "wlp3s0" ip = ip1(ethernet_card) self.sock.bind((ip,4242)) self.clients_list = [] def talkToClient(self, ip): self.sock.sendto("ok".encode('utf-8'), ip) def listen_clients(self): #listen to multiple clients def parse(msg): uri = "mongodb://localhost:27017" client = pymongo.MongoClient(uri) database = client['orchtrail'] collection = database['testData'] result = database.testData.insert_many(msg) testData = collection.find({}) for test in testData: print(test) result.inserted_id while True: msg, client = self.sock.recvfrom(1024) print(type(msg)) print(msg) parse(msg) print('connected with : ' + client[0]+ ':' + str(client[1])) t = threading.Thread(target= self.talkToClient,args=(client,)) t.start() if __name__=='__main__': C= C() C.broad(msg="") C.listen_clients() client side temperature="" hum="" json=json.dumps({"temp"=temperature,"hum":hum}) msg=json self.sock.sendto(msg.encode(),address)
answer count: 1
has answer: http://stackoverflow.com/a/51802476
type: UnansweredQuestion
tagged with: python
tagged with: multithreading
has title: TypeError: While storing the bytes to mongo db using python
type: Question
tagged with: mongodb

http://stackoverflow.com/a/60788286
has body: To start I recommend to convert your .edf to an .asc file. In this way it is easier to read it to get a first impression. For this there exist many tools, but I used the SR-Research Eyelink Developers Kit (here). I don't know your setup but the Eyelink 1000 itself detects saccades and fixation. I my case in the .asc file it looks like that: SFIX L 10350642 10350642 864.3 542.7 2317.0 ... ... 10350962 863.2 540.4 2354.0 EFIX L 10350642 10350962 322 863.1 541.2 2339 SSACC L 10350964 10350964 863.4 539.8 2359.0 ... ... 10351004 683.4 511.2 2363.0 ESACC L 10350964 10351004 42 863.4 539.8 683.4 511.2 5.79 221 The first number corresponds to the timestamp, the second and third to x-y coordinates and the last is your pupil diameter (what the last numbers after ESACC are, I don't know). SFIX -&gt; start fixation EFIX -&gt; end fixation SSACC -&gt; start saccade ESACC -&gt; end saccade You can also check out PyGaze, I haven't worked with it, but searching for a toolbox, this one always popped up. EDIT I found this toolbox here. It looks cool and works fine with the example data, but sadly does not work with mine EDIT No 2 Revisiting this question after working on my own Eyetracking data I thought I might share a function wrote, to work with my data: def eyedata2pandasframe(directory): ''' This function takes a directory from which it tries to read in ASCII files containing eyetracking data It returns eye_data: A pandas dataframe containing data from fixations AND saccades fix_data: A pandas dataframe containing only data from fixations sac_data: pandas dataframe containing only data from saccades fixation: numpy array containing information about fixation onsets and offsets saccades: numpy array containing information about saccade onsets and offsets blinks: numpy array containing information about blink onsets and offsets trials: numpy array containing information about trial onsets ''' eye_data= [] fix_data = [] sac_data = [] data_header = {0: 'TimeStamp',1: 'X_Coord',2: '…
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/51809979
upvote count: 1

http://stackoverflow.com/comment/90743525
type: Comment
has text: Not in Python you can't
score: 1
comment on: http://stackoverflow.com/a/51895591
type: AnswerComment

http://stackoverflow.com/q/51820831
accepted answer: http://stackoverflow.com/a/51821747
tagged with: django
has body: I'm trying to build a web application using Django where a user can create a 'Project' and within that 'Project', there are four different forms. My Question is, how do I associate those forms to a specific 'project' in the sense that the form is linked to that specific 'project'. I'm close to doing it but I'm having issues with the 'create-project.html', 'create-request-1.html' and 'create-request-2.html' pages from rendering due to the 'PK' in the 'projects.html' page URL. The exact errors I get for navigating to those pages is - NoReverseMatch at /projects/create-project/ Reverse for 'initiate_project' with no arguments not found. 1 pattern(s) tried: ['projects\\/project\\/(?P<pk>[0-9]+)\\/$'] Or NoReverseMatch at /project/create-post-1/ Reverse for 'initiate_project' with no arguments not found. 1 pattern(s) tried: ['projects\\/project\\/(?P<pk>[0-9]+)\\/$'] The path is as follows - 'projects.html' - 'create-project.html' - 'initiate-project.html' - 'create-request-1.html' 'create-request-2.html' I can navigate and go into each unique 'project' (e.g. project 1, project 2) in 'projects.html' but I can't get into my forms ('create-request-1.html', 'create-request-2.html') inside the 'initiate-project.html' page that's within each 'project' in the 'projects.html' page. Here's my code so far - model.py - from django.db import models class create_new_project(models.Model): list_display = ('project_name', 'project_manager', 'technical_lead', 'test_lead') class Meta: verbose_name = 'Create New Project' verbose_name_plural = 'Create New Projects' project_name = models.CharField(max_length=100) project_manager = models.CharField(max_length=100) technical_lead = models.CharField(max_length=100) test_lead = models.CharField(max_length=100) environment_choices = ( ('1', '1'), ('2', '2'), ('3', '3') ) environment = models.CharField( max_length=50, choices=environment_choices, default='ICCS') def __str__(self): return self.project_name views.py from django.shortcuts import re…
tagged with: model-view-controller
type: AnsweredQuestion
type: Question
answer count: 1
has answer: http://stackoverflow.com/a/51821747
tagged with: url
has title: Associate multiple unique forms to a unique object in Django
score: 0
tagged with: python

http://stackoverflow.com/a/51803069
upvote count: 1
has body: Conditional operator result = value if value else "" This is the ternary conditional operator and basically equivalent to the following if statement: if value: result = value else: result = "" It is very explicit and allows you to describe exactly what condition you require. In this case, it just looks at the truthy value of value, but you could easily expand this to make a strict test against None for example: result = value if value is not None else "" This would for example retain falsy values like False or 0. or operator value or "" This uses the boolean or operator: The expression x or y first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned. So this is basically a way to get the first truthy value (defaulting to the right operand). So this does the same as the value if value else "". Unless the conditional operator, it does not support other checks though, so you can only check for truthiness here. Comparison In your case, where you want to just check against None and fall back to an empty string, there’s no difference at all. Just choose what is most understandable to you. From a “pythonic” point of view, one would probably prefer the or operator, as that’s also a bit shorter. From a performance standpoint, the conditional operator is slightly more expensive in this case, as this needs to evaluate the dictionary access twice. In practice that won’t be noticeable though, especially not for a dictionary access. If you do believe that this could have an impact on your application performance, then you should not believe in numbers you get from isolated benchmarks of a single statement; instead, you should profile your application and then try to identify bottlenecks which you can then improve on. I’ll guarantee you that it will be a long way before a second dictionary access will have any impact. So yes, you can totally ignore the performance arguments for this. Just choose whatever you prefer, what …
downvote count: 0
type: Answer
score: 1
answers question: http://stackoverflow.com/q/51802974

http://stackoverflow.com/a/51883366
has body: Break inner the loop on 1st found. and you don't need a continue cleandata = [] data = [{'text':'some string1 word1 word2','another key':'some other text'}, {'text':'some string2 word1', 'another key':'some other text 2'}] words = ['word1','word2'] for d in data: for word in words: if word in d['text']: cleandata.append(d) break
score: 4
upvote count: 4
accepted answer of: http://stackoverflow.com/q/51883103
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90718439
type: Answer
answers question: http://stackoverflow.com/q/51883103

http://stackoverflow.com/comment/90818623
type: Comment
comment on: http://stackoverflow.com/a/51934282
has text: Within Databricks, where did the file go? Maybe I can just manually grab it from there. Please advise.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/90697757
score: 0
type: Comment
has text: Thx. I modified the frontend with django template {% static %} finally.
comment on: http://stackoverflow.com/a/51839323
type: AnswerComment

http://stackoverflow.com/comment/90686650
score: 1
has text: You probably want to use the second method there: `await client.send_message(client.get_channel('12324234183172'), 'hello')`. The `Object` class resolving items based on their ids works, but it's really easy to lose track of what the type of that object should be, espescially when your bots start getting large.
type: AnswerComment
comment on: http://stackoverflow.com/a/51867380
type: Comment

http://stackoverflow.com/q/51873851
has body: I have a dataset of 129,013 files and want to encode them linewise, i.e. one line occuring is one token. I used the countVectorizer from scikit learn and went with vec = CountVectorizer(input='filename', token_pattern='.+') dtm = vec.fit_transform(all_paths) # all paths is a list with all filename paths print(dtm.shape) # (129013 , 541107) In the research paper, the dataset is referring to, the authors speak about 545,333 different tokens, i.e. my tokenizer did not catch everything. To check if my dataset is complete i ran for f in *; do cat $f; done | sort | uniq | wc -l 545333 in a bash shell indicating that everything is there. What am I missing here?
answer count: 1
downvote count: 0
tagged with: scikit-learn
tagged with: countvectorizer
has answer: http://stackoverflow.com/a/51874717
favorite count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
score: 1
type: Question
has title: Scikit Learn Count Vectorizer does not find all tokens

http://stackoverflow.com/q/51853060
has comment: http://stackoverflow.com/comment/90671552
has comment: http://stackoverflow.com/comment/90670997
tagged with: web-scraping
tagged with: request
type: Question
has title: Getting past a login page in Python
tagged with: session
score: 0
tagged with: python-3.x
has body: For some reason I cannot get my head around using the requests.Session() function to save login credentials. My current code isn't working and I cannot figure out why, can someone help correct my code and explain the changes that were needed? I don't want to keep asking for help on a website by website basis. headers = { 'Content-type': 'text/html', 'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.97 Safari/537.36', 'origin':'https://stockinvest.us', 'referer':'https://stockinvest.us' } data = {'email':'user-email', 'password: 'user-password'} with requests.Session() as s: login = s.post('https://stockinvest.us/login', data=data, headers=headers) s.cookies r = s.get('https://stockinvest.us/profile/edit')
has comment: http://stackoverflow.com/comment/90723539
type: UnansweredQuestion
tagged with: python
answer count: 0

http://stackoverflow.com/comment/90676688
score: 0
type: Comment
type: QuestionComment
has text: its a sudo file its just two words there are many more I just want to clear about concept so I given this
comment on: http://stackoverflow.com/q/51862123

http://stackoverflow.com/q/51914767
type: Question
has comment: http://stackoverflow.com/comment/90779446
has answer: http://stackoverflow.com/a/51915565
upvote count: 0
has comment: http://stackoverflow.com/comment/90786217
answer count: 1
favorite count: 0
has body: def insertion_sort2(A): for i in range(1,len(A)): key = A[i] j = i-1 for j in range(i-1,0,-1): if A[j] &gt; key : A[j+1] = A[j] else: A[j+1] = key break for i in range(1, len(arr)): key = arr[i] j = i-1 while j &gt;=0 and key &lt; arr[j] : arr[j+1] = arr[j] j -= 1 arr[j+1] = key Hello I have tried both methods to do simple Insertion Sort in c++ it works but in python it is not working,but both of them are giving answers like 1st one: [56, 77, 77, 77, 77, 77, 77, 99] 2nd one: does not sort even Note:The second one starts after break and I have not run them both together,I commented out one and then run the other one
type: UnansweredQuestion
has title: Insertion Sort in python using Key
tagged with: python
has comment: http://stackoverflow.com/comment/90779628
score: -1
has comment: http://stackoverflow.com/comment/90779547
tagged with: insertion-sort
downvote count: 1

http://stackoverflow.com/q/51810185
linked to: http://stackoverflow.com/q/62728083
has comment: http://stackoverflow.com/comment/110939973
score: 6
tagged with: python
has title: How to name keras model based on functional api
upvote count: 6
type: AnsweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/90575969
accepted answer: http://stackoverflow.com/a/51810878
has body: I know how to set name of keras model when used sequential but I don't know how to name a functional api based model. Let me re-phrase, I am asking how to set name of a keras model not the layer Solved Well I experimented a little and it worked, so to name functional api based keras model, just pass the input in Model as follows: Model(inputs=inputs, outputs=dense_out, name=name)
answer count: 1
downvote count: 0
tagged with: keras
favorite count: 0
has answer: http://stackoverflow.com/a/51810878

http://stackoverflow.com/q/51906971
type: UnansweredQuestion
tagged with: python
has title: Find words including ":" in a list with Python
has comment: http://stackoverflow.com/comment/90764768
tagged with: list
has comment: http://stackoverflow.com/comment/90764539
has comment: http://stackoverflow.com/comment/90766967
type: Question
has answer: http://stackoverflow.com/a/51907002
score: -2
has comment: http://stackoverflow.com/comment/90766654
has answer: http://stackoverflow.com/a/51907017
tagged with: list-comprehension
upvote count: 2
downvote count: 4
answer count: 3
favorite count: 0
has body: I have a list which has some words. I want to filter out words including ":". How can I write a code to separate them from other words?
has comment: http://stackoverflow.com/comment/90764286
has answer: http://stackoverflow.com/a/51907192

http://stackoverflow.com/a/51889679
has body: You can try below code : &gt;&gt;&gt; zones_string = 'a b c' &gt;&gt;&gt; zones_list = zones_string.split(' ') &gt;&gt;&gt; zones_list [ 'a', 'b', 'c' ]
has comment: http://stackoverflow.com/comment/90732430
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51889653

http://stackoverflow.com/comment/90857222
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51953394
has text: But your non-for loop version doesn't make a list, it just prints things. Do you want to select only elements of the list which have `.pdf` in them (or, better, end with `.pdf`?)
type: QuestionComment

http://stackoverflow.com/q/51840787
tagged with: python-3.x
has body: Say, I have two lists: a = [1,2,3] and b = [2,3,1] If I do a a == b it returns False, If I check sorted(a) == sorted(b), it returns True. Now, I have two objects: obj1 = {'a': 1, 'b': 2, 'c': [1, 2]} and obj2 = {'b': 2, 'a': 1, 'c': [1, 2]} obj1 == obj2 is True, irrespective of the order of keys. But if obj2 = {'b': 2, 'a': 1, 'c': [2, 1]} how do I test the equality? Obviously, obj1 == obj2 returns False. sorted(obj1) will have ['a', 'b', 'c'], so sorted(obj1) == sorted(obj2) is kind of waste check. I should have probably overridden the equality method for the object, or use some library. Is, is there any way to write idiomatic python code for deep equality?
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90634562
tagged with: pytest
upvote count: 2
score: 1
has comment: http://stackoverflow.com/comment/90634745
possible better answer: http://stackoverflow.com/a/51841111
has answer: http://stackoverflow.com/a/51840911
downvote count: 1
has answer: http://stackoverflow.com/a/51841111
type: Question
answer count: 2
has title: dictionary with lists custom equality check
accepted answer: http://stackoverflow.com/a/51840911
has comment: http://stackoverflow.com/comment/90635109
favorite count: 0

http://stackoverflow.com/q/51908926
tagged with: python-3.x
has body: I have this numpy ndarray nd. [['BO' '05-02-2009' 1.0718954248366013 1.1620915032679742 1.0045751633986928 1.1130718954248366 272564] ['BO' '06-02-2009' 1.1339869281045751 1.1941176470588235 1.1189542483660129 1.1718954248366011 189758] ['BO' '09-02-2009' 1.1705882352941177 1.1725490196078432 1.1320261437908496 1.1601307189542482 109528]] I want to delete the first column, 2nd column and last column. nd with the deleted columns will look like this; [[1.0718954248366013 1.1620915032679742 1.0045751633986928 1.1130718954248366 ] [1.1339869281045751 1.1941176470588235 1.1189542483660129 1.1718954248366011 ] [1.1705882352941177 1.1725490196078432 1.1320261437908496 1.1601307189542482 ]] I tried to delete the column using the code below; import numpy as np nd = np.delete(nd, 1, 0) # delete column 1 nd = np.delete(nd, 1, 1) # delete column 2 nd = np.delete(nd, 1, 4) # delete column 7 However, the columns remain. How can the columns be deleted?
accepted answer: http://stackoverflow.com/a/51908978
type: Question
tagged with: python
answer count: 1
upvote count: 1
tagged with: numpy
tagged with: numpy-ndarray
has answer: http://stackoverflow.com/a/51908978
has title: How to delete columns 1,2,7 of this numpy ndarray?
type: AnsweredQuestion
downvote count: 0
score: 1
favorite count: 0

http://stackoverflow.com/comment/90855456
comment on: http://stackoverflow.com/q/51945248
has text: That is correct, all you can do is ask/explain that in order for MQ to detect a network issue as soon as possible that the IBM default of 300 from 20 years ago is no much too high. if it is less than 60 the timeout is 2*HBINT, if it is 60 or greater the timeout is HBINT+60. Any MQ Admin that understands the technology should be willing to set this lower, it will benefit them as well since they will clear up defunct channel processes sooner.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90601148
type: Comment
type: QuestionComment
has text: Why have three close-voters voted this question as off-topic? It looks like *a specific programming problem* which is on-topic as per https://stackoverflow.com/help/on-topic. Why is this being voted as off-topic?
score: 0
comment on: http://stackoverflow.com/q/51823203

http://stackoverflow.com/comment/90643506
comment on: http://stackoverflow.com/a/51844269
score: 0
type: AnswerComment
type: Comment
has text: Ok, thanks alot. This really helped me alot. Using Inspect I also found the XHR from boerse-frankfurt.de for ticks and Intraday ranging with different timestamps, for example [here](http://proxy.boerse-frankfurt.de/cst/BoerseFrankfurt/Share/chart.json?instruments=16830,998032,830,814&period=Intraday) which prints out all data of the day or [here](http://charts.finanzen.net/ChartData.ashx?request=HISTORY+998032;830;814+TICKS+100), printing only a number of sets (100 in this case). This can also be altered to intraday, replacing `TICKS` with `INTRADAY 1`, 5, 60 etc. where 1, 5... is the tick.

http://stackoverflow.com/comment/90617887
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51831634
has text: You should never need to set ticks manually (but you can of course). What's the reason to use `set_ticklabels` in the first place?
score: 0

http://stackoverflow.com/q/51908541
has comment: http://stackoverflow.com/comment/90767228
has comment: http://stackoverflow.com/comment/90768183
answer count: 0
type: UnansweredQuestion
has body: I make my GUI calculator and compile it with pyinstaller. All is Ok, I add an icon to it with the help of pyinstaller. But i also want icon to be in the right top corner. I try to add: root.iconbitmap('calculator.ico') But when I open .exe file after compiling I get an error. What can i do?
type: Question
has comment: http://stackoverflow.com/comment/90768537
has comment: http://stackoverflow.com/comment/90767190
tagged with: python
tagged with: tkinter
score: 0
has title: Adding icon to Tkinter GUI while compiling

http://stackoverflow.com/comment/90721488
has text: I don't think this is a basic question; I actually never saw a full description of execution order of all framework parts. If in doubt, write a small test project that prints statements and analyze the output, see [my other answer](https://stackoverflow.com/a/51685073/2650249) where I check the execution order of test class fixtures and methods.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51884507
score: 1

selenium
tags question: http://stackoverflow.com/q/51873603
tags question: http://stackoverflow.com/q/51865300
tags question: http://stackoverflow.com/q/51837901
tags question: http://stackoverflow.com/q/51849234
tags question: http://stackoverflow.com/q/51815106
tags question: http://stackoverflow.com/q/51838719
tags question: http://stackoverflow.com/q/51811762
tags question: http://stackoverflow.com/q/51900046
tags question: http://stackoverflow.com/q/51940907
tags question: http://stackoverflow.com/q/51885140
tags question: http://stackoverflow.com/q/51869254
tags question: http://stackoverflow.com/q/51907791
tags question: http://stackoverflow.com/q/51870889
tags question: http://stackoverflow.com/q/51919821
tags question: http://stackoverflow.com/q/51831970
tags question: http://stackoverflow.com/q/51822138
tags question: http://stackoverflow.com/q/51878006
tags question: http://stackoverflow.com/q/51833805
tags question: http://stackoverflow.com/q/51916961
tags question: http://stackoverflow.com/q/51799251
tags question: http://stackoverflow.com/q/51852893
tags question: http://stackoverflow.com/q/51867761
tags question: http://stackoverflow.com/q/51850011
tags question: http://stackoverflow.com/q/51953062
tags question: http://stackoverflow.com/q/51952707
tags question: http://stackoverflow.com/q/51813334
tags question: http://stackoverflow.com/q/51843237
tags question: http://stackoverflow.com/q/51921221
tags question: http://stackoverflow.com/q/51845668
tags question: http://stackoverflow.com/q/51932852
tags question: http://stackoverflow.com/q/51937046
tags question: http://stackoverflow.com/q/51878819
tags question: http://stackoverflow.com/q/51807299
tags question: http://stackoverflow.com/q/51888636
tags question: http://stackoverflow.com/q/51847645
tags question: http://stackoverflow.com/q/51911439
tag name: selenium
tags question: http://stackoverflow.com/q/51955896
tags question: http://stackoverflow.com/q/51854268
tags question: http://stackoverflow.com/q/51865429
tags question: http://stackoverflow.com/q/51857320
tags question: http://stackoverflow.com/q/51893564
tags question: http://stackoverflow.com/q/51916797
tags question: http://stackoverflow.com/q/51903521
tags question: http://stackoverflow.com/q/51954010
tags question: http://stackoverflow.com/q/51846188
tags question: http://stackoverflow.com/q/51878000
tags question: http://stackoverflow.com/q/51808255
tags question: http://stackoverflow.com/q/51847670
tags question: http://stackoverflow.com/q/51915039
tags question: http://stackoverflow.com/q/51807477
tags question: http://stackoverflow.com/q/51901141
tags question: http://stackoverflow.com/q/51909466
tags question: http://stackoverflow.com/q/51921415
tags question: http://stackoverflow.com/q/51817104
tags question: http://stackoverflow.com/q/51908229
tags question: http://stackoverflow.com/q/51832019
tags question: http://stackoverflow.com/q/51848530
tags question: http://stackoverflow.com/q/51806436
tags question: http://stackoverflow.com/q/51896615
tags question: http://stackoverflow.com/q/51838630
tags question: http://stackoverflow.com/q/51805184
tags question: http://stackoverflow.com/q/51895714
tags question: http://stackoverflow.com/q/51812302
tags question: http://stackoverflow.com/q/51905101
tags question: http://stackoverflow.com/q/51924128
tags question: http://stackoverflow.com/q/51825077
tags question: http://stackoverflow.com/q/51892846
tags question: http://stackoverflow.com/q/51888181
tags question: http://stackoverflow.com/q/51890887
tags question: http://stackoverflow.com/q/51871856
tags question: http://stackoverflow.com/q/51911615
type: Tag
tags question: http://stackoverflow.com/q/51887473
tags question: http://stackoverflow.com/q/51942665
tags question: http://stackoverflow.com/q/51888615
tags question: http://stackoverflow.com/q/51941841
tags question: http://stackoverflow.com/q/51927757
tags question: http://stackoverflow.com/q/51928064
tags question: http://stackoverflow.com/q/51802268

http://stackoverflow.com/comment/90814441
type: Comment
score: 0
type: AnswerComment
has text: One more, imagine I need to add not only constants but also a variable (because I have to launch many times this command inside a loop), so `'index_OUT'` needs to be a vector not always [1, 1], but in general [my_num, my_num]. Because `format` with `{} {}` does not seem to work. Thx.
comment on: http://stackoverflow.com/a/51931732

http://stackoverflow.com/comment/90727650
type: Comment
comment on: http://stackoverflow.com/a/51869895
has text: Comments are superbad for more than one line of code, and that goes double for Python which has indent syntax. `fnmatch` matching and `regexp` matching are two different kinds of matching - you can't give `fnmatch` a regular expression, if that's what you were trying to do. And even so, compiled regular expressions are created by `needle = re.compile(regex_string)`, then you can use it as `needle.search(haystack)`; `re.search(regex_string, haystack)` is a shortcut that does this together.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/90831172
has text: @ZizhengWu: Because `**kwargs` is defined to mean "act as if all the key/value pairs in the dictionary were passed one-by-one as keyword arguments". Function calls reject duplicated arguments precisely because of the confusion involved in accidentally passing duplicate arguments; normally this is because someone passes an argument positionally and by keyword, but passing twice by keyword is equally wrong.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51940623

http://stackoverflow.com/a/51866299
downvote count: 0
answers question: http://stackoverflow.com/q/51866182
score: 1
type: Answer
upvote count: 1
has body: Try to use str accessor with split using a regex that looks for a space and open paranthesis or close paranthesis: df.title.str.split('\s\(|\)',expand=True) .drop(2, axis=1) .set_axis(['movies','year'], inplace=False, axis=1) Output: movies year 0 Toy Story 1995 1 Jumanji 1995 2 Grumpier Old Men 1995 3 Waiting to Exhale 1995 4 Father of the Bride Part II 1995

http://stackoverflow.com/comment/90577056
type: QuestionComment
comment on: http://stackoverflow.com/q/51810888
type: Comment
has text: @jezrael Yes. I have added the plotting part.
score: 0

http://stackoverflow.com/a/51844073
downvote count: 0
answers question: http://stackoverflow.com/q/51806400
type: Answer
upvote count: 2
has body: This model appears to need several changes to be directly servable. One requirement of the service is that each of the inputs have an unspecified outer dimension which is interpreted as the "batch" dimension. The inputs input_x and sequence_length meet this requirement, but batch_size and keep_prob do not. The service dynamically builds batches which is why it needs to be variable length. Thus, have an input called batch_size is going to be problematic, since the service doesn't know that it should be setting that input. Instead, it builds up a batch and sends it to TensorFlow. TensorFlow already knows the batch size because it's the value of the outer dimension of inputs such as input_x. Instead of using batch_size as an input, it's preferable to do something like: batch_size = tf.shape(input_x)[0] Although I will note that even the need for that is usually fairly rare in practice. Things usually "just work", because input_x is used in some sort of operation like a matrix multiply or convolution which will handle things fine without explicitly knowing the batch size. Finally, there is keep_prob, which usually indicates there is a dropout layer in the model. Even though you can hard code this to 1.0, it's usually recommended that you just remove dropout layers altogether for serving. Basically, when you export the model, you actually build a different graph than for training. This is exemplified in this sample.
score: 2

http://stackoverflow.com/a/51877165
answers question: http://stackoverflow.com/q/51876184
type: Answer
upvote count: 1
score: 1
has body: You can also use the np.gradient function and look where the gradient changes sign: z = np.gradient(y, x) i = 0 while i &lt; len(x)-2: if (z[i]*z[i+2]&lt;=0 and z[i]&gt;0): #gradient changes sign &gt; optima, and point previous to optima has a positive slope print(i+1, x[i+1], y[i+1]) i = i+1 i+=1 plt.ylim(-1, 1) plt.plot(x, z) Looing at the plot, it seems the point at around 210 is not a maxima (the gradient doesnt reach zero). You can check this by replacing the if statement with the following if (y[i+1]&gt;y[i] and y[i+1]&gt;y[i+2]):
downvote count: 0

http://stackoverflow.com/q/51914837
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/90779789
type: UnansweredQuestion
tagged with: data-visualization
tagged with: python
has body: I have the following function to create a line plot: def plot_genres(genre_list, chart_title): fig, ax = plt.subplots(figsize=(20,10)) plt.xticks(np.arange(1960, 2019, step = 10.0)) plt.yticks(np.arange(3, 10, 0.2)) plt.xlabel('Release Year', fontsize=20) plt.ylabel('Vote Average', fontsize=20) plt.title(chart_title, fontsize=20) for genre, sub_df in test_df.groupby(['genres']): if (genre in genre_list): random_color = [np.random.random_sample() for _ in range(3)] plt.plot('release_year', 'vote_average_mean', data = sub_df, marker = '', markerfacecolor = random_color, markersize = 5, color = random_color, linewidth = 0.5, label = genre) loc = plticker.MultipleLocator(base=1.0) ax.xaxis.set_major_locator(loc) plt.xticks(rotation=45) plt.legend() plt.show() plt.clf() The test_df has columns release_year and vote_average_mean, which I want to be the x and y axis respectively. I've configured it so that genre_list only has one genre in the list, so we would only see a trend line for one genre. Here's the chart that I get: As you can see, there are multiple lines extending from a single plot, but I only want one line to appear for this single genre trend line. As far as I can see, there is only one point for each x-axis, so I'm not sure what the confusion is with the line plot.
answer count: 0
type: Question
has title: Matplotlib/Pandas line plot doesn't connect properly
tagged with: charts
has comment: http://stackoverflow.com/comment/90779617
tagged with: matplotlib

http://stackoverflow.com/comment/90675717
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51861651
has text: Django Version is 2.0.6
type: Comment

http://stackoverflow.com/a/51897696
has body: I would avoid using global and class-scoped variables if at all possible. These can make your program harder to understand (if something else changes a global underneath you it's hard to notice) and test (you need to reset all global state between every test; it's often easier to just create new empty state). I might restructure this example by creating a state object: class State: def __init__(self): self.session_id = '' And then making that explicitly be a property, say, of the base class: class Base: def __init__(self, state): self.state = state def m1(self): print("SESSION_ID in base: " + str(self.state.session_id)) class Derived(Base): def m2(self): self.state.session_id = '10' print("SESSION_ID in derived: " + str(self.state.session_id)) Then in your main function you need to explicitly create the state object and pass it in def main(): state = State() c2 = Derived(state) c2.m2() c2.m1() But, critically, your tests don't need to worry about state leakage def test_m2(): state = State() obj = Derived(state) obj.m2() assert state.session_id == '10' def test_m1(): state = State() obj = Base(state) obj.m1() # If the session ID was a global or a class variable, # you'd get a different result if m2() was called or not assert state.session_id == ''
downvote count: 0
type: Answer
score: 1
answers question: http://stackoverflow.com/q/51897243
upvote count: 1

http://stackoverflow.com/q/51805184
tagged with: gmail
answer count: 0
type: UnansweredQuestion
tagged with: selenium
tagged with: authentication
upvote count: 1
tagged with: selenium-webdriver
linked to: http://stackoverflow.com/q/44856887
has comment: http://stackoverflow.com/comment/90581791
score: 1
has title: Python Gmail auto login script
has comment: http://stackoverflow.com/comment/90581824
has body: I am trying to write a simple Python script that logs in to Gmail(I know it I may violate Gmail terms &amp; conditions, but this is only for testing purpose). I have done proper research on it before posting this question here. but, it still doesn't work. I have watched a video on YouTube and the same code works there, but not in my local machine(I am using Windows 10 on my HP Laptop). Can you please take a look at the below script and let me know if there's any error in it? from selenium import webdriver import time driver = webdriver.Chrome(r'C:\Users\hp\Downloads\chromedriver.exe') driver.get('https://accounts.google.com/signin/v2/identifier?service=mail&amp;passive=true&amp;rm=false&amp;continue=https%3A%2F%2Fmail.google.com%2Fmail%2F&amp;ss=1&amp;scc=1&amp;ltmpl=default&amp;ltmplcache=2&amp;emr=1&amp;osid=1&amp;flowName=GlifWebSignIn&amp;flowEntry=ServiceLogin') email_field = driver.find_element_by_id('identifierId') email_field.clear() email_field.send_keys('My Email ID') email_field_button = driver.find_element_by_id('identifierNext') email_field_button.click() time.sleep(1) password_field = driver.find_element_by_id('password') password_field.clear() password_field.send_keys('My password') password_field_button = driver.find_element_by_id('passwordNext') password_field_button.click() time.sleep(1) This is the error message I am getting: Traceback (most recent call last): File "gmail_login.py", line 6, in &lt;module&gt; driver.get('https://accounts.google.com/signin/v2/identifier?service=mail&amp;passive=true&amp;rm=false&amp;continue=https%3A%2F%2Fmail.google.com%2Fmail%2F&amp;ss=1&amp;scc=1&amp;ltmpl=default&amp;ltmplcache=2&amp;emr=1&amp;osid=1&amp;flowName=GlifWebSignIn&amp;flowEntry=ServiceLogin') File "C:\Users\hp\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 332, in get [6012:9752:0812/071242.870:ERROR:shader_disk_cache.cc(237)] Failed to create shader cache entry: -2 [6012:9752:0812/071242.96…
type: Question
downvote count: 0
duplicate of: http://stackoverflow.com/q/48230370
favorite count: 0
has comment: http://stackoverflow.com/comment/90573513
tagged with: python

http://stackoverflow.com/q/51903504
downvote count: 0
has comment: http://stackoverflow.com/comment/90872936
answer count: 1
has answer: http://stackoverflow.com/a/51905069
favorite count: 0
tagged with: tkinter
type: UnansweredQuestion
has title: Having a little difficulty with adding frames to my program
upvote count: 1
tagged with: python
has body: I'm trying to work on changing the layout of my program but I'm having difficulty adding in frames and in turn widgets into those frames. Partly because I don't fully understand the code I have written below, yet. I have indicated the parts I need help understanding from a frame perspective with a *. The problem I am having is that I would like to split my screen in half width ways so that the top half of the window displays as a red and the bottom blue. To do this I have packed the side in as TOP and BOTTOM respectively; however, there is white space between them. How can I remove this? Thank you, class The99club (Tk): def __init__ (self, *args, **kwargs): Tk.__init__(self,*args,**kwargs) Tk.title(self, 'The 99 Club') container = Frame(self) container.grid(row = 0, column = 0, sticky='nsew')* container.grid_rowconfigure (2,weight = 1)* container.grid_columnconfigure (2,weight = 1)* self.frames = {} for F in (StartPage,PageOne,PageTwo,PageThree,PageFour,PageFive): frame = F (container,self) self.frames[F] = frame frame.grid(row=0, column = 0, sticky = 'nsew')* self.show_frame(StartPage) def show_frame (self, cont): frame = self.frames[cont] frame.tkraise() class StartPage(Frame): def __init__(self, parent, controller): Frame.__init__(self, parent) self.controller = controller self.top_frame = Frame(self, bg = 'red') self.top_frame.pack(side = TOP, fill= X) self.bottom_frame = Frame (self, bg = 'blue') self.bottom_frame.pack(side = BOTTOM, fill = X) label = Label(self.top_frame, text = 'Welcome to The 99 Club', bg = '#66B132',fg='yellow', font = ('Agent Red',30)) label.pack() label2 = Label(self.top_frame, text = 'Press Enter to begin.',bg = '#66B132',fg='yellow',font = ('Comic Sans MS',24)) label2.pack() self.button = Button(self, text = 'Enter',bg = 'yellow',command=lambda: controller.show_frame(PageOne),font = ('Comic Sans MS', 24),relief = SUNKEN) self.button.pack()
score: 1
type: Question

http://stackoverflow.com/comment/90836424
comment on: http://stackoverflow.com/q/51936644
score: 0
type: Comment
type: QuestionComment
has text: Hi @vealkind, I have edited my question and tried to make it more case specific. Let me know if it helped. Thanks a lot man for dropping by!

http://stackoverflow.com/a/51938803
upvote count: 1
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/51803569
has body: I can only offer a butcher's solution, potentially a nightmare to maintain. In my own, very limited scenario, it worked like a charm where several other OCR engines either failed or had unacceptable running times. My prerequisites: I knew exactly in which area of the screen the text was going to go. I knew exactly which fonts and colors were going to be used. the text was semitransparent, so the underlying image interfered, and it was a variable image to boot. I could not detect reliably text changes to average frames and reduce the interference. What I did: - I measured the kerning width of each character. I only had A-Za-z0-9 and a bunch of punctuation characters to worry about. - The program would start at position (0,0), measure the average color to determine the color, then access the whole set of bitmaps generated from characters in all available fonts in that color. Then it would determine which rectangle was closest to the corresponding rectangle on the screen, and advance to the next one. (Months later, requiring more performances, I added a varying probability matrix to test first the most likely characters). In the end, the resulting C program was able to read the subtitles out of the video stream with 100% accuracy in real time.

http://stackoverflow.com/comment/123324187
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51954417
has text: @mathiash got a solution for vector of cdef class? vector is nogil and cdef class can be nogil too, but vector doesn't accept cdef class in template
score: 0

http://stackoverflow.com/a/51940430
accepted answer of: http://stackoverflow.com/q/51940264
score: 4
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51940264
type: Answer
has body: An ugly but vectorized numpy solution: import numpy as np a = np.array([0.53, 0.66, 0.064, 0.94, 0.44]) x = 14.3 idx = np.arange(a.size) 0.9 ** idx * (0.1 * (a * 0.9 ** (-idx)).cumsum() + x * 0.9) # array([12.923 , 11.6967 , 10.53343 , 9.574087 , 8.6606783]) Result from for loop: a = [0.53, 0.66, 0.064, 0.94, 0.44] b = [0.0]*5 x = 14.3 for i in range(5): x = b[i] = a[i]*0.1 + x*0.9 b #[12.923000000000002, # 11.696700000000003, # 10.533430000000003, # 9.574087000000002, # 8.660678300000002] This is because: And components in the result can be vectorized correspondingly, note the sum of a terms in the inner parenthesis is vectorized as cumsum.
upvote count: 4
has comment: http://stackoverflow.com/comment/90831255

http://stackoverflow.com/comment/90657686
comment on: http://stackoverflow.com/q/51852504
type: Comment
score: 0
has text: Is it dumplicate with https://stackoverflow.com/questions/32409629/what-is-the-right-way-to-debug-in-ipython-notebook ?
type: QuestionComment

http://stackoverflow.com/comment/90848062
type: Comment
type: QuestionComment
score: 1
has text: Indent the line after `def sigmoid(x):`
comment on: http://stackoverflow.com/q/51949122

http://stackoverflow.com/comment/90720165
score: 0
type: AnswerComment
type: Comment
has text: You seem to have gotten your sizes a bit mixed up - sometimes you say the array is 8 MB, sometimes you say 4 MB, and in any case, `array('f')` stores 32-bit floats, not 64-bit.
comment on: http://stackoverflow.com/a/51882201

http://stackoverflow.com/q/51838935
downvote count: 0
has comment: http://stackoverflow.com/comment/90635957
tagged with: android
answer count: 1
favorite count: 0
upvote count: 2
type: UnansweredQuestion
has title: Lag between DataOutputStream and DataInputStream using an android client and python server
tagged with: sockets
tagged with: python
score: 2
has answer: http://stackoverflow.com/a/51839378
tagged with: java
type: Question
has comment: http://stackoverflow.com/comment/90631986
has body: I'm having an issue with my android client where I click a button to send data to a python server through a socket, which processes it, then sends it back upper cased. My android client's datainputstream always seems to be "one step behind": the first time I click the button the python server clearly receives it(as shown by the print function) but the TextView in my android doesn't show anything. When I click again with different data the python server receives the new data but my android's dis.readUTF() seems to read the old data. Here is my android client onClick function: public void onClick(View arg0) { Thread t = new Thread(){ @Override public void run() { try { Socket s = new Socket("192.168.4.1", 9999); //OutputStreamWriter osw= new OutputStreamWriter(s.getOutputStream(), "UTF-8"); DataOutputStream dos = new DataOutputStream(s.getOutputStream()); //byte[] bufO=message.getText().toString().getBytes("UTF-8"); dos.writeUTF(message.getText().toString()); DataInputStream dis = new DataInputStream(s.getInputStream()); serverResponse= dis.readUTF(); s.close(); } catch (IOException e) { e.printStackTrace(); } } }; if(message.getText().toString().equals("")){ Toast.makeText(this, "Empty command", Toast.LENGTH_SHORT).show(); } else{ message_received.setText(""); t.start(); Toast.makeText(this, "Command sent", Toast.LENGTH_SHORT).show(); message_received.append(serverResponse + "\n"); Log.d(TAG, serverResponse); } } Here is my Python server: import socketserver import socket class MyHandler(socketserver.BaseRequestHandler): def handle(self): self.sentence= self.request.recv(1024).strip() print(self.sentence) self.request.sendall(self.sentence.upper()) def main(): print ("Opening socket") host='192.168.4.1' port=9999 server1=socketserver.TCPServer((host,port),MyHandler) print ("Running server") server1.serve_forever() main() I've tried different things including adding a thread.sleep between the writeutf() and readutf() but nothing seems to fix this.

http://stackoverflow.com/a/51858095
has body: You can't do this in post_save(), user can only be determined in request
accepted answer of: http://stackoverflow.com/q/51858046
type: Answer
has comment: http://stackoverflow.com/comment/90668364
has comment: http://stackoverflow.com/comment/90668313
answers question: http://stackoverflow.com/q/51858046
score: 0
type: AcceptedAnswer

http://stackoverflow.com/a/51896667
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51896168
has body: mef_list = ["UR", "CPI", "CEI", "Farm", "PCI", "durable", "C_CVM"] form = ['', '_M3', '_M6', '_M9', '_M12', '_LN', '_C'] Variable_new = [] foo = 0 for variable in form: Variable_new.append(mef_list[foo]+variable) foo += 1 print(Variable_new)
has comment: http://stackoverflow.com/comment/90744269
has comment: http://stackoverflow.com/comment/90745167

http://stackoverflow.com/comment/90565780
score: 0
type: Comment
type: QuestionComment
has text: So, each time change test_data values by putting in it 96 values
comment on: http://stackoverflow.com/q/51804842

http://stackoverflow.com/q/51837002
type: Question
answer count: 2
has title: Python - how to get the current weekday without using calendar, datetime
score: 0
has comment: http://stackoverflow.com/comment/90633510
tagged with: datetime
has answer: http://stackoverflow.com/a/51837112
has body: I'm having a little bit of a problem here. My system lets me pip install calendar but for some reason it doesn't recognize it when importing it in my script. Whereas for datetime, the module datetime.datetime gives me an error saying that there is no attribute datetime in datetime. And datetime.date wants me to feed it a datetime.datetime object, therefore it doesn't let me input strings, lists, ints, or whatever. Does anyone know another possible way to get the current weekday, or how to fix one of the above? Thanks
type: UnansweredQuestion
tagged with: python
tagged with: calendar
has comment: http://stackoverflow.com/comment/90627259
has answer: http://stackoverflow.com/a/51840558
tagged with: date

http://stackoverflow.com/comment/90789195
comment on: http://stackoverflow.com/a/51905861
has text: @MattW. _TimeoutException_ is the outcome of _failed expected-conditions_. Debug your code through `find_element_by_*` in-conjunction with `time.sleep()`. If you are able to locate the element, update the question with the observations.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/90789133
type: Comment
type: QuestionComment
score: 4
has text: Your JSON file contains multiple top-level objects, which means it is not valid JSON. Perhaps you meant to wrap them in an array?
comment on: http://stackoverflow.com/q/51919698

http://stackoverflow.com/a/51890863
type: Answer
answers question: http://stackoverflow.com/q/51890152
score: 0
has body: memory = {} def rec(n): if n in memory: value = memory[n] elif n == 1: value = 1 elif n == 2: value = 1 elif n &gt; 2: value = rec(n - 2) + rec(n - 1) memory[n] = value return value print (rec(5)) print (rec(5)) Now it prints 5 both times. The problem was with value=n while it should be value=memory[n], So, value=n meant that the value of 2 too gets updated to 2.

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

http://stackoverflow.com/comment/90705316
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51877094
type: AnswerComment
has text: It would come from the `repr()` method - https://github.com/python/cpython/blob/master/Lib/datetime.py#L1326 as the default mechanism that converts a `datetime` to string.

http://stackoverflow.com/q/51804513
tagged with: python
score: 4
has comment: http://stackoverflow.com/comment/90565639
tagged with: psycopg2
answer count: 1
has comment: http://stackoverflow.com/comment/90648458
accepted answer: http://stackoverflow.com/a/51805172
has body: I've read some q&a about "syntax error at or near" but none could solve my issue. A sample of the error: Traceback (most recent call last): File "<stdin>", line 1, in <module> psycopg2.ProgrammingError: syntax error at or near "UPDATE" LINE 1: DECLARE "teste" CURSOR WITHOUT HOLD FOR UPDATE applicant SET... ^ Please, note the ^ right on the UPDATE. I've tested the update script on pgadmin 4 and everything worked fine. The script is really simple: UPDATE applicant SET cv_entities = %s WHERE id = %s My code is basically: def _connect_database(): return psy.connect( dbname=settings.DATABASE['DBNAME'], host=settings.DATABASE['HOST'], port=settings.DATABASE['PORT'], user=settings.DATABASE['USER'], password=settings.DATABASE['PASSWORD'], application_name=settings.env ) # Connects to database conn = _connect_database() # Creats a named cursor cur = conn.cursor('test') # Execute cur.execute(update_script, ('{"json": "test"}', '11125ba0-748f-11e8-b1d0-d8108ee3at21')) I've explicitly written the script on the execute method as well as the parameters, but I still get the same error: cur.execute("UPDATE applicant SET cv_entities = 'json here' WHERE id = '11125ba0-748f-11e8-b1d0-d8108ee3at21'") Note that I even removed the double quotes from the first parameter ('json here') Am I missing something?!
has title: psycopg2 syntax error at or near "UPDATE"
upvote count: 4
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/90648307
favorite count: 0
tagged with: postgresql
has comment: http://stackoverflow.com/comment/90646694
has answer: http://stackoverflow.com/a/51805172
type: Question
tagged with: sql-update

http://stackoverflow.com/comment/90783056
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51916580
has text: If they are reading from `stdin`, the simplest way is to put each "enter" as a newline in a text file, along with any other replies, and redirect stdin from the file. For example: `subprocess.call("sudo apt-get update < cmd.txt", shell = True)`

http://stackoverflow.com/comment/90636275
has text: @toti08 thanks for the answer, so [entry] is the key changing every time the loop goes on and if it's true it will increase the value of the current key by 1 otherwise make a new key from the current entry and give it a value of 1 ? , am I correct ?
score: 1
comment on: http://stackoverflow.com/q/51840326
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51886598
tagged with: python
score: 0
answer count: 1
has title: Add hours to timestamps in a pandas df
has answer: http://stackoverflow.com/a/51886695
has body: I am trying to add hours to specific values in a pandas df so that they are consistent. For the df below I want to add 24 hours to the first value. import pandas as pd d = ({ 'time' : ['3:00:00','27:30:00','28:00:00'], }) df = pd.DataFrame(data=d) I'm using this at the moment. df['time'].iloc[0] = df['time'].iloc[0] + pd.Timedelta(hours=24) But it produces: time 0 1 days 03:00:00 1 27:30:00 2 28:00:00 My intended output is: time 0 27:00:00 1 27:30:00 2 28:00:00
tagged with: pandas
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/34134971
has comment: http://stackoverflow.com/comment/90724627
type: Question
accepted answer: http://stackoverflow.com/a/51886695
tagged with: time
has comment: http://stackoverflow.com/comment/90724670

http://stackoverflow.com/comment/90800056
type: AnswerComment
comment on: http://stackoverflow.com/a/51925109
type: Comment
has text: @EranMoshe I tried and it works. As mentioned by coldspeed, it is solved by ``fillna``
score: 1

http://stackoverflow.com/q/51904950
has comment: http://stackoverflow.com/comment/90760646
has comment: http://stackoverflow.com/comment/90761100
tagged with: namespaces
linked to: http://stackoverflow.com/q/291978
has title: python: access class variable from class method argument list
has comment: http://stackoverflow.com/comment/90761081
type: Question
has body: Code class Foo: bar = 1 def run(self, arg1=bar): # ok # def run(self, arg1=Foo.bar): # fail # def run(self, arg1=self.bar): # fail # print(bar) # fail print(Foo.bar) # ok print(self.bar) # ok Foo().run() Question Why do argument list and function body require different access patterns? Do they have different namespace rules? Where can I find authentic documentation about this?
has comment: http://stackoverflow.com/comment/90760647
duplicate of: http://stackoverflow.com/q/4041624
has comment: http://stackoverflow.com/comment/90760799
has comment: http://stackoverflow.com/comment/90760819
tagged with: scope
score: 0
duplicate of: http://stackoverflow.com/q/291978
tagged with: python
has comment: http://stackoverflow.com/comment/90760862
has comment: http://stackoverflow.com/comment/90760824
linked to: http://stackoverflow.com/q/4041624
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/51871322
type: UnansweredQuestion
tagged with: multiprocessing
type: Question
tagged with: python-multiprocessing
score: 0
has title: How to keep files number of files inmemory and pass them to multiprocessing in python?
has comment: http://stackoverflow.com/comment/90694178
has comment: http://stackoverflow.com/comment/90694128
has body: I have to merge number of CSV files into one CSV. Currently I write all csv files in a folder and then pass them to Multiprocessing to make them in a single CSV file. def transform(): ...... transform = etree.XSLT(xslt) result = transform(elem) writeOutput(result) //---&gt;writes csv files to outputdir(i want to do this inmemory) pool = multiprocessing.Pool(max_threads) list_of_csvs=[] outputdir = 'output/' for csvFile in glob(outputdir + '*.csv'): list_of_csvs.append(csvFile) pool.map(writeToSingleCSV, list_of_csvs) pool.close() Without writing each and every CSV file into the outputdir, how can I keep that inmemory and pass that to pool.map()?
tagged with: python
answer count: 0

http://stackoverflow.com/a/63999348
answers question: http://stackoverflow.com/q/51902824
type: Answer
has body: I did not find a way to do it with the write method, but in some scenarios you could work around it by putting the @ on the clipboard and paste it: import pyperclip pyperclip.copy('@') pyautogui.hotkey('ctrl', 'v')
downvote count: 0
score: 8
upvote count: 8

http://stackoverflow.com/comment/90566077
score: 2
has text: `for word in delete_list` is looping over each _character_ in the phrase, not each _word_. Try `for word in delete_list.split():` instead.
comment on: http://stackoverflow.com/q/51805159
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51911908
has answer: http://stackoverflow.com/a/51920659
has answer: http://stackoverflow.com/a/51921801
accepted answer: http://stackoverflow.com/a/51920659
score: 0
has answer: http://stackoverflow.com/a/76751009
tagged with: python
has comment: http://stackoverflow.com/comment/90774270
has title: ending gnuplot process using PyGnuplot
answer count: 4
has body: I am using gnuplot (through Python with PyGnuplot) as a live plotter for numeric data from an Arduino. Additionally I want to save the plot at discretionary points. Whenever I try saving a pdf/jpg, from gnuplot while live-plotting, gnuplot lodges. I think it is necessary to restart the gnuplot-process before saving a plot as pdf - what simply won't work using PyGnuplot.c('quit') or similar commands. When I use different python scripts for live-plotting and saving a pdf, all works fine, but I know that it cannot be necessary to have two scripts running. Here is a running (respectively not running) minimal example: import random,time import PyGnuplot as gp filename = "data.txt" def rand(): return random.random() def writetxt(file,info): fobj = open(file, "a") fobj.write(info) fobj.close() def liveplot(file): gp.c('plot "' + file + '" with lines') def plotinfile(dat): gp.c('set terminal pdf') gp.c('set output "example.pdf"') gp.c('plot "' + dat + '" with lines') gp.c('unset output') gp.c('set terminal x11') for i in range(10): onerow = str(i) + " " + str(rand()) + " " + str(rand()) #simulate incoming data print(onerow) #print in console for comparison writetxt(filename ,onerow + "\n") #write data into txt-file liveplot(filename) #liveplot the data from txt-file if i == 4: #simulate an arbitrary point for saving plotinfile(filename) #save graph from txt-file to pdf time.sleep(1) #incoming data occurs only every second
tagged with: gnuplot
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90789478
possible better answer: http://stackoverflow.com/a/51913052
has answer: http://stackoverflow.com/a/51913052
has comment: http://stackoverflow.com/comment/90796303
type: Question

http://stackoverflow.com/a/51905817
type: Answer
answers question: http://stackoverflow.com/q/51902941
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51902941
has body: I think pulling two managed objects (this is the SNMP parlance) at once is the right way to do it. It is the most efficient way to get data over the high-level SNMP API. Once you get two managed objects in response, you can iterate over them and take actions accordingly - this is what your code seems to do. I personally do not see any issues there. To resolve received variable-bindings (representing SNMP managed objects) against a MIB you just call .prettyPrint() on them: for oid, value in varBinds: print("Name: ", oid.prettyPrint(), "Value: ", value.prettyPrint()): If you want to branch your processing based on the OID value, the most efficient way is to compare those ugly OIDs: for oid, value in varBinds: if oid == (1, 3, 6, 1, 2, 1, 1, 5, 0): # 'SNMPv2-MIB::sysName.0': #take specific actions
type: AcceptedAnswer
downvote count: 0
score: 1

http://stackoverflow.com/a/51849844
score: 2
answers question: http://stackoverflow.com/q/51842961
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51842961
has body: To install PyTables from sources you need a lot of prerequisites. At PyPI there are w32 and w64 binary wheels for Python 2.7, 3.5 and 3.6. If you can change your Python version you can install precompiled PyTables.
type: Answer
upvote count: 2

http://stackoverflow.com/a/63110422
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51935179
type: Answer
has body: You can use plotly or if you are interested in more interactivity, go for Dash DataTable: The DataTable is interactive. This chapter demonstrates the interactive features of the table and how to wire up these interations to Python callbacks. These actions include: Paging Selecting Rows Sorting Columns Filtering Data
downvote count: 0

http://stackoverflow.com/comment/90839180
has text: Thanks, all I need it to present a one-line TextStim RTL, it should work right? To any RTL language? (e.g. Arabic, Hebrew, etc). So should I just download the text.py from GitHub and replace my file with it?
comment on: http://stackoverflow.com/a/51944677
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/51846824
favorite count: 0
has body: I'm trying to mock out os.environ in a Python unit test with unittest.mock.patch.dict. However, when I try to execute the test, I'm getting TypeError: str expected, not int. Roughly, I have the following: import os from unittest.mock import patch with patch.dict('os.environ', values={"foo": 3, "bar": "hello"}, clear=True): print(os.environ["foo"]) print(os.environ["bar"]) Executing this code yields the following stack trace: Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/local/Cellar/python/3.7.0/Frameworks/Python.framework/Versions/3.7/lib/python3.7/unittest/mock.py", line 1630, in __enter__ self._patch_dict() File "/usr/local/Cellar/python/3.7.0/Frameworks/Python.framework/Versions/3.7/lib/python3.7/unittest/mock.py", line 1652, in _patch_dict in_dict.update(values) File "/Users/&lt;redacted&gt;/&lt;redeacted&gt;/&lt;redacted&gt;/venv/bin/../lib/python3.7/_collections_abc.py", line 841, in update self[key] = other[key] File "/Users/&lt;redacted&gt;/&lt;redacted&gt;/&lt;redacted&gt;/venv/bin/../lib/python3.7/os.py", line 683, in __setitem__ value = self.encodevalue(value) File "/Users/&lt;redacted&gt;/&lt;redacted&gt;/&lt;redacted&gt;/venv/bin/../lib/python3.7/os.py", line 753, in encode raise TypeError("str expected, not %s" % type(value).__name__) TypeError: str expected, not int What am I doing wrong? I've looked up the documentation and it seems like this is the correct way to use unittest.mock.patch to mock a dictionary. I'm running Python 3.7.0 on MacOS High Sierra (version 10.13.5).
tagged with: python-3.x
type: UnansweredQuestion
upvote count: 1
tagged with: python
tagged with: unit-testing
has answer: http://stackoverflow.com/a/51848195
score: 1
has title: Using unittest.mock.patch.dict on os.environ is resulting in a TypeError
type: Question
downvote count: 0
answer count: 1

http://stackoverflow.com/comment/90576882
type: QuestionComment
has text: Please post the code that produced that error.
comment on: http://stackoverflow.com/q/51810944
score: 1
type: Comment

http://stackoverflow.com/q/51811451
has title: getting int not callable while using logger in python
score: 1
favorite count: 0
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/51811492
tagged with: int
upvote count: 1
tagged with: python
possible better answer: http://stackoverflow.com/a/51811492
accepted answer: http://stackoverflow.com/a/51811494
has body: I am very new to python. When i try to run the following code getting int object not callable. I found lot of posts in the internet but none of them worked. please help me out. Code: if __name__ == '__main__': scheduler = BackgroundScheduler(timzone='Asia/Kolkata') scheduler.add_job(schedule_creditCnts_job, 'cron', minute=2, hour=23) logging.INFO("starting scheduler") Error: Traceback (most recent call last): File "../util/JobScheduler", line 18, in &lt;module&gt; logging.INFO("starting scheduler") TypeError: 'int' object is not callabl
downvote count: 0
has answer: http://stackoverflow.com/a/51811494
type: AnsweredQuestion

http://stackoverflow.com/comment/90719603
has text: Yes @MattMessersmith
score: 0
comment on: http://stackoverflow.com/q/51883926
type: QuestionComment
type: Comment

http://stackoverflow.com/q/51849581
tagged with: tkinter
downvote count: 2
has comment: http://stackoverflow.com/comment/90652480
tagged with: arduino
accepted answer: http://stackoverflow.com/a/51864045
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90680074
upvote count: 0
has title: Regarding Tkinter() Based GUI for Arduino
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51864045
has body: I'm trying to write a python GUI for an arduino, the idea is that a computer will be communicating through serial port with the arduino. I figured the arduino code itself was too complex to try controlling the thing directly from like matlab, so instead I'd like to control it by sending commands through serial. In addition to that I'm trying to live plot some data. I'm having a hard time getting the live plot to work without having hard-coded the connection port into the script. def connectArduino(): global e1 serial_port = e1.get() baud_rate = 9600 path = "data.txt" ser = serial.Serial(serial_port, baud_rate, timeout=0, writeTimeout=0) def setTunings(): global entries kp = entries[0][1].get() ki = entries[1][1].get() kd = entries[2][1].get() print(kp + ki + kd) def animate(i): ser.reset_input_buffer() data = ser.readline() data_array = data.split('\t') xvalue = float(data_array[0])/1000 yvalue = float(data_array[1]) yar.append(yvalue) xar.append(xvalue) line.set_data(xar, yar) ax1.set_xlim(0, i+1) print(data_array[0] + '\t' + data_array[1]) import serial from Tkinter import * from matplotlib import pyplot as plt import matplotlib.animation as animation from matplotlib import style from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg root = Tk() #root.geometry('1200x700+200+100') root.title('Temperature Control') root.config(background='#fafafa') frame = Frame(root) frame.pack(side=LEFT) l1 = Label(frame, text = "Connection Port:", anchor ='w') l1.pack() e1 = Entry(frame) e1.pack() b1 = Button(frame, text = "Connect", command = connectArduino) b1.pack() fields = 'Kp', 'Ki', 'Kd' entries = [] for field in fields: row = Frame(frame) lab = Label(row, width=15, text=field, anchor='w') ent = Entry(row) row.pack(side=TOP, fill=X, padx=5, pady=5) lab.pack(side=LEFT) ent.pack(side=RIGHT, expand=YES, fill=X) entries.append((field, ent)) b2 = Button(frame, text = 'Set Tunings') b2.pack() b3 = Button(frame, text = 'Start') b3.pack(side=LEFT, padx=5, pady=5) #b2.pack…
tagged with: python
score: -2

http://stackoverflow.com/q/51895536
type: Question
accepted answer: http://stackoverflow.com/a/51895582
has title: How to map with multiple columns python
tagged with: pandas
answer count: 1
downvote count: 0
has body: I have two data frames as below: df1: col1 col2 col3 1 2 A 1 2 A 3 4 B 3 4 B df2: col1 col2 1 2 3 4 I want to put the value of col3 of df1 in df2 like below: result: col1 col2 col3 1 2 A 3 4 B I tried with following code for mapping but getting error message, How to do that df2['col3'] = df2'col1','col2.map(df1.set_index(['col1','col2])['col3'])
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51895582
tagged with: python
type: AnsweredQuestion
score: 3
upvote count: 3
tagged with: dataframe

http://stackoverflow.com/a/51953449
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51941227
has body: I would recommend using a template engine like Jinja2. And for your html structure it depends on how you want to show the data. You could show inside a &lt;ul&gt; with &lt;li&gt;, or some &lt;div&gt; anywhere, really depends on what you are trying to achieve.

http://stackoverflow.com/comment/90864889
comment on: http://stackoverflow.com/q/51932858
type: Comment
type: QuestionComment
score: 0
has text: Using PyAutoGUI might be overkill for this and is probably brittle. If you need to get your JS results to Python, you can try setting up your JS code so that it makes an http request to localhost, sending the info to a web server you run on your machine. The web server can be a simple Flask app running on Python. This means you might have to learn a few new things, but it would be much more robust than using PyAutoGUI to copy/paste results. However, I'd recommend that you figure out why your Python code is running so much slower.

http://stackoverflow.com/a/51818090
upvote count: 2
answers question: http://stackoverflow.com/q/51817806
type: Answer
score: 2
has body: extract() extracts the textual data as a list of strings . To match selectors with regular expression, you need to use re() on selector itself. html = """ Sr No. Name Registration No Address Sectors 1 ABCD Address 12345 Data Not Found """ from scrapy.selector import Selector response= Selector(text=html) links = response.css(".table.table-striped.table-bordered.table-hover.Tax>tbody>tr>td>a").xpath("./@onclick").re("show_info\((.+?)\)") print links returns : [u'"173543"'] Hope this helps :)
has comment: http://stackoverflow.com/comment/90597420
downvote count: 0

http://stackoverflow.com/comment/108721570
comment on: http://stackoverflow.com/a/51815792
score: 1
type: AnswerComment
has text: "Using `imageio.imsave` ... should solve this" -- that function does not exist. Do you mean `.imwrite`?
type: Comment

pyorient
tag name: pyorient
tags question: http://stackoverflow.com/q/51865703
type: Tag

http://stackoverflow.com/comment/90630799
type: Comment
has text: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/177999/discussion-between-arius-and-nabih-bawazir).
comment on: http://stackoverflow.com/a/51824937
score: 0
type: AnswerComment

http://stackoverflow.com/q/51854116
tagged with: python
has comment: http://stackoverflow.com/comment/90663961
upvote count: 2
accepted answer: http://stackoverflow.com/a/51857743
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/90660595
has title: How to find all occurences of string (case-insensitive) in a file, python?
has comment: http://stackoverflow.com/comment/90661389
type: AnsweredQuestion
has body: I have got the following code to find a string in a file and count the number of exact matches: counter+=book.read().count(word) What I'm trying to do is count the number of times the word (stored in the variable word – this is part of a for loop) appears, but case insensitivley. Does anyone know how to do this?
score: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51857743
type: Question
has comment: http://stackoverflow.com/comment/90660634

http://stackoverflow.com/q/51948922
has answer: http://stackoverflow.com/a/51949083
has comment: http://stackoverflow.com/comment/90847720
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/90847664
favorite count: 0
linked to: http://stackoverflow.com/q/17644824
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90847646
score: 1
has answer: http://stackoverflow.com/a/51949394
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/90847903
has body: Why I am not getting the desired result and only getting the number of words in a file? I should also get a list of words without being repeated and also the full content of a file. class text_reader: # for opening of file def __init__(self,file_name): global fo self.file_name = file_name fo=open(file_name,"r") # for counting no of words in a file def wordcount(self): num_word=0 for line in fo: words = line.split() num_word=num_word + len(words) print("Number of words:") print(num_word) # for printing the content of a file def display(self): contents = fo.read() print(contents) # for printing list of words in a file and words should not be repeated def wordlist(self): for x in fo: word = x.split() list=word.set() print(list) t = text_reader("C:/Users/ALI/Desktop/article.txt") t.wordcount() t.display() t.wordlist() # article.txt """PYTHON IS AN INTERPRETED HIGH-LEVEL PROGRAMMING LANGUAGE FOR GENERAL- PURPOSE PROGRAMMING. CREATED BY GUIDO VAN ROSSUM AND FIRST RELEASED IN 1991, PYTHON HAS A DESIGN PHILOSOPHY THAT EMPHASIZES CODE READABILITY, NOTABLY USING SIGNIFICANT """
has title: why this is not printing all the things and its only giving total number of words in a file?

http://stackoverflow.com/comment/90797526
type: QuestionComment
has text: Why do you need the class, in first place? Why don't just use a dictionary?
type: Comment
comment on: http://stackoverflow.com/q/51923925
score: 0

http://stackoverflow.com/comment/90720388
type: Comment
comment on: http://stackoverflow.com/q/51883275
score: 0
type: QuestionComment
has text: Oh, I understand what you are saying now.

http://stackoverflow.com/q/51821428
has comment: http://stackoverflow.com/comment/90602541
has comment: http://stackoverflow.com/comment/90602167
has answer: http://stackoverflow.com/a/51822137
upvote count: 3
tagged with: postgresql
has comment: http://stackoverflow.com/comment/90603346
answer count: 1
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/90603444
type: UnansweredQuestion
has title: PostgreSQL Sqlalchemy commit takes a lot of time
has body: When I'm trying to commit changes into table it takes a lot of time (about 300 seconds per each 1000 rows). Model class: class Quotes(base): __tablename__ = 'quotes' id = Column(INTEGER, primary_key=True, autoincrement=True, index=True) ticker = Column(TEXT) data = Column(ARRAY(FLOAT)) def create(): Session = sessionmaker(db) session = Session() return session def add(session, ticker=None, data=None): new_row = Quotes(ticker=ticker, data=data) session.add(new_row) def commit(session): t0 = time.time() session.commit() print("SQLAlchemy ORM commit(): Total time " + str(time.time() - t0) + " secs") Code looks like: for index in range(len(quotes['timestamp'])): temp = [ int(quotes['timestamp'][index]), quotes['open'][index], quotes['high'][index], quotes['low'][index], quotes['close'][index] ] Quotes.add(session, ticker, temp) counter += 1 if counter % 1000 == 0: Quotes.commit(session) I have about 100k rows. At the start I created a session, then I'm adding new row into a session on each iteration of for loop. I call .commit() method each 1000 row, and it takes about 300 seconds. It seems too slow for me. Is it okay or there is another (correct) way to insert such a large data set into database.
score: 3
has comment: http://stackoverflow.com/comment/90600729
downvote count: 0
has comment: http://stackoverflow.com/comment/90601606
tagged with: sqlalchemy
has comment: http://stackoverflow.com/comment/90602032
type: Question
linked to: http://stackoverflow.com/q/13125236

http://stackoverflow.com/comment/90848218
has text: you dont' need the book_quantity field in your Cart model. book_quantity holds the result of a simple calculation, such things don't need to be stored in the database.
comment on: http://stackoverflow.com/q/51949189
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/51852310
favorite count: 0
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/51852462
tagged with: c++
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/145270
type: Question
tagged with: ctypes
downvote count: 0
has body: My question is based on this example. What's different is that in my C++ code, I have a function that initiates an object of a self-defined class within that function. In my python code, I simply want to call that function. I don't need to create an object of the self-defined class in Python. For example, there are three files in my C++ code foo.h class foo { public: foo(); void bar(); int a; }; foo.cpp extern "C" { foo::foo () { a = 5; } void foo::bar(){ std::cout &lt;&lt; "Hello" &lt;&lt; std::endl; }; } mainFunc.cpp extern "C" { void printStuff (int addNum) { foo fooArg; fooArg.a = fooArg.a + addNum; std::cout&lt;&lt;"Printing..."&lt;&lt;std::endl; std::cout&lt;&lt;fooArg.a&lt;&lt;std::endl; } } In my Python code, I want to create a Python function that calls printStuff in mainFunc.cpp. I don't need to initiate an object of foo in Python. However, two questions: (1) Did I use extern "C" correctly? (2) How should I compile these three files into a shared library? I use g++.
has answer: http://stackoverflow.com/a/51852462
answer count: 1
score: 1
has title: Using Ctypes to call complicated c++ code

http://stackoverflow.com/a/51890613
type: Answer
answers question: http://stackoverflow.com/q/51887473
has body: One way to login automatically every time you request the website is to use specific chrome profile on initialization. If you want to use your existing profile of your google chrome check out this post. Therefore, you have to add one more option: options=Options() options.add_argument('start-maximized') options.add_argument('disable-infobars') options.add_argument('--disable-extensions') options.add_argument('user-data-dir=/path/to/chrome/profile') driver=webdriver.Chrome(chrome_options=options, executable_path='/Users/ae/Downloads/chromedriver') So, if you have logged in using this profile and you have checked "remember me", every time you request this website you will be logged in automatically.
score: 0
has comment: http://stackoverflow.com/comment/90745147

http://stackoverflow.com/q/51898251
score: 1
has title: How can I do certificate pinning for TLS sockets in python 2.7?
favorite count: 0
accepted answer: http://stackoverflow.com/a/51899978
has comment: http://stackoverflow.com/comment/90892746
has comment: http://stackoverflow.com/comment/90753382
has comment: http://stackoverflow.com/comment/90752912
type: Question
has comment: http://stackoverflow.com/comment/90747910
tagged with: python
tagged with: tls1.2
has comment: http://stackoverflow.com/comment/90749103
has body: I have a python TLS server using a self signed certificate. That works. The code looks like this for now: #!/usr/bin/python import socket, ssl context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH) context.load_cert_chain(certfile="server.crt", keyfile="server.key") bindsocket = socket.socket() bindsocket.bind(('127.0.0.1', 8888)) bindsocket.listen(5) while True: newsocket, fromaddr = bindsocket.accept() connstream = context.wrap_socket(newsocket, server_side=True) try: print("Got connection!") finally: connstream.shutdown(socket.SHUT_RDWR) connstream.close() I am now trying to make a client in python that connects to this server. On the first connection attempt, I'd like to retrieve either the public key, or a hash of the public key, and then verify this on all future connections. How can I do with with python and the ssl package? This is the code I'm playing with: #!/usr/bin/python import ssl, socket, pprint context = ssl.SSLContext(ssl.PROTOCOL_TLS) context.verify_mode = ssl.CERT_REQUIRED context.check_hostname = False cnx = context.wrap_socket(socket.socket(socket.AF_INET), certfile="server.crt") cnx.connect(('127.0.0.1', 8888)) pprint.pprint(cnx.getpeercert()) As it stands right now, it fails because there is no certificate chain to verify the cert. I don't care about that, though. All I care about is that the server I'm talking to has the private key that matches the public key. What do I do?
has comment: http://stackoverflow.com/comment/90756007
has comment: http://stackoverflow.com/comment/90938605
has comment: http://stackoverflow.com/comment/90753094
tagged with: certificate
upvote count: 1
has comment: http://stackoverflow.com/comment/90753519
has comment: http://stackoverflow.com/comment/90756398
has comment: http://stackoverflow.com/comment/90753527
has comment: http://stackoverflow.com/comment/90747678
has answer: http://stackoverflow.com/a/51899978
tagged with: ssl
has comment: http://stackoverflow.com/comment/90750946
has comment: http://stackoverflow.com/comment/90752076
tagged with: python-2.7
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90753118
downvote count: 0
answer count: 1

http://stackoverflow.com/comment/99787882
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51805494
has text: I am having a problem understanding this and unfortunately that little paragraph is the only thing that remotely tries (and fails spectacularly) to explain it in the official docs. The rate limit in ops example is set on the task, not the queue. So how do you set it on a queue?

http://stackoverflow.com/q/51862256
has title: Using python script to download google sheet as csv
downvote count: 1
type: Question
tagged with: google-sheets-api
tagged with: google-sheets
score: -1
tagged with: python-2.7
answer count: 2
upvote count: 0
has answer: http://stackoverflow.com/a/68505728
has answer: http://stackoverflow.com/a/51862874
favorite count: 0
type: UnansweredQuestion
tagged with: python
has body: I'm using the python script on raspberry pi3 from this link- inserting my google email address and google sheet number into the script: https://gist.github.com/Thuruv/dc0e2f781b8e095b9981f265647b8304 and then my google password as I run the script but I get the below errors: Traceback (most recent call last): File "Googlespreadsheets.py", line 53, in &lt;module&gt; csv_file = gs.download(ss) File "Googlespreadsheets.py", line 34, in download "Authorization": "GoogleLogin auth=" + self.get_auth_token(), File "Googlespreadsheets.py", line 29, in get_auth_token return self._get_auth_token(self.email, self.password, source, service="wise") File "Googlespreadsheets.py", line 25, in _get_auth_token return re.findall(r"Auth=(.*)", urllib2.urlopen(req).read())[0] File "/usr/lib/python2.7/urllib2.py", line 154, in urlopen return opener.open(url, data, timeout) File "/usr/lib/python2.7/urllib2.py", line 435, in open response = meth(req, response) File "/usr/lib/python2.7/urllib2.py", line 548, in http_response 'http', request, response, code, msg, hdrs) File "/usr/lib/python2.7/urllib2.py", line 473, in error return self._call_chain(*args) File "/usr/lib/python2.7/urllib2.py", line 407, in _call_chain result = func(*args) File "/usr/lib/python2.7/urllib2.py", line 556, in http_error_default raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) urllib2.HTTPError: HTTP Error 404: Not Found

http://stackoverflow.com/q/51850473
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/90654311
has answer: http://stackoverflow.com/a/51853895
has comment: http://stackoverflow.com/comment/90686513
upvote count: 3
downvote count: 1
answer count: 1
type: UnansweredQuestion
tagged with: google-bigquery
has body: I've used pip (and pip3) to install google-api-python-client, all over the place, but whenever I try to issue from google.cloud import bigquery I get an ImportError: No module named google.cloud" error. sys.path contains the directory that pip reports google-api-python-client is installed in, although it's near the end of a long(ish) list of directories. Edit: I've also installed google-cloud. The error occurs with both libraries installed. Edit2: the Location for both are: "/home/swood/.local/lib/python3.5/site-packages" print(sys.path) returns: ['/mnt/pasnas00/dbdata/snowflakedata/lib', '/usr/lib/python35.zip', '/usr/lib/python3.5', '/usr/lib/python3.5/plat-x86_64-linux-gnu', '/usr/lib/python3.5/lib-dynload', '/home/swood/.local/lib/python3.5/site-packages', '/usr/local/lib/python3.5/dist-packages', '/usr/lib/python3/dist-packages']
has title: In what python library is google.cloud?
score: 2
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/comment/90719935
type: QuestionComment
has text: @GoCurry At a high level, this would "just" be a compiler that outputs Python code instead of assembler. Lots of talk on that [here](https://stackoverflow.com/questions/1669/learning-to-write-a-compiler) But I'd imagine it would be easier to just do it manually...
comment on: http://stackoverflow.com/q/51867082
score: 0
type: Comment

http://stackoverflow.com/q/51951966
score: 0
has title: Interactive skimage viewer canvastools RectangleTool
has answer: http://stackoverflow.com/a/51976843
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52042317
accepted answer: http://stackoverflow.com/a/52042317
possible better answer: http://stackoverflow.com/a/51976843
tagged with: scikit-image
tagged with: image-processing
tagged with: viewer
has body: I've run into trouble with skimage.viewer.canvastools.RectangleTool() and would be grateful for any help that could be offered. I would like the selection box to be interactive i.e. after drawing, one can edit the selected region using the handles. This feature appears to work with matplotlib.widgets.RectangleSelector()...e.g. from matplotlib.widgets import RectangleSelector from pylab import * def onselect(eclick, erelease): 'Dummy function' x = arange(100)/(99.0) y = sin(x) fig = figure ax = subplot(111) ax.plot(x,y) test = RectangleSelector(ax, onselect, drawtype='box', interactive=True) show() However, with skimage.viewer.canvastools.RectangleTool()when I use rect_tool = RectangleTool(viewer, on_enter=save_region, interactive=True) I'm thrown: TypeError: init() got an unexpected keyword argument 'interactive' ...and if I use rect_tool = RectangleTool(viewer, on_enter=save_region, rect_props=dict(interactive=True)) I'm thrown this error: AttributeError: Unknown property interactive Have I misunderstood the manpage? Many thanks! This is where I am at (RectangleTool not interactive): import skimage.io from skimage.viewer import ImageViewer from skimage.viewer.canvastools import RectangleTool import numpy as np from tkinter import Tk from tkinter.filedialog import askopenfilename from tkinter.simpledialog import askfloat Tk().withdraw() # we don't want a full GUI, so keep the root window from appearing filename = askopenfilename() # show an "Open" dialog box and return the path to the selected file print(filename) image_rgb = skimage.io.imread(filename) image_r = image_rgb[:,:,0] # extract red channel ######## # Does this need to be initialised differently to make the rectangle interactive? viewer = ImageViewer(image_r) intensity_dumps = [] # used to store pixel values for selected regions def save_region(extents): global image_r, intensity_dumps xmin = np.floor(extents[0]).astype('uint16') xmax = np.ceil(extents[1]).astype('uint16') ymin = np.floor(extents[2]).asty…
type: Question
answer count: 2
tagged with: interactive

http://stackoverflow.com/a/51885178
answers question: http://stackoverflow.com/q/51884992
has body: Here is an implementation using str.join(): my_list = [ ['3', 'cs2313', 'someone', 'cs231', 'IT networks', 'cs232', 'IT Workshop', 'cs233', 'IT programming'], ['5', 'ec3325', 'someone', 'ec301', 'Maths2', 'ec302', 'Theory of Circuits', 'ec303', 'PCB design'], ['7', 'cs4890', 'someone', 'cs401', 'Game Theory', 'cs402', 'Systems Programming', 'cs403', 'Automata'], ['1', 'ec1008', 'someone', 'ec101', 'Digitization', 'ec102', 'Analog cicuit design', 'ec103', 'IP Telephony'], ['3', 'cs2002', 'someone', 'cs231', 'IT networks', 'cs232', 'IT Workshop', 'cs233', 'IT programming'], ['3', 'cs2009', 'someone', 'cs231', 'IT networks', 'cs232', 'IT Workshop', 'cs233', 'IT programming'] ] with open('output_file', 'a+') as f_data: f_data.write('[\n') for elm in my_list: # Maybe you don't need to check if the elm is a list ? if isinstance(elm, list): f_data.write(', '.join("'{}'".format(k) for k in elm) + '\n') f_data.write(']\n') Output: $&gt; cat output_file [ '3', 'cs2313', 'someone', 'cs231', 'IT networks', 'cs232', 'IT Workshop', 'cs233', 'IT programming' '5', 'ec3325', 'someone', 'ec301', 'Maths2', 'ec302', 'Theory of Circuits', 'ec303', 'PCB design' '7', 'cs4890', 'someone', 'cs401', 'Game Theory', 'cs402', 'Systems Programming', 'cs403', 'Automata' '1', 'ec1008', 'someone', 'ec101', 'Digitization', 'ec102', 'Analog cicuit design', 'ec103', 'IP Telephony' '3', 'cs2002', 'someone', 'cs231', 'IT networks', 'cs232', 'IT Workshop', 'cs233', 'IT programming' '3', 'cs2009', 'someone', 'cs231', 'IT networks', 'cs232', 'IT Workshop', 'cs233', 'IT programming' ]
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/51884992
score: 0

http://stackoverflow.com/q/51887864
score: 2
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90727045
has title: Python- How to check if a word has lower and uppercases
type: Question
has answer: http://stackoverflow.com/a/51887884
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/51888030
has answer: http://stackoverflow.com/a/51888059
has comment: http://stackoverflow.com/comment/90727058
has answer: http://stackoverflow.com/a/51888311
tagged with: python
answer count: 4
has body: I working on a school project. I am confused on how to make the ( if ) statement detect a character with upper and lower cases. I have tried to use 'and' in an if statement but it would be too long. My current input is: a=input('Line: ') if 'robot' in a: print('There is a small robot in the line.') elif ('robot'.upper()) in a: print('There is a big robot in the line.') elif b in a: print('There is a medium robot in the line.') else: print('No robots here.') Don't mind the (b) I was just figuring out something I don't know how to explain. An Output example I am looking for goes like: There is a "robot" in the line then it would print 'There is a robot in the line' The program will check for both upper and lowercase characters. If an input had all caps, it would print out There is a big robot in the line If an input had just lowercase letters then it would just print there is a small robot in the line. If an input with both lower and upper cases it would print: There is a medium robot in the line.

http://stackoverflow.com/q/51913755
tagged with: python
favorite count: 0
score: 4
tagged with: syntax
answer count: 2
has title: When is `pass` necessary in a Python if statement?
linked to: http://stackoverflow.com/q/13886168
has answer: http://stackoverflow.com/a/51913775
has comment: http://stackoverflow.com/comment/90777891
has body: Looking at some of the code other people have written for the project I am currently working on, I often see if statements in the following form. if condition: do this else: pass Is there a reason pass is used here? Could the entire else statement not just be left out? Why would you include the section with pass? Similarly I also see this: if condition: pass else: do this Why would you write the code this way, when you could do it this way: if not condition: do this Is there a reason for using the pass command that I am missing, or are these uses of pass superfluous?
has comment: http://stackoverflow.com/comment/90777803
upvote count: 4
downvote count: 0
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/13886168
has answer: http://stackoverflow.com/a/51913771
type: Question

http://stackoverflow.com/q/51909906
answer count: 1
type: UnansweredQuestion
has title: Python - How to iterate over dictionary to get attribute-based access
has answer: http://stackoverflow.com/a/51909968
tagged with: python-2.7
upvote count: 0
favorite count: 0
type: Question
has body: Using POST request i recieve this one respond <?xml version="1.0" encoding="UTF-8"?> description description description description description description description description Then, using this script i convert this data into dictionary to get access to attributes and put it to the database. def etree_to_dict(t): d = {t.tag: {} if t.attrib else None} children = list(t) if children: dd = defaultdict(list) for dc in map(etree_to_dict, children): for k, v in dc.iteritems(): dd[k].append(v) d = {t.tag: {k:v[0] if len(v) == 1 else v for k, v in dd.iteritems()}} if t.attrib: d[t.tag].update(('@' + k, v) for k, v in t.attrib.iteritems()) if t.text: text = t.text.strip() if children or t.attrib: if text: d[t.tag]['#text'] = text else: d[t.tag] = text return d my_result = ET.fromstring(my_response.decode('ascii', 'ignore')) d = globalvars.etree_to_dict(my_result) When i access to attribute of accommodation, every thing is fine: my_data=d['response']['accommodations']['accommodation'] for n in my_data.get('accommodation'): p = XMLData( name = n.get('@name') ) But when i try to iterate over concept or boards, i've got an Error list indices must be integers, not str, cause after for loop, i've got string but not dictionary for n in my_data.get('accommodation'): for k, v in n['concepts'].iteritems(): print v['@name'] How i shouls iterate over dictionary to have attribute-based access? Thanks a lot.
tagged with: python
score: -2
has comment: http://stackoverflow.com/comment/90770008
downvote count: 2
has comment: http://stackoverflow.com/comment/90770151

excel
tags question: http://stackoverflow.com/q/51912896
tags question: http://stackoverflow.com/q/51916094
tags question: http://stackoverflow.com/q/51952393
tags question: http://stackoverflow.com/q/51830789
tag name: excel
tags question: http://stackoverflow.com/q/51801034
tags question: http://stackoverflow.com/q/51852514
tags question: http://stackoverflow.com/q/51852686
tags question: http://stackoverflow.com/q/51934855
tags question: http://stackoverflow.com/q/51833930
tags question: http://stackoverflow.com/q/51866059
tags question: http://stackoverflow.com/q/51872586
tags question: http://stackoverflow.com/q/51938729
tags question: http://stackoverflow.com/q/51858187
tags question: http://stackoverflow.com/q/51864417
tags question: http://stackoverflow.com/q/51833351
tags question: http://stackoverflow.com/q/51856875
tags question: http://stackoverflow.com/q/51841615
tags question: http://stackoverflow.com/q/51899921
tags question: http://stackoverflow.com/q/51863735
tags question: http://stackoverflow.com/q/51814257
tags question: http://stackoverflow.com/q/51832672
tags question: http://stackoverflow.com/q/51902878
tags question: http://stackoverflow.com/q/51800931
tags question: http://stackoverflow.com/q/51825360
tags question: http://stackoverflow.com/q/51929876
tags question: http://stackoverflow.com/q/51859574
tags question: http://stackoverflow.com/q/51930180
tags question: http://stackoverflow.com/q/51936297
tags question: http://stackoverflow.com/q/51884648
type: Tag
tags question: http://stackoverflow.com/q/51851986
tags question: http://stackoverflow.com/q/51942083
tags question: http://stackoverflow.com/q/51860507
tags question: http://stackoverflow.com/q/51815049
tags question: http://stackoverflow.com/q/51934413
tags question: http://stackoverflow.com/q/51912858
tags question: http://stackoverflow.com/q/51860448
tags question: http://stackoverflow.com/q/51800122
tags question: http://stackoverflow.com/q/51936575
tags question: http://stackoverflow.com/q/51924775
tags question: http://stackoverflow.com/q/51853149
tags question: http://stackoverflow.com/q/51945110
tags question: http://stackoverflow.com/q/51867496
tags question: http://stackoverflow.com/q/51947269

http://stackoverflow.com/q/51916417
has body: I'm currently writing a program that calculates the gpa of different students. If I want to let the user input their course's credit worth and their grade value in percentages; is it any possibility that I could aske the # of courses the students are currently participating in and assigned each of the values to a new variable everytime the user inputs a value for it. For each of the new inputs, how can I add them into the equation everytime they are created? for example: def gpa1(): return ((x1*y1)+(x2*y2)+(x3*y3)+(x4*y4)+(x5*y5)+(x6*y6)+(x7*y7)+(x8*y8)+(x9*y9)+(x10*y10))/((y1+y2+y3+y4+y5+y6+y7+y8+y9+y10)) This is what the equation looks like if I would have 10 course intotal, but instead I want the user to have a choice to alter the # of inputs they are able to make instead of 10. Everytime the user inputs, a new varible my be added or an old varible may be deleted. How can I possibly achieve all this? I would very much appreciated anyone who attempts to help me at this.
type: Question
upvote count: 2
downvote count: 1
answer count: 1
has answer: http://stackoverflow.com/a/51916495
has title: How do I create variables as they are being assigned by the user a 'x' amount of times that the user chooses to input?
favorite count: 0
has comment: http://stackoverflow.com/comment/90782710
linked to: http://stackoverflow.com/q/23294658
type: UnansweredQuestion
tagged with: python
score: 1
linked to: http://stackoverflow.com/q/1373164

http://stackoverflow.com/q/51863827
has answer: http://stackoverflow.com/a/51897695
has answer: http://stackoverflow.com/a/61638606
tagged with: boto3
tagged with: amazon-web-services
has title: How to I access Security token for Python SDK boto3
answer count: 3
possible better answer: http://stackoverflow.com/a/51895874
has answer: http://stackoverflow.com/a/51895874
has comment: http://stackoverflow.com/comment/90742206
favorite count: 0
accepted answer: http://stackoverflow.com/a/51897695
tagged with: aws-sdk
tagged with: python
type: AnsweredQuestion
score: 3
upvote count: 3
type: Question
has comment: http://stackoverflow.com/comment/90683841
has body: I want to access AWS comprehend api from python script. Not getting any leads of how do I remove this error. One thing I know that I have to get session security token. try: client = boto3.client(service_name='comprehend', region_name='us-east-1', aws_access_key_id='KEY ID', aws_secret_access_key= 'ACCESS KEY') text = "It is raining today in Seattle" print('Calling DetectEntities') print(json.dumps(client.detect_entities(Text=text, LanguageCode='en'), sort_keys=True, indent=4)) print('End of DetectEntities\n') except ClientError as e: print (e) Error : An error occurred (UnrecognizedClientException) when calling the DetectEntities operation: The security token included in the request is invalid.
downvote count: 0

http://stackoverflow.com/a/51827332
has comment: http://stackoverflow.com/comment/90609385
accepted answer of: http://stackoverflow.com/q/51827117
upvote count: 5
has comment: http://stackoverflow.com/comment/90609437
has comment: http://stackoverflow.com/comment/90609040
has comment: http://stackoverflow.com/comment/90609499
has comment: http://stackoverflow.com/comment/90609008
score: 5
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90609094
has body: There's no bug in subprocess.kill. If you're really worried about that, just check the source, which is linked from the docs. The kill method just calls send_signal, which just calls os.kill unless the process is already done, and you can see the Windows implementation for that function. In short: subprocess.Process.kill doesn't care what name the process has in the kernel's process table (or the Task Manager); it remembers the PID (process ID) of the process it started, and kills it that way. The most likely problem is that, like many Windows apps, calc.exe has some special "single instance" code: when you launch it, if there's already a copy of calc.exe running in your session, it just tells that copy to come to the foreground (and open a window, if it doesn't have one), and then exits. So, by the time you try to kill it 2 seconds later, the process has already exited. And if the actual running process is calculator.exe, that means calc.exe is just a launcher for the real program, so it always tells calculator.exe to come to the foreground, launching it if necessary, and then exits. So, how can you kill the new calculator you started? Well, you can't, because you didn't start a new one. You can kill all calc.exe and/or calculator.exe processes (the easiest way to do this is with a third-party library like psutil—see the examples on filtering and then kill the process once you've found it), but that will kill any existing calculator process you had open before running your program, not just the new one you started. Since calc.exe makes it impossible to tell if you've started a new process or not, there's really no way around that.
answers question: http://stackoverflow.com/q/51827117
type: Answer
has comment: http://stackoverflow.com/comment/90609117

http://stackoverflow.com/comment/90975000
score: 0
type: AnswerComment
has text: Does the new error give you any idea what the problem is? I am still trying to get this to work.
comment on: http://stackoverflow.com/a/51811364
type: Comment

php
tags question: http://stackoverflow.com/q/51888027
tag name: php
tags question: http://stackoverflow.com/q/51820964
tags question: http://stackoverflow.com/q/51861742
tags question: http://stackoverflow.com/q/51954466
tags question: http://stackoverflow.com/q/51899780
tags question: http://stackoverflow.com/q/51845668
tags question: http://stackoverflow.com/q/51897917
tags question: http://stackoverflow.com/q/51875063
tags question: http://stackoverflow.com/q/51850166
tags question: http://stackoverflow.com/q/51804886
type: Tag

http://stackoverflow.com/comment/90565723
has text: Please show a long non-loop form of applying your function as it is not immediately clear from text.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51804842
score: 0

http://stackoverflow.com/q/51815010
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/90584449
has answer: http://stackoverflow.com/a/68548227
tagged with: pandas
tagged with: python
has body: I have been trying this for the last few days and not luck. What I want to do is do a simple Linear regression fit and predict using sklearn, but I cannot get the data to work with the model. I know I am not reshaping my data right I just dont know how to do that. Any help on this will be appreciated. I have been getting this error recently Found input variables with inconsistent numbers of samples: [1, 9] This seems to mean that the Y has 9 values and the X only has 1. I would think that this should be the other way around, but when I print off X it gives me one line from the CSV file but the y gives me all the lines from the CSV file. Any help on this will be appreciated. Here is my code. filename = "E:/TestPythonCode/animalData.csv" #Data set Preprocess data dataframe = pd.read_csv(filename, dtype = 'category') print(dataframe.head()) #Git rid of the name of the animal #And change the hunter/scavenger to 0/1 dataframe = dataframe.drop(["Name"], axis = 1) cleanup = {"Class": {"Primary Hunter" : 0, "Primary Scavenger": 1 }} dataframe.replace(cleanup, inplace = True) print(dataframe.head()) #array = dataframe.values #Data splt # Seperating the data into dependent and independent variables X = dataframe.iloc[-1:] y = dataframe.iloc[:,-1] print(X) print(y) logReg = LogisticRegression() #logReg.fit(X,y) logReg.fit(X[:None],y) #logReg.fit(dataframe.iloc[-1:],dataframe.iloc[:,-1]) And this is the csv file Name,teethLength,weight,length,hieght,speed,Calorie Intake,Bite Force,Prey Speed,PreySize,EyeSight,Smell,Class T-Rex,12,15432,40,20,33,40000,12800,20,19841,0,0,Primary Hunter Crocodile,4,2400,23,1.6,8,2500,3700,30,881,0,0,Primary Hunter Lion,2.7,416,9.8,3.9,50,7236,650,35,1300,0,0,Primary Hunter Bear,3.6,600,7,3.35,40,20000,975,0,0,0,0,Primary Scavenger Tiger,3,260,12,3,40,7236,1050,37,160,0,0,Primary Hunter Hyena,0.27,160,5,2,37,5000,1100,20,40,0,0,Primary Scavenger Jaguar,2,220,5.5,2.5,40,5000,1350,15,300,0,0,Primary Hunter Cheetah,1.5,154,4.9,2.9,70,2200,475,56,185,0…
possible better answer: http://stackoverflow.com/a/68548227
favorite count: 0
has title: Simple Linear Regression using CSV data file Sklearn
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/90584463
upvote count: 3
has answer: http://stackoverflow.com/a/51815375
type: Question
tagged with: numpy
answer count: 2
downvote count: 0
accepted answer: http://stackoverflow.com/a/51815375

http://stackoverflow.com/comment/90752937
type: Comment
has text: It is produced _from_ the range object, not _by_ the range object. Once again, `range` has no more to do with iterators than any other iterable. You wouldn't say "a tuple produces an iterator"?
comment on: http://stackoverflow.com/a/51899711
type: AnswerComment
score: 0

http://stackoverflow.com/q/51880474
has title: Get the Covariance returns for a dataframe
has body: I have a dataframe like this: YAU OTBL HLE 2009-03-08 nan nan nan 2009-03-09 1.59904743 1.66397210 1.67345829 2009-03-10 -0.37065629 -0.36541822 -0.36015840 2009-03-11 -0.41055669 0.60004777 0.00536958 This is my function. def get_covariance_returns(returns): return np.cov(returns.values) returns parameter is a DataFrame Returns for each ticker and date. The output is a 2 dimensional Ndarray The covariance of the returns. When I run my code I have: AssertionError: Wrong shape for output returns_covariance. Got (4, 4), expected (3, 3) Now, I modified my function like this: def get_covariance_returns(returns): return np.cov(returns.values, rowvar=False) My result is: OUTPUT returns_covariance: [[ nan nan nan] [ nan nan nan] [ nan nan nan]] Please note that the expected output is: EXPECTED OUTPUT FOR returns_covariance: [[ 0.89856076 0.7205586 0.8458721 ] [ 0.7205586 0.78707297 0.76450378] [ 0.8458721 0.76450378 0.83182775]] I need a guide to know what's wrong with my implementation, please. I am programming in Python language.
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51880578
type: Question
tagged with: numpy
tagged with: pandas
has answer: http://stackoverflow.com/a/51880578
downvote count: 0
answer count: 1
favorite count: 0
upvote count: 2
tagged with: python

http://stackoverflow.com/q/51902279
has comment: http://stackoverflow.com/comment/90756052
type: Question
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/90756294
has title: How to create a shell program that accepts commands and prints a "$" prompt to indicate that a user can input a command using a while loop?
has answer: http://stackoverflow.com/a/51902346
type: UnansweredQuestion
tagged with: python
has body: I'm a beginner Python coder and I'm very unsure on how to create a simple shell program that accepts commands (ex. printrecipes, printinventory, load etc.) The input should look like: $ loadrecipes $ printmoney() 20 For this shell, I'm trying to use a while loop so it continues through the program without crashing even if they input a command that is acceptable. def handle_commands(): keep_going=True command=input("$" + " ") while keep_going: if command == '$ quit': keep_going = False break elif command == "$ loadrecipefile(recipe_file)" j elif command == "$ printrecipes": printrecipes() elif command == "$ printiinventory": printiinventory() elif command == "$ printmoney": printmoney() elif command == "$ buyingredient": I have no idea what to go from here. The commands are that loadrecipes(recipe_file) takes in one argument, all print commands don't take an argument, buyingredient(ingredient_name, number:int) takes in 2 arguments (the ingredient name and how many of those ingredients). So, for each command I have created a function in correspondence. Such as for printiinventory() I have: def printiinventory(): print(iinventory['apple'],iinventory['beets'],iinventory['carrots']) so if the command is: $ printiinventory 0 4 3 it should come out to be like this

sorting
tags question: http://stackoverflow.com/q/51858833
tags question: http://stackoverflow.com/q/51900253
tags question: http://stackoverflow.com/q/51936781
tags question: http://stackoverflow.com/q/51912909
tags question: http://stackoverflow.com/q/51925809
tags question: http://stackoverflow.com/q/51911734
tags question: http://stackoverflow.com/q/51819370
tags question: http://stackoverflow.com/q/51922283
type: Tag
tags question: http://stackoverflow.com/q/51905944
tags question: http://stackoverflow.com/q/51809544
tags question: http://stackoverflow.com/q/51882756
tags question: http://stackoverflow.com/q/51842011
tags question: http://stackoverflow.com/q/51940769
tags question: http://stackoverflow.com/q/51870336
tag name: sorting
tags question: http://stackoverflow.com/q/51913532
tags question: http://stackoverflow.com/q/51933763
tags question: http://stackoverflow.com/q/51873302
tags question: http://stackoverflow.com/q/51888381
tags question: http://stackoverflow.com/q/51886874

http://stackoverflow.com/comment/90758764
score: 0
has text: Thanks a lot. I will think about your solution for a while because of my fool about python. And I try the k-means solution from sklearn.cluster, but I can not confirm that the result from k-means is the best.
comment on: http://stackoverflow.com/a/51898844
type: AnswerComment
type: Comment

http://stackoverflow.com/a/51826814
accepted answer of: http://stackoverflow.com/q/51826614
answers question: http://stackoverflow.com/q/51826614
score: -1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90608281
type: Answer
upvote count: 0
has body: Note that your two codes are not equvalent: The second version will call soup.find twice. Instead, you could wrap just the if part in a function. You could even define this function within the outer loop so it requires fewer parameters and does not clutter the remaining code: for i in soup.find("div", class_="bets betCols2"): def find_info(what): if i.find('span', 'bet_type').text == what: odd = i.find('span', 'koeff').text mylist.append(odd) find_info('Total Over 0.5') find_info('Total Under 0.5') Note that this still calls i.find twice (or four times). You could store those in temporary variables, but there's another way: Since the body of the if is the same, and you are just comparing the result of i.find to different values: for i in soup.find("div", class_="bets betCols2"): if i.find('span', 'bet_type').text in ('Total Over 0.5', 'Total Under 0.5'): odd = i.find('span', 'koeff').text mylist.append(odd) This way, there's no duplication, no nested functions, and it is IMHO much clearer what the code is doing.
downvote count: 1

http://stackoverflow.com/a/51926767
has body: You can use this: %matplotlib inline from matplotlib.pyplot import figure import matplotlib.pyplot as plt from numpy import arange, sin, pi t = arange(0.0, 2.0, 0.01) fig = figure(1) ax1 = fig.add_subplot(311) ax1.plot(t, sin(2*pi*t)) ax2 = fig.add_subplot(312) ax2.plot(t, sin(4*pi*t)) ax3 = fig.add_subplot(313) ax3.plot(t, sin(4*pi*t)+sin(2*pi*t)) plt.show()
downvote count: 0
score: 3
type: Answer
answers question: http://stackoverflow.com/q/51926684
upvote count: 3

http://stackoverflow.com/q/51911734
has comment: http://stackoverflow.com/comment/90773540
favorite count: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/51911802
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
upvote count: 2
has comment: http://stackoverflow.com/comment/90773537
has answer: http://stackoverflow.com/a/51913814
type: Question
has title: Sorting a dictionary by an inner "attribute" dictionary key-value
possible better answer: http://stackoverflow.com/a/51913814
tagged with: sorting
has answer: http://stackoverflow.com/a/51911802
answer count: 2
score: 2
has body: I created a dictionary using a for-loop and this code: players[name] = {'roll_total': player_roll, 'ante': None} Previously my dictionary was just players = {names: totals} and I could sort it using this code: players = [(k, players[k]) for k in sorted(players, key=players.get, reverse=True)] But now since I implemented the inner "attribute" dictionary, I get an error saying comparisons can't be made on dictionaries. TypeError: '&lt;' not supported between instances of 'dict' and 'dict' So how can I modify the sorting method to compare values of the dictionaries (the roll_total values), and have my players dictionary sorted?
downvote count: 0

http://stackoverflow.com/q/51869748
has body: I have a dataset with four columns, Date, Subject, Student, Marks_Obtained. I want to find the mean Marks_Obtained I am trying to understand how can I implement a Python code where I need to find the mean Marks_Obtained across all subjects by each student. I also want to implement how to find out the trends of the students who are improving over time, basically to find the student improving the most vs students who is improving the least over time with respect to the marks obtained. enter image description here
has comment: http://stackoverflow.com/comment/90691190
has comment: http://stackoverflow.com/comment/90899678
has comment: http://stackoverflow.com/comment/90691061
score: 0
has comment: http://stackoverflow.com/comment/90691209
has title: Python Code to Find out Mean and Trends on a Dataset
answer count: 0
has comment: http://stackoverflow.com/comment/90691398
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90691186
tagged with: python
has comment: http://stackoverflow.com/comment/90692367
has comment: http://stackoverflow.com/comment/90691172
type: Question
has comment: http://stackoverflow.com/comment/90691002

http://stackoverflow.com/q/51809578
has body: My plotly is not working properly. I am trying to render the graph in html, but it keeps showing the text rather than the graph itself. Below is an extract of the code written in the 'app.py' file - using the Flask microframework. k = plotly.offline.plot({ "data": [go.Scatter(x = money_x, y = result, name = "Expenditure")], "layout": go.Layout(title="Expenditure") }, auto_open=True, show_link=False, output_type = 'div', include_plotlyjs=False) return render_template('plot.html', name=session['name'], surname=session['surname'], k=str(k), sun=session['student_number']) Below is an extract from the html file. In the html, I included an online graphic so as to try and see what was wrong with the code - but that has since returned moot. {{name}} {{surname}} Expenditure Plot {{k}} Below is a picture of the observed output of the program. As one can see, the plotly image that was harnessed from online remained unharmed, while my generated graph does not get translated into plotly content. Please help (As best as I know, the relevant Javascript has been included for the project)
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/3206344
tagged with: plotly
tagged with: jinja2
has answer: http://stackoverflow.com/a/51809602
accepted answer: http://stackoverflow.com/a/51809602
type: Question
tagged with: flask
score: 0
upvote count: 1
tagged with: http://stackoverflow.com/tag/html
answer count: 1
downvote count: 1
favorite count: 0
has title: Plotly in Python
tagged with: python
duplicate of: http://stackoverflow.com/q/3206344

http://stackoverflow.com/comment/90757085
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51902953
score: 0
has text: Meanwhile, your function doesn't return anything; it just modifies `singleList` and then `print`s it. So, after that call, `rock` is just going to be `None`.

http://stackoverflow.com/comment/90569970
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51806306
has text: Opps it appears that column was hidden. Thanks for your help!
score: 0

http://stackoverflow.com/q/51828790
has comment: http://stackoverflow.com/comment/138079132
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/51829021
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
has title: What is the difference between ProcessPoolExecutor and ThreadPoolExecutor?
tagged with: python
tagged with: parallel-processing
tagged with: multithreading
has answer: http://stackoverflow.com/a/51829082
upvote count: 83
has body: I read the docs trying to get a basic understanding but it only shows that ProcessPoolExecutor allows to side-step the Global Interpreter Lock which I think is the way to lock a variable or function so that parallel processes do not update its value at the same time. What I am looking for is when to use ProcessPoolExecutor and when to use ThreadPoolExecutor and what should I keep in mind while using each approach!
type: Question
score: 83
tagged with: python-3.5

http://stackoverflow.com/comment/90631085
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51838953
score: 0
has text: Why do you think that it will wait for something? `find_elements_by_id` doesn't wait, but returns list of all elements with specified `id` (or empty list) immediately

http://stackoverflow.com/a/52004530
answers question: http://stackoverflow.com/q/51858476
score: 0
type: AcceptedAnswer
type: Answer
has body: Well, it looks like there is no way to set the streaming options at the VLC instance level. What I did instead was to loop through all media in the medialist and set the proper options via the add_option function. If you have to do that, careful since you have to prepend : before the option media.add_option(":sout=#gather:rtp{dst=%s,port=%d,mux=ts}"%(multicast_address,video_port))
accepted answer of: http://stackoverflow.com/q/51858476

http://stackoverflow.com/q/51887141
has comment: http://stackoverflow.com/comment/90725940
downvote count: 0
accepted answer: http://stackoverflow.com/a/51930307
tagged with: regex
favorite count: 0
tagged with: python-3.x
has body: I have a set of text files from which I have to extract date of birth. The below code is able to extract date of birth from most of the files but is getting failed when given in the below format. May I know how could I extract DOB? The data is very much un-uniform. Data: data=""" Thomas, John - DOB/Sex: 12/23/1955 11/15/2014 11:53 AM" Jacob's Date of birth is 9/15/1963 Name:Annie; DOB:10/30/1970 Code: import re pattern = re.compile(r'.*DOB.*((?:\d{1,2})(?:(?:\/|-)\d{1,2})(?(?:\/|-)\d{2,4})).*',re.I) matches=pattern.findall(data) for match in matches: print(match) expected output: 12/23/1955
tagged with: data-extraction
possible better answer: http://stackoverflow.com/a/51888659
has answer: http://stackoverflow.com/a/51888659
tagged with: python
has title: Unable to extract date of birth from a given format
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/90726007
upvote count: 1
has answer: http://stackoverflow.com/a/51930307
type: Question
answer count: 2

http://stackoverflow.com/q/51841342
has comment: http://stackoverflow.com/comment/90682273
has comment: http://stackoverflow.com/comment/90986495
type: Question
has body: I use dbus by it's python bindings dbus. I issue calls via dbus.call_async to send them out fast. Some of the calls target dbus services, which may be running or will be activated upon call. However, if a dbus service needs to be still activated, this triggers the activation, but fails to execute the call. It seems the method can't be resolved until the service is up, but there is no queue to keep the call pending until then. dbus specs say that service activations should be totally transparent to bus users, but for python, it seems, they are not. Of course I can backup on this, and send the call again, but this leads to abitrary repitions. So is there any mechanism I've missed, to issue a call that is executed at the first moment it is possible, if activation is still in progress?
tagged with: dbus
upvote count: 1
has comment: http://stackoverflow.com/comment/90639852
favorite count: 0
has title: dbus service activating method call lost
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90696489
tagged with: python
answer count: 0
downvote count: 0
score: 1

http://stackoverflow.com/q/51878354
has answer: http://stackoverflow.com/a/51878547
accepted answer: http://stackoverflow.com/a/51878547
possible better answer: http://stackoverflow.com/a/51878552
tagged with: built-in
upvote count: 7
favorite count: 0
tagged with: python
answer count: 4
type: AnsweredQuestion
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51878552
downvote count: 0
has answer: http://stackoverflow.com/a/51878653
type: Question
linked to: http://stackoverflow.com/q/1277278
tagged with: python-itertools
has title: zip()-like built-in function filling unequal lengths from left with None value
score: 7
has answer: http://stackoverflow.com/a/51878571
has body: Is there a built-in function that works like zip(), but fills the results so that the length of the resulting list is the length of the longest input and fills the list from the left with e.g. None? There is already an answer using zip_longest from itertools module and the corresponding question is very similar to this. But with zip_longest it seems that you can only fill missing data from the right. Here might be a use case for that, assuming we have names stored only like this (it's just an example): header = ["title", "firstname", "lastname"] person_1 = ["Dr.", "Joe", "Doe"] person_2 = ["Mary", "Poppins"] person_3 = ["Smith"] There is no other permutation like (["Poppins", "Mary"], ["Poppins", "Dr", "Mary"]) and so on. How can I get results like this using built-in functions? &gt;&gt;&gt; dict(magic_zip(header, person_1)) {'title': 'Dr.', 'lastname': 'Doe', 'firstname': 'Joe'} &gt;&gt;&gt; dict(magic_zip(header, person_2)) {'title': None, 'lastname': 'Poppins', 'firstname': 'Mary'} &gt;&gt;&gt; dict(magic_zip(header, person_3)) {'title': None, 'lastname': 'Smith', 'firstname': None}

http://stackoverflow.com/comment/90699968
type: AnswerComment
has text: I tried but this does not solve the problem, I still get the same error
comment on: http://stackoverflow.com/a/51874217
type: Comment
score: 0

http://stackoverflow.com/comment/90633509
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51839339
has text: Thanks! I may have figured out!

http://stackoverflow.com/a/57838491
has comment: http://stackoverflow.com/comment/103541180
has comment: http://stackoverflow.com/comment/122148236
score: 31
has comment: http://stackoverflow.com/comment/103511140
upvote count: 31
has body: My answer's for c++ but still kinda related. I'm using the C/C++ extension from Microsoft, and when I switched its Intelli Sense Engine setting from Default, with "context-aware results", to Tag Parser, with "'fuzzy' results that are not context-aware", it immediately started showing IntelliSense options instead of delaying for 5+ seconds. So maybe check the particular options of your language's or environment's extension(s).
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/51874486

http://stackoverflow.com/q/51884709
has answer: http://stackoverflow.com/a/51884833
has title: Find the indices of similar elements in numpy array
type: AnsweredQuestion
tagged with: list
has answer: http://stackoverflow.com/a/51884791
has answer: http://stackoverflow.com/a/51884843
type: Question
tagged with: numpy
answer count: 6
has answer: http://stackoverflow.com/a/51884890
accepted answer: http://stackoverflow.com/a/51884890
has body: I have a numpy array that has different values in it some of which could be equal. I want to return a list of lists that each list contains the indices of equal elements. For example, imagine A=np.array([2,3,2,1,1,1,3,4,5,6,6,6,6,3]) Then the result I want should be [[0,2],[1,6,13],[3,4,5],[7],[8],[9,10,11,12]] here is my solution but I am looking for a smarter way to do it: h=[] s=set() for i in list_name: if i in s: continue h.append(np.where(list_name==i)) s.add(i) print h
score: 0
has answer: http://stackoverflow.com/a/51884797
possible better answer: http://stackoverflow.com/a/51884791
has answer: http://stackoverflow.com/a/51884871
tagged with: python

http://stackoverflow.com/comment/90744927
comment on: http://stackoverflow.com/q/51896458
score: 0
type: Comment
type: QuestionComment
has text: How about your memory usage during the whole process? The memory usage should between `2*5.6gb` and `3*5.6gb` including virtual memory.

http://stackoverflow.com/a/51949391
answers question: http://stackoverflow.com/q/51949356
has comment: http://stackoverflow.com/comment/90848572
downvote count: 0
score: 4
has body: You can use iloc function, and please remember that indices are zero based a.iloc[0:1000,] a.iloc[1000:2000,] iloc will allow you to filter like this
type: Answer
upvote count: 4
has comment: http://stackoverflow.com/comment/90848718

http://stackoverflow.com/q/51816917
tagged with: xlwt
tagged with: web-scraping
tagged with: python
tagged with: request
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51835069
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/90588494
has body: Here is my scrape: from bs4 import BeautifulSoup import requests url = 'http://www.baseballpress.com/lineups' soup = BeautifulSoup(requests.get(url).text, 'html.parser') for names in soup.find_all(class_="players"): print(names.text) I want to import my scrape to excel using xlwt. I used this code below to see if I could make an excel sheet using python: import xlwt wb = xlwt.Workbook() ws = wb.add_sheet("Batters") ws.write(0,0,"coding isn't easy") wb.save("myfirst_xlwt") The code above worked. I would now like to apply it to my original scrape. How do I merge these two codes? I am new so any help would be greatly appreciated. Thanks for your time! =)
has comment: http://stackoverflow.com/comment/90615675
has title: How do you export python data to excel using xlwt?
has answer: http://stackoverflow.com/a/51817266
tagged with: beautifulsoup
accepted answer: http://stackoverflow.com/a/51817266
score: 0
has answer: http://stackoverflow.com/a/51835069

http://stackoverflow.com/q/51942850
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90843723
tagged with: matrix
has comment: http://stackoverflow.com/comment/90839006
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/90872184
favorite count: 0
has body: import numpy as np a=np.zeros(shape=(3,4,5)) print(type(a)) a[0][1]=1,2,3,4,5 a[1][3]=6,7,8,9,12 a[2][1]=12,34,54,21,89 a is the following matrix: [[[ 0. 0. 0. 0. 0.] [ 1. 2. 3. 4. 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.] [ 6. 7. 8. 9. 12.]] [[ 0. 0. 0. 0. 0.] [12. 34. 54. 21. 89.] [ 0. 0. 0. 0. 0.] [ 0. 0. 0. 0. 0.]]] . print(a.max(axis=0)) print(a.argmax(axis=0)) I can get the matrix results: [[ 0. 0. 0. 0. 0.] [12. 34. 54. 21. 89.] [ 0. 0. 0. 0. 0.] [ 6. 7. 8. 9. 12.]] [[0 0 0 0 0] [2 2 2 2 2] [0 0 0 0 0] [1 1 1 1 1]] , but how can I get the whole index of each maximum like [0,0,1] or something, as I need the index to draw a 3D figure.
has answer: http://stackoverflow.com/a/51947284
tagged with: python
has comment: http://stackoverflow.com/comment/90852946
score: 1
has title: Find each row's maximum and index in 3-dimentional matrix in python
upvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/51947284

http://stackoverflow.com/comment/90684234
has text: Thank you for the answer! However, this approach wouldn't work for the smaller artefacts in the beginning of the recording, or for recordings where the trace goes from for example 300ms to 1500ms since the absolute values of the artefacts would be smaller or larger than parts of the trace. In that case one would have to apply a moving average and apply the StDev-exclusion based on a neighbouring segment of data for each data-point. Also, I've added the raw data.
comment on: http://stackoverflow.com/a/51864953
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/90791883
type: AnswerComment
has text: @darknoaut Awesome! I really like this answer. Both ascitree and treelib were good candidates but didn't figure out how to skip the root node. Prune's answer was good but it was missing the continuous lines. Plus, in comparison, I think this one is really convenient to work with, I think having fixed-width levels has few advantages. So yeah, thanks ;)
comment on: http://stackoverflow.com/a/51920869
score: 0
type: Comment

argparse
tags question: http://stackoverflow.com/q/51806986
tags question: http://stackoverflow.com/q/51954897
tags question: http://stackoverflow.com/q/51878263
tag name: argparse
tags question: http://stackoverflow.com/q/51877507
type: Tag
tags question: http://stackoverflow.com/q/51826006
tags question: http://stackoverflow.com/q/51915342

http://stackoverflow.com/q/51847755
type: Question
tagged with: database
score: 0
has body: I am working on a Django app and I'm having some issues with the structuring of my models. What I have is 3 models Topic, Video, and Document, and the video and document models are in many to many relationship with the Topic model, like so: class Topic(models.Model): name = models.Charfield(max_length=20) videos = models.manytomanyfield('Video', blank=True) docs = models.manytomanyfield('Document', blank=True) class Video(models.Model): title = models.Charfield(max_length=20) videourl = models.Charfield() class Document(models.Model): title = models.Charfield(max_length=20) doc = models.Textfield() So I'm having two problems; -First, I want to have the document Model to be a rich text document, like in Google Docs where a user on the site can write a document and put images in the document. How do I create a model that can support this? -Second, I want to have multiple Video and Document objects for each Topic object and have each Video and Document have there own page and have those pages have a specific order (ie. video1, video2, document1, video3, document4, etc...). How can I keep track of what page number each document or video is? Thank you for the help!
answer count: 1
tagged with: database-schema
has answer: http://stackoverflow.com/a/51847954
has title: How to structure Django models for pages and rich text
tagged with: django
tagged with: python
type: UnansweredQuestion

http://stackoverflow.com/comment/126412932
type: AnswerComment
has text: @user15649753 - from pyspark.sql import functions as func
type: Comment
comment on: http://stackoverflow.com/a/51880971
score: 0

http://stackoverflow.com/comment/90800354
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51917930
has text: See http://sphinxsearch.com/docs/current.html#installation.

http://stackoverflow.com/comment/90580941
comment on: http://stackoverflow.com/q/51812972
score: 0
has text: You could use the `re` (regex) module to extract the part in each line. I'm not familiar with regex, but I think it might be something like `r'.*(\d{0,4} g).*'`. Could anyone amend this?
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51863888
has body: I use Channels for websockets in Django. It is nicely supported with Django. Have a look into it and let me know if you need any help in using it.
type: Answer
answers question: http://stackoverflow.com/q/51860792
score: 0

http://stackoverflow.com/q/51942059
answer count: 1
tagged with: flann
tagged with: python
tagged with: kdtree
has title: python cv2 feature matching give different results
tagged with: sift
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52115346
type: Question
has body: When I match SIFT feature using FLANN,I found same input descriptor give different match pairs in same process. python code: import cv2 def match(des_q, des_t): FLANN_INDEX_KDTREE = 1 ratio = 0.7 index_params = dict(algorithm=FLANN_INDEX_KDTREE, trees=5) search_params = dict(checks=50) flann1 = cv2.FlannBasedMatcher(index_params, search_params) two_nn = flann1.knnMatch(des_q, des_t, k=2) matches = [(first.queryIdx, first.trainIdx) for first, second in two_nn if first.distance &lt; ratio * second.distance] print(matches) return matches def img_sim(img1, img2): img1 = cv2.cvtColor(img1, cv2.IMREAD_GRAYSCALE) img2 = cv2.cvtColor(img2, cv2.IMREAD_GRAYSCALE) sift = cv2.xfeatures2d.SIFT_create() eps = 1e-7 # find the keypoints and descriptors with SIFT kp1, des1 = sift.detectAndCompute(img1, None) des1 /= (des1.sum(axis=1, keepdims=True) + eps) des1 = np.sqrt(des1) kp2, des2 = sift.detectAndCompute(img2, None) des2 /= (des2.sum(axis=1, keepdims=True) + eps) des2 = np.sqrt(des2) # test images,same input(des1,des2),different output? matches1 = match(des1, des2) matches2 = match(des1, des2) img1 = '' # query image img2 = '' # index image img1 = cv2.cvtColor(cv2.imread(img1), cv2.COLOR_BGR2RGB) img2 = cv2.cvtColor(cv2.imread(img2), cv2.COLOR_BGR2RGB) img_sim(img1, img2) I found the matches in line 11 is different although my input descriptor(des1,des2) is same,I guess the reason is kd-tree cache,but I can't solve it.Any one could help me? I want the matches result is always same. My cv2 version is 3.4.0, Thanks in advance.
tagged with: opencv
tagged with: opencv3.0
score: 0

http://stackoverflow.com/comment/94352993
comment on: http://stackoverflow.com/a/51953882
has text: I understand your point about names, but why you say it is nor vectorizable?
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/90677036
comment on: http://stackoverflow.com/a/51861788
has text: Sorry; I hadn't run the code yet and just assumed it was right. It's fixed now. The reason I use `itertools.islice()` was to efficiently skip the first list in `time_series_data` since we had already used it. The original code I had skipped the last value instead of the first because I wasn't paying attention to where I was putting the 1.
type: AnswerComment
score: 0
type: Comment

apache
tag name: apache
tags question: http://stackoverflow.com/q/51865565
tags question: http://stackoverflow.com/q/51868154
tags question: http://stackoverflow.com/q/51953349
tags question: http://stackoverflow.com/q/51892217
tags question: http://stackoverflow.com/q/51849725
tags question: http://stackoverflow.com/q/51897917
tags question: http://stackoverflow.com/q/51843807
tags question: http://stackoverflow.com/q/51830831
type: Tag

http://stackoverflow.com/comment/90746225
type: Comment
comment on: http://stackoverflow.com/a/51849848
has text: Isn't the point of anaconda to install python? Why would you already have python installed?
type: AnswerComment
score: 0

http://stackoverflow.com/comment/90822105
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51903209
has text: For some reason, on my end, it is rejecting .txt file as well

http://stackoverflow.com/q/51804365
tagged with: swift
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/60531883
accepted answer: http://stackoverflow.com/a/51804652
tagged with: signal-processing
type: Question
has title: Why is FFT different in Swift than in Python?
answer count: 2
possible better answer: http://stackoverflow.com/a/60531883
has body: I'm trying to port some python numpy code to Swift using the Accelerate framework. In python I write import numpy as np frames = np.array([1.0, 2.0, 3.0, 4.0]) fftArray = np.fft.fft(frames, len(frames)) print(fftArray) And the output is: [10.+0.j -2.+2.j -2.+0.j -2.-2.j] So in Swift I'm trying to calculate the FFT like this: import Foundation import Accelerate func fftAnalyzer(frameOfSamples: [Float]) { // As above, frameOfSamples = [1.0, 2.0, 3.0, 4.0] let analysisBuffer = frameOfSamples let frameCount = frameOfSamples.count var reals = [Float]() var imags = [Float]() for (idx, element) in analysisBuffer.enumerated() { if idx % 2 == 0 { reals.append(element) } else { imags.append(element) } } var complexBuffer = DSPSplitComplex(realp: UnsafeMutablePointer(mutating: reals), imagp: UnsafeMutablePointer(mutating: imags)) let log2Size = Int(log2f(Float(frameCount))) guard let fftSetup = vDSP_create_fftsetup(vDSP_Length(log2Size), Int32(kFFTRadix2)) else { return [] } // Perform a forward FFT vDSP_fft_zrip(fftSetup, &amp;(complexBuffer), 1, UInt(log2Size), Int32(FFT_FORWARD)) let realFloats = Array(UnsafeBufferPointer(start: complexBuffer.realp, count: Int(frameCount))) let imaginaryFloats = Array(UnsafeBufferPointer(start: complexBuffer.imagp, count: Int(frameCount))) print(realFloats) print(imaginaryFloats) // Release the setup vDSP_destroy_fftsetup(fftSetup) return realFloats } The realFloats and imaginaryFloats are printed like so: [20.0, -4.0, 0.0, 0.0] [-4.0, 4.0, 0.0, 0.0] Any ideas on what I should be doing differently?
downvote count: 0
tagged with: accelerate-framework
favorite count: 0
tagged with: fft
has answer: http://stackoverflow.com/a/51804652
upvote count: 1
tagged with: python

http://stackoverflow.com/comment/90855468
type: QuestionComment
type: Comment
score: 1
has text: Welcome to Stack Overflow! Could you please post a [Minimal, Complete, and Verifiable](https://stackoverflow.com/help/mcve) example of your attempt and say specifically where you're stuck.
comment on: http://stackoverflow.com/q/51952333

http://stackoverflow.com/a/51929430
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: This is the same issue as described for R scripts here, but for the sake of clarity, I'll add an answer for Python in Power BI as well. Short answer: Just change the Date data type from date to Text before you insert the Python Script. The details: If you import the csv file using the Home &gt; Get Data functionality, and then go to Home &gt; Edit Queries, this is what you'll see: Before you do anything else, just click on the symbol next to date and select Text. Now you can click Run Python Script, insert your code and clikc OK. This takes you to one last intermediate step where you'll have to click Table here: This is it: Notice that the datatype of Date is changed to a date format. If not you can easily change it again with the right-click drop-down menu as explained above.
has comment: http://stackoverflow.com/comment/137330816
score: 16
upvote count: 16
accepted answer of: http://stackoverflow.com/q/51929420
answers question: http://stackoverflow.com/q/51929420

http://stackoverflow.com/q/51902501
tagged with: pyqt4
has body: I've been trying to get a controller to work with signals (pyqtSignal), but I get this message when interacting with the GUI: Traceback (most recent call last): File "main_signals.py", line 102, in &lt;module&gt; helper.Sinal.Emt.connect(PID.Imprime, QtCore.Qt.QueuedConnection) AttributeError: 'PyQt4.QtCore.pyqtBoundSignal' object has no attribute 'Emt' Would someone please tell me what I'm doing wrong, here's the stripped down version of the code (main_signals.py): # Import 3rd party libraries from PyQt4 import QtGui, QtCore from PyQt4.QtCore import QObject, pyqtSignal import time import pyqtgraph # Import python standard modules import sys # This file holds the MainWindow import Plotter # Variables T = [0] R = [0] # Disregard this function def ReadChannel(channel): # ----------------------------------------------------------------- class Ctrldr(QtGui.QMainWindow, Plotter.Ui_MainWindow): def __init__(self): super(self.__class__, self).__init__() self.setupUi(self) self.QOutput.clicked.connect(self.Calculo) # Plotting @QtCore.pyqtSlot(str, tuple) def Imprime(self, name, ptm): global T, R, W x, y = ptm R.append(y) self.graphicsView.plotItem.plot(T, R, pen='b') # Calculations def Calculo(self): global T t = time.clock() T.append(t) Read = ReadChannel(0) Helper.Sinal.emit("Sensor", (t, Read)) Read = str(Read) self.QResult.setText(Read) # ----------------------------------------------------------------- class Helper(QtCore.QObject): Sinal = QtCore.pyqtSignal(str, tuple) def __init__(self): super(self.__class__, self).__init__() def Emt(self, str, tuple): self.Sinal.emit(str, tuple) # ----------------------------------------------------------------- if __name__ == '__main__': app = QtGui.QApplication(sys.argv) PID = Ctrldr() helper = Helper() helper.Sinal.connect(PID.Imprime) PID.show() app.exec_() Tried to follow the examples in these 2 pages: Plotting with pyqtgraph using external data Tutorial- Creating your own signals an slots
tagged with: python-2.7
tagged with: pyqt
answer count: 1
linked to: http://stackoverflow.com/q/50314924
has answer: http://stackoverflow.com/a/51903021
tagged with: python
type: AnsweredQuestion
has title: AttributeError: 'PyQt4.QtCore.pyqtBoundSignal' object has no attribute 'Emt'
score: 0
tagged with: qt-signals
type: Question
accepted answer: http://stackoverflow.com/a/51903021

http://stackoverflow.com/comment/90782728
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51887428
has text: Thank you guys ! I appreciate your opinions.
score: 0

http://stackoverflow.com/a/51865603
downvote count: 0
has comment: http://stackoverflow.com/comment/90683443
has body: The right way to do what you asked for is almost certainly to use the debugger, pdb. The right way to do what you want is probably something completely different: find some signal that tells you that the step is done, and wait for that signal. With problems like this, almost any time you pick will be way, way too long 99% of the time, but still too short 1% of the time. That signal may be joining a thread, or waiting on a (threading or multiprocessing) Condition, or getting from a queue, or awaiting a coroutine or future, or setting the sync flag on an AppleEvent, or… It really depends on what you're doing. But if you really want to do this, you can use settrace: def sleeper(frame, event, arg): if event == 'line': time.sleep(2) return sleeper sys.settrace(sleeper) One small problem is that the notion of line used by the interpreter may well not be what you want. Briefly, a 'line' trace event is triggered whenever the ceval loop jumps to a different lnotab entry (see lnotab_notes.txt in the source to understand what that means—and you'll probably need at least a passing understanding of how bytecode is interpreted, at least from reading over the dis docs, to understand that). So, for example, a multiline expression is a single line; the line of a with statement may appear twice, etc.1 And there's probably an even bigger problem. Sometimes, the script continues to next step before the previous step is fully complete. I don't know what those steps are, but if you put the whole thread to sleep for 2 seconds, there's a good chance the step you're waiting for won't make any progress, because the thread is asleep. (For example, you're not looping through any async or GUI event loops, because you're doing nothing at all.) If so, then after 2 seconds, it'll still be just as incomplete as it was before, and you'll have wasted 2 seconds for nothing. 1. If your notion of "line" is closer to what's described in the reference docs on lexing and parsing Python, you could create an…
type: Answer
upvote count: 3
answers question: http://stackoverflow.com/q/51865326
score: 3
has comment: http://stackoverflow.com/comment/90683376

http://stackoverflow.com/q/51955647
score: 0
has comment: http://stackoverflow.com/comment/90862288
tagged with: python
accepted answer: http://stackoverflow.com/a/51956426
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90862572
has comment: http://stackoverflow.com/comment/90862466
has body: I am using magpie - a multilabel classifier on Tensorflow with Word2vec. The training works fine using Python 2.7, but with Python 3.x it gives this error below. I am on Ubuntu 16.04.5 LTS, weirdly the Python 3.x code works fine on a different Ubuntu machine. I have updated my dependencies: word2vec, magpie, tf and not sure what could be going wrong. /usr/lib/python3.5/importlib/_bootstrap.py:222: RuntimeWarning: numpy.dtype size changed, may indicate binary incompatibility. Expected 96, got 88 return f(*args, **kwds) Using TensorFlow backend. /usr/lib/python3.5/importlib/_bootstrap.py:222: RuntimeWarning: numpy.dtype size changed, may indicate binary incompatibility. Expected 96, got 88 return f(*args, **kwds) /usr/lib/python3.5/importlib/_bootstrap.py:222: RuntimeWarning: numpy.dtype size changed, may indicate binary incompatibility. Expected 96, got 88 return f(*args, **kwds) /usr/lib/python3.5/importlib/_bootstrap.py:222: RuntimeWarning: numpy.dtype size changed, may indicate binary incompatibility. Expected 96, got 88 return f(*args, **kwds) /usr/lib/python3.5/importlib/_bootstrap.py:222: RuntimeWarning: numpy.dtype size changed, may indicate binary incompatibility. Expected 96, got 88 return f(*args, **kwds) Traceback (most recent call last): File "train_magpie.py", line 1, in &lt;module&gt; from magpie import Magpie File "/usr/local/lib/python3.5/dist-packages/magpie/__init__.py", line 1, in &lt;module&gt; from .main import Magpie File "/usr/local/lib/python3.5/dist-packages/magpie/main.py", line 12, in &lt;module&gt; from magpie.base.word2vec import train_word2vec, fit_scaler File "/usr/local/lib/python3.5/dist-packages/magpie/base/word2vec.py", line 7, in &lt;module&gt; from gensim.models import Word2Vec File "/usr/local/lib/python3.5/dist-packages/gensim/__init__.py", line 6, in &lt;module&gt; from gensim import parsing, matutils, interfaces, corpora, models, similarities, summarization File "/usr/local/lib/python3.5/dist-packages/gensim/parsing/__init__.p…
has comment: http://stackoverflow.com/comment/90862497
has answer: http://stackoverflow.com/a/51956426
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/90863441
type: Question
type: AnsweredQuestion
has title: "TypeError: join() argument must be str or bytes, not 'NoneType'" using Magpie+Tensorflow/Python3
has comment: http://stackoverflow.com/comment/90861991
answer count: 1

http://stackoverflow.com/comment/90681294
type: Comment
has text: Perfect. Thanks guys. I will accept the answer once it allows me to do so.
type: AnswerComment
comment on: http://stackoverflow.com/a/51864524
score: 0

http://stackoverflow.com/comment/90711596
score: 0
comment on: http://stackoverflow.com/q/51880062
has text: Only that `.` is **any** character and not necessarily an alphanumeric... Not sure if that's what you mean though? (You can also use `\?` for a literal ? instead of putting it in a character class)
type: Comment
type: QuestionComment

recurrent-neural-network
tags question: http://stackoverflow.com/q/51872304
tags question: http://stackoverflow.com/q/51810283
tags question: http://stackoverflow.com/q/51939022
tags question: http://stackoverflow.com/q/51917160
tags question: http://stackoverflow.com/q/51842242
type: Tag
tags question: http://stackoverflow.com/q/51814651
tags question: http://stackoverflow.com/q/51919077
tags question: http://stackoverflow.com/q/51817228
tag name: recurrent-neural-network
tags question: http://stackoverflow.com/q/51827349

http://stackoverflow.com/a/52150297
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/51856215
has body: I could not export the sample clock on this gear, The solution I found is using the same master clock, and use the start trigger of the first card for the second one. I start the second one (waiting for the trigger) end then the first one. self.task2.timing.ref_clk_src = "PXI_Clk10" self.task2.timing.ref_clk_rate = 10000000 self.task2.timing.cfg_samp_clk_timing(rate=rate2, sample_mode=nidaqmx.constants.AcquisitionType.CONTINUOUS, samps_per_chan=2048) self.task3.timing.ref_clk_src = "PXI_Clk10" self.task3.timing.ref_clk_rate = 10000000 self.task3.timing.cfg_samp_clk_timing(rate=rate3, sample_mode=nidaqmx.constants.AcquisitionType.CONTINUOUS, samps_per_chan=2048) self.task2.control(TaskMode.TASK_COMMIT) self.task3.triggers.start_trigger.cfg_dig_edge_start_trig( "/PXI1Slot2/ai/StartTrigger") self.task3.start() self.task2.start()
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51856215

http://stackoverflow.com/a/51925517
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51924775
type: Answer
has body: I suggest use sheet_name=None parameter for create Ordered Dictionary of DataFrames by all sheets: path = "file.xlsx" df = pd.read_excel(path, sheet_name=None) print (df) OrderedDict([('Run 1', Test Name Test Status Time Value 0 Test 1 PASS 00:06:43 1 Test 2 Fail 00:06:24 2 Test 3 PASS 00:06:10 3 Test 4 PASS 00:05:25 4 Test 5 Fail 00:05:07 5 Test 6 PASS 00:02:45), ('Run 2', Test Name Test Status Time Value 0 Test 1 PASS 00:05:43 1 Test 2 Fail 00:04:24 2 Test 3 PASS 00:05:10 3 Test 4 PASS 00:06:25 4 Test 5 PASS 00:03:07 5 Test 6 PASS 00:04:45), ('Run 3', Test Name Test Status Time Value 0 Test 1 PASS 00:06:40 1 Test 2 PASS 00:06:52 2 Test 3 PASS 00:05:50 3 Test 4 PASS 00:05:35 4 Test 5 PASS 00:06:17 5 Test 6 PASS 00:03:55)]) Then loop and concat together with align by columns Test Name and Test Status, so set_index is necessary. Also NaNs are added for not matched values: d = {k:v.set_index(['Test Name','Test Status'])['Time Value'] for k, v in df.items()} result= pd.concat(d, axis=1).reset_index() print (result) Test Name Test Status Run 1 Run 2 Run 3 0 Test 1 PASS 00:06:43 00:05:43 00:06:40 1 Test 2 Fail 00:06:24 00:04:24 NaN 2 Test 2 PASS NaN NaN 00:06:52 3 Test 3 PASS 00:06:10 00:05:10 00:05:50 4 Test 4 PASS 00:05:25 00:06:25 00:05:35 5 Test 5 Fail 00:05:07 NaN NaN 6 Test 5 PASS NaN 00:03:07 00:06:17 7 Test 6 PASS 00:02:45 00:04:45 00:03:55 Last append to existing file in new sheet: #https://stackoverflow.com/a/42375263 from openpyxl import load_workbook book = load_workbook(path) writer = pd.ExcelWriter(path, engine = 'openpyxl') writer.book = book result.to_excel(writer, sheet_name = 'Status', index=False) writer.save() writer.close()
score: 0
accepted answer of: http://stackoverflow.com/q/51924775

http://stackoverflow.com/q/51833386
has answer: http://stackoverflow.com/a/51833440
type: AnsweredQuestion
has title: CSV writer prints extra quotes
type: Question
upvote count: 4
has comment: http://stackoverflow.com/comment/90620805
downvote count: 0
has body: I am learning Python script. I want to read a TSV file and print the result in a particular format like below, Input file [tab separated]: 1 john henry 1.234 Output: 1, "john", "henry", 1.234 I wrote the below code. tsvfile = csv.reader(open('input.tsv' , 'r'), delimiter='\t') outfile = csv.writer(open('output.txt' , 'w+'), escapechar='\"', quoting=csv.QUOTE_NONE) row_number = 1 for row in tsvfile: outfile.writerow([row[0]+","]) outfile.writerow(['"'+row[1]+'"'+","]) outfile.writerow(['"'+row[2]+'"'+","]) outfile.writerow([row[3]]) row_number = row_number + 1 It generates the output as 1, ""john""", ""henry""", 1.234 The script prints ", instead of , and "" instead of ". I am trying to understand this behavior. Can anyone help me why my scripts prints extra " everywhere? How should I generate the expected output?
score: 4
has comment: http://stackoverflow.com/comment/90620859
has comment: http://stackoverflow.com/comment/90654724
answer count: 3
has answer: http://stackoverflow.com/a/77232519
has answer: http://stackoverflow.com/a/51833577
has comment: http://stackoverflow.com/comment/90654828
favorite count: 0
accepted answer: http://stackoverflow.com/a/51833577
possible better answer: http://stackoverflow.com/a/51833440
tagged with: python

http://stackoverflow.com/q/51828692
tagged with: libraries
type: Question
has body: I have been using the python ctypes library (in cygwin on windows 7) to make calls to a dll that was written in c and built on cygwin. Recently, the producer of the dll put out an update and now the file handle changes every time I call ctypes.CDLL, the old version used to take the same handle each time. My question is: What differences in the build process of a dll could cause it to take a consistent file handle each time vs taking a new one each time? Thanks!
tagged with: ctypes
has title: DLL file handle changes
tagged with: dll
score: -1
has answer: http://stackoverflow.com/a/51830297
downvote count: 1
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
upvote count: 0

http://stackoverflow.com/a/51840236
score: 1
type: Answer
upvote count: 1
has body: It seems like the stop words returned by NLTK are a list, thus having O(n) lookup. Convert the list to a set first, then it will be much faster. &gt;&gt;&gt; some_word = "aren't" &gt;&gt;&gt; stop = stopwords.words('english') &gt;&gt;&gt; type(stop) list &gt;&gt;&gt; %timeit some_word in stop 1000000 loops, best of 3: 1.3 µs per loop &gt;&gt;&gt; stop = set(stopwords.words('english')) &gt;&gt;&gt; %timeit some_word in stop 10000000 loops, best of 3: 43.8 ns per loop However, while this should solve the performanc problem, it seems like your code is not doing what you expect it to do in the first place. readit is a single string holding the content of the entire file, thus you are iterating characters and not words. You import the csv module, but you never use it. Also, the strings in your csv file should be quoted, otherwise it will split at all ,, not just at the last one. If you can not change the csv file, it might be easier to use str.rsplit though. texts = [line.rsplit(",", 1)[0] for line in readit.splitlines()] filtered = [[w for w in text.split() if w.lower() not in stopwords_set] for text in texts]
answers question: http://stackoverflow.com/q/51839778
downvote count: 0

http://stackoverflow.com/comment/90632281
score: 0
comment on: http://stackoverflow.com/q/51839219
type: Comment
type: QuestionComment
has text: I'm not sure what you mean by "deleted the python"? You mean you used `conda` to uninstall and reinstall pandas?

http://stackoverflow.com/comment/119121947
type: QuestionComment
has text: @dablackreaper did you manage to solve this?
score: 0
comment on: http://stackoverflow.com/q/51815254
type: Comment

http://stackoverflow.com/q/51826422
has comment: http://stackoverflow.com/comment/90607200
answer count: 2
downvote count: 4
has comment: http://stackoverflow.com/comment/90607482
has comment: http://stackoverflow.com/comment/90607202
has title: Python inheritance questions
favorite count: 0
has comment: http://stackoverflow.com/comment/90607547
has comment: http://stackoverflow.com/comment/90607553
type: UnansweredQuestion
score: -3
has comment: http://stackoverflow.com/comment/90607415
has answer: http://stackoverflow.com/a/51826700
tagged with: python
has answer: http://stackoverflow.com/a/51826664
has comment: http://stackoverflow.com/comment/90607177
has comment: http://stackoverflow.com/comment/90607580
has body: I'm a self-taught programmer and currently I'm learning elementary python; read material with inheritance in python yet still don't understand how it works. Here, players is a child class of Football; however, it can't inherit the function/ objects (.getCoach) from Football. (error: p.getCoach())- the final line. May I know which part goes wrong? class Football: def __init__(self, name, ranking, coach): self.name= name self.rank = ranking self.coach= coach def getName(self): print(self.name) def getRank(self): print(self.name+ "was in" + self.rank) def getCoach(self): if self.rank&lt;5: print(self.coach+ "is a bad coach") else: print(self.coach+ "is a good coach") class Players(Football): def __init__(self, Appearances, Score): self.Appearances= Appearances self.Score= Score def getapp(self): print(self.Appearances) def getscore(self): print(self.Score) p = Players(5,5, "Vincent") p.getCoach()
upvote count: 1
has comment: http://stackoverflow.com/comment/90607507
has comment: http://stackoverflow.com/comment/90608549
type: Question
has comment: http://stackoverflow.com/comment/90607543
has comment: http://stackoverflow.com/comment/90607491
tagged with: oop
tagged with: inheritance
tagged with: parent-child
has comment: http://stackoverflow.com/comment/90607500

http://stackoverflow.com/q/51932585
has answer: http://stackoverflow.com/a/51980769
has title: How to apply executor.map to for loop without a function?
tagged with: python
type: AnsweredQuestion
has body: I have a list of xml and a for loop that flattens the xml into a pandas dataframe. The for loop works perfectly fine but is taking very long to flatten the xml, which is getting larger as time goes on. How do I wrap the below for-loop in executor.map to spread the work load among different cores? I am following this article https://medium.com/@ageitgey/quick-tip-speed-up-your-python-data-processing-scripts-with-process-pools-cf275350163a for loop to flatten xml: df1 = pd.DataFrame() for i in lst: print('i am working') soup = BeautifulSoup(i, "xml") # Get Attributes from all nodes attrs = [] for elm in soup(): # soup() is equivalent to soup.find_all() attrs.append(elm.attrs) # Since you want the data in a dataframe, it makes sense for each field to be a new row consisting of all the other node attributes fields_attribute_list= [x for x in attrs if 'Id' in x.keys()] other_attribute_list = [x for x in attrs if 'Id' not in x.keys() and x != {}] # Make a single dictionary with the attributes of all nodes except for the `Field` nodes. attribute_dict = {} for d in other_attribute_list: for k, v in d.items(): attribute_dict.setdefault(k, v) # Update each field row with attributes from all other nodes. full_list = [] for field in fields_attribute_list: field.update(attribute_dict) full_list.append(field) # Make Dataframe df = pd.DataFrame(full_list) df1 = df1.append(df) Does the for loop need to be transformed into a function?
type: Question
accepted answer: http://stackoverflow.com/a/51980769
score: 5
upvote count: 5
downvote count: 0
answer count: 1
tagged with: concurrent.futures
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/comment/90809889
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51929973
has text: thank you very much, of course adding 'add () po x.average_rating' solved the whole problem.

http://stackoverflow.com/q/51938027
downvote count: 1
type: Question
has title: Python logging.setLoggerClass() isn't
answer count: 1
has body: Given this bit of Python: logging.setLoggerClass(MyLogger) logger = logging.getLogger() print(type(logger)) ...and what I believe is a properly implemented MyLogger class: class MyLogger(logging.getLoggerClass()): def __init__(self, name: str=os.path.basename(__file__)) -&gt; None: logging.Logger.__init__(self, name=name) I'd expect GetLogger to return an instance of MyLogger, but it doesn't: &lt;class 'logging.RootLogger'&gt; No errors or warning. It also seems that the MyLogger constructor is never being called when I make a call to logging.getLogger() What am I doing wrong?
favorite count: 0
has answer: http://stackoverflow.com/a/51938121
score: 6
tagged with: python
accepted answer: http://stackoverflow.com/a/51938121
tagged with: logging
type: AnsweredQuestion
upvote count: 7

http://stackoverflow.com/comment/90824610
comment on: http://stackoverflow.com/q/51937189
score: 0
type: Comment
type: QuestionComment
has text: Welcome to StackOverflow. You need to show a complete, runnable code snippet that shows your problem. The cause of your error is almost certainly earlier in your code, not in the two lines you showed us. Read and follow [How to create a Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve).

http://stackoverflow.com/comment/90828262
type: AnswerComment
has text: Does this require the user to install any software like Pyperclip? The instructions on the assignment this is about are: "Solutions that require the user install any software will NOT be accepted (in case you are not sure, this means NO Pyperclip.)"
type: Comment
comment on: http://stackoverflow.com/a/51933139
score: 0

http://stackoverflow.com/comment/90587308
comment on: http://stackoverflow.com/q/51816479
score: 0
type: Comment
type: QuestionComment
has text: @user3483203 that sounds promising, feel free to write an answer teaching me the flatten and join process.

http://stackoverflow.com/q/51867255
tagged with: callback
favorite count: 0
upvote count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51867726
tagged with: python
has answer: http://stackoverflow.com/a/51867780
linked to: http://stackoverflow.com/q/19545982
score: 2
has title: Python contextmanager and object creation
type: Question
linked to: http://stackoverflow.com/q/16017397
tagged with: contextmanager
answer count: 2
has body: I would like to create a contextmanager that would intercept any object instantiation from a given class or subclasses of this classes and do something with the object. I sudo code it could look like something like this: with my_context_watchdog(my_callback, BaseClass): obj_1 = BaseClass(name) # launch callback obj_2 = SubClass(name) # launch callback obj_3 = RandomClass(name) # does not launch callback def my_callback(new_obj): print("new object name:", new_obj.name) Is there anyway I could do something like this in Python? The best would be that the callback is executed only after the object has been fully instantiated. Important: I can't modify any of the object classes, they are in a library I don't have any control on it. I just want to raise a callback when some of the Classes of this library are instantiated. Maybe the contextmanager is not the best idea, I'm opened to any other solution.
downvote count: 0

http://stackoverflow.com/comment/90599944
has text: something is probably using the file in background. Restart your system and try running the code again.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51822965

http://stackoverflow.com/q/51940358
type: Question
has comment: http://stackoverflow.com/comment/90835590
has comment: http://stackoverflow.com/comment/90831061
score: 0
tagged with: pandas
type: UnansweredQuestion
has title: group by 5 years
has comment: http://stackoverflow.com/comment/90830588
tagged with: python
has body: I have a dataframe, indexed by year, month and day. Other fields are total_spending and total_earning. I need to find out highest_earning and highest_spending in each year and then have to find mean of highest_earning and and mean of higest_spending in every 5 years. I am getting hard time on how find mean of those 2 field for every 5 years
linked to: http://stackoverflow.com/q/39718157
has comment: http://stackoverflow.com/comment/90831212
answer count: 0

http://stackoverflow.com/q/51868533
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90761624
answer count: 0
score: 1
has title: "Error: variable "real" does not exist in the model block" in Stan
has comment: http://stackoverflow.com/comment/90722468
upvote count: 1
tagged with: pystan
type: Question
has body: I am following the example code using Stan in Python but it is not compiled because of the syntax error: ValueError: Failed to parse Stan model 'anon_model_ad43313e8b4b0b001a1a5d32da64a34e'. Error message: SYNTAX ERROR, MESSAGE(S) FROM PARSER: variable "real" does not exist. error in 'unknown file name' at line 20, column 9 ------------------------------------------------- 18: } 19: model{ 20: real l1; ^ 21: real l2; ------------------------------------------------- And this is the stan code: import numpy as np import statsmodels.api as sm import pystan from scipy.stats import uniform, invgauss stan_code = """ data{ int&lt;lower=0&gt; N; vector[N] Y; vector[N] x1; } parameters{ real beta0; real beta1; real&lt;lower=0&gt; lambda; } transformed parameters{ vector[N] exb; vector[N] xb; for (i in 1:N) xb[i] = beta0 + beta1 * x1[i]; for (i in 1:N) exb[i] = exp(xb[i]); } model{ real l1; real l2; vector[N] loglike; lambda ~ uniform(0.0001, 100); for (i in 1:N){ l1 = 0.5 * (log(lambda) - log(2 * pi() * pow(Y[i], 3))); l2 = -lambda*pow(Y[i] - exb[i], 2)/(2 * pow(exb[i], 2) * Y[i]); loglike[i] = l1 + l2; } target += loglike; } """ fit = pystan.stan(model_code=stan_code, data= stan_data, iter=5000, chains=3, warmup=2500, n_jobs=3) Is there any something wrong? I also defined stan_data before implementing stan function. I read the Stan manual about the model block and it says it is allowed to declare local variables in the model block... Please let me know the problems above.
tagged with: stan
downvote count: 0
favorite count: 0

http://stackoverflow.com/q/51807477
has body: I'm trying to list the selected options from the page. But nothing is printed with below code. Any help will be appreciated. HTML code: 1 2 3 4 What I tried: el = driver.find_element_by_id("tag_opts") for option in el.find_elements_by_tag_name('option'): if option.text in labels: print(option) I tried with many other options but couldn't succeed.
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90570191
accepted answer: http://stackoverflow.com/a/51809842
has comment: http://stackoverflow.com/comment/90573446
tagged with: selenium
tagged with: web-scraping
type: Question
has comment: http://stackoverflow.com/comment/90570161
possible better answer: http://stackoverflow.com/a/51807629
has comment: http://stackoverflow.com/comment/90571062
score: 0
has title: List selected options in Selenium Python
answer count: 2
has answer: http://stackoverflow.com/a/51807629
has answer: http://stackoverflow.com/a/51809842
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90570397
tagged with: python

http://stackoverflow.com/a/51824126
downvote count: 0
upvote count: 2
answers question: http://stackoverflow.com/q/51823857
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/90627795
has body: Looking at faster_rcnn.proto: // Naming conventions: // Faster R-CNN models have two stages: a first stage region proposal network // (or RPN) and a second stage box classifier. We thus use the prefixes // `first_stage_` and `second_stage_` to indicate the stage to which each // parameter pertains when relevant And so: // Maximum number of RPN proposals retained after first stage postprocessing. optional int32 first_stage_max_proposals = 15 [default=300]; Faster R-CNN has two networks, the first proposes regions where objects may be found and the second tries to detect objects in those. Increasing the number of proposals by the first network increases the accuracy but implies more computational work, because the second network has to search in more potential areas. For a quick explanation on how Faster R-CNN works check out Faster R-CNN Explained, and if you want to have the full picture you can look at the original publication: Faster R-CNN: Towards Real-Time Object Detection with Region Proposal Networks.
has comment: http://stackoverflow.com/comment/90619546

http://stackoverflow.com/comment/90885260
comment on: http://stackoverflow.com/a/51935876
score: 0
type: AnswerComment
has text: @PythonNewb The best way would be to read it as a string. Then remove leading $, for example using next code df['Price'] = df['Price'].str[1:]. Then convert to int using next code df['Price'] = df['Price'].astype('int64')
type: Comment

http://stackoverflow.com/comment/90621238
type: Comment
comment on: http://stackoverflow.com/a/51833440
score: 0
type: AnswerComment
has text: The above code writes the single quote for all values in the input file, I would like to have quotes only for the specific string in the input like 'John' or 'henry' and no quotes for the number values. Is there any way I can avoid that?

http://stackoverflow.com/q/51900841
answer count: 3
has comment: http://stackoverflow.com/comment/90949168
has answer: http://stackoverflow.com/a/65779097
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/57749576
upvote count: 2
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/52299064
score: 2
tagged with: openpyxl
has comment: http://stackoverflow.com/comment/90965705
type: Question
has title: OpenPyXL - How to query cell borders?
has body: New to both python and openpyxl. Writing a py script to glom through a ton of Excel workbooks/sheets, and need to find certain cells identified by their border formatting. I see several examples online of how to set cell borders, but I need to read them. Specifically, I wish to identify table boundaries, when the data within the table is inconsistent, but the table borders are always present. So, I need to find identify the cells with: * top / left borders * top / right borders * bottom / left borders * bottom / right borders (thin borders). There is only one such table per worksheet. Could some kind maven point me to a code sample? I would provide my code thus far, but honestly I have no idea how to begin. My code for looping through each worksheet is: for row in range(1, ws.max_row, 1): for col in range(1, sheet.max_column+1): tmp = NumToAlpha(col) ref = str(tmp) + str(row) hasTopBorder = ws[ref].?????? <=== how do I get a boolean here? hasLeftBorder = ws[ref].?????? <=== how do I get a boolean here? hasRightBorder = ws[ref].?????? <=== how do I get a boolean here? hasBottomBorder = ws[ref].?????? <=== how do I get a boolean here? if hasTopBorder==True and hasLeftBorder==True and hasRightBorder==False and hasBottomBorder==False: tableTopLeftCell = tmp + str(row) elif hasTopBorder==True and hasLeftBorder==False and hasRightBorder==True and hasBottomBorder==False: tableTopRightCell = tmp + str(row) elif hasTopBorder==False and hasLeftBorder==True and hasRightBorder==False and hasBottomBorder==True: tableBottomLeftCell = tmp + str(row) elif hasTopBorder==False and hasLeftBorder==False and hasRightBorder==True and hasBottomBorder==True: tableBottomRightCell = tmp + str(row) if tableTopLeftCell != "" and tableTopRightCell != "" and tableBottomLeftCell != "" and tableBottomRightCell != "": break if tableTopLeftCell != "" and tableTopRightCell != "" and tableBottomLeftCell != "" and tableBottomRightCell != "": break Comments/suggestions for streamlining this novice code …
has comment: http://stackoverflow.com/comment/90768825

http://stackoverflow.com/a/51799426
score: 1
answers question: http://stackoverflow.com/q/51799183
has comment: http://stackoverflow.com/comment/90555671
downvote count: 0
has comment: http://stackoverflow.com/comment/90555812
type: Answer
has body: copyfile() destination should be complete filename. As per Pythons docs: shutil.copyfile(src, dst) Copy the contents (no metadata) of the file named src to a file named dst. dst must be the complete target file name; look at shutil.copy() for a copy that accepts a target directory path. Try this: import shutil import os programSourcePath = "C:\Users\Admin\Desktop\Utilities_Installers_new\Programs" pstoolfiles = os.listdir(programSourcePath + '/PSTools') for name in pstoolfiles: srcname = os.path.join(programSourcePath + '/PSTools', name) dstname = os.path.join(r'c:/WINDOWS/System32', name) shutil.copyfile(srcname, dstname)
upvote count: 1
has comment: http://stackoverflow.com/comment/90555637
has comment: http://stackoverflow.com/comment/90555771

http://stackoverflow.com/q/51846547
has comment: http://stackoverflow.com/comment/90646523
has comment: http://stackoverflow.com/comment/90646488
answer count: 3
has answer: http://stackoverflow.com/a/51846686
has answer: http://stackoverflow.com/a/51846718
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/90646415
tagged with: python
has title: How to convert float into Hours Minutes Seconds?
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51846686
has body: I've values in float and I am trying to convert them into Hours:Min:Seconds but I've failed. I've followed the following post: Converting a float to hh:mm format For example I've got a value in float format: time=0.6 result = '{0:02.0f}:{1:02.0f}'.format(*divmod(time * 60, 60)) and it gives me the output: 00:36 But actually it should be like "00:00:36". How do I get this?
tagged with: time
upvote count: 3
has comment: http://stackoverflow.com/comment/90646484
type: Question
score: 3
linked to: http://stackoverflow.com/q/27496889
has comment: http://stackoverflow.com/comment/100568059
possible better answer: http://stackoverflow.com/a/51846797
tagged with: floating
has answer: http://stackoverflow.com/a/51846797

http://stackoverflow.com/q/51898761
has answer: http://stackoverflow.com/a/51898997
has comment: http://stackoverflow.com/comment/90748616
accepted answer: http://stackoverflow.com/a/51898997
has body: Everything I have found so far teaches only how to perform operations with the same Keys. I would like to perform a numpy var on two different dict, then have the result be the value in the resulting dict and the key be the concatenation of the two keys used. Ive tried serval different ways (trying to be efficient) to no avail. this is my current method. dict1 = {'mall': [[928046, 47653]], 'place': [[95446, 4233]], 'thing': [[76546, 4345463]]} dict2 = {'sam': [[4236, 44323]], 'dan': [[8676, 34223]], 'red': [[4236, 49684323]], 'bob': [[654, 42345]], 'sharon': [[321, 454234]], 'ashley': [[4958843, 4343423]]} var_dict = {(dict1[key] + dict2[key]): np.var((np.array(dict1.[key], dict2[key])) for key in dict1}
downvote count: 0
answer count: 1
favorite count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/90748776
tagged with: python
has comment: http://stackoverflow.com/comment/90748452
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90748746
type: Question
tagged with: numpy
has title: How do I perform a variance operation between two dictionaries with different keys in python?

http://stackoverflow.com/q/51853944
type: Question
has answer: http://stackoverflow.com/a/51854468
accepted answer: http://stackoverflow.com/a/51854468
has comment: http://stackoverflow.com/comment/90660511
upvote count: 1
answer count: 1
has title: Access data saved in ModelForm in views form_valid function
favorite count: 0
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/90660796
type: AnsweredQuestion
tagged with: many-to-many
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/90660708
has body: Suppose I have two models: Payment and User models.py class Payment(models.Model): user = models.ManyToManyField(A, blank=True) class User(models.Model): name = models.CharField(...) has_paid = models.BooleanField(...) forms.py CreatePayment(forms.ModelForm): class Meta: fields = '__all__' Now, when I submit the CreatePayment form, I can select multiple users for each payment (and vice versa, because multiple users can be paid for in a single payment and each user can make multiple payments). Is there a way I can edit the form_valid method in views.py so that I can make the has_paid field True only for the users selected in the CreatePayment form? Thanks in advance.

http://stackoverflow.com/comment/90675493
score: 1
comment on: http://stackoverflow.com/q/51861577
type: Comment
type: QuestionComment
has text: List comprehensions do not pre-allocated exactly the required memory. They essentially work like a for-loop with append, which overallocates

http://stackoverflow.com/comment/90561645
comment on: http://stackoverflow.com/q/51800340
has text: @MartijnPieters That is an misunderstanding, I'm afraid. Write any function (sync or async), register it and that's it. Other modules may then call it remotely and receive results.
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/90678909
has text: I think it's because you used "df" before you declared it.
type: AnswerComment
comment on: http://stackoverflow.com/a/51848717
type: Comment
score: 0

http://stackoverflow.com/q/51909312
has comment: http://stackoverflow.com/comment/91198787
has comment: http://stackoverflow.com/comment/90769895
answer count: 2
upvote count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/113653368
has comment: http://stackoverflow.com/comment/91451459
has comment: http://stackoverflow.com/comment/90785562
has comment: http://stackoverflow.com/comment/90785544
favorite count: 0
has answer: http://stackoverflow.com/a/57110294
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90768828
has title: ModuleNotFoundError: No module named 'tensorflow.compiler'
tagged with: python
has comment: http://stackoverflow.com/comment/90785454
has answer: http://stackoverflow.com/a/52540673
has comment: http://stackoverflow.com/comment/92021265
score: 1
tagged with: google-cloud-tpu
has body: ~\AppData\Roaming\Python\Python36\site-packages\tensorflow\contrib\tpu\python\tpu\tpu_estimator.py in &lt;module&gt;() 38 from tensorflow.contrib.tpu.python.tpu import tpu_config 39 from tensorflow.contrib.tpu.python.tpu import tpu_context ---&gt; 40 from tensorflow.contrib.tpu.python.tpu import tpu_feed 41 from tensorflow.contrib.tpu.python.tpu import training_loop 42 from tensorflow.contrib.tpu.python.tpu import util as util_lib ~\AppData\Roaming\Python\Python36\site-packages\tensorflow\contrib\tpu\python\tpu\tpu_feed.py in &lt;module&gt;() 26 from six.moves import xrange # pylint: disable=redefined-builtin 27 ---&gt; 28 from tensorflow.compiler.xla.experimental.xla_sharding import xla_sharding 29 from tensorflow.compiler.xla.python_api import xla_shape 30 from tensorflow.contrib.tpu.python.ops import tpu_ops ModuleNotFoundError: No module named 'tensorflow.compiler' The above error occurred when I ran the following code: env:windows10+jupyter notebook+tensorflow1.9+python3.6 import tensorflow as tf x_image = tf.reshape(x, [-1,24,24,3]) h_conv1 = tf.contrib.layers.conv2d(x_image, 64,5,1, "SAME", activation_fn=tf.nn.relu)
tagged with: tensorflow
type: Question

http://stackoverflow.com/comment/90769832
comment on: http://stackoverflow.com/a/51909568
score: 0
type: AnswerComment
has text: What does the program output as the `shift` value? It should be 16 for `X -> N`
type: Comment

http://stackoverflow.com/q/51830697
linked to: http://stackoverflow.com/q/2623156
has comment: http://stackoverflow.com/comment/90615838
upvote count: 4
has comment: http://stackoverflow.com/comment/90615941
has title: Convert date from integer to date format
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51847973
possible better answer: http://stackoverflow.com/a/51837477
downvote count: 0
has answer: http://stackoverflow.com/a/51837477
favorite count: 0
has comment: http://stackoverflow.com/comment/90615725
type: Question
has comment: http://stackoverflow.com/comment/90617346
tagged with: python
has answer: http://stackoverflow.com/a/51848717
has comment: http://stackoverflow.com/comment/90615998
score: 4
has body: I have a column 'start_date' which is an integer 37823. This happened when I used xlrd library to convert xlsx to csv. Hence '2003/07/21' got converted to 37823. I have gone through xlrd documentation and I understand there are several ways to convert it to date. However, I need to convert this to date format using PySpark in AWS Glue ETL jobs. Any suggestions? I tried using to_date, date_format functions, but nothing worked.
answer count: 3
linked to: http://stackoverflow.com/q/1108428
tagged with: aws-glue
tagged with: pyspark
has answer: http://stackoverflow.com/a/51847973

http://stackoverflow.com/comment/90693568
type: QuestionComment
comment on: http://stackoverflow.com/q/51871101
has text: Sounds like homework. What have you tried so far?
score: 0
type: Comment

http://stackoverflow.com/q/51941949
answer count: 4
score: 2
has answer: http://stackoverflow.com/a/51942129
downvote count: 0
has body: I have a task that was assigned to me for homework. Basically the problem is: Write a program that can get rid of the brand names and replace them with the generic names. The table below shows some brand names that have generic names. The mapping has also been provided to you in your program as the BRANDS dictionary. BRANDS = { 'Velcro': 'hook and loop fastener', 'Kleenex': 'tissues', 'Hoover': 'vacuum', 'Bandaid': 'sticking plaster', 'Thermos': 'vacuum flask', 'Dumpster': 'garbage bin', 'Rollerblade': 'inline skate', 'Asprin': 'acetylsalicylic acid' } This is my code: sentence = input('Sentence: ') sentencelist = sentence.split() for c in sentencelist: if c in BRANDS: d = c.replace(c, BRANDS[c]) print(d, end=' ') else: print(c, end=' ') My output: Sentence: I bought some Velcro shoes. I bought some hook and loop fastener shoes. Expected output: Sentence: I bought some Velcro shoes. I bought some hook and loop fastener shoes. It looks the same, but in my output there was an extra whitespace after 'shoes.' when there isn't supposed to be a whitespace. So how do I remove this whitespace? I know you could do rstrip() or replace() and I tried it, but it would just jumble everything together when I just need to remove the trailing whitespace and not remove any other whitespace. If the user put the brand name in the middle of the sentence, and I used rstrip(), it would join the brand name and the rest of the sentence together.
type: Question
type: AnsweredQuestion
tagged with: removing-whitespace
has title: Remove only trailing whitespace from output
has answer: http://stackoverflow.com/a/51942132
has answer: http://stackoverflow.com/a/51942239
has comment: http://stackoverflow.com/comment/90833599
tagged with: replace
upvote count: 2
has answer: http://stackoverflow.com/a/51942584
favorite count: 0
accepted answer: http://stackoverflow.com/a/51942584
has comment: http://stackoverflow.com/comment/90833560
has comment: http://stackoverflow.com/comment/90833770
tagged with: python
possible better answer: http://stackoverflow.com/a/51942132

http://stackoverflow.com/q/51865651
has comment: http://stackoverflow.com/comment/90683491
tagged with: python
possible better answer: http://stackoverflow.com/a/51866129
has comment: http://stackoverflow.com/comment/90683761
favorite count: 0
tagged with: text-based
has answer: http://stackoverflow.com/a/51866129
upvote count: 1
has body: I am learning Python by creating a text-based adventure game. I was having a difficult time figuring out if I could call a previous variable. For example, this is a snippet of my code (advice on how to consolidate would be helpful haha) I have an if statement that allows the player to select an input. Under the ALIEN input, you'll see if they select 1. They choose "Accept defeat". I have the same outcome towards the end of this code, for the player to choose "Accept defeat" again after the IMPROV input. I would like to loop back to the first alien variable if that option is chosen. Rather than writing the same if, elif, statements over again. Is this possible? def main(): #Groups together the entire script, allows for a loop. The enitire script is called main. import sys #imports system settings and functions from colorama import init #imports color scheme init() init(autoreset=True) #resets color scheme after every use #Text based adventure game in progress from colorama import Fore, Back, Style s_b = Style.BRIGHT # This allows you to shorthand a variable, rather than typing Style.BRIGHT everytime. f_c = Fore.CYAN f_g = Fore.GREEN f_y = Fore.YELLOW f_r = Fore.RED print ("") print ("") print (f_y + s_b + " WELCOME TO THE MAZE ") print ("") print ("") print (s_b + "You have found yourself stuck within a dark room, inside this room are 5 doors.. Your only way out..") print ("") print (s_b + "Do you want to enter door 1,2,3,4, or 5?") #This gives the player options to choose. print ("") door = input(f_y + s_b + "&gt; "); # input("&gt; ") means the player can give any variable # Will only work if the variable is defined down below if door == "1": print ("") print (s_b + "Theres an alien eating what appears to be a human arm, though its so damaged it's hard to be sure. There is a knife next to the alien.") print ("") print (s_b + "what do you want to do?") print ("") print (f_g + s_b + "1. Go for the knife") print ("") print (f_g + s_b + "2. Attack alien before it notice…
tagged with: loops
accepted answer: http://stackoverflow.com/a/51867517
downvote count: 1
has comment: http://stackoverflow.com/comment/90683517
has comment: http://stackoverflow.com/comment/90683572
type: AnsweredQuestion
tagged with: conditional-statements
tagged with: if-statement
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/90683739
has comment: http://stackoverflow.com/comment/90683742
has answer: http://stackoverflow.com/a/51867517
has title: Text-based adventure game looping to previous line?
score: 0

http://stackoverflow.com/comment/90853167
type: Comment
type: QuestionComment
has text: Why do you say that you won't know which item has which set of tags? You can pad them in exactly the same way, so to maintain the same position in the sequence
comment on: http://stackoverflow.com/q/51945455
score: 0

hotkeys
tags question: http://stackoverflow.com/q/51826724
type: Tag
tag name: hotkeys

http://stackoverflow.com/a/51934064
accepted answer of: http://stackoverflow.com/q/51933331
type: Answer
answers question: http://stackoverflow.com/q/51933331
upvote count: 3
score: 3
type: AcceptedAnswer
downvote count: 0
has body: Solution should be simplier, but because 29. February is necessary first remove this dates for same number of rows for each year and if necessary append them back: For repeat values is used numpy.tile. dates = pd.date_range('2018-04-01', '2019-03-31') df = pd.DataFrame({'col1': range(365), 'col2': range(0, 365 * 2, 2), 'col3': range(0, 365 * 3, 3)}, index=dates) #create range by add 6 years to last value of index rng=pd.date_range(df.index[0] + pd.offsets.DateOffset(years=1), df.index[-1] + pd.offsets.DateOffset(years=6)) print (rng) DatetimeIndex(['2019-04-01', '2019-04-02', '2019-04-03', '2019-04-04', '2019-04-05', '2019-04-06', '2019-04-07', '2019-04-08', '2019-04-09', '2019-04-10', ... '2025-03-22', '2025-03-23', '2025-03-24', '2025-03-25', '2025-03-26', '2025-03-27', '2025-03-28', '2025-03-29', '2025-03-30', '2025-03-31'], dtype='datetime64[ns]', length=2192, freq='D') #filtering 29.2. mask1 = df.index.strftime('%m-%d') != '02-29' mask2 = rng.strftime('%m-%d') == '02-29' rng1 = rng[mask2] rng2 = rng[~mask2] #create 29.2. DataFrame df2 = pd.DataFrame([[0] * len(df.columns)], columns=df.columns, index=rng1) print (df2) col1 col2 col3 2020-02-29 0 0 0 2024-02-29 0 0 0 df = pd.DataFrame(np.tile(df[mask1].values, (6, 1)), columns=df.columns, index=rng2).append(df2) print (df.head()) col1 col2 col3 2019-04-01 0 0 0 2019-04-02 1 2 3 2019-04-03 2 4 6 2019-04-04 3 6 9 2019-04-05 4 8 12 print (df.tail()) col1 col2 col3 2025-03-29 362 724 1086 2025-03-30 363 726 1089 2025-03-31 364 728 1092 2020-02-29 0 0 0 2024-02-29 0 0 0 #last sorting for correct align 29.2 dates df = df.sort_index() #print (df)

http://stackoverflow.com/comment/90796931
has text: @eyllanesc This is kind of a strange question, but still answerable, and understandable
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51923677

http://stackoverflow.com/comment/90818735
score: 0
comment on: http://stackoverflow.com/q/51934227
has text: Run with a fixed seed so I can reproduce. I'd like to see the exact data
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51949446
has comment: http://stackoverflow.com/comment/90853541
has comment: http://stackoverflow.com/comment/90853772
answer count: 0
type: UnansweredQuestion
tagged with: python
tagged with: relationships
has body: I have been trying to model a relationship between four tables, where entries from table A can be linked to entries in the other three tables. For example: Table A (components) id brand status N1 br3 free N2 br2 used N3 br2 used N4 br3 used N5 br2 used Table B (device1) id comp1 comp2 2 N2 N3 Table C (device2) id comp1 comp2 6 N4 N5 Table D (device3) id comp1 comp2 I can link the component from the device table like so: class Device1(db.Model): id = db.Column(db.Integer, primary_key=True) comp1 = db.Column(db.String(20), db.ForeignKey('components.id'), unique=True) comp2 = db.Column(db.String(20), db.ForeignKey('components.id'), unique=True) But how do I implement a relationship for all three tables from table A? I was looking for something like component.deviceinstalled which would return the device that the component is attached to, regardless of which table it belongs to (B, C or D), for instance: component1 -&gt; &lt;N2 br2 used&gt; component1.deviceinstalled -&gt; &lt;2 N2 N3&gt; from table B component2 -&gt; &lt;N4 br3 used&gt; component2.deviceinstalled -&gt; &lt;6 N4 N5&gt; from table C
tagged with: sqlalchemy
type: Question
score: 0
has comment: http://stackoverflow.com/comment/90854224
has comment: http://stackoverflow.com/comment/90853127
has title: SQLAlchemy one to one relationship across multiple tables

http://stackoverflow.com/q/51815172
tagged with: python
score: 1
has answer: http://stackoverflow.com/a/51815210
upvote count: 1
type: Question
tagged with: numpy
has title: create a week-day/weekend time series dataframe based on a daily time series dataframe
downvote count: 0
tagged with: pandas
answer count: 1
has body: I have created a dataframe with time series information, for instance Time daily-bill 2012-01-01 200 2012-01-02 300 2012-01-03 100 2012-01-04 500 …. I would like to create another time series dataframe based on the above time series. How to do it in Pandas? Time(weekday-and-weekend) total-bill Monday-Friday Weekend Monday-Friday Weekend Monday-Friday Weekend In other words, the time step will be a continuous sequence of weekday and weekend. The weekday consists of Monday to Friday; while the weekend consists of Saturday and Sunday. The total-bill column will store the sum of bills happened in the corresponding days, these information comes from the existing time series.
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion

http://stackoverflow.com/comment/90706765
type: Comment
type: QuestionComment
has text: @roganjosh I have no `try-except`in my cell , nope. I was wondering if restarting the kernel could solve the problem and most important, would save my variables'values
comment on: http://stackoverflow.com/q/51877700
score: 0

http://stackoverflow.com/comment/91027458
comment on: http://stackoverflow.com/q/51873988
score: 0
type: Comment
type: QuestionComment
has text: @benvc I came back to work today and tried, it worked perfectly. Thank you so much, now I'll start expanding to cover other tags in my data. You helped me a lot, thank you very much for your patience.

http://stackoverflow.com/q/51932439
score: 0
accepted answer: http://stackoverflow.com/a/51932722
has comment: http://stackoverflow.com/comment/90815086
type: Question
type: AnsweredQuestion
has title: Minimax solution not working
has comment: http://stackoverflow.com/comment/90815485
has comment: http://stackoverflow.com/comment/90815042
has body: So I've been looking at this problem for a very long time now. But I just can't figure it out. I have got a player class that looks like this: class perfectplayer(): def __init__(self, player, game): self.player = player self.game = game def possible_moves(self, board): '''Finds all possible moves of given board''' possible_moves = [] for x in range(len(board)): for y in range(len(board[x])): if board[x][y] is None: possible_moves.append((x, y)) return possible_moves def score(self, game, depth): '''Gives score to given board based on depth and who wins''' if game.win()[0]: if game.win()[1] is self.player: return 10 - depth else: return depth - 10 return 0 def minimax(self, game, depth): '''Constructs minimax tree and selects best move based on that tree''' if game.game_over(): return self.score(game, depth) depth += 1 scores = [] moves = [] # Recursively creates tree of possible decisions for move in self.possible_moves(game.board): possible_game = game possible_game.move(move) scores.append(self.minimax(possible_game, depth)) moves.append(move) # max the score if it is player's turn if game.current_player is self.player: max_score_idx = scores.index(max(scores)) self.choice = moves[max_score_idx] return scores[max_score_idx] # min the score if it is not player's turn else: min_score_idx = scores.index(min(scores)) self.choice = moves[min_score_idx] return scores[min_score_idx] def best_move(self, game): '''returns best move in give game state''' self.minimax(game, 0) return self.choice Which hooks into a game class that has all the required functions to work properly. It can return if a game is over, who won it and who's currently going to move. This all works as I have tested it. The idea is basically that the best_move function returns the next choice for the AI-player. But when I run my little game: game1 = game() player1 = perfectplayer("x", game1) while not game1.game_over(): # finds best choice choice = player1.best_move(game1) # puts down a mark game1.move(…
answer count: 1
has answer: http://stackoverflow.com/a/51932722
tagged with: python
has comment: http://stackoverflow.com/comment/90815709

http://stackoverflow.com/comment/90850515
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51950098
has text: You may find my code [here](http://stackoverflow.com/q/41777880/4014959) of interest. Also see my other code linked at the end of that answer.
type: Comment

http://stackoverflow.com/q/51920199
upvote count: 0
score: -3
has answer: http://stackoverflow.com/a/51920227
type: AnsweredQuestion
has body: I want to remove a specific amount of words from a string. For example, my string is s = "I am a good person JOKE JOKE JOKE" and I want to remove the last 3 words from my string. How to do that?
favorite count: 0
has title: How to remove specific amount of words from a string - Python
type: Question
has comment: http://stackoverflow.com/comment/90790245
tagged with: python
answer count: 1
accepted answer: http://stackoverflow.com/a/51920227
downvote count: 3

http://stackoverflow.com/q/51939023
has comment: http://stackoverflow.com/comment/90828338
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90828318
tagged with: exception
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90828242
tagged with: python
has comment: http://stackoverflow.com/comment/90828228
upvote count: 0
has body: I am running someone else's code: ./run_me.sh Traceback (most recent call last): File "train.py", line 13, in &lt;module&gt; import options File "/Users/test/Desktop/lang-emerge/options.py", line 44 except IOError, msg: parser.error(str(msg)); ^ SyntaxError: invalid syntax I tried modifying the except block, but again I get an error: ./run_me.sh Traceback (most recent call last): File "train.py", line 13, in &lt;module&gt; import options File "/Users/test/Desktop/lang-emerge/options.py", line 44 except: IOError, msg: parser.error(str(msg)); ^ SyntaxError: only single target (not tuple) can be annotated The code where error is: try: parsed = vars(parser.parse_args()); except: IOError, msg: parser.error(str(msg)); Don't know what to do to resolve the error? The msg is a keyword in python try/except blocks. With the modified code, IOError as msg: I get: ./run_me.sh Traceback (most recent call last): File "train.py", line 13, in &lt;module&gt; import options File "/Users/test/Desktop/lang-emerge/options.py", line 44 except: IOError as msg: parser.error(str(msg)); ^ SyntaxError: invalid syntax
type: Question
tagged with: try-catch
has title: Syntax Error in Python in Try, Except Block
score: -1
has comment: http://stackoverflow.com/comment/90828177
has answer: http://stackoverflow.com/a/51939136
downvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/90828231

http://stackoverflow.com/q/51860706
tagged with: decimal
score: 2
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/51865989
type: Question
has title: How can I normalize the columns when calling up a .describe function in python? I want an output of 2 decimal places
tagged with: python
upvote count: 2
has body: How can I normalize the columns when calling up a .describe function in python? I want an output of two decimal places.
answer count: 1
tagged with: describe
type: UnansweredQuestion

http://stackoverflow.com/q/51877700
has title: Jupyter notebook kernel does not want to interrupt
has comment: http://stackoverflow.com/comment/90706934
downvote count: 1
has answer: http://stackoverflow.com/a/51897922
has comment: http://stackoverflow.com/comment/90706785
upvote count: 5
has comment: http://stackoverflow.com/comment/90707256
has comment: http://stackoverflow.com/comment/90707212
has comment: http://stackoverflow.com/comment/90707057
linked to: http://stackoverflow.com/q/36489576
has comment: http://stackoverflow.com/comment/90706647
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51897922
favorite count: 0
tagged with: jupyter-notebook
has comment: http://stackoverflow.com/comment/90707386
has comment: http://stackoverflow.com/comment/90709460
has body: I was running a cell in a Jupyter Notebook for a while and decided to interrupt. However, it still continues to run and I don't know how to proceed to have the thing interrupted... Thanks for help
type: Question
tagged with: python
answer count: 1
has comment: http://stackoverflow.com/comment/90706765
score: 4

http://stackoverflow.com/q/51840390
favorite count: 0
tagged with: seaborn
upvote count: 1
tagged with: python
type: AnsweredQuestion
score: 1
tagged with: matplotlib
type: Question
downvote count: 0
has answer: http://stackoverflow.com/a/51840478
has body: ax=sns.relplot(data=price_quantity, x='Net price', y='Delivery quantity', hue='MG 5', height=10, aspect=.8) plt.xlabel('Unit Price') plt.ylabel('Delivery Quantity') plt.title('Net Price-Delivery Quantity\n(RMB,Unit)') plt.ylim(0, 500) plt.xlim(0, 1000) I was confused by this error! It was runnable last time and I cannot change the y range now. Once I removed the plt.ylim, then everything is fine. I have checked all details but cannot find a solution. I cannot change the y range for any figures now in python....However the xlimit works fine, very weired...
has title: Maybe a bug of matplotlib/seaborn axis range?
answer count: 1
accepted answer: http://stackoverflow.com/a/51840478

http://stackoverflow.com/comment/90757101
type: Comment
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/51902666
has text: Not a problem, you can use Daniel's solution which works well. As a sanity check you could add word boundaries as Wiktor suggests in his comment above.

http://stackoverflow.com/comment/90705148
has text: Yes, I realised, I need to update to Python 3.x soon.. But defaultdict is anyway very useful, thank you..
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51876933
type: AnswerComment

http://stackoverflow.com/q/51938080
type: AnsweredQuestion
has body: Say I have a PythonOperator task pushing message to XCom, how can I pull this messages in SparkSubmitOperator? def get_some_value(**kwargs): some_value = 10 return some_value task1 = PythonOperator(task_id='run_task_1', python_callable=get_some_value, provide_context=True, dag=dag) task2 = SparkSubmitOperator( task_id='run_sparkSubmit_job', conn_id='spark_default', java_class='com.example', application='example.jar', name='airflow-spark-job', verbose=True, application_args=["some_value"], #&lt;---I want to use some_value from task1 here conf={'master':'yarn'}, dag=dag, ) task1 &gt;&gt; task2
type: Question
tagged with: airflow
answer count: 1
score: 0
upvote count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/51939249
accepted answer: http://stackoverflow.com/a/51939249
favorite count: 0
tagged with: python
has title: How to pass XCom message from PythonOperator task to a SparkSubmitOperator task in Airflow

http://stackoverflow.com/comment/90675034
has text: Where does your code fail? What does your current output look like?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51860378
score: 1

http://stackoverflow.com/comment/90816576
comment on: http://stackoverflow.com/a/51933252
has text: This is more of a comment rather than an answer.
score: 1
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/90683447
has text: @Jlanger I added some fun example how you could still use setattr in this case, but again, not recommended :) Good luck with python!
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51865487

http://stackoverflow.com/q/51881692
has comment: http://stackoverflow.com/comment/90882317
has comment: http://stackoverflow.com/comment/90780669
has comment: http://stackoverflow.com/comment/90719841
has comment: http://stackoverflow.com/comment/90788876
has body: I have the following package structure as a minimal example (for convenience, all is uploaded here): . ├── sphinx │ ├── build │ ├── Makefile │ └── source │ ├── conf.py │ ├── index.rst │ └── train.rst └── train ├── __init__.py └── train.py When writing Python packages, one must specifiy the __all__ constant in the __init__.py of any package in order for Sphinx to be able to map a reference such as train.DatasetMeta to train.train.DatasetMeta or similar. However, sphinx-apidoc generates the following sections for these packages: train package ============= Submodules ---------- train.train module ------------------ .. automodule:: train.train :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: train :members: :undoc-members: :show-inheritance: Which duplicates the entire documentation as it contains .. automodule:: module.file as well as .. automodule:: module, which refer to the same thing. Removing either of these sections results in undefined reference warnings (turned into errors when using -n to SPHINXOPTS). sphinx_test/train/train.py:docstring of train.DatasetMeta:1:py:class reference target not found: train.train.DatasetMeta How can I solve this? train/train.py from collections import namedtuple class DatasetMeta(namedtuple('DatasetMeta', ['dataset', 'num_classes', 'shape'])): @property def size(self): '''int: Number of examples in the dataset''' return self.shape[0] train/__init__.py from .train import * __all__ = ['DatasetMeta'] sphinx/source/conf.py import os import sys sys.path.insert(0, os.path.abspath('.')) sys.path.insert(0, os.path.abspath('../../')) project = 'test' copyright = '' author = '' version = '' release = '0' extensions = [ 'sphinx.ext.autodoc', ] source_suffix = '.rst' master_doc = 'index' I just cannot figure out what the logic is here.
has comment: http://stackoverflow.com/comment/90780573
has comment: http://stackoverflow.com/comment/90878108
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/90775819
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90788772
has comment: http://stackoverflow.com/comment/90780587
tagged with: python-sphinx
type: UnansweredQuestion
tagged with: python
has title: How can I use Sphinx with subpackages without duplicating everything?
has comment: http://stackoverflow.com/comment/90772461
has comment: http://stackoverflow.com/comment/90717193
downvote count: 0
has comment: http://stackoverflow.com/comment/90784442
score: 16
has comment: http://stackoverflow.com/comment/90730514
has comment: http://stackoverflow.com/comment/90784356
type: Question
has comment: http://stackoverflow.com/comment/90788298
has comment: http://stackoverflow.com/comment/90716643
has comment: http://stackoverflow.com/comment/90780555
upvote count: 16
has answer: http://stackoverflow.com/a/52007480

http://stackoverflow.com/q/51894583
score: 0
has title: Java Process causing python script JSON error
has comment: http://stackoverflow.com/comment/90739827
has comment: http://stackoverflow.com/comment/90740122
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51894811
has comment: http://stackoverflow.com/comment/90739781
tagged with: java
tagged with: http://stackoverflow.com/tag/json
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/51895021
has comment: http://stackoverflow.com/comment/90740036
has body: I have a Java program that manages data. When it wants to create a report from said data it does so via saving a JSON file with the relevant data for the report and then setting off the python script via the use of a ProcessBuilder object. I'm however having a weird error should I try and extract data from the output of the python script. ProcessBuilder pythonProcess = new ProcessBuilder("python","ReportingTool.py"); pythonProcess.directory(new File("invoice_python_files\\")); Process pythonRunnable =pythonProcess.start(); /* BufferedReader outputReader = new BufferedReader(new InputStreamReader(pythonRunnable.getInputStream())); BufferedReader errorReader = new BufferedReader(new InputStreamReader(pythonRunnable.getErrorStream())); String line =null; System.out.println("&lt;ERROR&gt;"); while ( (line = errorReader.readLine()) != null) System.out.println(line); System.out.println("&lt;/ERROR&gt;"); System.out.println("&lt;Output"&gt;) while ( (line = outputReader.readLine()) != null) System.out.println(line); System.out.println("&lt;/OUTPUT&gt;"); */ This works fine and produces the report as expected (without the input stream code). If I then uncomment the code I get an error from the python script. File "C:\Users\o.cohen\AppData\Local\Programs\Python\Python36- 32\lib\json\decoder.py", line 357, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) I don't understand how the java process is causing the error and more importantly how to fix it. Below is the code that causes the error (specifically the last line: with open("InvoiceMakerDoc.json") as json_file: json_data=json_file.read() decoded_data =json.loads(json_data)

http://stackoverflow.com/q/51816669
tagged with: eof
has body: in c / c++ i use EOF like int n; while( scanf("%d",&amp;n) != EOF ){ printf("%d",n); } now how can i use EOF in Python ? please give me the same code using python
duplicate of: http://stackoverflow.com/q/46003639
type: Question
linked to: http://stackoverflow.com/q/15599639
upvote count: 1
score: -2
answer count: 1
favorite count: 0
duplicate of: http://stackoverflow.com/q/15599639
downvote count: 3
has answer: http://stackoverflow.com/a/51816703
tagged with: python
tagged with: python-3.x
has title: How can i use EOF in Python 3
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90588376
linked to: http://stackoverflow.com/q/46003639

http://stackoverflow.com/comment/90691201
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51869713
type: Comment
has text: Welcome to Stack Overflow. Please post a [minimal, complete and verifiable example](https://stackoverflow.com/help/mcve) to get help with your problem.

http://stackoverflow.com/comment/90799312
score: 0
has text: @hoefling ok I check it, but in the first dockerfile in your answer, there isn't a `pip` installation!
type: Comment
comment on: http://stackoverflow.com/a/51916006
type: AnswerComment

http://stackoverflow.com/a/51832922
type: Answer
score: 1
upvote count: 1
has body: Might be slightly cleaner to call by column name df.index.get_level_values('NAME').tolist()
downvote count: 0
answers question: http://stackoverflow.com/q/51832868

http://stackoverflow.com/comment/90868056
type: Comment
comment on: http://stackoverflow.com/a/51923906
has text: Install (https://www.digitalocean.com/community/tutorials/how-to-install-the-anaconda-python-distribution-on-ubuntu-16-04) anaconda, which is very easy and handy to use and you wont get this kind of problem again. once done run this commands ```conda create --name env_name python=3.5``` ```source activate env_name``` ```pip install gunicorn``` thats it, now you should be able to see gunicorn at ```Location: /home/<your_user>/anaconda3/envs/env_name/bin/gunicorn``` location.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/90614492
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51827714
has text: reread the docs for pyplot.plot. We don't normally print its output
score: 0

http://stackoverflow.com/comment/90872389
type: AnswerComment
has text: @user10050371, I updated my answer with the output image.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51954982

http://stackoverflow.com/comment/90602271
score: 1
type: Comment
has text: How do you expect your `while True:` loop to terminate?
type: QuestionComment
comment on: http://stackoverflow.com/q/51823927

http://stackoverflow.com/comment/90635961
score: 1
has text: Working on a lot of small files will indeed avoid the csv formatting issues. Also it makes parallelisation much easier. All you have to do is to replace the hardcoded file path with a parameter then launch N parallel process to process your files (this part can be written as another script).
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51840387

http://stackoverflow.com/a/51902861
has comment: http://stackoverflow.com/comment/113325059
upvote count: 3
has comment: http://stackoverflow.com/comment/90761642
has body: pyautogui.hotkey('altright','2')
answers question: http://stackoverflow.com/q/51902824
type: Answer
score: 3
downvote count: 0

http://stackoverflow.com/a/51865800
score: 0
accepted answer of: http://stackoverflow.com/q/51865072
type: AcceptedAnswer
has body: This is working now well: qcmz = session1.query(func.sum(KCom.c1)).filter(KCom.users_id != current_user.id and KCom.ofv_id == cmz_id).all() qcmz0 = np.array(qcmz) if qcmz0 == None: qcmz3 = 0 else: qcmz1 = qcmz0 + 0. # conversia din list in float cu numpy qcmz2 = float(qcmz1[0]) qcmz3 = float("{0:.2g}".format(qcmz2))
type: Answer
answers question: http://stackoverflow.com/q/51865072

http://stackoverflow.com/q/51846073
score: 0
answer count: 2
has body: I've never downloaded with pip before so I might be doing something dumb, but I've looked at tutorials. I'm installing with pip in cmd, using the path to python34/Scripts (which is where pip is). I'm getting the console output: C:/Python34/Scripts&gt;pip install pyinstaller Downloading/unpacking pyinstaller Cannot fetch index base URL https://pypi.python.org/simple/ Could not find any downloads that satisfy the requirement pyinstaller Cleaning up... No distributions at all found for pyinstaller Storing debug log for failure [...] I tried using pip3: C:\Python34\Scripts&gt;pip3 install pyinstaller Collecting pyinstaller Using cached PyInstaller-3.3.1.tar.gz Requirement already satisfied: setuptools in c:\python34\lib\site-packages (from pyinstaller) Collecting pefile&gt;=2017.8.1 (from pyinstaller) Using cached pefile-2017.11.5.tar.gz Collecting macholib&gt;=1.8 (from pyinstaller) Using cached macholib-1.9-py2.py3-none-any.whl Collecting future (from pyinstaller) Using cached future-0.16.0.tar.gz Collecting pypiwin32 (from pyinstaller) Using cached pypiwin32-223-py3-none-any.whl Collecting altgraph&gt;=0.15 (from macholib&gt;=1.8-&gt;pyinstaller) Using cached altgraph-0.15-py2.py3-none-any.whl Collecting pywin32&gt;=223 (from pypiwin32-&gt;pyinstaller) Could not find a version that satisfies the requirement pywin32&gt;=223 (from pypiwin32-&gt;pyinstaller) (from versions: ) No matching distribution found for pywin32&gt;=223 (from pypiwin32-&gt;pyinstaller) Could not find a version that satisfies the requirement pywin32>=223 Is this because python 3.4 is not supported, maybe? I'll try downloading 3.6 I tried downloading 3.6, for some reason it ended up at C:\Users\user\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Python 3.6 and I cannot find pip anywhere near. Can i just drag the pip from 3.4 to 3.6? Tried dragging it over, then running pip3 install pyinstaller from the directory C:\Users\user\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Python 3.6. G…
tagged with: pyinstaller
tagged with: python
has comment: http://stackoverflow.com/comment/90645805
has answer: http://stackoverflow.com/a/51846506
possible better answer: http://stackoverflow.com/a/51846232
tagged with: pip
has answer: http://stackoverflow.com/a/51846232
has comment: http://stackoverflow.com/comment/90645944
type: Question
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51846506
has title: Unble to download pyinstaller with pip for python 3.4, 3.6
has comment: http://stackoverflow.com/comment/90645785

http://stackoverflow.com/comment/90752989
score: 0
comment on: http://stackoverflow.com/a/51887725
has text: I modified ymd, this is because when I imported it was in this form(mdy)
type: AnswerComment
type: Comment

http://stackoverflow.com/q/51836421
has body: I currently have a big file server.py containing all my bottle functions for routing. My application could be divided into 3 applications: news, forum, and blog. I would know there is a good way to split my big file into 4 parts: news functions, forum functions, blog functions and common utilities (decorators, text formatting and others). My current approach is to split my functions into 5 files : server.py, blog.py, admin.py, news.py and utils.py. server.py just contains the bottle.run() and import all others views. Is it the good way? Is there any way to load/import functions automatically WITHOUT an import *.
type: Question
answer count: 1
has comment: http://stackoverflow.com/comment/90628595
favorite count: 0
upvote count: 3
has answer: http://stackoverflow.com/a/51849050
accepted answer: http://stackoverflow.com/a/51849050
tagged with: python
tagged with: bottle
downvote count: 0
has title: How to split Python views in bottle.py
type: AnsweredQuestion
score: 3

http://stackoverflow.com/comment/90709094
type: Comment
has text: Look at the `nunique` method instead of count.
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51878299

http://stackoverflow.com/a/51935763
accepted answer of: http://stackoverflow.com/q/51935715
type: Answer
answers question: http://stackoverflow.com/q/51935715
score: 0
type: AcceptedAnswer
has body: you need to commit after execute # Make sure data is committed to the database conn.commit() cur.close() conn.close()

http://stackoverflow.com/comment/90832587
comment on: http://stackoverflow.com/q/51941464
has text: What have you tried so far?
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90733797
has text: I see no `return` statements anywhere...
type: Comment
comment on: http://stackoverflow.com/q/51891406
type: QuestionComment
score: 3

http://stackoverflow.com/a/51815760
has comment: http://stackoverflow.com/comment/90586155
has comment: http://stackoverflow.com/comment/90586178
has comment: http://stackoverflow.com/comment/90614306
has comment: http://stackoverflow.com/comment/90585881
type: Answer
upvote count: 4
downvote count: 0
has body: By doing this: for category in categories: ... ... You are essentially turning the problem from multi-label to binary. If you want to proceed with this, then no need for the OneVsRestClassifier. You can use the MultinomialNB directly. Or else you can directly do this with OneVsRestClassifier: # Send all labels at once. NB_pipeline.fit(X_train,train[categories]) prediction = NB_pipeline.predict(X_test) print 'NB test accuracy is {} '.format(accuracy_score(test[categories],prediction)) print 'NB f1 measurement is {} '.format(f1_score(test[categories],prediction, average='micro')) It may throw some warnings about some labels present in all the training data, but thats because the sample data you posted is too small. @user2906838, you are correct about scores. When average='micro', the results produced will be equal. This is mentioned in documentation here: Note that for “micro”-averaging in a multiclass setting with all labels included will produce equal precision, recall and F, Its written about multi-class there, but I doubt that its the same for binary also. See this similar question in which the user has calculated all the scores manually: Multi-class Clasification (multiclassification): Micro-Average Accuracy, Precision, Recall and F Score All Equal
has comment: http://stackoverflow.com/comment/90586240
answers question: http://stackoverflow.com/q/51815299
score: 4

http://stackoverflow.com/a/51824565
score: 4
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51824521
answers question: http://stackoverflow.com/q/51824521
type: Answer
upvote count: 4
has body: Adding dayfirst df_scaled['Date'] = pd.to_datetime(df_scaled['Date'], dayfirst=True).dt.strftime('%Y-%m-%d') Out[510]: 283 2009-02-10 284 2009-02-11 285 2009-02-12 286 2009-02-13 287 2009-02-17 288 2009-02-18 Name: Date, dtype: datetime64[ns]
downvote count: 0

http://stackoverflow.com/comment/90651462
comment on: http://stackoverflow.com/q/51847520
type: Comment
type: QuestionComment
has text: Solution: Weekly Score [0-9]{2}.[0-9]{2}.[0-9]{4} Report.csv
score: 0

http://stackoverflow.com/comment/90896319
has text: I added my result of my dictionary to the question. I am getting this error is a debug log: NtOpenThread: {Access Denied} A process has requested access to an object, but has not been granted those access rights. (0xc0000022) [0821/154137.228:ERROR:exception_snapshot_win.cc(88)] thread ID 10752 not found in process Any ideas ??
type: Comment
comment on: http://stackoverflow.com/a/51937318
score: 0
type: AnswerComment

http://stackoverflow.com/a/51939645
has body: They are just for different keras versions, before Keras 2.0 the layers were called ConvolutionalND for N = 1, 2, 3, and since Keras 2.0 they are just called ConvND.
answers question: http://stackoverflow.com/q/51939468
type: Answer
score: 10
downvote count: 0
upvote count: 10
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51939468

http://stackoverflow.com/a/51833146
type: Answer
answers question: http://stackoverflow.com/q/51831538
has comment: http://stackoverflow.com/comment/90630737
has body: In Python3 all strings are unicode, so the problem you're having is likely due to your locale settings not being correct. The Python3 interpreter looks to use the locale environment variables and if it cannot find them it emulates basic ASCII From locale.py: except ImportError: # Locale emulation CHAR_MAX = 127 LC_ALL = 6 LC_COLLATE = 3 LC_CTYPE = 0 LC_MESSAGES = 5 LC_MONETARY = 4 LC_NUMERIC = 1 LC_TIME = 2 Error = ValueError Double check the locale on your shell from which you are executing. Here are a few work arounds you can try to see if they get you working before you go through the task of getting your env setup correctly. 1) Validate UTF-8 locale or language files are installed (see link above) 2) Try adding this to the top of your script #!/usr/bin/env LC_ALL=en_US.UTF-8 /usr/local/bin/python3 print('カタカナ') or #!/usr/bin/env LANG=en_US.UTF-8 /usr/local/bin/python3 print('カタカナ') Or export shell variables before executing the Python interpreter export LANG=en_US.UTF-8 export LC_ALL=en_US.UTF-8 python3 &gt;&gt;&gt; print('カタカナ') Sorry I cannot be more specific, as these settings are platform and OS specific. You can forcefully attempt to set the locale in Python directly using the locale module, but I don't recommend that, and it won't help if they are not installed. Hope that helps.
accepted answer of: http://stackoverflow.com/q/51831538
upvote count: 5
score: 5
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90630141
has comment: http://stackoverflow.com/comment/90649870
has comment: http://stackoverflow.com/comment/90630171

http://stackoverflow.com/a/51936488
answers question: http://stackoverflow.com/q/51936346
score: 3
has comment: http://stackoverflow.com/comment/90823977
upvote count: 3
has comment: http://stackoverflow.com/comment/90824635
has comment: http://stackoverflow.com/comment/90824636
downvote count: 0
has comment: http://stackoverflow.com/comment/90824382
has body: Using groupby transform max df['YES_or_NO']=df.salhike.eq(df.groupby('empid')['salhike'].transform('max')).astype(int) df Out[380]: empid age salhike month YES_or_NO 0 123 23 12 1 0 1 123 23 24 2 0 2 123 23 87 3 1 3 123 23 35 4 0 4 111 23 87 1 1 5 111 23 35 2 0 6 111 23 14 3 0 7 111 23 12 4 0 Update df['YES_or_NO']=0 df.loc[df.groupby('empid')['salhike'].idxmax(),'YES_or_NO']=1
has comment: http://stackoverflow.com/comment/90823233
has comment: http://stackoverflow.com/comment/90824665
type: Answer
has comment: http://stackoverflow.com/comment/90824343

http://stackoverflow.com/q/51807101
favorite count: 0
has title: Python while loop getting stuck during quicksort
has comment: http://stackoverflow.com/comment/90569604
has comment: http://stackoverflow.com/comment/90575137
tagged with: while-loop
type: Question
tagged with: python
tagged with: quicksort
upvote count: 2
has comment: http://stackoverflow.com/comment/90570078
answer count: 1
has body: I am trying to write a quicksort function in Python using a while loop and for some reason, my loop will cause sublime to shut down if I don't increase i during EACH iteration (which is not something I want to do as index 0 of the array may change during the loop). Any ideas about why this may be happening or what is wrong with my while loop? Thanks for the help! I bet I am just being dumb somewhere. from random import randint def quicksort(arr): print(arr) pivot = arr[randint(0, len(arr)-1)] i = 0 while i &lt; len(arr): print('value', arr[i]) print('pivot', pivot) if arr[i] &lt; pivot: arr.append(arr[i]) del arr[i] else: i += 1 print(arr) print(arr) arr1 = [3,86,5,75,2,58,6,4,9,7,87,2,1,6,9,90,65,5,1,890] quicksort(arr1)
has comment: http://stackoverflow.com/comment/90569592
has answer: http://stackoverflow.com/a/51807156
linked to: http://stackoverflow.com/q/42418398
accepted answer: http://stackoverflow.com/a/51807156
has comment: http://stackoverflow.com/comment/90569630
has comment: http://stackoverflow.com/comment/90569760
score: 2
has comment: http://stackoverflow.com/comment/90569598
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/comment/90628768
has text: What is your use case? What do you want to pass to second estimator in place of `X` and `y`? LR dont have `transform()` method to change the data. Explain in detail what you want to do?
comment on: http://stackoverflow.com/q/51837748
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/q/51799764
tagged with: memory-management
answer count: 0
type: UnansweredQuestion
has body: I want to process the data in an unsupervised.py notebook. However, every time I launch it, my computer almost freeze and it seems that the kernel dies. It seems to be generated because of a memory management error. In particular, it is when I execute the step 3 of the following function: &gt;&gt;&gt;train.shape (130318, 4) &gt;&gt;&gt;len(dict_emb) 179862 &gt;&gt;&gt;def process_data(train): print("step 1") train['sentences'] = train['context'].apply(lambda x: [item.raw for item in TextBlob(x).sentences]) print("step 2") train["target"] = train.apply(get_target, axis = 1) print("step 3") train['sent_emb'] = train['sentences'].apply( lambda x: [dict_emb[item][0] if item in dict_emb else np.zeros(4096) for item in x) &gt;&gt;&gt;train = process_data(train) Maybe it's a memory problem? Are there online solutions? For now I'm going to try Google Collaboratory ... Maybe transform that into a loop that will handle a problem per packet of lines? My attempt: for i in range(0,len(train.shape[0]-200,200)): print(i) train['sent_emb'] = train['sentences'].iloc[i,i+200].apply( lambda x: [dict_emb[item][0] if item in dict_emb else np.zeros(4096) for item in x]) But it gives me several errors : step 1 step 2 step 3 --------------------------------------------------------------------------- ValueError Traceback (most recent call last) &lt;ipython-input-26-d3e879a8c753&gt; in &lt;module&gt;() ----&gt; 1 train = process_data(train) &lt;ipython-input-25-7063894d5c9a&gt; in process_data(train) 10 #train['sent_emb'] = train['sentences'].apply(lambda x: [dict_emb[item][0] if item in\ 11 # dict_emb else np.zeros(4096) for item in x]) ---&gt; 12 train['quest_emb'] =[] 13 for i in range(0,len(train.shape[0]-200,200)): 14 print(i) ~/Documents/programming/mybot/mybotenv/lib/python3.5/site-packages/pandas/core/frame.py in __setitem__(self, key, value) 3117 else: 3118 # set column -&gt; 3119 self._set_item(key, value) 3120 3121 def _setitem_slice(self, key, value): ~/Documents/programming/mybo…
has title: How to process data without my kernel dying?
type: Question
tagged with: optimization
has comment: http://stackoverflow.com/comment/90593755
score: 0
has comment: http://stackoverflow.com/comment/90565312
tagged with: python
tagged with: jupyter-notebook

http://stackoverflow.com/a/51869895
downvote count: 0
has comment: http://stackoverflow.com/comment/90727855
has comment: http://stackoverflow.com/comment/90727672
has comment: http://stackoverflow.com/comment/90727891
has comment: http://stackoverflow.com/comment/90727506
type: Answer
has comment: http://stackoverflow.com/comment/90727564
has comment: http://stackoverflow.com/comment/90728081
has comment: http://stackoverflow.com/comment/90728156
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/51869782
has comment: http://stackoverflow.com/comment/90728034
has body: re.search needs a pattern and a text. You left one of them out. Python does not have a literal syntax for regular expressions, which means all regular expressions in Python need to be strings. You probably didn't mean .xlsx. You need to escape the extension dot. (You do not need to escape the dot in the date, since it is inside square brackets, a character class.) You need to account for space. A literal space works okay here; if it's possible it might be a tab or something \s would be preferable. I use raw string literal r'...' so I can write \d instead of \\d etc. All together now: match = re.search(r'^Weekly \d{2}[/.-]\d{2}[/.-]\d{4} Scores\.xslx$', file_to_test)
accepted answer of: http://stackoverflow.com/q/51869782
has comment: http://stackoverflow.com/comment/90727650
type: AcceptedAnswer

http://stackoverflow.com/q/51891538
has body: I am trying to create a surface plot of a mountain in python, of which I have some xyz data. The end result should look something like that. The file is formatted as follows: 616000.0 90500.0 3096.712 616000.0 90525.0 3123.415 616000.0 90550.0 3158.902 616000.0 90575.0 3182.109 616000.0 90600.0 3192.991 616025.0 90500.0 3082.684 616025.0 90525.0 3116.597 616025.0 90550.0 3149.812 616025.0 90575.0 3177.607 616025.0 90600.0 3191.986 and so on. The first column represents the x coordinate, the middle one the y coordinate, and z the altitude that belongs to the xy coordinate. I read in the data using pandas and then convert the columns to individual x, y, z NumPy 1D arrays. So far I managed to create a simple 3D scatter plot with a for loop iterating over each index of each 1D array, but that takes ages and makes the appearance of being quite inefficient. I've tried to work with scipy.interpolate.griddata and plt.plot_surface, but for z data I always get the error that data should be in a 2D array, but I cannot figure out why or how it should be 2D data. I assume that given I have xyz data, there should be a way to simply create a surface from it. Is there a simple way?
downvote count: 0
has answer: http://stackoverflow.com/a/51891796
has answer: http://stackoverflow.com/a/70722081
answer count: 3
has answer: http://stackoverflow.com/a/55066536
upvote count: 11
favorite count: 0
has title: Create a surface plot of xyz altitude data
tagged with: geography
type: UnansweredQuestion
tagged with: python
score: 11
tagged with: topography
tagged with: surface
type: Question

http://stackoverflow.com/comment/90566488
type: AnswerComment
comment on: http://stackoverflow.com/a/51805363
score: 0
type: Comment
has text: I want to store all of the values of mape by passing one day incrementally to pred.

http://stackoverflow.com/comment/90718560
has text: The code that creates the table is never executed? I don't see where you're calling it.
comment on: http://stackoverflow.com/q/51883383
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/q/51921470
tagged with: python
has title: Error Installing PyInstaller for Python 3.7 on Windows 10
has answer: http://stackoverflow.com/a/51921534
has comment: http://stackoverflow.com/comment/90792697
possible better answer: http://stackoverflow.com/a/54486865
has answer: http://stackoverflow.com/a/54486865
upvote count: 2
has answer: http://stackoverflow.com/a/64138263
accepted answer: http://stackoverflow.com/a/51921534
has body: I used the command pip install pyinstaller to installer PyInstaller for Python 3.7 on Windows 10, but the Command Prompt gave me the following errors: ModuleNotFoundError: No module named 'pywintypes' ... ModuleNotFoundError: No module named 'cffi' ... During handling of the above exception, another exception occurred: ... SyntaxError: invalid syntax ----------------------------------------` Command "python setup.py egg_info" failed with error code 1 in C:\Users\MUHAMM~1\AppData\Local\Temp\pip-install-6_q2lzs2\pyinstaller\ I installed the midule cffi, then tried to install pywintypes but it was not found. Any help? Thanks in advance.
answer count: 5
has answer: http://stackoverflow.com/a/63439638
has answer: http://stackoverflow.com/a/66521524
type: AnsweredQuestion
score: 2
downvote count: 0
tagged with: windows-10
has comment: http://stackoverflow.com/comment/90792751
favorite count: 0
type: Question
tagged with: pyinstaller

pyside2
tags question: http://stackoverflow.com/q/51947810
tags question: http://stackoverflow.com/q/51912816
tags question: http://stackoverflow.com/q/51948132
type: Tag
tag name: pyside2
tags question: http://stackoverflow.com/q/51878772
tags question: http://stackoverflow.com/q/51834981
tags question: http://stackoverflow.com/q/51903209
tags question: http://stackoverflow.com/q/51820108
tags question: http://stackoverflow.com/q/51954478

http://stackoverflow.com/comment/90705932
type: Comment
comment on: http://stackoverflow.com/q/51876954
score: 0
type: QuestionComment
has text: Would you mind asking that in your question?

http://stackoverflow.com/q/51850071
has answer: http://stackoverflow.com/a/51932590
accepted answer: http://stackoverflow.com/a/51932590
tagged with: python
has title: How do I move table to the middle of the webpage in Python + Dash + Plotly?
type: AnsweredQuestion
type: Question
has body: I want to move a table to the middle of the screen on a webpage. I have the following code: import dash import dash_core_components as dcc import dash_html_components as html import pandas as pd df = pd.read_csv( 'https://gist.githubusercontent.com/chriddyp/' 'c78bf172206ce24f77d6363a2d754b59/raw/' 'c353e8ef842413cae56ae3920b8fd78468aa4cb2/' 'usa-agricultural-exports-2011.csv') def generate_table(dataframe, max_rows=10): return ( # Header html.Table([html.Tr([html.Th(col) for col in dataframe.columns])] + # Body [html.Tr([ html.Td(dataframe.iloc[i][col]) for col in dataframe.columns ]) for i in range(min(len(dataframe), max_rows))] )) app = dash.Dash() app.layout = html.Div(children=[ html.Div([dcc.Input(id='my-id1', value='initial value', type='text')]), html.Div([dcc.Input(id='my-id2', value='initial value', type='text')]), html.Div([dcc.Input(id='my-id3', value='initial value', type='text')]), html.H4(children='US Agriculture Exports (2011)'), generate_table(df) ]) app.css.append_css({ 'external_url': 'https://codepen.io/chriddyp/pen/bWLwgP.css' }) if __name__ == '__main__': app.run_server(debug=True) Which makes a webpage that looks like this: But I want it to look like this: I've tried using 'margin-top' and 'margin-left' to move the table and the input boxes but they don't work how I want them to. They create a lot of white space which is not what I'm looking to do. I just want to move the table to the middle of the page and bring the input boxes down. I tried using 'columns' which I read was a good way to organise the page, but that didn't work either. Could it be that plotly table doesn't work well with Dash? Is there another solution to this issue? Thanks in advance.
tagged with: plotly-dash
answer count: 1
score: 0

http://stackoverflow.com/q/51845606
has comment: http://stackoverflow.com/comment/129920959
score: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/51861749
has title: Python Mann-Whitney confidence interval
upvote count: 1
tagged with: python
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/51861749
tagged with: statistics
has body: I have two datasets (Pandas Series) - ds1 and ds2 - for which I want to calculate 95% confidence interval for difference in mean (if normal) or median (for non-normal). For difference in mean, I calculate t test statistic and CI as such: import statsmodels.api as sm tstat, p_value, dof = sm.stats.ttest_ind(ds1, ds2) CI = sm.stats.CompareMeans.from_data(ds1, ds2).tconfint_diff() for median, I do: from scipy.stats import mannwhitneyu U_stat, p_value = mannwhitneyu(ds1, ds2, True, "two-sided") How do I to calculate CI for difference in median?
type: AnsweredQuestion

http://stackoverflow.com/comment/90604417
comment on: http://stackoverflow.com/q/51813805
has text: Your `resolve_products` method is returning a list of dictionaries, not a list of `Product`
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51851239
tagged with: python-3.x
has title: pandas.Series.str.replace() based on another series
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51851267
has answer: http://stackoverflow.com/a/51851350
has body: I am working with a dataset of used cars made available in a DataQuest guided project (https://www.dataquest.io/m/294/guided-project%3A-exploring-ebay-car-sales-data/). I have provided a sample of the data for this question. What I am trying to do is remove redundant information from the car name such as brand name. Brand is already contained in another column in the data, and the exercise is working with pandas for data cleaning, so I want to see if there is a clean way to replace such substrings with the library's functionality. I have tried passing a pandas Series as the pat argument in Series.str.replace(), but obviously it won't work. What's a clean way to perform a vectorized replacement on a pandas Series based on another Series? Ideally 'Peugeot_807_160_NAVTECH_ON_BOARD' would become '_807_160_NAVTECH_ON_BOARD' and so on. import pandas as pd autos_dict = { 'brand': ['peugeot', 'bmw', 'volkswagen', 'smart', 'chrysler'], 'name': [ 'Peugeot_807_160_NAVTECH_ON_BOARD', 'BMW_740i_4_4_Liter_HAMANN_UMBAU_Mega_Optik', 'Volkswagen_Golf_1.6_United', 'Smart_smart_fortwo_coupe_softouch/F1/Klima/Panorama', 'Chrysler_Grand_Voyager_2.8_CRD_Aut.Limited_Stow´n_Go_Sitze_7Sitze' ] } autos_df = pd.DataFrame.from_dict(autos_dict) autos_df['name'].str.replace(autos_df['brand'], '', case=False) The following error message is returned: Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/anaconda3/lib/python3.6/site-packages/pandas/core/strings.py", line 2429, in replace flags=flags, regex=regex) File "/anaconda3/lib/python3.6/site-packages/pandas/core/strings.py", line 656, in str_replace compiled = re.compile(pat, flags=flags) File "/anaconda3/lib/python3.6/re.py", line 233, in compile return _compile(pattern, flags) File "/anaconda3/lib/python3.6/re.py", line 289, in _compile p, loc = _cache[type(pattern), pattern, flags] File "/anaconda3/lib/python3.6/site-packages/pandas/core/generic.py", line 1489, in __hash__ ' hashed'.format(self.__class_…
type: Question
tagged with: replace
has answer: http://stackoverflow.com/a/51851271
score: 0
answer count: 3
tagged with: pandas

http://stackoverflow.com/comment/132993490
type: AnswerComment
score: 0
type: Comment
has text: Curious why `source ~/.bashrc` the bash config file inside zsh config? Are you using `.zshrc.local` as a common config for both shells? Seems very specific to your setup and could cause issues on other people's systems e.g if they have bash specific syntax in a `~/.bashrc` file on their system. The `virtualenv-init` part also relates to a plugin that others might not use.
comment on: http://stackoverflow.com/a/71646176

http://stackoverflow.com/comment/90656727
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51851234
has text: this worked great thank you. I did realize those that ideally I would like the replace to be case insensitive is there a way to include that?
type: Comment

http://stackoverflow.com/comment/90670997
has text: why not try to use cookies they tend to work
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51853060

http://stackoverflow.com/a/70907644
upvote count: 38
has comment: http://stackoverflow.com/comment/129953305
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/130845893
has comment: http://stackoverflow.com/comment/125383397
has comment: http://stackoverflow.com/comment/135930262
has comment: http://stackoverflow.com/comment/130636305
has comment: http://stackoverflow.com/comment/140102209
has comment: http://stackoverflow.com/comment/137412621
answers question: http://stackoverflow.com/q/51930339
type: Answer
has comment: http://stackoverflow.com/comment/130119459
has comment: http://stackoverflow.com/comment/130811222
accepted answer of: http://stackoverflow.com/q/51930339
has comment: http://stackoverflow.com/comment/132625554
has comment: http://stackoverflow.com/comment/127384259
has comment: http://stackoverflow.com/comment/130847605
has comment: http://stackoverflow.com/comment/135848508
has comment: http://stackoverflow.com/comment/134116315
has body: In addition to Campi's answer about the mypy's recommendation of typing mixins with Protocol: An alternative to typing the methods' selfs is just inheriting the protocol. from typing import Protocol class HasValueProtocol(Protocol): @property def value(self) -&gt; int: ... class MultiplicationMixin(HasValueProtocol): def multiply(self, m: int) -&gt; int: return self.value * m class AdditionMixin(HasValueProtocol): def add(self, b: int) -&gt; int: return self.value + b class MyClass(MultiplicationMixin, AdditionMixin): def __init__(self, value: int) -&gt; None: self.value = value Additionally, if you are TYPE_CHECKING a Protocol, and given that you cannot forward reference a parent class (i.e. passing the parent class as a string literal), a workaround would be: from typing import Protocol, TYPE_CHECKING if TYPE_CHECKING: class HasValueProtocol(Protocol): @property def value(self) -&gt; int: ... else: class HasValueProtocol: ... class MultiplicationMixin(HasValueProtocol): def multiply(self, m: int) -&gt; int: return self.value * m ...
has comment: http://stackoverflow.com/comment/134107721
has comment: http://stackoverflow.com/comment/137799006
downvote count: 1
has comment: http://stackoverflow.com/comment/137409870
has comment: http://stackoverflow.com/comment/130017935
has comment: http://stackoverflow.com/comment/134077829
has comment: http://stackoverflow.com/comment/134118236
score: 37
has comment: http://stackoverflow.com/comment/125424808
has comment: http://stackoverflow.com/comment/135848539
has comment: http://stackoverflow.com/comment/137791187

http://stackoverflow.com/q/51811316
possible better answer: http://stackoverflow.com/a/51811356
has title: How do I replace a substring with another string that contains that substring as a part of it using regex in python
has answer: http://stackoverflow.com/a/51811356
tagged with: pandas
type: AnsweredQuestion
has body: Suppose I have a string "03/25/93" which is in a pandas series. I want to find /93 first and then replace it with /1993. How do I go about it? The pandas series is 03/25/93 6/18/85 7/8/71 9/27/75 2/6/96 I want this to be 03/25/1993 6/18/1985 7/8/1971 9/27/1975 2/6/1996 df.str.replace(r'[/]\d{2}$', '/19??')
type: Question
answer count: 2
tagged with: python
tagged with: regex
has answer: http://stackoverflow.com/a/51811381
score: 0
accepted answer: http://stackoverflow.com/a/51811381

random
tags question: http://stackoverflow.com/q/51952449
tags question: http://stackoverflow.com/q/51918580
tags question: http://stackoverflow.com/q/51916745
tags question: http://stackoverflow.com/q/51936434
tags question: http://stackoverflow.com/q/51914697
tags question: http://stackoverflow.com/q/51842678
tags question: http://stackoverflow.com/q/51946345
tag name: random
type: Tag
tags question: http://stackoverflow.com/q/51813308
tags question: http://stackoverflow.com/q/51923941

http://stackoverflow.com/comment/90735506
has text: It is nice to show the error message, but it would be better to give the full stacktrace to know at what line the error was raised. And when it comes to encoding question, you should also say what is the exact Python version and the OS.
comment on: http://stackoverflow.com/q/51891420
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/51913210
type: AnsweredQuestion
has title: Python Script with timezone fails when back ported to python 2.7
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/51913324
accepted answer: http://stackoverflow.com/a/51913314
has comment: http://stackoverflow.com/comment/90776683
tagged with: timezone
linked to: http://stackoverflow.com/q/2331592
tagged with: python
has answer: http://stackoverflow.com/a/51913314
has body: I have a python script running on python 3.6.4 locally buy trying to run it on a system with python 2.7. File "report_scheduler.py", line 5, in &lt;module&gt; from datetime import datetime, timedelta, timezone, tzinfo ImportError: cannot import name timezone I cant seem to import timezone module. I can't seem to install the timezone module. is there an easy way to import that module or modify the scripts to not need it? my only two references to that module are below. from datetime import datetime, timedelta, timezone, tzinfo last_run=(row[4]).replace(tzinfo=timezone.utc) time_since_last_request = datetime.now(timezone.utc) - last_run
possible better answer: http://stackoverflow.com/a/51913324
type: Question

http://stackoverflow.com/q/51806906
type: Question
has comment: http://stackoverflow.com/comment/90569266
tagged with: python
linked to: http://stackoverflow.com/q/4710247
has answer: http://stackoverflow.com/a/51806957
answer count: 6
score: 0
accepted answer: http://stackoverflow.com/a/51806987
has title: Can't calculate two values replacing certain sign
has body: How can I add two values replacing / between them? I tried with item.replace("/","+") but it only places the + sign replacing / and does nothing else. For example If i try the logic on 2/1.5 and -3/-4.5, I get 2+1.5 and -3+-4.5. My intention here is to add the two values replacing / between them and divide it into 2 so that the result becomes 1.875 and -3.75 respectively if I try the logic on (2/1.5 and -3/-4.5). This is my try so far: for item in ['2/1.5','-3/-4.5']: print(item.replace("/","+")) What I'm having now: 2+1.5 -3+-4.5 Expected output (adding the two values replacing / with + and then divide result by two): 1.75 -3.75
has answer: http://stackoverflow.com/a/51807074
has comment: http://stackoverflow.com/comment/90569280
has answer: http://stackoverflow.com/a/51806975
has comment: http://stackoverflow.com/comment/90569288
tagged with: str-replace
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51806962
has answer: http://stackoverflow.com/a/51806962
tagged with: string
has comment: http://stackoverflow.com/comment/90569256
has answer: http://stackoverflow.com/a/51806987
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51807041

http://stackoverflow.com/comment/90759172
comment on: http://stackoverflow.com/q/51904126
score: 0
type: QuestionComment
has text: What arguments does `write_colum` expect? `data` in the loop (for a 2d array) will be a 1d array.
type: Comment

string
tags question: http://stackoverflow.com/q/51911383
tags question: http://stackoverflow.com/q/51820939
tags question: http://stackoverflow.com/q/51806906
tags question: http://stackoverflow.com/q/51912028
tags question: http://stackoverflow.com/q/51940291
tags question: http://stackoverflow.com/q/51893873
tags question: http://stackoverflow.com/q/51900253
tags question: http://stackoverflow.com/q/51923925
tags question: http://stackoverflow.com/q/51826657
tags question: http://stackoverflow.com/q/51934032
tags question: http://stackoverflow.com/q/51856802
tags question: http://stackoverflow.com/q/51828755
tags question: http://stackoverflow.com/q/51836554
tags question: http://stackoverflow.com/q/51843128
tags question: http://stackoverflow.com/q/51814121
tags question: http://stackoverflow.com/q/51830966
tags question: http://stackoverflow.com/q/51845385
tags question: http://stackoverflow.com/q/51860990
tags question: http://stackoverflow.com/q/51813129
tags question: http://stackoverflow.com/q/51836275
tags question: http://stackoverflow.com/q/51929970
tags question: http://stackoverflow.com/q/51946413
tags question: http://stackoverflow.com/q/51837231
tags question: http://stackoverflow.com/q/51828078
tags question: http://stackoverflow.com/q/51815463
tags question: http://stackoverflow.com/q/51864087
tags question: http://stackoverflow.com/q/51845080
tags question: http://stackoverflow.com/q/51941303
tags question: http://stackoverflow.com/q/51801527
tag name: string
tags question: http://stackoverflow.com/q/51816479
tags question: http://stackoverflow.com/q/51831829
tags question: http://stackoverflow.com/q/51952842
tags question: http://stackoverflow.com/q/51828592
tags question: http://stackoverflow.com/q/51800428
tags question: http://stackoverflow.com/q/51882609
tags question: http://stackoverflow.com/q/51886795
tags question: http://stackoverflow.com/q/51947326
tags question: http://stackoverflow.com/q/51857601
tags question: http://stackoverflow.com/q/51867868
tags question: http://stackoverflow.com/q/51856781
type: Tag
tags question: http://stackoverflow.com/q/51911933
tags question: http://stackoverflow.com/q/51816941
tags question: http://stackoverflow.com/q/51819606
tags question: http://stackoverflow.com/q/51849509
tags question: http://stackoverflow.com/q/51881324
tags question: http://stackoverflow.com/q/51955809
tags question: http://stackoverflow.com/q/51864326
tags question: http://stackoverflow.com/q/51876200
tags question: http://stackoverflow.com/q/51889248
tags question: http://stackoverflow.com/q/51937095
tags question: http://stackoverflow.com/q/51913147
tags question: http://stackoverflow.com/q/51879764
tags question: http://stackoverflow.com/q/51929474
tags question: http://stackoverflow.com/q/51908009
tags question: http://stackoverflow.com/q/51843474
tags question: http://stackoverflow.com/q/51812672
tags question: http://stackoverflow.com/q/51949681
tags question: http://stackoverflow.com/q/51881487
tags question: http://stackoverflow.com/q/51821841
tags question: http://stackoverflow.com/q/51818807
tags question: http://stackoverflow.com/q/51934474
tags question: http://stackoverflow.com/q/51859152
tags question: http://stackoverflow.com/q/51859857
tags question: http://stackoverflow.com/q/51867377
tags question: http://stackoverflow.com/q/51890292
tags question: http://stackoverflow.com/q/51923190
tags question: http://stackoverflow.com/q/51888381
tags question: http://stackoverflow.com/q/51898099
tags question: http://stackoverflow.com/q/51813600
tags question: http://stackoverflow.com/q/51885673
tags question: http://stackoverflow.com/q/51926237
tags question: http://stackoverflow.com/q/51915672
tags question: http://stackoverflow.com/q/51890834
tags question: http://stackoverflow.com/q/51940695

http://stackoverflow.com/a/51954798
has body: import requests import json import csv headers = {'Content-type': 'application/json'} data = json.dumps({"seriesid": ['LAUMT421090000000005'],"startyear":"2011", "endyear":"2014"}) p = requests.post('https://api.bls.gov/publicAPI/v2/timeseries/data/', data=data, headers=headers) json_data = json.loads(p.text) After the above lines of code, use the steps describe in the following stackoverflow link for the next steps: How can I convert JSON to CSV? Hope it helps!
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51954361

http://stackoverflow.com/comment/90740608
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51894772
type: Comment
has text: @ysearka - Thank you.

websocket
tags question: http://stackoverflow.com/q/51912845
tags question: http://stackoverflow.com/q/51830264
tags question: http://stackoverflow.com/q/51811167
tags question: http://stackoverflow.com/q/51860792
tags question: http://stackoverflow.com/q/51848766
type: Tag
tags question: http://stackoverflow.com/q/51884339
tags question: http://stackoverflow.com/q/51825315
tags question: http://stackoverflow.com/q/51899138
tag name: websocket
tags question: http://stackoverflow.com/q/51901499
tags question: http://stackoverflow.com/q/51848526

http://stackoverflow.com/a/51941524
score: 22
upvote count: 22
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51941149
has body: You can do this in a single query by using array_agg() and a join on the information_schema.tables and information_schema.columns tables. This would return something similar to your expected output: select t.table_name, array_agg(c.column_name::text) as columns from information_schema.tables t inner join information_schema.columns c on t.table_name = c.table_name where t.table_schema = 'public' and t.table_type= 'BASE TABLE' and c.table_schema = 'public' group by t.table_name; Here I'm taking all the tables first, then I join it with the columns tables, and finally use array_agg() to aggregate them all to an array, grouped by the table name. Hope it helps :) Feel free to ask if you have any doubts.
answers question: http://stackoverflow.com/q/51941149
type: Answer

http://stackoverflow.com/comment/129260814
type: Comment
comment on: http://stackoverflow.com/a/51916006
type: AnswerComment
has text: Looks like the package is gone now :( https://pkgs.alpinelinux.org/packages?name=py3-zm*&branch=edge `py3-zmq (no such package)`
score: 0

http://stackoverflow.com/comment/90671991
comment on: http://stackoverflow.com/q/51859331
score: 0
type: Comment
type: QuestionComment
has text: @favoretti: the default, but I also don't think it's related as we don't use any special functions here. Our configure options: --with-libraries=/usr/local/lib' '--with-includes=/usr/local/include' '--enable-thread-safety' '--disable-debug' '--enable-nls' '--without-pam' '--with-openssl' '--without-gssapi'

http://stackoverflow.com/comment/90622593
type: Comment
score: 1
type: QuestionComment
has text: If you added `6` and `A` then the answer is `6` and `A`. If you want a program for the general case, you need to specify correctly the general case.
comment on: http://stackoverflow.com/q/51834311

http://stackoverflow.com/comment/90764552
score: 0
type: Comment
has text: Hi Esthita, thank you for your suggestion but sadly it hasn't worked. There is still whitespace between the red and blue border.
type: AnswerComment
comment on: http://stackoverflow.com/a/51905069

http://stackoverflow.com/a/51873633
upvote count: 1
has comment: http://stackoverflow.com/comment/90698809
type: Answer
has body: You can use pd.DataFrame.reset_index() or pd.Series.reset_index() with drop=True argument: n = 5 df = pd.DataFrame({'idx0': [0] * n, 'idx1': range(n, 0, -1), 'idx2': range(0, n), 'idx3': ['a'] * n, 'value': [i/2 for i in range(n)]}, ).set_index(['idx0', 'idx1', 'idx2', 'idx3']) df Out: idx0 idx1 idx2 idx3 value 0 5 0 a 0.0 4 1 a 0.5 3 2 a 1.0 2 3 a 1.5 1 4 a 2.0 df.reset_index(level=(1, 3), drop=True) Out: idx0 idx2 value 0 0 0.0 1 0.5 2 1.0 3 1.5 4 2.0
downvote count: 0
answers question: http://stackoverflow.com/q/51872584
score: 1

http://stackoverflow.com/q/51823830
type: Question
has comment: http://stackoverflow.com/comment/90602145
has body: I'm trying to develop a Python script in order to extract easily XPath of elements in a XML or HTML file. For instance, Imagine we have the XML file below (test.xml) for which we would like to get the XPATH of "blue" : Element1 color /Colors/red Colors red 0xFF0000 blue 0x0000FF I tried to use LXML, but I'm bit lost : from lxml import etree doc = etree.parse('test.xml') tree = etree.ElementTree(doc.getroot()) How can I get the XPath of the element in tree with text="blue"? Thank you, Thomas
has answer: http://stackoverflow.com/a/65417647
linked to: http://stackoverflow.com/q/1577293
score: 0
answer count: 1
tagged with: lxml
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90602170
has title: Find the XPath of a string in Python with LXML

http://stackoverflow.com/comment/90844606
type: Comment
type: QuestionComment
has text: You should reinstall with the command pip install -v dlib so you can see the messages it prints about what it’s doing and why. It will say why it’s not using cuda.
score: 1
comment on: http://stackoverflow.com/q/51943050

http://stackoverflow.com/q/51801498
favorite count: 0
has title: Creating a Surface of Revolution
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51801634
score: 1
type: Question
tagged with: matplotlib
has body: I have a 3d plot of a disk, here is the code: ri = 100 ra = 300 h=20 # input xy coordinates xy = np.array([[ri,0],[ra,0],[ra,h],[ri,h],[ri,0]]) # radial component is x values of input r = xy[:,0] # angular component is one revolution of 30 steps phi = np.linspace(0, 2*np.pi, 50) # create grid R,Phi = np.meshgrid(r,phi) # transform to cartesian coordinates X = R*np.cos(Phi) Y = R*np.sin(Phi) # Z values are y values, repeated 30 times Z = np.tile(xy[:,1],len(Y)).reshape(Y.shape) fig = plt.figure() ax = fig.add_subplot(1, 1, 1, projection='3d') ax.set_zlim(0,200) ax.plot_surface(X, Y, Z, alpha=0.5, color='grey', rstride=1, cstride=1) I get this nice plot: Further I have this plot: The code is: import numpy as np import matplotlib.pyplot as plt import matplotlib as mpl arr = np.array([[100, 15], [114.28, 17], [128.57, 18], [142.85, 19], [157.13, 22], [171.13, 24], [185.69, 25], [199.97, 27], [214.25, 28], [228.53, 30], [242.81, 31], [257.09, 35], [271.37, 36], [288.65, 37], [300, 38]]) #interpolating between the single values of the arrays new_x = np.concatenate([np.linspace(arr[i,0],arr[i+1,0], num=50) for i in range(len(arr)-1)]) new_y = np.interp(new_x, arr[:,0], arr[:,1]) t=np.arange(700) p = plt.scatter(new_x,new_y,c=t, cmap="jet") #inserting colorbar cax, _ = mpl.colorbar.make_axes(plt.gca(), shrink=0.8) cbar = mpl.colorbar.ColorbarBase(cax, cmap='jet', label='testvalues', norm=mpl.colors.Normalize(15, 40)) plt.show() Now my question: Is there a way to plot this 2d graph into my 3d environment? Further is it possible to create a surface out of this line (points) by rotating them around the middlepoint ? I tried it the same way like I did it with my disk but I failed because I think I need a closed contour ? Here is a picture to understand better what I want:
tagged with: surface
tagged with: 3d
upvote count: 1
downvote count: 0
answer count: 1

http://stackoverflow.com/q/51895370
has answer: http://stackoverflow.com/a/51895447
type: Question
score: 5
linked to: http://stackoverflow.com/q/17610698
downvote count: 0
has body: We have a partially working code and 2 examples with different types of custom steps. The example 2 (Int) is working, while the example 1 is not, as it is rounding up instead of down. import math def step_size_to_precision(ss): return ss.find('1') - 1 def format_value(val, step_size_str): precision = step_size_to_precision(step_size_str) if precision &gt; 0: return "{:0.0{}f}".format(val, precision) return math.floor(int(val)) ########################### # # example 1 step_size = "0.00000100" quantity = 0.00725562 print(quantity) print(format_value(quantity, step_size)) # 0.00725562 # 0.007256 &lt;= Is rounding up instead of down. Should be 0.007255 ########################### # # example 2 # step_size = "1" # quantity = 3.00725562 # print(quantity) # print(format_value(quantity, step_size)) # returns 3 &lt;= This is correct ########################### How do we fix it?
answer count: 3
tagged with: python
favorite count: 0
possible better answer: http://stackoverflow.com/a/51895447
has answer: http://stackoverflow.com/a/51895558
accepted answer: http://stackoverflow.com/a/51895558
has title: Python Rounding Down to Custom Step
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/67452574
tagged with: rounding
upvote count: 5

http://stackoverflow.com/comment/90673787
has text: You are opening a new file (with the same name) for each `i` in `__main__` block.
comment on: http://stackoverflow.com/q/51860742
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51880360
answer count: 1
has answer: http://stackoverflow.com/a/51881578
has comment: http://stackoverflow.com/comment/90712226
downvote count: 4
has comment: http://stackoverflow.com/comment/90712280
type: AnsweredQuestion
upvote count: 0
tagged with: yaml
has comment: http://stackoverflow.com/comment/90720315
has body: I am very new to Python and have several YAML files that I need to convert into csv. These are notes, comments and emails that came from our CRM (Highrise). I ONLY need the Notes and Comments, not the emails. Here are a few examples. Test_Co_1.txt --- - ID: 273679215 Name: Test Company 1 Tags: - Sample tag 1 - Sample tag 2 - Sample tag 3 - Sample tag 4 - Contact: - - Addresses - - "123 W Elm Street, Anywhere, FL, 11111, United States" - - Phone_numbers - - 555-111-2222 - Background: sample text - Note 424169327: - Author: Diane S. - Written: "May 16, 2017 19:32" - About: Jeff Smith - Body: Called 5/16/17 - Receptionist indicated Jeff was unavailable. She said they are not interested in attending any webinars hung up. - Note 424598243: - Author: Jenny S. - Written: "May 18, 2017 15:45" - About: Test Company 1 - Body: |- email sent to TM: Pete Pete, Can you help us with this prospective customer to determine if he is interested? We made some outbound calls this week, inviting dealers to the prospective dealer Summer Series webinars, with the first one being this Friday. Can you see if Jeff is interested? We do not have an email for him. Do you have that? This is the note from earlier this week: Called 5/16/17 - Receptionist indicated Jeff was unavailable. She said they are not interested in attending any webinars hung up. Thanks for your help. photo Jenny - Comment 424601588: - Author: Jenny S. - Written: "May 18, 2017 15:56" - About: Test Company 1 - Body: |- email back from TM: Jenny, Yes. I will reach out to them. Thanks! Pete Another Example: Fake_Co_2 --- - ID: 306184746 Name: Fake Company 2 Tags: - Sample Tag 1 - Contact: - - Addresses - - "444 N Oak St, Faketon City, MI, 22222, United States" - - Phone_numbers - - 333-333-3333 - Note 473905168: - Author: Robin S. - Written: "February 20, 2018 22:19" - About: Fake Company 2 - Body: "1:1 with Steven 2/27/18" - Email 476444812: - Author: Aaron N. - Written: "March 06, 2018 16:30" - About: Jose Viago - Subject: Wel…
has title: Convert several YAML files to CSV
accepted answer: http://stackoverflow.com/a/51881578
score: -4
favorite count: 0
type: Question
tagged with: http://stackoverflow.com/tag/csv
linked to: http://stackoverflow.com/q/46679787
tagged with: python

http://stackoverflow.com/q/51927973
tagged with: access-token
score: 0
tagged with: oauth-2.0
has comment: http://stackoverflow.com/comment/91051201
has title: Post Requests Failed to capture the access token in Robot Framework
answer count: 1
has comment: http://stackoverflow.com/comment/90812857
has body: ** Settings *** Library RequestsLibrary Library Collections *** Variables *** ${SERVICE_ROOT} https://xxx.yyy.org/m1/oauth ${SERVICE_NAME} accesstoken ${client_key} 11111111111111111111111111111111111 ${client_secret} 2222222222222222222222222222222222222222 *** Test Cases *** Test 1 Create access token *** Keywords *** Create access token Create Session accessurl ${SERVICE_ROOT} verify=True &amp;{data_1} Create Dictionary grant_type=client_credentials key=${client_key} secret=${client_secret} ${header} Create Dictionary Content-Type=application/json ${resp} Post Request accessurl /token params=${data_1} headers=${header} Should be Equal ${resp.status_code} 200 In simple words, I am trying to replicate the POST METHOD from Postman to Robot Framework (Type oauth 2 ) Mandatory parameters are grant type, client id and secret. Expected Authorization: Bearer with access token Upon executing, I am getting 401 and params returns Empty I had tried all possible ways to generate the token by making changes in the code but all proved to be unsuccessful. Kindly help me to fix this and let me know what error I have made, I am very new to automation scripting.
has answer: http://stackoverflow.com/a/52050651
tagged with: robotframework
linked to: http://stackoverflow.com/q/50910964
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90814122
has comment: http://stackoverflow.com/comment/90830552
has comment: http://stackoverflow.com/comment/90838865
has comment: http://stackoverflow.com/comment/90844710
type: Question
has comment: http://stackoverflow.com/comment/90817157
tagged with: python
accepted answer: http://stackoverflow.com/a/52050651

http://stackoverflow.com/q/51876176
has comment: http://stackoverflow.com/comment/90711096
type: Question
has body: I am trying to execute a very long statement from python which has around 1.3 million characters using following code: import pyodbc conn_str = 'Driver={SQL Server}; SERVER=MYSERVER;DATABASE=MyDatabase;TrustedConnection=True' conn = pyodbc.connect(conn_str) cursor = conn.cursor() try: cursor.execute("A SQL statement with 1.3m characters") cursor.commit() except Exception as e: print(e) finally: conn.close() It's basically a long list of insert statements. I am watching the SQL Profiler as this is running against my SQL server and it executes every time a different number of INSERT statements. It inserts the data up to around 40k characters. Then it suddenly stops. I was thinking of a max number of characters that a sql statement can hold, but since it's executing a different number of statements that doesn't sound like the issue here? Any one any ideas what's happening here and how I could get around this? Thanks, Joe Edit: here is the query: SET XACT_ABORT ON; SET QUOTED_IDENTIFIER ON; IF (select max(id) from Table1) = 87648 BEGIN BEGIN TRY BEGIN TRANSACTION INSERT INTO Table1 VALUES (87649, 'G4KG72HF6','87649'); INSERT INTO Table1 VALUES (87650, 'G4KG72HF6','87650'); INSERT INTO Table1 VALUES (87651, 'GDGVFKVW6','87651'); INSERT INTO Table1 VALUES (87652, 'GYAPWLNU1','87652'); INSERT INTO Table1 VALUES (87653, 'GYAPWLNU1','87653'); INSERT INTO Table1 VALUES (87654, 'H884542A2','87654'); INSERT INTO Table1 VALUES (87655, 'HT2XM4U83','87655'); INSERT INTO Table1 VALUES (87656, 'GPD9P39C7','87656'); INSERT INTO Table1 VALUES (87657, 'J2ZBUN7Q7','87657'); INSERT INTO Table1 VALUES (87658, 'JBWS35M69','87658'); INSERT INTO Table1 VALUES (87659, 'JMU6ANZN7','87659'); INSERT INTO Table1 VALUES (87660, 'JWRLK6D48','87660'); INSERT INTO Table1 VALUES (87661, 'K6NZSPSL2','87661'); --- a lot more inserts happening here COMMIT END TRY BEGIN CATCH PRINT N'ERROR: ' + ERROR_MESSAGE() IF @@TRANCOUNT &gt; 0 BEGIN ROLLBACK PRINT N'Transaction rolled back' END END CATCH END ELSE PRI…
has comment: http://stackoverflow.com/comment/90708283
has title: pyodbc: can't execute very long sql statement
tagged with: sql-server
has comment: http://stackoverflow.com/comment/90709277
score: 0
answer count: 1
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90730310
tagged with: python
tagged with: pyodbc
has comment: http://stackoverflow.com/comment/90704763
has answer: http://stackoverflow.com/a/51950705
has comment: http://stackoverflow.com/comment/90703846

http://stackoverflow.com/q/51901735
answer count: 1
tagged with: certbot
tagged with: lets-encrypt
tagged with: python
accepted answer: http://stackoverflow.com/a/51902928
has comment: http://stackoverflow.com/comment/90757351
type: AnsweredQuestion
has title: Request specific challenge with ACME client library
has body: How to request specific challenge (TLSSNI01) from the server? Currently only DNS01, HTTP01, TLSALPN01 are returned and I don't see any place where it could be specified by reading https://acme-python.readthedocs.io/en/latest/index.html
has answer: http://stackoverflow.com/a/51902928
type: Question
tagged with: ssl
score: 0

http://stackoverflow.com/q/51860716
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90673704
possible better answer: http://stackoverflow.com/a/56981871
has comment: http://stackoverflow.com/comment/90674211
has answer: http://stackoverflow.com/a/56981871
has answer: http://stackoverflow.com/a/51860780
score: 25
has answer: http://stackoverflow.com/a/51860765
type: AnsweredQuestion
downvote count: 3
answer count: 6
has answer: http://stackoverflow.com/a/77755307
type: Question
has answer: http://stackoverflow.com/a/51860833
has comment: http://stackoverflow.com/comment/90673752
tagged with: arrays
has answer: http://stackoverflow.com/a/51861335
accepted answer: http://stackoverflow.com/a/51860833
favorite count: 0
upvote count: 28
has body: I have a array of this type: xyz = [['nameserver','panel'], ['nameserver','panel']] How can I save this to an abc.txt file in this format: nameserver panel nameserver panel I tried this using, on iterating over each row: np.savetxt("some_i.txt",xyz[i],delimiter=','); It's showing this error: TypeError: Mismatch between array dtype ('&lt;U11') and format specifier ('%.18e')
tagged with: python
has title: How save a array to text file in python?

http://stackoverflow.com/comment/90819398
comment on: http://stackoverflow.com/q/51934592
score: 0
type: Comment
type: QuestionComment
has text: What is your query? It’s clearly not the string `"QUERY"`. Presumably it’s something that `SELECT`s four values. And if that fourth value is something like `NOW()` then it’s entirely up to the database whether to run that once per row, once per result set, or once per entire query, but almost all databases will do one of the last two. In which case the code you’ve shown us, and Python in general, is completely irrelevant, and you should be asking a SQL question about your SQL query.

http://stackoverflow.com/q/51950122
tagged with: openexr
accepted answer: http://stackoverflow.com/a/51968209
tagged with: pyinstaller
tagged with: python
tagged with: exe
type: AnsweredQuestion
has body: I am using PyInstaller 3.3.1 and OpenEXR 1.3.0 in my project. I create single file executable with --onefile option. This works as intended: import sys if getattr(sys, 'frozen', False): print("hello world") "hello world" is simply output into console and program closes. This on the other hand makes exe crash (no errors are displayed): import sys import OpenEXR if getattr(sys, 'frozen', False): print("hello world") I tried debugging the program, to see if OpenEXR module is being properly included in exe. It is. What can be the other reason of the crash? Is there any way to make the exe tell me why it crashes?
type: Question
tagged with: crash
has answer: http://stackoverflow.com/a/51968209
has title: PyInstaller and OpenEXR - exe crashes
score: 0
answer count: 1

http://stackoverflow.com/comment/90728716
type: Comment
type: QuestionComment
has text: did you include the _settings.py_ changes required for celery? and also did you add `from .celery import app as celery_app` and `__all__ = ['celery_app']` in the _init.py_
score: 0
comment on: http://stackoverflow.com/q/51888821

http://stackoverflow.com/a/51810664
has comment: http://stackoverflow.com/comment/90576560
has body: Your issue would not be that you aren't passing a DataFrame to append(), but that .append() here is not in-place; try reassigning the return of append() to Cand as Cand = Cand.append(y), given that append returns your initial DataFrame + other (Cand + y, in this case). Side Note: You can return a DataFrame from .loc by using double square brackets. Example: y = x.loc[[x['Hits'].idxmax()]]
accepted answer of: http://stackoverflow.com/q/51810322
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/51810322

http://stackoverflow.com/comment/90618640
comment on: http://stackoverflow.com/a/51832320
type: AnswerComment
score: 0
type: Comment
has text: You're making the same mistake as the OP: confusing file names with directory names. Files and directories are fundamentally different things. [`os.listdir`](https://docs.python.org/3/library/os.html#os.listdir) operates on directories, not files.

http://stackoverflow.com/comment/90578586
has text: @CoreyGoldberg I've set `framed_replay: false` in the pywb config, making it run under the same DOM, I think. It worked fine when accessing the link directly and it scrolled down
comment on: http://stackoverflow.com/q/51807299
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51848724
accepted answer: http://stackoverflow.com/a/51848821
tagged with: python
type: AnsweredQuestion
tagged with: loops
type: Question
has title: How to create a loop and new data set from the function I created?
has answer: http://stackoverflow.com/a/51848821
tagged with: dataframe
score: 4
upvote count: 4
tagged with: pandas
has body: I have this real estate data: neighborhood type_property type_negotiation price Smallville house rent 2000 Oakville apartment for sale 100000 King Bay house for sale 250000 ... And I created a function that sorts through this large data set by the neighborhood you input and if it's a house for sale, and then returns the 10th and 90th percentile and quantity of these houses. I have it here below: def foo(string): a = df[(df.type_negotiation == 'forsale')&amp;(df.type_property == 'house')&amp;(df.neighborhood == string)] b = pd.DataFrame(a.price.quantile(0.1), a.price.quantile(0.9), len(a.index), columns=('tenthpercentile', 'ninetiethpercentile', 'Quantity')) return b print(foo('KingBay')) tenthpercentile ninetiethpercentile Quantity 0 250000.0 250000.0 1 I want to write a loop that does this for the list of neighborhoods that I have, and then compiles each return in a new dat a frame. Looking something like this: tenthpercentile ninetiethpercentile Quantity King Bay 250000.0 250000.0 1 Smallville 99000.0 120000.0 8 Oakville 45000.0 160000.0 6 Thank you in advance.
tagged with: function
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/90853296
type: Comment
comment on: http://stackoverflow.com/a/51948532
has text: look how I have put `location` in the query.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/113325059
type: Comment
score: 1
has text: This didn't work for me. Although manually I would press AltGr+2 to get "@", this code doesn't produce anything (Belgian keyboard layout).
type: AnswerComment
comment on: http://stackoverflow.com/a/51902861

http://stackoverflow.com/comment/90628959
comment on: http://stackoverflow.com/a/51836647
has text: @ThelMi - I see it, give me a sec.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/52081050
type: Answer
answers question: http://stackoverflow.com/q/51927838
has body: I had a similar problem and it appears that the correct API is NOT https://westus.tts.speech.microsoft.com/cognitiveservices/v1 but https://speech.platform.bing.com/synthesize
score: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51927838
upvote count: 2
has comment: http://stackoverflow.com/comment/91128003
has comment: http://stackoverflow.com/comment/91965449

http://stackoverflow.com/comment/90615315
has text: I adjusted the code again @MartinLiu... I am not sure if that is what you wanted. Can you please explain your question further? Thanks again =) I will have to look into using pandas.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51817266
type: Comment

http://stackoverflow.com/q/51951849
favorite count: 0
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 1
has body: i have a tensor of (BatchSize X 1) numbers, between 0 to 9, e.g: 3 4 2 . . . 2 From each number i need to create a new tensor, starting with the number and descending until number - 9. For example, for the number 3 i to create a tensor: 3 2 1 0 -1 -2 -3 -4 -5 -6 This can be done using a single: tf.range(3,3-9,1) I need to do it for the whole tensor, to create a new tensor (following the example above): 3 2 1 0 -1 -2 -3 -4 -5 -6 4 3 2 1 0 -1 -2 -3 -4 -5 2 1 0 -1 -2 -3 -4 -5 -6 -7 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 1 0 -1 -2 -3 -4 -5 -6 -7 One option is doing it in an iterative manner, but that requires me to hard-code the batch size into the loop, and i am trying to avoid that. Any ideas for a good elegant solution will be welcomed.
tagged with: tensorflow
type: Question
accepted answer: http://stackoverflow.com/a/51952025
has answer: http://stackoverflow.com/a/51952025
upvote count: 1
answer count: 1
has title: Elegant way for multiply tf.range()

http://stackoverflow.com/q/51817516
has answer: http://stackoverflow.com/a/52109657
has title: How to use scan filters with boto3 for dynamodb
tagged with: amazon-dynamodb
tagged with: python
accepted answer: http://stackoverflow.com/a/52109657
type: AnsweredQuestion
has body: I'm trying to test sample filters with dynamodb using boto3. My simple example -written almost identical to the documented one- fails. I'm using a Table 'User' that correctly works with .scan: In [24]: list(User.scan()) Out[24]: [users_info-dev&lt;giovanni&gt;, users_info-dev&lt;nicola&gt;, users_info-dev&lt;ping&gt;] When trying to filter on a key: User.scan(FilterExpression=Attr('user_id').eq('giovanni')) --------------------------------------------------------------------------- ValueError Traceback (most recent call last) ... ValueError: Attribute FilterExpression specified for filter does not exist. from boto3.dynamodb.conditions import Key, Attr What's the error and which is the correct way to execute this scan? Note: I have not really got the difference between scan and query. It seems 'query' should be used for filtering on primary key. Having a background on SQL db that sounds wierd to me...
type: Question
tagged with: boto3
score: 0
answer count: 1

http://stackoverflow.com/q/51817304
tagged with: python
has body: For a project I had to switch from C++ to python but I'm having some trouble fully understanding the __init__.py file. I found the following documentation on the __init__.py file: https://docs.python.org/3/tutorial/modules.html https://www.pythoncentral.io/how-to-create-a-python-package/ http://mikegrouchy.com/blog/2012/05/be-pythonic-__init__py.html To get more familiar with the way the __init__.py file works I did some tests in both python 2.7 and 3.6.5. I used the "PythonCentral" test pacakge (see link 2) for this: Now I understand the following about the __init__.py file: The __init__.py file executes when a module or subpackage module is imported. The __init__.py can be used to overload the package __all__ method. The __init__.py can be used to define the import order The __init__.py can be used to make classes available on package and subpackage level. Using the different modules and classes from the scope of my main file seems to go as explained in the documentation. However when trying to use a class that is defined in another subpackage module I run into troubles. In python 2.7 created the following __init__.py file in the subanimals subpackage: from Mammals import Mammals print "subpackage __init__.py executed" Following I created the following code inside the Bird.py module: class Birds: def __init__(self): ''' Constructor for this class. ''' # Create some member animals self.members = ['Sparrow', 'Robin', 'Duck'] def printMembers(self): print('Printing members of the Birds class') for member in self.members: print('\t%s ' % member) test = Mammals() test.printMembers When running the main following main script: from animals.subanimals import Birds test = Birds() test.printMembers() I keep getting the global name Mammals not defined. I can solve this in python 2.7 by adding from Mammals import Mammals to the top of the Birds.py. Does the __init__.py only import packages and classes on the scope level of the main script and therefore not inside the Birds.py…
type: AnsweredQuestion
score: 1
downvote count: 1
type: Question
tagged with: python-import
has comment: http://stackoverflow.com/comment/90589701
has comment: http://stackoverflow.com/comment/90589775
has comment: http://stackoverflow.com/comment/90589819
has title: What is the scope of imports defined in the package __init__.py file?
tagged with: python-2.7
has answer: http://stackoverflow.com/a/51819640
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/51819640
upvote count: 2
has comment: http://stackoverflow.com/comment/90588734
has comment: http://stackoverflow.com/comment/90589480

http://stackoverflow.com/q/51872838
has comment: http://stackoverflow.com/comment/90697729
has body: I'm struggling to assign a unique value to a column / index out of multiple allowed values (other columns). for example: So I would assign either vertex 4 or 2 to edge 0, vertex 1 or 2 to edge 1, etc. But, every edge should have an unique vertex assigned to them! So if I take edge0 = vertex4, edge1 = vertex1, edge2 = vertex3, ... then edge3 can only choose between vertex 1 or 4, which is already taken by one of the other edges. In this case edge0 = vertex2, edge1 = vertex1, edge2 = vertex3 and edge3 = vertex4, would work! In the end there will still be combinations that will leave an "edge" without a unique vertex, but then this edge should just get a NaN value or so. Thanks in advance for the help! Cheer, Glenn
has comment: http://stackoverflow.com/comment/90701025
has comment: http://stackoverflow.com/comment/90698087
tagged with: python
has title: Assign unique value out of multiple columns (allowed values)
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51875430
type: Question
has comment: http://stackoverflow.com/comment/90697489
has comment: http://stackoverflow.com/comment/90697211
has answer: http://stackoverflow.com/a/51875430
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/90697960
answer count: 1
has comment: http://stackoverflow.com/comment/90701136

http://stackoverflow.com/a/51860063
score: 0
answers question: http://stackoverflow.com/q/51845509
type: Answer
has comment: http://stackoverflow.com/comment/90714415
has comment: http://stackoverflow.com/comment/90672615
has body: The documentation has a page on this: custom ordering. That said, you should tell django-tables2 how to order the query, that's not something django-tables2 can do for you, as the implementation of your property is opaque to django-tables2. In your example, things would be easier if the name_id column were a models.ForeignKey, and not models.IntegerField(), but I assume you have a reason to do so. If you know how to sort the query, you can write an order_object_name method, like explained in the docs.
has comment: http://stackoverflow.com/comment/90714576

http://stackoverflow.com/comment/90758508
comment on: http://stackoverflow.com/q/51903617
type: Comment
has text: I go for verbose when it is intended and planned; but it is also good to know what the options are; knifes are inherently unsafe but they can still be super useful.
score: 0
type: QuestionComment

http://stackoverflow.com/comment/90725123
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51886802
has text: @jarmod yes that is the difference, however I still want to store everything that is -1 into one variable and everything with -2 in another, so I was not sure exactly how I would be able to store the variables correctly.

http://stackoverflow.com/comment/90809787
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51930001
has text: I am thankful for your help, Sir. The reason I do not use BeautifulSoup is because it does not come in standard library and might create dependency issues later when put in production and deployed on different environments. +1 for your help and solution :)

http://stackoverflow.com/comment/90725675
has text: Thanks, that solved it. Feel free to convert this to answer.
comment on: http://stackoverflow.com/q/51886699
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/q/51826053
type: Question
upvote count: 1
has title: Update JSON data from Python into Firebase
favorite count: 0
has body: I have data from my sensors that I control with my Raspberry Pi. I packed this data into a JSON file. With Python I want to write a program that updates this data hourly and uploads it to Firebase. My code looks like this so far: from firebase import firebase import requests import json from pprint import pprint with open (thejsondata) as data_file: data=json.load(data_file) pprint(data) firebase=firebase.FirebaseApplication("...") r2 = requests.put("https://testproject...",data=jsondata) print(r2) How do I manage to upload it to Firebase every hour?
has comment: http://stackoverflow.com/comment/90607041
tagged with: python
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/90606418
type: UnansweredQuestion
score: 1
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/90607113

http://stackoverflow.com/q/51929945
upvote count: 3
has answer: http://stackoverflow.com/a/51930246
type: Question
tagged with: dataframe
has body: I have a large csv file (6 GB) and I want to sample 20% of it. These 20% should be with same distribution as the large original file. For example, take Kaggles data: https://www.kaggle.com/c/avazu-ctr-prediction/data I thought about chunks but how can I get the distribution to be the same? Tried read_csv, fread but without luck. Please advise how can I do this? My laptop can't handle 6GB csv file.
tagged with: http://stackoverflow.com/tag/r
possible better answer: http://stackoverflow.com/a/52231386
answer count: 3
has title: Analyse huge csv file in R/Python and sampling X% according to the distribution of the file?
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/51930246
tagged with: python
has answer: http://stackoverflow.com/a/51945559
tagged with: py-datatable
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/52231386

swagger-ui
tag name: swagger-ui
type: Tag
tags question: http://stackoverflow.com/q/51937823
tags question: http://stackoverflow.com/q/51854492

http://stackoverflow.com/comment/90860892
comment on: http://stackoverflow.com/a/51954855
type: AnswerComment
score: 0
type: Comment
has text: @JoeIddon You're right about that. I had the "hasNextLine" idea in mind, which is equivalent to `file.tell() != eof`, but this code actually negates that. I've fixed it now.

http://stackoverflow.com/comment/90788145
has text: I have updated accordingly. Thanks
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51918856

http://stackoverflow.com/a/51862848
answers question: http://stackoverflow.com/q/51862705
upvote count: 4
has comment: http://stackoverflow.com/comment/90677977
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90678013
has comment: http://stackoverflow.com/comment/90677964
has body: It works just fine... as a Series operation, that is. dfg['Grades'] &gt; 'C+' excellent True excellent True excellent True good True good True good True ok False ok False ok False poor False poor False Name: Grades, dtype: bool When you perform logical comparisons on the Series, the elements are treated as Categorical values with ordering. When you iterate over them in a loop, you inadvertently treat them as strings, so logical comparisons are evaluated lexicographically. There's a difference between "compare the strings C+ and D-", and "compare the categories C+ and D-", which is effectively what's going on here.
type: Answer
accepted answer of: http://stackoverflow.com/q/51862705
score: 4

http://stackoverflow.com/comment/90875731
type: Comment
comment on: http://stackoverflow.com/a/51879896
type: AnswerComment
has text: you mean even some service/component/anything else that is not directly part of LUIS, correct?
score: 0

http://stackoverflow.com/a/51946251
score: 2
answers question: http://stackoverflow.com/q/51945917
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: One approach with broadcasting - In [67]: df Out[67]: 0 1 2 3 0 1.0 2.0 NaN NaN 1 3.0 4.0 5.0 6.0 2 2.0 6.0 NaN NaN In [68]: constant_set = [1, 2, 3, 4, 5, 6] In [69]: (df.values[:,:,None] == constant_set).any(1).astype(int) Out[69]: array([[1, 1, 0, 0, 0, 0], [0, 0, 1, 1, 1, 1], [0, 1, 0, 0, 0, 1]]) # Dataframe output In [73]: out = (df.values[:,:,None] == constant_set).any(1).astype(int) In [74]: pd.DataFrame(out, columns=constant_set) Out[74]: 1 2 3 4 5 6 0 1 1 0 0 0 0 1 0 0 1 1 1 1 2 0 1 0 0 0 1 One more with memory efficiency in mind - idx = np.searchsorted(constant_set, a) out = np.zeros((len(df),len(constant_set)),dtype=int) flattend_idx = idx + out.shape[1]*np.arange(len(idx))[:,None] out.flat[flattend_idx[idx&lt;len(constant_set)]] = 1
accepted answer of: http://stackoverflow.com/q/51945917
upvote count: 2

http://stackoverflow.com/a/70658031
has body: You could run a discord bot in a separate thread, and also set attributes to each other. Similarly, you could run django in a different thread if you want, too. import threading django_app = DjangoApp() # However this works, I'm not familiar with Django bot = discord.Bot() # commands.Bot() for the discontinued discord.py bot.django = django_app django_app.discord_bot = bot thread = threading.Thread(target=lambda: bot.run(BOT_TOKEN)) thread.start()```
downvote count: 0
answers question: http://stackoverflow.com/q/51808519
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/comment/90838539
score: 0
type: AnswerComment
has text: @ducminh how can I use `collections.defaultdict` in my case. I have integers as keys and lists as values in my dictionary. I want to find all the duplicated values and print the keys containing the duplicated values.
type: Comment
comment on: http://stackoverflow.com/a/51943957

http://stackoverflow.com/q/51842354
has answer: http://stackoverflow.com/a/51842424
tagged with: pandas
tagged with: python
upvote count: 1
type: Question
type: AnsweredQuestion
score: 1
tagged with: group-by
has body: I have the following data set and im trying to build a third variable by counting how many times a skill appear across the set, for example if they appear in group 1 three times we still count as one.I'm new to python and im not so sure where to start. Group Skill 1 Windows 1 Excel 2 Windows 2 Java 3 Windows 3 Python 4 Python 4 SAS What I am trying to achieve is, if a skill appear only in one group we call sector-specific, in more than one but less then 2 cross-sector and in more than 2 transversal. That may be times the same skill appear in the same group twice, however i still want to call only one time. Then the final result would be: Group Skill Type 1 Windows Transversal 1 Excel Sector-specific 2 Windows Transversal 2 Java Sector-Specific 3 Windows Transversal 3 Python Cros-Sector 4 Python Cros-Sector 4 SAS Sector-specific
accepted answer: http://stackoverflow.com/a/51842424
answer count: 1
downvote count: 0
has title: Python - Defining a variable based on appearing more than one time within groups
favorite count: 0

http://stackoverflow.com/a/51950522
answers question: http://stackoverflow.com/q/51950465
downvote count: 0
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/51950465
has body: You are close, there are 2 possible solutions - convert DatetimeIndex to dates by DatetimeIndex.date - then is necessary converting to Series or remove times by DatetimeIndex.floor - get DatetimeIndex again: s = pd.Series(df.index.date).value_counts() print (s) 2016-01-04 2 2016-02-04 2 2016-03-04 1 dtype: int64 print (s.index) Index([2016-01-04, 2016-02-04, 2016-03-04], dtype='object') print (type(s.index[0])) &lt;class 'datetime.date'&gt; s = df.index.floor('d').value_counts() print (s) 2016-01-04 2 2016-02-04 2 2016-03-04 1 dtype: int64 print (s.index) DatetimeIndex(['2016-02-04', '2016-01-04', '2016-03-04'], dtype='datetime64[ns]', freq=None) Last is possible create one column DataFrame with set index names use Series.to_frame and rename_axis: s = df.index.floor('d').value_counts().to_frame('Occurrences').rename_axis('Date_Time') print (s) Occurrences Date_Time 2016-02-04 2 2016-01-04 2 2016-03-04 1
score: 1
upvote count: 1

http://stackoverflow.com/comment/90796092
score: 0
comment on: http://stackoverflow.com/q/51887163
type: Comment
type: QuestionComment
has text: Using `%within%` and `interval()` from `lubridate` package, could also be another idea, but for huge (>GB) data sets it'd take more time.

http://stackoverflow.com/a/51825644
has body: You could try the following: import pandas as pd import numpy as np df = pd.DataFrame({'name': ['apples', 'orange', 'apples', 'banana', 'strawberry'], 'month': ['jan18', 'jan18', 'feb18', 'feb18','jan18'], 'sum': [56, 75, 32, 98, 12]}) print(df.pivot_table(index='name', columns='month', values='sum', aggfunc=np.sum, fill_value=0, margins=True)) This prints out: month feb18 jan18 All name apples 32 56 88 banana 98 0 98 orange 0 75 75 strawberry 0 12 12 All 130 143 273 If you want to save to CSV: pivoted.to_csv(path_or_buf='d:/work/pivoted.csv') This will produce a file with content: name,feb18,jan18,All apples,32,56,88 banana,98,0,98 orange,0,75,75 strawberry,0,12,12 All,130,143,273
score: 0
has comment: http://stackoverflow.com/comment/90605748
has comment: http://stackoverflow.com/comment/90606135
has comment: http://stackoverflow.com/comment/90607056
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51825275
has comment: http://stackoverflow.com/comment/90606042
has comment: http://stackoverflow.com/comment/90605719
answers question: http://stackoverflow.com/q/51825275
has comment: http://stackoverflow.com/comment/90606255
type: Answer
has comment: http://stackoverflow.com/comment/90607116
has comment: http://stackoverflow.com/comment/90606537

http://stackoverflow.com/q/51800698
has answer: http://stackoverflow.com/a/51801630
score: 3
tagged with: python
has body: What is the right way of closing connection to mysql? In the tutorial I was following, the author closed the connection with the first way, but that does not seem right. Because it will try to close after return. So which one of the following is the proper closing? First way, the way author does it: @app.route("/dashboard") @login_required def dashboard(): cur = mysql.connection.cursor() result = cur.execute("SELECT * FROM articles") articles = cur.fetchall() if result &gt; 0: return render_template("dashboard.html", articles = articles) else: msg = "No Articles Yet" return render_template("dashboard.html", msg = msg) cur.close() // wrong My suggestion, the way i think is correct: @app.route("/dashboard") @login_required def dashboard(): cur = mysql.connection.cursor() result = cur.execute("SELECT * FROM articles") articles = cur.fetchall() cur.close() // correct if result &gt; 0: return render_template("dashboard.html", articles = articles) else: msg = "No Articles Yet" return render_template("dashboard.html", msg = msg)
type: AnsweredQuestion
upvote count: 3
type: Question
accepted answer: http://stackoverflow.com/a/51801630
has comment: http://stackoverflow.com/comment/90557831
tagged with: mysql
has title: flask - When to close mysql connection?
downvote count: 0
answer count: 1
tagged with: flask
has comment: http://stackoverflow.com/comment/90557773
favorite count: 0

http://stackoverflow.com/comment/90581791
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51805184
has text: I don't think there is any problem with the Chrome driver. This is the latest version of it and the same script works with Facebook.

http://stackoverflow.com/q/51932832
has comment: http://stackoverflow.com/comment/90817298
tagged with: django-cms
answer count: 0
type: UnansweredQuestion
tagged with: django
upvote count: 1
type: Question
tagged with: anaconda
score: 1
has comment: http://stackoverflow.com/comment/90817350
tagged with: conda
has title: How to install django cms in Anaconda/Conda?
downvote count: 0
linked to: http://stackoverflow.com/q/48972603
favorite count: 0
has body: When I try to install Django cms in conda with conda install -c auto djangocms-installer I get the following error message: UnsatisfiableError: The following specifications were found to be in conflict: - anaconda==5.2.0=py36_3 - djangocms-installer How to install django cms in Anaconda/Conda?
tagged with: python

http://stackoverflow.com/comment/90702606
has text: @DanielF Hi, I have updated the question. Now it only needs to updated the value of pixel A. Can you help to solve this? Thank you.
score: 0
comment on: http://stackoverflow.com/q/51873797
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90809190
comment on: http://stackoverflow.com/q/51929390
type: QuestionComment
type: Comment
has text: Somehow I am not able to reproduce same output again, I am trying few combinations , once I get that will provide that input and output. @AndriyIvaneyko
score: 0

http://stackoverflow.com/comment/90573131
has text: @user7692855: *any* method can be a called method. Exceptions continue up the stack until caught, you as a programmer get to decide how far.
score: 0
comment on: http://stackoverflow.com/q/51808715
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51824521
accepted answer: http://stackoverflow.com/a/51824565
tagged with: python
duplicate of: http://stackoverflow.com/q/15929861
score: 2
tagged with: python-3.x
upvote count: 2
has title: Inconsistent conversion of date format in panda dataframe date column
has body: I have this panda dataframe df_scaled. Name Date Sales 283 AXP 10-02-2009 1.143791 284 AXP 11-02-2009 1.065359 285 AXP 12-02-2009 1.039869 286 AXP 13-02-2009 1.049020 287 AXP 17-02-2009 0.975817 288 AXP 18-02-2009 0.922222 I run the following code to convert the date format in the Date column from dd-mm-yyyy to yyyy-mm-dd. df_scaled['Date'] = pd.to_datetime(df_scaled['Date']).dt.strftime('%Y-%m-%d') The result looks like this; Name Date Sales 283 AXP 2009-10-02 1.143791 284 AXP 2009-11-02 1.065359 285 AXP 2009-12-02 1.039869 286 AXP 2009-02-13 1.049020 287 AXP 2009-02-17 0.975817 288 AXP 2009-02-18 0.922222 In the first 3 rows, the converted date format is yyyy-dd-mm. In the last 3 rows, the converted date format is yyyy-mm-dd. What is wrong with the code to produce this inconsistency in the conversion? I am using python v3.6
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90603456
tagged with: date
has answer: http://stackoverflow.com/a/51824565
has comment: http://stackoverflow.com/comment/90603238
type: Question
has comment: http://stackoverflow.com/comment/90608519
answer count: 1
downvote count: 0
favorite count: 0
linked to: http://stackoverflow.com/q/37538080
linked to: http://stackoverflow.com/q/15929861
tagged with: pandas

http://stackoverflow.com/comment/90674244
score: 0
type: QuestionComment
has text: Could you post the ___init___
type: Comment
comment on: http://stackoverflow.com/q/51860945

http://stackoverflow.com/comment/90813843
type: AnswerComment
comment on: http://stackoverflow.com/a/51931732
type: Comment
has text: Ah no thats a intern python type called long string which starts and ends with 3 " It is also used to comment on functions and classes. But since it does not use " and ' for anything I always use this data type to save command line arguments.
score: 1

http://stackoverflow.com/q/51804599
favorite count: 0
has answer: http://stackoverflow.com/a/51805290
tagged with: python
has body: I want to find the x value for a given y (I want to know at what t, X, the conversion, reaches 0.9). There are questions like this all over SO and they say use np.interp but I did that in two ways and both were wrong. The code is: import numpy as np import matplotlib.pyplot as plt from scipy.integrate import odeint # Create time domain t = np.linspace(0,4000,100) # Parameters A = 1.5*10**(-3) # Arrhenius constant T = 300 # Temperature [K] R = 8.31 # Ideal gas constant [J/molK] E_a= 1000 # Activation energy [J/mol] V = 5 # Reactor volume [m3] # Initial condition C_A0 = 0.1 # Initial concentration [mol/m3] def dNdt(C_A,t): r_A = (-k*C_A)/V dNdt = r_A*V return dNdt k=A*np.exp(-E_a/(R*T)) C_A = odeint(dNdt,C_A0,t) N_A0 = C_A0*V N_A = C_A*V X = (N_A0 - N_A)/N_A0 # Plot plt.figure() plt.plot(t,X,'b-',label='Conversion') plt.plot(t,C_A,'r--',label='Concentration') plt.legend(loc='best') plt.grid(True) plt.xlabel('Time [s]') plt.ylabel('Conversion') Looking at the graph, at roughly t=2300, the conversion is 0.9. Method 1: I wrote this function so I can ask for any given point and get the x-value: def find(x_val,f): f = np.reshape(f,len(f)) global t t = np.reshape(t,len(t)) return np.interp(x_val,t,f) print('Conversion of 0.9 is reached at: ',int(find(0.9,X)),'s') When I call the function at 0.9 I get 0.0008858 which gets rounded to 0 which is wrong. I thought maybe something is going wrong when I declare global t?? Method 2: When I do it outside the function; so I manually reshape X and t and use np.interp(0.9,t,X), the output is 0.9. X = np.reshape(X,len(X)) t = np.reshape(t,len(t)) print(np.interp(0.9,t,X)) I thought I made a mistake in the order of the variables so I did np.interp(0.9,X,t), and again it surprised me with 0.9. I'm unsure as to where I'm going wrong. Any help would be appreciated. Many thanks :)
type: AnsweredQuestion
upvote count: 3
downvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/51805290
tagged with: numpy
score: 2
tagged with: arrays
answer count: 1
has title: Using np.interp to find x value for a given y gives wrong answer

http://stackoverflow.com/comment/90637596
type: QuestionComment
comment on: http://stackoverflow.com/q/51841092
has text: @Mornor I see my explanation was very ambigous, fixed now. Sorry.
score: 0
type: Comment

http://stackoverflow.com/q/51812972
upvote count: 1
has comment: http://stackoverflow.com/comment/90580941
has title: Extracting quantitative Information out of Strings
has comment: http://stackoverflow.com/comment/90580824
downvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/51813483
has comment: http://stackoverflow.com/comment/90580937
tagged with: feature-extraction
has body: I am analyzing the Open Food Facts dataset. The dataset is very messy and has a column called 'quantity' with entries like the following: '100 g ', '5 oz (142 g)', '12 oz', '200 g ', '12 oz (340 g)', '10 f oz (296ml) ', '750 ml', '1 l', '250 ml', '8 OZ', '10.5 oz (750 g)', '1 gallon (3.78 L) ', '27 OZ (1 LB 11 OZ) 765g ', '75 cl', As you can see the values and units of measurement are all over the place! Sometimes the quantity is given in two different measurements... My goal is to create a new column 'quantity_in_g' in my pandas data frame where I extract the information out of the string and create an integer Value based on the number of grams from the 'quantity' column. So if the quantity column has '200 g' I want the integer 200 and if it says '1 kg' I want the integer 1000. I would also like to convert the other units of measurements to grams. For '2 oz' I want the integer 56 and for 1 L I would like to get 1000. Could someone help me to convert this column? I would really appreciate it! Thanks in advance
has comment: http://stackoverflow.com/comment/90580861
score: 0
answer count: 1
favorite count: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/51813483
tagged with: python
tagged with: regex
tagged with: text-extraction
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/51811914

http://stackoverflow.com/q/51899774
has title: Compiling many txt/csv files into a single dataframe with filename added as a column
favorite count: 0
has answer: http://stackoverflow.com/a/51899860
has body: I'm struggling to compile many files and simultaneously add the filename as a column in the resulting dataframe. The following script works but somehow only performs the operation on a single file... why isn't this pulling all the files together? import glob import pandas as pd import os # format Working but only reads 1 file indir = "C:\\location\test" outfile = "C:\\location\test\output.csv" # Change the directory to where the files are located os.chdir(indir) # Make an empty list filelist = [] # Populate list with filenames. structure criteria with wild cards for files in glob.glob('*.txt'): filelist.append(files) print(filelist) # so far so good, all files are in the list # apply a for loop to the files listed above by glob for files in filelist: # built up dataframes and append the filepath as a column frame = [pd.read_csv(files, skiprows=21, header=None, delim_whitespace=True).assign(Filename=os.path.basename(files))] df = pd.concat(frame, ignore_index=True) df.columns = ['Wavelength', 'Value', 'Filename'] df.to_csv(outfile, index=None) print(df) I know there are a few threads already dealing with a similar matter but those threads got me to this particular brick wall somehow. Incidentally the shape of the source files is 2256 rows by two columns (Wavelength, and Value) and I'm adding the Filename column with assign(Filename=os.path.basename()) at the moment.
tagged with: python
type: AnsweredQuestion
tagged with: list
downvote count: 0
score: 1
type: Question
answer count: 1
accepted answer: http://stackoverflow.com/a/51899860
tagged with: glob
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
upvote count: 1

http://stackoverflow.com/q/51843321
score: 0
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51845772
has title: Different outcome with the same regular expression in Python
has body: I just learning Python and the regular "language". But I just encountered this problem which I can't answer. Some help or recommendations would be helpful. import re m = " text1 \abs{foo} text2 text3 \L{E.F} text4 " def separate_mycmd(cmd,m): math_cmd = re.compile(cmd) math = math_cmd.findall(m) text = math_cmd.split(m) return(math,text) (math,text) = separate_mycmd(r'\abs',m) print math # ['\x07bs'] print text # [' text1 ', '{foo} text2 text3 \\L{E.F} text4 '] (math,text) = separate_mycmd(r'\L',m) print math # **Question:** Just ['L'] and not ['\\L'] or ['\L] print text # [' text1 \x07bs{foo} text2 text3 \\', '{E.F} text4 '] # **Question:** why the \\ after text3 ? I don't understand the output from the last call. My related questions are in the comments. Thanks in advance, Ulrich
tagged with: python
tagged with: regex
upvote count: 2
type: UnansweredQuestion
downvote count: 2
type: Question
has comment: http://stackoverflow.com/comment/90640000
has comment: http://stackoverflow.com/comment/90644895
has comment: http://stackoverflow.com/comment/90639697
has comment: http://stackoverflow.com/comment/90639817

http://stackoverflow.com/comment/90759498
type: Comment
type: QuestionComment
score: 1
has text: `lsvirtualenv` comes with `virtualenvwrapper` which is a utility for managing multiple virtualenvs. It does not list virtualenvs not managed through this wrapper (which centralizes the where the venvs are created). While there is no equivalent to `virtualenvwrapper` (e.g. `Pipenvwrapper`) `Pipenv` does respect `WORKON_HOME` so should also provision `venv`s in the same directory so `lsvirtualenv` would also list those `venv`s.
comment on: http://stackoverflow.com/q/51904300

http://stackoverflow.com/q/51888503
score: -2
favorite count: 0
has title: Verify if a user is using English or latin characters and issue a warning if not
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90728264
has comment: http://stackoverflow.com/comment/90728114
downvote count: 2
has comment: http://stackoverflow.com/comment/90728219
tagged with: django
tagged with: python
answer count: 1
has comment: http://stackoverflow.com/comment/90728313
has answer: http://stackoverflow.com/a/51888682
upvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90728150
type: Question
has body: I'm having a Django site, which is in English. I know there are many other languages that use Latin besides English, but I have some 'pattern matching' issues in urls slugs with Cyrillic, Asian, Arab characters, and I want to avoid them. I'm thinking to do a more generic clean, loop thru all the fields at once, instead of using clean_field for all fields in all forms. Or maybe do it at the Model level.

http://stackoverflow.com/q/51839019
score: 2
has comment: http://stackoverflow.com/comment/90634767
upvote count: 2
tagged with: python
has answer: http://stackoverflow.com/a/51840438
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/44747343
has comment: http://stackoverflow.com/comment/90633465
has comment: http://stackoverflow.com/comment/90631051
accepted answer: http://stackoverflow.com/a/51840438
tagged with: tensorflow
type: Question
has body: I know that currently there are some good posts discussing this topic (this one is excellent and very detailed) but after 2 hours struggling with it I still have some issues: Just for having some context: I'm obtaining the spectrogram of some wav files (16 kHz, 3 seconds divided in 20ms) and triying to feed them into a neural network in order to find if they contain a concrete word (considering 0 to 1 the certainty range). def obtain_sample(wav): sample_rate, samples = wavfile.read(wav) frequencies, times, spectrogram = signal.spectrogram(samples, sample_rate, nperseg=320, noverlap=16) dBS = 10 * np.log10(spectrogram) # convert to dB return dBS def create_model(): print("Creating Model...") model= Sequential() model.add(Dense(10,input_shape=(161,157))) model.add(Activation('sigmoid')) model.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['accuracy']) com1=obtain_sample("comando.wav") com2=obtain_sample("comando2.wav") nocom=obtain_sample("nocomando.wav") inputs=np.array([com1,com2,nocom]) results=np.array([[1.],[1.],[0.]]) model.fit(inputs,results,epochs=10,) #model.fit(com1,[1.],epochs=10) #model.fit(com2,[1.],epochs=10) #model.fit(nocom,[0.],epochs=10) model.save("modelo_comando") print("Model saved") I'm actually getting the following error: ValueError('Error when checking target: expected activation_1 to have 3 dimensions, but got array with shape (3, 1)',) and after almost an hour trying to explain better the problem while inspecting the local var values, I think I'd rather ask if I'm actually giving a correct input shape and how could I use a Flatten/Reshape layer in order to obtain a single value output per sample? Sorry for not being able to be more concrete
answer count: 1
tagged with: neural-network
downvote count: 0
has title: Input shaping in Keras and model training
tagged with: keras
has comment: http://stackoverflow.com/comment/90631426
favorite count: 0

django-1.11
tags question: http://stackoverflow.com/q/51951919
tags question: http://stackoverflow.com/q/51848082
tag name: django-1.11
tags question: http://stackoverflow.com/q/51898417
type: Tag

http://stackoverflow.com/comment/90737298
score: 0
type: Comment
has text: I tried to overwrite and use my own templatetag, but the problem lies somewhere else. either I am missing some middleware or some middleware is not doing its job
comment on: http://stackoverflow.com/a/51893137
type: AnswerComment

http://stackoverflow.com/q/51840520
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90635403
has comment: http://stackoverflow.com/comment/90635073
has title: How to pop an item of a list as a float
has body: I hope this is more clear: numbers = [2, 3, 2] total = 0 while numbers: total += numbers.pop() this will return the total valeu of numbers. Now I must the total valeu of purchase__amount (first code) in this way (second code): purchase_amount=[] item=[] while item != 'done': item=input("Enter the price, or type 'done' to finnesh ", ) if item != 'done': if item.isdigit(): purchase_amount.append(item) else: print('please type only numbers') print(purchase_amount) numbers = [purchase_amount] total = 0 while numbers: total += numbers.pop() print(numbers) With each atempt though I cant get the numbers from the input in the first code to become a float here and be addet in one number.
downvote count: 1
type: Question
score: -1
has comment: http://stackoverflow.com/comment/90634816
has comment: http://stackoverflow.com/comment/90634011
has comment: http://stackoverflow.com/comment/90635239
upvote count: 0
has answer: http://stackoverflow.com/a/51846685
answer count: 1
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/comment/90856067
has text: @gogaz "as close as possible to N"
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51952833

http://stackoverflow.com/a/51917443
downvote count: 0
upvote count: 8
has comment: http://stackoverflow.com/comment/123173189
has comment: http://stackoverflow.com/comment/90841206
has body: You can do this with dynamic command prefixes. Write a function or coroutine that takes a Bot and a Message and outputs the appropriate prefix for that message. Assuming you had a JSON of server ids to prefixes: { "1234": "!", "5678": "?" } You can load that json into a dictionary and then look up server ids in that dictionary. Below I also include a default prefix, but you could also raise a CommandError or something for servers with no specific prefix. from discord import commands import json with open("prefixes.json") as f: prefixes = json.load(f) default_prefix = "!" def prefix(bot, message): id = message.guild.id return prefixes.get(id, default_prefix) bot = commands.Bot(command_prefix=prefix) ...
type: Answer
has comment: http://stackoverflow.com/comment/90808439
has comment: http://stackoverflow.com/comment/90806448
answers question: http://stackoverflow.com/q/51915962
score: 8
has comment: http://stackoverflow.com/comment/90840979

http://stackoverflow.com/comment/90678527
score: 0
type: Comment
type: QuestionComment
has text: What if you used form `input` boxes inside some ` ` tags and populated the boxes with placeholders that are what has last been saved?
comment on: http://stackoverflow.com/q/51862924

http://stackoverflow.com/comment/90653283
has text: One thing that fixed this was putting the whole "load_model" method inside the "predict" method. However, this means that whenever the API is called, the model trains with all the data in the csv file.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51847727

http://stackoverflow.com/comment/117476136
type: Comment
comment on: http://stackoverflow.com/a/54486865
type: AnswerComment
has text: For MacOS, you may need `python3 -m pip install -U pyinstaller`
score: 0

http://stackoverflow.com/a/52198829
upvote count: 3
type: AcceptedAnswer
downvote count: 0
has body: To sum up what solved the problem: if you want to import the settings file from any child folder (objects or other dir) you should first add the parent directory to the python path using the sys.path.append directive: import sys sys.path.append('../') import settings In this way python will also look into the parent directory for modules to import.
type: Answer
score: 3
has comment: http://stackoverflow.com/comment/99395431
answers question: http://stackoverflow.com/q/51875030
has comment: http://stackoverflow.com/comment/99395442
accepted answer of: http://stackoverflow.com/q/51875030

http://stackoverflow.com/a/51810938
upvote count: 3
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51804842
has comment: http://stackoverflow.com/comment/90579671
has body: Consider building a generalized function, mape_calc, to receive a subset data frame as input and call the function in R's by. As the object-oriented wrapper to tapply, by will subset the main data frame by each distinct date, passing subsets into defined function for calculation. Within the method, a new, one-row data frame is built to align mape with each date. Then all rows are binded together with do.call: mape_calc &lt;- function(sub_df) { pred &lt;- predict.glm(glm_model, sub_df) actual &lt;- sub_df$Ptot mape &lt;- 100 * mean(abs((actual - pred)/actual)) new_df &lt;- data.frame(date = sub_df$date[[1]], mape = mape) return(new_df) } # LIST OF ONE-ROW DATAFRAMES df_list &lt;- by(test_data, test_data$date, map_calc) # FINAL DATAFRAME final_df &lt;- do.call(rbind, df_list) Should you have same setup in Python pandas and numpy (possibly statsmodels for glm model), use pandas DataFrame.groupby as the counterpart to R's by. Of course adjust below pseudocode to your actual needs. import pandas as pd import numpy as np import statsmodels.api as sm ... train_data = sm.add_constant(train_data) model_formula = 'Ptot ~ Temp + JFK + AEH + ART + CS + CP ...' glm_model = sm.glm(formula = model_formula, data = train_data.drop(columns=['date','Date_time']), family = sm.families.Gaussian()).fit() def mape_calc(dt, sub_df): pred = glm_model.predict(sub_df.drop(columns=['date','Date_time','Ptot'])) actual = sub_df['Ptot'] mape = 100 * np.mean(np.abs((actual - pred)/actual)) new_df = pd.DataFrame({'date': dt, 'mape': mape}, index=[0]) return new_df # LIST OF ONE-ROW DATAFRAMES df_list = [mape_calc(i, g) for i, g in test_data.groupby('date')] # FINAL DATAFRAME final_df = pd.concat(df_list, ignore_index=True)
type: Answer
accepted answer of: http://stackoverflow.com/q/51804842
has comment: http://stackoverflow.com/comment/90580124
score: 3
downvote count: 0

http://stackoverflow.com/q/51826724
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/52086297
tagged with: hotkeys
has body: I have a PyQt4 GUI that houses numerous libraries (such as Mayavi) which have their own internal keyboard shortcuts natively (already present without putting in any code to set them up). One such key is s in Mayavi - if you press this button while hovering over a Mayavi Figure, a save window will appear. Even worse, pressing the letter p while hovering over will completely freeze out all camera controls on that window. I made a similar post back in April on how to turn off these shortcuts within one of these embedded libraries (Mayavi) - however, 5 months later and it appears such knowledge is very elusive. Any help on this matter is greatly appreciated. UPDATE: I've edited the original post based on forum feedback - very sorry for obfuscating this issue; hopefully the below code will prove more clear: import sys, os from pyface.qt import QtGui, QtCore os.environ['ETS_TOOLKIT'] = 'qt4' from traits.api import HasTraits,Instance,on_trait_change,Int from traitsui.api import View,Item,VGroup from mayavi import mlab from mayavi.core.ui.api import MayaviScene, MlabSceneModel, SceneEditor class Mayavi_Scene(HasTraits): scene = Instance(MlabSceneModel, ()) @on_trait_change('scene.activated') def update_scene(self): Mayavi_Scene.fig1 = mlab.figure(1, bgcolor=(.5,.5,.5)) self.scene.mlab.clf(figure=Mayavi_Scene.fig1) testPlot = mlab.test_contour3d() view = View(Item('scene', editor = SceneEditor(scene_class=MayaviScene), height=300, width=300, show_label=False), resizable=True, ) class P1(QtGui.QWidget): def __init__(self, parent=None): super(P1, self).__init__(parent) layout = QtGui.QGridLayout(self) self.label_avgVol = QtGui.QLabel('PyQt window without Mayavi') self.label_avgVol.setMargin(5) self.label_avgVol.setFrameStyle(QtGui.QFrame.Box | QtGui.QFrame.Sunken) self.label_avgVol.setAlignment(QtCore.Qt.AlignCenter | QtCore.Qt.AlignVCenter) layout.addWidget(self.label_avgVol, 0, 0, 1, 3) self.label_avgVol.show() class P2(QtGui.QWidget): def __init__(self, parent=None): super(…
has comment: http://stackoverflow.com/comment/111601353
has comment: http://stackoverflow.com/comment/98028202
downvote count: 1
has comment: http://stackoverflow.com/comment/90608016
type: Question
upvote count: 0
has comment: http://stackoverflow.com/comment/91118252
tagged with: pyqt4
answer count: 1
has comment: http://stackoverflow.com/comment/90793682
score: -1
has comment: http://stackoverflow.com/comment/91122878
has comment: http://stackoverflow.com/comment/90611415
has comment: http://stackoverflow.com/comment/90793642
has comment: http://stackoverflow.com/comment/91121295
has answer: http://stackoverflow.com/a/52086297
has comment: http://stackoverflow.com/comment/90615744
favorite count: 0
linked to: http://stackoverflow.com/q/28417640
has comment: http://stackoverflow.com/comment/90615758
has title: PyQt4 - how to disable all hot keys (native keyboard shortcuts)

http://stackoverflow.com/q/51901141
tagged with: testing
tagged with: automation
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51902020
has answer: http://stackoverflow.com/a/51902020
type: Question
accepted answer: http://stackoverflow.com/a/51911248
score: 0
answer count: 2
tagged with: selenium
tagged with: python
has body: I'm trying to find broken links in a page. I'm using this code: (I'm not posing the original URL and element ID data because it's confidential information, and I'm using an explicit wait because it requires a login prior accessing to the page) import requests from selenium import webdriver from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By options = webdriver.ChromeOptions() options.add_argument("start-maximized") options.add_argument('disable-infobars') driver=webdriver.Chrome(chrome_options=options, executable_path='C:\\Chromedriver\\chromedriver.exe') driver.get('https://pagename.com') WebDriverWait(driver, 60).until(EC.presence_of_element_located((By.ID, 'elementID'))) links = driver.find_elements_by_css_selector("a") for link in links: r = requests.head(link.get_attribute('href')) print(link.get_attribute('href'), r.status_code) The thing is this code works for most pages. But the page I'm working with doesn't have the full URL in the href, it only has the '/extension'. So i get the requests.exceptions.MissingSchema: Invalid URL 'None': No schema supplied. Perhaps you meant http://None? error, and I'm having truble with joining the URL with the href. How do I join the URL with the href in the loop?
has answer: http://stackoverflow.com/a/51911248
tagged with: webdriver
has title: Find broken links in python with Selenium. No supplied schema error

http://stackoverflow.com/comment/90771421
type: Comment
comment on: http://stackoverflow.com/a/51881868
has text: @OK707 Why would you need the `Comparator.thenComparing()` method? You can use your own `Comparator` that compares the values however you want.
type: AnswerComment
score: 0

http://stackoverflow.com/q/51869975
possible better answer: http://stackoverflow.com/a/51870101
score: 0
has answer: http://stackoverflow.com/a/51870101
has title: In python parallel processing, how to find first process calls the function?
accepted answer: http://stackoverflow.com/a/51870081
has answer: http://stackoverflow.com/a/51870161
type: AnsweredQuestion
type: Question
has answer: http://stackoverflow.com/a/51870081
answer count: 3
has body: I have following code snippet which reads list of CSV files and merge them into a single csv. import multiprocessing def do(): pool = multiprocessing.Pool(max_threads) list_of_csvs=[] outputdir = 'output/' for csvFile in glob(outputdir + '*.csv'): list_of_csvs.append(csvFile) pool.map(writeToSingleCSV, list_of_csvs) pool.close() def writeToSingleCSV(csvFile): with open('singleDataFile.csv', 'a') as singleFile: inFile = open(csvFile, 'r') for line in inFile: singleFile.write(line) Above is code working, but I want to skip the header of following CSV files.(because all csv files contain same header)How can I skip the header from 2nd file?
tagged with: python

http://stackoverflow.com/q/51802903
type: UnansweredQuestion
type: Question
upvote count: 2
has title: Parsing HTML of Youtube playlists
answer count: 1
has comment: http://stackoverflow.com/comment/90562226
favorite count: 0
tagged with: beautifulsoup
has answer: http://stackoverflow.com/a/51806594
has body: I am having trouble parsing the HTML of youtube Playlists. For example, when I inspect the tags of "https://www.youtube.com/playlist?list=PLS1QulWo1RIYmaxcEqw5JhK3b-6rgdWO_". I see the class name "yt-simple-endpoint.style-scope.ytd-playlist-video-renderer" . But this does not work when I select the elements using bs4. However, I found another piece of working code online which selects the following class "pl-video-title-link" . But I am not able to find this class on the web page and none of the tags have this class? Attached is the working code. Any help would be appreciated. from bs4 import BeautifulSoup as bs import requests r = requests.get('https://www.youtube.com/playlist? list=PLS1QulWo1RIYmaxcEqw5JhK3b-6rgdWO_') page = r.text soup = bs(page,'html.parser') res = soup.find_all('a',{'class':'pl-video-title-link'}) for l in res: print (l.get("href"))
tagged with: scripting
tagged with: python
score: 2
downvote count: 0

http://stackoverflow.com/comment/90709419
type: QuestionComment
type: Comment
has text: @Wen What is `s` here, can you elaborate your answer.
comment on: http://stackoverflow.com/q/51878850
score: 0

http://stackoverflow.com/a/67762927
has body: I'm the author of Lucid-Dynamodb, a minimalist wrapper to AWS DynamoDB. This problem can be easily solved using this python library. Reference: https://github.com/dineshsonachalam/Lucid-Dynamodb#8-add-an-attribute-to-the-list from LucidDynamodb.Operations import DynamoDb import os import logging logging.basicConfig(level=logging.INFO) AWS_ACCESS_KEY_ID = os.getenv("AWS_ACCESS_KEY_ID") AWS_SECRET_ACCESS_KEY = os.getenv("AWS_SECRET_ACCESS_KEY") table_schema = { "TableName": "test", "KeySchema": [ { "AttributeName": "user", "KeyType": "HASH" } ], "AttributeDefinitions": [ { "AttributeName": "user", "AttributeType": "S" } ], "GlobalSecondaryIndexes": [], "ProvisionedThroughput": { "ReadCapacityUnits": 1, "WriteCapacityUnits": 1 } } if __name__ == "__main__": # 1. create a new table db = DynamoDb(region_name="us-east-1", aws_access_key_id=AWS_ACCESS_KEY_ID, aws_secret_access_key=AWS_SECRET_ACCESS_KEY) table_creation_status = db.create_table( TableName=table_schema.get("TableName"), KeySchema=table_schema.get("KeySchema"), AttributeDefinitions=table_schema.get("AttributeDefinitions"), GlobalSecondaryIndexes=table_schema.get("GlobalSecondaryIndexes"), ProvisionedThroughput=table_schema.get("ProvisionedThroughput") ) if(table_creation_status == True): logging.info("{} table created successfully".format(table_schema.get("TableName"))) else: logging.error("{} table creation failed".format(table_schema.get("TableName"))) # 2. Create a new item item_creation_status = db.create_item( TableName=table_schema.get("TableName"), Item = { "user": "xyz", "itemdetails": [{ "location": "67666", "name": "item1", "tags": [ "k7866" ] }, { "location": "45444", "name": "item12", "tags": [ "ha23", "ju4532" ] } ] } ) if(item_creation_status == True): logging.info("Item created successfully") else: logging.warning("Item creation failed") # 3. Add/Append an attribute to the list item_update_status = db.update_item( TableName=table_schema.get("TableName"), Key={ "user": "xyz" }, AttributesToUpdate…
upvote count: 2
answers question: http://stackoverflow.com/q/51816315
type: Answer
score: 2
downvote count: 0

http://stackoverflow.com/comment/90686190
comment on: http://stackoverflow.com/q/51861677
type: Comment
type: QuestionComment
has text: it doesn't say the which line it is on...
score: 0

http://stackoverflow.com/comment/90772362
comment on: http://stackoverflow.com/a/51910692
type: AnswerComment
has text: Thanks Sir. Understood the Logic.
score: 0
type: Comment

http://stackoverflow.com/comment/90747280
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51896755
has text: I haven't yet defined this but I was thinking of something like this: cache.set('my_key', 'obj', 30) I can use my custom key one for an entry. I think that is not important because I do not need to retrieve an entry by key or update it. I need only a way to store an entry and retrive all current saved entries
score: 0

http://stackoverflow.com/comment/90811458
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51930730
has text: @RushabhMehta the accepted answer on that question states it is possible but you shouldn't do it, and doesn't give details on how to do it
type: Comment

http://stackoverflow.com/comment/130847605
has text: @MattLyon Answered in the gist.
type: AnswerComment
type: Comment
score: 1
comment on: http://stackoverflow.com/a/70907644

http://stackoverflow.com/comment/90633510
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51837002
score: 0
has text: I did, it's down below

http://stackoverflow.com/comment/90656347
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/51851720
has text: That string contains two separate numbers. How do you decide which one do you want?
type: Comment

http://stackoverflow.com/comment/90844885
comment on: http://stackoverflow.com/a/51947239
score: 0
type: AnswerComment
type: Comment
has text: @JAG2024 - Maybe `()` are necesarry like in first solution.

http://stackoverflow.com/q/51819053
tagged with: visual-studio-code
possible better answer: http://stackoverflow.com/a/51819110
downvote count: 0
has answer: http://stackoverflow.com/a/51819110
tagged with: virtualenv
favorite count: 0
tagged with: python
upvote count: 1
has answer: http://stackoverflow.com/a/51830851
has title: Using virtualenv with VS Code
type: AnsweredQuestion
has body: I tried to open a python script with VS code. The library that requires with the script is in a virtualenv. I am not sure how to integrate this with VS Code. I could not find my virtualenv in the intepreter. For your information, the virtualenv I created is called "vc-web" and the scripts is in the folder called "web_scraper" inside the "vc-web" folder.
score: 1
accepted answer: http://stackoverflow.com/a/51830851
type: Question
answer count: 2

http://stackoverflow.com/a/51900852
has comment: http://stackoverflow.com/comment/90753248
type: Answer
has body: I believe if you want your list to be ['a', 'b', 'c'] or `['a', 'b'] then you put the if statement outside as follows: mylist = ['a', 'b', 'c' if condition else None] This isn't a list comprehension (above): in list comprehensions there is some loop and a single if that acts as a filter. Your code is a conditional (ternary) expression which must be evaluated to produce a result.
has comment: http://stackoverflow.com/comment/90753186
has comment: http://stackoverflow.com/comment/90753219
downvote count: 2
has comment: http://stackoverflow.com/comment/90753408
has comment: http://stackoverflow.com/comment/90753124
score: -2
upvote count: 0
answers question: http://stackoverflow.com/q/51900773

http://stackoverflow.com/q/51832499
has title: Bind Python turtle exitonclick() function to another key
type: Question
answer count: 1
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/90619183
has answer: http://stackoverflow.com/a/51845746
has body: I am using Python 2.7 turtle graphics to make a simple mouse sensor that draws whenever you hold down the mouse button. Since my function is based on the user, it crashes right when you run it. I found out that turtle.exitonclick() will help keep the interface on, but I can't draw because my draw is bound to the left mouse button click. Is there any solution to get around this or is it possible to rebind turtle.exitonclick() to something else? Here's my code: import turtle wn = turtle.Screen() wn.bgcolor("lightblue") #wn.screensize(400,300) turtle.setup(400,300) draw = turtle.Turtle() def gothere(event): draw.penup() draw.goto(event.x-360, 340-event.y) draw.pendown() #draw.color(blue) def movearound(event): draw.goto(event.x-360, 340-event.y) draw.color(blue) def release(event): draw.penup() def reset(event): draw.clear() cavset = turtle.getcanvas() cavset.bind("&lt;Button-2&gt;", gothere) cavset.bind("&lt;B1-Motion&gt;", movearound) cavset.bind("&lt;ButtonRelease-2&gt;", release) cavset.bind("&lt;Escape&gt;", reset) wn.listen() wn.exitonclick() (I am running through command prompt, BTW.)
tagged with: turtle-graphics
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/51881649
type: Answer
has comment: http://stackoverflow.com/comment/137352089
answers question: http://stackoverflow.com/q/51881503
has comment: http://stackoverflow.com/comment/90715534
has body: You can use df.apply to solve your problem, where d is your dictionary. df["Date"] = df["Member"].apply(lambda x: d.get(x)) What this code does is takes every value in the Member column and will look for that value in your dictionary. If the value is found in the dictionary than the corresponding dictionary value will populate the column. If the value is not in the dictionary then None will be returned. Also, make sure your dictionary contains valid data types. In your dictionary the keys (abc, def, ghi) should be represented as strings and your dates should be represented as either strings or date objects.
upvote count: 40
accepted answer of: http://stackoverflow.com/q/51881503
has comment: http://stackoverflow.com/comment/98351606
score: 40
has comment: http://stackoverflow.com/comment/129614516
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/51924537
downvote count: 0
answer count: 1
score: 1
tagged with: xlw
has body: I know you can do this sheet1.write(3, 3, 'TEXT') Or you can do a for loop, but I have multiple users working with my file and I don't know what's the number of the current row. I could create a var CurrentRow and increase it every time new user joins, but this might happen: User1 is writing to the file (CurrentRow = 1) User2 starts wrirting to the file (CurrentRow = 2) So User1's data will be written in row #2. Is there anything like sheet1.write('next available line')?
favorite count: 0
has title: python xlwt, write to the next available line
has answer: http://stackoverflow.com/a/51925206
tagged with: python
type: AnsweredQuestion
upvote count: 1
accepted answer: http://stackoverflow.com/a/51925206
type: Question

http://stackoverflow.com/q/51923891
accepted answer: http://stackoverflow.com/a/51924626
has comment: http://stackoverflow.com/comment/90797501
tagged with: pandas
has comment: http://stackoverflow.com/comment/90797390
answer count: 1
has comment: http://stackoverflow.com/comment/90797428
has comment: http://stackoverflow.com/comment/90797360
tagged with: python
has comment: http://stackoverflow.com/comment/90798336
type: AnsweredQuestion
tagged with: list
has answer: http://stackoverflow.com/a/51924626
score: 0
tagged with: file
has title: how to rename with the name of subfolder then copy files in python efficiently
has body: I have a directory in which there is multiple folder inside. name of folder is 1, 2,3,...10. Also there is some files inside these folders. I want to rename the file which the name is topics to the name of subfolder. then copy to the one level before where 1,2,3 folders are there. For example: dir1-&gt; 1 topics cd 2 topics cd 3 topics cd I want to rename name of topics to 1 in the first one topics to 2 in the second one topics to 3 in the third one Also copy the newest changed name file into the dir1(one level back where folder 1, 2 ,3 ) are there. I have tried this: for root, subdirs, files in os.walk(input_dir): for filename in files: #print(os.path.join(root, filename)) if filename=='topics.csv': os.rename(os.path.join(root, filename), os.path.join(root, str(i)) + ".csv") shutil.move(os.path.join(root,str(i)), os.path.join(input_dir,str(i))) i = i+1 But it did not work. My expected result will be dir1-&gt; 1 1.txt 1.txt cd 2 2.txt 2.txt cd 3 3.txt 2.txt cd here 1.txt = topics which has been renamed then coppied one level behind Thanks for your help :)
type: Question
tagged with: performance
has comment: http://stackoverflow.com/comment/90797517
has comment: http://stackoverflow.com/comment/90797610
has comment: http://stackoverflow.com/comment/90797469

http://stackoverflow.com/a/51935018
answers question: http://stackoverflow.com/q/51934855
type: AcceptedAnswer
downvote count: 0
has body: Firstly you need to create function which will highlighting your cells: def func(): #here contidions for highlighting the cells return ['background-color: red'] Now you can apply this function to cells you need: data_frame.style.apply(func) Second variant is: # Create a Pandas Excel writer using XlsxWriter as the engine. writer = pd.ExcelWriter('pandas_conditional.xlsx', engine='xlsxwriter') # Convert the dataframe to an XlsxWriter Excel object. df.to_excel(writer, sheet_name='Sheet1') # Get the xlsxwriter workbook and worksheet objects. workbook = writer.book worksheet = writer.sheets['Sheet1'] # Apply a conditional format to the cell range. worksheet.conditional_format('B2:B8', {'type': '3_color_scale'}) # Close the Pandas Excel writer and output the Excel file. writer.save()
type: Answer
upvote count: 1
score: 1
accepted answer of: http://stackoverflow.com/q/51934855

http://stackoverflow.com/comment/90613800
type: AnswerComment
comment on: http://stackoverflow.com/a/51829736
type: Comment
has text: Obviously, if you don't really need the parallelism, as your answer indicates, the correct solution is to fix the algorithmic choices that caused the slowdown and avoid pointless parallelism, I just figured explaining the cause of your problem might be helpful should you need to parallelize in the future.
score: 1

http://stackoverflow.com/comment/90579909
comment on: http://stackoverflow.com/q/51812449
score: 0
has text: I looked at it, but I could not understand.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90762136
has text: @Maher So what if you did `df['col'] = pd.Categorical(df['col'], categories=cats, ordered=True)` and then ran `df['col'].cat.codes`?
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51904468

http://stackoverflow.com/a/51824589
answers question: http://stackoverflow.com/q/51820782
type: Answer
has body: You can find the latest release here -> https://www.python.org/downloads/
score: 2
downvote count: 0
upvote count: 2

http://stackoverflow.com/comment/91083024
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51865607
has text: My script creates plots for each of 50 tests of 20 units. During development it had both `plt.savefig()` and `plt.show()` calls. When the script is run in File Explorer, the `show` call displays each figure and doesn't proceed until you close it. So how should I reset the `plt.plot()` queue (?) so it creates the files without using show?

http://stackoverflow.com/comment/90732381
has text: Try this https://pip.pypa.io/en/stable/installing/
comment on: http://stackoverflow.com/q/51890657
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/comment/90584007
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51814765
has text: Seems you haven't add python path to environment variable? could you add your environment variable information?
score: 0

http://stackoverflow.com/comment/90817252
comment on: http://stackoverflow.com/q/51933498
score: 0
type: Comment
type: QuestionComment
has text: do you have another python instalation? or only conda? And try pip list and python -V from the same environment you are running the exe ( same directory) Check if it is the same from conda. If nothing works try to generate the exe again or run it in admin mode

http://stackoverflow.com/comment/90893461
comment on: http://stackoverflow.com/a/51935987
type: AnswerComment
score: 0
has text: It all depends on what you want to do. If you know you will have a certain grid pattern (rows x columns) then you can do like above (including rows in a similar fashion) to lay it out. If you just want a specified label cell width and label placement in that cell you could just do something like: `label1 = Label(root, textvariable=Var, width=100, anchor=E)` followed by `label1.grid()`.
type: Comment

http://stackoverflow.com/q/51929531
has body: i am making stopwords removal api with using django.when i submit user text input fairly getting output but text area not visible after getting output.my requirement is below output is displaying input should remain same. below code as u can see in image snapshots is the text area is invisible.so it shoul be visible views.py from django.shortcuts import render,redirect,HttpResponse from django.views.generic.edit import FormView from .forms import ReportForm from django.views import View import spacy import pdb nlp = spacy.load('en_core_web_sm') class stopwordsremoval(FormView): template_name = 'report.html' form_class = ReportForm def form_valid(self, form): document1 = ((form.cleaned_data.get('text'))) return redirect('report_details', document1) class ReportDetails(View): def get(self,request,document1): word_lemma = [] #pdb.set_trace() for word in (nlp(document1)): a = (word.is_stop, word.text) word_lemma.append(a) searchedData = (word_lemma) return render(request, 'report.html', {'naturallanguageprocessing': searchedData}) forms.py from django import forms class ReportForm(forms.Form): text = forms.CharField(widget=forms.Textarea(attrs={'rows': 5, 'cols': 100})) report.html {% extends 'base.html' %} {% block content %} StopWordsRemoval {% csrf_token %} {{ form.as_p}} stopwordsremoval {{ naturallanguageprocessing }} [![enter image description here][1]][1] <a href="{% url 'stopwordsremoval' %}" {% endblock %} [![this is the user input we are giving][1]][1] [1]: https://i.sstatic.net/TlSlL.png [![this output the text area is not visible have to make visible][1]][1] [1]: https://i.sstatic.net/M80Un.png
tagged with: django-forms
type: Question
has comment: http://stackoverflow.com/comment/90808616
score: 0
upvote count: 1
downvote count: 1
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90809186
tagged with: django
tagged with: python
has title: Django form should remain same after submit button clicked
answer count: 0

http://stackoverflow.com/comment/90799854
type: QuestionComment
score: 2
has text: Could you be more specific about the sorting order?
comment on: http://stackoverflow.com/q/51925233
type: Comment

http://stackoverflow.com/q/51851520
downvote count: 0
has comment: http://stackoverflow.com/comment/90656011
has comment: http://stackoverflow.com/comment/90656061
type: Question
has comment: http://stackoverflow.com/comment/90656054
score: 1
has comment: http://stackoverflow.com/comment/90656042
tagged with: sleep
has comment: http://stackoverflow.com/comment/90656025
has comment: http://stackoverflow.com/comment/90656010
tagged with: pool
has comment: http://stackoverflow.com/comment/90656021
upvote count: 1
has comment: http://stackoverflow.com/comment/90656016
answer count: 1
has comment: http://stackoverflow.com/comment/90655996
has answer: http://stackoverflow.com/a/51853346
has title: Sleep the thread on if statement check, Python Pool
favorite count: 0
accepted answer: http://stackoverflow.com/a/51853346
has comment: http://stackoverflow.com/comment/90656019
has comment: http://stackoverflow.com/comment/90659253
tagged with: python
has body: I have a code the reads a very large text file and process each line in Pools. In the case of the elif I need to sleep the whole process for 120 seconds, in other words, I want all other Pools created to pause. But after 120 seconds all Pools should resume working. The code's functionality is similar to this: from multiprocessing import Pool import sys sys.tracebacklimit = 0 def req(line): if "@" not in line: # (some function for processing here) return line elif "somestring" in line: #HERE I NEED TO SLEEP ALL POOLS else: # (some function for processing) return line if __name__ == "__main__": pool = Pool(20) with open("list.txt") as source_file: # chunk the work into batches of 20 lines at a time pool.map(req, source_file, 35)
type: AnsweredQuestion

cs50
tag name: cs50
type: Tag
tags question: http://stackoverflow.com/q/51879889

http://stackoverflow.com/a/51865324
downvote count: 0
answers question: http://stackoverflow.com/q/51865268
has body: There are other ways, but if you aren't opposed to numpy, it is easy, and you can avoid an explicit loop: import numpy as np np.mean(np.stack((a,b,c))[:,:3]) Which returns 2.0 The above says: take the mean of all values up to the 3rd for all arrays together If you want an explicit loop, you could do: my_list = [] for l in [a,b,c]: my_list.extend(l[:3]) sum(my_list) / len(my_list) Which also returns 2.0
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/q/51860417
has answer: http://stackoverflow.com/a/51861007
downvote count: 0
has answer: http://stackoverflow.com/a/51860995
favorite count: 0
has answer: http://stackoverflow.com/a/51861012
tagged with: python
has title: Find if all nodes in BST are greater than a item
answer count: 4
type: AnsweredQuestion
score: 3
upvote count: 3
type: Question
accepted answer: http://stackoverflow.com/a/51861012
has body: I have been working on trying to implement the function all_bigger below but I am not sure if there are flaws in my logic. To my understanding, BST's are organized having the smallest values on the left side so I would only need to check the left side of the BST. Is there a better way of writing this or is my code incorrect? class BSTNode: """A node is a BST """ def __init__(self: 'BSTNode', item, left, right): self.item, self.left, self.right = item, left, right def all_bigger(self, value): """ &gt;&gt;&gt; bst = BSTNode(5, BSTNode(4), BSTNode(6)) &gt;&gt;&gt; all_bigger(bst, 2) True """ while self.left: if self.left &gt; value: self.value = self.left: else: return False return True
has comment: http://stackoverflow.com/comment/90673372
has comment: http://stackoverflow.com/comment/90674039
has answer: http://stackoverflow.com/a/51861053
possible better answer: http://stackoverflow.com/a/51861007

http://stackoverflow.com/a/51881043
has body: I think you should be able to specify encoding manually like this: response.replace(encoding='gb2312') and then try to pass that to the link extractor. Edit: So it seems scrapy fails to specify url encoding somewhere down the link processing chain (at w3lib.url.canonicalize_url I believe when performing deduplication). As a workaround you can use this: resp = response.replace(encoding='utf8', body=response.text.encode('utf8'))
accepted answer of: http://stackoverflow.com/q/51880685
type: Answer
answers question: http://stackoverflow.com/q/51880685
score: 1
has comment: http://stackoverflow.com/comment/90746402
upvote count: 1
has comment: http://stackoverflow.com/comment/90744813
has comment: http://stackoverflow.com/comment/90732941
has comment: http://stackoverflow.com/comment/90724902
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/125503752
has text: This worked for me! I used the 16 digit password generated by app passwords.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51837049
type: Comment

http://stackoverflow.com/q/51900310
upvote count: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/90751899
has comment: http://stackoverflow.com/comment/90751846
tagged with: nameerror
score: 0
tagged with: python-import
has comment: http://stackoverflow.com/comment/90752354
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90752131
tagged with: python
has body: I have a directory structure which is as follows controllers/ __init__.py imports.py BLL/ __init__.py foo.py in imports.py I have following line CLASSROOM_STUDENT_KEY = ndb.Key("Entity", "classroom_student_key") I want to access this CLASSROOM_STUDENT_KEY in foo.py in foo.py I have imported contents of imports like this from controllers.imports import * but when I run the code it gives me error: NameError: global name 'CLASSROOM_STUDENT_KEY' is not defined both of my init.py are empty. I donot want to use CLASSROOM_STUDENT_KEY as imports.CLASSROOM_STUDENT_KEY. It should be available with typing just its own name
has title: importing from parent package Python - Python import error
answer count: 0

http://stackoverflow.com/comment/90571221
type: Comment
has text: I'm not sure I'm following. This is the first time I'm trying multithreading. This code is based on example I saw.. I passed the page argument just for the printing. It's not actually needed. The [(executor.submit(getdata, page, hed, value_limit), page) for page in pages] works great! I'm open to any further suggestion you have..
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51807982

http://stackoverflow.com/comment/90581604
type: Comment
has text: Oh okay that makes sense, how would I implement that into my coding though? I've tried a few if statements but nothing quite seems to let me modify the speed to 3 * 1.41 when moving diagonally
comment on: http://stackoverflow.com/a/51810519
score: 0
type: AnswerComment

http://stackoverflow.com/q/51820939
answer count: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/1373164
type: Question
has comment: http://stackoverflow.com/comment/90623137
duplicate of: http://stackoverflow.com/q/1373164
has comment: http://stackoverflow.com/comment/90596178
has body: I'd like to iterate a python script over a set of data variables. I have input data variables named data_X, data_Y, etc. which are defined at the beginning of my script, e.g. data_X = [1, 2, 5, 42, 793]. In bash, I could just use "$X" to specify that I want the string, so I'm looking for a python equivelent. When I try for variable in ['X', 'Y']: run_data = 'data_' + variable what happens is that run_data is now equal to a string data_X, but not equal to the actual data that I had earlier defined as data_X How do I specify that I want run_data to equal the values originally assigned to data_X?
has comment: http://stackoverflow.com/comment/90596202
has comment: http://stackoverflow.com/comment/90602245
score: 0
tagged with: for-loop
tagged with: string
has title: Python - specifying file names in for loop
has comment: http://stackoverflow.com/comment/90596832
tagged with: python
has comment: http://stackoverflow.com/comment/90596828

http://stackoverflow.com/q/51900500
has comment: http://stackoverflow.com/comment/90888790
has comment: http://stackoverflow.com/comment/116617378
has comment: http://stackoverflow.com/comment/94572162
tagged with: google-cloud-dataflow
score: 4
has comment: http://stackoverflow.com/comment/116671644
answer count: 1
downvote count: 0
has body: I'm trying to transform a few Terabytes of mail logs stored in GCS without using too much memory. As recommended in the guide, I'm adding timestamp to each element, split it to a sliding window and I have specified an (aggregation) trigger before sending it to a GroupByKey and a ParDo parser after. This should do, but still GroupByKey waits for all data to arrive. Why? I have tried it with Direct and Google Dataflow runner as well. What do I miss? Here's the gist of the code: known_args, pipeline_options = parse_args(sys.argv) pipeline = beam.Pipeline(options=pipeline_options) lines = pipeline | 'read' &gt;&gt; beam.io.ReadFromText(known_args.input) parsed_json = lines \ | 'cut' &gt;&gt; beam.Map(lambda x: x[39:])\ | 'jsonify' &gt;&gt; beam.Map(json_loads).with_outputs('invalid_input', main='main') keyed_lines = parsed_json['main']\ | 'key_filter' &gt;&gt; beam.Filter(lambda x: u'key' in x)\ | 'keyer' &gt;&gt; beam.Map(lambda x: (x['key'], x))\ | 'log_processed_rows' &gt;&gt; beam.Map(log_processed_rows) window_trigger = trigger.DefaultTrigger() windowed_lines = keyed_lines\ | 'timestamp' &gt;&gt; beam.ParDo(AddTimestampDoFn())\ | 'window' &gt;&gt; beam.WindowInto(beam.window.SlidingWindows(size=3600+600, period=3600), trigger=window_trigger, accumulation_mode=trigger.AccumulationMode.DISCARDING) # 1 hour steps with 10 minutes of overlap results = windowed_lines \ | 'groupbykey' &gt;&gt; beam.GroupByKey()\ | 'parse' &gt;&gt; beam.ParDo(ParseSendingsDoFn()).with_outputs('too_few_rows', 'invalid_rows', 'missing_recipients', main='main_valid') output = results['main_valid'] \ | 'format' &gt;&gt; beam.Map(output_format)\ | 'write' &gt;&gt; beam.io.WriteToText(known_args.output, file_name_suffix=".gz")
favorite count: 0
type: UnansweredQuestion
tagged with: apache-beam
tagged with: python
upvote count: 4
has title: How to transform bounded pcollection to unbounded in Python with Apache Beam?
has answer: http://stackoverflow.com/a/56139981
type: Question

http://stackoverflow.com/q/51854971
upvote count: 1
answer count: 1
linked to: http://stackoverflow.com/q/25870729
favorite count: 0
type: UnansweredQuestion
has body: I am developing a desktop application using Python 3.6 and PyQt5. After compiling the application using Pyinstaller i intend to make a setup file using Inno setup. The software give us the opportunity to choose the application's language while running the setup file. I would like to know how can i load the translation file (.qm file) based on that choice and thanks.
tagged with: python
has title: Load translation files to Pyqt5 application
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/51855686
tagged with: pyqt5
type: Question
tagged with: inno-setup

http://stackoverflow.com/comment/90704737
comment on: http://stackoverflow.com/q/51876411
score: 0
has text: What do you mean you are unable to read the latest messages from Kafka? Are there any new messages while the consumer is running or not?
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51911992
score: 1
type: Question
has title: pyowm call works in own program, but not when called from other program
tagged with: function
has body: The pyowm library allows one to get weather forecasts from https://openweathermap.org. It works nicely in a little program I've written to download a near-term forecast (see below, excepting my API key which I've X'd out; insert your own API key of you want to test the code, they're freely available from openweathermap). #!/usr/bin/env python import pyowm import json owm = pyowm.OWM('XXXXXXXXXXXXX') # You MUST provide a valid API key forecaster = owm.three_hours_forecast('Santa Fe, US') forecast = forecaster.get_forecast() forecastJSON=json.loads(forecast.to_JSON()) def oneForecast(): mrForecast = forecastJSON['weathers'][:1] return mrForecast[0]['detailed_status'] def printForecast(): print oneForecast() if __name__ == "__main__": printForecast() That works perfectly from the command line. However, if I create another program that periodically calls oneForecast(), it returns the correct answer the first time, and then NEVER CHANGES ITS FORECAST. See for example #!/usr/bin/env python import time import msForecast def run(): while True: text = msForecast.oneForecast() print text time.sleep(10.0) if __name__ == "__main__": run_text = run() This program, when run from the command line, should print a simple forecast every ten seconds. As it makes a call to the API each time, this forecast should update as the weather changes, but it does not. If the forecast is 'light rain' when the program is first run, it will print 'light rain' every ten seconds indefinitely, without ever changing. Have I made an error in the way the second bit of code calls the first? Is there some cache that needs to be flushed? What might I be missing here?
upvote count: 1
answer count: 1
tagged with: weather-api
favorite count: 0
accepted answer: http://stackoverflow.com/a/51912012
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51912012
downvote count: 0

http://stackoverflow.com/comment/90696605
comment on: http://stackoverflow.com/q/51872584
score: 0
type: Comment
has text: Do you think `df = df.reset_index(level=[0,1]).reset_index()` ?
type: QuestionComment

http://stackoverflow.com/comment/90766087
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51907791
has text: Are you waiting (programmatically) for the element to load and identify if it is there or not in your code?
score: 0

http://stackoverflow.com/q/51925830
has title: Unable to write data in a csv file using dictwriter
linked to: http://stackoverflow.com/q/26944274
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51926243
has answer: http://stackoverflow.com/a/51926243
tagged with: http://stackoverflow.com/tag/json
duplicate of: http://stackoverflow.com/q/26944274
tagged with: web-scraping
upvote count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/51926283
type: Question
score: 0
answer count: 3
linked to: http://stackoverflow.com/q/29773991
has answer: http://stackoverflow.com/a/51926101
has body: I've written a script in python to scrape some item names, estimated time along with reviews, reviewers and rating connected to each item name from a webpage using their api and write them to a csv file. The thing is my below script can parse the data accordingly but I can't write them to a csv file. However, when I try to write them to a csv file I get the following error: Traceback (most recent call last): File "C:\Users\WCS\AppData\Local\Programs\Python\Python36-32\demo000000.py", line 71, in &lt;module&gt; w.writerow(reviews) File "C:\Users\WCS\AppData\Local\Programs\Python\Python36-32\lib\csv.py", line 155, in writerow return self.writer.writerow(self._dict_to_list(rowdict)) File "C:\Users\WCS\AppData\Local\Programs\Python\Python36-32\lib\csv.py", line 151, in _dict_to_list + ", ".join([repr(x) for x in wrong_fields])) ValueError: dict contains fields not in fieldnames: 'reviews' This is what I tried so far: import csv import requests url = "https://eatstreet.com/api/v2/restaurants/{}?yelp_site=" res = requests.get("https://eatstreet.com/api/v2/locales/madison-wi/restaurants") with open('reviews.csv', 'w', newline='') as f: w = csv.DictWriter(f,['name','eta','messg','reviewer','rating']) w.writeheader() for item in res.json(): itemid = item['id'] req = requests.get(url.format(itemid)) if not 'yelpReviews' in req.json():continue reviews = {} reviews['name'] = req.json()['name'] reviews['eta'] = req.json()['waitTime'] reviews['reviews'] = [] for texualreviews in req.json()['yelpReviews']: reviews_data = {'messg':texualreviews['message'],'reviewer':texualreviews['reviewerName'],'rating':texualreviews['rating']} reviews['reviews'].append(reviews_data) w.writerow(reviews) Any help to write the scraped data in a csv file will be highly appreciated. Thanks.
favorite count: 0
tagged with: python-3.x
tagged with: http://stackoverflow.com/tag/csv
accepted answer: http://stackoverflow.com/a/51926101
tagged with: python

http://stackoverflow.com/q/51833233
has comment: http://stackoverflow.com/comment/90620576
has comment: http://stackoverflow.com/comment/90620629
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90620766
downvote count: 3
has comment: http://stackoverflow.com/comment/90620556
upvote count: 1
has comment: http://stackoverflow.com/comment/90620699
has comment: http://stackoverflow.com/comment/90620676
linked to: http://stackoverflow.com/q/1481488
has body: In my python program, I create a self-defined object. This program is exited by receiving a CTRL-C signal. However, the __del__ function is not called when the program exits. When the program exits, all the object created by this program should be deleted, but why the __del__ function is not called? For now, in order to do some clean-up, i resolve to atexit module. Is there any more graceful methods? Actually, I want to use RAII in C++ to manage my python object, can I do this?
has answer: http://stackoverflow.com/a/51833300
type: Question
has comment: http://stackoverflow.com/comment/90620371
answer count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/6104535
tagged with: python
score: -2
has comment: http://stackoverflow.com/comment/90620365
duplicate of: http://stackoverflow.com/q/6104535
has title: How to ensure the __del__ function be called when the program exits by ctrl-c?
has comment: http://stackoverflow.com/comment/90620721

http://stackoverflow.com/q/51952006
has comment: http://stackoverflow.com/comment/90858114
score: 0
has title: How to fix broken Conda
has body: I am in a small cluster environment where Anaconda 4.2 is installed, however, if I go to the bin folder of Anaconda and run conda, it says: ImportError: No module named conda.cli The content of this conda is below: $ cat conda #!/usr/bin/env python if __name__ == '__main__': import sys import conda.cli sys.exit(conda.cli.main()) I don't want to install conda again as I am not sure if it would ruin the existing installation which was within Cloudera's parcels management, and I doubt if I need to re-install it. Any idea would be appreciated. Thank you.
type: UnansweredQuestion
tagged with: python
duplicate of: http://stackoverflow.com/q/19825250
has comment: http://stackoverflow.com/comment/90854821
tagged with: anaconda
answer count: 0
has comment: http://stackoverflow.com/comment/90861672
has comment: http://stackoverflow.com/comment/90861498
type: Question

http://stackoverflow.com/comment/90834106
type: Comment
has text: @tankbusta OP wants it to run in the directory, not to run it remotely. I’m essentially automating the copy/paste he talks about.
comment on: http://stackoverflow.com/a/51942076
score: 0
type: AnswerComment

http://stackoverflow.com/q/51804857
has body: I have two buttons on my interface. I want both of them to be able to call their respective functions when I either click on them or a hit the Enter Key. The problem I'm having is that only the last button in the traveral focus gets activated when I hit the Enter Key, even if the preceeding one has the focus. What can I do to resolve this problem. Useful answer are welcome and appreciated. This is the problem in question: from tkinter import * w = Tk() def startProgram(event = None): print('Program Starting') def readyContent(event = None): print('Content being prepared') # Buttons Button(text='Prepare', command=readyContent).grid(row=10,column=2) w.bind('&lt;Return&gt;',readyContent) # Binds the Return key to a Function Button(text='Start', command=startProgram).grid(row=10,column=3) w.bind('&lt;Return&gt;',startProgram) # Binds the Return key to a Function w.mainloop() When you click on the Prepare or Start button, in return you get either Content being prepared or Program Starting repectively. Nothing like that happens when you use the Tab Key to give focus to one button or the other. Even if the focus is on the Prepare button, when you hit Enter you get: Program Starting
type: Question
tagged with: python-3.6
has answer: http://stackoverflow.com/a/51807193
score: 0
answer count: 1
tagged with: tkinter
type: UnansweredQuestion
has title: Button error, but I get IndexError: list index out of range
has comment: http://stackoverflow.com/comment/90565642
tagged with: python
has comment: http://stackoverflow.com/comment/90569634
has comment: http://stackoverflow.com/comment/90565645

http://stackoverflow.com/q/51806549
type: Question
has comment: http://stackoverflow.com/comment/90568577
has comment: http://stackoverflow.com/comment/90568554
has comment: http://stackoverflow.com/comment/90568603
has comment: http://stackoverflow.com/comment/90568591
favorite count: 0
has comment: http://stackoverflow.com/comment/90568579
answer count: 2
tagged with: python
has title: What does 'unsupported operand type(s) for -: 'float' and 'tuple' mean in my code
has answer: http://stackoverflow.com/a/51806586
has comment: http://stackoverflow.com/comment/90568612
has body: So I got this message in my code and am not sure how to fix it. I have tried looking at other peoples questions however they don't seem to relate to mine. The Problem is located on the 6th line of the third block of code. coc =float(Cappacuino.get()) col= float(Latte.get()) cofw= float(Flat_White.get()) cob= float(Black_Coffee.get()) coa= float(Americano.get()) cof= float(Frappe.get()) costofcappacuino = coc*4 costoflatte = col*4 costofflatwhite = cofw*3 costofblackcoffee = cob*3 costofamericano = coa*4 costoffrappe = cof*5 costoforder = "$",str('%.2f'% (costofcappacuino + costoflatte + costofflatwhite + costofblackcoffee + costofamericano + costoffrappe)) PayTax=((costofcappacuino + costoflatte + costofflatwhite + costofblackcoffee + costofamericano + costoffrappe)*0.15) Totalcost=(costofcappacuino + costoflatte + costofflatwhite + costofblackcoffee + costofamericano + costoffrappe) Disscount=((costofcappacuino + costoflatte + costofflatwhite + costofblackcoffee + costofamericano + costoffrappe)/10) Disscount="$",str('%.2f'% Disscount) OverAllCost="$",str( PayTax + Totalcost - Disscount) PaidTax="$",str('%.2f'% PayTax) Disscount.set(Disscount) cost.set(costoforder) Tax.set(PaidTax) Subtotal.set(costoforder) Total.set(OverAllCost) Exception in Tkinter callback Traceback (most recent call last): File "/Users/samjones/Documents/source/CoffeeShop.py", line 49, in Ref OverAllCost="$"+str( PayTax + Totalcost - Disscount) TypeError: unsupported operand type(s) for -: 'float' and 'tuple'
has answer: http://stackoverflow.com/a/51806631
downvote count: 4
has comment: http://stackoverflow.com/comment/90568609
upvote count: 0
type: UnansweredQuestion
score: -4

http://stackoverflow.com/a/51879483
accepted answer of: http://stackoverflow.com/q/51878761
answers question: http://stackoverflow.com/q/51878761
has body: Whatever the print statements will be in the end, to use the save button as call for changing something you have to override/extend create() and write() methods of your model. class ResPartner_school(models.Model): @api.multi def changed_half_pension(self) for record in self: if record.half_pension: print "half_pension is on" else: print "half_pension is off" @api.model def create(self, vals): record = super(ResPartner_school, self).create(vals) record.changed_half_pension() return record @api.multi def write(self, vals): result = super(ResPartner_school, self).write(vals) self.changed_half_pension() return result The onchange decorator is used to call the decorated method whenever the field is changed in the client. The change itself will be then saved by the button "save". So onchange behaviour is the wrong decision in this case.
has comment: http://stackoverflow.com/comment/90711790
has comment: http://stackoverflow.com/comment/90712520
has comment: http://stackoverflow.com/comment/90711252
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90712451
has comment: http://stackoverflow.com/comment/90711743
type: Answer
has comment: http://stackoverflow.com/comment/90711610
score: 1
has comment: http://stackoverflow.com/comment/90711624
upvote count: 1
has comment: http://stackoverflow.com/comment/90712259
has comment: http://stackoverflow.com/comment/90711689

http://stackoverflow.com/comment/108802402
has text: @cyrf it's json object. Whitespace doesn't affect anything. It's just for styling- to make it more readable.
score: 1
comment on: http://stackoverflow.com/a/59062665
type: AnswerComment
type: Comment

http://stackoverflow.com/q/51867317
favorite count: 0
has title: curve_fit fails when using endpoint=False in independent variable
tagged with: curve-fitting
tagged with: python
type: AnsweredQuestion
tagged with: mathematical-optimization
accepted answer: http://stackoverflow.com/a/51874173
upvote count: 1
tagged with: scipy
type: Question
has body: I'm fitting some data (I have hard-coded it here) using a technique described in this question and it seemed to work fine. However, I realized my xdata was not quite what I wanted it to be so I used 'endpoint=False' so that my xdata increased from 17 to 27.5 in steps of 0.5. Upon doing this, scipy warned me that: minpack.py:794: OptimizeWarning: Covariance of the parameters could not be estimated category=OptimizeWarning) Perhaps this is working as intended and I'm missing some part of how curve_fit, or the Fourier function works, but I would really like to be able to fit this with the correct (albeit only slightly different) x values. My y values do have an offset that the fit removes when it runs successfully, which is fine by me. import numpy as np import matplotlib.pyplot as plt from scipy.optimize import curve_fit ydata = [48.97266579, 54.97148132, 65.33787537, 69.55269623, 56.5559082, 41.52973366, 28.06554699, 19.01652718, 16.74026489, 19.38094521, 25.63856506, 24.39780998, 18.99308014, 30.67970657, 31.52746582, 45.38796043, 45.3911972, 42.38343811, 41.90969849, 38.00998878, 49.11366463, 70.14483643] xdata = np.linspace(17, 28, 22, endpoint=False) #, endpoint=False def make_fourier(na, nb): def fourier(x, *a): ret = 0.0 for deg in range(0, na): ret += a[deg] * np.cos((deg+1) * 2 * np.pi * x) for deg in range(na, na+nb): ret += a[deg] * np.sin((deg+1) * 2 * np.pi * x) return ret return fourier def obtain_fourier_coef(ydata, harms): popt, pcov = curve_fit(make_fourier(harms, harms), xdata, ydata, [0.0]*harms*2) plt.plot(xdata, (make_fourier(harms,harms))(xdata, *popt)) plt.show() plt.plot(xdata, ydata) obtain_fourier_coef(ydata, 10) With endpoint=False: curve fit results plot Without endpoint=False: curve fit results plot
score: 1
linked to: http://stackoverflow.com/q/32590720
tagged with: numpy
has answer: http://stackoverflow.com/a/51874173
downvote count: 0
answer count: 1

http://stackoverflow.com/comment/90654828
comment on: http://stackoverflow.com/q/51833386
has text: I was using the escape char which was causing the issue as " and , need an escape char in front of it. Actially what I need can be done in a much simpler way with basic print. That worked. Thank you all for clarifying my question.
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51832173
downvote count: 0
type: AcceptedAnswer
has body: It is impossible to know from your code what the data you are trying to insert looks like but from reading your models definition and the error, you are violating a unique constraint in your Track table. Your Track uri attribute and track_id attribute have a unique constraint which means you can only have one unique track uri and one track_id in the whole database. Could it be possible that a user might have the same track in two different playlists? if this is possible than you should remove the unique constraint in your Track table definition on track_id and uri and see if this error will disappear.
answers question: http://stackoverflow.com/q/51830528
accepted answer of: http://stackoverflow.com/q/51830528
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/comment/90853353
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51951429
has text: But when do you expect it and when not? E.g., it may be perfectly reasonable to use a dict comprehension to get unique values based on some list. Granted, in this entirely constant dict comprehension, it's clearly unintentional, but I'd consider this the job of the IDE (or maybe some linter)
score: 0

http://stackoverflow.com/a/51852887
downvote count: 1
has comment: http://stackoverflow.com/comment/107434791
answers question: http://stackoverflow.com/q/51852025
type: Answer
has body: If you are personally an admin of the pages, then using your personal user access token, you can request a page access token via the API. Then use that to do the operation. https://developers.facebook.com/docs/pages/access-tokens/#page-access-tokens $ okurl https://graph.facebook.com/v3.1/me/accounts?fields=access_token,name --token XXXXXXXXU { "data": [ { "access_token": "XXXX1", "name": "Page 1", "id": "99999999" }, { "access_token": "XXXX2", "name": "Page 2", "id": "99999999" }, { "access_token": "XXXX3", "name": "Page 3", "id": "99999999" },
score: 0
upvote count: 1

http://stackoverflow.com/a/51845441
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51845113
has comment: http://stackoverflow.com/comment/90649369
answers question: http://stackoverflow.com/q/51845113
type: Answer
has comment: http://stackoverflow.com/comment/90652430
has body: You can use pandas to join in the new values: import pandas as pd df1 = pd.read_csv("&lt;path to csv1&gt;.csv") df2 = pd.read_csv("&lt;path to csv2&gt;.csv").rename(columns={"Switch": "new_switch", "Port": "new_port"}) # clean up column names df1.columns = [i.strip() for i in df1.columns] df2.columns = [i.strip() for i in df2.columns] # join in new values result = df1.join(df2.set_index("Mac"), on="Mac") # use the new values where they're defined, otherwise fill in with the old values result["Switch"] = result["new_switch"].fillna(result["Switch"]) result["Port"] = result["new_port"].fillna(result["Port"]) # delete the "new" columns, which are no longer needed del result["new_switch"], result["new_port"] # write out result.to_csv("&lt;path to new csv&gt;.csv", index=False) This assumes your csv2 has only one row for each Mac value.
has comment: http://stackoverflow.com/comment/90650601
score: 0

http://stackoverflow.com/q/51845504
upvote count: 2
type: Question
has comment: http://stackoverflow.com/comment/90644418
has title: Change icon of another running process with Python
accepted answer: http://stackoverflow.com/a/51845625
has body: I would like to change in Python the icon of another running process (NOT the icon of an exe made from python with the likes of cx_freeze) in Windows. Is this possible?
answer count: 1
downvote count: 0
tagged with: pywinauto
favorite count: 0
has answer: http://stackoverflow.com/a/51845625
tagged with: python
type: AnsweredQuestion
score: 2

http://stackoverflow.com/q/51860652
has comment: http://stackoverflow.com/comment/90677403
type: UnansweredQuestion
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/51860925
has comment: http://stackoverflow.com/comment/90673644
tagged with: django-models
tagged with: django-forms
linked to: http://stackoverflow.com/q/31833769
type: Question
has body: I am new to Django. I created the sqlite3 database called "test.db" and I'm not using the models.py or default database to sync in views.py for saving data. I've created the HTML to get the value to store in test.db and print the data using the normal sqlite3 query. The problem is that I have to access the test.db database in admin panel to search and print the data stored in the database. How to do this task?
has title: Creating search form in admin panel - Django
answer count: 1
tagged with: django-rest-framework
score: 0

http://stackoverflow.com/comment/90731912
has text: Post your code, not screenshot of your code
type: QuestionComment
type: Comment
score: 7
comment on: http://stackoverflow.com/q/51890444

http://stackoverflow.com/q/51839219
has comment: http://stackoverflow.com/comment/90632641
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90632311
has comment: http://stackoverflow.com/comment/90632546
tagged with: python
has comment: http://stackoverflow.com/comment/90633359
tagged with: anaconda
has comment: http://stackoverflow.com/comment/90632811
has comment: http://stackoverflow.com/comment/90631939
type: Question
has comment: http://stackoverflow.com/comment/90633315
has title: Can't use SPYDER (anaconda)
has answer: http://stackoverflow.com/a/51840710
has comment: http://stackoverflow.com/comment/90632281
has comment: http://stackoverflow.com/comment/90631721
has comment: http://stackoverflow.com/comment/90631536
score: 0
linked to: http://stackoverflow.com/q/50089668
has body: I've installed anaconda for spyder ide. But I had multiple problems. runfile('C:/Users/Berk DOĞUŞ/Spyder Projects/DogrusalRegresyon.py', wdir='C:/Users/Berk DOĞUŞ/Spyder Projects') Traceback (most recent call last): File "", line 1, in runfile('C:/Users/Berk DOĞUŞ/Spyder Projects/DogrusalRegresyon.py', wdir='C:/Users/Berk DOĞUŞ/Spyder Projects') File "C:\AConda\lib\site-packages\spyder\utils\site\sitecustomize.py", line 705, in runfile execfile(filename, namespace) File "C:\AConda\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile exec(compile(f.read(), filename, 'exec'), namespace) File "C:/Users/Berk DOĞUŞ/Spyder Projects/DogrusalRegresyon.py", line 13, in import pandas as pd File "C:\Users\Berk DOĞUŞ\AppData\Roaming\Python\Python36\site-packages\pandas__init__.py", line 35, in "the C extensions first.".format(module)) ImportError: C extension: No module named 'pandas._libs.tslib' not built. If you want to import pandas from the source directory, you may need to run 'python setup.py build_ext --inplace --force' to build the C extensions first. I don't understand where I am making a mistake? I tried the answer here but it has led to a different issue: runfile('C:/Users/Berk DOĞUŞ/Spyder Projects/DogrusalRegresyon.py', wdir='C:/Users/Berk DOĞUŞ/Spyder Projects') Traceback (most recent call last): File "", line 1, in runfile('C:/Users/Berk DOĞUŞ/Spyder Projects/DogrusalRegresyon.py', wdir='C:/Users/Berk DOĞUŞ/Spyder Projects') File "C:\AConda\lib\site-packages\spyder\utils\site\sitecustomize.py", line 705, in runfile execfile(filename, namespace) File "C:\AConda\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile exec(compile(f.read(), filename, 'exec'), namespace) File "C:/Users/Berk DOĞUŞ/Spyder Projects/DogrusalRegresyon.py", line 12, in import pandas as pd File "C:\AConda\lib\site-packages\pandas__init__.py", line 40, in import pandas.core.config_init File "C:\AConda\lib\site-packages\pandas\core\config_init.py",…
tagged with: spyder
answer count: 1

http://stackoverflow.com/comment/90777485
comment on: http://stackoverflow.com/q/51913726
score: 1
has text: I don't know python, but you can try something like this `(?=hello)(?=from)(?=city)` which works in perl
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90689733
comment on: http://stackoverflow.com/q/51868926
score: 2
has text: You can remove the `respawn` directive if you don't want the service to automatically respawn.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90775936
comment on: http://stackoverflow.com/q/51902711
score: 0
has text: You asked about numpy arrays. The only hint that something in your code is a `pd.Series` is the `x_test.iloc`. And don't confuse `dtype` with `type`.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51948769
score: 3
upvote count: 3
has body: redis_time_cache = 180 # seconds cache.set(key, data, redis_time_cache) key = 'my_key' data = JSON or STRING redis_time_cache = TIMEOUT
answers question: http://stackoverflow.com/q/51948687
downvote count: 0
type: Answer

http://stackoverflow.com/q/51907237
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/90765817
favorite count: 0
has answer: http://stackoverflow.com/a/61015439
has comment: http://stackoverflow.com/comment/90765055
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90764884
tagged with: python
score: 2
has comment: http://stackoverflow.com/comment/90765572
has title: Django Sqlite3 programming error
upvote count: 2
tagged with: mysql
has comment: http://stackoverflow.com/comment/90765774
tagged with: django
has comment: http://stackoverflow.com/comment/90765801
type: Question
has body: I am very new to Django. I have created a sample project with Python v3.6 and Django V2.1. Initially, I have was using default sqlite3 database but now we have planned to change that into Mysql. For that, I have installed all the necessary plugin. On the other hand, I didn't create any table with sqlite3 except admin. It is working fine if it was in default database when I change that into MySQL I am getting error which I can't resolve for a week :-( System check identified no issues (0 silenced). Unhandled exception in thread started by &lt;function check_errors.&lt;locals&gt;.wrapper at 0x0000000003A93C80&gt; Traceback (most recent call last): File "C:\Users\ccduce\AppData\Local\Continuum\miniconda3\lib\site-packages\django\db\backends\base\base.py", line 2 16, in ensure_connection self.connect() File "C:\Users\ccduce\AppData\Local\Continuum\miniconda3\lib\site-packages\django\db\backends\base\base.py", line 1 94, in connect self.connection = self.get_new_connection(conn_params) File "C:\Users\ccduce\AppData\Local\Continuum\miniconda3\lib\site-packages\django\db\backends\mysql\base.py", line 227, in get_new_connection return Database.connect(**conn_params) File "C:\Users\ccduce\AppData\Local\Continuum\miniconda3\lib\site-packages\MySQLdb\__init__.py", line 86, in Connec t return Connection(*args, **kwargs) File "C:\Users\ccduce\AppData\Local\Continuum\miniconda3\lib\site-packages\MySQLdb\connections.py", line 204, in __ init__ super(Connection, self).__init__(*args, **kwargs2) _mysql_exceptions.OperationalError: (2059, "Authentication plugin 'caching_sha2_password' cannot be loaded: The speci fied module could not be found.\r\n") self.connect() File "C:\Users\ccduce\AppData\Local\Continuum\miniconda3\lib\site-packages\django\db\utils.py", line 89, in __exit_ _ raise dj_exc_value.with_traceback(traceback) from exc_value File "C:\Users\ccduce\AppData\Local\Continuum\miniconda3\lib\site-packages\django\db\backends\base\base.py", line 2 16, in ensure_connection self.c…
has comment: http://stackoverflow.com/comment/90765620
has comment: http://stackoverflow.com/comment/90765828

http://stackoverflow.com/a/51947463
has body: How about having the data in a smaller scope? class Application(): def __init__(self, data_file): self.use_read_data(DataReader(data_file).read()) After application is started, self.data_dictionary is no longer needed If you do not need the data for the whole lifetime of the application then you shouldn't be storing it in an instance attribute. Choose the right scope and you won't need to care about deleting variables.
type: Answer
answers question: http://stackoverflow.com/q/51946818
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/90964632
has comment: http://stackoverflow.com/comment/90967448
upvote count: 1

http://stackoverflow.com/comment/90599504
type: QuestionComment
has text: @OzeriossSmith these file names are stored in the log filles
score: 0
comment on: http://stackoverflow.com/q/51819714
type: Comment

http://stackoverflow.com/q/51875490
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/json
type: Question
has answer: http://stackoverflow.com/a/51875596
has body: I want to use " instead of '. countryid="be" msg = "{'field1': 'abc','field2': '"+countryid+"', 'field3': '1'}" I tried to use """ as follows: msg = """{"field1": "abc","field2": """"+countryid+"""", "field3": "1"}""" But then I get: {"field1": "abc","field2": +countryid+, "field3": "1"} instead of: {"field1": "abc","field2": "be", "field3": "1"}
has title: How to use " instead of ' to generate Json strings
possible better answer: http://stackoverflow.com/a/51875596
score: 0
answer count: 2
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51876538
accepted answer: http://stackoverflow.com/a/51876538
has comment: http://stackoverflow.com/comment/90702249
tagged with: python

http://stackoverflow.com/comment/90604147
comment on: http://stackoverflow.com/q/51818566
score: 1
type: Comment
type: QuestionComment
has text: Well, can you please tell me, your tensorflow version, protobuf version, and show me the content of your pbtxt?

jpype
tag name: jpype
tags question: http://stackoverflow.com/q/51869785
type: Tag

http://stackoverflow.com/comment/90566437
type: AnswerComment
comment on: http://stackoverflow.com/a/51805359
type: Comment
score: 0
has text: awesome. Thanks!

http://stackoverflow.com/comment/90641639
type: QuestionComment
comment on: http://stackoverflow.com/q/51844034
has text: @VeltzerDoron: `s1` is required to be a `set`.
score: 0
type: Comment

http://stackoverflow.com/q/51890024
has answer: http://stackoverflow.com/a/51896324
tagged with: google-api
type: AnsweredQuestion
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/51906173
tagged with: api
linked to: http://stackoverflow.com/q/24361060
has title: Python Google API resource limit error
tagged with: python-2.7
score: 0
tagged with: python
has body: I understand the resource limit, and that you can just wait it out and go again. So I made a code that runs until the limit is hit, then waits 6 minutes, runs again, etc. Just to test the time limit. Well sometimes that 6 minutes is enough, sometimes not. I need a consistent way to beat this resource limit. counter=0 try: for i in range(5000): # high enough to break limit client.open(google_sheet).sheet1 counter+=1 sleep(.02) print counter except Exception as e: print "ERROR" if re.search('"code": 429', str(e)): #confirms error is due to resource limit sleep(360) for i in range(5000): sheets_of_months[1].sheet_object counter+=1 sleep(.02) print counter I have it run until the error appears, wait 6 minutes, run again. The printing is just to avoid any pointless waiting. Thanks for reading and thanks for any and all responses!
possible better answer: http://stackoverflow.com/a/51896324
accepted answer: http://stackoverflow.com/a/51906173

http://stackoverflow.com/q/51948767
tagged with: loops
has title: Using a Loop and the Data Frame Style property in Python to Highlight Excel Column Cells
type: Question
tagged with: automation
has body: I'm trying to automate a simple process. What I want the code to do is to go through every article in 'Article URL' and check if the company listed under 'Sub-Category Name' is present in that article. If so, I want it to highlight the cell green, and if not, red. I managed to make it work on one cell (See Image 1). But then I tried to loop it through the entire spreadsheet. And for the life of me, I can't figure out why it's not working (See code below). The loop runs without any errors, but when I go to the document, it is not highlighted at all (See Image 2). I suspect it has something to do with the change to the spreadsheet not being saved after each loop. But how do you save a spreadsheet to a variable because the style application can only be viewed once the data frame is exported and saved as an xlsx. Thank you for your assistance in advance :) Image 1 Image 2 import pandas as pd import requests as rq path='/Users/mbongeni/Documents/Career/Internship/ProjectRunway/ProjectRunwayCopy.xlsx' df = pd.read_excel(path) #select following columns from df: dfR = df'Category Name','Sub-Category Name','Country','Article URL' #filter by online news coverage in column Category Name is_online = dfR['Category Name']=='Online News Coverage: Project Runway SA' dfR_online = dfR[is_online] #colour functions def cell_color_g(d): return 'background-color: green' def cell_color_r(d): return 'background-color: red' #test loop on first five rows: for i, site in enumerate(dfR_online[0:4]['Article URL']): #download site and check if strings in 'condition' are on site site_download = rq.get(site) condition = "Project Runway" in site_download.text \ and "South Africa" in site_download.text \ or "Project Runway SA" in site_download.text if condition: #color cell row i in column 'Article URL' green dfR_online.style.\ applymap(cell_color_g, subset=pd.IndexSlice[i,['Article URL']]) else: #color cell row i in column 'Article URL' red dfR_online.style.\ applymap(cell_color_r, subset=pd.In…
upvote count: 1
has comment: http://stackoverflow.com/comment/90847547
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: css
has comment: http://stackoverflow.com/comment/90851075
answer count: 0
downvote count: 0
score: 1
tagged with: dataframe

http://stackoverflow.com/q/51816869
type: Question
downvote count: 0
has comment: http://stackoverflow.com/comment/90588017
possible better answer: http://stackoverflow.com/a/51817120
tagged with: pandas
has answer: http://stackoverflow.com/a/51817120
has answer: http://stackoverflow.com/a/51817133
has comment: http://stackoverflow.com/comment/90588140
favorite count: 0
has body: data is in epoch nanoseconds as below the sample shows: time duration 1.530706769E+018 40000000000 1.53070683E+018 41000000000 1.530706891E+018 41000000000 1.530706951E+018 41000000000 1.530707011E+018 41000000000 1.530707068E+018 37000000000 1.530707128E+018 41000000000 1.530707188E+018 41000000000 1.530707248E+018 40000000000 1.530707313E+018 45000000000 1.530707368E+018 40000000000 1.530707432E+018 44000000000 1.530707492E+018 44000000000 1.530707552E+018 44000000000 1.530707612E+018 39000000000 1.530707673E+018 41000000000 1.530707729E+018 37000000000 1.530712952E+018 45000000000 1.530713007E+018 40000000000 1.530713067E+018 35000000000 1.530713132E+018 40000000000 1.530713187E+018 36000000000 1.530713248E+018 36000000000 1.530713308E+018 40000000000 1.530713369E+018 41000000000 1.530713429E+018 40000000000 1.53071349E+018 41000000000 1.530713551E+018 42000000000 1.530713611E+018 40000000000 1.530713671E+018 40000000000 1.530713732E+018 40000000000 1.530713792E+018 39000000000 1.530713852E+018 39000000000 1.530713913E+018 40000000000 1.530713973E+018 40000000000 1.530714029E+018 36000000000 1.53071409E+018 36000000000 1.530714151E+018 41000000000 1.530714212E+018 41000000000 1.530714272E+018 41000000000 1.530714332E+018 40000000000 1.530714393E+018 41000000000 1.530714454E+018 41000000000 1.530714515E+018 42000000000 1.530714574E+018 39000000000 1.53071463E+018 39000000000 1.530714694E+018 44000000000 1.530714753E+018 40000000000 1.530714814E+018 41000000000 1.530714874E+018 42000000000 1.530714934E+018 41000000000 1.530714995E+018 41000000000 1.530715056E+018 41000000000 1.530715112E+018 37000000000 1.530715245E+018 16000000000 1.530715275E+018 15000000000 1.530715305E+018 15000000000 1.530715335E+018 15000000000 1.530715366E+018 16000000000 1.530715396E+018 15000000000 1.530715427E+018 16000000000 1.530715456E+018 15000000000 1.530715487E+018 16000000000 1.530715517E+018 15000000000 1.530715548E+018 16000000000 1.530715578E+018 15000000000 To transform I used …
has title: KeyError: '[datetime.time(12, 19, 29) not in index'
tagged with: python
has answer: http://stackoverflow.com/a/51819022
has answer: http://stackoverflow.com/a/51817023
answer count: 4
type: AnsweredQuestion
score: 3
accepted answer: http://stackoverflow.com/a/51817133
upvote count: 3
tagged with: matplotlib

http://stackoverflow.com/comment/90608679
score: 0
type: Comment
type: QuestionComment
has text: How are you executing the file?
comment on: http://stackoverflow.com/q/51826384

http://stackoverflow.com/q/51813355
tagged with: gzip
has answer: http://stackoverflow.com/a/51813390
type: AnsweredQuestion
type: Question
has title: How to save tar file in flat tar.gz using Python
tagged with: python
accepted answer: http://stackoverflow.com/a/51813390
has body: I have a tar file with the following structure: example.tar --file1 --file2 and I want to save the file as tar.gz, so it will look like: example.tar.gz --file1 --file2 I tried to use TarFile.add() in tarfile module, but I only managed to create tar.gz file with another hierarchy. I managed to find only two solutions, which doesn't seems optimal: "un-tar" the file, and then put them in a new "tar.gz" file calling the following Unix command from the Python script gzip -c example.tar &gt; example.tar.gz Is there a batter way of doing it in Python?
score: 0
tagged with: http://stackoverflow.com/tag/tar
answer count: 1

http://stackoverflow.com/q/51851542
score: 0
answer count: 1
tagged with: initialization
tagged with: python-3.x
has answer: http://stackoverflow.com/a/51851626
type: UnansweredQuestion
has title: Is there a way to make a Meta Function / Meta initializer?
tagged with: python
has body: I wrote this little code while learning Meta classes that just registers all my class docs to a global var for all classes that have the given Meta Class: docs = {} def register_docs(cls): docs[cls.__name__] = cls.__doc__ class Meta(type): def __new__(meta, name, bases, class_dict): cls = type.__new__(meta, name, bases, class_dict) register_docs(cls) return cls class RegDocs(metaclass=Meta): ''' My Docs are here ''' def __init__(self): pass print(docs) {'RegDocs': '\n My Docs are here\n '} Is there a way to do something similar in __init__.py or have a "Meta Function" that can do this for a flat method file? I would like to be able to access a global that has information about methods similar to the example below, that does some initialization on methods before being called. func_info = {} @metafunc def foo(): """ My foo docs """ pass print(func_info) &gt; {'foo':'\n My foo docs\n '}
type: Question

http://stackoverflow.com/comment/90660625
type: AnswerComment
has text: Edited answer according to some code I found around, @UnaTripolla . Hope it helps
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51853979

http://stackoverflow.com/q/51897861
type: Question
has body: I am using Pyodbc to pull from a Microsoft SQL server. The REGEXP function in the SQL query is not being recognized. I'm not a strong SQL user but this seems pretty straight forward, I've tried many different syntax, nothing is working. The LIKE function worked for a single string, but I think it's different this regex. import pyodbc import pandas as pd if __name__ == '__main__': conn = None cursor = None try: conn = pyodbc.connect(r'DRIVER={ODBC Driver 17 for SQL Server};' ,SERVER='###########' ,DATABASE='####', UID='#####', PWD='#####') sql = "select top 5 * from dataset where (lower(variable) regexp '(^(total|)revenue(.|..|)$)') " data = pd.read_sql(sql,conn) print (data) except pyodbc.Error as e: print('ERR', e) finally: if cursor is not None: cursor.close() if conn is not None: conn.close() The returned error: pandas.io.sql.DatabaseError: Execution failed on sql 'select top 5 * from dataset where (lower(variable) regexp '(^(total|)revenue(.|..|)$)') ': ('42000', "[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Incorrect syntax near 'regexp'. (102) (SQLExecDirectW)") I don't have much info on the SQL server, but I am using python3.5. Update: I guess the answer is that REGEX is not supported on this server and a LIKE function is the only option. Thanks
has comment: http://stackoverflow.com/comment/90746729
linked to: http://stackoverflow.com/q/45698496
has comment: http://stackoverflow.com/comment/90750941
has title: Using Pyodbc with SQL server, regexp function not being recognized
has answer: http://stackoverflow.com/a/51898152
tagged with: sql
duplicate of: http://stackoverflow.com/q/45698496
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/90747902
favorite count: 0
tagged with: sql-server
has comment: http://stackoverflow.com/comment/90750994
has comment: http://stackoverflow.com/comment/90748320
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90748141
tagged with: python
tagged with: pyodbc
tagged with: regex
has comment: http://stackoverflow.com/comment/90758127
score: 1
upvote count: 1

http://stackoverflow.com/q/51803798
tagged with: flask
tagged with: http://stackoverflow.com/tag/html
answer count: 1
downvote count: 0
has title: Flask jinja variable breaking css
favorite count: 0
has answer: http://stackoverflow.com/a/51807030
upvote count: 1
tagged with: python
tagged with: css
type: AnsweredQuestion
score: 1
tagged with: jinja2
accepted answer: http://stackoverflow.com/a/51807030
type: Question
has body: I am working on a flask application, and am passing a variable back into the rendered html with this block of code: @app.route('/profile') @login_required def profile(): return render_template('profile.html', key = db.get_user_token(session['email'])) I want to use this passed key to render the key to the user on the template but it breaks the page when loading. Here are two images to show with the jinja template and without as well as the associated code. With: API Key {{key}} Generate Image of the output: with Without: API Key This is a bunch of text to show that it is not working when given a variable Generate Image of the output: Without

http://stackoverflow.com/a/51935570
downvote count: 0
type: Answer
score: 6
upvote count: 6
has comment: http://stackoverflow.com/comment/103415805
answers question: http://stackoverflow.com/q/51933300
has comment: http://stackoverflow.com/comment/90822528
has comment: http://stackoverflow.com/comment/90836185
has body: This is what I meant in the comments... fill everything that is black like the top-left corner, and connected to it, with white so that the bit you want is now entirely surrounded by white all the way to the edges. Then fill everything that is white and connected to the top-left corner with black. #!/usr/local/bin/python3 import numpy as np import cv2 from PIL import Image # Load image and greyscale it im = np.array(Image.open("framedcircles.jpg").convert('L')) # Normalize and threshold image im = cv2.normalize(im, None, alpha=0, beta=255, norm_type=cv2.NORM_MINMAX) res, im = cv2.threshold(im, 64, 255, cv2.THRESH_BINARY) # Fill everything that is the same colour (black) as top-left corner with white cv2.floodFill(im, None, (0,0), 255) # Fill everything that is the same colour (white) as top-left corner with black cv2.floodFill(im, None, (0,0), 0) # Save result Image.fromarray(im).save("result.png") Result:

http://stackoverflow.com/comment/97878122
type: Comment
comment on: http://stackoverflow.com/q/51874486
score: 15
has text: Any solution to this problem? I facing the same. VsCode v1.33 and happens with all extensions disabled as well.
type: QuestionComment

http://stackoverflow.com/comment/90862572
comment on: http://stackoverflow.com/q/51955647
has text: ahh, that was it. I reinstalled the boto plugins and that fixed it. Phew! Thanks @abarnert. can you post as an answer?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51798913
tagged with: pivot-table
linked to: http://stackoverflow.com/q/27263805
upvote count: 1
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51799156
score: 1
has title: In pandas, how to count items between commas, dividing between column types?
type: Question
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/90554504
favorite count: 0
accepted answer: http://stackoverflow.com/a/51799156
possible better answer: http://stackoverflow.com/a/51799142
has answer: http://stackoverflow.com/a/51799142
tagged with: pandas
tagged with: python
has body: In python3 and pandas I have this dataframe: df_selecao_atual.info() &lt;class 'pandas.core.frame.DataFrame'&gt; Int64Index: 340 entries, 2 to 678 Data columns (total 26 columns): cpf 339 non-null object nome 340 non-null object nome_completo 340 non-null object partido 339 non-null object uf 339 non-null object cargo_parlamentar 340 non-null object tipo 340 non-null object classe 340 non-null object numero 340 non-null object único 340 non-null object assunto 340 non-null object data_inicial 340 non-null object data_final 340 non-null object andamento 340 non-null object link 340 non-null object transparencia 339 non-null object conferencia 339 non-null object data_conferencia 339 non-null object resumo 332 non-null object observacao 311 non-null object link_noticia_tribunal_confiavel 104 non-null object interessa 337 non-null object ministro_relator 339 non-null object processo_conectado 44 non-null object situacao 337 non-null object cadastro_push 337 non-null object dtypes: object(26) memory usage: 71.7+ KB Each line of this dataframe has information about legal proceedings, one court case per line The column "nome" has names of people, such as: FULANO DE TAL BELTRANO DA SILVA SICRANO APARECIDO NINGUEM AUGUSTO The "tipo" column has the types of lawsuits, only two types: INQ AP And column "resumo" has crimes investigated for prosecution in court proceedings. But each legal process may one or more crimes. And the crimes are separated by ",": Peculato, Lavagem de Dinheiro Corrupção passiva, Ocultação de bens, Lavagem de dinheiro Corrupção passiva, Lavagem de dinheiro, Crimes Eleitorais Crimes Eleitorais, Lavagem de dinheiro Peculato Quadrilha ou Bando, Crimes da Lei de licitações, Peculato I need to count: In each name Divided by INQ and AP processes The appearance of each individual crime between "," Taking the example above the "resumo" column, something like this: Peculato, Lavagem de dinheiro Corrupção passiva, Ocultação de bens, Lavagem de dinheiro Corrupção p…

http://stackoverflow.com/a/51849050
accepted answer of: http://stackoverflow.com/q/51836421
type: Answer
answers question: http://stackoverflow.com/q/51836421
has body: from blog import blogRoute from admin import adminRoute from news import newsRoute from utils import utilsRoute botapp = bottle.app() for approute in (blogRoute, adminRoute, newsRoute, utilsRoute): botapp.merge(approute) And in each of your python files, you just need this at the top: blog.py for example from bottle import Bottle blogRoute = Bottle()
score: 4
upvote count: 4
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/51875232
has comment: http://stackoverflow.com/comment/90747610
accepted answer of: http://stackoverflow.com/q/51873797
has comment: http://stackoverflow.com/comment/90875060
has body: As suggested by @Matin, you could consider Bresenham's algorithm to get your points on the AC line. A simplistic PyTorch implementation could be as follows (directly adapted from the pseudo-code here ; could be optimized): import torch def get_points_from_low(x0, y0, x1, y1, num_points=3): dx = x1 - x0 dy = y1 - y0 xi = torch.sign(dx) yi = torch.sign(dy) dy = dy * yi D = 2 * dy - dx y = y0 x = x0 points = [] for n in range(num_points): x = x + xi is_D_gt_0 = (D &gt; 0).long() y = y + is_D_gt_0 * yi D = D + 2 * dy - is_D_gt_0 * 2 * dx points.append(torch.stack((x, y), dim=-1)) return torch.stack(points, dim=len(x0.shape)) def get_points_from_high(x0, y0, x1, y1, num_points=3): dx = x1 - x0 dy = y1 - y0 xi = torch.sign(dx) yi = torch.sign(dy) dx = dx * xi D = 2 * dx - dy y = y0 x = x0 points = [] for n in range(num_points): y = y + yi is_D_gt_0 = (D &gt; 0).long() x = x + is_D_gt_0 * xi D = D + 2 * dx - is_D_gt_0 * 2 * dy points.append(torch.stack((x, y), dim=-1)) return torch.stack(points, dim=len(x0.shape)) def get_points_from(x0, y0, x1, y1, num_points=3): is_dy_lt_dx = (torch.abs(y1 - y0) &lt; torch.abs(x1 - x0)).long() is_x0_gt_x1 = (x0 &gt; x1).long() is_y0_gt_y1 = (y0 &gt; y1).long() sign = 1 - 2 * is_x0_gt_x1 x0_comp, x1_comp, y0_comp, y1_comp = x0 * sign, x1 * sign, y0 * sign, y1 * sign points_low = get_points_from_low(x0_comp, y0_comp, x1_comp, y1_comp, num_points=num_points) points_low *= sign.view(-1, 1, 1).expand_as(points_low) sign = 1 - 2 * is_y0_gt_y1 x0_comp, x1_comp, y0_comp, y1_comp = x0 * sign, x1 * sign, y0 * sign, y1 * sign points_high = get_points_from_high(x0_comp, y0_comp, x1_comp, y1_comp, num_points=num_points) * sign points_high *= sign.view(-1, 1, 1).expand_as(points_high) is_dy_lt_dx = is_dy_lt_dx.view(-1, 1, 1).expand(-1, num_points, 2) points = points_low * is_dy_lt_dx + points_high * (1 - is_dy_lt_dx) return points # Inputs: # (@todo: extend A to cover all points in maps): A = torch.LongTensor([[0, 1], [8, 6]]) C = torch.LongTensor([[6…
type: Answer
has comment: http://stackoverflow.com/comment/90745558
has comment: http://stackoverflow.com/comment/90783534
has comment: http://stackoverflow.com/comment/90774131
answers question: http://stackoverflow.com/q/51873797
has comment: http://stackoverflow.com/comment/90706293
has comment: http://stackoverflow.com/comment/90703258
has comment: http://stackoverflow.com/comment/90772608
score: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/91497400
type: Comment
type: QuestionComment
has text: Thank you, this has been very helpful. Also, is there a way for the user to modify the 'text=' variable within pdf.drawString(x=100, y=727, text='Midland REalty Pty Ltd') straight from user input in the GUI? Could you please give an example of the code for this?
comment on: http://stackoverflow.com/q/51905249
score: 0

http://stackoverflow.com/q/51847674
tagged with: sequence
favorite count: 0
type: UnansweredQuestion
tagged with: python
answer count: 0
tagged with: pytorch
score: 1
has title: Re-encoding a context vector after every step of decoding?
has body: I am currently working on a sequence model which aims to predict the head orientation of somebody watching VR for an arbitrary amount of frames in the future. Using an encoder-decoder paradigm, a person's previous 100 frames of head orientation and the video's previous 100 frames of data are fed into an encoder to create a context. (100 is arbitrary here, but for sake of writing I will use 100 frames, so the previous sequence's data will be [ T(-100) - T0 ] ) The context is then fed into the decoder, and frame by frame outputting a probability distribution of where the viewer will be looking at T1 for the first iteration of decoding, T2 for the second iteration, etc. The context vector therefore has a lot of weight on its shoulders, encoding data from the entire previous sequence. So in order to help with the decoder's output, at each step of decoding I want to let the decoder have access to the video's future 100 frames of data. So at time T2, the decoder will be on its second iteration and have access to the 102nd video frame to use for convolution, saliency, etc. The way we were thinking to accomplish this is to have the encoder re-encode the context vector on each iteration of decoding the context, and replacing the encoder's input to contain the future video frame data. So for example on the second iteration of decoding, we would re-encode the context, but replace the data for T(-100) with the decoded output for T1, and the video frame for T(-100) with the video frame for T2. We would continue to iterate through decoding in this way. The thought is this would be a way to provide the decoder with information about the upcoming video, and use its previous predictions to enforce the integrity of future predictions of movement. This idea of re-encoding the context was also presented by Johannes Baptist from the University of Amsterdam in this paper, though I am an undergraduate student and still new to this field, so the paper was a bit challenging to grasp. If any…
upvote count: 1
type: Question
tagged with: lstm
tagged with: encoder-decoder
downvote count: 0

http://stackoverflow.com/comment/90708272
score: 0
type: Comment
type: QuestionComment
has text: I've added a full dataset; however you could always use these data multiple times to emulate multiple subs (obviously). If you do - it would perhaps be a good idea to include more (fake) values, to force different/new positions to be used ie. replace some NaNs with values.
comment on: http://stackoverflow.com/q/51876744

http://stackoverflow.com/q/51888649
accepted answer: http://stackoverflow.com/a/51888798
has body: I have a large number of files in one folder (about 2 million files), I would like to combine every 50 files into one. the code below combines all into one. I can't come about a way to combine every 50 files into one and also ensure that any number over the multiplication of 50 is also combined into one file. For example, if the number of files is 2,000,034 then I end up with many files of 50 combined files and one file that has the last 34 files. from glob import iglob import shutil import os PATH = r'C:\Test' destination = open('allcontents.sh', 'wb') for file in iglob(os.path.join(PATH, '*.sh')): shutil.copyfileobj(open(file, 'rb'), destination) destination.close()
possible better answer: http://stackoverflow.com/a/51910794
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/51910936
tagged with: shutil
has answer: http://stackoverflow.com/a/51888798
tagged with: python
type: AnsweredQuestion
type: Question
has title: Combine every number of files in a folder into one file
has answer: http://stackoverflow.com/a/51910794
tagged with: os.path

http://stackoverflow.com/comment/90776450
type: QuestionComment
has text: You are not gonna want to use regex for removing whitespace and linebreaks in python. Just do `string.replace(" ", "")` and `string.replace("\n", "")`
comment on: http://stackoverflow.com/q/51913142
score: 0
type: Comment

http://stackoverflow.com/q/51946721
tagged with: google-analytics-api
tagged with: google-analytics
type: Question
answer count: 1
has comment: http://stackoverflow.com/comment/90842998
has body: I've got an analytics reporting api v4 script in Python which returns to me the sessions for certain landing pages and which city the sessions have come from. Is there a way to limit this to only the top 50 city locations per landing page for sessions so I don't get returned the city's that are landing on them which have like 1 session for example. Here is the base code for the analytics request: api_client = google_build(serviceName=api_name, version=api_version, http=authorized) for i in developments: sample_request = { 'viewId': '6690350', 'pageSize': 100000, 'dateRanges': { 'startDate': datetime.strftime(datetime.now() - timedelta(days = 30),'%Y-%m-%d'), 'endDate': datetime.strftime(datetime.now(),'%Y-%m-%d') }, 'metrics': [{'expression': 'ga:sessions'}], 'orderBys': [ {'fieldName': 'ga:pagePath', 'sortOrder': 'ASCENDING'}, {'fieldName': 'ga:sessions', 'sortOrder': 'DESCENDING'} ], 'dimensions': [{'name': 'ga:pagePath'},{'name': 'ga:city'},{'name': 'ga:latitude'},{'name': 'ga:longitude'}], 'dimensionFilterClauses' : [ {
has comment: http://stackoverflow.com/comment/90843057
tagged with: python-3.x
has title: How to get Top 50 Sessions from Google Analytics Reporting API v4 Python
type: UnansweredQuestion
score: 0
has answer: http://stackoverflow.com/a/51947104
tagged with: python

http://stackoverflow.com/comment/90567889
comment on: http://stackoverflow.com/q/51805995
type: Comment
type: QuestionComment
score: 1
has text: you probably have multiple installations of `python`. The one that you installed `pandas` in is not the interpreter used in VS Code. Try [this](https://code.visualstudio.com/docs/python/environments)

http://stackoverflow.com/a/51972455
type: Answer
has body: I'm still getting that error despite changing my requirements.txt file to: Django>=2 psycopg2 Any other suggestions? I've pretty much run out of ideas. I've been using https://docs.docker.com/compose/django/#connect-the-database. So far as I can tell I've done everything by the book according to that web page.
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/51915687
upvote count: 1

http://stackoverflow.com/q/51817286
score: 1
type: Question
has answer: http://stackoverflow.com/a/51984905
accepted answer: http://stackoverflow.com/a/51984905
upvote count: 2
tagged with: wrapper
tagged with: api
downvote count: 1
answer count: 1
favorite count: 0
has body: I would like to use rozzac90/pinnacle API python wrapper github project for placing automated bet on Pinnacle. I would like to know, what is the best method for getting the actual main market for an event, if I know the home and away team names. I'm using something like this in order to get the markets: soccer_events = api.market_data.get_fixtures(29) for league in soccer_events[u'league']: for event in league[u'events']: if event[u'status'] == 'I': fixtures[i].append(league[u'id']) fixtures[i].append(event[u'id']) fixtures[i].append(event[u'home']) fixtures[i].append(event[u'away']) fixtures.append([]) i=i+1 After that I cycle through the home and away elements for names, and select the best matching. BUT Sometimes if I get the right home and away names the corresponding eventid is not always valid, and that is my main problem. I discovered that there could be multiple eventids associated with the same team names in different fixtures[] location. Anybody could help me filter only the right and actual events? Best Regards
tagged with: python
has title: How to query actual markets with Python Wrapper for Pinnacle Sports API
type: AnsweredQuestion

http://stackoverflow.com/a/51944690
has comment: http://stackoverflow.com/comment/90839033
has comment: http://stackoverflow.com/comment/90838918
type: Answer
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/51944627
has comment: http://stackoverflow.com/comment/90838962
has body: It basically does nothing. It is often used as a placeholder like in your code; you'll notice that the code does not run at all without the pass there. class SomeClass: pass # to be filled This is because Python expects something to be under the definition of SomeClass, but being empty it raises an IndentationError. class SomeClass: # to be filled &lt;--- empty other_function() # &lt;--- IndentationError It is also used with try-except when you do not want to do anything: try: some_stuff() except SomeException: pass # I don't mind this
has comment: http://stackoverflow.com/comment/90838892
upvote count: 2

http://stackoverflow.com/a/51816066
type: Answer
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/90586760
has body: Python doesn't use static type-casting. So the short answer is No, Python doesn't know what type of variable is being passed into your function. There is a way to check manually however, using the isinstance() function. isinstance(your_var, type); returns True or False. Here is an example that relates to the function you are building. if isinstance(a_list, list) or isinstance(a_list, tuple): Your code else: Return bad var type In addition, there is a way to recommend to the user the type of the variable the function expects to take, using this syntax: def minOfList(a_list: list): return This lets the user know what type they should be passing in. Be cautioned however, this does not force the parameter type - the use can still pass in any variable. Hope this helps!
has comment: http://stackoverflow.com/comment/90586992
has comment: http://stackoverflow.com/comment/90642286
upvote count: 2
answers question: http://stackoverflow.com/q/51816005
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51816005

http://stackoverflow.com/comment/90844497
type: Comment
type: QuestionComment
has text: Yes this is true. But I don't know what should be written in that django view so that it can execute the script on server and return the result as httpresponse.
comment on: http://stackoverflow.com/q/51946946
score: 0

http://stackoverflow.com/comment/90825411
score: 0
type: Comment
type: QuestionComment
has text: I edited the original post let me know if that is good enough or if I need to do something else.
comment on: http://stackoverflow.com/q/51935797

http://stackoverflow.com/a/51876129
score: 1
upvote count: 1
downvote count: 0
answers question: http://stackoverflow.com/q/51871937
type: Answer
has body: From the cli you can use following command redis-cli info Sample Output # Server redis_version:4.0.1 redis_git_sha1:00000000 redis_git_dirty:0 redis_build_id:f37081b32886670b redis_mode:standalone os:Darwin 16.7.0 x86_64 arch_bits:64 multiplexing_api:kqueue atomicvar_api:atomic-builtin gcc_version:4.2.1 or if you need version you can try with pipe cmd redis-cli info | grep "redis_version" Output redis_version:4.0.1 i hope this will help

http://stackoverflow.com/a/51873777
type: Answer
has comment: http://stackoverflow.com/comment/90701926
score: 1
has comment: http://stackoverflow.com/comment/90699647
has body: I think this may help you: locale.setlocale(LC_NUMERIC, 'nl-NL') # set to a locale where the comma is used as decimal point for row in reader: data1.append(float(locale.atof(row[0]))) resistance_values = np.array(data1) instead of float() you could also try decimal() If float() still does too much rounding.
upvote count: 1
answers question: http://stackoverflow.com/q/51873354
downvote count: 0
has comment: http://stackoverflow.com/comment/90701836

http://stackoverflow.com/comment/90878248
comment on: http://stackoverflow.com/a/51963439
type: AnswerComment
has text: @Isma Its traversing inside folders and subfolders inside the current directory . It can be used with function so that file ext can be passed as per our need. I found it easy to use without much code, please test from your end as well.Your time and answer is much appreciated also, I am marking it as a solution.
score: 0
type: Comment

http://stackoverflow.com/comment/90733100
has text: but i need "Variable" in the output columns with fiscal_week_id.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51891000

http://stackoverflow.com/q/51857274
type: UnansweredQuestion
has title: How can I load and use a PyTorch (.pth.tar) model
downvote count: 2
tagged with: python
score: 11
upvote count: 13
has answer: http://stackoverflow.com/a/51880724
tagged with: pytorch
type: Question
has body: I am not very familiar with Torch, and I primarily use Tensorflow. I, however, need to use a retrained inception model that was retrained in Torch. Due to the large amount of computing resources required to retrain an inception model for my particular application, I would like to use the model that was already retrained. This model is saved as a .pth.tar file. I would like to be able to first load this model. So far, I have been able to figure out that I must use the following: model = torch.load('iNat_2018_InceptionV3.pth.tar', map_location='cpu') This seems to work, because print(model) prints out a large set of numbers and other values, which I presume are the values for the weights an biases. After this, I need to be able to classify an image with it. I haven't been able to figure this out. How must I format the image? Should the image be converted into an array? After this, how must I pass the input data to the network?
tagged with: neural-network
tagged with: torch
linked to: http://stackoverflow.com/q/53844826
answer count: 1
has comment: http://stackoverflow.com/comment/94571352
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/comment/90774178
has text: Yes, https://www.jetbrains.com/pycharm/ for example
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51910960

http://stackoverflow.com/a/51965666
upvote count: 2
type: Answer
score: 2
has body: You can commit outside the loop: for table in table_names: cursor.execute("INSERT INTO public.{0} VALUES(CURRENT_TIMESTAMP, 999999)".format(table)) cursor.connection.commit() However, there is a side effect. First columns (timestamps) will have different values when committed separately in contrast to the same value when committed together. This is because CURRENT_TIMESTAMP gives the time of the start of transaction.
accepted answer of: http://stackoverflow.com/q/51941780
answers question: http://stackoverflow.com/q/51941780
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/51802854
has title: How do I import a text file into a SQLite3 table using python
has comment: http://stackoverflow.com/comment/90563135
type: Question
has body: I currently have a txt file of movies which contain a movieID,Movie Name, and genre. Example: 1,Toy Story (1995),Animation|Children's|Comedy 2,Jumanji (1995),Adventure|Children's|Fantasy 3,Grumpier Old Men (1995),Comedy|Romance 4,Waiting to Exhale (1995),Comedy|Drama 5,Father of the Bride Part II (1995),Comedy I am trying to import this file into a SQLite3 table created with Python: import sqlite3 conn = sqlite3.connect('CSC 452 Final.db') c=conn.cursor() Drop Tables c.execute('''DROP TABLE IF EXISTS temp_movie''') print("Table temp_movie dropped.") Create Table for Movies c.execute('''CREATE TABLE temp_movie ( MovieID NUMERIC (5), movie_title_year VARCHAR2 (255), movie_categories VARCHAR2 (255), CONSTRAINT movies_movieID_PK PRIMARY KEY ( MovieID ))''') print("Table temp_movie successfully created.") conn.commit() What's the best way to import my text file into this database with the delimiter being ','?
answer count: 2
has answer: http://stackoverflow.com/a/51802906
score: 0
tagged with: sqlite
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51802927

eclipse
tag name: eclipse
tags question: http://stackoverflow.com/q/51815161
type: Tag

http://stackoverflow.com/q/51939022
tagged with: dataset
tagged with: deep-learning
accepted answer: http://stackoverflow.com/a/51967955
answer count: 1
downvote count: 0
has body: I am attempting to train an RNN on time series data, and while there are plenty of tutorials out there on how to build a RNN model I am having some trouble with building the dataloader object for this task. The data is all going to be the same length, so no need for padding as well. The approach I have taken so far is to return a range of data in the getitem function on the dataset class and define the length as len(data) - seq_len + 1 , however I feel that this is a bit "hacky" and that there should be a more proper way to do this. This method seems confusing and I feel that this would cause problems if collaborating with a group. More specifically, I think that somehow overriding the sampler function in the Pytorch Dataset constructor is the correct way, but I am having trouble understanding how to implement that. Below is the current dataset class I have built, can anyone point me in the right direction with how to fix it? Thank you in advance. class CustomDataset(Dataset): def __init__(self, df, cats, y, seq_l): self.n, self.seq_l = len(df), seq_l self.cats = np.array(np.stack([c.values for n,c in df[cats].items()], 1).astype(np.int64)) self.conts = np.array(np.stack([c.values for n,c in dfi for i in df.columns if i not in cats.items()], 1).astype(np.float32)) self.y = np.array(y) def __len__(self): return len(self.y) - self.seq_l + 1 def __getitem__(self, idx): return [ (torch.from_numpy(self.cats[idx:idx+self.seq_l]), torch.from_numpy(self.conts[idx:idx+self.seq_l])), self.y[idx+self.seq_l-1] ]
favorite count: 0
tagged with: python
type: AnsweredQuestion
score: 3
has title: Correct way to create Pytorch dataset that returns sequence of data for RNN?
tagged with: pytorch
upvote count: 3
has answer: http://stackoverflow.com/a/51967955
tagged with: recurrent-neural-network
type: Question

http://stackoverflow.com/comment/90871503
comment on: http://stackoverflow.com/a/51953596
type: Comment
score: 0
has text: Loop through x["items"] as Kevin has shown, and assign them to a string.
type: AnswerComment

http://stackoverflow.com/comment/90601630
has text: which python version are using?
score: 0
comment on: http://stackoverflow.com/q/51823780
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51817352
type: UnansweredQuestion
tagged with: plpython
tagged with: python
score: 2
upvote count: 2
type: Question
tagged with: postgresql-10
has title: Pl\Python: issues when importing module
downvote count: 0
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/62695589
has body: I have successfully setup plpyton3u extension in Postgresql 10 (64 bit) on my windows 10 (64 bit) machine. However, when i try to make a http request by calling requests module I am getting attribute error AttributeError: 'module' object has no attribute 'get' . Here is the code that I am using CREATE OR REPLACE FUNCTION from_url( -- The URL to download. IN url text, -- Should any errors (like HTTP transport errors) -- throw an exception or simply return default_response IN should_throw boolean DEFAULT true, -- The default response if any errors are found. -- Only used when should_throw is set to true IN default_response text DEFAULT E'' ) RETURNS text AS $$ # We will use traceback so we get decent error reporting. import requests import traceback # Either throws an error or returns the defeault response # depending on the should_throw parameter of the from_url() function def on_error(): if should_throw: # plpy.error() throws an exception which stops the current transaction plpy.error("Error downloading '{0}'\n {1}".format(url, traceback.format_exc())) else: return default_response try: response = requests.get(url) return response.data except: # Log and re-throw the error or return the default response return on_error() $$ LANGUAGE plpython3u VOLATILE; select from_url(&lt;SOME_DATA_FETCHING_URL&gt;); Where SOME_DATA_FETCHING_URL is the url of the server serving the data. When I run this code it throws following error ERROR: plpy.Error: Error downloading SOME_DATA_FETCHING_URL Traceback (most recent call last): File "", line 16, in __plpython_procedure_from_url_24640 AttributeError: 'module' object has no attribute 'get' CONTEXT: Traceback (most recent call last): PL/Python function "from_url", line 19, in return on_error() PL/Python function "from_url", line 11, in on_error plpy.error("Error downloading '{0}'\n {1}".format(url, traceback.format_exc())) PL/Python function "from_url" SQL state: XX000 my PYTHONPATH is set to C:\Python34\;C:\Python34\Scripts;C:\Python34…

http://stackoverflow.com/a/51847687
has body: Your problem is that the page doesn't contain those span elements in first place. If you check the response tab in your browser developer tools (press F12 in firefox) you can see that the page is composed of script tags with some code written in javascript that creates the elements dynamically when executed. Since BeautifulSoup can't execute Javascript, you can't extract the elements directly with it. You have two alternatives: Use something like selenium that allows you to drive a browser from python - that means javascript will be executed because you're using a real browser - however the performance suffers. Read the javascript code, understand it and write python code to simulate it. This usually is harder but luckly for you this seem very simple for the page you want: import requests import lxml.html r = requests.get('https://www.bitmex.com/app/trade/XBTUSD') doc = lxml.html.fromstring(r.text) data = json.loads(doc.xpath("//script[@id='initialData']/text()")[0]) As you can see the data is in json format inside the page. After loading the data variable you can use it to access the infomation you want: for row in data['orderBook']: print(row['symbol'], row['price'], row['side']) Will print: ('XBTUSD', 6051.5, 'Sell') ('XBTUSD', 6051, 'Sell') ('XBTUSD', 6050.5, 'Sell') ('XBTUSD', 6050, 'Sell')
downvote count: 0
has comment: http://stackoverflow.com/comment/90649435
has comment: http://stackoverflow.com/comment/90649991
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/51847199
score: 1

http://stackoverflow.com/q/51840865
score: 0
answer count: 1
tagged with: dummy-variable
tagged with: feature-extraction
has title: Using hashing trick for new incoming data
tagged with: pandas
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51850865
type: Question
tagged with: one-hot-encoding
accepted answer: http://stackoverflow.com/a/51850865
has body: Is there anyway of using hashing trick after I train and deploy my model? Assume I have the following data and I tased the Cat feature as follows: from sklearn.feature_extraction import FeatureHasher D = {"ID": [1,2,3,4,5,6,7,8,9,10], "Cat": ["A", "A", "B", "A", "A", "B", "A", "B", "B", "B"]} df = pd.DataFrame(D) fh = FeatureHasher(n_features=1, input_type='string') hashed_features = fh.fit_transform(df['Cat']) hashed_features.toarray() How can use the taser to hash incoming new data? I am looking for something like: fh.predict('A') Should I just build a dictionary from the hashing process during training and then just map the new incoming data to the build dictionary? Is there a better way?
tagged with: python

http://stackoverflow.com/q/51916233
has answer: http://stackoverflow.com/a/51916311
upvote count: 3
type: UnansweredQuestion
type: Question
has answer: http://stackoverflow.com/a/51916543
score: 3
has title: How to print the problematic row in exception
answer count: 2
downvote count: 0
favorite count: 0
tagged with: pandas
has body: I'm using Pandas in my code and while manipulating some data frame using the code below: def exit(exitCode, errorMsg=None, monitor_thread=None): if exitCode is not None: logger.error(errorMsg) logger.error(traceback.format_exc()) sys.exit(exitCode) try: results['name'] = results['name'].astype(float).astype(int) except Exception as e: # catch *all* exceptions exit("Failed to convert name" + str(e), 8) I get this error: Traceback (most recent call last): File "DIST\FDmanInfo.py", line 206, in File "DIST\FDmanInfo.py", line 191, in main File "\local\Python\lib\site-packages\pandas\core\generic.py", line 3054, in astype raise_on_error=raise_on_error, **kwargs) File "\local\Python\lib\site-packages\pandas\core\internals.py", line 3189, in astype return self.apply('astype', dtype=dtype, **kwargs) File "\local\Python\lib\site-packages\pandas\core\internals.py", line 3056, in apply applied = getattr(b, f)(**kwargs) File "\local\Python\lib\site-packages\pandas\core\internals.py", line 461, in astype values=values, **kwargs) File "\local\Python\lib\site-packages\pandas\core\internals.py", line 504, in _astype values = _astype_nansafe(values.ravel(), dtype, copy=True) File "\local\Python\lib\site-packages\pandas\types\cast.py", line 531, in _astype_nansafe raise ValueError('Cannot convert NA to integer') ValueError: Cannot convert NA to integer and I want to know which row is doing the problem, but I can't find out anywhere how on exception to print it (the row) to log, like it the input dataframe is: name 0 1.0 1 NaN 2 3.0 3 4.0 I want it to print on the row it fails on, in this case "1 NaN", is it even possible? Thanks,
tagged with: python

http://stackoverflow.com/a/51949451
has comment: http://stackoverflow.com/comment/90848997
type: Answer
upvote count: 0
has body: I found some interesting topic on the internet saying that you could speed it up by 5x-9x: Taken from here I've noticed that os.walk() is a lot slower than it needs to be because it does an os.stat() call for every file/directory. It does this because it uses listdir(), which doesn't return any file attributes. So instead of using the file information provided by FindFirstFile() / FindNextFile() and readdir() -- which listdir() calls -- os.walk() does a stat() on every file to see whether it's a directory or not. Both FindFirst/FindNext and readdir() give this information already. Using it would basically bring the number of system calls down from O(N) to O(log N). I've written a proof-of-concept (see [1] below) using ctypes and FindFirst/FindNext on Windows, showing that for sizeable directory trees it gives a 4x to 6x speedup -- so this is not a micro-optimization! I started trying the same thing with opendir/readdir on Linux, but don't have as much experience there, and wanted to get some feedback on the concept first. I assume it'd be a similar speedup by using d_type &amp; DT_DIR from readdir(). The problem is even worse when you're calling os.walk() and then doing your own stat() on each file, for example, to get the total size of all files in a tree -- see [2]. It means it's calling stat() twice on every file, and I see about a 9x speedup in this scenario using the info FindFirst/Next provide. So there are a couple of things here: 1) The simplest thing to do would be to keep the APIs exactly the same, and get the ~5x speedup on os.walk() -- on Windows, unsure of the exact speedup on Linux. And on OS's where readdir() doesn't return "is directory" information, obviously it'd fall back to using the stat on each file. 2) We could significantly improve the API by adding a listdir_stat() or similar function, which would return a list of (filename, stat_result) tuples instead of just the names. That might be useful in its own right, but of course os.walk() could us…
answers question: http://stackoverflow.com/q/51948306
score: -2
downvote count: 2
has comment: http://stackoverflow.com/comment/90848740

http://stackoverflow.com/a/51881060
type: Answer
has body: There are a lot of options for creating a pdf in python. Some of these options are ReportLab, pydf2, pdfdocument and FPDF. The FPDF library is fairly stragihtforward to use and is what I've used in this example. FPDF Documentation can be found here. It's perhaps also good to think about what python modules you might want to use to create graphs and tables. In my example, I use matplotlib (link to docs) and I also use Pandas to create a dataframe using pandas.dataframe(). I've posted a rather lengthy but fully reproducible example below, using pandas, matplotlib and fpdf. The data are a subset of what the OP provided in the question. I loop through the dataframe in my example to create the table, but there are alternative and perhaps more efficient ways to do this. import pandas as pd import matplotlib from pylab import title, figure, xlabel, ylabel, xticks, bar, legend, axis, savefig from fpdf import FPDF df = pd.DataFrame() df['Question'] = ["Q1", "Q2", "Q3", "Q4"] df['Charles'] = [3, 4, 5, 3] df['Mike'] = [3, 3, 4, 4] title("Professor Criss's Ratings by Users") xlabel('Question Number') ylabel('Score') c = [2.0, 4.0, 6.0, 8.0] m = [x - 0.5 for x in c] xticks(c, df['Question']) bar(m, df['Mike'], width=0.5, color="#91eb87", label="Mike") bar(c, df['Charles'], width=0.5, color="#eb879c", label="Charles") legend() axis([0, 10, 0, 8]) savefig('barchart.png') pdf = FPDF() pdf.add_page() pdf.set_xy(0, 0) pdf.set_font('arial', 'B', 12) pdf.cell(60) pdf.cell(75, 10, "A Tabular and Graphical Report of Professor Criss's Ratings by Users Charles and Mike", 0, 2, 'C') pdf.cell(90, 10, " ", 0, 2, 'C') pdf.cell(-40) pdf.cell(50, 10, 'Question', 1, 0, 'C') pdf.cell(40, 10, 'Charles', 1, 0, 'C') pdf.cell(40, 10, 'Mike', 1, 2, 'C') pdf.cell(-90) pdf.set_font('arial', '', 12) for i in range(0, len(df)): pdf.cell(50, 10, '%s' % (df['Question'].iloc[i]), 1, 0, 'C') pdf.cell(40, 10, '%s' % (str(df.Mike.iloc[i])), 1, 0, 'C') pdf.cell(40, 10, '%s' % (str(df.Charles.iloc[i])), 1, 2, 'C')…
has comment: http://stackoverflow.com/comment/95550990
has comment: http://stackoverflow.com/comment/112130254
downvote count: 0
has comment: http://stackoverflow.com/comment/95553328
has comment: http://stackoverflow.com/comment/108399628
has comment: http://stackoverflow.com/comment/107633544
has comment: http://stackoverflow.com/comment/95536130
has comment: http://stackoverflow.com/comment/95556730
score: 76
accepted answer of: http://stackoverflow.com/q/51864730
has comment: http://stackoverflow.com/comment/108009969
answers question: http://stackoverflow.com/q/51864730
has comment: http://stackoverflow.com/comment/108139027
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/95534635
upvote count: 76

http://stackoverflow.com/a/51921522
has comment: http://stackoverflow.com/comment/90793186
type: Answer
answers question: http://stackoverflow.com/q/51921510
has comment: http://stackoverflow.com/comment/90793213
score: 2
downvote count: 0
upvote count: 2
has body: for num in num_tuple means iterate over num_tuple and set each value to num. num isn't the index of the tuple. def multiply_squares(*num_tuple): result = [] for num in num_tuple: c = num**2 result.append(c) d = 1 for i in result: d *= i print(d) return d multiply_squares(3,2,1) multiply_squares(2,5) Regarding recursive solution: def multiply_squares(*num_tuple): if not num_tuple: # Base case: return 1 return (num_tuple[0] ** 2) * multiply_squares(*num_tuple[1:])
has comment: http://stackoverflow.com/comment/90792931

http://stackoverflow.com/a/51843189
type: Answer
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/51843015
downvote count: 0
has comment: http://stackoverflow.com/comment/90640048
has body: If it is not appearing in pycharm then you can add the path. Go to Settings>Project interpreter>Virtualenv Environment>...>add. Then make sure you path to python 3.6. Also do the same thing for System interpreter. Hope that helps

http://stackoverflow.com/comment/90843305
type: AnswerComment
comment on: http://stackoverflow.com/a/51946871
score: 0
type: Comment
has text: @Neil - No, `print (d[(1, 'MS')])` or `print (d['MS_1'])` return DataFrames

http://stackoverflow.com/q/51921014
tagged with: pip
tagged with: mousewheel
has comment: http://stackoverflow.com/comment/90791820
downvote count: 0
score: 1
tagged with: eof
type: Question
upvote count: 1
has comment: http://stackoverflow.com/comment/90804327
has title: Error when installing pip. EOF while scanning triple-quoted string literal
favorite count: 0
tagged with: python
has body: I'm trying to install pip to my mac and keep running into a String literal error. I run this to create the file from the get-pip website: curl https://bootstrap.pypa.io/get-pip.py > get_pip.py But when I run the python file I get the error: File "get-pip.py", line 9947 tE8 ^ SyntaxError: EOF while scanning triple-quoted string literal
has comment: http://stackoverflow.com/comment/90792170
answer count: 0
type: UnansweredQuestion

flask
tags question: http://stackoverflow.com/q/51804596
tags question: http://stackoverflow.com/q/51882407
tags question: http://stackoverflow.com/q/51914900
tags question: http://stackoverflow.com/q/51842977
tags question: http://stackoverflow.com/q/51854109
tags question: http://stackoverflow.com/q/51863958
tags question: http://stackoverflow.com/q/51932057
tags question: http://stackoverflow.com/q/51813834
tags question: http://stackoverflow.com/q/51921368
tags question: http://stackoverflow.com/q/51809633
tags question: http://stackoverflow.com/q/51942909
tags question: http://stackoverflow.com/q/51836370
tags question: http://stackoverflow.com/q/51848526
tags question: http://stackoverflow.com/q/51907875
tags question: http://stackoverflow.com/q/51865461
tags question: http://stackoverflow.com/q/51803021
tags question: http://stackoverflow.com/q/51833491
tags question: http://stackoverflow.com/q/51913220
tags question: http://stackoverflow.com/q/51849433
tags question: http://stackoverflow.com/q/51912331
tags question: http://stackoverflow.com/q/51803008
tags question: http://stackoverflow.com/q/51822192
tags question: http://stackoverflow.com/q/51870981
tags question: http://stackoverflow.com/q/51905066
tags question: http://stackoverflow.com/q/51903651
tags question: http://stackoverflow.com/q/51815254
tags question: http://stackoverflow.com/q/51871550
tags question: http://stackoverflow.com/q/51831141
tags question: http://stackoverflow.com/q/51908121
tags question: http://stackoverflow.com/q/51907487
tags question: http://stackoverflow.com/q/51852750
tags question: http://stackoverflow.com/q/51829184
tags question: http://stackoverflow.com/q/51948012
tags question: http://stackoverflow.com/q/51951686
tags question: http://stackoverflow.com/q/51931361
tags question: http://stackoverflow.com/q/51902483
tags question: http://stackoverflow.com/q/51824723
tags question: http://stackoverflow.com/q/51852782
tags question: http://stackoverflow.com/q/51941493
tags question: http://stackoverflow.com/q/51810471
tags question: http://stackoverflow.com/q/51922105
tags question: http://stackoverflow.com/q/51917226
tags question: http://stackoverflow.com/q/51840676
tags question: http://stackoverflow.com/q/51931143
tags question: http://stackoverflow.com/q/51953636
tags question: http://stackoverflow.com/q/51899770
tags question: http://stackoverflow.com/q/51852997
tags question: http://stackoverflow.com/q/51815038
tags question: http://stackoverflow.com/q/51800698
tags question: http://stackoverflow.com/q/51883773
tags question: http://stackoverflow.com/q/51908697
tags question: http://stackoverflow.com/q/51954052
tags question: http://stackoverflow.com/q/51934663
tags question: http://stackoverflow.com/q/51813092
tags question: http://stackoverflow.com/q/51856523
type: Tag
tags question: http://stackoverflow.com/q/51809578
tags question: http://stackoverflow.com/q/51812927
tags question: http://stackoverflow.com/q/51876287
tags question: http://stackoverflow.com/q/51817237
tags question: http://stackoverflow.com/q/51804202
tags question: http://stackoverflow.com/q/51916177
tags question: http://stackoverflow.com/q/51883383
tags question: http://stackoverflow.com/q/51889745
tags question: http://stackoverflow.com/q/51875333
tags question: http://stackoverflow.com/q/51887319
tags question: http://stackoverflow.com/q/51952293
tags question: http://stackoverflow.com/q/51902224
tags question: http://stackoverflow.com/q/51938595
tags question: http://stackoverflow.com/q/51801353
tags question: http://stackoverflow.com/q/51932277
tags question: http://stackoverflow.com/q/51812634
tags question: http://stackoverflow.com/q/51941827
tags question: http://stackoverflow.com/q/51855899
tags question: http://stackoverflow.com/q/51890933
tags question: http://stackoverflow.com/q/51897977
tags question: http://stackoverflow.com/q/51911674
tags question: http://stackoverflow.com/q/51932231
tags question: http://stackoverflow.com/q/51925284
tags question: http://stackoverflow.com/q/51929071

http://stackoverflow.com/comment/90609943
type: QuestionComment
comment on: http://stackoverflow.com/q/51827749
has text: `myarray.argmax(0)`?
score: 4
type: Comment

http://stackoverflow.com/q/51903803
score: 0
answer count: 1
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/51908607
tagged with: node.js
tagged with: apache-kafka
has title: Not able to consume large messages with Kafka (over 1.3 MB)?
has body: I followed the link How can I send large messages with Kafka (over 15MB)? to resolve the kafka msg limit issue. But no luck I tried increasing A.) On Broker: message.max.bytes=15728640 replica.fetch.max.bytes=15728640 B.) On Consumer: fetch.message.max.bytes=15728640 Still facing the same problem. Not able to consume data that is over 1.3 MB on a particular topic In my application, a msg in sent on a topic from python code and is consumed on node server.
has comment: http://stackoverflow.com/comment/90821061
type: Question
linked to: http://stackoverflow.com/q/21020347
has comment: http://stackoverflow.com/comment/90758958

http://stackoverflow.com/comment/90728401
type: Comment
has text: Basically, any way to extract the confidence if that makes sense
comment on: http://stackoverflow.com/q/51870095
score: 0
type: QuestionComment

http://stackoverflow.com/comment/90717522
type: QuestionComment
comment on: http://stackoverflow.com/q/51867937
has text: Possible duplicate of https://stackoverflow.com/questions/16551009/gravity-in-pygame
score: 0
type: Comment

http://stackoverflow.com/q/51869266
has answer: http://stackoverflow.com/a/51869573
tagged with: scrapy
type: Question
answer count: 2
has body: is it possible to do something like below but with multiple url like below? Each link will have about 50 pages to crawl and loop. The current solution is working but only working if I use 1 URL instead of multiple urls. start_urls = [ 'https://www.xxxxxxx.com.au/home-garden/page-%s/c18397' % page for page in range(1, 50), 'https://www.xxxxxxx.com.au/automotive/page-%s/c21159' % page for page in range(1, 50), 'https://www.xxxxxxx.com.au/garden/page-%s/c25449' % page for page in range(1, 50), ]
has answer: http://stackoverflow.com/a/51870414
accepted answer: http://stackoverflow.com/a/51870414
score: 0
linked to: http://stackoverflow.com/q/32435776
linked to: http://stackoverflow.com/q/6566322
possible better answer: http://stackoverflow.com/a/51869573
tagged with: python
has title: Python scrapy start_urls
type: AnsweredQuestion

http://stackoverflow.com/q/51851950
has comment: http://stackoverflow.com/comment/90656860
has comment: http://stackoverflow.com/comment/90656855
type: Question
score: 0
has comment: http://stackoverflow.com/comment/90656748
tagged with: pip
has comment: http://stackoverflow.com/comment/90656876
tagged with: python
answer count: 1
has comment: http://stackoverflow.com/comment/90656802
has comment: http://stackoverflow.com/comment/90656941
has answer: http://stackoverflow.com/a/51852140
has body: Summary I've got the back end of a neat python program down, but I hate the gui options we have by default. Tkinter is unreliable, in my experience. And the turtle graphics thing would in no way benefit my project. So I looked into alternatives and Krivy came up. I followed the install step by step and I'm getting line after line of errors. Windows 10 Python 3.6 Question What is happening and how do I fix it? I've already looked at other questions and they are either from previous years or slightly different to my own problem. Below is the result of a pip install (or attempt). Outcome C:\Users\*&gt;pip3.6 install pygyubu Collecting pygyubu Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:833)'),)': /simple/pygyubu/ Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:833)'),)': /simple/pygyubu/ Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:833)'),)': /simple/pygyubu/ Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:833)'),)': /simple/pygyubu/ Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:833)'),)': /simple/pygyubu/ Could not fetch URL https://pypi.python.org/simple/pygyubu/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.python.org', port=443): Max retries exceeded with url: /simple/pygyubu/ (Caused by SSLEr…
has comment: http://stackoverflow.com/comment/90656882
has title: Python Pip Failing to work | What is going on?
accepted answer: http://stackoverflow.com/a/51852140
has comment: http://stackoverflow.com/comment/90656932
linked to: http://stackoverflow.com/q/25981703
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90656785
has comment: http://stackoverflow.com/comment/90656844
has comment: http://stackoverflow.com/comment/90656825
has comment: http://stackoverflow.com/comment/90656854
has comment: http://stackoverflow.com/comment/90656827
has comment: http://stackoverflow.com/comment/90656716

http://stackoverflow.com/comment/90820434
comment on: http://stackoverflow.com/a/51935149
has text: @coldspeed hm, idea was not to call `.mode` which seems overkill
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/90660992
has text: Django will not compute those '{{ adsf }}'. Such placeholders are for templates. Outside of templates they don't work.
score: 0
comment on: http://stackoverflow.com/q/51848082
type: Comment
type: QuestionComment

tcp
type: Tag
tags question: http://stackoverflow.com/q/51891620
tags question: http://stackoverflow.com/q/51826523
tags question: http://stackoverflow.com/q/51910651
tags question: http://stackoverflow.com/q/51910169
tag name: tcp

http://stackoverflow.com/q/51890073
type: AnsweredQuestion
tagged with: discord.py
has title: Python Discord Get multuple messages after command
has body: What I'm trying to do is create a bot that will start off when an admin types !start. After that, users can type in a message that can only be 3 characters in length. EAch of these messages will be displayed in an embedded message. When an admin hits !stop then the messages will stopped being recorded. Right now, I can !start and !stop, but I can't get the messages in between. The msg2 variable doesn't even get printed out. @client.event async def on_message(message): if message.content.startswith('!start'): await client.send_message(message.channel, "Starting") def check(msg): return len(msg.content) == 3 while (not await client.wait_for_message(author=message.author, content='!stop')): msg2 = await client.wait_for_message(check=check) print (msg2.content) await client.send_message(message.channel, "Stopping")
has answer: http://stackoverflow.com/a/51895697
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/51895697
favorite count: 0
tagged with: python
score: 2
upvote count: 2
type: Question

http://stackoverflow.com/comment/90835276
score: 0
has text: Did you really mean to set `count` equal to the return of a print function?
comment on: http://stackoverflow.com/q/51941029
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/90795306
has text: Your question has nothing actually to do with `x = '10 0 17 5'`. Your updates look like you read the linked questions (which *don't* work) but did not pay attention to the answers. Please read carefully. I really can't help you if you're expecting a copy and paste job.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51922283

http://stackoverflow.com/comment/90696591
type: QuestionComment
comment on: http://stackoverflow.com/q/51872412
score: 0
has text: Yes, that is in fact the case. I didn't think about it.
type: Comment

http://stackoverflow.com/q/51824201
tagged with: google-bigquery
has answer: http://stackoverflow.com/a/75583276
type: Question
answer count: 2
downvote count: 0
has body: This is a simple code to export from Biq Query to Google storage, in CSV format def export_data(): client = bigquery.Client() project = 'xxxxx' dataset_id = 'xxx' table_id = 'xxx' bucket_name = 'xxx' destination_uri = 'gs://{}/{}'.format(bucket_name, 'EXPORT_FILE.csv') dataset_ref = client.dataset(dataset_id, project=project) table_ref = dataset_ref.table(table_id) extract_job = client.extract_table( table_ref, destination_uri, # Location must match that of the source table. location='EU') # API request extract_job.result() # Waits for job to complete. print('Exported {}:{}.{} to {}'.format( project, dataset_id, table_id, destination_uri)) It works perfectly for general tables, BUT when I try to export data from saved table VIEW, it failed with this error: BadRequest: 400 Using table xxx:xxx.xxx@123456 is not allowed for this operation because of its type. Try using a different table that is of type TABLE. Does exist any way to export data from table view? What I'm trying to achieve is, to get the data from BigQuery in CSV format, and upload to Google analytics Product Data
score: 1
has answer: http://stackoverflow.com/a/51824512
tagged with: python
favorite count: 0
accepted answer: http://stackoverflow.com/a/51824512
upvote count: 1
tagged with: google-analytics-api
has title: BigQuery | Python | Export data from BigQuery table VIEW
type: AnsweredQuestion
tagged with: google-analytics
possible better answer: http://stackoverflow.com/a/75583276

http://stackoverflow.com/comment/90668008
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51834946
has text: @Casey It looks like it does show the final player's dice, but pygame.display.update() kicks off too quickly after it drops out of the loop on the final run. I'm not sure it's a complete solution, but if you delete that statement and put it at the end of your loop, just after on_roll() is called, the dice for the final player does make it on screen long enough to be seen.

http://stackoverflow.com/a/51890633
downvote count: 0
has comment: http://stackoverflow.com/comment/90732622
type: Answer
has comment: http://stackoverflow.com/comment/90733176
accepted answer of: http://stackoverflow.com/q/51890489
score: 1
answers question: http://stackoverflow.com/q/51890489
upvote count: 1
has body: Use: import ast d = {'Answer.annotation_data': ['[{"left":171,"top":0,"width":163,"height":137,"label":"styrofoam container"},{"left":222,"top":42,"width":45,"height":70,"label":"chopstick"}]', '[{"left":170,"top":10,"width":173,"height":157,"label":"styrofoam container"},{"left":222,"top":42,"width":45,"height":70,"label":"chopstick"}]']} df = pd.DataFrame(d) print (df) Answer.annotation_data 0 [{"left":171,"top":0,"width":163,"height":137,... 1 [{"left":170,"top":10,"width":173,"height":157... #convert string data to list of dicts if necessary df['Answer.annotation_data'] = df['Answer.annotation_data'].apply(ast.literal_eval) For each value of cols extract values of dict and return DataFrame, last join together by concat: def get_val(val): comb = [[y.get(val, np.nan) for y in x] for x in df['Answer.annotation_data']] return pd.DataFrame(comb).add_prefix('{}_'.format(val)) cols = ['left','top','width','height'] df1 = pd.concat([get_val(x) for x in cols], axis=1) print (df1) left_0 left_1 top_0 top_1 width_0 width_1 height_0 height_1 0 171 222 0 42 163 45 137 70 1 170 222 10 42 173 45 157 70
has comment: http://stackoverflow.com/comment/90732910
type: AcceptedAnswer

http://stackoverflow.com/comment/107591024
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51863414
has text: @ikolim how to make it work if there are multiple dropdowns in the kv? how can we call a different function for each dropdown?
score: 0

http://stackoverflow.com/comment/90750250
has text: That can happen when fitting polynomials especially with degrees > 1. You could try using other types of regression methods like Kalman filters or splines
type: QuestionComment
comment on: http://stackoverflow.com/q/51899374
score: 0
type: Comment

http://stackoverflow.com/comment/90631123
comment on: http://stackoverflow.com/a/51838777
type: AnswerComment
score: 0
type: Comment
has text: Nice ! @Nihail what if I have multiple iframe urls ? what do I need to change to loop all iframe urls ? And how to print only text ? 'cause now it prints the whole html source.

http://stackoverflow.com/a/51947382
answers question: http://stackoverflow.com/q/51945917
downvote count: 0
type: Answer
has body: You could also use the get_dummies function as follows: import numpy as np import pandas as pd # The definition of your dataframe df = pd.DataFrame({'col_1': [1, 3, 2], 'col_2': [2, 4, 6], 'col_3': [np.NaN, 5, np.NaN], 'col_4': [np.NaN, 6, np.NaN]}, dtype=float) # Get dummies where you leave out the prefix # This will ensure that all columns of the same value will get the same column name df = pd.get_dummies(df, columns=['col_1', 'col_2', 'col_3', 'col_4'], prefix='') # Initialise your result result = pd.DataFrame() # Use the groupby method to group on column name for column, data in df.groupby(level=0, axis=1): # Merge data of same columns into one column result[column] = data.max(axis=1) So what we essentialy do here is to apply get_dummies on all columns resulting in something like _1.0 _2.0 _3.0 _2.0 _4.0 _6.0 _5.0 _6.0 0 1 1 0 1 0 0 0 0 1 0 0 1 0 1 1 1 1 2 0 1 0 1 0 1 0 1 Then we merge all columns with the same name to get the desired result _1.0 _2.0 _3.0 _4.0 _5.0 _6.0 0 1 1 0 0 0 0 1 0 0 1 1 1 1 2 0 1 0 0 0 1
upvote count: 2
score: 2

mininet
tag name: mininet
tags question: http://stackoverflow.com/q/51808140
tags question: http://stackoverflow.com/q/51902738
tags question: http://stackoverflow.com/q/51813091
type: Tag

oop
tags question: http://stackoverflow.com/q/51918857
tag name: oop
tags question: http://stackoverflow.com/q/51853732
tags question: http://stackoverflow.com/q/51922368
tags question: http://stackoverflow.com/q/51817007
tags question: http://stackoverflow.com/q/51828012
tags question: http://stackoverflow.com/q/51943056
tags question: http://stackoverflow.com/q/51928071
tags question: http://stackoverflow.com/q/51946290
tags question: http://stackoverflow.com/q/51852658
tags question: http://stackoverflow.com/q/51929528
tags question: http://stackoverflow.com/q/51943892
tags question: http://stackoverflow.com/q/51826422
tags question: http://stackoverflow.com/q/51876378
tags question: http://stackoverflow.com/q/51839583
tags question: http://stackoverflow.com/q/51867579
tags question: http://stackoverflow.com/q/51846827
tags question: http://stackoverflow.com/q/51858649
type: Tag
tags question: http://stackoverflow.com/q/51871011
tags question: http://stackoverflow.com/q/51848586

http://stackoverflow.com/comment/90857728
score: 0
type: AnswerComment
has text: @Dustin fixed :-)
type: Comment
comment on: http://stackoverflow.com/a/51940922

http://stackoverflow.com/comment/90585316
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/51815532
has text: Perhaps you want to define a function that does something like `def myreplace(string): return string if string.strip() else '0'`
type: Comment

http://stackoverflow.com/comment/90613036
score: 0
has text: Why not using a token for local access as well?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51829249

http://stackoverflow.com/a/51915007
accepted answer of: http://stackoverflow.com/q/51853581
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/90780214
score: 1
has comment: http://stackoverflow.com/comment/90780055
upvote count: 1
has body: This can be easily achieved using this two lines of python code: temp = filePathsReturned[1:-1] list = temp.split("} {")
answers question: http://stackoverflow.com/q/51853581

http://stackoverflow.com/q/51832803
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51833752
tagged with: tensorflow
type: Question
score: 0
answer count: 1
tagged with: raspberry-pi3
has answer: http://stackoverflow.com/a/51833752
has body: I hope to make an electronic project where I connect electronics with Tensorflow, and I decided to use Raspberry pi 3 B+. I previously used Arduino. On the Raspberry Pi GPIO is for electronics, is it possible for me to connect GPIO with Tensorflow by using "import tensorflow as tf?"
has title: Can I import Tensorflow to Raspberry pi 3 B+ GPIO with 'import tensorflow as tf'?
tagged with: python
tagged with: artificial-intelligence

http://stackoverflow.com/a/51874717
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/51873851
has body: If anyone else encounters a similar problem, the CountVectorizer has a lowercase parameter that is True on default. Using vec = CountVectorizer(input='filename', token_pattern='.+', lowercase=False) solved the problem.
downvote count: 0
has comment: http://stackoverflow.com/comment/90737043
type: Answer

http://stackoverflow.com/comment/90722146
type: Comment
has text: No, I am a LOT unaware of the order of things :) The above is a snippet from my code. At the moment, my Flask app is one route to display a dashboard. That relies on being logged into the Hive API and having a token. This might be used in lots of functions and routes. Thank you for your answer. I'll give that a try tomorrow.
comment on: http://stackoverflow.com/a/51881455
type: AnswerComment
score: 0

http://stackoverflow.com/comment/90823011
has text: Why do you have to manually approve it? please share the code.
comment on: http://stackoverflow.com/q/51936437
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90842558
type: QuestionComment
comment on: http://stackoverflow.com/q/51933804
score: 0
type: Comment
has text: you need to add try-except in all places wherever you are navigating a website. if it is a single place to add, then go ahead. Also, I assume accet_alert won't wait for the alert to be preset (implicit wait), so no time killing there for each navigation.

http://stackoverflow.com/a/51884791
has body: Try finding unique elements in the array using np.unique 1. Loop over this array using np.where 2. Example to find all indices with element 0 is numpy.where(x == 0)[0]
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51884709
upvote count: 2
score: 2

http://stackoverflow.com/q/51931673
has body: Go lang has a feature, that has a name "struct tags". https://github.com/golang/go/wiki/Well-known-struct-tags Does python have something similar to it? I mean that I want to say python somehow that if I'm using my class in json unmarshalling that it should be filled using one names, and if it's data from db reading that names could be a little bit different. Go example: struct test { TestField int64 `json:"test_int" db:"TestInt"` }
has comment: http://stackoverflow.com/comment/90813484
downvote count: 0
has comment: http://stackoverflow.com/comment/90813303
favorite count: 0
tagged with: go
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90813355
tagged with: python
score: 2
has title: Go struct tags in Python
answer count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/90813787
type: Question

http://stackoverflow.com/q/51910396
tagged with: nltk
score: 1
has title: How to search for specific sequences of words within a string?
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/51912125
has answer: http://stackoverflow.com/a/51911264
favorite count: 0
possible better answer: http://stackoverflow.com/a/51911264
tagged with: python
tagged with: regex
has body: I wish to search for specific sequences of words within a string. I have so far been able to find them (jumbled within) the string, but am unable to find them in a specific sequence. Let me illustrate: from nltk.tokenize import word_tokenize negative_descriptors = ['no', 'unlikely', 'no evidence of'] diagnosis = 'disc prolapse' report = 'There is no evidence of disc prolapse but this is evidence of a collection.' def find_diagnosis(diagnosis, negative_descriptors, report): keywords = word_tokenize(diagnosis) if [keyword for keyword in keywords if keyword in report] == keywords: if [descriptor for descriptor in negative_descriptors if descriptor in report]: return False else: return True In the above example, the algorithm should return False if the negative descriptors AND diagnosis appear in the report, and the negative descriptors should appear BEFORE the diagnosis within the report (and should not be more than 1 word apart). How do I ensure the algorithm takes not only the words but their sequences to account?
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90771265
accepted answer: http://stackoverflow.com/a/51912125
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/90771170

http://stackoverflow.com/q/51951332
has comment: http://stackoverflow.com/comment/90918798
favorite count: 0
score: 0
has comment: http://stackoverflow.com/comment/90855051
has comment: http://stackoverflow.com/comment/90853501
has comment: http://stackoverflow.com/comment/90858651
tagged with: python
has answer: http://stackoverflow.com/a/51954089
accepted answer: http://stackoverflow.com/a/51954089
upvote count: 1
downvote count: 1
linked to: http://stackoverflow.com/q/42494229
has title: Python - imports and folder structure
type: AnsweredQuestion
has body: I have the following file structure: command.py simulations basis basis.py hamiltonian hamiltonian.py where the names without extensions are folders. command.py is importing basis.py and hamiltonian.py like: from basis.basis import Basis from hamiltonian.hamiltonian import Hamiltonian where Basis and Hamiltonian are two classes. I can run command.py fine, all the imports are Okay. Now, I want to work with hamiltonian.py alone, but it needs to import basis.py. In order for command.py to work fine, the import in hamiltonian.py has to be from basis.basis import Basis In order for hamiltonian.py to run on its own, the import needs to be os.chdir('..') from basis.basis import Basis however this makes command.py not work anymore. -- 1) Can I somehow run the os.chdir('..') only if hamiltonian.py is run on its own? Like with if name == 'main'? 2) Is there a more elegant solution to this?
tagged with: import
has comment: http://stackoverflow.com/comment/90865392
type: Question
answer count: 1

http://stackoverflow.com/a/51876418
accepted answer of: http://stackoverflow.com/q/51871420
score: 2
answers question: http://stackoverflow.com/q/51871420
has body: Solved by adding align='edge' in the bar plot. That is: bars = ax.bar(bins[:bins_number], n, width=width, bottom=0.0, align='edge') Thanks to ImportanceOfBeingErnest
type: AcceptedAnswer
downvote count: 0
upvote count: 2
type: Answer

http://stackoverflow.com/a/51948759
answers question: http://stackoverflow.com/q/51948687
type: Answer
has comment: http://stackoverflow.com/comment/125013258
has body: I think you solve the problem at the wrong level: the CACHES settings have a setting for automatic expiration: the 'TIMEOUT' key: CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.db.DatabaseCache', 'LOCATION': 'exchange_rate_cache', 'TIMEOUT': 604800 # 7 days } } This settings speicifies the number of seconds before the value "expires", or as said in the documentation [Django-doc]: TIMEOUT: The default timeout, in seconds, to use for the cache. This argument defaults to 300 seconds (5 minutes). You can set TIMEOUT to None so that, by default, cache keys never expire. A value of 0 causes keys to immediately expire (effectively “don’t cache”). A day takes 60×60×24 seconds, and a week is 7 days, so a week has, 604800 seconds. By adding this in the settings, you can easily change the expiration if you later change your mind. A cache by default also holds a limited number of elements (see other settings in the documentation), and furthermore there other things can cause the cache to remove elements (for example if you use a memory cache restarting the server will normally clear the cache). Furthermore you can - like @marin says - also ad-hoc specify an expiration for a specific key when you set(..) it; as is specified in the documentation: The basic interface is set(key, value, timeout) and get(key) (..) The timeout argument is optional and defaults to the timeout argument of the appropriate backend in the CACHES setting (explained above). It’s the number of seconds the value should be stored in the cache. Passing in None for timeout will cache the value forever. A timeout of 0 won’t cache the value.
score: 9
upvote count: 9
has comment: http://stackoverflow.com/comment/134539654
has comment: http://stackoverflow.com/comment/97194151
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51948687

http://stackoverflow.com/q/51925924
score: 1
downvote count: 1
has title: To find mean in onedataframe for another dataframe id's using python pandas?
type: Question
has body: Data frame 1: Stationid 10 11 12 13 14 15 16 17 Data frame 2: Stationid Maintanance 10 55 15 38 21 100 10 56 22 101 15 39 10 56 I need to calculate mean for station id's in dataframe 1 on dataframe 2 Expected output: Stationid Maintainance Mean 10 55.666667 15 38.500000
tagged with: pandas
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51925978
accepted answer: http://stackoverflow.com/a/51925978
upvote count: 2
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/51824728
has title: Insert conditional values into dict from key using RE
score: -1
accepted answer: http://stackoverflow.com/a/51849009
has body: So my problem is quite simple, my conditions are: if "__" in key, insert 'class=\"\" ' into opening tag in value pair: so it becomes: then insert the relevant values of "__" else leave as is I've done 95% of this but I'm missing one step. Here is my dict and code: d1 = { "h1": " [] ", "h1__display-3": " [] ", "h1__display-3_text-white_text-center": " [] ", "h1__mt-4": " [] ", "h1__mt-5": " [] ", "h1__mt-5_kakabum": " [] ", "h1__my-4": " [] ", "h2": " [] ", "h2__card-title": " [] ", "h2__mt-4": " [] ", "h2__my-4": " [] " } d2 = {k:k for k, v in d1.items()} res = {} for k in d2: key = k.split('__')[0] if key in d1: res[k] = d1[key] res2 = {k: re.sub(r'class="([\w\- ]+)"', r'class="\1 ' + d2[k] + '"', v) for k,v in res.items()} res3 = {k: re.sub(r'\w\w\__', r'', v).replace('_', ' ') for k, v in res2.items()} print('Res', json.dumps(res3, indent= 2)) After above I get undesired: { "h1": " [] ", # notice the unnecessary 'h1' in class "h1__display-3": " [] ", "h1__display-3_text-white_text-center": " [] ", "h1__mt-4": " [] ", "h1__mt-5": " [] ", "h1__mt-5_kakabum": " [] ", "h1__my-4": " [] ", "h2": " [] ", "h2__card-title": " [] ", "h2__mt-4": " [] ", "h2__my-4": " [] " } Instead of desired: { "h1": " [] ", "h1__display-3": " [] ", "h1__display-3_text-white_text-center": " [] ", "h1__mt-4": " [] ", "h1__mt-5": " [] ", "h1__mt-5_kakabum": " [] ", "h1__my-4": " [] ", "h2": " [] ", "h2__card-title": " [] ", "h2__mt-4": " [] ", "h2__my-4": " [] " } ^notice: No class attribute as per d1 for "h2": " [] ", but because key has '__', class pattern has been inserted "h2__card-title": " [] ". I'm missing the step between res2 and res3, could someone help me out?
upvote count: 0
tagged with: dictionary-comprehension
answer count: 1
favorite count: 0
tagged with: python-3.x
tagged with: python
tagged with: dictionary
tagged with: regex
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51849009
downvote count: 1
type: Question

http://stackoverflow.com/q/51837346
has title: Python getsize issue with S3
score: 0
has comment: http://stackoverflow.com/comment/90628303
linked to: http://stackoverflow.com/q/5315603
tagged with: hdfs
has body: I'm trying to check backuped file on our S3 bucket using getsize. I think it's not possible to use this function with the s3 wrapper. Any alternative? Here is my code: def check_created_file(self,destination) : if destination != None : files = os.popen("hdfs dfs -ls %s | awk {'print $8'}"%(destination)).read().split("\n") files = files[1::len(files)-1] for file in files : if os.path.getsize(file) &gt; 0 : print file else: print " [*] WARNING " print "%s is empty"%(file) else: raise Exception("Remote dir is not specified") the error I am getting: OSError: [Errno 2] No such file or directory
type: UnansweredQuestion
tagged with: python
answer count: 0
tagged with: amazon-s3
has comment: http://stackoverflow.com/comment/90628171
type: Question

http://stackoverflow.com/a/51921162
type: Answer
upvote count: 4
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51907699
answers question: http://stackoverflow.com/q/51907699
score: 4
type: AcceptedAnswer
has body: Changed this self.object.point = fromstr('POINT(%s %s)'%(self.object.lat, self.object.lon), srid=4326) to self.object.point = fromstr('POINT(%s %s)'%(self.object.lon, self.object.lat), srid=4326) The lon comes before lat.

http://stackoverflow.com/q/51873708
score: 8
has comment: http://stackoverflow.com/comment/90700799
has answer: http://stackoverflow.com/a/56902036
has comment: http://stackoverflow.com/comment/90733233
tagged with: django
has comment: http://stackoverflow.com/comment/91345750
type: Question
has comment: http://stackoverflow.com/comment/90735343
has comment: http://stackoverflow.com/comment/90699252
has body: I am trying to find a bug which happens from time to time on our production server, but could not be reproduced otherwise: some value in the DB gets changed in a way which I don't want it to. I could write a PostgreSQL trigger which fires if this bug happens, and raise an exception from said trigger. I would see the Python traceback which executes the unwanted SQL statement. But in this case I don't want to stop the processing of the request. Is there a way to log the Python/Django traceback from within a PostgreSQL trigger? I know that this is not trival since the DB code runs under a different linux process with a different user id. I am using Python, Django, PostgreSQL, Linux. I guess this is not easy since the DB trigger runs in a different context than the python interpreter. Please ask if you need further information. Update One solution might be to overwrite connection.notices of psycopg2.
has comment: http://stackoverflow.com/comment/91273862
has comment: http://stackoverflow.com/comment/91274955
has comment: http://stackoverflow.com/comment/90736116
has answer: http://stackoverflow.com/a/51898376
has comment: http://stackoverflow.com/comment/90735875
has comment: http://stackoverflow.com/comment/91270707
has title: Log Stacktrace of current Python Interpreter via PostgreSQL trigger
downvote count: 0
has comment: http://stackoverflow.com/comment/91345847
has answer: http://stackoverflow.com/a/56216742
favorite count: 0
tagged with: postgresql
upvote count: 8
answer count: 5
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52135763
tagged with: python
has answer: http://stackoverflow.com/a/52133148
has comment: http://stackoverflow.com/comment/90740018
has comment: http://stackoverflow.com/comment/91269914

http://stackoverflow.com/q/51893787
has comment: http://stackoverflow.com/comment/90738677
has answer: http://stackoverflow.com/a/51894757
type: Question
has title: Extracting text from string using Regex
score: 4
linked to: http://stackoverflow.com/q/1240504
upvote count: 4
has answer: http://stackoverflow.com/a/51894013
has body: I have a very large string. There are many paragraphs inside that string. Each paragraph starts with a title and follows a particular pattern. Example: == Title1 == // Paragraph starts ............. ............. // Some texts ............. End of Paragraph ===Title2 === // Paragraph starts ............. ............. // Some texts ............. The pattern of the title are: 1.) New Paragraph title starts with an equal to ( = ) and can be followed by any number of =. 2.) After = , there can be a white space ( not necessary though ) and it is followed by text. 3.) After text completion, again there can be a white space ( not necessary ), followed by again any number of equal to's ( = ). 4.) Now the paragraph starts. I have to extract the text until it encounters a similar pattern. Can anyone help me with how to do this with regex? TIA
downvote count: 0
accepted answer: http://stackoverflow.com/a/51894757
has answer: http://stackoverflow.com/a/51894183
favorite count: 0
possible better answer: http://stackoverflow.com/a/51894013
tagged with: python
tagged with: regex
answer count: 4
has answer: http://stackoverflow.com/a/51893991
has comment: http://stackoverflow.com/comment/90738389
type: AnsweredQuestion

http://stackoverflow.com/comment/90821824
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51935476
has text: So your SSH server was actually not working at all? => Your question is not about Python, Paramiko nor Lambda?

http://stackoverflow.com/a/51826815
type: Answer
upvote count: 4
answers question: http://stackoverflow.com/q/51826802
score: 4
accepted answer of: http://stackoverflow.com/q/51826802
has body: the barcode module only accepts strings as input, you should then just make that integer a string: import barcode from barcode.writer import ImageWriter number = 5901234123457 number = str(number) EAN = barcode.get_barcode_class('ean13') ean = EAN(number, writer=ImageWriter()) fullname = ean.save('barcode')
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/90608291
has text: Okay, my bad. But from my guess I don't think there should be those commas either side of `str(i)` in the left/right strings
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51826734

flask-restplus
tag name: flask-restplus
tags question: http://stackoverflow.com/q/51931361
tags question: http://stackoverflow.com/q/51857316
tags question: http://stackoverflow.com/q/51942909
type: Tag

http://stackoverflow.com/comment/90627165
comment on: http://stackoverflow.com/a/51834019
type: AnswerComment
score: 0
has text: So I have to repeat the same form class 10 times to make it work 10 different times? I know I can do that but I was hoping keep from repeating the code
type: Comment

http://stackoverflow.com/comment/90843916
type: Comment
has text: @Albert I am not sure how you wanna create the directory structure from the example you have demonstrated, do you wanna create a folder with user defined name at a location and further create a subdirectory?
comment on: http://stackoverflow.com/a/51926825
type: AnswerComment
score: 0

http://stackoverflow.com/q/51945705
has comment: http://stackoverflow.com/comment/90860643
has body: I am taking user input and sending it to Django backend for some text processing. After performing backend operation I want to display results. I tried but as I am new with ajax,I am not sure where I am making mistake. Can anyone please give me correct way of using ajax for this operation? I appreciate if you can give link to any good reference document. Current issue - When I click on submut button it removes input text area. My html report.html - {% extends 'base.html' %} {% block content %} StopWordsRemoval {% csrf_token %} {{ form}} stopwordsremoval {{ naturallanguageprocessing }} <a href="{% url 'stopwordsremoval' %}" {% endblock %} urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'stopwordsremoval/$', views.stopwordsremoval.as_view(), name='stopwordsremoval'), url(r'stopwordsremoval/(?P<document1>.+)/$', views.ReportDetails.as_view(), name='report_details'), ] forms.py from django import forms class ReportForm(forms.Form): #pdb.set_trace() text = forms.CharField(widget=forms.Textarea(attrs={'rows': 5, 'cols': 100}))
has answer: http://stackoverflow.com/a/51952132
upvote count: 1
type: Question
tagged with: javascript
has comment: http://stackoverflow.com/comment/90842642
tagged with: ajax
has comment: http://stackoverflow.com/comment/90840825
has comment: http://stackoverflow.com/comment/90947160
has title: Using Ajax with Django to call backend and display result
answer count: 1
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/90840893
favorite count: 0
type: UnansweredQuestion
tagged with: django
tagged with: python

http://stackoverflow.com/comment/91008423
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51920263
has text: Retrieve the Word.Document object from either Explorer.PreviewPane.WordEditor / Inspector.WordEditor or Explorer.ActiveInlineResponseWordEditor. Once you have that object, you can use Word Object Model to highlight any text - see, for example, https://stackoverflow.com/questions/44158886/how-to-highlight-text-in-a-word-document-using-visual-basic
type: AnswerComment

http://stackoverflow.com/a/51853992
has comment: http://stackoverflow.com/comment/90660550
has body: This is what you want, what I just did, is that I mapped the prediction which is a numpy array representing the class labels index in your categories list. So here's the complete code. import pandas as pd import numpy as np from sklearn import svm from sklearn.datasets import samples_generator from sklearn.feature_selection import SelectKBest from sklearn.feature_selection import f_regression from sklearn.pipeline import Pipeline from sklearn.model_selection import train_test_split from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.multiclass import OneVsRestClassifier from sklearn.svm import LinearSVC from sklearn.metrics import accuracy_score from sklearn.metrics import f1_score df = pd.read_csv("finalupdatedothers.csv") categories = ['ADR','WD','EF','INF','SSI','DI','others'] train,test = train_test_split(df,random_state=42,test_size=0.3,shuffle=True) X_train = train.sentences X_test = test.sentences SVC_pipeline = Pipeline([ ('tfidf', TfidfVectorizer(stop_words=[])), ('clf', OneVsRestClassifier(LinearSVC(), n_jobs=1)), ]) for category in categories: print('... Processing {} '.format(category)) SVC_pipeline.fit(X_train,train[category]) prediction = SVC_pipeline.predict(X_test) print([{X_test.iloc[i]:categories[prediction[i]]} for i in range(len(list(prediction))) ]) print('SVM Linear Test accuracy is {} '.format(accuracy_score(test[category], prediction))) print ('SVM Linear f1 measurement is {} '.format(f1_score(test[category], prediction, average='weighted'))) print ("\n") And here's the sample output: ... Processing ADR [{'extreme weight gain, short-term memory loss, hair loss.': 'ADR'}, {'I am detoxing from Lexapro now.': 'ADR'}] SVM Linear Test accuracy is 0.5 SVM Linear f1 measurement is 0.3333333333333333 ... Processing WD [{'extreme weight gain, short-term memory loss, hair loss.': 'ADR'}, {'I am detoxing from Lexapro now.': 'ADR'}] SVM Linear Test accuracy is 1.0 SVM Linear f1 measurement is 1.0 I hope this helps.
has comment: http://stackoverflow.com/comment/90661005
has comment: http://stackoverflow.com/comment/90660936
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/90660732
has comment: http://stackoverflow.com/comment/90661348
has comment: http://stackoverflow.com/comment/90660853
has comment: http://stackoverflow.com/comment/90660837
has comment: http://stackoverflow.com/comment/90660769
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90660938
has comment: http://stackoverflow.com/comment/90661297
accepted answer of: http://stackoverflow.com/q/51853429
has comment: http://stackoverflow.com/comment/90661248
has comment: http://stackoverflow.com/comment/90660873
has comment: http://stackoverflow.com/comment/90661074
has comment: http://stackoverflow.com/comment/90660898
answers question: http://stackoverflow.com/q/51853429
type: Answer
has comment: http://stackoverflow.com/comment/90661040

http://stackoverflow.com/q/51892846
has comment: http://stackoverflow.com/comment/90738095
has comment: http://stackoverflow.com/comment/90744396
type: UnansweredQuestion
tagged with: python
tagged with: selenium-chromedriver
tagged with: captcha
has answer: http://stackoverflow.com/a/55190885
has comment: http://stackoverflow.com/comment/90738440
tagged with: selenium
has comment: http://stackoverflow.com/comment/90740352
tagged with: google-chrome
has title: Selenium gets detected and and captcha pops up immediately after opening the bloomberg url for the first time
linked to: http://stackoverflow.com/q/33225947
type: Question
has comment: http://stackoverflow.com/comment/90739923
has body: Like the title says, I'm having problems with scraping a site, specifically, it's bloomberg.com. I'm supposed to open a link like this: from selenium import webdriver driver = webdriver.Chrome(path_to_driver) driver.get("https://www.bloomberg.com/research/stocks/private/snapshot.asp?privcapId=4253471") But immediately I get a warning and captcha pops up on the second link I open. I didn't flood the website with other requests or anything, all I'm doing is calling driver.get() every 10 seconds or so. What I have tried so far: from here link to a similar question. I learned you should modify chromedriver.exe in a HEX editor and replace "$cdc" with something like "xyzw", but doing that has changed nothing (I get different IP when I switch my router on/off so I'm definitely not IP blocked). Any ideas what can be done here? So far I never encountered something like this before, getting blocked on a first link.
score: 0
has comment: http://stackoverflow.com/comment/90738797
answer count: 1

http://stackoverflow.com/comment/90756368
type: Comment
type: QuestionComment
has text: @amalloy Ya, poor wording. My bad. I meant vectors so you can get the near constant access.
comment on: http://stackoverflow.com/q/51869268
score: 0

http://stackoverflow.com/a/52016794
upvote count: 1
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51884050
has comment: http://stackoverflow.com/comment/99508292
accepted answer of: http://stackoverflow.com/q/51884050
score: 1
has body: As there's no way (that I could find) to apply weights to each sentence supplied to countvectorizer, it is possible to multiply the resulting sparse matrix. cv = CountVectorizer(lowercase = False, min_df=0.001, tokenizer = space_splitter) X = cv.fit_transform(all_strings) # Multiply the resulting sparse matrix by the weight (count) of each sentence. counts = scipy.sparse.diags(df.weight, 0) X = (X.T*counts).T Xc = (X.T * X) # create co-occurance matrix Notice the matrix you multiply by has to be a sparse matrix and the weights need to be in its diagonal.
has comment: http://stackoverflow.com/comment/99484755

http://stackoverflow.com/comment/90615689
score: 0
has text: Yes sir! That is exactly what I want.
type: Comment
comment on: http://stackoverflow.com/q/51830567
type: QuestionComment

http://stackoverflow.com/comment/90748628
type: Comment
has text: @khachik. The whole point is to avoid re-implementing the parent setter.
comment on: http://stackoverflow.com/q/51879805
score: 0
type: QuestionComment

http://stackoverflow.com/q/51897182
has answer: http://stackoverflow.com/a/51897343
tagged with: python
possible better answer: http://stackoverflow.com/a/51897431
type: Question
has answer: http://stackoverflow.com/a/51897431
type: AnsweredQuestion
tagged with: split
has body: I have table: Name1 Name2 Name3 0 ABC FGD NNY 1 111S PC 1T Trees are always yellow NaN NaN 2 P FGD NNY 3 JJJ FGD NNY 4 111S PC 1T Trees are always yellow NaN NaN 5 ABC FGD NNY 6 UIK GJ DE and i want to get this: Name1 Name2 Name3 Name4 0 ABC FGD NNY NaN 1 111S PC 1T Trees are always yellow 2 P FGD NNY NaN 3 JJJ FGD NNY NaN 4 111S PC 1T Trees are always yellow 5 ABC FGD NNY NaN 6 UIK GJ DE NaN I need to split only some rows and other rows should not change. I was able to determine the lines in which it is necessary to split the data: if df[colname1].isnull: df_index=df[df[colname1].isnull()].index print(df_index) Now need to separate values ​​in strings. I get somthing like that: if df[colname1].isnull: df_index=df[df[colname1].isnull()].index print(df_index) for i in df_index: print(i) df1=df[colname][i].split(' ') df1 is string with needful information for me, but i don't know how put this info to DataFrame df in needful index. Could you help me with this.
accepted answer: http://stackoverflow.com/a/51897343
tagged with: dataframe
has title: Split needful rows in DataFrame
score: 0
answer count: 2
tagged with: pandas

http://stackoverflow.com/a/67557619
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/123837283
downvote count: 0
answers question: http://stackoverflow.com/q/51881429
has body: UPDATE to patrick's code: @bot.command(pass_context=True) async def broadcast(ctx, *, msg): for server in bot.guilds: for channel in server.text_channels: try: await channel.send(msg) except Exception: continue else: break Changes: Servers Are Now Called Guilds, we need to use the send method of channel class , also we want to use only text_channels.
upvote count: 2

http://stackoverflow.com/q/51925228
has answer: http://stackoverflow.com/a/51925628
tagged with: django
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/90800302
has title: Django Image resizing script
has comment: http://stackoverflow.com/comment/90799988
has answer: http://stackoverflow.com/a/51925445
answer count: 2
accepted answer: http://stackoverflow.com/a/51925628
possible better answer: http://stackoverflow.com/a/51925445
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/90800314
tagged with: python
has body: Hi I have a project that the images upload and save in a sub folder in the media and never set an image size so now the images save 4mb and ended up totalling to 40GB in size. I know how to write a script if the images were in a single folder but could someone guide me to do this to check all images in a folder and resize it ? Even if its in a sub folder and another sub folder. Using Django and python Function for image upload def artwork_theme_name(instance, filename): path, name = get_hashed_upload_to(instance.id, filename) return 'theme/{}/{}'.format(path, name) Upload model class ArtworkForeground(models.Model): title = models.CharField(_("title"), max_length=128) description = models.TextField(_("description")) foreground = models.ImageField(_("foreground image"), upload_to=artwork_theme_name)
has comment: http://stackoverflow.com/comment/90799920
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/90799832

http://stackoverflow.com/q/51842218
has comment: http://stackoverflow.com/comment/90648204
has comment: http://stackoverflow.com/comment/90637457
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/51842291
has title: python convert list of string into list intgers
favorite count: 0
has comment: http://stackoverflow.com/comment/90647976
type: UnansweredQuestion
tagged with: python
has body: want to convert list of string into list of integer . It only works when I initialize list but not when the a number is converted into list. a=list(raw_input("enter no :")) print (a) r = list(map(int, a)) print (r) #getting error #enter no :111 #['1', '1', '1', '\n'] #Traceback (most recent call last): #File "C:/Users/shris/PycharmProjects/demo1/d1.py", line 4, in &lt;module&gt; #r = list(map(int, a)) #ValueError: invalid literal for int() with base 10: '\n' #want r=[1,1,1]
score: 2
upvote count: 2
type: Question
has comment: http://stackoverflow.com/comment/90637418

http://stackoverflow.com/comment/136487337
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51955248
type: AnswerComment
has text: Function name should be `visit_module` instead of `process_module`

http://stackoverflow.com/q/51887958
favorite count: 0
upvote count: 2
has body: My network was achieving 96% accuracy on my dataset (edit: on predicting 9 classes). I saved the entire model for every epoch (weights included) whenever I ran it. I ran it 3 times, each time testing different hyperparameters, each time achieving around 96% accuracy. When I try to load any of these tests now and run it again, it achieves around 50% accuracy. I'm extremely confident I'm running it on the same dataset. Here's the interesting thing: if I train a new network instance of the exact same architecture, same size, shape, etc., it only ever reaches a max of 85% accuracy. Additionally, saving and loading these new training models works correctly, as in the model will reach the same 85% accuracy. So, there's no problem with loading and no problem with my dataset. The only way this could happen is if something is wrong in my custom layer, or something else is happening. Unfortunately I haven't been committing all of my changes to the custom layer to git. While I can't guarantee that my custom layer is the exact same, I'm almost completely confident it is. Any ideas to what could be causing this discrepancy? Edit: To add more context, the layer is ripped from the ConvLSTM2d class but I replaced the call() function to simply be a vanilla RNN that uses convolution instead of the dot product. I am confident that the call() function is the same as before, but I am not confident that the rest of the class is the same. Is there anything else in the class that could affect performance? I've checked activation function already.
tagged with: python
has comment: http://stackoverflow.com/comment/90771301
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90731985
has answer: http://stackoverflow.com/a/51921611
possible better answer: http://stackoverflow.com/a/51891264
has comment: http://stackoverflow.com/comment/90761515
has answer: http://stackoverflow.com/a/51891264
tagged with: machine-learning
has title: Loading a saved model in Keras with a custom layer and prediction results are different?
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/90727667
type: Question
answer count: 2
downvote count: 0
accepted answer: http://stackoverflow.com/a/51921611
tagged with: keras-layer
score: 2
has comment: http://stackoverflow.com/comment/90761522
tagged with: keras

http://stackoverflow.com/q/51937207
score: 1
upvote count: 1
type: Question
has title: How to change column Values of data imported in Python
has body: I want to change column values of data imported in python.I have imported an excel workbook using pandas. Data=pd.read_excel(r"...\Report.xlsx") I want to write a function to import excel and change column value(Column Name-Name) and Values('C' has to be changed to 'A' and 'E' to 'B). The below Table data is sample table and data. Name Place A UK B Aus C US D AFR E CHN My code is import pandas as pd def read_csv(filename): string_data = pd.read_excel(filename) if 'C' in string_data['Name']: string_data['Name'].replace('C','A',inplace=True) if 'E' in string_data['Name']: string_data['Name'].replace('E','B',inplace=True) result=string_data.groupby(["Name"])["Place"].count().reset_index(name='result_count') return result Here the if condition in function doesn't working and values are not changed. Am i writing condition wrongly. How to change column values and bring result? Could anyone help on writing this function
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/51937308
tagged with: python
accepted answer: http://stackoverflow.com/a/51937308
type: AnsweredQuestion

distinct
tag name: distinct
tags question: http://stackoverflow.com/q/51871550
type: Tag

http://stackoverflow.com/comment/90736272
type: AnswerComment
comment on: http://stackoverflow.com/a/51892569
type: Comment
has text: Woah. Worked. Hail Rudolf ;).
score: 0

http://stackoverflow.com/a/51831771
has comment: http://stackoverflow.com/comment/90627098
type: AcceptedAnswer
has body: Likely the easiest way to do this is using Particle's __subclasses__ method. You could define ParticleSystem like this: class ParticleSystem(object): def __init__(self): self.particles = [] def create_particle(self, particle_type, location): if particle_type in (cls.__name__ for cls in Particle.__subclasses__()): p = eval(particle_type)(self) p.location = location self.particles.append(p) else: raise TypeError("{} is not a subclass of Particle".format(particle_type)) That said, it's often a good idea to avoid having different classes know about each other's inner workings. Does ParticleSystem really need to know all the subclasses of Particle (better yet - does each particle need to know about the system it's in?)? Or do you just need an easy way to instantiate new Particle objects? If you simply need the latter, you could just use a simple factory method. Note: using eval is generally a bit reckless, but because it is protected by the in Particle.__subclasses__() condition, we should be fine.
score: 0
type: Answer
answers question: http://stackoverflow.com/q/51831219
accepted answer of: http://stackoverflow.com/q/51831219

http://stackoverflow.com/a/51945022
answers question: http://stackoverflow.com/q/51942945
has body: def get_new_theta(msg, theta, time): new_theta = [theta] new_time = [time] for a, b in zip(msg[3::5], msg[4::5]): new_theta.append(new_theta[-1] + a + b) new_time.append(new_time[-1]+time) return new_theta[:-1], new_time[:-1] msg = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15] theta = 1 time = 4.5 for i, (theta, time) in enumerate( zip(*get_new_theta(msg, theta, time)) ): for j in range(5): print(theta, msg[i*5+j], time) gives: 1 1 4.5 1 2 4.5 1 3 4.5 1 4 4.5 1 5 4.5 10 6 9.0 10 7 9.0 10 8 9.0 10 9 9.0 10 10 9.0 29 11 13.5 29 12 13.5 29 13 13.5 29 14 13.5 29 15 13.5 get_new_theta(msg, theta, time) returns a tuple of the lists (new_theta, new_time). And zip(*get_new_theta(msg, theta, time)) gives an iterator over tuples (theta, time)
upvote count: 1
type: AcceptedAnswer
type: Answer
score: 1
accepted answer of: http://stackoverflow.com/q/51942945
downvote count: 0

http://stackoverflow.com/comment/90882194
comment on: http://stackoverflow.com/q/51952393
score: 0
has text: @miken32 I just edited the whole thing if you would like to take a look, and deleted what my general aim was, trying to learn stuff step by step now.
type: Comment
type: QuestionComment

cx-oracle
tags question: http://stackoverflow.com/q/51800678
tags question: http://stackoverflow.com/q/51900647
tags question: http://stackoverflow.com/q/51950472
tags question: http://stackoverflow.com/q/51902175
tags question: http://stackoverflow.com/q/51851524
type: Tag
tags question: http://stackoverflow.com/q/51820017
tag name: cx-oracle

http://stackoverflow.com/comment/90575727
type: Comment
has text: can you post the original data of df so this is a reproducible problem?
type: QuestionComment
comment on: http://stackoverflow.com/q/51810322
score: 0

http://stackoverflow.com/q/51842888
score: -2
has comment: http://stackoverflow.com/comment/90638873
has body: I have about 50 urls named url1.....url50 I want to make a dictionary of these variables for example: url1 = "https://example1.com" url2 = "https://example2.com" url3 = "https://example3.com" . . I tried this:: all_urls = {} a= 'url' for i in range(1,51): all_urls[a+str(i)] = a+str(i) For this I get the keys right but how can I get variables as the value. Output: {'url1': 'url1', 'url10': 'url10', 'url11': 'url11', 'url12': 'url12', 'url13': 'url13', 'url14': 'url14', 'url2': 'url2', 'url3': 'url3', 'url4': 'url4', 'url5': 'url5', 'url6': 'url6', 'url7': 'url7', 'url8': 'url8', 'url9': 'url9' Desired output: 'url1' : 'https://example.com' 'url2' : 'https://example.org' 'url3' : 'https://example.com' and so on..
has comment: http://stackoverflow.com/comment/90638903
has title: converting variables to dictionaries, Making variable string as value in a dictionary
upvote count: 2
answer count: 2
duplicate of: http://stackoverflow.com/q/1373164
favorite count: 0
has comment: http://stackoverflow.com/comment/90639056
has comment: http://stackoverflow.com/comment/128696501
tagged with: python
downvote count: 4
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/1373164
has answer: http://stackoverflow.com/a/51843197
linked to: http://stackoverflow.com/q/9437726
type: Question
has comment: http://stackoverflow.com/comment/90638957
has answer: http://stackoverflow.com/a/51842935

http://stackoverflow.com/q/51923655
tagged with: python
accepted answer: http://stackoverflow.com/a/51924018
has comment: http://stackoverflow.com/comment/90796879
has comment: http://stackoverflow.com/comment/90797127
tagged with: django
type: AnsweredQuestion
has title: Set value of an unknown Django Model Field
has body: I am implementing a function that gets a model class as a parameter, and should get a dictionary from the same model, set model fields to namesake keys in such dictionary, and save the model to the database. This is the code of the function: def populate_model(self, model_to_populate): model_to_populate_instance = model_to_populate() if hasattr(model_to_populate_instance, 'populate_data'): populate_data = getattr(model_to_populate, 'populate_data') for key, value in populate_data.items(): field = getattr(model_to_populate_instance, key) field = value model_to_populate_instance.save() Something is wrong because I don't get values from the dictionary in the database, but objects GeneralApp.models.CustomCharField&gt;. I guess I am not succeeding to set the value of the model instance field to the value in the dictionary. O would appreciate your help.
tagged with: django-models
has answer: http://stackoverflow.com/a/51924018
type: Question
score: 0
has comment: http://stackoverflow.com/comment/90799210
answer count: 1
has comment: http://stackoverflow.com/comment/90796843

http://stackoverflow.com/comment/90666117
type: QuestionComment
has text: Posted now. I didn't put it as an answer initially because it does not exactly solve your question of which version "the correct one", but I suppose if someone has better information they can post it later.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/51856613

http://stackoverflow.com/a/51932449
downvote count: 0
has body: You could use the ternary notation which was added in version 2.5 of python. You can read more on those here First the condition is evaluated and then the if or else result is returned. So you could rewrite your function like this. def fun(cond, x, y): return (x, y) if cond == 'A' else y However like already mentioned in the comment I would advise against return multiple different types of results from a single function. Either always return a tuple or return a single value.
has comment: http://stackoverflow.com/comment/90816287
answers question: http://stackoverflow.com/q/51932125
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/comment/90770672
type: QuestionComment
has text: @RafaelC Any solution?
comment on: http://stackoverflow.com/q/51908642
score: 0
type: Comment

http://stackoverflow.com/a/51895936
score: 1
upvote count: 1
has body: Can you try to reproduce the same error with a clean code? Yours contain a few mistakes, and unnecessary lines. We also need a sample of your data that helps reproduce the error otherwise we won't be able to help. Here is what I assume is you are trying to do, please try to launch it with your data and tell us if you still obtain the same error: import pandas as pd from sklearn import svm from sklearn.model_selection import train_test_split from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer dataset = pd.DataFrame({'data':['A first sentence','And a second sentence','Another one','Yet another line','And a last one'], 'label':[1,0,0,1,1]}) data = dataset['data'] labels = dataset['label'] X_train, X_test, y_train, y_test = train_test_split (data, labels, test_size = 0.2, random_state = 0) vecteur = CountVectorizer() tfidf = TfidfTransformer() X_train_counts = vecteur.fit_transform(X_train) X_train_tfidf = tfidf.fit_transform(X_train_counts) X_test_tfidf = tfidf.transform(vecteur.transform(X_test)) clf = svm.SVC(kernel = 'linear', C = 10).fit(X_train_tfidf, y_train) print(clf.score(X_test_tfidf, y_test)) EDIT: According to your data, the error might be due to a comma character in your csv file, causing pandas parser to bug. You can tell pandas to ignore such rows by using erro_bad_lines argument in read_csv. Here is a short example: temp=u"""data, label A first working line, refund a second ok line, call last line with an inside comma: , character which makes it bug, call""" df = pd.read_csv(pd.compat.StringIO(temp),error_bad_lines=False)
accepted answer of: http://stackoverflow.com/q/51894591
answers question: http://stackoverflow.com/q/51894591
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/90743844
has comment: http://stackoverflow.com/comment/90743937

http://stackoverflow.com/comment/90610909
type: QuestionComment
comment on: http://stackoverflow.com/q/51828197
has text: could your break be the problem? i mean ok you don't want to do anything when the index is at the edge but by using break u go out of your loop without iterating though all the elements. At least thats what it looks like to me at a mere glance. You should make use of additional conditonal for the controlflow and stay away from break in this case if you ask me.
score: 0
type: Comment

http://stackoverflow.com/q/51936044
has comment: http://stackoverflow.com/comment/90822191
has title: python variable is not defined using print function
has body: After running the below code, python prompt error and tell me name "tony" is not defined. print('Hello Sam, this is Javis') #let user enter their name, "nm" being the variable nm = input('Please tell me your name =&gt; ') print('It is definitely nice to meet you',nm,'!') I input name as "Tony" What did i do wrong?
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51936092
linked to: http://stackoverflow.com/q/21122540
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/90822168
score: 0
duplicate of: http://stackoverflow.com/q/21122540
answer count: 1

http://stackoverflow.com/comment/90849113
type: Comment
type: QuestionComment
has text: Try adding these two lines to your code `fit1 = np.poly1d(np.polyfit(x, y, 3))` and `ax.plot(x, fit1(x), '-ko', label= "Smoothed curve")`. Here I am using a third degree polynomial fit and then passing *actual* `x` data points from your DataFrame to plot *only* the corresponding 1 value for each animal.
comment on: http://stackoverflow.com/q/51949000
score: 0

firefox
tags question: http://stackoverflow.com/q/51878819
tags question: http://stackoverflow.com/q/51846188
tag name: firefox
type: Tag
tags question: http://stackoverflow.com/q/51873603

http://stackoverflow.com/comment/102170039
type: Comment
score: 2
comment on: http://stackoverflow.com/a/57872364
type: AnswerComment
has text: please write a complete answer if you want to post it as an answer. If you want to complete someone else's answer, consider adding a comment under that answer.

http://stackoverflow.com/comment/90862261
has text: Based on the code sample you provided, There is no way for it to even try to render response.html since your are instructing both of your views `index()` and `parse_data()` to render `index.html`.from your ajax call, the `parse_data()` code will run but notice how at the end, you are rendering `index.html` instead of rendering `response.html. See my update #2 in the answer
comment on: http://stackoverflow.com/a/51953357
type: AnswerComment
type: Comment
score: 0

http://stackoverflow.com/q/51939468
possible better answer: http://stackoverflow.com/a/53997197
answer count: 2
upvote count: 7
has answer: http://stackoverflow.com/a/53997197
tagged with: keras
favorite count: 0
tagged with: python
has title: Keras Conv1D or Convolution1D
type: AnsweredQuestion
downvote count: 0
score: 7
has body: I came across multiple implementations of a CNN in Keras and noticed that some people use Conv1D from from keras.layers.convolutional import Conv1D and others use Convolution1D from from keras.layers import Convolution1D. Is there a difference or an advantage to either one or are they possibly simply just different versions of Keras.
type: Question
has answer: http://stackoverflow.com/a/51939645
accepted answer: http://stackoverflow.com/a/51939645

http://stackoverflow.com/q/51888996
tagged with: tensorflow
type: Question
tagged with: k-means
tagged with: amazon-sagemaker
score: 0
answer count: 2
accepted answer: http://stackoverflow.com/a/51904108
possible better answer: http://stackoverflow.com/a/51894972
has title: How to write Tensorflow KMeans Estimator script for Sagemaker
has answer: http://stackoverflow.com/a/51904108
tagged with: python
has body: I'm attempting to use Tensorflows tf.contrib.factorization.KMeansClustering estimator with SageMaker but am having some trouble. The output of my SageMaker predictor.predict() call looks incorrect. The cluster values are too large as they should be integers from 0-7. (I have the number of clusters set to 8). I get a similar output on every run (where the last half of the array is 4L or some other digit like 0L). There are 40 values in the array because that s how many rows(users and their ratings I pass into the predict() function) Example: {'outputs': {u'output': {'int64_val': [6L, 0L, 6L, 1L, 2L, 4L, 5L, 7L, 7L, 7L, 7L, 5L, 0L, 1L, 7L, 3L, 3L, 6L, 7L, 3L, 7L, 2L, 6L, 2L, 3L, 7L, 6L, 3L, 3L, 6L, 1L, 2L, 1L, 3L, 7L, 7L, 7L, 3L, 5L, 7L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L], 'dtype': 9, 'tensor_shape': {'dim': [{'size': 100L}]}}}, 'model_spec': {'signature_name': u'serving_default', 'version': {'value': 1534392971L}, 'name': u'generic_model'}} The data I'm working with is a sparse matrix of item ratings where rows=users, cols=items, and the cells contain floats bewteen 0.0 and 10. So my input data is a matrix instead of the typical array of features. I think the issue might be in the serving_input_fn function. Here is my SageMaker entry_point script: def estimator_fn(run_config, params): #feature_columns = [tf.feature_column.numeric_column('inputs', shape=list(params['input_shape']))] return tf.contrib.factorization.KMeansClustering(num_clusters=NUM_CLUSTERS, distance_metric=tf.contrib.factorization.KMeansClustering.COSINE_DISTANCE, use_mini_batch=False, feature_columns=None, config=run_config) def serving_input_fn(params): tensor = tf.placeholder(tf.float32, shape=[None, None]) return tf.estimator.export.build_raw_serving_input_receiver_fn({'inputs': tensor})() def tr…
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51894972
tagged with: machine-learning

http://stackoverflow.com/comment/90822321
type: Comment
score: 0
type: AnswerComment
has text: @PM2Ring you are right. I misunderstood the question. Thank you for pointing it out.
comment on: http://stackoverflow.com/a/51936092

http://stackoverflow.com/q/51862781
tagged with: python-unittest
has title: How to unit test instance variables initialized outside __init__ method
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/51862954
has body: I have a class that initializes an instance variable in a method other than __init__. That instance variable is further referred to in the __init__ method. In the code below, ProductionClass is the class I am testing. In ProductionClass, __init__ makes a call to method a_method. Method a_method initializes an instance variable inst_var_2. inst_var_2 is used by __init__ to set another instance variable inst_var_3. class LibraryClass(object): def __init__(self): self.some_attrib = "some_attrib_value" class ProductionClass(object): def __init__(self, arg_one): self.inst_var_1 = arg_one self.a_method() self.inst_var_3 = self.inst_var_2.some_attrib def a_method(self): self.inst_var_2 = LibraryClass() import unittest from unittest.mock import patch, MagicMock class ProdTestCase(unittest.TestCase): @patch.object(ProductionClass, 'a_method') def test_init_method(self, mock_method): instance = ProductionClass(1234) self.assertEqual(1234, instance.inst_var_1) mock_method.assert_called_once_with() I am trying to unit test the __init__ method of ProductionClass and I am unable to create an instance of the ProductionClass, due to missing instance variable inst_var_2. Here is the error message: Traceback (most recent call last): ... File "/... production_class.py", line 9, in __init__ self.inst_var_3 = self.inst_var_2.some_attrib AttributeError: 'ProductionClass' object has no attribute 'inst_var_2' My question, is it possible to unit test the __init__ method while I am mocking the a_method. I want to mock a_method because I don't want the method to instantiate LibraryClass.
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/25608107
upvote count: 3
type: Question
score: 3
accepted answer: http://stackoverflow.com/a/51862954

http://stackoverflow.com/comment/90567129
score: 0
comment on: http://stackoverflow.com/q/51805571
has text: I'm not sure how to implement what you suggested - passing the parent node down the recursive chain. Aren't I at the end of the line when I reach the parent node? I was getting a NoneType error when I tried to pass the parent node recursively through _remove() because the node was equal to None
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/99892980
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51843831
has text: It can detect script or font? What if the document contains different font?

http://stackoverflow.com/comment/107634712
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51950571
has text: @juanpa.arrivillaga: thank you. You are right. Initially, I used a confusing terminology. Now it is corrected with references to Python's FAQ on the matter.
type: AnswerComment

http://stackoverflow.com/a/63196814
score: 6
type: Answer
upvote count: 6
answers question: http://stackoverflow.com/q/51933830
has body: Python's for loop is an iterator-based loop (that's why bruno desthuilliers says that it "works for all iterables (lists, tuples, sets, dicts, iterators, generators etc)". A string is also another common type of iterable). Let's say you have a list of tuples. Using that nomenclature you shared, one can iterate through both the keys and values simultaneously. For instance: tuple_list = [(1, "Countries, Cities and Villages"),(2,"Animals"),(3, "Objects")] for k, v in tuple_list: print(k, v) will give you the output: 1 Countries, Cities and Villages 2 Animals 3 Objects If you use a dictionary, you'll also gonna be able to do this. The difference here is the need for .items() dictionary = {1: "Countries, Cities and Villages", 2: "Animals", 3: "Objects"} for k, v in dictionary.items(): print(k, v) The difference between dictionary and dictionary.items() is the following dictionary: {1: 'Countries, Cities and Villages', 2: 'Animals', 3: 'Objects'} dictionary.items(): dict_items([(1, 'Countries, Cities and Villages'), (2, 'Animals'), (3, 'Objects')]) Using dictionary.items() we'll get a view object containig the key-value pairs of the dictionary, as tuples in a list. In other words, with dictionary.items() you'll also get a list of tuples. If you don't use it, you'll get TypeError: cannot unpack non-iterable int object If you want to get the same output using a simple list, you'll have to use something like enumerate() list = ["Countries, Cities and Villages","Animals", "Objects"] for k, v in enumerate(list, 1): # 1 means that I want to start from 1 instead of 0 print(k, v) If you don't, you'll get ValueError: too many values to unpack (expected 2) So, this naturally raises the question... do I need always a list of tuples? No. Using enumerate() we'll get an enumerate object.
downvote count: 0

minimum
tags question: http://stackoverflow.com/q/51922622
tag name: minimum
type: Tag

http://stackoverflow.com/a/51832213
upvote count: 1
has body: If you look at the docs, the last argument should be a Rectangle object. In your Particle constructor, change the first line to this: class Particle(object): def __init__(self, Color, xpos, ypos): pygame.draw.rect(window, Color, pygame.Rect(xpos, ypos, particle_size, particle_size))
score: 1
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51832141

http://stackoverflow.com/q/51952311
type: Question
has comment: http://stackoverflow.com/comment/90855975
has comment: http://stackoverflow.com/comment/90855101
has comment: http://stackoverflow.com/comment/90855184
has comment: http://stackoverflow.com/comment/90855198
has body: I am struggling with some DateTime issues in Django. I believe it all comes down to data types and conversions and I am just not quite getting it. I would greatly appreciate if someone could clean up my code, as posted below. I would ask also not to change too much. I am very new to programming. I'm certain that there are better ways to accomplish what I am trying to do, but my understanding is limited to doing things a certain way. So if you could help me make this work without wholesale changes I would really appreciate it. Okay... As a learning project I am building a very basic "Travel App" in Django (Python 2, Django 1). I want users to be able to enter a start and end date for a trip. The start date must be in the future and the end date must be after the start date. First, I create my Trip table in models: class Trip(models.Model): destination = models.CharField(max_length=55) description = models.TextField() start_date = models.DateField(null=True) end_date = models.DateField(null=True) travelers = models.ManyToManyField(User, related_name="trips") planned_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name="trips_added") created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = TripManager() I think all is well with this. Also in models, I set up both a validation and an add method for the "add trip" form. Here is what I have as of now - I know there are some errors in here: class TripManager(models.Manager): def trip_validation(self, postData): start_date = datetime.strptime(postData['start_date'], "%Y-%m-%d") end_date = datetime.strptime(postData['end_date'], "%Y-%m-%d") errors = {} if len(postData['destination']) &lt; 1: errors['destination'] = 'You must enter trip destination.' if len(postData['description']) &lt; 1: errors['description'] = 'You must enter trip description.' if len(postData['start_date']) &lt; 1: errors['start_date'] = 'Please enter a start date for your trip.' elif n…
has comment: http://stackoverflow.com/comment/90855763
has comment: http://stackoverflow.com/comment/90855706
has title: DateField issues in Django
type: UnansweredQuestion
tagged with: datetime
tagged with: django
has comment: http://stackoverflow.com/comment/90855870
tagged with: python
answer count: 0
score: 0

http://stackoverflow.com/comment/90703464
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51875906
has text: Related: https://stackoverflow.com/questions/7367976/calling-a-c-sharp-library-from-python. Can you give us detail on the package used and installed?
score: 0

http://stackoverflow.com/comment/90707116
has text: No worries. Take your time and accept whichever answer works best for you. (Darkonaut's answer looks like a good candidate if you consider Pandas a clean solution.)
type: AnswerComment
comment on: http://stackoverflow.com/a/51876689
score: 0
type: Comment

http://stackoverflow.com/comment/90660053
type: QuestionComment
comment on: http://stackoverflow.com/q/51853704
has text: @Shaido, No, I don't have. In fact, it's not required to order the DF by.
score: 0
type: Comment

http://stackoverflow.com/comment/90640434
comment on: http://stackoverflow.com/q/51843579
has text: Do you get an error, or your output is different as you would expect? Please describe what are you getting now.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51809401
tagged with: sockets
has title: Python login script not working using sockets
tagged with: python
has comment: http://stackoverflow.com/comment/90574235
type: Question
has comment: http://stackoverflow.com/comment/90574872
score: 0
has body: I have made a python socket server and you need to login with an account that is linked to a text file with the format Username:Password:ID which works fine but in my code to figure out the issue I made it print out what username and password was used but when you type in the username it says this Username: Admin Password: Password Admin Password Basically for some reason it is putting a new line above it changing the credentials put in, why? Here is the relevant code: def username(conn, prefix="Username: "): conn.send(prefix) return conn.recv(512) def password(conn, prefix="Password: "): conn.send(prefix) data = conn.recv(512) if data: return conn.recv(512) createLogin = file("login.txt", "a") with open("login.txt", "r") as login: lines = login.readlines() while True: username = username(conn) password = password(conn) conn.send("%s" % username) conn.send("%s" % password) for line in lines: if line.split(":")[0] == username and line.split(":")[1] == password: print("Do stuff") else: print("Failed") conn.close() Just a reminder this works perfectly fine on localhost, it is when I run it on a VPS it breaks.
has comment: http://stackoverflow.com/comment/90574794
has comment: http://stackoverflow.com/comment/90574280
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/51949554
score: 1
has body: I have a pandas dataframe with a column that stores the name of particular task and another column reporting the id number of the employee who performed that task. Something similar to: EMPLOYEE_ID TASK_NAME Employee1 Inspection Employee2 Inspection Employee3 Inspection Employee4 Inspection Employee5 Inspection Employee1 Change Employee2 Inspection Employee3 Change Employee1 Change Employee2 Change I was wondering what type of command/analyses I have to do in order to group/cluster employees over task performed. In other words, I'd like to to say that, for instance, "Employee_Group_1" (which includes Employee1, Employee2, Employee3) has performed 75% of all Inspection and Change tasks.. Any help would be much apprecieated! Thanks in advance.
favorite count: 0
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/51949747
upvote count: 1
tagged with: cluster-computing
answer count: 1
has comment: http://stackoverflow.com/comment/90849062
has comment: http://stackoverflow.com/comment/90849173
has title: Grouping categorical data over other categorical data with python/pandas
accepted answer: http://stackoverflow.com/a/51949747
tagged with: pandas
type: AnsweredQuestion
tagged with: grouping
downvote count: 0

http://stackoverflow.com/comment/90812861
type: QuestionComment
comment on: http://stackoverflow.com/q/51931396
has text: `if y in x:` should be ``if y in materials[x]:` so you reference the value in the dictionary, and not the value
score: 0
type: Comment

http://stackoverflow.com/comment/90611857
has text: tried my best, without data is impossible to know better :)
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51828270
type: Comment

http://stackoverflow.com/q/51811914
answer count: 1
accepted answer: http://stackoverflow.com/a/51812020
score: 0
has body: I am working with the Open Food Facts dataset which is very messy. There is a column called quantity in which in information about the quantity of respective food. the entries look like: 365 g (314 ml) 992 g 2.46 kg 0,33 litre 15.87oz 250 ml 1 L 33 cl ... and so on (very messy!!!) I want to create a new column called is_liquid. My idea is that if the quantity string contains an l or L the is_liquid field in this row should get a 1 and if not 0. Here is what I've tried: I wrote this function: def is_liquid(x): if x.str.contains('l'): return 1 elif x.str.contains('L'): return 1 else: return 0 (BTW: if something is measured in 'oz' is it liquid?) And then tried to apply it df['is_liquid'] = df['quantity'].apply(is_liquid) But all I get is this error: AttributeError: 'str' object has no attribute 'str' Could someone help me out?
tagged with: pandas
has answer: http://stackoverflow.com/a/51812020
tagged with: python
tagged with: regex
tagged with: feature-engineering
has comment: http://stackoverflow.com/comment/90578934
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90578805
tagged with: apply
type: Question
has title: creating new column based on whether the letter 'l' or 'L' is in the string of another column

http://stackoverflow.com/q/51842968
tagged with: scatter
has title: How to plot a 3D scatter graph with a specified color for everypoint
has answer: http://stackoverflow.com/a/51843328
type: AnsweredQuestion
favorite count: 0
has body: This question might be stupid but I can't find the answer. I'm using python and I want to plot a scatter graph where x is of size Nx, y of size Ny, z of size Nz and where for every point (x[i] , y[j], z[k]) I have an intensity I[i,j,k] which is a real number. I would like to plot this scatter graph where every point of coordinates (x,y,z) has a color depending on the intensity
type: Question
downvote count: 2
accepted answer: http://stackoverflow.com/a/51843328
tagged with: python
score: -2
answer count: 1
tagged with: colormap
upvote count: 0

http://stackoverflow.com/comment/90791805
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51921007
has text: Actually, dumping the object is the solution. If you have multiple images and their vectors, then you can create a dictionary of them to be dumped.
score: 0

http://stackoverflow.com/q/51934869
has body: I have 2 dictionaries and here is the dictionaries: a = [{'filtered':'eat','lang':'en'},{'filtered':'drink','lang':'en'},{'filtered':'makan','lang':'id'},{'filtered':'minum','lang':'id'}] b = [{'filtered':'drink','lang':'en'},{'filtered':'makan','lang':'id'},{'filtered':'tidur','lang':'id'}] I want to intersect those 2 dictionaries with the value of 'filtered' as the filtering variable and i want the result to be like this: result = [{'filtered':'drink','lang':'en'},{'filtered':'makan','lang':'id'}] What is the code to intersect dictionary in list like that? Thank you for your respond.
answer count: 1
favorite count: 0
has title: Python: Dictionary in List Intersection
type: UnansweredQuestion
tagged with: python
tagged with: dictionary
upvote count: 0
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51934943
tagged with: intersection
score: -1
linked to: http://stackoverflow.com/q/5943330

http://stackoverflow.com/a/51857378
has body: You can use tesseract to iterate over words that it has identified and get the bounding box for each word.However, you will have the following challenge : Orientation : While you can configure tesseract to auto detect orientation , your image has multiple orientations for different cards which contain the digits. Duplicates : You will have same digits visible twice on some card and only once on others if they are hidden by other cards. One approach you might be able to use is that you can generate your reference digits for font used in card at multiple rotations for ex: every 10 degress...As a result of this you will have 36 reference images for each character and 360 in all. You can now train tesseract on this model. Also, i notice your card has black color used only for digits and border. You can preprocess your image to remove remaining background colors to improve accuracy..You might have to retry with different angles if you are not getting very good result with 10 degree rotations. For duplicate issue, once you have bounding box for all digits and you know that digits in a given card will have fixed distance from its opposite pair. you can use this information to remove any duplicates.
answers question: http://stackoverflow.com/q/51853480
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/90682625

http://stackoverflow.com/q/51873145
has body: I'm not able to do something and I would like to know if it's a bug or normal way. I was trying to a Nested Cross Validation on dataset, and each of it belong to a patient. To avoid learning and testing on the same patient, I've seen that you implement a "group" mecanism and GroupKFold seems the right one in my case. As my classifier get differents parameters, I proceed to GridSearchCv to fix hyper parameters of my model. In the same way, I suppose that testing / training have to belong on differents patients. ( For those that are interested in Nested Cross Validation: http://scikit-learn.org/stable/auto_examples/model_selection/plot_nested_cross_validation_iris.html ) I proceed that way: pipe = Pipeline([('pca', PCA()), ('clf', SVC()), ]) # Find the best parameters for both the feature extraction and the classifier grid_search = GridSearchCV(estimator=pipe, param_grid=some_param, cv=GroupKFold(n_splits=5), verbose=1) grid_search.fit(X=features, y=labels, groups=groups) # Nested CV with parameter optimization predictions = cross_val_predict(grid_search, X=features, y=labels, cv=GroupKFold(n_splits=5), groups=groups) And get some: File : _split.py", line 489, in _iter_test_indices raise ValueError("The 'groups' parameter should not be None.") ValueError: The 'groups' parameter should not be None. In the code it appear that groups is not shared by _fit_and_predict() method to the estimator and so, groups needed can't be used. Can I have some clues on it? Have a nice day, Best regards
tagged with: python
type: Question
score: 4
upvote count: 4
has answer: http://stackoverflow.com/a/60146997
answer count: 1
downvote count: 0
tagged with: scikit-learn
favorite count: 0
has title: Nest cross validation for predictions using groups
type: UnansweredQuestion

http://stackoverflow.com/comment/90598193
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51816875
type: AnswerComment
has text: thank you. Please, one quick question. How can you tell from the code it's angular element?

http://stackoverflow.com/comment/90826558
comment on: http://stackoverflow.com/a/51922572
score: 0
type: Comment
type: AnswerComment
has text: Maybe the commands here? https://stackoverflow.com/questions/45276830/xcode-version-must-be-specified-to-use-an-apple-crosstool

http://stackoverflow.com/comment/90843643
comment on: http://stackoverflow.com/q/51946571
has text: I would rather not to use private fields like that. Thanks anyway
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51864008
has comment: http://stackoverflow.com/comment/90680109
has comment: http://stackoverflow.com/comment/90687818
has comment: http://stackoverflow.com/comment/90865962
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/90680297
has comment: http://stackoverflow.com/comment/90683062
accepted answer: http://stackoverflow.com/a/52075651
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/90684212
has comment: http://stackoverflow.com/comment/90681221
has comment: http://stackoverflow.com/comment/90680594
tagged with: python
tagged with: jupyter
has title: Numpy no module/attribute when importing other packages depending on it
has answer: http://stackoverflow.com/a/52075651
upvote count: 1
has comment: http://stackoverflow.com/comment/90681082
has body: On 2 distinct independent systems, I have Anaconda/Miniconda. On my default virtual environment on either one, since 2018-8-15, when I import pandas or matplotlib, I get errors module 'numpy' has no attribute '__version__' and module 'numpy' has no attribute 'square', respectively. An update to conda or one of the modules may have done damage, but I haven't been able to figure out. The computers, one is a Mac and one a Windows PC. The only common features are that I use the Jupyter Notebook environment on both systems, both are default environments, both may have deep learning packages installed on them (as opposed to the other environments which are still functioning well), and I've been using the Jupyter Notebook environment to code on both. Has anyone come across this problem? Is there a solution? Is it waiting for a fix update?
tagged with: miniconda
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90684810
tagged with: anaconda
score: 1
has comment: http://stackoverflow.com/comment/90940087

http://stackoverflow.com/q/51822462
has answer: http://stackoverflow.com/a/51822538
accepted answer: http://stackoverflow.com/a/51822538
tagged with: python
possible better answer: http://stackoverflow.com/a/51822534
type: AnsweredQuestion
downvote count: 0
score: 1
linked to: http://stackoverflow.com/q/38067704
has answer: http://stackoverflow.com/a/51822534
type: Question
has body: I have this panda dataframe df. Name Date Score Score2 Joe 26-12-2007 53.45 53.4500 Joe 27-12-2007 52.38 52.7399 Joe 28-12-2007 51.71 51.8500 I would like to convert the date format in the Date column from dd-mm-yyyy to yyyy-mm-dd. The converted dataframe will look like this; Name Date Score Score2 Joe 2007-12-26 53.45 53.4500 Joe 2007-12-27 52.38 52.7399 Joe 2007-12-28 51.71 51.8500 I am using python v3.6 EDIT: The duplicate question assumes that the original date format is yyyy-mm-dd. However, my original date format is dd-mm-yyyy. If I were to apply the answer in that question, the converted dates is wrong. How to change the datetime format in pandas
tagged with: dataframe
answer count: 2
has title: Change date format of dataframe date column
tagged with: pandas
upvote count: 1
favorite count: 0
tagged with: python-3.x
duplicate of: http://stackoverflow.com/q/38067704

http://stackoverflow.com/comment/90757090
type: QuestionComment
has text: interestingly, typing `hash` says hash table is clear yet python still says it is hashed.
score: 0
comment on: http://stackoverflow.com/q/51901570
type: Comment

http://stackoverflow.com/q/51833699
linked to: http://stackoverflow.com/q/51911734
score: 0
answer count: 2
has body: I want my program to cycle through each player, and this code does that. However, on the last player, it displays the info then instantly clears it. I want it to wait for a user to press a keydown (like space or enter) before clearing the screen. I tried implementing this with event = pygame.event.wait() but now my program just hangs when it reaches that declaration. players = {} for player in range(1, int(num_players)+1): name = ask(DISPLAYSURF, "Player " + str(player) + "'s name") player_roll = None while player_roll is None: for event in pygame.event.get(): if event.type == pygame.KEYDOWN: pygame.event.clear() while event.type != pygame.KEYDOWN: event = pygame.event.wait() DISPLAYSURF.fill(WHITE) FIRST_DICE = roll_a_dice() SECOND_DICE = roll_a_dice() player_roll = FIRST_DICE + SECOND_DICE players[name] = player_roll display_dice(FIRST_DICE, SECOND_DICE) our_roll(name) My full code is here: https://github.com/Legitimate/Street-Dice/blob/master/main.py Here is a video of the issue: https://youtu.be/ChxZq0bY4wk
linked to: http://stackoverflow.com/q/20748326
tagged with: python
tagged with: pygame
has answer: http://stackoverflow.com/a/51834946
possible better answer: http://stackoverflow.com/a/51833993
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51833993
has title: Wait for keydown before continuing in Pygame
type: Question
accepted answer: http://stackoverflow.com/a/51834946

http://stackoverflow.com/comment/90711469
has text: I have had issues related to the use of CPU optimisations such as AVX instruction sets that some cloud machines don't use (I don't know about AWS). Could be worth looking into.
type: Comment
comment on: http://stackoverflow.com/q/51879904
score: 0
type: QuestionComment

http://stackoverflow.com/q/51839514
linked to: http://stackoverflow.com/q/45589718
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has title: Python wrap multiple with-statement variables in a method call
tagged with: with-statement
answer count: 0
type: Question
duplicate of: http://stackoverflow.com/q/45589718
has comment: http://stackoverflow.com/comment/90632137
has comment: http://stackoverflow.com/comment/90632035
has body: I have a method with multiple with variables: def my_method(): with A() as a, \ B() as b, \ C(a) as c, \ ... X() as x: ... Now, in order to repeat this with in a couple of methods, I would like to export it to a method of its own. Is there any syntax that will allow me to do that? def needed_with_params(): return (A(), B(), C(a), ..., X()) def my_method(): with needed_with_params() as tuple: ... Which is of course is not correct, but shows my intention.
score: 0

http://stackoverflow.com/comment/90888822
comment on: http://stackoverflow.com/a/51948532
type: AnswerComment
type: Comment
has text: Found this really informative page on the format: https://www.moesif.com/blog/technical/api-design/REST-API-Design-Filtering-Sorting-and-Pagination/ I'll go from there :) Thanks
score: 1

http://stackoverflow.com/comment/90823347
score: 0
type: Comment
has text: I am getting smaller salhike and max month number as 1.
type: AnswerComment
comment on: http://stackoverflow.com/a/51936444

http://stackoverflow.com/comment/90807951
comment on: http://stackoverflow.com/q/51929096
type: QuestionComment
has text: Why are you thinking in terms of columns and SQL? You should be thinking in terms of your models. And since this is almost the simplest thing you can do, what was not covered in the tutorial that left you confused about how to do this?
score: 0
type: Comment

http://stackoverflow.com/a/51893099
has comment: http://stackoverflow.com/comment/90736935
type: Answer
score: 3
upvote count: 3
downvote count: 0
has body: Use re.findall instead, and match digits followed by either A, B, or S: re.findall(r'\d+[ABS]', '11A4B') Output: ['11A', '4B'] If the input might have other alphabetical characters as well, then use a negated character set instead: re.findall(r'[^ABS]+[ABS]', 'ZZZAYYYSXXXB') Output: ['ZZZA', 'YYYS', 'XXXB']
answers question: http://stackoverflow.com/q/51893013

http://stackoverflow.com/comment/90604736
type: QuestionComment
has text: Confirm you're using not just the same python version but also pandas and other libraries. A new version of pandas was released on August 8. https://pandas.pydata.org
score: 1
comment on: http://stackoverflow.com/q/51824991
type: Comment

http://stackoverflow.com/q/51888893
score: 2
downvote count: 0
favorite count: 0
tagged with: python-3.x
tagged with: python
tagged with: regex
answer count: 4
accepted answer: http://stackoverflow.com/a/51889216
has title: Regex to replace words separated by underscore in Python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51888966
upvote count: 2
has body: I am trying to replace specific words (separated by a specific word boundary of underscore) with Python. I know i can just do a string split and loop through the list items to replace the key phrases and then re-join it into string afterwards.. but it does not feel like the most elegant or the best way to go about doing it. So, let's say I create a small function based on regex for the purposes of what i want to do, something like this: def replace_words(string, rep_dict, separator): regex = r'({0}|\b)({1})({2}|\b)'.format(re.escape(separator), '|'.join(rep_dict.keys()), re.escape(separator)) return re.sub(regex, lambda x: '{0}{1}{2}'.format(x.group(1), rep_dict[x.group(2)], x.group(3)), string) Suppose i use any other separator, like for example an asterisk (*), then it works as intended: rep_odds = {'first': '1st', 'third': '3rd', 'fifth': '5th'} rep_evens = {'second': '2nd', 'fourth': '4th'} orders = ['first', 'second', 'third', 'fourth', 'fifth'] before = '*'.join(orders) after = replace_words(before, rep_odds, separator='*') # returns: 1st*second*3rd*fourth*5th after = replace_words(before, {**rep_odds, **rep_evens}, separator='*') # returns: 1st*2nd*3rd*4th*5th But if i change this to use the separator as underscore (_) instead, I get this unexpected and (wrong) behavior: before = '_'.join(orders) after = replace_words(before, rep_odds, separator='_') # returns: 1st_second_3rd_fourth_5th &lt;-- Good after = replace_words(before, {**rep_odds, **rep_evens}, separator='_') # returns: 1st_second_3rd_fourth_5th &lt;-- What went wrong ?! If someone can help me understand this behavior, I am still kind of new to learning regex and how it works in Python ... thanks.
has answer: http://stackoverflow.com/a/51889614
possible better answer: http://stackoverflow.com/a/51888966
type: Question
has answer: http://stackoverflow.com/a/51889247
has comment: http://stackoverflow.com/comment/90728811
has comment: http://stackoverflow.com/comment/90728830
has answer: http://stackoverflow.com/a/51889216

http://stackoverflow.com/comment/90770212
has text: @DebanjanB I understand perfectly well about tags. The tags should be relevant to the question. If you hover each tag, it will describe what the tag covers. You are adding tags that aren't relevant to the questions. I explained in my previous comment. See [tagging](https://stackoverflow.com/help/tagging) for more info.
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51901267

http://stackoverflow.com/comment/90849936
has text: daily_info is a nested list so i think the logic doesn't quite work there. Because we are checking for how many columns doesn't `try: len(daily_info[1]) == 5` work better logically? Because the length of the list changes
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51948205

http://stackoverflow.com/comment/90655196
has text: how are you deleting it?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51851011
score: 0

http://stackoverflow.com/comment/90696765
type: Comment
type: QuestionComment
has text: If you're still getting errors, put the error code here so that we can better help you
score: 0
comment on: http://stackoverflow.com/q/51872583

http://stackoverflow.com/a/51854069
has body: import logging logger = logging.getLogger(__name__) You can either put a self.logger = logging.getLogger(name) in your Generic.init() function, or define a global logger after importing the logging. Refer to this answer : NameError: global name 'logger' is not defined
answers question: http://stackoverflow.com/q/51853806
score: 0
type: Answer

http://stackoverflow.com/comment/90772688
has text: Sample Data where I have few Score as float: KEY,NAME,RANK,BOOKNAME,SCORE,AUTHER 123,ABCD,500,FREEDOM1,15200,PXYZ 133,EFGH,400,FREEDOM2,15300.5,XTYZ nan,SYGH,700,FREEDOM3,15400,RYYZ 143,LKMN,800,FREEDOM4,15500.5,XYCZ
type: Comment
score: 0
comment on: http://stackoverflow.com/a/51910876
type: AnswerComment

http://stackoverflow.com/comment/90703941
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51876184
has text: I am new to python and this stackoverlfow. Could you help me, how to upload data? So that I can upload it here.
score: 0

http://stackoverflow.com/comment/90679109
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51862216
has text: Could you explain me a meaning of this line-> lines[i] = re.sub(r'[0-9.]+', str(x1), lines[i]) rest of things I understood. @rahlf23
score: 0

http://stackoverflow.com/a/51824799
downvote count: 3
has comment: http://stackoverflow.com/comment/134432161
type: Answer
has comment: http://stackoverflow.com/comment/90603686
has comment: http://stackoverflow.com/comment/90603856
has body: You will have to install the Cryptography package. Visit here for more details. Or you can try pip install at the terminal: pip3 install pycrypto
has comment: http://stackoverflow.com/comment/90604009
upvote count: 3
answers question: http://stackoverflow.com/q/51824628
score: 0

http://stackoverflow.com/q/51823228
answer count: 3
tagged with: python
tagged with: tesseract
tagged with: python-tesseract
upvote count: 9
has answer: http://stackoverflow.com/a/60188898
has answer: http://stackoverflow.com/a/51843831
has title: Get orientation pytesseract Python3
possible better answer: http://stackoverflow.com/a/60188898
downvote count: 0
linked to: http://stackoverflow.com/q/44619077
type: Question
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51843831
has body: I want to get the orientation of a scanned document. I saw this post Pytesseract OCR multiple config options and I tried to use --psm 0 to get the orientation. target = pytesseract.image_to_string(text, lang='eng', boxes=False, \ config='--psm 0 tessedit_char_whitelist=0123456789abcdefghijklmnopqrstuvwxyz') But I get an error: FileNotFoundError: [Errno 2] No such file or directory: '/var/folders/jy/np7p4twj4bx_k396hyc_bnxw0000gn/T/tess_dzgtpadd_out.txt'
favorite count: 0
has answer: http://stackoverflow.com/a/55122818
score: 9

http://stackoverflow.com/comment/90648642
score: 0
has text: @aakib use Pythex to help you generate what you want: https://pythex.org/
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51847520

http://stackoverflow.com/q/51873995
has title: Creating behavior flow report without using Google Analytics
score: 0
has comment: http://stackoverflow.com/comment/90806573
tagged with: pandas
has body: I have to create behavior flow report without using GA because we have very large data set and we face the problem of sampling if we are using GA (in this case it creates all the reports based on ~1% of data). We have a table containing all the page visits done by our users. I am not very experienced in data analysis and I can't even think of possible intermediate steps to do this. What are your suggestions?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90803005
tagged with: python
tagged with: clickhouse
answer count: 0
has comment: http://stackoverflow.com/comment/90838117
has comment: http://stackoverflow.com/comment/90802635
tagged with: analysis
type: Question

http://stackoverflow.com/comment/90836292
score: 0
type: Comment
type: QuestionComment
has text: You can leverage the use of default arguments if you don't always want to pass all 8 of them while creating the Contact Object. Something like `def __init__(self, firstname, middlename, lastname, nickname, title_photo=None, email=None, email2=None, email3=None):`. Please note that you can have any other string as the default value for your optional arguments
comment on: http://stackoverflow.com/q/51942665

conventions
tags question: http://stackoverflow.com/q/51933681
tag name: conventions
tags question: http://stackoverflow.com/q/51867912
tags question: http://stackoverflow.com/q/51857641
type: Tag

http://stackoverflow.com/comment/90732647
comment on: http://stackoverflow.com/q/51890489
has text: The expected output is the height, width, left and top for each instance so that it can be manipulated for further use
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/90557526
has text: [Here](http://guilload.com/python-string-interning/).
score: 0
comment on: http://stackoverflow.com/q/51800428
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90724398
comment on: http://stackoverflow.com/q/51886457
score: 0
type: Comment
type: QuestionComment
has text: Each time through the loop, you do spawn a new soldier. In fact, you do this forever. You erase all the existing soldiers by covering them with white snow, then spawn a new German and a new Russian, forever (although eventually they're off the edge of the screen so you won't see them).

http://stackoverflow.com/q/51941418
upvote count: 0
tagged with: tkinter
type: Question
has answer: http://stackoverflow.com/a/51941480
score: -1
has title: How do I execute commands after a tkinter window closes in a function?
answer count: 1
downvote count: 1
favorite count: 0
has body: I have a window with a button, and I want that button to create a new window with a new button. The new button will destroy the new window, and as a result the code should progress and print "hi". from tkinter import * root1 = Tk() def create(): root2 = Tk() Button(root2, text="2", command=lambda: root2.destroy()).grid() root2.mainloop() print("hi") Button(root1, text="1", command=lambda: create()).grid() root1.mainloop() What I am finding is that root2 is created and destroyed just fine, however the "print("hi")" line is only run after root1 is closed. I want the "print("hi") line to be executed straight after I click the button which says "2". Any ideas would be much appreciated. Thanks a lot!
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/91885485
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51868366
has text: @abarnert If you can point me to the POSIX and Windows ways, that'd be really helpful.

http://stackoverflow.com/a/51845772
type: Answer
has comment: http://stackoverflow.com/comment/90644954
has comment: http://stackoverflow.com/comment/90645031
has comment: http://stackoverflow.com/comment/90646465
has body: You want to match on "\\L", not \L, giving you: &gt; (math,text) = separate_mycmd(r'\\L',m) &gt; print math ['\\L'] &gt; print text [' text1 \x07bs{foo} text2 text3 ', '{E.F} text4 '] You also probably wanted to use \\a as well. And you probably also wanted to use it in the string you're searching, giving: m = " text1 \\abs{foo} text2 text3 \\L{E.F} text4 "
score: 0
answers question: http://stackoverflow.com/q/51843321

http://stackoverflow.com/a/51857740
score: 0
answers question: http://stackoverflow.com/q/51857641
has comment: http://stackoverflow.com/comment/90672441
has comment: http://stackoverflow.com/comment/90670106
has body: I'm not aware of any generic standard here, but if it's meant to be replaced, you can use the new string formatting method as follows: string = 'some text {add_text_here} some more text' Then to replace it when you need to: value = 'formatted' string = string.format(add_text_here=value) Now print it out: &gt;&gt;&gt; string 'some text formatted some more text' In fact, this quite neat at the addition of curly {brackets} around the text that needs to be replaced also may make it stand out a little.
type: Answer

http://stackoverflow.com/comment/90810941
type: Comment
comment on: http://stackoverflow.com/q/51930556
has text: Is there a class inside of `sanity_test.py`?
score: 0
type: QuestionComment

http://stackoverflow.com/q/51807522
duplicate of: http://stackoverflow.com/q/36901
has body: I have been attempting to parse variables from a list into a function separately. I don't know how to parse each value from the list into the .format() function. The solution is probably pretty obvious but I can't seem to find it. Here is a simplified version of the code: variables = ["a", "b", "c", "d"] def format(variables): string = "{:^4}" * len(variables) #don't know how to do return string.format(variables_from_list) Ideally, the code would work the same as below: variables = ["a", "b", "c", "d"] def format(variables): string = "{:^4}" * len(variables) print(string.format("a", "b", "c", "d")) Any help is appreciated!
has comment: http://stackoverflow.com/comment/90572137
favorite count: 0
linked to: http://stackoverflow.com/q/36901
tagged with: python
tagged with: python-3.x
answer count: 0
downvote count: 0
type: UnansweredQuestion
score: 1
has title: How to parse values from list into a function as separate values (python)
type: Question
has comment: http://stackoverflow.com/comment/90570308
has comment: http://stackoverflow.com/comment/90570326
has comment: http://stackoverflow.com/comment/90570248
upvote count: 1

http://stackoverflow.com/comment/90702335
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51875438
has text: Alright, I now understand why they're different, is there a way to pass an argument by ref or by pointer specifically, like & or * in c++?
type: Comment

http://stackoverflow.com/comment/90803904
comment on: http://stackoverflow.com/a/51926900
type: Comment
has text: Because `f(x) = a + b^x` is not an [exponential function](https://en.wikipedia.org/wiki/Exponential_function) since it doesn't satisfy the equation `df/dx = Cf(x)`. If OP was happy to use an exponential spacing with a constant shift `a` then you could do what OP wants since you'd then have three constants in the equation `g(x) = a + Cb^x` which would allow you to vary one (presumably `b`).
score: 1
type: AnswerComment

http://stackoverflow.com/comment/90580240
type: Comment
comment on: http://stackoverflow.com/q/51812575
score: 0
has text: You can't use Tkinter from a background thread. There are multiple workarounds, but they're all clunky, and you have to decide which one you want. Just knowing that you've looked at some existing answers without knowing which ones you looked at and what you don't understand, there's really nothing else anyone can tell you that wouldn't just be a repeat of one of those answers you already didn't understand.
type: QuestionComment

http://stackoverflow.com/comment/90783163
type: QuestionComment
has text: I thought python would be a better fit. Obviously I can do it with a shell script tho.
comment on: http://stackoverflow.com/q/51916580
score: 0
type: Comment

http://stackoverflow.com/q/51812095
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90579157
upvote count: 0
has title: Is pandas a local-only library
score: -1
type: Question
answer count: 1
has answer: http://stackoverflow.com/a/51812406
has body: I recently started coding, but took a brief stint. I started a new job and I’m under some confidential restrictions. I need to make sure python and pandas are secure before I do this—I’ll also be talking with IT on Monday I was wondering if pandas in python was a local library, or does the data get sent to or from elsewhere? If I write something in pandas—will the data be stored somewhere under pandas? The best example of what I’m doing is best found on a medium article about stripping data from tables that don’t have csv Exports. https://medium.com/@ageitgey/quick-tip-the-easiest-way-to-grab-data-out-of-a-web-page-in-python-7153cecfca58
tagged with: pandas
downvote count: 1
tagged with: python

http://stackoverflow.com/q/51950002
downvote count: 0
favorite count: 0
possible better answer: http://stackoverflow.com/a/57842296
tagged with: typeerror
type: Question
has answer: http://stackoverflow.com/a/57842296
tagged with: tensorboard
has body: I am using tensorflow version 1.3.0 and tensorboard version 1.10.0 I just updated my tensorboard version and after the update when I am trying to start tensorboard i got the following error message; Traceback (most recent call last): File "c:\users\sztaki_user\anaconda3\envs\tensorflow\lib\runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "c:\users\sztaki_user\anaconda3\envs\tensorflow\lib\runpy.py", line 85, i n _run_code exec(code, run_globals) File "C:\Users\Sztaki_user\Anaconda3\envs\tensorflow\Scripts\tensorboard.exe\_ _main__.py", line 5, in &lt;module&gt; File "c:\users\sztaki_user\anaconda3\envs\tensorflow\lib\site-packages\tensorb oard\main.py", line 40, in &lt;module&gt; from tensorboard import default File "c:\users\sztaki_user\anaconda3\envs\tensorflow\lib\site-packages\tensorb oard\default.py", line 37, in &lt;module&gt; from tensorboard.plugins.audio import audio_plugin File "c:\users\sztaki_user\anaconda3\envs\tensorflow\lib\site-packages\tensorb oard\plugins\audio\audio_plugin.py", line 30, in &lt;module&gt; from tensorboard.plugins.audio import metadata File "c:\users\sztaki_user\anaconda3\envs\tensorflow\lib\site-packages\tensorb oard\plugins\audio\metadata.py", line 22, in &lt;module&gt; from tensorboard.plugins.audio import plugin_data_pb2 File "c:\users\sztaki_user\anaconda3\envs\tensorflow\lib\site-packages\tensorb oard\plugins\audio\plugin_data_pb2.py", line 22, in &lt;module&gt; serialized_pb=_b('\n+tensorboard/plugins/audio/plugin_data.proto\x12\x0btens orboard\"}\n\x0f\x41udioPluginData\x12\x0f\n\x07version\x18\x01 \x01(\x05\x12\x3 7\n\x08\x65ncoding\x18\x02 \x01(\x0e\x32%.tensorboard.AudioPluginData.Encoding\" \n\x08\x45ncoding\x12\x0b\n\x07UNKNOWN\x10\x00\x12\x07\n\x03WAV\x10\x0b\x62\x06 proto3') TypeError: __init__() got an unexpected keyword argument 'serialized_options' I tried to change the tensorboards log directory with the following command: tensorboard --logdir=the log directory Do you have any ideas how to fi…
tagged with: python
upvote count: 2
answer count: 2
has comment: http://stackoverflow.com/comment/90850685
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/90887929
has answer: http://stackoverflow.com/a/54398959
accepted answer: http://stackoverflow.com/a/54398959
has comment: http://stackoverflow.com/comment/90888125
has title: Tensorboard TypeError: __init__() got an unexpected keyword argument 'serialized_options'
score: 2
type: AnsweredQuestion

http://stackoverflow.com/comment/90758548
type: QuestionComment
has text: Do you want to avoid repeating that block of code or something else? why do you want to merge them? If you need them in templates, you can send them via a context processor once and they will be available
score: 0
comment on: http://stackoverflow.com/q/51903751
type: Comment

http://stackoverflow.com/comment/90731744
type: QuestionComment
has text: @Tanmayjain no difference. no, `parents[] = []` is incorrect, typo. (it's not the issue)
comment on: http://stackoverflow.com/q/51890339
score: 0
type: Comment

http://stackoverflow.com/a/51908607
has body: Kafka does have strict restriction over the size of data; default is 1MB. I believe you have missed topic level config. There are multiple configs at different levels: You have a broker setting message.max.bytes (default is 1000012) http://kafka.apache.org/documentation/#brokerconfigs There is a topic level config max.message.bytes (default is 1000012) http://kafka.apache.org/documentation/#topicconfigs Producer has max.request.size (default is 1048576) http://kafka.apache.org/documentation/#producerconfigs Consumer has max.partition.fetch.bytes (default is 1048576) http://kafka.apache.org/documentation/#consumerconfigs
type: Answer
answers question: http://stackoverflow.com/q/51903803
score: 2
downvote count: 0
upvote count: 2

c++
tags question: http://stackoverflow.com/q/51820904
tags question: http://stackoverflow.com/q/51805078
tags question: http://stackoverflow.com/q/51833291
type: Tag
tags question: http://stackoverflow.com/q/51955605
tags question: http://stackoverflow.com/q/51883544
tags question: http://stackoverflow.com/q/51902317
tags question: http://stackoverflow.com/q/51948983
tags question: http://stackoverflow.com/q/51808891
tags question: http://stackoverflow.com/q/51906096
tags question: http://stackoverflow.com/q/51944206
tags question: http://stackoverflow.com/q/51852310
tags question: http://stackoverflow.com/q/51856485
tags question: http://stackoverflow.com/q/51866202
tags question: http://stackoverflow.com/q/51918395
tags question: http://stackoverflow.com/q/51934871
tags question: http://stackoverflow.com/q/51867653
tags question: http://stackoverflow.com/q/51903324
tags question: http://stackoverflow.com/q/51905284
tags question: http://stackoverflow.com/q/51907232
tags question: http://stackoverflow.com/q/51835532
tags question: http://stackoverflow.com/q/51933309
tag name: c++
tags question: http://stackoverflow.com/q/51887916

http://stackoverflow.com/a/51819428
accepted answer of: http://stackoverflow.com/q/51818797
answers question: http://stackoverflow.com/q/51818797
type: AcceptedAnswer
upvote count: 9
type: Answer
downvote count: 0
has body: Nothing is explicit about that. Simply the documentation of a the abstractmethod decorator says: A class that has a metaclass derived from ABCMeta cannot be instantiated unless all of its abstract methods and properties are overridden. And PEP 3119 says: A class containing at least one method declared with this decorator that hasn't been overridden yet cannot be instantiated. and later Implementation: The @abstractmethod decorator sets the function attribute __isabstractmethod__ to the value True. The ABCMeta.__new__ method computes the type attribute __abstractmethods__ as the set of all method names that have an __isabstractmethod__ attribute whose value is true. It does this by combining the __abstractmethods__ attributes of the base classes, adding the names of all methods in the new class dict that have a true __isabstractmethod__ attribute, and removing the names of all methods in the new class dict that don't have a true __isabstractmethod__ attribute. If the resulting __abstractmethods__ set is non-empty, the class is considered abstract, and attempts to instantiate it will raise TypeError. My interpretation of the implementation part is that @abstractmethod never prevents the method to be called but only say that that class cannot be instantiated and that a subclass will still be abstract unless it overrides all of its abstract methods. So I would not say that it is by design, but it is at least an assumed side effect.
score: 9

http://stackoverflow.com/q/51878786
type: Question
has body: I am trying to copy row from one database server to another and then assigning different values to some fields. prod_conn = pymysql.connect(prod_common_db_endpoint, prod_user, prod_password, prod_common_table_name) prod_cursor = prod_conn.cursor() prod_ConnectFirm_table = prod_cursor.execute("select * from beta2_Common.Firm where id = " + prod_source_firm + ";") data = prod_cursor.fetchall() for row in data: oef_name = row[1] oef_path = row[2] oef_username = row[5] oef_password = row[6] oef_poolLimit = row[7] oef_database = row[8] oef_port = row[9] oef_serverGroupId = row[10] oef_threadWeight = row[11] oef_isDeleted = row[12] oef_tags = row[13] oef_createdBy = row[14] oef_createdDate = row[15] oef_editedBy = row[16] oef_editedDate = row[17] if env == "dev": oef_server = 'dev-firmdb1-cluster.cluster-xxxxxxxxxxx.us-east-1.rds.amazonaws.com' oef_roServer = 'dev-firmdb1-cluster.cluster-ro-xxxxxxxxxxx.us-east-1.rds.amazonaws.com' elif env == "beta": oef_server = 'beta-cluster.cluster-xxxxxxxxxxx.us-east-1.rds.amazonaws.com' oef_roServer = 'beta-cluster.cluster-ro-xxxxxxxxxxx.us-east-1.rds.amazonaws.com' conn = pymysql.connect(target_common_db_endpoint, user, password, common_schema_name) cursor = conn.cursor() add_Firm_command = ("INSERT INTO Common.Firm " "(id, name, path, server, roServer, username, password, poolLimit, database, port, serverGroupId, threadWeight, \ isDeleted, tags, createdBy, createdDate, editedBy, editedDate) " "VALUES (%(oef_last_id)s, %(oef_name)s, %(oef_path)s, %(oef_server)s, %(oef_roServer)s, %(oef_username)s, %(oef_password)s, \ %(oef_poolLimit)s, %(oef_database)s, %(oef_port)s, %(oef_serverGroupId)s, %(oef_threadWeight)s, %(oef_isDeleted)s, %(oef_tags)s, \ %(oef_createdBy)s, %(oef_createdDate)s, %(oef_editedBy)s, %(oef_editedDate)s)") oef_last_id = conn.insert_id() Firm_values = { 'oef_last_id' : oef_last_id, 'oef_name' : oef_name, 'oef_path' : oef_path, 'oef_server' : oef_server, 'oef_roServer' : oef_roServer, 'oef_username' : oef_username, '…
score: 0
has title: Copying row from one database to another and changing some values
answer count: 1
tagged with: pymysql
tagged with: python
has answer: http://stackoverflow.com/a/51888429
type: UnansweredQuestion
tagged with: mysql

http://stackoverflow.com/q/51812368
has title: Retrieving data from a DB and send it via mail
tagged with: python-3.x
has body: I am creating a script that takes some data from a database and then it sends it via mail. Unfortunately, I am stuck with something that seems very easy to do. If there is only one entry from the DB it works perfectly (ex: 18/10/18 - Do math exercises) but if there are multiple entries they don't show up, I thought about using a while loop but as I have to keep all the entries in the same variable I can't get it working. I share the code below: # Enviar correu Python 3.6 (NO ANOMENAR EMAIL.PY) import smtplib, pymysql.cursors, secrets, re, datetime from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from time import strftime def dbb(): connection = pymysql.connect(host='X', user='root', password='X', db='deuresc', charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor) try: with connection.cursor() as cursor: # Llegim tots els recordatoris dataactual = strftime('%Y-%m-%d') data = datetime.datetime.strptime(dataactual, "%Y-%m-%d") datafinal = data + datetime.timedelta(days=1) sql = "SELECT * FROM `deures` WHERE `data`=%s" cursor.execute(sql, datafinal) resultat = cursor.fetchall() for row in resultat: data = str(row['data']) print(data) tasca = str(row['tasca']) print(tasca) # It prints all the values but it doesn't send them below. fromaddr = "X" PASSWORD = "X" welcome = ['Jefe', 'Gery', 'Boss', 'Gary'] # Misstage del correu SUBJECT = "Recordatori deures " + data body = "Bon dia " + secrets.choice(welcome) + ',' + '\n' + 'Tens les següents tasques programades per demà: ' + '\n' + data + ' ' + tasca toaddr = "X" try: msg = MIMEMultipart() msg['From'] = fromaddr msg['To'] = toaddr msg['Subject'] = SUBJECT msg.attach(MIMEText(body, 'plain')) # Detalles del servidor de correu (Gmail, SMTP, Port: 587, TLS) server = smtplib.SMTP('smtp.gmail.com', 587) server.starttls() server.login(fromaddr, PASSWORD) text = msg.as_string() server.sendmail(fromaddr, toaddr, text) server.quit() print("S'ha enviat el recordatori a '" + toaddr + "' satisfact…
tagged with: python
answer count: 1
has answer: http://stackoverflow.com/a/51816932
score: 0
tagged with: pymysql
accepted answer: http://stackoverflow.com/a/51816932
type: Question
type: AnsweredQuestion
tagged with: email

http://stackoverflow.com/comment/90645118
comment on: http://stackoverflow.com/q/51840480
score: 0
has text: I think [this](https://stackoverflow.com/a/46310416/3944322) is what you're looking for (making a file-like object from your csv files to be used with read_csv).
type: QuestionComment
type: Comment

http://stackoverflow.com/q/51842011
type: Question
tagged with: pandas
accepted answer: http://stackoverflow.com/a/51842094
tagged with: python
score: 1
tagged with: python-3.x
upvote count: 1
answer count: 1
tagged with: dataframe
has title: How to order DataFrame in python with special structure of date?
has body: I have a DataFrame in python, the cell value is the purchase quantity like: code 1/18 2/18 3/18 4/18 5/18 1 NaN 15 15 16 14 2 NaN NaN 30 23 24 3 24 21 23 NaN 26 I want to order the code in terms of the date they were first purchased, the result would be: code 1/18 2/18 3/18 4/18 5/18 3 24 21 23 NaN 26 1 NaN 15 15 16 14 2 NaN NaN 30 23 24 Please help!
has answer: http://stackoverflow.com/a/51842094
type: AnsweredQuestion
downvote count: 0
tagged with: sorting
favorite count: 0

http://stackoverflow.com/q/51815128
has answer: http://stackoverflow.com/a/51815252
upvote count: 1
answer count: 1
downvote count: 1
tagged with: virtualenv
has title: virtualenv weird behavior: forced to use system python interpreter
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90584654
has comment: http://stackoverflow.com/comment/90584669
has body: EDIT: TL;DR: I can see that my question is ambiguous. Summary of it, u can understand that whatever I do, the virtualenv keep using system python interpreter (from /usr/bin/), even if I manually specify it by virtualenv -p. Stranger thing is if I use virtualenv -p python3, it works. Ok here's the deal I have anaconda2, and anaconda is in PATH. Current python, virtualenv, pip is from anaconda2. When I type python: Python 2.7.14 |Anaconda, Inc.| (default, Dec 7 2017, 17:05:42) [GCC 7.2.0] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; When I create new virtualenv, source it, which python does show the python interpreter from the virtualenv, but when I run python, something weird happended: Python 2.7.12 (default, Nov 19 2016, 06:48:10) [GCC 5.4.0 20160609] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; Upon my knowledge, virtualenv will use the python interpreter that virtualenv was installed with (virtualenv --help says so). That 2.7.12 python, not the same as the above python (2.7.14). So I thought that "Ok maybe there is something wrong with my anaconda2's python. Let's use another one". I used another python by specifying the flag -p (I have many python versions installed on my machine. It's a remote server with many people accessing it, I've just pointed to one of my colleague's python. I can be sure there is no environment conflict here, we all use virtualenv for project and control each person's $PATH preferences via ~/.bash_aliases ) No help. I start being confused. Ok maybe virtualenv is broken. Maybe pip is broken. Maybe anaconda is broken. Checked the path, seems tobe normal. Reinstalled everything, no help at all. Right now, I have to use system python (at least it's not directly /usr/bin/python, but /path/to/virtualenv/python. At least I don't need sudo everywhere). Nothing much change here, but I feel so unhappy and desperately want to know the reason. Can anyon…
has comment: http://stackoverflow.com/comment/90584622
type: Question
score: 0

http://stackoverflow.com/comment/90683221
has text: I got that part. But ALL of the text or only certain parts of the text?
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51864323
type: Comment

http://stackoverflow.com/comment/90605719
type: AnswerComment
comment on: http://stackoverflow.com/a/51825644
score: 0
type: Comment
has text: Still does not work for me. It uses the month - feb18- as the index and not the column 'name'

http://stackoverflow.com/a/51889695
type: Answer
score: 2
downvote count: 0
has body: import numpy as np import matplotlib.pyplot as plt imageArray = plt.imread('earth.jpg') # Don't use loops. Just use image slicing since imageArray is a Numpy array. # (i, j) is the row and col index of the top left corner of square. imageArray[i:i + 20, j:j + 20] = (255, 0, 0)
upvote count: 2
answers question: http://stackoverflow.com/q/51888836

http://stackoverflow.com/comment/92152520
has text: @JoshuaNixon that doesn't apply to sqlalchemy model
comment on: http://stackoverflow.com/q/51949279
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/90713613
has text: Did you mean I can create a dictionary `search_params` such that one of the key-value pair is `{'sort': 'value desc'}` and then my default sort order will be `value desc`?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51877630
type: Comment

http://stackoverflow.com/comment/90787521
type: Comment
type: QuestionComment
score: 0
has text: Fix the circular import problem instead.
comment on: http://stackoverflow.com/q/51918856

http://stackoverflow.com/q/51804721
tagged with: python
score: 1
favorite count: 0
has title: Memoized vs non-memoized time complexity analysis for combination sums
has answer: http://stackoverflow.com/a/51809639
has comment: http://stackoverflow.com/comment/90613962
answer count: 2
has comment: http://stackoverflow.com/comment/90565362
upvote count: 1
tagged with: algorithm
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90569813
has comment: http://stackoverflow.com/comment/90622555
downvote count: 0
has answer: http://stackoverflow.com/a/51846926
has body: I'm trying to understand why using lru_cache to solve this problem yields a slower performance of the code. The question is essentially to return all combinations that add up to a certain target. I'm using the lru_cache decorator to do the memoization (docs), and this is my solution: from functools import lru_cache def combinationSum(candidates, target): return dfs(tuple(candidates), 0, target) @lru_cache(maxsize=None) def dfs(candidates, i, target): if target &lt; 0: return [] if target == 0: return [[]] if i == len(candidates): return [] final_results = [] for j in range(i, len(candidates)): results = dfs(candidates, j, target - candidates[j]) for x in results: final_results.append([candidates[j]] + x) return final_results It seems like when the lru_cache decorator is commented out, I get almost a 50% increase in the runtime speed of this algorithm. This seems a little counter intuitive as I thought the time complexity of the solution should be reduced, even with the increased overhead of function calls to retrieve results from the memoization. For the memoized solution, I believe the time complexity should be O(n^2*k*2^n) where n is the length of the array, and k being all numbers in the range from 0 to target. This is my analysis (need a little help verifying): time complexity = possible states for memoization x work done at each step = (n * k) * (n * maximum size of results) = n * k * n * 2^n I'm also missing some gaps in my knowledge on how to analyze the time complexity of the recursive solution, I could use some help in doing so! EDIT: I'm using range(1, 10000) as a test input, here are the benchmarks: # with lru_cache $ time python3 combination_sum.py CacheInfo(hits=59984, misses=49996, maxsize=None, currsize=49996) real 0m4.031s user 0m3.996s sys 0m0.024s # without lru_cache $ time python3 combination_sum.py real 0m0.073s user 0m0.060s sys 0m0.010s
has comment: http://stackoverflow.com/comment/90622473
type: Question
tagged with: dynamic-programming
has comment: http://stackoverflow.com/comment/90622539

dask
tags question: http://stackoverflow.com/q/51822669
type: Tag
tags question: http://stackoverflow.com/q/51809076
tags question: http://stackoverflow.com/q/51894019
tags question: http://stackoverflow.com/q/51930488
tag name: dask
tags question: http://stackoverflow.com/q/51945646
tags question: http://stackoverflow.com/q/51884682
tags question: http://stackoverflow.com/q/51862846
tags question: http://stackoverflow.com/q/51879576
tags question: http://stackoverflow.com/q/51931942
tags question: http://stackoverflow.com/q/51908579
tags question: http://stackoverflow.com/q/51831161

http://stackoverflow.com/a/51955402
accepted answer of: http://stackoverflow.com/q/51950957
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90897929
answers question: http://stackoverflow.com/q/51950957
type: Answer
downvote count: 0
score: 1
has body: Always provide as much informations as possible (some example data, Python/Cython Version, Compiler Version/Settings and CPU Model. Without that it is quite hard to compare any timings. For example this problem benefits quite well from SIMD-vectorization. It will make quite a difference which compiler you use or if you want to redistribute a compiled version which should also run on low-end or quite old CPUS (eg. no AVX). I am not very familiar with Cython, but I think your main problem is the missing declaration for scanData. Maybe the C-Compiler needs additional flags like march=native, but the real syntax is compiler dependend. I am am also not sure how Cython or the C-compiler optimizes this part: arrayDiff = np.subtract(topShift, bottomShift) arraySquared = np.square(arrayDiff) arrayMean = np.mean(arraySquared, axis = 0) If that loops (all vectorized commands are actually loops) are not joined, but intead there are temporary arryas like in pure Python created, this will slow down the code. It will be a good idea to create a 1D array first. (eg. scanData=scanData[::1] As said I am not that familliar with Cython, I tried what is possible with Numba. At least it shows what should also be possible with a resonable good Cython implementation. Maybe easier to otimize for the compiler import numba as nb import numpy as np @nb.njit(fastmath=True,error_model='numpy',parallel=True) #scanData is a 1D-array here def hdcfTransfomation(scanData): scanLength = scanData.shape[0] hdcfFunction = np.zeros(scanLength, dtype = scanData.dtype) for position in nb.prange(scanLength - 1): topShift = scanData[1 + position:] bottomShift = scanData[:scanData.shape[0]-(position + 1)] sum=0. jj=0 for i in range(scanLength-(position + 1)): jj+=1 sum+=(topShift[i]-bottomShift[i])**2 hdcfFunction[position] = sum/jj return hdcfFunction I also used parallelization here, because the problem is embarrassingly parallel. At least with a size of 80_000 and Numba it doesn't matter if you use a slightl…
has comment: http://stackoverflow.com/comment/90961926
has comment: http://stackoverflow.com/comment/90898316

http://stackoverflow.com/q/51808020
has title: Why is the child method called here from the base class?
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/90571182
type: Question
has comment: http://stackoverflow.com/comment/90571215
has comment: http://stackoverflow.com/comment/90571290
tagged with: inheritance
score: 0
linked to: http://stackoverflow.com/q/119506
answer count: 1
tagged with: python
has body: I dont understand why the childs method set_state() is called here, when i call it from the __init__() method of the base class: class base(): def __init__(self, x): self.set_state(x) def set_state(self, x): self.x = x print("base") class child(base): def __init__(self, x, y): super().__init__(x) self.set_state(y) def set_state(self, y): self.y = y print("child") test = child(1, 2) Output is: child child
favorite count: 0
has comment: http://stackoverflow.com/comment/90571204
tagged with: super
has comment: http://stackoverflow.com/comment/90571185
has comment: http://stackoverflow.com/comment/90571246
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51808089

http://stackoverflow.com/a/51841652
has body: If you have many columns to aggregate across many rows, you can aggregate via taking the NumPy array representation and then casting to a list of lists. Then use GroupBy + apply as normal: df = pd.DataFrame({'user': ['a', 'a', 'c'], 'prod': ['prod_1', 'prod_2', 'prod_1'], 'prod_cat': ['cat_1', 'cat_2', 'cat_1'], 'sub_cat': ['sub_1', 'sub_2', 'sub_3'], 'goal_label': [5, 5, 1]}) df['comb'] = df'prod', 'prod_cat', 'sub_cat'.values.tolist() res = df.groupby('user')['comb'].apply(list).tolist() print(res) [[['prod_1', 'cat_1', 'sub_1'], ['prod_2', 'cat_2', 'sub_2']], 'prod_1', 'cat_1', 'sub_3']
type: Answer
answers question: http://stackoverflow.com/q/51839761
score: 0

http://stackoverflow.com/q/51822709
has comment: http://stackoverflow.com/comment/90600763
favorite count: 0
has comment: http://stackoverflow.com/comment/90600329
has title: How to use conditionnal statement with startswith() on Python - dfply?
tagged with: pandas
tagged with: python
has comment: http://stackoverflow.com/comment/90600282
has comment: http://stackoverflow.com/comment/90601273
tagged with: dplyr
has comment: http://stackoverflow.com/comment/90600652
has comment: http://stackoverflow.com/comment/90599566
tagged with: dfply
linked to: http://stackoverflow.com/q/20109391
has comment: http://stackoverflow.com/comment/90601339
has comment: http://stackoverflow.com/comment/90600290
has answer: http://stackoverflow.com/a/51823441
accepted answer: http://stackoverflow.com/a/51823441
has comment: http://stackoverflow.com/comment/90600762
type: AnsweredQuestion
has body: I'm doing data wrangling on Python, using the package dfply. I want to create a new variable "a06", from 'FC06' of the dataset data_a, so that : a06 = 1 if FC06[i] starts with the character "1" (ex : FC06[i]=173) a06 = 2 if FC06[i] starts with the character "2" a06 = NaN if FC06[i] = NaN For instance, with the input : df = pd.DataFrame({'FC06':[173,170,220,float('nan'),110,230,float('nan')]}) I want to get the output : df1= pd.DataFrame({'a06':[1,1,2,float('nan'),1,2,float('nan')]}) On R it would be obtained by : data_a %&gt;% mutate(a06 = ifelse(substr(FC06,1,1)=="1",1,ifelse(substr(FC06,1,1)=="1",2,NaN))) but I don't find how to do this with Python. I achieved a first version with just 2 alternatives : NaN or 1, with : data_a &gt;&gt; mutate(a06=if_else((X['FC06'].apply(pd.isnull)),float('nan'),1) but I can't find how to differentiate the result according to the first character of FC06. (I tried things like : (data_a &gt;&gt; mutate(a06=if_else(X['FC06'].apply(pd.isnull),float('nan'),if_else(X['FC06'].apply(str)[0]=='1',1,2)))) but without success : - [0] doesn't work there to get the first character - and/or str() can't be used with apply (neither str.startswith('1')) Does anybody knows how to solve such situations ? Or another package to do that on Python ? Thank you !!
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/90600315
tagged with: apply
type: Question
has comment: http://stackoverflow.com/comment/90600480
upvote count: 1
answer count: 1

http://stackoverflow.com/q/51904191
type: Question
upvote count: 1
favorite count: 0
tagged with: python
has body: I wish to read data from a spectrometer and plot a frequency vs intensity graph inside a PyQt5 Gui, I have done all other stuff and the following code plots a graph: plot1 = pg.PlotWidget() plot2 =pg.PlotWidget() layout.addWidget(plot1,2,3,15,10) layout.addWidget(plot2,100,3,5,10) sptdll.getFrame(byref(spectra),0xFFFF) #this is just that my program takes data from a dll file b = np.frombuffer(spectra, dtype=np.uint16) plot1.plot(data,b[0:3653],pen='g') # data is my x axis array, and b is y axis Now my problem I want this graph to run live, that is change with time, I was able to do that in matplotlib as follows: fig = plt.figure() ax1 = fig.add_subplot(1,1,1) def animate(i): sptdll.getFrame(byref(spectra),0xFFFF) b = np.frombuffer(spectra, dtype=np.uint16) ax1.clear() ax1.plot(data,b[0:3653]) ani = animation.FuncAnimation(fig, animate, interval=10) plt.show() but since i want to do the same with pyqtgraph inside my GUI; can somebody help, I am attaching the current screenshot of my GUI. Image of Gui, I need the green graph to go live.
answer count: 0
downvote count: 0
type: UnansweredQuestion
score: 1
tagged with: pyqtgraph
tagged with: matplotlib
has title: Live Plotting using pyqtgraph

http://stackoverflow.com/comment/94195977
comment on: http://stackoverflow.com/q/51808229
score: 1
has text: I had the same problem. The problem went away after installing pyqt5-tools. I went through the steps of uninstalling and re-installing pyqt5 packages: 'pip uninstall pyqt5', 'pip uninstall pyqt5-tools' (Skipped as it is not installed), 'pip install pyqt5', 'pip install pyqt5-tools'. I assume that the pyqt5-tools were missing.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51827710
has body: i want a python re to match exact one occurrence of / . indeed if occurs more / such as // or /// re shouldn't match any of them. for example below inputs must convert: a/b -> a b a//b -> a//b a/// -> a///b
has answer: http://stackoverflow.com/a/51827753
has comment: http://stackoverflow.com/comment/90609771
has answer: http://stackoverflow.com/a/51827795
type: Question
upvote count: 4
has answer: http://stackoverflow.com/a/51828598
downvote count: 0
score: 4
answer count: 3
tagged with: python
has title: python re match exact only one occurrence (no repeat Consecutive)
tagged with: regex
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion

http://stackoverflow.com/a/51829163
upvote count: 1
score: 1
has body: I ended up solving it by basically 'starting over again': I removed the access for the 'Cleo' third-party app, re-downladed the client_secret.json file, and went to localhost:8000/test again in an incognito window. After logging in, it seems that page indeed returns the expected JSON response: I'm not sure which of these steps 'did the trick'; why did it not work with the existing access (if that was the problem)?
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51828397
answers question: http://stackoverflow.com/q/51828397
type: Answer

http://stackoverflow.com/a/53248019
downvote count: 0
answers question: http://stackoverflow.com/q/51852131
type: Answer
upvote count: 1
has body: Although the answer is a bit late - your mistake is that you mix &lt;> and {} in your template. Instead of &lt;% block content %&gt;&lt;% endblock content %&gt; it should be {% block content %}{% endblock content %}.
score: 1

http://stackoverflow.com/a/51846089
score: -1
upvote count: 0
has comment: http://stackoverflow.com/comment/90652041
type: Answer
answers question: http://stackoverflow.com/q/51845854
downvote count: 1
has body: with open('country_simple_info.csv', 'w', encoding='utf-8') as outputFile: writer = csv.DictWriter(outputFile, reader.fieldnames) writer.writeheader() writer.writerows(result) Using the "with open" statement will force the outputFile to close when it goes out of scope and thus saving the text written to it. Hope this helps.

http://stackoverflow.com/comment/90577472
comment on: http://stackoverflow.com/a/51806777
score: 0
type: AnswerComment
has text: What's the reasoning behind storing the ip address in the form 'ZGL3Ywx5YwR1YwR2AN==' rather than just having the address.
type: Comment

http://stackoverflow.com/comment/90801707
has text: hello thanks for your solution you helped me fix half of the problem which was to end when the user said no, but how do I also make the program tell the user to again type either yes or no when they are just pressing enter or typing some random words,
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51925900

http://stackoverflow.com/q/51877242
type: Question
has comment: http://stackoverflow.com/comment/90705675
has body: tensorflow - 1.9.0 numpy - 1.13.1 i try to install tensorflow and it throws me RuntimeError : RuntimeErrorTraceback (most recent call last) RuntimeError: module compiled against API version 0xc but this version of numpy is 0xb RuntimeErrorTraceback (most recent call last) RuntimeError: module compiled against API version 0xc but this version of numpy is 0xb though it gives an error while importing, something did happen because running tf.contrib.layers does not give tf not found but another error: AttributeErrorTraceback (most recent call last) &lt;ipython-input-2-28c9425cf301&gt; in &lt;module&gt;() ----&gt; 1 tf.contrib.layers /opt/ds/local/lib/python2.7/site-packages/tensorflow/python/util/lazy_loader.pyc in __getattr__(self, item) 51 52 def __getattr__(self, item): ---&gt; 53 module = self._load() 54 return getattr(module, item) 55 /opt/ds/local/lib/python2.7/site-packages/tensorflow/python/util/lazy_loader.pyc in _load(self) 40 def _load(self): 41 # Import the target module and insert it into the parent's namespace ---&gt; 42 module = importlib.import_module(self.__name__) 43 self._parent_module_globals[self._local_name] = module 44 /usr/lib/python2.7/importlib/__init__.pyc in import_module(name, package) 35 level += 1 36 name = _resolve_name(name[level:], package, level) ---&gt; 37 __import__(name) 38 return sys.modules[name] /opt/ds/local/lib/python2.7/site-packages/tensorflow/contrib/__init__.py in &lt;module&gt;() 37 from tensorflow.contrib import deprecated 38 from tensorflow.contrib import distribute ---&gt; 39 from tensorflow.contrib import distributions 40 from tensorflow.contrib import estimator 41 from tensorflow.contrib import factorization /opt/ds/local/lib/python2.7/site-packages/tensorflow/contrib/distributions/__init__.py in &lt;module&gt;() 38 from tensorflow.contrib.distributions.python.ops.distribution_util import softplus_inverse 39 from tensorflow.contrib.distributions.python.ops.distribution_util import tridiag ---&gt; 40 from tensorflow.co…
upvote count: 2
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/90706282
favorite count: 0
has title: RuntimeError importing tensorflow that goes away the second time it is imported
type: UnansweredQuestion
tagged with: python
score: 2
answer count: 0
downvote count: 0
tagged with: tensorflow

http://stackoverflow.com/comment/90747350
type: Comment
comment on: http://stackoverflow.com/a/51898063
score: 0
type: AnswerComment
has text: Yes, was looking for `setdefault` there, too early in the morning :P

http://stackoverflow.com/a/51839323
upvote count: 2
answers question: http://stackoverflow.com/q/51838887
score: 2
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/90697757
has body: See this. It says "In addition to using a static/ directory inside your apps, you can define a list of directories (STATICFILES_DIRS) in your settings file where Django will also look for static files." The example that they give puts static in the specification of the additional directory, but that appears to be inessential. So you would just list your /demo/faces/male and /demo/faces/female/ directories.

http://stackoverflow.com/q/51899780
has body: I import a header and footer with PHP in which I close the head, start and close the body, and close html. Like this: &lt;html&gt; &lt;head&gt; &lt;?php include ('Header.php');?&gt; CODE &lt;?php include ('Footer.php');?&gt; Beautiful soup tries to fix this by inserting tags to fix my 'broken' ones. &lt;html&gt; &lt;head&gt; &lt;?php include ('Header.php');?&gt; &lt;/head&gt;&lt;body&gt; &lt;------------------------- CODE &lt;?php include ('Footer.php');?&gt; &lt;/body&gt;&lt;/html&gt; &lt;------------------------- I know Beautiful Soup is working as intended, but how can I either remove the added tags, or make Beautiful Soup not add them. I've tried the lxml parser but it did the same exact thing. Thanks.
tagged with: parsing
tagged with: beautifulsoup
type: UnansweredQuestion
has title: Prevent Beautiful Soup from closing my tags
tagged with: python
tagged with: php
has comment: http://stackoverflow.com/comment/90750922
type: Question
answer count: 1
has comment: http://stackoverflow.com/comment/90750654
score: 0
has comment: http://stackoverflow.com/comment/90753952
tagged with: http://stackoverflow.com/tag/html
has answer: http://stackoverflow.com/a/51910262

http://stackoverflow.com/q/51842358
upvote count: 1
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/90865379
has comment: http://stackoverflow.com/comment/90638321
type: UnansweredQuestion
tagged with: python
downvote count: 0
has comment: http://stackoverflow.com/comment/90942528
score: 1
has comment: http://stackoverflow.com/comment/90638851
has title: Does pyperclip have a maximum of characters?
has answer: http://stackoverflow.com/a/51842723
type: Question
tagged with: pyperclip
linked to: http://stackoverflow.com/q/1880321
has body: I have a problem using pyperclip. I have to upload a bunch of documents to the web. I used the join method to make a string of the files contained in a specific folder. The problem comes when that string reaches 260 characters. pyperclip copies up to 260, the rest is not copied. Is there a way I can change this? Or another method I can use? from os import listdir from os.path import isfile, join cell1 = str(cell1) my_path = "C:\Users\\"+user+"\Desktop\folder\\"+cell1 onlyfiles = [f for f in listdir("C:\Users\\"+user+"\Desktop\folder\\"+cell1) if isfile(join(my_path, f))] for doc in onlyfiles: doc = '" "'.join(map(str, onlyfiles)) docs = '"' + doc + '"' print docs time.sleep(1) #copiar directorio from pyperclip import copy copy(my_path) keyboard.press(Key.ctrl) keyboard.press('v') keyboard.release(Key.ctrl) keyboard.release('v') time.sleep(1.5) keyboard.press(Key.enter) keyboard.release(Key.enter)

http://stackoverflow.com/comment/90792521
has text: Unfortunately, I get the same error. Maybe someone else knows? Also, do you have any idea about Question2? The confusion matrix shows error. Would you know why it is?
comment on: http://stackoverflow.com/q/51921075
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/90851047
type: Comment
has text: @JoeMoss - Does your machine have Microsoft Office installed? If so, is it 32-bit or 64-bit?
score: 0
comment on: http://stackoverflow.com/q/51936010
type: QuestionComment

http://stackoverflow.com/q/51886536
answer count: 0
downvote count: 0
has body: I tried to create a Kivy APK using Buildozer but I keep receiving the same error no matter what I do. I am using Ubuntu. Here is the Error: [INFO]: STDOUT (last 20 lines of 172): jnius/jnius.c:47655:20: warning: format '%zd' expects argument of type 'signed size_t', but argument 4 has type 'long int' [-Wformat=] jnius/jnius.c: In function '__Pyx_GetBufferAndValidate': jnius/jnius.c:47902:7: warning: format '%zd' expects argument of type 'signed size_t', but argument 3 has type 'Py_ssize_t' [-Wformat=] dtype-&gt;name, (Py_ssize_t)dtype-&gt;size, (dtype-&gt;size &gt; 1) ? "s" : ""); ^ jnius/jnius.c:47902:7: warning: format '%zd' expects argument of type 'signed size_t', but argument 6 has type 'long int' [-Wformat=] jnius/jnius.c: In function '__Pyx_ValidateAndInit_memviewslice': jnius/jnius.c:51148:22: warning: format '%zu' expects argument of type 'size_t', but argument 3 has type 'Py_ssize_t' [-Wformat=] (dtype-&gt;size &gt; 1) ? "s" : ""); ^ jnius/jnius.c: In function '__pyx_f_5jnius_5jnius_convert_python_to_jobject': jnius/jnius.c:11068:21: warning: '__pyx_v_retmidinit' may be used uninitialized in this function [-Wmaybe-uninitialized] __pyx_v_retobject = (__pyx_v_j_env[0])-&gt;NewObjectA(__pyx_v_j_env, __pyx_v_retclass, __pyx_v_retmidinit, __pyx_v_j_ret); ^ jnius/jnius.c:11068:21: warning: '__pyx_v_retclass' may be used uninitialized in this function [-Wmaybe-uninitialized] creating build/lib.linux-x86_64-2.7 creating build/lib.linux-x86_64-2.7/jnius /home/perrythekeypad/Documents/Android Python Development/.buildozer/android/platform/python-for-android-new-toolchain/pythonforandroid/tools/liblink.sh --sysroot /home/perrythekeypad/.buildozer/android/platform/android-ndk-r9c/platforms/android-19/arch-arm -lm -L/home/perrythekeypad/Documents/Android/build/libs_collections/myapp/armeabi-v7a -L/home/perrythekeypad/Documents/Android/build/libs_collections/myapp/armeabi-v7a -L/home/perrythekeypad/Documents/Android/build/libs_collections/myapp -L/home/perrythekeypad/Do…
score: 1
favorite count: 0
has title: Buildozer Error
type: Question
tagged with: android
tagged with: python
has comment: http://stackoverflow.com/comment/90728065
upvote count: 1
type: UnansweredQuestion
tagged with: buildozer

http://stackoverflow.com/q/51942292
has title: How do I assign a UUID to a file (.mydsl) using python code
type: Question
has comment: http://stackoverflow.com/comment/90834419
tagged with: uniqueidentifier
tagged with: guid
has comment: http://stackoverflow.com/comment/90834217
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90834069
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90835054
has body: I have multiple .mydsl files in my dir. I want to assign each file with a unique ID using Python. When I run the python code, any new files and existing files in the specific directory should b assigned with an ID. Could anyone be able to help me with this. for root, dirs, files in os.walk( './'): for file in files: if file.endswith(".mydsl"): print(os.path.join(file))
answer count: 0
tagged with: uuid
score: 0

http://stackoverflow.com/q/51829622
type: AnsweredQuestion
score: 1
tagged with: pyqt5
type: Question
tagged with: pyqt
downvote count: 0
answer count: 1
tagged with: qgroupbox
has body: I want to do something like this: I'm not being able to find any way to group the buttons like that. Namely, to enclose them in rectangles and put a 'title' to that 'button section'. Is it possible to do this in PyQt5?
has title: Group buttons aesthetically in PyQt5
has answer: http://stackoverflow.com/a/51830109
favorite count: 0
has comment: http://stackoverflow.com/comment/90614282
accepted answer: http://stackoverflow.com/a/51830109
upvote count: 1
tagged with: python

http://stackoverflow.com/comment/90565526
type: QuestionComment
comment on: http://stackoverflow.com/q/51798738
has text: @JamesA.Bednar sure, I added a simple my_graph to my code.
score: 0
type: Comment

http://stackoverflow.com/q/51849745
tagged with: teradata
downvote count: 0
has comment: http://stackoverflow.com/comment/90675272
favorite count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: python
tagged with: pyodbc
has title: pyodbc truncates column names
type: Question
has answer: http://stackoverflow.com/a/58830190
has comment: http://stackoverflow.com/comment/90655180
has answer: http://stackoverflow.com/a/69663060
has body: I'm using python 3.6.2, pyodbc 4.0.23, to access Teradata 15.10.07.15 on Ubuntu 16.04. The teradata driver I have installed is tdodbc1620 16.20.00.36-1 amd64 SIMBA Teradata ODBC driver package for Ubuntu. When I run the following: &gt;&gt;&gt;pyodbc.pooling = False &gt;&gt;&gt;conn_str="autocommit=True;ANSI=True;PWD=xxx;UID=xxx;DATABASE=xxx;LOGINTIMEOUT=300;DBCNAME=xxx;DRIVER=Teradata;SERVER=x.x.x)" &gt;&gt;&gt;conn=pyodbc.connect(conn_str) &gt;&gt;&gt;conn.setdecoding(pyodbc.SQL_CHAR, encoding='latin') &gt;&gt;&gt;conn.setdecoding(pyodbc.SQL_WCHAR, encoding='latin') &gt;&gt;&gt;conn.setdecoding(pyodbc.SQL_WMETADATA, encoding='latin') &gt;&gt;&gt;conn.setencoding(encoding='latin') &gt;&gt;&gt;cur = conn.cursor() &gt;&gt;&gt;sql5 = """SELECT IP3_addr, cntry_name, city_name FROM tns_access_views.DW_TNS_IP_ADDR_GEO_LOC_LKP where cntry_name in (xxx) """ &gt;&gt;&gt;ip = pandas.io.sql.read_sql(sql5,conn) &gt;&gt;&gt;ip.columns Index(['IP3_', 'CNTRY', 'CITY_'], dtype='object') I'm expecting IP3_addr, cntry_name, city_name. Any idea why it is shortening the column names?
answer count: 2
score: 2

http://stackoverflow.com/q/51933498
has comment: http://stackoverflow.com/comment/90817039
type: Question
has comment: http://stackoverflow.com/comment/90817499
has answer: http://stackoverflow.com/a/65338842
has comment: http://stackoverflow.com/comment/90817104
downvote count: 0
has body: I created .exe file using pyinstaller 3.3.1 and I got this message Traceback (most recent call last): File "install.py", line 14, in &lt;module&gt; ImportError: No module named configobj [8468] Failed to execute script install I'm working with python 2.7 using conda environment. Lately I had updated pyinstaller to version 3.3.1 so this happened to me while I'm checking that the update is safe. I have also created another .exe file from different script that uses also this import and its went well, so any help will be welcome.
tagged with: conda
has comment: http://stackoverflow.com/comment/90817440
tagged with: python-2.7
answer count: 2
has title: ImportError: No module named configobj
favorite count: 0
tagged with: configobj
type: UnansweredQuestion
tagged with: pyinstaller
has comment: http://stackoverflow.com/comment/90817583
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/90817252
has answer: http://stackoverflow.com/a/63597156
score: 1

http://stackoverflow.com/q/51888636
has answer: http://stackoverflow.com/a/51889021
answer count: 3
upvote count: 1
has answer: http://stackoverflow.com/a/51892205
accepted answer: http://stackoverflow.com/a/51892205
possible better answer: http://stackoverflow.com/a/51889021
has comment: http://stackoverflow.com/comment/90728397
favorite count: 0
tagged with: python
tagged with: selenium-webdriver
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90728459
downvote count: 0
score: 1
has body: I am trying to scrape this page: https://redmart.com/fresh-produce/fresh-vegetables. But the problem I face is it returns only some elements. Code I have used is below: from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium import webdriver # Start the WebDriver and load the page wd = webdriver.Chrome(executable_path=r"C:\Chrome\chromedriver.exe") wd.get('https://redmart.com/fresh-produce/fresh-vegetables') # Wait for the dynamically loaded elements to show up WebDriverWait(wd, 300).until( EC.visibility_of_element_located((By.CLASS_NAME, "productDescriptionAndPrice"))) # And grab the page HTML source html_page = wd.page_source wd.quit() # Now you can use html_page as you like from bs4 import BeautifulSoup soup = BeautifulSoup(html_page, 'lxml') print(soup) I needed to use Selenium becasue the source code is not useful as the page is JAVAscript generated. If you open the page, it has some 60 rows of products (around 360 products in total). Running this code only gives me 6 rows of products. Stopping at the yellow onions. thanks!
has comment: http://stackoverflow.com/comment/90731690
tagged with: selenium
tagged with: web-scraping
tagged with: webdriver
type: Question
has title: How to scrape the product names from the website through Selenium?
has answer: http://stackoverflow.com/a/51896367
has comment: http://stackoverflow.com/comment/90731304

http://stackoverflow.com/a/51855891
type: AcceptedAnswer
upvote count: 3
has comment: http://stackoverflow.com/comment/90664096
has body: Idea is create new 2 columns and use them for pivoting by split: all_data = all_data.loc[all_data["Variable"].str.startswith(tuple(event_names))] all_data'Event','b' = all_data['Variable'].str.split(expand=True) df=all_data.set_index(['ID','Event','b'])['Value'].unstack().reset_index().rename_axis(None,1) print (df) ID Event Decile Rank Score 0 1056 Cycle 9 32 96 1 1056 Run 8 56 89 2 1056 Swim 8 64 92 Thanks @asongtoruin for another solution, especially if need aggregate data: all_data.pivot_table(index=['ID', 'Event'], columns='b', values='Value', aggfunc='sum').reset_index().rename_axis(None, 1)) Another solution is extract by event_names: event_names = ["Run", "Swim", "Cycle"] all_data = all_data.loc[all_data["Variable"].str.startswith(tuple(event_names))] pat = '(' + '|'.join(event_names) + ')\s+(.*)' all_data'Event','b' = all_data['Variable'].str.extract(pat) df = (all_data.pivot_table(index=['ID', 'Event'], columns='b', values='Value', aggfunc='sum').reset_index().rename_axis(None, 1)) print (df) ID Event Decile Rank Score 0 1056 Cycle 9 32 96 1 1056 Run 8 56 89 2 1056 Swim 8 64 92
type: Answer
accepted answer of: http://stackoverflow.com/q/51855835
downvote count: 0
answers question: http://stackoverflow.com/q/51855835
has comment: http://stackoverflow.com/comment/90664184
has comment: http://stackoverflow.com/comment/90664020
score: 3

http://stackoverflow.com/comment/90763823
type: Comment
has text: Checkout my updated answer and let me know the status
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51902514

http://stackoverflow.com/a/51881391
has body: df['driving'] = df['tour_id'].map(df[~df'condA','condB','condC'.all(1)].groupby('tour_id')['time'].sum()) Yields: tour_id time condA condB condC driving 0 1 10 True True True 70 1 1 20 True True True 70 2 1 30 False False False 70 3 1 40 False False False 70 4 2 15 True True True 100 5 2 25 False False False 100 6 2 30 False False False 100 7 2 45 False False False 100 8 2 50 True True True 100
type: Answer
has comment: http://stackoverflow.com/comment/90714498
accepted answer of: http://stackoverflow.com/q/51880970
has comment: http://stackoverflow.com/comment/90732646
answers question: http://stackoverflow.com/q/51880970
upvote count: 1
has comment: http://stackoverflow.com/comment/90714339
score: 1
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/90670215
has text: @FuzzyPixelz It depends on your specifications.. basically depends on how memory-costy is each object in your list, and how much free memory you have available
comment on: http://stackoverflow.com/q/51858765
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51956223
has comment: http://stackoverflow.com/comment/90863166
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/90863728
has comment: http://stackoverflow.com/comment/90864393
type: AcceptedAnswer
downvote count: 0
has body: The problem is that tkinter callbacks ¹do not directly support arguments and ²ignore the return value. The issue can be solved ¹using a lambda with default arguments and ²using a mutable object (e.g., a list) as said default argument, because when the callback function modify it the changes are reflected in the caller scope. E.g., you can go define select_files with an argument, a list, that is a mutable argument that you modify at will def select_files(pairs): pairs.clear() # this voids the content of the list # many lines of code for the algorithm that splits images into pairs pairs.append(['a.jpg', 'b.jpg']) then, in your main, you modify the command=... to introduce a default argument pairs = [] ... selectButton = Button(root, text = "Select", command = lambda pairs=pairs: select_files(pairs)) so that, eventually, you can acces each pair of image filenames for fn1, fn2 in pairs: ... To show it in practice, &gt;&gt;&gt; def gp(pairs): ... pairs.append([1,2]) ... &gt;&gt;&gt; pairs = [] &gt;&gt;&gt; (lambda p=pairs: gp(p))() &gt;&gt;&gt; pairs [[1, 2]] &gt;&gt;&gt; and a counter example &gt;&gt;&gt; def gp(pairs): ... pairs = [[1, 2]] ... &gt;&gt;&gt; pairs = [] &gt;&gt;&gt; (lambda p=pairs: gp(p))() &gt;&gt;&gt; pairs [] &gt;&gt;&gt; that shows that you should never assign to the function argument...
type: Answer
accepted answer of: http://stackoverflow.com/q/51955332
answers question: http://stackoverflow.com/q/51955332

http://stackoverflow.com/q/51832484
tagged with: python
has body: Let's say that we have these code: def judgement(): content = _get_config_content() # do something in content return content + '.' def _get_config_content(): with open('test_config', 'r') as f: return f.read() I want to test the judgement function, as we can see it: the judgement function is calling _get_config_content(), which is aimed to be private, and the _get_config_content() will open file and read it. And it's good to stub out the file reading part, and there are two ways to stub the file reading logic: stub private _get_config_content() function, and make it just return fake result. stub the built-in open function, and make it return the fake file object. Which way is better? Or is there other way to stub the file system in unit test?
tagged with: unit-testing
type: Question
has title: Unit test: Stub the file system layer in product code
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/56067053
type: UnansweredQuestion

http://stackoverflow.com/comment/90613173
comment on: http://stackoverflow.com/q/51829362
has text: Are you sure that's the exact error message? Considering `changeColor` never even refers to the `game` object, it's surprising to me that it would appear in a NameError in that context. Are you sure it wasn't `gameButtons`?
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/a/51919442
has body: Explicit loop for i in range(1, max(nums)+2): with nested implicit loop if i not in nums: is not O(n) ;)
upvote count: 1
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51919407
answers question: http://stackoverflow.com/q/51919407
type: Answer
score: 1

http://stackoverflow.com/q/51911615
downvote count: 0
tagged with: headless
tagged with: selenium
has body: I am a web developer in Korea. We've recently been using this Python to implement the website crawl feature. I'm new to Python. We looked for a lot of things for about two days, and we applied them. Current issues include: Click the Excel download button to display a new window (pop up). Clicking Download in the new window opens a new tab in the parent window and shuts down all browsers down as soon as the download starts. Download page is PHP and data is set to Excel via header so that browser automatically recognizes download. The problem is that the browser has shut down and the download is not complete, nor is the file saved. I used the following source code. import time 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 from selenium.common.exceptions import TimeoutException chrome_driver = './browser_driver/chromedriver' options = webdriver.ChromeOptions() options.add_argument('--headless') download_path = r"C:\Users\files" timeout = 10 driver = webdriver.Chrome(executable_path=chrome_driver, chrome_options=options) driver.command_executor._commands["send_command"] = ( "POST", '/session/$sessionId/chromium/send_command') params = {'cmd': 'Page.setDownloadBehavior', 'params': {'behavior': 'allow', 'downloadPath': download_path}} command_result = driver.execute("send_command", params) driver.get("site_url") #download new window down_xls_btn = driver.find_element_by_id("download") down_xls_btn.click() driver.switch_to_window(driver.window_handles[1]) #download start down_xls_btn = driver.find_element_by_id("download2") down_xls_btn.click() The browser itself shuts down as soon as the download is started during testing without headless mode. The headless mode does not download the file itself. Annotating a DevTools source related to Page.setDownloadBehavior removes the shutd…
type: Question
answer count: 1
upvote count: 3
has title: The file download path setting in python selenium chrome headless does not apply
has answer: http://stackoverflow.com/a/57384658
favorite count: 0
tagged with: download
type: UnansweredQuestion
tagged with: python
score: 3

http://stackoverflow.com/comment/90753221
score: 0
type: Comment
type: QuestionComment
has text: The code is not realy needed because it doesnt matter why it crashes but i will post something
comment on: http://stackoverflow.com/q/51901008

http://stackoverflow.com/comment/90820781
comment on: http://stackoverflow.com/q/51935309
type: QuestionComment
type: Comment
score: 1
has text: No need for a dictionary if your keys are *sequential* integers

http://stackoverflow.com/comment/90746191
comment on: http://stackoverflow.com/q/51896094
score: 0
has text: use `os.path.exists(database)` instead of `os.stat(database).st_size`
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90734190
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51891442
has text: Its working now, I changed the order in /etc/nsswitch.conf put files infront of dns
score: 0

http://stackoverflow.com/a/51953747
answers question: http://stackoverflow.com/q/51953452
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 1
upvote count: 1
has body: You could do something like this instead: x = json.loads(x)['items'] for item in x: print item['description'] print item['title']
has comment: http://stackoverflow.com/comment/90874786
accepted answer of: http://stackoverflow.com/q/51953452

http://stackoverflow.com/comment/90681643
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51864665
score: 2
has text: Can you include the full error message so we know where in your code the error is occurring?

http://stackoverflow.com/comment/90651277
type: QuestionComment
comment on: http://stackoverflow.com/q/51848913
score: 0
has text: I would not be surprised to see that uniform-sampling is NP-hard. If you are desperate and don't get something out of this question, you can adapt [this](https://stackoverflow.com/a/47208133/2320035) approach.
type: Comment

http://stackoverflow.com/a/51880200
answers question: http://stackoverflow.com/q/51862846
has comment: http://stackoverflow.com/comment/90733427
type: Answer
upvote count: 7
has body: From dask's documentation for DummyEncoder columns parameter: The columns to dummy encode. Must be categorical dtype. Dummy encodes all categorical dtype columns by default. Also, it says here that you must always use a Categorizer before using some encoders (DummyEncoder included). A correct way to do this: from dask_ml.preprocessing import Categorizer, DummyEncoder from sklearn.pipeline import make_pipeline pipe = make_pipeline( Categorizer(), DummyEncoder()) pipe.fit(data) pipe.transform(testD) Which will ouput: B_a B_b B_c 0 1 0 0 1 1 0 0
accepted answer of: http://stackoverflow.com/q/51862846
score: 7
has comment: http://stackoverflow.com/comment/90714695
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/51832638
score: 0
tagged with: ubuntu-16.04
has comment: http://stackoverflow.com/comment/90619381
has answer: http://stackoverflow.com/a/75755474
has answer: http://stackoverflow.com/a/69571846
has title: copy all files in directory/subdirectories from samba with python
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/44871317
tagged with: ubuntu
has comment: http://stackoverflow.com/comment/90619339
has body: I'm trying to copy a whole directory or all the files in a directory and its subdirectories from a Samba (SMB) connection, using a Python script. I know how to get an individual file using: conn = SMBConnection('server', 'password', 'IP', 'share', use_ntlm_v2 = True) assert conn.connect('IP', 139) x = 'test.txt' with open(x, 'wb') as fp: conn.retrieveFile('shared', '/EC/test/Pytest/Confocal/test.txt', fp) But I would like to implement something like: root = "/home/to/directory/" path = os.path.join(root, "source") destination = "/home/to/target/directory/" for path, subdirs, files in os.walk(root): for name in files: print (os.path.join(path, name)) if name.endswith(".nimp"): shutil.move(os.path.join(path, name), destination) To get all files in subdirectories with a specific type (ie .nimp). This code works when using a local directory, but I cannot implement it to the SMB connection. According to the documentation, there is no command to copy a whole folder. I would also like to dynamically save files as their current names in the SMB connection. Any suggestions? Alternatively, I was thinking about copying a whole folder, and then using the second bit of code to copy all files, and then delete the copied folder after. Would that also be possible? Also, there is no post on this site that addresses my specific question.
tagged with: smb
has comment: http://stackoverflow.com/comment/90619674
has comment: http://stackoverflow.com/comment/90619404
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/90619623
has comment: http://stackoverflow.com/comment/90620019
tagged with: python
tagged with: samba

http://stackoverflow.com/a/51881400
score: 1
has comment: http://stackoverflow.com/comment/90773970
downvote count: 0
has comment: http://stackoverflow.com/comment/90748542
has comment: http://stackoverflow.com/comment/90781213
has body: That's not the correct way for doing it. Running K.eval(y_another) you are asking keras backend to evaluate an Input object (which is only a placeholder for the data you want to feed into the network) without feeding it with any data, that's the reason of your error. Thus, assuming that you want to compute the output of the network given a new input that is a random sequence multiplied by 2 (is this right?), then you should modify the body of on_epoch_end(self, epoch, logs=None) in your callback as follow: x, _ = next(RandomSeq()) print(self.model.predict(x*2))
type: Answer
has comment: http://stackoverflow.com/comment/90774033
answers question: http://stackoverflow.com/q/51871328
upvote count: 1
has comment: http://stackoverflow.com/comment/90722792
has comment: http://stackoverflow.com/comment/90736953

http://stackoverflow.com/comment/90789472
type: Comment
has text: This almost works, except I get the array like so, `['N', 'e', 'w', ' ', 'Y', 'o', 'r', 'k']`
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51919385

http://stackoverflow.com/comment/90633315
type: Comment
has text: If you used anaconda only for spyder, you might aswell just install python and spyder. First DL the desired python version (I recommand latest 3.x version), and then open a console and use `py -3.x -m pip install spyder`
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51839219

http://stackoverflow.com/q/51943536
has comment: http://stackoverflow.com/comment/90836687
has answer: http://stackoverflow.com/a/51943672
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/90836810
has comment: http://stackoverflow.com/comment/90836956
favorite count: 0
has body: I'm using python3.7 and typed the following code in python shell: &gt;&gt;&gt; s0 = r'\c' &gt;&gt;&gt; s0 '\\c' &gt;&gt;&gt; print(s0) \c &gt;&gt;&gt; s1 = '\c' &gt;&gt;&gt; s1 '\\c' &gt;&gt;&gt; print(s1) \c &gt;&gt;&gt; s2 = '\\c' &gt;&gt;&gt; s2 '\\c' &gt;&gt;&gt; print(s2) \c My questions: Why does python automatically add \ to s1 instead of raising error? Can anyone provide link of this feature (auto \ adding) in python docs? Do s0, s1 and s2 store the same data internally?
has comment: http://stackoverflow.com/comment/90836643
has comment: http://stackoverflow.com/comment/90836707
tagged with: python
has comment: http://stackoverflow.com/comment/90837270
has comment: http://stackoverflow.com/comment/90837379
has comment: http://stackoverflow.com/comment/90836717
has comment: http://stackoverflow.com/comment/90836890
type: AnsweredQuestion
duplicate of: http://stackoverflow.com/q/24085680
downvote count: 0
has comment: http://stackoverflow.com/comment/90836796
has title: Why does python automatically add backslash to string?
type: Question
accepted answer: http://stackoverflow.com/a/51943672
score: 1
linked to: http://stackoverflow.com/q/24085680

http://stackoverflow.com/comment/90823927
comment on: http://stackoverflow.com/q/51936789
has text: `locModel.save_weights('model1_weights.h5')` completes without errors - my ultimate goal is to convert to TFLite, so I need the whole graph...
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/q/51910726
tagged with: flask-restful
has answer: http://stackoverflow.com/a/51912993
score: 0
answer count: 1
has body: I am using blueprints and I have this line to create the blueprint: api_bp = Blueprint('api', __name__) And some_resources is added and blueprint is registered by below lines: rest_api = Api() rest_api.init_app(api_bp) rest_api.add_resource(SomeResourceApi, '/some_resources', '/some_resources/&lt;int:some_resource_id&gt;', endpoint='some_resources') app.register_blueprint(api_bp, url_prefix='/some/api/v1.0') The fields dict used for marshal() has 'uri': fields.Url('api.some_resources'), The output that I receive is "uri": "/some/api/v1.0/some_resources" inside my response. Notice that the id is not appended at the end in the url. Just to be sure I replaced the line 'uri': fields.Url('api.some_resources'), inside my field dict to 'id': fields.Integer and in this case the integer id is returned correctly inside the response. Also I have tested both with the decorator @marshal_with and the method marshal(), that doesn't make any difference. For now, I am getting my work done by having my fields dict to have an extra field: id with the value fields.Integer which contains the actual id, so the output has these two fields in response which collectively gives the complete address: "uri": "/some/api/v1.0/some_resources", "id": 11 While this serves the purpose, it looks kind of hacky. Am I doing anything wrong that the ids are not appended in the response when using fields.Url()? Library Version details: Flask==1.0.2 Flask-RESTful==0.3.6 Flask-SQLAlchemy==2.3.2 SQLAlchemy==1.2.10 Corresponding github issue: https://github.com/flask-restful/flask-restful/issues/774
tagged with: flask
tagged with: rest
accepted answer: http://stackoverflow.com/a/51912993
tagged with: python
type: AnsweredQuestion
has title: `fields.Url('some_resource')` doesn't append the `id` at the end if using blueprints
linked to: http://stackoverflow.com/q/24770999
type: Question

http://stackoverflow.com/a/51838127
upvote count: 1
has body: Here is a solution to your problem from what I understood from the above comments. In case this is not you want, let me know and I will update accordingly. I am using list comprehensions here. I used (i+1)%5 to access 5th index because the index starts from 0 in python. L = [ 10, 2, 56, 33, 23, 1, 564, 32, 122, 42, 3, 4, 2, 1, 3, 2, 1, 54, 5, 9, 1, 65, 254 ] x = int(input("Insert number here: ")) L1 = [x if i &gt; 100 else i for i in L] L2 = [2*j if (i+1)%5==0 else j for i, j in enumerate(L1)] L_output = L1 + L2 print (L1) print (L2) print (L_output) Output Insert number here: 6 [10, 2, 56, 33, 23, 1, 6, 32, 6, 42, 3, 4, 2, 1, 3, 2, 1, 54, 5, 9, 1, 65, 6] [10, 2, 56, 33, 46, 1, 4, 32, 4, 84, 3, 4, 2, 1, 6, 2, 1, 54, 5, 18, 1, 65, 4] [10, 2, 56, 33, 23, 1, 6, 32, 6, 42, 3, 4, 2, 1, 3, 2, 1, 54, 5, 9, 1, 65, 6, 10, 2, 56, 33, 46, 1, 4, 32, 4, 84, 3, 4, 2, 1, 6, 2, 1, 54, 5, 18, 1, 65, 4]
has comment: http://stackoverflow.com/comment/90629428
has comment: http://stackoverflow.com/comment/90629745
has comment: http://stackoverflow.com/comment/90629771
has comment: http://stackoverflow.com/comment/90629549
has comment: http://stackoverflow.com/comment/90629893
downvote count: 0
has comment: http://stackoverflow.com/comment/90629519
has comment: http://stackoverflow.com/comment/90629829
answers question: http://stackoverflow.com/q/51837752
has comment: http://stackoverflow.com/comment/90629406
type: Answer
has comment: http://stackoverflow.com/comment/90629796
score: 1

http://stackoverflow.com/q/51854809
answer count: 1
downvote count: 0
has body: I need to group data by semesters but there is no frequency tag available here 2QS (2 quarters from start) and 6MS (6 months from start) won't do because they will start in different moments, according to the first datetime in my dataframe. (Quite counterintuitive and prone to errors, IMHO: I didn't see this issue till I used a different dataset that began in May instead of January...) from datetime import * import pandas as pd import numpy as np df = pd.DataFrame() days = pd.date_range(start="2017-05-17", end="2017-11-29", freq="1D") df = pd.DataFrame({'DTIME': days, 'DATA': np.random.randint(50, high=80, size=len(days))}) df.set_index('DTIME', inplace=True) grouped = df.groupby(pd.Grouper(freq='2QS')) print("Groups date start:") for dtime, group in grouped: print dtime # print(group) returns Groups date start: 2017-04-01 00:00:00 &lt;== because my first datetime is in May, 2017 2017-10-01 00:00:00 instead of: Groups date start: 2017-01-01 00:00:00 &lt;== I want the semesters referred to the year! 2017-06-01 00:00:00 As a possible workaround I created two new columns in my dataframe and then group according to them: df["year"] = df.index.year.astype(int) df["semester"] = df.index.month.astype(int) df["semester"] = df["semester"] - 1 df["semester"] = df["semester"] // 6 grouped = df.groupby(["year", "semester"]) Is this the only way to to this? There are two other little questions, just for the sake of curiosity and not worth an indipendent stackoverflow question: why a tag W (end of week) is available, but WS (start of week) is not? how to write this in a single line? df["semester"] = df.index.month.astype(int) df["semester"] = df["semester"] - 1 df["semester"] = df["semester"] // 6
favorite count: 0
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51854849
score: 3
upvote count: 3
type: Question
has title: Pandas groupby: group by semester
accepted answer: http://stackoverflow.com/a/51854849
tagged with: pandas-groupby
tagged with: pandas

http://stackoverflow.com/q/51817345
has comment: http://stackoverflow.com/comment/90605260
type: Question
has comment: http://stackoverflow.com/comment/90602674
score: 1
tagged with: reticulate
downvote count: 0
has comment: http://stackoverflow.com/comment/90604209
favorite count: 0
has title: sourcing Python function from R not importing modules
tagged with: http://stackoverflow.com/tag/r
has comment: http://stackoverflow.com/comment/90603569
has body: The reticulate documentation says that I can source any Python script just as I would source an R script using the source_python() function. I tried the example they provided but it does not work for me. I am getting " No module named pandas" error. first i specify the path to my python library(reticulate) use_python("/Users/fberhane/anaconda3/bin/python", required=TRUE) then save the python code below as flights.py import pandas def read_flights(file): flights = pandas.read_csv(file) flights = flights[flights['dest'] == "ORD"] flights = flights'carrier', 'dep_delay', 'arr_delay' flights = flights.dropna() return flights Then I source the above python code after first saving it as flights.py source_python("flights.py") flights <- read_flights("flights.csv") library(ggplot2) ggplot(flights, aes(carrier, arr_delay)) + geom_point() + geom_jitter() but I get the error message that there is no module called pandas.
tagged with: python
has comment: http://stackoverflow.com/comment/90603839
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90589231
has comment: http://stackoverflow.com/comment/90605662
has comment: http://stackoverflow.com/comment/90603392
upvote count: 1

http://stackoverflow.com/comment/90679181
type: AnswerComment
has text: Hi Mike, I'm sure this solution works, I'm just wondering what the benefit of destroying the canvas and then rebuilding it instead of using delete? The downsides seem to be the risk that your layout might be tough to recreate if you're using a manger that's order-dependent (or if the user has manually resized some widgets), and that if you are running this at a very high frequency you might see the widgets jumping around trying to resize quickly
score: 0
comment on: http://stackoverflow.com/a/51861466
type: Comment

http://stackoverflow.com/comment/90728465
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51879528
has text: @AurenFerguson - I just test it and why `766206 1429531 1` has to be in first group like `664627 1429531 1`? What is reason?
type: Comment

http://stackoverflow.com/q/51852645
has body: I saved an numpy array to an image as follows: plt.imshow(xNext[0,:,:,0]) #xNext has shape (1,64,25,1) print(xNext[0,:,:,0].shape) #outputs (64,25) plt.savefig(os.path.join(root,filename)+'.png') np.save(os.path.join(root,filename)+'.npy',xNext[0,:,:,0]) How can I obtain the same numpy array back from the .png saved image? Can you also please show me if I had saved as .jpg image? I've tried the following and works with 3D array (v1) where resulting image close to the original numpy array produced image (original). image = Image.open(imageFilename) #brings in as 3D array box = (315,60,500,540) image = image.crop(box) image = image.resize((25,64)) #to correct to desired shape arr = np.asarray(image) plt.imshow(arr) plt.savefig('v1.png') plt.close() However, when I convert the 3D array to 2D array, the resulting image is different (v1b and v1c). arr2 = arr[:,:,0] plt.imshow(arr2) plt.savefig('v1b.png') plt.close() arr3 = np.dot(arr[...,:3],[0.299,0.587,0.11]) plt.imshow(arr3) plt.savefig('v1c.png') plt.close() How can I convert the 3D to 2D correctly? Thanks for your help. original, v1 (saved from 3D array) v1b, v1c (saved from 2D arrays) original (with original size)
score: 0
answer count: 2
tagged with: python-imaging-library
accepted answer: http://stackoverflow.com/a/51909244
possible better answer: http://stackoverflow.com/a/51852905
has title: Convert back to 2D numpy array from .jpg image
linked to: http://stackoverflow.com/q/25696615
has answer: http://stackoverflow.com/a/51852905
linked to: http://stackoverflow.com/q/26929052
tagged with: numpy
has comment: http://stackoverflow.com/comment/90658364
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90759814
tagged with: arrays
has comment: http://stackoverflow.com/comment/90760525
type: Question
has answer: http://stackoverflow.com/a/51909244
tagged with: python
linked to: http://stackoverflow.com/q/902761
linked to: http://stackoverflow.com/q/39102051

http://stackoverflow.com/q/51818052
tagged with: neural-network
tagged with: keras
score: 4
possible better answer: http://stackoverflow.com/a/51819841
has body: I'm new to all this Neural Networks thing and I'm actually trying some toy codes with different codig options (raw Python, TF...) Currently, I've made a simple binary AND, OR and NOT operator solving network in TFLearn: # 1. Import library of functions import numpy as np import tflearn from keras.models import Sequential from keras.layers import Dense, Activation # 2. Logical data input = [[0., 0.], [0., 1.], [1., 0.], [1., 1.]] YOR = [[0.], [1.], [1.], [1.]] YAND=[[0.], [0.], [0.], [1.]] YNOT=[[0.], [1.], [1.], [0.]] ###### VERSION TFLEARN ##### # 3. Building our neural network/layers of functions neural_net = tflearn.input_data(shape=[None, 2]) neural_net = tflearn.fully_connected(neural_net, 1, activation='sigmoid') neural_net = tflearn.regression(neural_net, optimizer='sgd', learning_rate=2, loss='mean_square') # 4. Train the neural network / Epochs model = tflearn.DNN(neural_net,tensorboard_verbose=0) model.fit(input, YOR, n_epoch=1000, snapshot_epoch=False) # 5. Testing final prediction print("Testing OR operator") print("0 or 0:", model.predict([[0., 0.]])) print("0 or 1:", model.predict([[0., 1.]])) print("1 or 0:", model.predict([[1., 0.]])) print("1 or 1:", model.predict([[1., 1.]])) Now I'm trying to replicate it in Keras (using CNTK backend) using this code: # 2. Logical OR operator / the data input = np.array([[0., 0.], [0., 1.], [1., 0.], [1., 1.]]) YOR = np.array([[0.], [1.], [1.], [1.]]) YAND=np.array([[0.], [0.], [0.], [1.]]) YNOT=np.array([[0.], [1.], [1.], [0.]]) ###### VERSION KERAS ##### # 3. Building our neural network/layers of functions model= Sequential() model.add(Dense(4,input_shape=[2,])) model.add(Activation('sigmoid')) model.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['accuracy']) # 4. Train the neural network / Epochs model.fit(input,YOR,epochs=1000,verbose=1) # 5. Testing final prediction print("Testing OR operator") print("0 or 0:", model.predict([[0., 0.]])) print("0 or 1:", model.predict([[0., 1.]])) print("1 …
upvote count: 4
has title: Different Input/Output shape in Keras
favorite count: 0
tagged with: python
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/51818314
accepted answer: http://stackoverflow.com/a/51818314
type: Question
has answer: http://stackoverflow.com/a/51819841
answer count: 2

http://stackoverflow.com/q/51810759
has comment: http://stackoverflow.com/comment/90576652
has title: Submit a form using POST with g-recaptcha-response argument
type: AnsweredQuestion
downvote count: 0
favorite count: 0
tagged with: http://stackoverflow.com/tag/r
tagged with: httr
linked to: http://stackoverflow.com/q/65403238
has answer: http://stackoverflow.com/a/51850978
type: Question
tagged with: python
tagged with: recaptcha
score: 10
tagged with: 2captcha
has comment: http://stackoverflow.com/comment/90576987
has comment: http://stackoverflow.com/comment/90576940
answer count: 1
has body: I want to submit a form from following web page: http://www.hzzo-net.hr/statos_OIB.htm First, I use 2captcha service to bypass recaptcha: # parameters api_key &lt;- "c+++" api_url &lt;- "http://2captcha.com/in.php" site_key &lt;- "6Lc3SAgUAAAAALFnYxUbXlcJ8I9grvAPC6LFTKQs" hzzo_url &lt;- "http://www.hzzo-net.hr/statos_OIB.htm" # GET method req_url &lt;- paste0("http://2captcha.com/in.php?key=", api_key,"&amp;method=userrecaptcha&amp;googlekey=", site_key, "&amp;pageurl=", hzzo_url) get_response &lt;- POST(req_url) hzzo_content &lt;- content(get_response) hzzo_content &lt;- xml_text(hzzo_content) captcha_id &lt;- stringr::str_extract_all(hzzo_content[[1]], "\\d+")[[1]] # solve captcha Sys.sleep(16L) captcha2_solve &lt;- function(apiKey, capstchaID){ req_url &lt;- paste0("http://2captcha.com/res.php?key=", api_key,"&amp;action=get&amp;id=", capstchaID) result &lt;- GET(req_url) captcha_content &lt;- content(result) hzzo_response &lt;- xml_text(captcha_content) hzzo_response &lt;- strsplit(hzzo_response, "\\|") return(hzzo_response) # hzzo_response &lt;- hzzo_response[[1]][[2]] # return(hzzo_response) } hzzo_response &lt;- captcha2_solve(api_key, captcha_id) while(hzzo_response[[1]] == "CAPCHA_NOT_READY"){ Sys.sleep(16L) hzzo_response &lt;- captcha2_solve(api_key, captcha_id) return(hzzo_response) } hzzo_response &lt;- hzzo_response[[1]][[2]] After executing this code I got the response that I have enter to textarea of recaptcha. This part works fine, as I expected. The response looks like this: "03AHqfIOmo9BlCsCKyg-lDes4oW-U3PWgCtATRUqXFcEV032acDgGoOzrV8GiZNDzCF4TbCVLcY8HZ8hR1JqO11YdRExvgPDL0EUsjCZdI0rUm_LnBRRifyb66X7V6r4n8CIm1si3EKmw36XIcZK7MGrHSNWRrj2aGzWAYO8ceobViOICOhkYe9Bsfv64tUHWvHSqNIoesD_FHplbWG3B0eMag5341NyycjpNLxgNCwVzA8mhCU3oQUcloze-mIclFMZ7J_nbVhXdy8-qipF5ZFH4xIhSQXHH-TqxyaGQFjKdgLch7MuDEQVRcQGo1o4QuSEoeCTjlPn3Mah5vC8zKrnqfbMgiOVOIDJFGvFY4KOivbBzYTz5nW9g" After that, I should submit the form. This is the part I can't get right. I tried to add all arguments …
accepted answer: http://stackoverflow.com/a/51850978
has comment: http://stackoverflow.com/comment/90576777
upvote count: 10

http://stackoverflow.com/q/51804782
tagged with: mysql
type: UnansweredQuestion
has body: I want to connect to mysql server. The SQL server is installed with XAMPP. I want to write a script for streamlabs chatbot but stuck at this point. I'm not able to connect to the MySQL Server. I get the following Debug Error: FileName: C:\Python27\Lib\site-packages\mysql\connector\network.py Function recv_plain LineNr: 244 Message: unsupported operand type(s) for +=:'bytearray' and 'str' So it's a problem in the connector library. MysqlDB = mysql.connector.connect(user='root', password='xxx', host='127.0.0.1', database='stream') I can start the script outside of streamlabs and it connects as intended. I can make select queries and so on. Is there someone who can give me a clue?
answer count: 0
tagged with: connector
downvote count: 0
score: 1
favorite count: 0
type: Question
tagged with: python
upvote count: 1
has title: MySQL Connection Error in Python

http://stackoverflow.com/a/51866033
has comment: http://stackoverflow.com/comment/90684727
answers question: http://stackoverflow.com/q/51865819
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/90684677
downvote count: 0
has body: Check if this works. For writing in separate lines, you can use "\n". And id you would want to put the phrase "Match in both the lists" only once, you will need to put an additional if statement. test = 0 fileout = open('9output.txt', 'w') for val1 in lines1: for val2 in lines2: if val1 == val2: if test == 0: fileout.write("Match in both the lists") fileout.write(val1+"\n") test = 1 else: fileout.write(val1+"\n") fileout.close() if test == 0: print("No matches found!")
upvote count: 2
accepted answer of: http://stackoverflow.com/q/51865819
has comment: http://stackoverflow.com/comment/90684607
type: AcceptedAnswer

http://stackoverflow.com/a/51913379
has body: You have in your code more inconsistencies. Firstly, when you have in staff_dtls e.g. self.lname_entry.get(), you have to have defined self.lname_entry, it's not sufficient to have only lname_entry, because of Python Classes and OOP theory. Next, you have some mess in variable names e.g. in staff_dtls you have self.inc_type.get(), but you have to have self.inc_type_entry.get() and vice versa, you have e.g. ue_tax = ttk.Entry(box2, textvariable=ue_tax_entry_value), but you need ue_tax_entry = ttk.Entry(box2, textvariable=ue_tax_entry_value). So unite precisely your variable names. Next, instead of c.excecute("INSERT INTO staffing VALUES (?)", (element)) (with typo excecute), you need something like this self.c.execute("INSERT INTO staffing VALUES (?, ?, ?, ?, ?, ?, ...)", (element)), with so many question marks, how many columns you want to insert to DB. These are the main errors when you fix them, you will be on the right track.
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/51913076
score: 0
answers question: http://stackoverflow.com/q/51913076

http://stackoverflow.com/comment/92803087
type: Comment
has text: I prefer you to use a virtualBox and install Ubuntu. Its the easiest solution. You can create a shared folder with the virtual system and your windows.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51907281

http://stackoverflow.com/a/51885580
type: Answer
accepted answer of: http://stackoverflow.com/q/51882107
answers question: http://stackoverflow.com/q/51882107
has body: The problem is when you try to access the view blogfrance from a URL, you always end up to blogslovenia because they both have the exact same url pattern and I guess since slovenia is listed first it goes to slovenia. So when you enter a slug for france, the SloveniaExperience. As @Daniel Roseman mentioned, there is no point having these two models, just merge them in one with an extra field, something like this: country_choices = ( ("slovenia", "Slovenia"), ("france", "France"), ) class FranceExperience(models.Model): author = models.ForeignKey('auth.User', on_delete=models.CASCADE) exchange_country = CountryField(default='DEFAULT VALUE') category = models.IntegerField(choices=CATEGORY_CHOICES) title = models.CharField(max_length=200, default='DEFAULT VALUE') slug = models.SlugField(default='default-value') text = models.TextField(default='DEFAULT VALUE') created_date = models.DateTimeField(default=timezone.now) published_date = models.DateField(blank=True, null=True) country = models.CharField(max_length=30, choices=country_choices) # Added field Then you can have one view and one url.
score: 0
type: AcceptedAnswer

http://stackoverflow.com/q/51890748
has body: My input dataframe looks like this: Variable | fiscal_week_id | units xxxxxxxxxxx | 201801 | xx_unit_201801 xxxxxxxxxxx | 201802 | xx_unit_201802 xxxxxxxxxxx | 201803 | xx_unit_201803 yyyyyyyyyyy | 201801 | yy_unit_201801 yyyyyyyyyyy | 201802 | yy_unit_201802 yyyyyyyyyyy | 201803 | yy_unit_201803 Need output like this: Variable | 201801 | 201802 | 201803 xxxxxxxxxxx | xx_unit_201801 | xx_unit_201802 | xx_unit_201803 yyyyyyyyyyy | yy_unit_201801 | yy_unit_201802 | yy_unit_201803 Any help please, new to pandas and need solution in pandas only. I tried out with set_index, but didn't seem to work out.
tagged with: pandas
answer count: 1
downvote count: 0
duplicate of: http://stackoverflow.com/q/47152691
favorite count: 0
type: UnansweredQuestion
has title: Need to reshape pandas dataframe
tagged with: transpose
tagged with: python
has answer: http://stackoverflow.com/a/51891000
score: 1
upvote count: 1
type: Question

http://stackoverflow.com/q/51854444
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90661367
has answer: http://stackoverflow.com/a/64034533
upvote count: 5
tagged with: speed-test
answer count: 5
tagged with: python
has comment: http://stackoverflow.com/comment/90661308
has answer: http://stackoverflow.com/a/69469777
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/67933088
type: Question
has answer: http://stackoverflow.com/a/74296729
accepted answer: http://stackoverflow.com/a/52559837
has comment: http://stackoverflow.com/comment/90661280
score: 5
has answer: http://stackoverflow.com/a/52559837
has comment: http://stackoverflow.com/comment/90661330
has body: I am trying to use the speedtest-cli api. Copied part of the code from official wiki (and removed unused stuff): import speedtest s = speedtest.Speedtest() s.get_best_server() s.download() In python console I get everything ok: &gt;&gt;&gt; import speedtest &gt;&gt;&gt; s = speedtest.Speedtest() &gt;&gt;&gt; s.get_best_server() {HIDDEN} &gt;&gt;&gt; s.download() 37257579.09084724 But when I create .py file and run it I get: AttributeError: module 'speedtest' has no attribute 'SpeedTest' Thanks
possible better answer: http://stackoverflow.com/a/67933088
has title: speedtest-cli works in console, but not as script
favorite count: 0

http://stackoverflow.com/q/51859590
has title: Pandas - How to GroupBy from Particular Time of Day Every 24 hours?
accepted answer: http://stackoverflow.com/a/51859648
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51859648
type: Question
duplicate of: http://stackoverflow.com/q/12579150
has body: My data has two columns - first is TxnAmount, second is TxnDate ( which has date &amp; time in string format) **TxnAmount** **TxnDate** 100 '2018-04-01 19:12:26' 135 '2018-04-01 17:03:50' 210 '2018-04-01 14:37:17' 70 '2018-04-02 12:24:49' 250 '2018-04-02 09:56:18' Here is my code, which is able to sum ( day wise) import pandas as pd import numpy as np df = pd.read_csv('File.csv') df["TxnDate"] = pd.to_datetime(df["TxnDate"]) df.set_index(df["TxnDate"],inplace=True) df['TxnAmount'].resample('D', how='sum') But, I need the sum to be from 6:00 AM to 6:00 AM interval. The code I assume by default sums according to stand 0:00 AM to 0:00 interval.
score: 0
tagged with: pandas
answer count: 1
linked to: http://stackoverflow.com/q/12579150

http://stackoverflow.com/a/51916116
accepted answer of: http://stackoverflow.com/q/51916062
has comment: http://stackoverflow.com/comment/90782345
has comment: http://stackoverflow.com/comment/90782154
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90782243
has comment: http://stackoverflow.com/comment/90782385
has comment: http://stackoverflow.com/comment/90782398
type: Answer
has comment: http://stackoverflow.com/comment/90782332
has body: You define the clean function as: class SignUpForm(forms.Form): # ... def clean(self): password = self.cleaned_data.get('password') # ... return password The super(..) however, is supposed to return the cleaned_data, so a dictionary. By overwriting it and returning the password, the "endproduct" of form.cleaned_data is no longer a dictionary-like object, but a string. Or like the documentation on form-cleaning [Django-doc] specifies: The form subclass's clean() method can perform validation that requires access to multiple form fields. This is where you might put in checks such as "if field A is supplied, field B must contain a valid email address". This method can return a completely different dictionary if it wishes, which will be used as the cleaned_data. So as a result, password will take the place of the cleaned_data (and it is not a dictionary-like object), so we can no longer obtain form.cleaned_data['username'], since 'some_password'['username'], of course makes no sense to Python. We can rewrite the clean function by returning the self.cleaned_data at the end (by calling the super().clean() function for example): from django import forms class SignUpForm(forms.Form): # ... def clean(self): password = self.cleaned_data.get('password') password_confirmation = self.cleaned_data.get('password_confirmation') print(password) print(password_confirmation) if password != password_confirmation: raise forms.ValidationError('Password Must Match') return super().clean() Additional error(s): after the form is validated, you aim to create a User object with: user = User(request, username=username,email=email) It is however not crear to me why you here use the request object. I think it should be: user = User(username=username, email=email, password=hashed_password) You will also need to hash the password first, since otherwise it is a serious security threat. See the Django documentation on password hashing for more information.
has comment: http://stackoverflow.com/comment/90782279
upvote count: 3
has comment: http://stackoverflow.com/comment/90782164
answers question: http://stackoverflow.com/q/51916062
has comment: http://stackoverflow.com/comment/90782352
score: 3

http://stackoverflow.com/a/51827520
score: 2
downvote count: 0
has body: When doing a comparison in a program with == we must compare two variables of the same type (which can be devious when starting Python). Answer is a number, while question is a string which was written by the user. Thus Python recognizes the two as different and false. To avoid this you must either convert the number to a string or the string to a number so you compare two variables of the same type.
upvote count: 2
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51827374
accepted answer of: http://stackoverflow.com/q/51827374
type: Answer

http://stackoverflow.com/q/51939744
type: Question
possible better answer: http://stackoverflow.com/a/51939864
has comment: http://stackoverflow.com/comment/90830947
score: 0
answer count: 2
tagged with: pandas
has answer: http://stackoverflow.com/a/51940061
upvote count: 1
accepted answer: http://stackoverflow.com/a/51940061
downvote count: 1
favorite count: 0
has body: If I do str.extract(r'^(\d{1,})'), it will only return 1 in this case. Is any way to extract the string like 1,000? Name Income 0 A 1,000 1 B 900 2 C 80
has comment: http://stackoverflow.com/comment/90829921
has comment: http://stackoverflow.com/comment/90829810
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51939864
has title: How to extract string '1,000' in dataframe?

http://stackoverflow.com/q/51872534
type: Question
tagged with: nltk
has body: I am running my python script with nltk on localhost. My code is : #!C:\Users\fname lname\AppData\Local\Programs\Python\Python37-32\python.exe print("Content-type: text/plain\n") print("Single Quotes") print("checkkk") from nltk.tokenize import sent_tokenize, word_tokenize EXAMPLE_TEXT = "Hello Mr. Smith, how are you doing today? The weather is great, and Python is awesome. The sky is pinkish-blue. You shouldn't eat cardboard." print(sent_tokenize(EXAMPLE_TEXT)) Output coming as: Single Quotes checkkk Content-type: text/plain Single Quotes checkkk Problem is that: It is not considering nltk import and code after this line. Please help.
score: 0
has comment: http://stackoverflow.com/comment/90696798
has answer: http://stackoverflow.com/a/51872693
has title: Cannot run python script with nltk
answer count: 1
has comment: http://stackoverflow.com/comment/90696828
has comment: http://stackoverflow.com/comment/90728256
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90696680
tagged with: python
has comment: http://stackoverflow.com/comment/90696760
has comment: http://stackoverflow.com/comment/90696487
has comment: http://stackoverflow.com/comment/90696759
has comment: http://stackoverflow.com/comment/90696735
has comment: http://stackoverflow.com/comment/90696649

http://stackoverflow.com/comment/90740839
comment on: http://stackoverflow.com/q/51894698
type: Comment
type: QuestionComment
has text: Yes you can. And you can even use the same column name.
score: 3

http://stackoverflow.com/q/51862644
type: Question
has answer: http://stackoverflow.com/a/51863557
has body: I have a project and want to access a url by python. If i have variable1=1 and variable2=2, I want an output to be like this: www.example.com/data.php?variable1=1&amp;variable2=2 How do I achieve this? Thanks!
upvote count: 0
score: -1
answer count: 3
has title: How to access webpage with variables in python
accepted answer: http://stackoverflow.com/a/51863557
favorite count: 0
has comment: http://stackoverflow.com/comment/90677806
has answer: http://stackoverflow.com/a/51862730
tagged with: python
has comment: http://stackoverflow.com/comment/90677633
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/51862730
downvote count: 1
has answer: http://stackoverflow.com/a/51862729

import
tags question: http://stackoverflow.com/q/51939541
type: Tag
tags question: http://stackoverflow.com/q/51848558
tags question: http://stackoverflow.com/q/51906909
tag name: import
tags question: http://stackoverflow.com/q/51883339
tags question: http://stackoverflow.com/q/51880803
tags question: http://stackoverflow.com/q/51829944
tags question: http://stackoverflow.com/q/51846548
tags question: http://stackoverflow.com/q/51824561
tags question: http://stackoverflow.com/q/51827824
tags question: http://stackoverflow.com/q/51859155
tags question: http://stackoverflow.com/q/51824207
tags question: http://stackoverflow.com/q/51951332
tags question: http://stackoverflow.com/q/51863208
tags question: http://stackoverflow.com/q/51879473
tags question: http://stackoverflow.com/q/51820398
tags question: http://stackoverflow.com/q/51910966
tags question: http://stackoverflow.com/q/51815161

http://stackoverflow.com/a/51846686
upvote count: 2
downvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/51846547
has body: Divmod function accepts only two parameter hence you get either of the two Divmod() So you can try doing this: time = 0.6 mon, sec = divmod(time, 60) hr, mon = divmod(mon, 60) print "%d:%02d:%02d" % (hr, mon, sec)
score: 0
has comment: http://stackoverflow.com/comment/114315401
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51846547

http://stackoverflow.com/comment/90709565
comment on: http://stackoverflow.com/q/51873379
score: 0
type: Comment
type: QuestionComment
has text: @IljaEverilä: won't you drop a response so I can accept it?

http://stackoverflow.com/comment/98968667
comment on: http://stackoverflow.com/a/51815785
type: AnswerComment
score: 0
type: Comment
has text: The answer here does not highlight the reason behind. it. It should not be the accepted ans.

http://stackoverflow.com/q/51907438
score: -1
type: AnsweredQuestion
tagged with: tkinter
has comment: http://stackoverflow.com/comment/90765675
has body: I am trying to insert text into a new window that opens on a user's button click. However, when I try this, the textbox that I want to open in the new window opens up in the first window. See image below: I have done my research and one answer I have come across is that I am sharing the 'Tk' widget too many times. Here is my code from tkinter import * import tkinter as tk root = tk.Tk() text = Text(root, height=4, width=100) text.pack() text.insert(END, "The family car starting price is £24060 including VAT and CO2 taxes") text.insert(END, "\nThe sports car starting price is £30115 including VAT and CO2 taxes") text.insert(END, "\nThe suv car starting price is £36100 including VAT and CO2 taxes") def family_create_window(): window = tk.Toplevel(root) window.title("family Exterior colour") text = Text(root, height=4, width=100) text.pack() text.insert(END, "Hello") def newwindow(): window = tk.Toplevel(root) window.title("New window") greyex = PhotoImage(file="vwfamilygrey.png") greyexlabel = Button(window, image=greyex) greyexbutton = Button(window, image=greyex, command=newwindow) greyexbutton.pack() window.mainloop() familycar = PhotoImage(file = "VW family car.png") familylabel = Button(root, image=familycar) familybutton = Button(root, image=familycar, command=family_create_window) familybutton.pack() root.mainloop() As soon as the user clicks on the image of the family car, what I want to happen is for a new window with images to open with the text 'hello' at the top of the window. The 'greyex' is the exterior colour for additional help. Any help appreciated. Thanks
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/51907720
upvote count: 0
answer count: 1
has title: Text opens in wrong window tkinter
favorite count: 0
has comment: http://stackoverflow.com/comment/90765787
accepted answer: http://stackoverflow.com/a/51907720
tagged with: python

http://stackoverflow.com/comment/90790171
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51919806
has text: Seems like you could use `subprocess.Popen()` to execute a separate command line process (and `wait()` for it to finish). When the process ends and `wait()` return you can the process the updated file as desired. Most OS's come with some sort of basic text editor, so you could pick an appropriate one based on `os.name`.

http://stackoverflow.com/comment/90631500
type: QuestionComment
comment on: http://stackoverflow.com/q/51834420
has text: You can use the buffers directly. So reshape the numpy array into a vector and pass the 1D array along with the dimensions to the C++ interface. Within the C++ code, convert the 1D array into a cv::Mat using also the dimensions passed from python. Reverse the process in the other direction (C++ to python). You might find this helpful: https://github.com/yati-sagade/opencv-ndarray-conversion/blob/master/conversion.cpp
score: 0
type: Comment

http://stackoverflow.com/a/51855871
type: Answer
has comment: http://stackoverflow.com/comment/90664367
score: 0
has comment: http://stackoverflow.com/comment/90667592
has body: I found two solution for the problem on Superuser StackExchange Solution 1 ln -s /etc/yum.conf /etc/yum/yum.conf Solution 2 Remove newly installed python rm /usr/bin/python Link python with the correct version (x.y) ln -s /usr/bin/pythonx.y /usr/bin/python
answers question: http://stackoverflow.com/q/51855290
has comment: http://stackoverflow.com/comment/90689199
has comment: http://stackoverflow.com/comment/90690424
has comment: http://stackoverflow.com/comment/90690374

http://stackoverflow.com/q/51815299
possible better answer: http://stackoverflow.com/a/51815760
answer count: 2
has comment: http://stackoverflow.com/comment/90585180
accepted answer: http://stackoverflow.com/a/51815785
has comment: http://stackoverflow.com/comment/90585290
has comment: http://stackoverflow.com/comment/90585076
tagged with: scikit-learn
favorite count: 0
has comment: http://stackoverflow.com/comment/90585385
has comment: http://stackoverflow.com/comment/90585582
has comment: http://stackoverflow.com/comment/90585155
tagged with: python
has comment: http://stackoverflow.com/comment/90584937
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90585000
has comment: http://stackoverflow.com/comment/90585652
upvote count: 2
has body: I have written a code based on this site and made different multi-label classifiers. I would like to evaluate my model based on accuracy per class and F1 measurement per class. The problem is that I am getting the same number for both accuracy and f1 measurement in all models. I am suspicious I have done something wrong. I would like to know in which circumstances this may happen. the code is exactly the same as the site and I calculated the f1 measurement like this: print('Logistic Test accuracy is {} '.format(accuracy_score(test[category], prediction))) print 'Logistic f1 measurement is {} '.format(f1_score(test[category], prediction, average='micro')) Update 1 this is the whole code, df = pd.read_csv("finalupdatedothers.csv") categories = ['ADR','WD','EF','INF','SSI','DI','others'] train,test = train_test_split(df,random_state=42,test_size=0.3,shuffle=True) X_train = train.sentences X_test = test.sentences NB_pipeline = Pipeline([('tfidf', TfidfVectorizer(stop_words=stop_words)), ('clf',OneVsRestClassifier(MultinomialNB(fit_prior=True,class_prior=None))),]) for category in categories: print 'processing {} '.format(category) NB_pipeline.fit(X_train,train[category]) prediction = NB_pipeline.predict(X_test) print 'NB test accuracy is {} '.format(accuracy_score(test[category],prediction)) print 'NB f1 measurement is {} '.format(f1_score(test[category],prediction,average='micro')) print "\n" and this is the output: processing ADR NB test accuracy is 0.821963394343 NB f1 measurement is 0.821963394343 and this is the way my data looks: ,sentences,ADR,WD,EF,INF,SSI,DI,others 0,"extreme weight gain, short-term memory loss, hair loss.",1,0,0,0,0,0,0 1,I am detoxing from Lexapro now.,0,0,0,0,0,0,1 2,I slowly cut my dosage over several months and took vitamin supplements to help.,0,0,0,0,0,0,1 3,I am now 10 days completely off and OMG is it rough.,0,0,0,0,0,0,1 4,"I have flu-like symptoms, dizziness, major mood swings, lots of anxiety, tiredness.",0,1,0,0,0,0,0 5,I have no i…
has answer: http://stackoverflow.com/a/51815785
tagged with: machine-learning
tagged with: multilabel-classification
downvote count: 1
has comment: http://stackoverflow.com/comment/90584956
type: Question
has title: Same accuracy and F1 score while doing multi label classification
has comment: http://stackoverflow.com/comment/90585095
has comment: http://stackoverflow.com/comment/90585139
has answer: http://stackoverflow.com/a/51815760
score: 1
linked to: http://stackoverflow.com/q/31421413
tagged with: svm

http://stackoverflow.com/a/51822316
has comment: http://stackoverflow.com/comment/90599886
score: 0
has comment: http://stackoverflow.com/comment/90599801
type: Answer
has body: You need: It's not clear from the question that horse and horseless can both be True at same time. import pandas as pd import numpy as np df = pd.DataFrame({'Name':['Alabama','Deleware','Ohio','Virginia'], 'value1':[1,2,3,4], 'value2':[5,6,7,8]}) horse_mayor_yes = ['Alabama', 'Deleware'] horse_mayor_no = ['Ohio', 'Virginia'] df['Horse'] = np.where(df['Name'].isin(horse_mayor_yes), 1, 0) df['Horseless'] = np.where(df['Name'].isin(horse_mayor_no), 1, 0) print(df) Output: Name value1 value2 Horse Horseless 0 Alabama 1 5 1 0 1 Deleware 2 6 1 0 2 Ohio 3 7 0 1 3 Virginia 4 8 0 1
answers question: http://stackoverflow.com/q/51822161

deep-learning
tags question: http://stackoverflow.com/q/51827712
tags question: http://stackoverflow.com/q/51890070
tags question: http://stackoverflow.com/q/51914632
tags question: http://stackoverflow.com/q/51848406
tags question: http://stackoverflow.com/q/51952028
tags question: http://stackoverflow.com/q/51805991
tags question: http://stackoverflow.com/q/51930944
tags question: http://stackoverflow.com/q/51948171
tags question: http://stackoverflow.com/q/51946114
tags question: http://stackoverflow.com/q/51949208
tags question: http://stackoverflow.com/q/51838583
tags question: http://stackoverflow.com/q/51934087
tags question: http://stackoverflow.com/q/51907487
tags question: http://stackoverflow.com/q/51885739
tags question: http://stackoverflow.com/q/51825926
tags question: http://stackoverflow.com/q/51840815
tags question: http://stackoverflow.com/q/51944387
tags question: http://stackoverflow.com/q/51904877
tags question: http://stackoverflow.com/q/51801648
tags question: http://stackoverflow.com/q/51903086
tags question: http://stackoverflow.com/q/51907813
tags question: http://stackoverflow.com/q/51917036
tags question: http://stackoverflow.com/q/51811154
tags question: http://stackoverflow.com/q/51818163
tags question: http://stackoverflow.com/q/51939022
tags question: http://stackoverflow.com/q/51838201
tags question: http://stackoverflow.com/q/51828971
tags question: http://stackoverflow.com/q/51923094
tags question: http://stackoverflow.com/q/51901386
tags question: http://stackoverflow.com/q/51889378
tags question: http://stackoverflow.com/q/51886943
tags question: http://stackoverflow.com/q/51906602
tags question: http://stackoverflow.com/q/51812884
tags question: http://stackoverflow.com/q/51848429
tags question: http://stackoverflow.com/q/51853185
tags question: http://stackoverflow.com/q/51944836
type: Tag
tags question: http://stackoverflow.com/q/51886142
tags question: http://stackoverflow.com/q/51885171
tags question: http://stackoverflow.com/q/51943473
tags question: http://stackoverflow.com/q/51828770
tags question: http://stackoverflow.com/q/51926624
tags question: http://stackoverflow.com/q/51816305
tags question: http://stackoverflow.com/q/51951097
tags question: http://stackoverflow.com/q/51874695
tags question: http://stackoverflow.com/q/51835926
tags question: http://stackoverflow.com/q/51839415
tags question: http://stackoverflow.com/q/51948262
tag name: deep-learning
tags question: http://stackoverflow.com/q/51835810
tags question: http://stackoverflow.com/q/51818763
tags question: http://stackoverflow.com/q/51798784
tags question: http://stackoverflow.com/q/51906709

http://stackoverflow.com/comment/90568924
score: 2
comment on: http://stackoverflow.com/q/51806731
has text: You should not use `time.time` to measure execution time. But yes, `%timeit` in ipython reports somewhat comparable results (630 ms vs 60 ms, and only 7.7 ms without `apply/lambda`).
type: QuestionComment
type: Comment

http://stackoverflow.com/q/51815032
has comment: http://stackoverflow.com/comment/90585675
tagged with: discrete-mathematics
downvote count: 4
has comment: http://stackoverflow.com/comment/90585078
has comment: http://stackoverflow.com/comment/90584456
answer count: 1
tagged with: data-science
favorite count: 0
has title: How to do discrete optimization with python
tagged with: python
has comment: http://stackoverflow.com/comment/90584821
tagged with: mathematical-optimization
score: -3
has answer: http://stackoverflow.com/a/51829071
upvote count: 1
accepted answer: http://stackoverflow.com/a/51829071
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90585546
has body: I have a discrete optimization problem similar to Y=3X1+2X2 (a sample one) Minimize Y such that there are some constraints for X1 and X2 like X1 +X2 >20 X1 can take values from {5,10,15,25,85} X2 can take values from {20,25,5,40,10} etc How can do this problem with python
tagged with: math

http://stackoverflow.com/comment/90854536
score: 0
type: AnswerComment
type: Comment
has text: When I use that dataframe, I get `<Where is dave today, after school?/>`
comment on: http://stackoverflow.com/a/51951996

http://stackoverflow.com/a/51864893
answers question: http://stackoverflow.com/q/51852091
has body: Solved it! The thing is that Image.open(BytesIO(data)) apparently expects the data to have some kind of header to describe the image type and was therefore unfitting for a mat converted to bytes because a Mat appears to have no kind of header integrated, just the plain image data. In python an Image from a Mat bytearray can be derived using the following: img = cv2.imdecode(bytearray, flag) with flag being a number representing the cvtype of the image.
type: Answer
score: 0
accepted answer of: http://stackoverflow.com/q/51852091
type: AcceptedAnswer

http://stackoverflow.com/comment/90640021
type: Comment
comment on: http://stackoverflow.com/a/51830109
type: AnswerComment
has text: Why did you use `QToolButton` instead of `QPushButton`? I'm having trouble connecting the formers with functions, as they don't have a `connect()` method as the latters. How can a function be called when pressing a `QToolButton`?
score: 0

http://stackoverflow.com/comment/90858641
score: 0
has text: Initially, I did that. An error popped up saying add_ax not defined. Any other guess?
comment on: http://stackoverflow.com/a/51954105
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/90768064
score: 0
type: QuestionComment
type: Comment
has text: In your second code, the reason you don't get any legends is because in `plt.plot(vDT, mPR[i,:])` you don't specify any `legend`. In the third code, you are plotting `45xiN` plots whereas in your first code, you have only 45 plots
comment on: http://stackoverflow.com/q/51908481

api
tags question: http://stackoverflow.com/q/51801331
tags question: http://stackoverflow.com/q/51921949
tags question: http://stackoverflow.com/q/51847184
tags question: http://stackoverflow.com/q/51901399
tags question: http://stackoverflow.com/q/51913496
tags question: http://stackoverflow.com/q/51863463
tags question: http://stackoverflow.com/q/51941227
tags question: http://stackoverflow.com/q/51840471
tags question: http://stackoverflow.com/q/51905003
tags question: http://stackoverflow.com/q/51811109
type: Tag
tags question: http://stackoverflow.com/q/51817286
tags question: http://stackoverflow.com/q/51922869
tags question: http://stackoverflow.com/q/51859929
tag name: api
tags question: http://stackoverflow.com/q/51890024
tags question: http://stackoverflow.com/q/51903413
tags question: http://stackoverflow.com/q/51817237
tags question: http://stackoverflow.com/q/51954361
tags question: http://stackoverflow.com/q/51817192
tags question: http://stackoverflow.com/q/51916917
tags question: http://stackoverflow.com/q/51812123
tags question: http://stackoverflow.com/q/51954482

http://stackoverflow.com/comment/90861219
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/51891193
has text: Great explanation! Thanks!! I'm still working out the details and hope to understand all of it soon.

http://stackoverflow.com/comment/90579174
type: AnswerComment
has text: This triggers every time the mouse leaves the widget area, not if the focus changes.
type: Comment
comment on: http://stackoverflow.com/a/51812034
score: 0

http://stackoverflow.com/a/51827632
type: AcceptedAnswer
downvote count: 0
has body: No recursion needed; you've already done that hard parts of accessing and counting the pixels you need. Starting here: counts = (summit_roi &lt; 50).sum() Let's work both ways to get the result you want. First, let's work with counts to neatly get the results for one image: dark_pixel_count = (image[100:200, 250:450] &lt; 50).sum() Now, add the check against 2000 for your Boolean decision of whether there's a cloud: is_cloud = (image[100:200, 250:450] &lt; 50).sum() &gt; 2000 Note how I'm adding a new clause or clarification at each step, re-naming the result. You can do all of this with successive steps and intermediate variable names; that's good for debugging. Some one-line computations are more "Pythonic". is_cloud is a simple Boolean (True / False). Next, back up and get the image more directly from the source. Where we have for imagePath in image_path_list: image = cv2.imread(imagePath, 0) is_cloud = (image[100:200, 250:450] &lt; 50).sum() &gt; 2000 make the substitution for image is_cloud = (cv2.imread(imagePath, 0) [100:200, 250:450] &lt; 50).sum() &gt; 2000 Now, let's get a list of all the cloud detection, iterating over the input set: is_cloud_list = [ (cv2.imread(imagePath, 0) [100:200, 250:450] &lt; 50).sum() &gt; 2000 for imagePath in image_path_list ] This gives us a list of Booleans, one for each image. Now, we just count how many are True: cloud_count = [ (cv2.imread(imagePath, 0) [100:200, 250:450] &lt; 50).sum() &gt; 2000 for imagePath in image_path_list ].count(True) Does this solve the problem?
type: Answer
answers question: http://stackoverflow.com/q/51827358
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/51827358
has comment: http://stackoverflow.com/comment/90735511

http://stackoverflow.com/comment/90631830
type: QuestionComment
has text: you could publish the .kv to make a translation to .py
comment on: http://stackoverflow.com/q/51839412
score: 0
type: Comment

http://stackoverflow.com/q/51905249
has title: Python Tkinter GUI Save As User Input to Variables in .py File
score: 0
linked to: http://stackoverflow.com/q/14824163
has comment: http://stackoverflow.com/comment/90761204
has comment: http://stackoverflow.com/comment/90801411
has comment: http://stackoverflow.com/comment/90833094
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90828902
answer count: 0
has body: I am attempting to build an Python custom PDF invoicing code where with a GUI where: -The user types input into the GUI. -The inputs can be "Save as" into a new file generated. -This file is an executable to generate a custom invoice PDF file with the user's input. -However I am trying to get all of this done on the one screen GUI, with all the buttons to save as and execute the file to generate a custom PDF. --My biggest challenge right now is how to save user inputs as variables in a new "Save as" file. Should I use arrays for this? Thanks in advance! ---Here is my attempt so far. #Form filling mapping import io import pdfrw from reportlab.pdfgen import canvas def run(): canvas_data = get_overlay_canvas() form = merge(canvas_data, template_path='./SmartInvoice.pdf') save(form, filename='merged.pdf') def get_overlay_canvas() -&gt; io.BytesIO: data = io.BytesIO() pdf = canvas.Canvas(data) #Invoice issuer, company name etc: pdf.drawString(x=100, y=727, text='Midland REalty Pty Ltd') #Issuer address pdf.drawString(x=100, y=711, text='477 Darling Street, Balmain NSW 2041') #ABN or ACN pdf.drawString(x=100, y=696, text='ABN: 113 646 174') #Phone Contact pdf.drawString(x=100, y=681, text='Ph: 0433163800') #Invoice issued to: pdf.drawString(x=83, y=606, text='Invoiced to Client Name') #Customer Details: pdf.drawString(x=83, y=591, text='22 Moonview Crescent, Henley, NSW 2011, 0404755999') #Tax Invoice No. pdf.drawString(x=535, y=674, text='22') #Date of issuance of invoice pdf.drawString(x=516, y=658, text='Date of issuance of invoice') #Form Description pdf.drawString(x=33, y=650, text='Midland Realty Invoice #0209') #Subtotal pdf.drawString(x=500, y=458, text='$1,000,000') #Subtotal 2 pdf.drawString(x=500, y=400, text='$1,500,000') #Subtotal 3 pdf.drawString(x=500, y=342, text='$4,000,000') #Total pdf.drawString(x=500, y=237, text='$6,500,000') #GST pdf.drawString(x=500, y=210, text='$715,000') #Total Inc. GST pdf.drawString(x=500, y=178, text='$7,150,000') #Description…
has comment: http://stackoverflow.com/comment/90833882
has comment: http://stackoverflow.com/comment/91497400
type: Question

http://stackoverflow.com/q/51893841
has comment: http://stackoverflow.com/comment/90746647
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/51898913
has comment: http://stackoverflow.com/comment/90749315
tagged with: arrays
score: 2
has body: I currently try to pack a multitude of arrays to numpy structured arrays. According to the numpy documentation Sub-arrays always have a C-contiguous memory layout. But if I create a structured array with: x = np.zeros((2,), dtype=[('a', (np.float64, 5)), ('b', (np.float64, 5))]) x['a'].flags # Out: C_CONTIGUOUS : False # F_CONTIGUOUS : False # OWNDATA : False # ... While x.flags # Out: C_CONTIGUOUS : True # F_CONTIGUOUS : True # OWNDATA : True # ... And using a "outer" shape of (1,) for the arrays yields: x = np.zeros((1,), dtype=[('a', (np.float64, 5)),('b',(np.float64, 7))]) x['a'].flags # Out: C_CONTIGUOUS : True # F_CONTIGUOUS : False # OWNDATA : False # ... Omitting (1,) yields arrays with ndim=1 with c-contiguity. So the quote seems to be True only for the rows of an structured array. What confuses me is that contiguity is given when I specify the array shape directly for each subarray: x = np.zeros((), dtype=[('a', (np.float64, (2, 5))), ('b', (np.float64, (2, 5)))]) x['a'].flags #Out: C_CONTIGUOUS : True # F_CONTIGUOUS : False # OWNDATA : False From the quote of the numpy documentation I thought that sub-arrays always have a C-contiguous memory layout, but this only seems to be true for rows OR when the shape per array is given. Where does this behavior come from? Is defining the "outer" shape (I don't know how to call it...) telling numpy to make row-wise sub-arrays of sub-arrays, while specifying the shape for each sub-array directly contiguously stores each sub-array? What is the best way to deal with this when the first dimension of all sub-arrays is equal, while the second dimension is not? Should I specify each shape directly to keep them contiguous?
answer count: 1
has title: Sub-arrays in numpy structured array not c contiguous
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/51898913
tagged with: structured-array
upvote count: 2
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/a/51912798
downvote count: 0
score: 1
has body: The source code sheds some light on this ciphertext: tsfresh/feature_extraction/extraction.py:76: :param column_id: The name of the id column to group by. :type column_id: str So, this is a column that should have the same value for all points of a time series. If there are multiple values in this column in the dataframe, the lib will interpret it as multiple time series and analyze them all at the same time.
has comment: http://stackoverflow.com/comment/90775762
has comment: http://stackoverflow.com/comment/90775937
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/90775880
answers question: http://stackoverflow.com/q/51912461

http://stackoverflow.com/comment/90760257
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51904459
has text: Meanwhile, this would probably be a lot easier to explain with concrete, meaningful names instead of things like `C` and `x_C`.

http://stackoverflow.com/comment/90644046
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51845099
score: 0
has text: "My first idea was a metaclass that defines which functions need to exist and classes that implement these functions." Perhaps you want the `abc` module?

http://stackoverflow.com/comment/90636488
score: 0
comment on: http://stackoverflow.com/a/51841609
type: AnswerComment
type: Comment
has text: I get this error: AttributeError("'function' object has no attribute 'plot'")

http://stackoverflow.com/comment/121464034
comment on: http://stackoverflow.com/a/51866371
type: AnswerComment
score: 0
type: Comment
has text: Thanks. I was missing the `host='0.0.0.0'` bit.

http://stackoverflow.com/a/51823516
score: 6
has body: There are two ways: by a whitelist of roles using has_any_role @bot.command(pass_context=True) @commands.has_any_role("Big Cheese", "Medium Cheese") async def admins_only_command(ctx, *, args): '''do stuff''' or by permission using has_permissions @bot.command(pass_context=True) @commands.has_permissions(administrator=True) async def admins_only_command(ctx, *, args): '''do stuff''' Both of these decorators are Checks, and will raise some subclass of CommandError for you to optionally handle if they fail.
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51814995
type: Answer
upvote count: 6
accepted answer of: http://stackoverflow.com/q/51814995

http://stackoverflow.com/comment/90778512
comment on: http://stackoverflow.com/q/51914255
has text: Have you seen this? https://stackoverflow.com/questions/40390634/pandas-groupby-nlargest-sum
type: Comment
score: 1
type: QuestionComment

http://stackoverflow.com/comment/90608694
comment on: http://stackoverflow.com/a/51827157
score: 1
type: AnswerComment
has text: What if I was checking for 3 days before the current date? I did today = today - timedelta(3) when it was a datetime object
type: Comment

http://stackoverflow.com/a/51845847
answers question: http://stackoverflow.com/q/51844940
upvote count: 1
downvote count: 0
has body: The method you are looking for is weights: weights the weights of layers. New in version 2.0.0. As the annotation says, you'll need to update you Spark version to at least 2.0 to be able to use it.
type: Answer
has comment: http://stackoverflow.com/comment/90662401
score: 1

http://stackoverflow.com/a/51896892
accepted answer of: http://stackoverflow.com/q/51896621
has comment: http://stackoverflow.com/comment/90747577
has body: You can create another DataFrame by split resumo column and add to original by join, then for counting use groupby with size: s = (df.pop('resumo').str.split(',', expand=True) .stack() .reset_index(level=1, drop=True) .rename('resumo')) df = df.join(s).groupby(['nome','tipo','resumo']).size().reset_index(name='count') print (df) nome tipo resumo count 0 CÉSAR MESSIAS AP Desvio de verbas públicas 1 1 CÉSAR MESSIAS INQ Desvio de verbas públicas 1 2 FLAVIANO MELO AP Gestão fraudulenta 1 3 FLAVIANO MELO AP Peculato 1 4 FLAVIANO MELO INQ Prestação de contas rejeitada 1 If want use Counter solution with last solution: s = df.dropna().groupby(['nome', 'tipo']).resumo.agg(', '.join).str.split(', ').agg(Counter) print (s) nome tipo CÉSAR MESSIAS AP {'Desvio de verbas públicas': 1} INQ {'Desvio de verbas públicas': 1} FLAVIANO MELO AP {'Peculato': 1, 'Gestão fraudulenta': 1} INQ {'Prestação de contas rejeitada': 1} Name: resumo, dtype: object df2 = (pd.DataFrame(s.values.tolist(), index=s.index) .stack() .astype(int) .reset_index(name='count') .rename(columns={'level_2':'resumo'})) print (df2) nome tipo resumo count 0 CÉSAR MESSIAS AP Desvio de verbas públicas 1 1 CÉSAR MESSIAS INQ Desvio de verbas públicas 1 2 FLAVIANO MELO AP Gestão fraudulenta 1 3 FLAVIANO MELO AP Peculato 1 4 FLAVIANO MELO INQ Prestação de contas rejeitada 1
answers question: http://stackoverflow.com/q/51896621
has comment: http://stackoverflow.com/comment/90747447
has comment: http://stackoverflow.com/comment/91305712
score: 3
has comment: http://stackoverflow.com/comment/91299625
upvote count: 3
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91299634
type: Answer

wsgi
type: Tag
tags question: http://stackoverflow.com/q/51865565
tags question: http://stackoverflow.com/q/51892217
tags question: http://stackoverflow.com/q/51849725
tags question: http://stackoverflow.com/q/51933437
tags question: http://stackoverflow.com/q/51953349
tags question: http://stackoverflow.com/q/51842485
tag name: wsgi

http://stackoverflow.com/comment/90588805
comment on: http://stackoverflow.com/q/51817384
has text: As shown the first two lines of your code are irrelevant, neither of the variables they update is used in the `print` statement. I haven't a clue what you expect.
type: QuestionComment
type: Comment
score: 3

http://stackoverflow.com/a/51802440
answers question: http://stackoverflow.com/q/51802421
has comment: http://stackoverflow.com/comment/90561573
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/90563932
downvote count: 0
has body: You may use -[0-9]*([0-9]{2})- See the regex demo. The captured digits will be the last two before the hyphen. To grab the digit before the last two, use -[0-9]*([0-9])[0-9]{2}- See another regex demo. Details - - a hyphen [0-9]* - zero or more digits ([0-9]{2}) - Capturing group 1 (when using extract, that is the value returned by the method): two digits that are followed with... - - a hyphen.
has comment: http://stackoverflow.com/comment/90561736
upvote count: 2

http://stackoverflow.com/comment/90659972
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51852551
has text: I also updated with a small sample of my data frame so it is now reproducible.

http://stackoverflow.com/comment/90770637
type: QuestionComment
comment on: http://stackoverflow.com/q/51910264
score: 0
has text: What's the error message, or the unexpected behavior? "It doesn't work" is not useful.
type: Comment

http://stackoverflow.com/comment/90558983
has text: You can certainly use `logical_and()` but `numpy` does support using `&` operator - you just have to put `()` around each expression.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51801286
type: Comment

http://stackoverflow.com/comment/90867919
comment on: http://stackoverflow.com/q/51945233
score: 0
type: Comment
type: QuestionComment
has text: I would say that your first step is wrong. You should apply a strong non-linear, edge preserving smoothing to the original picture. This will simplify the image, reduce the number of colors you see, but not introduce unnatural edges and colors like these. In [this answer](https://stackoverflow.com/a/48701839/7328782) I show one such filter.

http://stackoverflow.com/a/73354352
type: Answer
score: 6
downvote count: 0
has body: Sorry for reviving this question, but I wanted to point out that one can implement a similar strategy without using javascript. The idea is to pre-process the form data on submit and then reload the form with the processed data (using the built-in capabilities of wtforms to recreate a form from its data). One way of doing it can be as follows. Add an extra input field to the form and define an update_self method: class AuthorForm(FlaskForm): name = StringField('name', validators=[InputRequired()]) books = FieldList(FormField(BookForm), min_entries=1) submit = SubmitField('Save') addline = SubmitField('Add new line') # This is the new input def update_self(self): # read the data in the form read_form_data = self.data # modify the data as you see fit: updated_list = read_form_data['books'] if read_form_data['addline']: updated_list.append({}) read_form_data['books'] = updated_list # reload the form from the modified data self.__init__(formdata=None, **read_form_data) self.validate() # the errors on validation are cancelled in the line above Note: formdata=None is necessary to prevent the FlaskForm to automatically read the data in the form. If you omit it, the form will receive formdata when running the .__init__ method and hence ignore your newly processed data. In the template, display the new input: {{ form.addline() }} In the definition route, call the update_self method as first thing on submit: @app.route('/', methods=['GET', 'POST']) def index(): form = AuthorForm() if form.validate_on_submit(): form.update_self() # This reloads the form with the processed data for book in form.books.data: print(book) return render_template_string(html_template_string, form=form) I hope this helps!
upvote count: 6
answers question: http://stackoverflow.com/q/51817148

http://stackoverflow.com/q/51805080
score: 0
accepted answer: http://stackoverflow.com/a/51812274
has body: I would like to know if there is a way to add markers to multiline for bokeh. I can get the multiple lines but then p.circle() doesn't seem to work on list of lists. Here is a sample: from bokeh.plotting import figure, show from bokeh.models import ColumnDataSource from bokeh.palettes import Spectral6, Spectral11 numlines = 2 mypalette = Spectral6[0:numlines] data = {'x_values': [[1, 2, 3], [1,2,3]], 'y_values': [[1, 2, 3], [4 ,5, 6]], 'labels': ['a', 'b'], 'line_color': mypalette} source = ColumnDataSource(data=data) p = figure() p.multi_line(xs='x_values', ys='y_values', line_color='line_color', source=source) show(p)
tagged with: multiline
answer count: 1
has title: query bokeh multi_line with markers
has answer: http://stackoverflow.com/a/51812274
tagged with: python
type: AnsweredQuestion
tagged with: bokeh
type: Question

http://stackoverflow.com/comment/90609422
comment on: http://stackoverflow.com/q/51827117
type: Comment
type: QuestionComment
has text: What are the `#Some actions` in your code? Are you talking to the calculator window via Windows messages (or `pyautogui` or something similar)? Or talking to a calculator instance via COM automation? If not, what do those actions have to do with the calculator window you just opened? If you can explain what you are trying to do, maybe we can explain a better way to do it.
score: 0

http://stackoverflow.com/q/51824219
type: UnansweredQuestion
tagged with: python
has body: I am encountering the following error: Traceback (most recent call last): File "C:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\platform\self_check.py", line 87, in preload_check ctypes.WinDLL(build_info.cudnn_dll_name) File "C:\Anaconda\envs\tensorflow\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 "&lt;stdin ", line 1, in &lt;module File "C:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\__init__.py", line 22, in &lt;module from tensorflow.python import pywrap_tensorflow # pylint: disable=unused-import File "C:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\__init__.py", line 49, in &lt;module from tensorflow.python import pywrap_tensorflow File "C:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 30, in &lt;module self_check.preload_check() File "C:\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\platform\self_check.py", line 97, in preload_check % (build_info.cudnn_dll_name, build_info.cudnn_version_number)) ImportError: Could not find 'cudnn64_7.dll'. TensorFlow requires that this DLL be installed in a directory that is named in your %PATH% environment variable. Note that installing cuDNN is a separate step from installing CUDA, and this DLL is often found in a different directory from the CUDA DLLs. You may install the necessary DLL by downloading cuDNN 7 from this URL: https://developer.nvidia.com/cudnn I have installed the required "cuDNN 7" files in the directory mentioned in the %Path% environment, yet the statement import tensorflow as tf is not working. I have downloaded the cuDNN 7 files from the mentioned site: https://developer.nvidia.com/cudnn I have gone through all the answers on StackOverflow and yet I am getting stuck with the same error. Please gui…
downvote count: 0
score: 1
tagged with: tensorflow
type: Question
has title: ImportError: Could not find 'cudnn64_7.dll'
tagged with: anaconda
has answer: http://stackoverflow.com/a/52079625
answer count: 3
upvote count: 1
tagged with: cudnn
has answer: http://stackoverflow.com/a/59968745
favorite count: 0
has answer: http://stackoverflow.com/a/68888109

http://stackoverflow.com/comment/90656290
has text: As a side note: If your code is really written for Python 2, and you aren't using `from __future__ import print_function`, you really shouldn't use Python 3-stye `print(…)` calls. Everything will seem to work, until the first time you accidentally do `print(one_thing, another_thing)` and wonder why it's printing out `('spam', 'eggs')` instead of `spam eggs`.
score: 2
type: QuestionComment
comment on: http://stackoverflow.com/q/51851410
type: Comment

http://stackoverflow.com/comment/90864285
comment on: http://stackoverflow.com/a/51956622
type: Comment
has text: This works so far. Still having the issue with only retrieving a small amount of Urls..
score: 0
type: AnswerComment

http://stackoverflow.com/comment/90655996
type: Comment
comment on: http://stackoverflow.com/q/51851520
score: 0
has text: Your indentation is all over the place. Please fix it. Python is very space sensitive and what you show simply won't run.
type: QuestionComment

http://stackoverflow.com/comment/90753982
type: Comment
has text: I did not pass the `batch_size` argument for `fit` . But I did use `shape=X.shape[1:]` and that did seem to fix my problem. Cheers!
comment on: http://stackoverflow.com/a/51854675
type: AnswerComment
score: 0

http://stackoverflow.com/a/51823361
score: 1
answers question: http://stackoverflow.com/q/51823203
upvote count: 1
type: Answer
downvote count: 0
has body: The following is what I would do. (Usage note: If a word ends in a capital, then the next word will start with a capital if separated by a single space.) def myfunc(word): new_string = '' for i, char in enumerate(word): if char == ' ': continue if i % 2 == 0: new_string += char.upper() else: new_string += char.lower() return new_string Notes: I replaced the *args parameter and made it word to give a clearer idea of what needs to be passed in to the function, and to make sure only 1 string is passed. I've omitted string type validation/checking. when counting a position in a loop, use enumerate() to return a tuple as (index, item). This acts as a counter like your variable x, which I chose to name i Generally use the parameter 'i' to keep count instead of x, although this is merely style. Iterate over a string to get its individual characters. Although a while loop with a counter is viable, for loops are cleaner and automatically return the correct item without having to manually index it from the string with your counter. I added the first if statement to ignore whitespace characters, but I don't think it's necessary for this function.

http://stackoverflow.com/comment/90611433
comment on: http://stackoverflow.com/q/51828192
has text: I'm not interested in drawing 3 separate figures and hiding them based on input. I want to have one figure in which points are toggled. So that the camera perspective, etc. is preserved.
score: 0
type: Comment
type: QuestionComment

cryptography
tag name: cryptography
type: Tag
tags question: http://stackoverflow.com/q/51806127
tags question: http://stackoverflow.com/q/51838134
tags question: http://stackoverflow.com/q/51939932
tags question: http://stackoverflow.com/q/51909512

http://stackoverflow.com/a/51915715
type: Answer
score: 0
upvote count: 1
answers question: http://stackoverflow.com/q/51914544
downvote count: 1
has body: I don't understand how there are 2^n cases for a list of length n. Ok, in this case, to check for every possible subset, we either take the current element in iteration or we don't take current element in iteration. This brings us 2 cases for each element -> Take or Not take. For the below tree, I will represent take as T and Don't take as DT. Let's consider this array => [1,3,5]. Recursion tree looks something like this- Start state / \ / \ / \ T-1 DT-1 / \ / \ / \ / \ / \ / \ / \ / \ T-3 DT-3 T-3 DT-3 / \ / \ / \ / \ / \ / \ / \ / \ T-5 DT-5 T-5 DT-5 T-5 DT-5 T-5 DT-5 As you can see from the above tree, there are 23 leaves defining 23 subset possibilities. You can make such recursion trees for inputs larger than size 3 to understand why complexity is exponential (2n) in this case. You can detect any subset from this tree by traversing from root to each leaf. For example- [Start state,T-1,DT-3,T-5] means subset [1,5].

http://stackoverflow.com/comment/90778406
type: Comment
score: 1
comment on: http://stackoverflow.com/q/51914164
has text: If your data contains two (or more) separate instances of decreasing GDP over two consecutive quarters, say for example 2004q2 to 2004q4 and also 2007q3 to 2008q1, which quarter do you want your code to return? 2004q2 or 2007q3?
type: QuestionComment

http://stackoverflow.com/q/51856733
tagged with: vector
tagged with: pyspark
type: UnansweredQuestion
tagged with: apache-spark
score: 2
answer count: 0
downvote count: 0
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/38384347
tagged with: python
duplicate of: http://stackoverflow.com/q/38384347
upvote count: 2
has body: I have a PySpark Dataframe that was created by pyspark.ml.clustering.LDA. The topicDistribution column is a vector of n doubles. +--------------------+ | topicDistribution| +--------------------+ |[0.93673575849807...| |[0.31615978901762...| |[0.33657712774309...| |[0.30523697192979...| +--------------------+ I want to create separate, (non-vector), double columns for each of the vector columns. Ultimately, I'm trying to "unwrap" the vector so I can write the data to a CSV file. I've tried multiple approaches. Approach 1 was to simply index into the column for i in range(3): df = df.withColumn("Col-" + str(i), df['topicDistribution'][i]) but this produces the error AnalysisException: u"Can't extract value from topicDistribution#858;" Approach 2 tried to use a UDF, but as you can see, my UDF isn't passed a vector but a "pickle". And I don't know what to do anything with that. getTyp = udf(lambda arr: getType(arr,1), StringType()) for i in range(3): df = df.withColumn("Col-" + str(i), getTyp(df['topicDistribution'])) which returns +--------------------+--------------------+--------------------+--------------------+ | topicDistribution| Col-0| Col-1| Col-2| +--------------------+--------------------+--------------------+--------------------+ |[0.93673577353151...|net.razorvine.pic...|net.razorvine.pic...|net.razorvine.pic...| |[0.31615869274437...|net.razorvine.pic...|net.razorvine.pic...|net.razorvine.pic...| |[0.33657583318666...|net.razorvine.pic...|net.razorvine.pic...|net.razorvine.pic...| |[0.30523585516934...|net.razorvine.pic...|net.razorvine.pic...|net.razorvine.pic...| +--------------------+--------------------+--------------------+--------------------+ Approach 3 used VectorSlicer which came close, but the resulting columns are still vectors. for i in range(3): slicer = VectorSlicer(inputCol="topicDistribution", outputCol="Col-" + str(i), indices=[i]) df = slicer.transform(df) which produces the following. Notice that each column is still a vector (surroundi…
has title: Extract a column from a vector Column in a PySpark Dataframe

http://stackoverflow.com/a/51945554
answers question: http://stackoverflow.com/q/51944799
has comment: http://stackoverflow.com/comment/90841411
has body: Edit: The solution to the original post was using text=localtime2.get() instead of textvariable=localtime2 in the label widget (for some strange reason). However, my original answer is still correct as tkinter variables should be used and so I will keep it up. You must use tkinter variables in tkinter widgets and not normal python variables. Tkinter variables are slightly different to normal variables and must first be defined as a specific data type. For example, a variable which contains a string must be first created like so: string_variable = tk.StringVar() likewise a boolean would be created like so: boolean_variable = tk.BooleanVar() Read here for more information on tkinter variables. These variables are in fact classes so in order to set them use must call the .set() method. Therefore to set a tkinter String variable to "a string" you would use the following code: string_variable = tk.StringVar() # Create the variable string_variable.set("a string") # Set the value of the variable Thus to fix your code you need to make localtime2 a tkinter variable and set it to the time using the .set() method. Example: localtime2 = tk.StringVar() # Create the localtime2 string variable localtime2.set(time.asctime(time.localtime(time.time()))) # Set the variable tk.Label(roots, font=('arial', 16, 'bold'), textvariable=localtime2, bd=16, anchor="w").grid(row=2, column=0)
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90844920
has comment: http://stackoverflow.com/comment/90845144
upvote count: 8
type: Answer
has comment: http://stackoverflow.com/comment/90841759
score: 8
accepted answer of: http://stackoverflow.com/q/51944799
has comment: http://stackoverflow.com/comment/90840667
has comment: http://stackoverflow.com/comment/90840513
has comment: http://stackoverflow.com/comment/90840709

http://stackoverflow.com/a/53333620
answers question: http://stackoverflow.com/q/51898314
has body: I'm using tensorflow with java on the desktop (which might be different) and all I do is create a multi-dimensional array with the correct size, then copy the values over, e.g. Tensor.copyTo(Object dst)
has comment: http://stackoverflow.com/comment/102239917
score: 0
type: Answer

http://stackoverflow.com/a/51902972
has body: singleList.extend( [rock, input('Size: '), int(input('Quantity: '))] )
score: 0
has comment: http://stackoverflow.com/comment/90761619
type: Answer
answers question: http://stackoverflow.com/q/51902953

http://stackoverflow.com/comment/90568169
comment on: http://stackoverflow.com/q/51805471
type: Comment
type: QuestionComment
score: 3
has text: 1. this has nothing to do with HSV. 2. Vectorization is a slow process so unless you got some more info or restrictions on the scene (shapes , orientation complexity) then do not expect fast results ...

http://stackoverflow.com/comment/109922178
has text: @AnshumanKumar I ended up using 2 classes, one class for the thing you are interested in e.g. in my case it's the dogs, and one class for everything else. I know there should be other solutions e.g. anomaly detection, but I haven't tried that. Let me know if you managed to get it working :)
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51894302

http://stackoverflow.com/a/51833374
score: 2
has comment: http://stackoverflow.com/comment/90620934
downvote count: 0
answers question: http://stackoverflow.com/q/51833165
has body: The items within the function must be defined as strings. Don't forget to include the parameters when calling functions. Hope this helps! Refactored Code: from random import randint item = randint(0, 9) def itemName(item): arr = ["Hat", "Gloves", "Scarf", "Top", "Pants", "Shoes", "Socks", "Sunglasses", "Bag", "Jacket"] return(arr[item]) print(itemName(item))
upvote count: 2
type: Answer

http://stackoverflow.com/q/51931167
tagged with: xml-parsing
answer count: 1
tagged with: beautifulsoup
has answer: http://stackoverflow.com/a/51931354
has title: Beautiful soup parsing XML incorrectly
has comment: http://stackoverflow.com/comment/90812282
type: UnansweredQuestion
tagged with: python
tagged with: http://stackoverflow.com/tag/xml
has body: <?xml version="1.0" encoding="UTF-8"?> – Jul-18 ABC – Aug-16 XYZ Beautiful Soup using xml/lxml/lxml-xml parser doesn't parse the second element correctly. It removes the space between Aug-16 and XYZ. It parses it as – Aug-16 XYZ which isn't correct. I have tried making the soup using from_encoding="utf-8" option too. None have worked.
type: Question
has comment: http://stackoverflow.com/comment/90812174
score: 0

http://stackoverflow.com/comment/90772608
has text: The code above already works for `N` pixels (`A` of shape `(N, 2)`). You could use `arange`/`meshgrid` functions to obtain all your image `A`s (shape `(H, W, 2)`) then flatten the tensor so that `N = H * W`.
score: 0
comment on: http://stackoverflow.com/a/51875232
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/90771813
type: Comment
type: QuestionComment
has text: Well if you want to operate on an instance, perhaps rethink making it a class method?
comment on: http://stackoverflow.com/q/51910150
score: 0

http://stackoverflow.com/comment/90641636
score: 0
type: AnswerComment
type: Comment
has text: Glad I could help ! :)
comment on: http://stackoverflow.com/a/51844032

http://stackoverflow.com/a/51900967
score: 2
downvote count: 0
has body: You can use the second dataframe as a dictionary for replacement: to_replace = df1.set_index('retroID')['playerID'].to_dict() df['retroID'].replace(to_replace, inplace=True)
type: Answer
answers question: http://stackoverflow.com/q/51900899
upvote count: 2

http://stackoverflow.com/q/51808519
has body: I would like to have a discord bot that accesses a Django DB. An obvious solution is to have 2 separate scripts. I would like to know if there is a way to make the discord-bot part of the Django as an app or something else.
has comment: http://stackoverflow.com/comment/90572914
has comment: http://stackoverflow.com/comment/90572997
downvote count: 2
type: Question
score: 3
tagged with: discord.py
has answer: http://stackoverflow.com/a/70658031
upvote count: 5
has comment: http://stackoverflow.com/comment/90573048
has title: Run Discord bot inside Django
answer count: 2
favorite count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/75271368
tagged with: django
linked to: http://stackoverflow.com/q/41825037
tagged with: python

http://stackoverflow.com/comment/90784193
type: QuestionComment
has text: I want to use a similar table, but with URLs, instead of usernames. URLs can be quite long and I was thinking about `TEXT` instead of `VARCHAR`.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51916845

http://stackoverflow.com/comment/90894641
type: Comment
type: QuestionComment
score: 2
has text: Hmm I'm not sure. At first glance, my impression was that this question was answered by existing docs but upon a closer look I think you may have uncovered a bug as the syntax of your command looks right to me. Perhaps someone else had the same first impression — I just gave my upvote to balance it out.
comment on: http://stackoverflow.com/q/51955417

http://stackoverflow.com/comment/129156474
has text: This works up through click 7.1.2 but fails with click 8.0.0: `TypeError: get_default() got an unexpected keyword argument 'call'`. The signature of `get_default` changes to `def get_default(self, ctx, call: bool = True):`.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51852432

http://stackoverflow.com/comment/90746252
comment on: http://stackoverflow.com/a/51897447
has text: Yep your import code worked like a charm thank you @modesitt
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/51926003
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/51925908
has body: bulit-in help() is a wrapper around pydoc.Helper, it writes to stdout by default, you could temporarily redirecting sys.stdout to a file: &gt;&gt;&gt; import contextlib &gt;&gt;&gt; with contextlib.redirect_stdout(open('browser_help.txt', 'w')): ... help(browser) or you could call pydoc.Helper directly, : &gt;&gt;&gt; import pydoc &gt;&gt;&gt; with open('browser_help.txt', 'w') as f: ... h = pydoc.Helper(output=f) ... h(browser)
upvote count: 5
type: Answer
downvote count: 0
score: 5
accepted answer of: http://stackoverflow.com/q/51925908

http://stackoverflow.com/q/51804916
tagged with: python
type: AnsweredQuestion
upvote count: 2
linked to: http://stackoverflow.com/q/49866887
has answer: http://stackoverflow.com/a/51805801
type: Question
tagged with: struct
linked to: http://stackoverflow.com/q/39252140
tagged with: python-2to3
accepted answer: http://stackoverflow.com/a/51805801
score: 2
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-3.x
has title: struct unpack (Type Error: a byte like object is required, not 'str"), Unpack a List?
has body: Attempting to use script that was built in Python 2, and now use it in Python 3 without adding a version 2 onto system. For the script, the only error I get is related to a struct.unpack at this line.... def go_parse(rec_list): size = (len(rec_list) - 4) / 4 first_arg = "%sI" % size return struct.unpack(first_arg, (rec_list.rstrip ('\xff\xff\xff\xff'))) at line 4 of this function, I get the error: TypeError: a bytes-like object is required, not 'str' I read several other posts regarding this, and that it needs to be explicitly labeled as bytes, but I cant seem to figure out where to explicitly label that in this context. The other examples on SO i found here and here, did not provide much of an explanation to it. The struct pages don't seem to cover the error possibilities of 2-3...Only that struct.unpack(fmt, buffer) has the two arguments of fmt and buffer. Based on those examples, i have tried identifying this as bytes explicitly as a second arg using b, as well as bytes before the arguments and on the tuple for the .strip. I attempted return this as a bytearray, but that seemed to produce the same errors. As an alternative, I am able to get the byte data I wanted into a list as shown below, what would be a way to get the list into unpack, attempt b'i' just looks at i as bytes. list1 = [b'\x03\x00\x00\x00\xff\xff\xff\xff', b'\x07\x00\x00\x00\x06\x00\x00\x00\xff\xff\xff\xff'] print(struct.unpack('&lt;s', bytes(i))) The bytes are of varying length, but all end in \xff\xff\xff\xff. The data I am looking at is text, just trying to bring it back to text.

http://stackoverflow.com/q/51885175
upvote count: 1
type: Question
has title: PYMC2 ZeroProbability error
has comment: http://stackoverflow.com/comment/90725921
tagged with: pymc
has answer: http://stackoverflow.com/a/51885594
has body: I have a model with 6 parameters with uniform priors: parameter1 = pm.Uniform('parameter1',0.01,1) parameter2 = pm.Uniform('parameter2',0,2) parameter3 = pm.DiscreteUniform('parameter3',1,50) parameter4 = pm.Uniform('parameter4',0,1.75) parameter5 = pm.Uniform('parameter5', 0.005, 0.25) parameter6 = pm.Uniform('parameter6', 0.005, 0.15) I have a custom likelihood function that returns log likelihood value: @pm.potential def log_l(experiment=experiment,parameter1=parameter1,parameter2=parameter2,parameter3=parameter3,parameter4=parameter4,parameter5=parameter5,parameter6=parameter6): if parameter5&lt;parameter4: return -np.inf parameters=[parameter1, parameter2, parameter3] log_l=calculate_probability(parameters, t_m, tol, n_integration, parameter4, parameter5, parameter6, experiment.decon_all[freq,:,:]) return log_l Where calculate_probability is a my function that returns log likelihood for this model given parameter values and observed data. For some reason when MCMC samples: model = pm.MCMC([parameter1,parameter2,parameter3,parameter4,parameter5,parameter6,log_l]) model.sample(100) and the programme satisfies the if condition (parameter5&lt;parameter4) I get this error: pymc.Node.ZeroProbability: Potential log_l forbids its parents' current values I was wondering if anyone knows what I may be doing wrong?
tagged with: log-likelihood
downvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/90729936
has comment: http://stackoverflow.com/comment/90729383
tagged with: python
accepted answer: http://stackoverflow.com/a/51885594
type: AnsweredQuestion
score: 1

http://stackoverflow.com/q/51850861
tagged with: pyqt
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/51863555
has body: While trying to set up a new slot and signal between a worker network QRunnable and code submitting it with callbacks (to handle network responses), I've got the following line of code: exception_callback = QtCore.pyqtSlot('PyQt_PyObject', str)(exception_callback) where exception_callback is a bound member function of some class instance. However, the aforementioned line fails with the following error: AttributeError: 'instancemethod' object has no attribute '__pyqtSignature__' What am I missing? Edit: A simple reproduction: class A(QtCore.QObject): def a(self): print("Called") a=A() QtCore.pyqtSlot()(a.a) Will raise the following exception: AttributeError: 'instancemethod' object has no attribute '__pyqtSignature__' A workaround I found is that wrapping the member function and using a closure around the member function, like so, will work: QtCore.pyqtSlot()(lambda : a.a()) However this is a little messy and I rather not use the workaround without understanding it's necessity.
has comment: http://stackoverflow.com/comment/90678997
has comment: http://stackoverflow.com/comment/90679246
tagged with: python
has comment: http://stackoverflow.com/comment/90655171
has comment: http://stackoverflow.com/comment/90673104
has comment: http://stackoverflow.com/comment/90655027
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90678924
has comment: http://stackoverflow.com/comment/90675701
has comment: http://stackoverflow.com/comment/90667689
has title: pyqt declaring a QtCore.pyslot for an instance method
type: Question
has answer: http://stackoverflow.com/a/51863555

http://stackoverflow.com/q/51825876
has comment: http://stackoverflow.com/comment/90723592
type: Question
tagged with: mongodb
has body: I am trying to connect to the MongoDB cluster I just set up. However, I get these errors and I haven't been able to find the solution. Help would be much appreciated! Python3 Mongodb Altas Cluster - Connect: atlasstring = urllib.parse.quote( "mongodb://&lt;&lt;MYEMAIL&gt;&gt;:&lt;&lt;MYPASSWORD&gt;&gt;@test-shard-00-00-3sqgv.mongodb.net:27017,test-shard-00-01-3sqgv.mongodb.net:27017,test-shard-00-02-3sqgv.mongodb.net:27017/test?ssl=true&amp;replicaSet=test-shard-0&amp;authSource=admin&amp;retryWrites=true") Code: from pymongo import MongoClient from atlasclusterpassword import atlasstring client = MongoClient(atlasstring) db = client.azuresupport print(client.mflix) Error: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pymongo/pool.py", line 357, in get_socket sock_info, from_pool = self.sockets.pop(), True KeyError: 'pop from an empty set' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/encodings/idna.py", line 167, in encode raise UnicodeError("label too long") UnicodeError: label too long The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Users/bethwalsh/Documents/classification-twitter-app/test/test-mongo.py", line 6, in &lt;module&gt; client = MongoClient(atlasstring) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pymongo/mongo_client.py", line 374, in __init__ self._ensure_connected(True) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pymongo/mongo_client.py", line 939, in _ensure_connected self.__ensure_member() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pymongo/mongo_client.py", line 813, in __ensure_member member, nodes = self.__find_node() File "/Library/Frameworks/Python.framework/Versions/…
has comment: http://stackoverflow.com/comment/90679034
linked to: http://stackoverflow.com/q/25103126
has title: MongoDB Atlas connection error - UnicodeError: label too long, UnicodeError: encoding with 'idna' codec failed (UnicodeError: label too long)
score: 0
type: UnansweredQuestion
tagged with: python
tagged with: mongodb-atlas
has comment: http://stackoverflow.com/comment/90606248
answer count: 0
has comment: http://stackoverflow.com/comment/90677456

syntax
tags question: http://stackoverflow.com/q/51913755
type: Tag
tags question: http://stackoverflow.com/q/51842977
tags question: http://stackoverflow.com/q/51889092
tags question: http://stackoverflow.com/q/51947200
tags question: http://stackoverflow.com/q/51943308
tags question: http://stackoverflow.com/q/51811800
tags question: http://stackoverflow.com/q/51944790
tags question: http://stackoverflow.com/q/51924485
tags question: http://stackoverflow.com/q/51923631
tags question: http://stackoverflow.com/q/51939096
tag name: syntax
tags question: http://stackoverflow.com/q/51902805

http://stackoverflow.com/comment/90681538
score: 0
type: AnswerComment
type: Comment
has text: There is random text like "document.documentElement.className = document.documentElement.className.replace" which is getting removed by my code but not by this. It is only removing <> but not other scripts like the one I mentioned have came now.
comment on: http://stackoverflow.com/a/51864323

http://stackoverflow.com/q/51890292
has body: I'd like to make a program in python that analyzes a users input. For example if the user writes "Hello, I'm 19 years old", the program can see that the string has numbers in it and assigns "19" to a variable. It could also at the same time see that the string has the word "years" in it and makes the variable: years = 19 I'm pretty new to python and programming in general, so sorry if the question is weird. Thanks.
upvote count: 0
tagged with: string
has comment: http://stackoverflow.com/comment/90731520
type: AnsweredQuestion
tagged with: input
tagged with: python
has comment: http://stackoverflow.com/comment/90731577
favorite count: 0
type: Question
downvote count: 8
has title: Analyzing strings in Python
has answer: http://stackoverflow.com/a/51890333
answer count: 1
has comment: http://stackoverflow.com/comment/90771104
accepted answer: http://stackoverflow.com/a/51890333
score: -8

http://stackoverflow.com/comment/90612924
has text: "the code does not work" tells us nothing that we can assist you with :/
type: QuestionComment
comment on: http://stackoverflow.com/q/51829209
type: Comment
score: 3

http://stackoverflow.com/comment/90565754
has text: @ Parfait I just have to put each time 96 values in test_data and do mape
score: 0
comment on: http://stackoverflow.com/q/51804842
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51872757
has body: Maybe something like this: menu = [dict(zip(i[::2], i[1::2])) for i in zip(view_class_keys, view_class_values, text_keys, text_values)]
answers question: http://stackoverflow.com/q/51872648
type: Answer
has comment: http://stackoverflow.com/comment/90697249
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/q/51860975
type: Question
score: 3
has title: Are sqlalchemy engine objects disposed automatically?
has comment: http://stackoverflow.com/comment/90676235
has comment: http://stackoverflow.com/comment/90676997
upvote count: 3
has comment: http://stackoverflow.com/comment/90677168
has comment: http://stackoverflow.com/comment/90675287
has comment: http://stackoverflow.com/comment/90675476
favorite count: 0
has body: I have been searching a lot around sqlalchemy connections and engine configuration after I got one of the error: psycopg2.OperationalError) FATAL: remaining connection slots are reserved for non-replication superuser connections I know it is related is pool_size and have increased it for the application to work properly. I was wondering why engine object is not disposed of by the garbage collector automatically. Do we always need to call engine.dispose() each time? Also, continuing with the previous argument does create_engine() will always create a new object or it can return an existing object and if it can return an existing object what is the deciding criteria (like e.g timeouts etc.) of the engine object to return to the pool again. Just shout if you need any more information from me.
type: UnansweredQuestion
tagged with: python
tagged with: psycopg2
downvote count: 0
answer count: 0
has comment: http://stackoverflow.com/comment/90676910
tagged with: sqlalchemy

data-visualization
tags question: http://stackoverflow.com/q/51944378
tags question: http://stackoverflow.com/q/51866626
tags question: http://stackoverflow.com/q/51914837
tags question: http://stackoverflow.com/q/51903232
tags question: http://stackoverflow.com/q/51810492
tags question: http://stackoverflow.com/q/51935179
tags question: http://stackoverflow.com/q/51940596
tags question: http://stackoverflow.com/q/51826942
tags question: http://stackoverflow.com/q/51927723
tags question: http://stackoverflow.com/q/51843313
tag name: data-visualization
tags question: http://stackoverflow.com/q/51865766
type: Tag

http://stackoverflow.com/comment/90841452
comment on: http://stackoverflow.com/q/51945949
type: QuestionComment
type: Comment
has text: I want to create df1 and df2 from the 'data' dataframe (without needing to write out Ouput1data and Output2data code).
score: 0

lstm
tags question: http://stackoverflow.com/q/51917160
tags question: http://stackoverflow.com/q/51842242
tags question: http://stackoverflow.com/q/51809132
tags question: http://stackoverflow.com/q/51886943
tags question: http://stackoverflow.com/q/51847306
tags question: http://stackoverflow.com/q/51845675
tags question: http://stackoverflow.com/q/51886142
tags question: http://stackoverflow.com/q/51945455
tags question: http://stackoverflow.com/q/51814651
tags question: http://stackoverflow.com/q/51822003
tags question: http://stackoverflow.com/q/51906602
tags question: http://stackoverflow.com/q/51812884
tags question: http://stackoverflow.com/q/51934111
tags question: http://stackoverflow.com/q/51817228
tag name: lstm
tags question: http://stackoverflow.com/q/51811797
tags question: http://stackoverflow.com/q/51885171
tags question: http://stackoverflow.com/q/51904845
tags question: http://stackoverflow.com/q/51847674
tags question: http://stackoverflow.com/q/51914632
tags question: http://stackoverflow.com/q/51864864
tags question: http://stackoverflow.com/q/51829810
tags question: http://stackoverflow.com/q/51872304
tags question: http://stackoverflow.com/q/51932767
type: Tag
tags question: http://stackoverflow.com/q/51828298
tags question: http://stackoverflow.com/q/51833821
tags question: http://stackoverflow.com/q/51838583

http://stackoverflow.com/comment/90638618
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51842228
score: 0
has text: @piRSquared df.dot is by far the easiest to understand, thank you. It would be useful here as well, the other thread hard reading.

http://stackoverflow.com/comment/90789564
type: AnswerComment
has text: I think you want `random.choice` rather than `random.sample` (which requires two arguments).
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51918697

http://stackoverflow.com/comment/90677456
comment on: http://stackoverflow.com/q/51825876
score: 0
type: QuestionComment
type: Comment
has text: I have edited the question thanks! Python 3 and atlasstring is the URI with my password and username included.

http://stackoverflow.com/a/51842449
has comment: http://stackoverflow.com/comment/90645453
score: 1
has body: The input shape of a Conv2D layer is (num_channels, width, height). So you should not add another dimension (actually the input shape is (batch_size, num_channels, width, height) but you don't need to set batch_size here; it will be set in fit method). Just pass input_shape=env.shape to Conv2D and it would work fine. Edit: Why do you define an Input layer and pass it to the model? That's not how it works. First, you need to compile the model using compile method, then train it on the training data using fit method and then use predict method to make predictions. I highly recommend to read the official guide to find out how these things work.
downvote count: 0
answers question: http://stackoverflow.com/q/51827602
has comment: http://stackoverflow.com/comment/90648331
has comment: http://stackoverflow.com/comment/90646862
type: Answer
upvote count: 1

http://stackoverflow.com/q/51840615
upvote count: 2
tagged with: differential-equations
tagged with: scipy
type: Question
tagged with: implicit
has body: I wrote a class with the aims to solve the system of differential equations (given in numpy.array form) , in order to solve the non linear system I'm using the scipy.optimize.fsolve using an example find here in one post, the method works fine with single equation while fail if I'm try to using for a system of differential equations ! I wrote a Minimal, Complete, and Verifiable example in this way you can verify and deep understand how the class works! import numpy as np from scipy.optimize import fsolve , newton_krylov import matplotlib.pyplot as plt class ImpRK4 : def __init__(self, fun , t0, tf, dt , y0): self.func = fun self.t0=t0 self.tf=tf self.dt=dt self.u0=y0 self.n = round((tf-t0)/dt) self.time = np.linspace(self.t0, self.tf, self.n+1 ) self.u = np.array([self.u0 for i in range(self.n+1) ]) def f(self,ti,ui): return np.array([functions(ti,ui) for functions in self.func]) def solve(self): for i in range(len(self.time)-1): def equations(variable): k1,k2 = variable f1 = -k1 + self.f(self.time[i]+ (0.5+np.sqrt(3)/6)* self.dt , self.u[i]+0.25*self.dt* k1+ (0.25+ np.sqrt(3)/6)*self.dt*k2) f2 = -k2 + self.f(self.time[i]+ (0.5-np.sqrt(3)/6)* self.dt , self.u[i]+(0.25-np.sqrt(3)/6)*self.dt *k1 + 0.25*self.dt* k2) return np.array([f1,f2]).ravel() #.reshape(2,) k1 , k2 = fsolve(equations,(2,2)) #(self.u[i],self.u[i])) self.u[i+1] = self.u[i] + self.dt/2* (k1 + k2) plt.plot(self.time,self.u) plt.show() def main(): func00 = lambda t,u : -10*(t-1)*u[0] func01 = lambda t,u : u[1] func02 = lambda t,u : (1-u[0]**2)*u[1] - u[0] func0x = np.array([func00]) func0 = np.array([func01,func02]) t0 = 0. tf = 2. u0 = y01 dt = 0.008 y01 = np.array([1.,1.]) diffeq = ImpRK4(func0,t0,tf,dt,y01) #y0 = np.array([np.exp(-5)]) #diffeq.solve() #diffeq = ImpRK4(func0x,t0,tf,dt,y0) ## with single equations works diffeq.solve() if __name__ == '__main__': main() EDIT No I'm sorry but is not what I was looking for ... basically when I have a system of equations I have to get K1 and K2 of the same…
answer count: 1
downvote count: 0
favorite count: 0
type: UnansweredQuestion
has title: How to solve non linear system of array using scipy
tagged with: python
has answer: http://stackoverflow.com/a/51844718
score: 2
tagged with: nonlinear-optimization

http://stackoverflow.com/q/51884531
linked to: http://stackoverflow.com/q/16417546
type: Question
has answer: http://stackoverflow.com/a/51884532
has comment: http://stackoverflow.com/comment/90720711
favorite count: 0
accepted answer: http://stackoverflow.com/a/51884532
upvote count: 2
tagged with: python
answer count: 1
duplicate of: http://stackoverflow.com/q/16417546
has body: I just wanted to create this question in case anyone happens to come across the interesting problem I did when using pytest. I was running my tests by simply typing pytest in the terminal from a folder a few directories above my tests. The tests would run just fine but the compiling took over two seconds. It was getting annoying.
tagged with: pytest
has comment: http://stackoverflow.com/comment/91068652
score: 2
type: AnsweredQuestion
downvote count: 0
has title: Pytest Is Taking Too Long to Compile

http://stackoverflow.com/comment/90711343
type: QuestionComment
has text: One quick way out of this is to define a separate method which the setter actually calls, and then subclasses override that method.
score: 2
comment on: http://stackoverflow.com/q/51879805
type: Comment

http://stackoverflow.com/comment/90695845
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51861684
has text: Thanks ... I am too used to the convenience of notebooks (am a data scientist) ... but when I take code out of there and am turning it into "real code" .. I miss the ability to just work on a cell -- without rerunning everything upstream if I something bugs out.
score: 3

http://stackoverflow.com/a/51885147
has comment: http://stackoverflow.com/comment/90722005
has comment: http://stackoverflow.com/comment/90721949
accepted answer of: http://stackoverflow.com/q/51885086
answers question: http://stackoverflow.com/q/51885086
has comment: http://stackoverflow.com/comment/90721908
type: AcceptedAnswer
score: 0
has comment: http://stackoverflow.com/comment/90722262
type: Answer
has comment: http://stackoverflow.com/comment/90721986
has comment: http://stackoverflow.com/comment/90722143
has comment: http://stackoverflow.com/comment/90722020
has body: For a non-numpy method, you can append your input variable to your list, sort it, and find the index where your input is found in the new list, and return that as well as the previous index: arr = [10,20,30,40,50] i = 25 i_index = sorted(arr+[i]).index(i) &gt;&gt;&gt; [i_index-1, i_index] [1, 2] Edit Based on your comment: if the value is already present in the array then I need just the exact index position of that value else I need the adjacent index values within which the value is falling into You can wrap it in an if statement to check if your input is in your array already: if i in arr: idx = sorted(arr).index(i) else: i_index = sorted(arr+[i]).index(i) idx = [i_index-1, i_index] &gt;&gt;&gt; idx [1, 2]
has comment: http://stackoverflow.com/comment/90722055

http://stackoverflow.com/comment/90653748
has text: In that case, should I modify my regex to allow `{` and `}`?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51848082
type: Comment

http://stackoverflow.com/comment/90704411
has text: Thanks @N.HariHaraSudhan :) That was what i needed !
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51873124

http://stackoverflow.com/a/51890764
answers question: http://stackoverflow.com/q/51885589
type: Answer
accepted answer of: http://stackoverflow.com/q/51885589
has body: There is an issue (and PR) about making it possible to pass keywords to the colorbar construction: https://github.com/geopandas/geopandas/issues/697. But for now, the best work-around is to create the colorbar yourself I think: Create the same figure but with legend=False: cmap = mpl.cm.get_cmap('cool') cmap.set_under('red') ax = troops.plot(column='survivors', cmap=cmap, vmin=10000, legend=False, markersize=50) Now, we get the collection created for the points (from a scatter plot) as the first element of the ax.collections, so we can instruct matplotlib to create a colorbar based on this mapping (and now we can pass additional keywords): scatter = ax.collections[0] plt.colorbar(scatter, ax=ax, extend='min') this gives me
has comment: http://stackoverflow.com/comment/90763226
has comment: http://stackoverflow.com/comment/90753504
score: 4
upvote count: 4
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/90760320
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51904756
has text: Also, why are you trying to build the equivalent of `os.walk` yourself (but more complicated, and handling fewer edge cases) instead of just using `os.walk`?
score: 0

http://stackoverflow.com/q/51941475
has body: The following is my nginx config: location /flower/ { rewrite /flower/(.*) /$1 break; sub_filter '="/' '="/flower/'; sub_filter_last_modified on; sub_filter_once off; proxy_pass http://localhost:5555/; proxy_set_header Host $host; proxy_redirect off; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; } location /flower/static/ { sub_filter '/api' '/flower/api'; sub_filter "'/monitor" "'/flower/monitor"; sub_filter "'/worker" "'/flower/worker"; sub_filter "'/'" "'/flower/'"; sub_filter "'/dashboard'" "'/flower/dashboard'"; sub_filter '"/update-dashboard"' '"/flower/update-dashboard"'; sub_filter_types application/javascript; # by default, sub_filter won't touch JS sub_filter_last_modified on; sub_filter_once off; alias &lt;VIRTUALENV_PATH&gt;/python3.4/site-packages/flower/static/; expires 30d; } Link for the above: https://github.com/mher/flower/issues/414 My flower version is 0.9.2 and nginx version is 1.12.1 I ran flower as follows: $celery flower -A project_name --port=5555 --broker redis://broker_url:port This renders the following: I ran flower as follows: (used --url_prefix=flower) $ celery flower -A project_name --port=5555 --broker redis://broker_url:port --url_prefix=flower This then rendered all the static files as shown: The problem occurs when I click on any of the tabs (say tasks) above as shown: I noticed that the url instead of being say: /flower/dashboard/ is /flower/flower/dashboard and so on. What am I missing here? Anything to be changed in nginx config?
has answer: http://stackoverflow.com/a/51984694
tagged with: python-3.x
type: UnansweredQuestion
has title: running flower behind a reverse proxy
tagged with: python
upvote count: 4
answer count: 4
has answer: http://stackoverflow.com/a/75801006
downvote count: 0
tagged with: flower
has answer: http://stackoverflow.com/a/71543291
favorite count: 0
has answer: http://stackoverflow.com/a/76975724
tagged with: celery
type: Question
tagged with: nginx
score: 4

http://stackoverflow.com/q/51910264
has title: coverting javascript to python
tagged with: javascript
tagged with: python
has comment: http://stackoverflow.com/comment/90770637
has body: I have a yale smart alarm and come across the the below javascript that allows you to access the alarm to get the status and set it. I'm wanting to use this in my home assistant set to which uses python. const fetch = require('node-fetch'); const setCookie = require('set-cookie-parser'); const urls = { login: 'https://www.yalehomesystem.co.uk/homeportal/api/login/check_login', getStatus: 'https://www.yalehomesystem.co.uk/homeportal/api/panel/get_panel_mode', setStatus: 'https://www.yalehomesystem.co.uk/homeportal/api/panel/set_panel_mode?area=1&amp;mode=', }; function getSessionCookie(username, password) { let sessionCookie = null; return fetch(urls.login, { method: 'POST', body: `id=${encodeURIComponent(username)}&amp;password=${password}&amp;rememberme=on&amp;notify_id=&amp;reg_id=Name`, headers: { 'Accept': 'application/json, application/xml, text/plain, text/html, *.*', 'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8' }, }) .then((res) =&gt; { sessionCookie = res.headers._headers['set-cookie']; return res.json(); }).then(json =&gt; { if (json.result === '0') { return Promise.reject('Incorrect account details'); } else { return sessionCookie[0]; } }) } function getStatus(sessionCookie) { return fetch(urls.getStatus, { method: 'POST', headers: { 'Cookie': sessionCookie, }, }).then(res =&gt; res.text()).then(textResponse =&gt; { // When initially writing this code I found if cookie payload // was invalid I got this text response so I added this code to // handle this, shouldn't happen but good to have an error message // for this use case if (textResponse === 'Disallowed Key Characters.') { return Promise.reject('Invalid request'); } else { try { // Hopefully if we got to this point we can parse the json const json = JSON.parse(textResponse); if (json.result === '0') { return Promise.reject('Unable to get status'); } else { return json; } } catch (error) { // If you get this error message I likely have not handled // a error state that I wasnt awar…
answer count: 0
type: UnansweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/90772505
score: 0
has comment: http://stackoverflow.com/comment/90770653
has comment: http://stackoverflow.com/comment/90770689

http://stackoverflow.com/q/51872533
upvote count: 2
answer count: 3
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/51873287
has comment: http://stackoverflow.com/comment/90697825
tagged with: datetime
tagged with: python
has comment: http://stackoverflow.com/comment/90696648
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51873571
accepted answer: http://stackoverflow.com/a/51873571
has body: I have a task of extracting data for only specific time from many log files which are text files of the form: Aug 15 17:32:57 sandbox_pre_process_config:[sandbox] Sandbox pre process Aug 15 17:32:57 sandbox_list_destroy:[sandbox] sandbox_list_destroy, sandbox list destroy done Aug 15 17:32:57 sandbox_list_create:[sandbox] sandbox_list_create, sandbox list create done Aug 15 17:32:57 entering ext_mac_pre_process_config, init_done 1 I am able to extract the date, but I am not able to convert it to a datetime object which I need for further operation. This is what I have tried so far: import subprocess from datetime import datetime import re month_abbr = {"jan": 1, "feb": 2, "mar": 3, "apr": 4, "may": 5, "jun": 6, "jul": 7, "aug": 8, "sep": 9, "oct": 10, "nov": 11, "dec": 12} def parse_date(lines): mon, day, tim = lines.split(None, 3) date_string = "{:02} {:02} ".format(month_abbr[mon.lower()], int(day)) + tim try: return datetime.strptime(date_string, "%m %d %H:%M:%S") except ValueError as e: return datetime.strptime(date_string, "%m %d %H:%M:%S.%f") f = open("temp.txt") for lines in f: line = lines.strip() date_obj = re.search('(.*?\d\d:\d\d:\d\d)', line) if date_obj: date = date_obj.group(1) val = parse_date(date) print val This is the error I am encountering: Aug 15 17:41:06 Aug 15 17:41:07 Aug 15 17:41:07 Traceback (most recent call last): File "main.py", line 23, in &lt;module&gt; val = parse_date(date) File "main.py", line 9, in parse_date mon, day, tim = lines.split(None, 3) # note the change ValueError: too many values to unpack I am not able to see what is wrong ! Please help me out ! P.S - Only standard python libraries can be used !
has answer: http://stackoverflow.com/a/51872642
has title: Python: Not able to parse the data to convert it into a datetime object
type: Question
possible better answer: http://stackoverflow.com/a/51873287

http://stackoverflow.com/q/51804523
tagged with: python
tagged with: nano
has answer: http://stackoverflow.com/a/58285304
type: AnsweredQuestion
score: 1
has title: How to save crontab -e on nano editor by python3 subprocess
upvote count: 1
possible better answer: http://stackoverflow.com/a/58285304
type: Question
accepted answer: http://stackoverflow.com/a/51818448
has comment: http://stackoverflow.com/comment/90590857
answer count: 2
has body: I want to set cronjob on Raspberry Pi 3, initiated by python subprocess, but I am not sure how to code pressing keys ctrl + x ,then y ,and then enter to save it. I am using nano as a text editor, and the below is my code so far. p = Popen(["crontab -e"], stdin=PIPE, stdout=PIPE, shell=True) p.stdin.write("@reboot python test.py")
downvote count: 0
tagged with: raspberry-pi3
favorite count: 0
tagged with: cron
has answer: http://stackoverflow.com/a/51818448

http://stackoverflow.com/comment/90702796
score: 0
type: Comment
has text: @Sociopath27 - Working for it ;)
type: AnswerComment
comment on: http://stackoverflow.com/a/51875724

http://stackoverflow.com/q/51922826
downvote count: 1
type: Question
duplicate of: http://stackoverflow.com/q/7023052
answer count: 1
tagged with: flask
has body: I am running a Flask app. app = Flask(__name__) app.run(host="0.0.0.0", port="5000") @app.route('/list', methods=['GET']) def get_all_list(): star = mongo.db.listdata if __name__ == '__main__': app.run(debug=True) My public IP :- 100.x.x.x When I am accessing 100.x.x.x:500/list it is giving me 404 not found. Server is running, as I can see the request in the flask console. But it is giving 404 to all routes.
linked to: http://stackoverflow.com/q/7023052
has comment: http://stackoverflow.com/comment/90795260
score: 0
has title: Flask app is giving 404 to routes from public ip
tagged with: python
has answer: http://stackoverflow.com/a/51923183
favorite count: 0
type: UnansweredQuestion
upvote count: 1

recaptcha
tag name: recaptcha
tags question: http://stackoverflow.com/q/51864984
tags question: http://stackoverflow.com/q/51810759
type: Tag

telegram
tags question: http://stackoverflow.com/q/51864930
tags question: http://stackoverflow.com/q/51876823
tags question: http://stackoverflow.com/q/51914326
tags question: http://stackoverflow.com/q/51830136
tag name: telegram
tags question: http://stackoverflow.com/q/51915418
type: Tag
tags question: http://stackoverflow.com/q/51919653
tags question: http://stackoverflow.com/q/51919537
tags question: http://stackoverflow.com/q/51905306

http://stackoverflow.com/comment/90754573
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/51901676
has text: add and subtract are function calls rather than function definition @Stack
type: Comment

http://stackoverflow.com/comment/90580069
comment on: http://stackoverflow.com/q/51811839
score: 0
has text: Thank you for the advice. The table that you describe is the ModuleAssignment table. The Delegation table includes the user data, so ModuleAssignment basically is (user, model, is_granted). The problem with just using the ModuleAssignment table, is that you would then need to filter by which objects are in ModuleSubscription. It is almost the same problem in reverse.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/51849141
has body: First, do the pre-work so that we have available the size of the square matrix and the population pop of each row and column. Now, initialize a matrix with pop ones on the diagonal. For n = 6 and pop = 3, you'd have [[1, 1, 1, 0, 0, 0] [0, 1, 1, 1, 0, 0] [0, 0, 1, 1, 1, 0] [0, 0, 0, 1, 1, 1] [1, 0, 0, 0, 1, 1] [1, 1, 0, 0, 0, 1]] Now, apply your friendly neighborhood random shuffle operation to the columns, then the rows (or in the other order). There's your matrix. A shuffle of rows-only or columns-only does not change the population on either axis.
has comment: http://stackoverflow.com/comment/90651984
answers question: http://stackoverflow.com/q/51848913
upvote count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/90651627
type: Answer
has comment: http://stackoverflow.com/comment/90651840
score: 1

http://stackoverflow.com/comment/90850370
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51950049
type: QuestionComment
has text: Ummm, seems like you are using the right way, I am not sure whether we have alternative solution for this question .

http://stackoverflow.com/q/51943574
type: AnsweredQuestion
type: Question
has title: pygame: position not updated with keyboard input
has answer: http://stackoverflow.com/a/51943819
score: 0
answer count: 1
tagged with: python
has body: I have been working on a Pong game using pygame. I am trying to get the paddle to move up by pressing 'w' key, but the position for the paddle LeftPaddle().pos seems to not be updated when pressing the key. I suspect LeftPaddle().pos being defined under __init__(self) make it call to the same value every time LeftPaddle().blit(self.background) is being used and therefore the position is not updated? Or is there some other logic problems causing the position to not be updated? Thanks. import pygame class DisplayWindow(object): def __init__(self, width=800, height=600,): """initialize pygame, window, background, setup boundaries """ pygame.init() pygame.display.set_caption('Pong with Pyton') self.width = width self.height = height self.screen = pygame.display.set_mode((self.width, self.height)) self.background = pygame.Surface(self.screen.get_size()).convert() self.bound_width = self.width*0.9 self.bound_thic = self.height*0.01 self.leftbound = self.width*0.05 self.rightbound = self.leftbound + self.bound_width self.upperbound = self.height * 0.05 self.lowerbound = self.height * 0.95 self.bound_height = self.lowerbound - self.upperbound def boundaries(self): """paint boundaries and middle line """ pygame.draw.rect(self.background, (255,255,255), (self.leftbound, self.upperbound - self.bound_thic, self.bound_width, self.bound_thic)) pygame.draw.rect(self.background, (255,255,255), (self.leftbound, self.lowerbound, self.bound_width, self.bound_thic)) def middleline(self): """paint middle line """ mid_thic = self.width*0.01 mid_height = (self.bound_height) / 81 mid_left = (self.width - mid_thic) / 2 mid_top = self.upperbound for i in range(0, 81): if i % 2 == 1: pygame.draw.rect(self.background, (255, 255, 255), (mid_left, mid_top + i * mid_height, mid_thic, mid_height)) def run(self): """main loop """ self.middleline() self.boundaries() LeftPaddle().blit(self.background) running = True while running: self.screen.blit(self.background, (0,0)) for event in pygame.event.get…
tagged with: pygame
accepted answer: http://stackoverflow.com/a/51943819

http://stackoverflow.com/comment/124292432
has text: A backend should run the default password hasher once and also check for inactive users. This backend should not be used in production.
comment on: http://stackoverflow.com/a/51885328
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/51821841
type: UnansweredQuestion
has body: I did some web scraping using the code below. When i try to convert list to string it includes the escape sequences and ascii code. When i tried print it is printing properly, but I am trying to make a csv using the text hence want the escape sequence to be removed import pandas as pd from bs4 import BeautifulSoup import requests page_link = "https://www.undercurrentnews.com/2018/08/07/ecuador-tax-reform-to-spur-more-shrimp-investment/" page_response = requests.get(page_link, timeout=5) page_content = BeautifulSoup(page_response.content, "lxml") textContent = [] for i in range(len(page_content.find_all("p"))): paragraphs = page_content.find_all("p")[i].text textContent.append(paragraphs) raw_text = ' '.join(textContent) 'Don\'t have an account? Sign up Enter the email address associated with your account.\nWe\'ll send you instructions to reset your password when i tried printing, it shows: Don't have an account? Sign up Enter the email address associated with your account. We'll send you instructions to reset your password. I want to remove the \n,\xa0 etc I tried some suggested decoding decoded_string = bytes(raw_text, "utf-8").decode("unicode_escape") still the same result. Since this is done for huge text I am unable to use the solutions. The text is fine when it is in list but when i convert it to string using join then these escape sequences are adding. Is there a way to add list itself to pandas ?
linked to: http://stackoverflow.com/q/8115261
tagged with: escaping
type: Question
tagged with: string
has comment: http://stackoverflow.com/comment/90597539
has comment: http://stackoverflow.com/comment/90598139
score: 0
tagged with: pandas
tagged with: python
has comment: http://stackoverflow.com/comment/90599243
has title: How to remove escape characters from a string or add a list of text into one pandas column?
answer count: 0

http://stackoverflow.com/comment/90791517
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/51920879
has text: Did you try to install it? `pip install scipy`
type: Comment

http://stackoverflow.com/a/51956426
type: Answer
accepted answer of: http://stackoverflow.com/q/51955647
upvote count: 1
answers question: http://stackoverflow.com/q/51955647
has body: The exception is coming from boto/plugin.py. For some reason, it's getting None instead of a string for some directory name, and then trying to glob all the files under None, which fails because you can't os.path.join a glob pattern to None. So, why is it doing that? Most likely, there's some garbage in your boto plugins directory. Or, if not there, in your config. (It would be nice if boto had better error handling for this case, but it probably doesn't come up all that often…) There's a good chance just uninstalling and reinstalling your boto plugins will fix it. For anyone reading this in the future: If your exception ends with this (except possibly different line numbers and version numbers): File "/usr/lib/python3/dist-packages/boto/__init__.py", line 1216, in &lt;module&gt; boto.plugin.load_plugins(config) File "/usr/lib/python3/dist-packages/boto/plugin.py", line 92, in load_plugins for file in glob.glob(os.path.join(directory, '*.py')): File "/usr/lib/python3.5/posixpath.py", line 89, in join genericpath._check_arg_types('join', a, *p) File "/usr/lib/python3.5/genericpath.py", line 143, in _check_arg_types (funcname, s.__class__.__name__)) from None TypeError: join() argument must be str or bytes, not 'NoneType' … it's the same bug. But, if reinstalling your boto plugins doesn't help, you'll need to create a new question. (And include the results of calling find or tree on your plugins directory, and the contents of your config file, and all of the relevant version numbers.)
score: 1
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/51807875
has comment: http://stackoverflow.com/comment/90571811
accepted answer: http://stackoverflow.com/a/51811079
tagged with: button
has comment: http://stackoverflow.com/comment/90575030
has title: Using a button to open and close a matplotlib widget
has comment: http://stackoverflow.com/comment/90576118
has body: The aim of what I've written so far is to have a "Temperature" button in my GUI that when pressed opens up a matplotlib plot that I made separately (mplwidget.py). However, when I run the code, both the app and the widget open up simultaneously, and the Temperature button appears to have no function (even if I close the widget, pressing the button doesn't open it again). import sys from PyQt5.QtCore import QCoreApplication from PyQt5.QtGui import QIcon from PyQt5.QtWidgets import QApplication, QWidget, QMainWindow, QPushButton, QAction, QMessageBox from PyQt5.uic.properties import QtGui from mplwidget import animate #import animation widget class window(QMainWindow): def __init__(self): super(window, self).__init__() self.setGeometry(50, 50, 500, 300) self.setWindowTitle('Temperature Control') self.setWindowIcon(QIcon('adn.png')) extractAction = QAction('&amp;Quit', self) extractAction.setShortcut('Ctrl+Q') extractAction.setStatusTip('leave the app') extractAction.triggered.connect(self.close_application) self.statusBar() mainMenu = self.menuBar() fileMenu = mainMenu.addMenu('&amp;File') fileMenu.addAction(extractAction) self.home() def home(self): btn = QPushButton('quit', self) btn.clicked.connect(self.close_application) btn.resize(btn.sizeHint()) btn.move(0, 100) button = QPushButton('Temperature',self) button.clicked.connect(self.opengraph) button.move(50,200) self.show() def opengraph(self): animate() def close_application(self): choice = QMessageBox.question(self, 'Message', "Are you sure to quit?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if choice == QMessageBox.Yes: sys.exit() else: pass if __name__ == "__main__": def run(): app = QApplication(sys.argv) Gui = window() sys.exit(app.exec_()) run() mplwidget is below def GraphWidget(): fig = plt.figure() ax1 = fig.add_subplot(1,1,1) Time = [] Temp = [] def animate(i): x = datetime.datetime.now() y = numpy.random.randint(48,52) Time.append(x) Temp.append(int(y)) # print (Temp) ax1.plot(Time,Temp) ani =…
possible better answer: http://stackoverflow.com/a/51811075
has answer: http://stackoverflow.com/a/51811075
has comment: http://stackoverflow.com/comment/90575428
has comment: http://stackoverflow.com/comment/90576732
linked to: http://stackoverflow.com/q/38282978
has comment: http://stackoverflow.com/comment/90572225
has comment: http://stackoverflow.com/comment/90576431
tagged with: python
has answer: http://stackoverflow.com/a/51811079
has comment: http://stackoverflow.com/comment/90572531
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90571530
tagged with: matplotlib
tagged with: pyqt5
has comment: http://stackoverflow.com/comment/90572174
has comment: http://stackoverflow.com/comment/90571581
type: Question
score: 0
answer count: 2

http://stackoverflow.com/comment/90819589
score: 0
comment on: http://stackoverflow.com/q/51934713
type: Comment
type: QuestionComment
has text: Definitely agree w/ @coldspeed here. If you are simply checking for specific values in a column, there is no need to convert them to binary. You are just adding unnecessary overhead. Try `df[df['ID'].isin(['Y','Z'])]`

http://stackoverflow.com/comment/90710670
score: 0
type: AnswerComment
has text: I couldn't bring myself to make my own answer. `df2 + f" - {stuff}"`
type: Comment
comment on: http://stackoverflow.com/a/51879260

http://stackoverflow.com/q/51838355
type: Question
has answer: http://stackoverflow.com/a/51841071
has body: I have a DataFrame on which I would like to somehow add new columns based on the value of a specific column, whose result depends on data contained in another DataFrame. More specifically, I have df_original = Crncy Spread Duration 0 EUR 100 1.2 1 nan nan nan 2 100 3.46 3 CHF 200 2.5 4 USD 50 5.0 ... df_interpolation = CRNCY TENOR Adj_EUR Adj_USD 0 EUR 1 10 20 1 EUR 2 20 30 2 EUR 5 30 40 3 EUR 7 40 50 ... 10 CHF 1 50 10 11 CHF 2 60 20 12 CHF 5 70 30 ... and would now like to add the columns Adj_EUR and Adj_USD to df_original for each row, based on the value of Crncy and Duration using standard linear interpolation. So, we want to use TENOR and Adj_USD/Adj_EUR from df_interpolation and Duration from df_original, for each available Crncy, to form the interpolation. E.g. Pseudo-code using optimize-package from scipy: from scipy import optimize """ Do this for both 'Adj_EUR' and 'Adj_USD' """ # For 'Adj_EUR' for curr, df in df_original.groupby('Crncy'): x_data = df_interpolation[df_interpolation['CRNCY']==curr].as_matrix(['TENOR']) y_data = df_interpolation[df_interpolation['CRNCY']==curr].as_matrix(['Adj_EUR']) """ Linear fit """ z_linear = optimize.curve_fit(lambda t,a,b: a + b * t, x_data.ravel(), y_data.ravel())[0] """ Somehow add the values back to df_original in a new column """ df['Adj_EUR'] = z_linear[0] + z_linear[1] * df['Duration'] Yielding Crncy Spread Duration Adj_EUR Adj_USD 0 EUR 100 1.2 12 22 1 nan nan nan 0.0 0.0 ... Any clue on how to do this? Much appreciable
score: 0
answer count: 2
tagged with: pandas
tagged with: python
has answer: http://stackoverflow.com/a/51839158
has comment: http://stackoverflow.com/comment/90630255
has comment: http://stackoverflow.com/comment/90630853
has title: Applying interpolation on DataFrame based on another DataFrame
type: UnansweredQuestion

http://stackoverflow.com/comment/90727058
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51887864
has text: Also, is you code supposed to work for "robotic", for example, or **only** the word `robot`

http://stackoverflow.com/q/51896429
has comment: http://stackoverflow.com/comment/90752993
has title: How to format django DateField in model from YYYY-MM-DD to MM/DD/YYYY
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90776512
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/90765649
tagged with: mysql
has comment: http://stackoverflow.com/comment/90766508
type: Question
has comment: http://stackoverflow.com/comment/90744617
has body: I have an excel file with over 40 thousand lines to import into MYSQL using a python script and the date format in the excel file is MM/DD/YYYY while the corresponding MYSQL field is expecting YYYY-MM-DD. Thefore; it gives the following error on the terminal: "Incorrect date value: '12/02/1960' for column 'dob' at row 1" Is there any django date field option that looks like the following: date = models.DateField(format=MM-DD-YYYY) I used django to create the MYSQL Table with the migration command. I CANNOT EDIT THE DATES IN THE EXCEL FILE MANUALLY BECAUSE THERE ARE OVER 40,000 LINES. If is not possible in django, how can I modify it in MYSQL instead? Or can someone guide me to how to write a python script to sort the dates in the excel date colomn? Any of these or any other methods are welcomed. Thanks
has comment: http://stackoverflow.com/comment/90743995
score: 0
has answer: http://stackoverflow.com/a/51897283
answer count: 1
has comment: http://stackoverflow.com/comment/90765714

http://stackoverflow.com/a/51922180
answers question: http://stackoverflow.com/q/51921244
score: 0
type: Answer
has body: You didn't really specify from which dataframe you want to show columns. Below solution will show you where you have differences at the same row level between both dataframes. Assuming as in your dfs, that there are no nulls earlier. val df11 = df1.withColumn("id", row_number().over(Window.orderBy("col1"))) val df22 = df2.withColumn("id", row_number().over(Window.orderBy("col1"))) val df_join = df11.join(df22.selectExpr("col1 as col11", "col2 as col22", "col3 as col33", "id"), Seq("id"), "inner") df_join.select(when($"col1" === $"col11", null).otherwise(col("col1")), when($"col2" === $"col22", null).otherwise(col("col2")), when($"col3" === $"col33", null).otherwise(col("col3"))).show

http://stackoverflow.com/comment/90808682
type: Comment
type: QuestionComment
score: 0
has text: are you loading this text from a file ???
comment on: http://stackoverflow.com/q/51929474

http://stackoverflow.com/a/51827217
downvote count: 0
score: 1
has body: I think @user3483203's groupby approach is the most straightforward. But one additional option is to use pivot_table(): df.reset_index().pivot_table(columns=["index"]) # add .T to transpose dates to rows index 2010Q1 2010Q2 2010Q3 2010Q4 a 0.5 2.0 2.5 4.0 b 4.0 4.0 7.5 9.0
upvote count: 1
answers question: http://stackoverflow.com/q/51827058
type: Answer

events
tags question: http://stackoverflow.com/q/51885246
tags question: http://stackoverflow.com/q/51939096
tag name: events
tags question: http://stackoverflow.com/q/51887888
type: Tag

http://stackoverflow.com/q/51880563
upvote count: 3
has answer: http://stackoverflow.com/a/51880762
type: Question
has comment: http://stackoverflow.com/comment/90714405
score: 3
has title: creating a matrix of flags for given dates in a pandas dataframe
has body: I want to create zeros in my dataframe for particular date ranges for selective columns. I am stuck at finding any efficient solution. My code creates a matrix of 1s. lets say dates=1/10/2016 - 16/8/2018 (i.e.ytd). matrix1cols=A,B,C,D: df = pd.DataFrame(np.ones(shape=(len(dates), len(matrix1cols))), index=dates) df.columns = ['A','B','C', 'D'] Now, I wish to make the Q1 (jan-mar) dates for column A = 0, Q2 dates for B = 0, Q3 dates for C = 0 and Q4 dates for col D = 0, for all years, in df. (I am essentially creating flags for myself) Ps- my date has many years, and I have simplified the dataset for purpose of ease.
answer count: 2
tagged with: pandas
has comment: http://stackoverflow.com/comment/90714624
downvote count: 0
has comment: http://stackoverflow.com/comment/90714534
possible better answer: http://stackoverflow.com/a/51880666
accepted answer: http://stackoverflow.com/a/51880762
favorite count: 0
has answer: http://stackoverflow.com/a/51880666
tagged with: python
has comment: http://stackoverflow.com/comment/90714172
has comment: http://stackoverflow.com/comment/90715224
has comment: http://stackoverflow.com/comment/90713850
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90714331

http://stackoverflow.com/q/51953233
type: Question
has body: My csv file has nothing but commas after every letter. It writes the data to a newline. What am I doing wrong with the data? I am trying to write each address to a new line in csv after it is put into a list. I have tried all kinds of different methods to write the data to a csv file but nothing has worked. I can't figure out what to do to make the data write the name and not so many commas. import requests from bs4 import BeautifulSoup import csv search_terms = "Bars" location = "New Orleans, LA" all_data = [] if ' ' in search_terms: search_terms = search_terms.replace(' ', '+') print(search_terms) if ', ' in location: location = location.replace(', ', '+') print(location) count = 1 while True: page_number = str(count) url = "https://www.yellowpages.com/search? search_terms="+search_terms+"&amp;geo_location_terms="+location+"&amp;page="+page_number print(url) page = requests.get(url) soup = BeautifulSoup(page.text, 'html.parser') info = soup.findAll("div", {"class": "info"}) if soup.findAll("div", {"class": "info"}): count = count+1 for each in info: try: business_name = each.find(itemprop="name").get_text() except: business_name = "No Business Name" try: street = each.find(itemprop="streetAddress").get_text() except: street = "No Street Address" try: city = each.find(itemprop="addressLocality").get_text() except: city = "No City," try: state = each.find(itemprop="addressRegion").get_text() except: state = "No State" try: zip = each.find(itemprop="postalCode").get_text() except: zip = "No Zip Code" try: telephone = each.find(itemprop="telephone").get_text() except: telephone = "No Telephone" business_data = business_name+","+street+","+city+state+","+zip+","+telephone business_data = business_data.replace(u'\xa0', u'') all_data.append(business_data) else: break with open(search_terms+'.csv', 'w+') as wf: csv_writer = csv.writer(wf) csv_writer.writerow(["Business Name","Street Address", "City", "State", "Zip", "Telephone"]) for line in all_data: csv_writer.writerow(…
score: 0
answer count: 2
accepted answer: http://stackoverflow.com/a/51953417
tagged with: writer
favorite count: 0
possible better answer: http://stackoverflow.com/a/51953388
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/51953388
tagged with: python
has title: Python csv writer outputs commas after each letter
has comment: http://stackoverflow.com/comment/90857025
upvote count: 1
has comment: http://stackoverflow.com/comment/90856889
downvote count: 1
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51953417

http://stackoverflow.com/q/51939804
possible better answer: http://stackoverflow.com/a/53384128
tagged with: base64
has title: Gmail API encoding - how to get rid of 3D and &amp
answer count: 3
downvote count: 0
has body: I am trying to extract the body of GMAIL emails via GMAIL API, using Python well. I am able to extract the messages using the commands below. However, there seems to be an issue with the encoding of the email text (Original email has html in it) - for some reason, every time before each quote 3D appears. Also, within the a href="my_url", I have random equal signs = appearing, and at the end of the link, there is &amp;amp character which is not in the original HTML of the email. Any idea how to fix this? Code I use to extract the email: from __future__ import print_function from googleapiclient.discovery import build from httplib2 import Http from oauth2client import file, client, tools from apiclient import errors import base64 msgs = service.users().messages().list(userId='me', q="no-reply@hello.com",maxResults=1).execute() for msg in msgs['messages']:message = service.users().messages().get(userId='me', id=m_id, format='raw').execute() "raw": Returns the full email message data with body content in the raw field as a base64url encoded string; the payload field is not used." print(base64.urlsafe_b64decode(message['raw'].encode('ASCII'))) td style=3D"padding:20px; color:#45555f; font-family:Tahoma,He= lvetica; font-size:12px; line-height:18px; " JPk79hd = JFQZEhc6%2BpAiQKF8M85SFbILbNd6IG8%2FEAWwe3VTr2jPzba4BHf%2FEnjMxq66fr228I7OS =
favorite count: 0
tagged with: gmail-api
has answer: http://stackoverflow.com/a/53384128
has answer: http://stackoverflow.com/a/65008467
tagged with: python
has comment: http://stackoverflow.com/comment/90856785
has answer: http://stackoverflow.com/a/51971360
accepted answer: http://stackoverflow.com/a/51971360
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/90832171
linked to: http://stackoverflow.com/q/6916805
type: Question
type: AnsweredQuestion

http://stackoverflow.com/comment/90599268
type: QuestionComment
comment on: http://stackoverflow.com/q/51822615
score: 0
has text: `sqrt(3)/2` isn't an exact value, it is an expression that will be evaluated to some value (in this case, the decimal approximation). It *looks* like you want a computer algebra system.
type: Comment

http://stackoverflow.com/a/51826424
answers question: http://stackoverflow.com/q/51826127
score: 0
has comment: http://stackoverflow.com/comment/90607635
type: AcceptedAnswer
has body: Replace a tag with button. Wrap a form tag over the button and add type=submit to it. In the form, you can add the input field. Template: Download file View: class CgfFileDownload(View): def get(self, request, pk): # query parameters are stored in `request.GET` dictionary fieldValue = request.GET.get('fieldName') content = MODEL_NAME.objects.get(pk=pk).name response = HttpResponse(content, content_type='text/plain') response['Content-Disposition'] = 'attachment; filename=%s' % 'testing.txt' return response
type: Answer
accepted answer of: http://stackoverflow.com/q/51826127

http://stackoverflow.com/q/51886457
has title: Why doesn't Python perform a function each time it goes through a loop?
accepted answer: http://stackoverflow.com/a/51886564
downvote count: 1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90724384
has comment: http://stackoverflow.com/comment/90724376
tagged with: loops
type: Question
has comment: http://stackoverflow.com/comment/90724398
has body: I've written this script which creates grey squares which move left and stop at a point, and creates red squares which go right indefinitely. Currently it only makes 1 of each square. To my mind (I'm a begginer) the part of the script below is in a loop so each time the computer goes through the loop it should create a new grey square until there are a total of 15 squares. Why doesn't it? (btw germans are grey squares) if germancount&lt;15: spawn_soldier(german_startx, german_starty, german_width, german_height, grey) My full code is below: import pygame import time import random pygame.init() display_width = 1000 display_height= 800 black = (0,0,0) white = (255,255,255) red = (255,0,0) green = (0,255,0) blue = (0,0,255) grey=(169,169,169) gameDisplay= pygame.display.set_mode((800,600)) pygame.display.set_caption('stalingrad') clock = pygame.time.Clock() def spawn_soldier(thingx,thingy, thingw, thingh, colour): pygame.draw.rect(gameDisplay, colour,[thingx, thingy, thingw, thingh]) def game_loop(): russian_width= 20 russian_height= 20 russian_speed = 2 russian_startx=-30 russian_starty=random.randrange(0, display_height) german_width=20 german_height=20 german_speed=-1 german_startx=780 german_starty=random.randrange(0, display_height) germancount=0 russiancount=0 game_exit=False while not game_exit: gameDisplay.fill(white) if germancount&lt;15: spawn_soldier(german_startx, german_starty, german_width, german_height, grey) if german_startx &gt; 700: german_startx += german_speed if russiancount&lt;100: spawn_soldier(russian_startx, russian_starty, russian_width, russian_height, red) russian_startx += russian_speed pygame.display.update() clock.tick(60) game_loop() pygame.quit() quit() edit, i suppose ive worked out a way of defining my problem a bit better. i need like 15 of these "spawn_soldier" functions just for the Germans. spawn_soldier_1(german_startx, german_starty, german_width, spawn_soldier_2(german_startx, german_starty, german_width, spawn_soldier_3(germa…
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/51886564
has comment: http://stackoverflow.com/comment/90724542
tagged with: python
tagged with: pygame
score: 2
upvote count: 3
has comment: http://stackoverflow.com/comment/90725098

http://stackoverflow.com/q/51835532
score: 1
type: Question
has comment: http://stackoverflow.com/comment/90730039
has body: I need to instrument a Python script using Intel Pin for ChampSim simulator. The problem is, whenever I run the tool, the script does not seem to run as nothing is printed. Moreover, no matter how long/complex the script is, the trace always ends up with a size of 62M (this is also the case when I simply instrument the interpreter without any script). I tried running the solution from this post, but it didn't work either. For reference, I am running the following command: ../../../pin -t obj-intel64/champsim_tracer.so -- ./python_script.py Is it even possible to instrument a Python script? If yes, please detail the steps. Thanks!
tagged with: instrumentation
upvote count: 1
tagged with: intel-pin
has title: Use Intel Pin to instrument Python scripts
favorite count: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/30743298
tagged with: python
has comment: http://stackoverflow.com/comment/90663827
tagged with: c++
answer count: 0
downvote count: 0

http://stackoverflow.com/comment/90712081
type: Comment
score: 1
comment on: http://stackoverflow.com/a/51880043
type: AnswerComment
has text: This is exactly what I was looking for, thanks! Indeed I needed empty lists in case there were only `NaN`s associated with the `A` column. :) Thanks so much!

http://stackoverflow.com/q/51910889
has body: so here's my problem. I have a search bar and when i click the search button i send an ajax request to retrieve all the items that contains the word in the search input. The problem is that when i append the retrieved items to the Table,two of my fields are represented as an id, not with a name (because they have ForeignKeys) Models.py class Inventory(models.Model): code = models.IntegerField(primary_key=True) category = models.ForeignKey(Categoria, on_delete=models.CASCADE) description = models.TextField() value = models.DecimalField(max_digits=8, decimal_places=2) user = models.ForeignKey( User, on_delete=models.SET_NULL, null=True, limit_choices_to={'is_superuser': True},) brand = models.CharField(max_length=20) model = models.CharField(max_length=25) serial = models.CharField(max_length=30) status = models.BooleanField(default=True) image = CloudinaryFieldFix('image', null=True, blank = True) def __str__(self): return '{0} {1}'.format(self.code, self.description) Inventory.js $(document).ready(function(){ $("#btnSearch").click(function(){ description = $("#search").val(); $.ajax({ url: '/inventary/list/searched_equipment', data: { 'description' : description }, dataType : 'json', success: function(data){ var equipment = data; if (equipment.length==0){ $("#tblEquip").empty(); alert("No items"); } else{ for (var i=0;i&lt;equipo.length;i++){ $("#tblEquip").empty(); alert(equipo[i]["fields"]["category"]); } } } }); }); Views.py def searched_equipment(request): description = request.GET.get('description') items = Inventory.objects.filter(description__icontains=description) html = seralizers.serialize('json',items) return HttpResponser(html) Also, i tried to use the Wadofstuff Full Serializer to get the full data of that other model object, not only the id, but i cant make it work. print(serializers.serialize('json',Inventory.objects.all(),indent=4,relations = ('category','user',))) File "C:\Python36\lib\json\__init__.py", line 176, in dump default=default, sort_keys=…
tagged with: django
tagged with: python
answer count: 0
tagged with: http://stackoverflow.com/tag/json
has title: Django and Ajax, get the Foreign Key values oreturned by Json serializer
type: Question
score: 0
has comment: http://stackoverflow.com/comment/90772426
has comment: http://stackoverflow.com/comment/90772046
tagged with: ajax
tagged with: serialization
type: UnansweredQuestion

http://stackoverflow.com/q/51923889
tagged with: react-native
has comment: http://stackoverflow.com/comment/90809530
has title: React native iOS authorization header with Django rest framework
type: Question
tagged with: ios
tagged with: django-rest-framework
has body: has anyone encountered in DRF that the request from a react native app IOS Simulator is always been denied because of the Authorization header, Basically, it doesn't accept my authorization header even if its correct and it is working fine on an android simulator and Insomnia. I'm using a specific RetrieveAPIView for that, and the weird thing is I also have a ListAPIView that needs Authorization but that one is working fine on request from IOS simulator, Hoping that someone could help me here. The solution I've made so far is: Enabling all server on my accepted Django CORS setting. Editing Info.plist file that allows the app to run or request even in local domains. Pointing to my domain which has a valid SSL certificate. But none of the above is working. thank you.
score: 0
has comment: http://stackoverflow.com/comment/97146504
answer count: 0
type: UnansweredQuestion
tagged with: django
tagged with: python

http://stackoverflow.com/a/51825377
has comment: http://stackoverflow.com/comment/90605513
type: Answer
has body: Your problem right now seems to be that to think way too complicated. It's really as simple as saying *row called 'v' is the sum of row called 'b' and row called 'd'. Or in pandas syntax: df.loc['v'] = df.loc['b'] + df.loc['d'] If you really need to use the sum() function, you have to understand how it works on the data frame. In your case you'd first have to select the respective rows (which will return a view of these rows as pandas.DataFrame) and then use the sum() function of this view like this: df.loc['v'] = df.loc'b','d'.sum() Works for me using pandas 0.23.3 and python 3.6.
upvote count: 3
score: 3
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90605220
accepted answer of: http://stackoverflow.com/q/51825145
answers question: http://stackoverflow.com/q/51825145

http://stackoverflow.com/comment/90657872
comment on: http://stackoverflow.com/q/51852658
score: 0
type: Comment
type: QuestionComment
has text: No, the whole *point* of classes is to avoid global state. Use *instance variables*.

http://stackoverflow.com/a/51897015
type: Answer
has comment: http://stackoverflow.com/comment/139907707
has comment: http://stackoverflow.com/comment/90748328
answers question: http://stackoverflow.com/q/51896862
has body: I've found out that the best way to implement Singleton is by using meta classes: class Singleton (type): _instances = {} def __call__(cls, *args, **kwargs): if cls not in cls._instances: cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs) return cls._instances[cls] # Python 2 class MyClass(): __metaclass__= Singleton # Python 3 class MyClass(metaclass=Singleton): pass
has comment: http://stackoverflow.com/comment/90745210
has comment: http://stackoverflow.com/comment/90745090
upvote count: 21
has comment: http://stackoverflow.com/comment/90745253
type: AcceptedAnswer
downvote count: 0
score: 21
accepted answer of: http://stackoverflow.com/q/51896862

http://stackoverflow.com/comment/90573671
type: Comment
type: QuestionComment
has text: @palivek Yes, they are in the same directory.
score: 0
comment on: http://stackoverflow.com/q/51808970

http://stackoverflow.com/a/51872744
upvote count: 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51872648
has comment: http://stackoverflow.com/comment/90697214
answers question: http://stackoverflow.com/q/51872648
has body: You are quite close. You should aggregate your dictionaries in the list while creating a new dictionary on each iteration appending it to the resulting list: length = 2 menu_list = [] view_class_keys = length * ["viewclass"] view_class_values = length * ["MDMenuItem"] text_keys = length * ["text"] text_values = ["option1", "option2"] for iterator in range(0, length): menu = {} menu[view_class_keys[iterator]] = view_class_values[iterator] menu[text_keys[iterator]] = text_values[iterator] menu_list.append(menu) print(menu_list) Edit: Assuming the only variable part in your code is text_values list, your code can be simplified to menu = [{"viewclass": "MDMenuItem", "text" : option} for option in text_values]
type: Answer
score: 2
downvote count: 0

python-click
tags question: http://stackoverflow.com/q/51822129
tag name: python-click
tags question: http://stackoverflow.com/q/51847639
type: Tag
tags question: http://stackoverflow.com/q/51846634
tags question: http://stackoverflow.com/q/51858816

http://stackoverflow.com/comment/90677042
score: 4
comment on: http://stackoverflow.com/q/51862332
type: Comment
type: QuestionComment
has text: What is your question? Also format your code properly

http://stackoverflow.com/comment/90976482
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51965157
type: Comment
has text: I am using Python 2 and Solution has been updated, Thanks a lot for pointer to the ctypes pointers :)

http://stackoverflow.com/q/51871372
has comment: http://stackoverflow.com/comment/90695540
has comment: http://stackoverflow.com/comment/90696638
favorite count: 0
tagged with: python-3.x
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/90695254
possible better answer: http://stackoverflow.com/a/51871808
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51871808
downvote count: 0
has answer: http://stackoverflow.com/a/51871959
has body: This is my project directory ├── feed │ ├── admin.py │ ├── apps.py │ ├── __init__.py │ ├── __init__.pyc │ ├── migrations │ │ ├── 0001_initial.py │ │ ├── 0002_auto_20180722_1431.py │ │ │ ├── models.py │ ├── __pycache__ │ │ │ ├── templates │ │ └── feed │ │ ├── base.html │ │ ├── footer.html │ │ ├── header.html │ │ ├── hindustantimes.html │ │ ├── index.html │ │ ├── ndtv.html │ │ ├── News_Home.html │ │ ├── republic.html │ │ └── tredns.html │ ├── tests.py │ ├── twitter │ │ ├── __init__.py │ │ ├── __pycache__ │ │ │ └── twitter_credentials.cpython-36.pyc │ │ ├── trends.py │ │ ├── tweets.py │ │ └── twitter_credentials.py │ ├── urls.py │ └── views.py ├── __init__.py ├── manage.py ├── os ├── pironews │ ├── __init__.py │ | │ ├── __pycache__ │ │ ├── __init__.cpython-36.pyc │ │ ├── settings.cpython-36.pyc │ │ ├── urls.cpython-36.pyc │ │ └── wsgi.cpython-36.pyc │ ├── settings.py │ | │ ├── urls.py │ └── wsgi.py └── __pycache__ I want to import the trends.py file in my views: I am doing the following in the views file from pironews.feed.twitter.trends import main def twitter_trend(request): output = main() print(output) return HttpResponse(output, content_type='text/plain') This is my trends.py file from __future__ import print_function import sys # used for the storage class import requests import pycurl # used for curling import base64 # used for encoding string import urllib.parse # used for enconding from io import StringIO# used for curl buffer grabbing import io import re import json # used for decoding json token import time # used for stuff to do with the rate limiting from time import sleep # used for rate limiting from time import gmtime, strftime # used for gathering time import twitter_credentials OAUTH2_TOKEN = 'https://api.twitter.com/oauth2/token' class Storage: def __init__(self): self.contents = '' self.line = 0 def store(self, buf): self.line = self.line + 1 self.contents = "%s%i: %s" % (self.contents, self.line, buf) def __str__(self): return self.contents def get…
accepted answer: http://stackoverflow.com/a/51871959
score: 1
has title: Import Error in django view?
has comment: http://stackoverflow.com/comment/90694401
type: Question
has comment: http://stackoverflow.com/comment/90694498
answer count: 2
has comment: http://stackoverflow.com/comment/90695694
has comment: http://stackoverflow.com/comment/90694954
has comment: http://stackoverflow.com/comment/90696031
has comment: http://stackoverflow.com/comment/90695046
upvote count: 1
has comment: http://stackoverflow.com/comment/90695160
has comment: http://stackoverflow.com/comment/90695102

http://stackoverflow.com/comment/90786612
type: Comment
type: QuestionComment
score: 3
comment on: http://stackoverflow.com/q/51918395
has text: There are *many* ways to do [*inter-process communication*](https://en.wikipedia.org/wiki/Inter-process_communication). Some which can only be done locally, and other which are better for remotely connected systems.

http://stackoverflow.com/comment/90637318
comment on: http://stackoverflow.com/q/51841936
has text: You can check your database connection by trying to execute a query without any database specific things like: `cursor.execute("SELECT VERSION()")`.
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/comment/90815046
comment on: http://stackoverflow.com/q/51931664
has text: Do the calculations need to be passed exactly as shown, i.e. the literal strings `'values1**2'` and `'np.exp(values2)'`, or are they supposed to be replaced with the results of first evaluating those Python expressions? I suspect it is the former (strings) because `values1` and `values2` are undefined variables.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90593006
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51819350
has text: I did not create any file. I'm just running the commands on terminal line by line.

http://stackoverflow.com/a/51926039
upvote count: 2
answers question: http://stackoverflow.com/q/51920907
accepted answer of: http://stackoverflow.com/q/51920907
has body: Assuming the input image named as "circles.jpg". First of all, import required libraries and load image in gray format. Use Numpy.where() function to purify the foreground and background of the image. Then find all the contours on this image: import cv2 import numpy as np image_gray = cv2.imread("circles.jpg", 0) image_gray = np.where(image_gray &gt; 30, 255, image_gray) image_gray = np.where(image_gray &lt;= 30, 0, image_gray) image_gray = cv2.adaptiveThreshold(image_gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 115, 1) _, contours, _ = cv2.findContours(image_gray, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) Secondly, create an empty image with same width and height. Then, draw the contours on the newly created image, with a filtering condition - the contour must have a circle-like shape: image_copy = np.zeros_like(image_gray) # create a new emtpy image for cnt in contours: peri = cv2.arcLength(cnt, True) approx = cv2.approxPolyDP(cnt, 0.04 * peri, True) (x, y, w, h) = cv2.boundingRect(cnt) ar = w / float(h) if len(approx) &gt; 5 and 0.9 &lt; ar &lt; 1.1: # filtering condition cv2.drawContours(image_copy, [cnt], 0, 255, -1) Thirdly, you need to store the area of each contour into a list and remove any contours that are too small: cnt_areas = [] cnt_circles = [] for cnt in contours: (x, y, w, h) = cv2.boundingRect(cnt) cnt_areas.append(w*h) cnt_circles.append(cnt) import statistics median_size_limit = statistics.median(cnt_areas) * 0.3 cnt_circles = [cnt for i, cnt in enumerate(cnt_circles) if cnt_areas[i] &gt; median_size_limit] And finally, display and check the result: # Draw the result and display image = cv2.cvtColor(image_gray, cv2.COLOR_GRAY2RGB) cv2.drawContours(image, cnt_circles, -1, (0, 0,255), 2) cv2.imshow("Result Preview", image) cv2.waitKey() Preview of final result can be seen here:
score: 2
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/q/51922381
tagged with: django
tagged with: python
tagged with: axios
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51952964
type: Question
has body: Update 2: I've given up on axios, I'm sure there is a way and now am using ajax with a bit of code from https://www.webforefront.com/django/formadvancedprocessing.html This is validating the form as usual, but I'm getting redirected to the action url even though I have $("#feedbackform").submit(function (event) { event.preventDefault(); The view: def error_checking(request): print('in error checking') if request.POST: form = RiderProfileFormSet(request.POST) print('made it') if form.is_valid(): print('NOT') return JsonResponse({'success': True}) else: print('YES') return JsonResponse({'error': form.errors}) Where am I going worng. I still would like to learn hwo to do this in axios. Update 1: I can get the form to the view as a string, but get stumped on how to ge the management form data to validate. Here are things I'm trying with no luck. one: # request_data = json.loads(request.body)['form_to_validate'] # The form as html string # Error: AttributeError: 'str' object has no attribute 'get' two: # request_data = json.load(request) # The form as a dict {'form_to_validate': '<form id="reg_form" method.....} #Error: ValidationError: ['ManagementForm data is missing or has been tampered with'] three: # request_data = RiderProfileFormSet(request.POST) #Error: ValidationError: ['ManagementForm data is missing or has been tampered with'] formset_post = RiderProfileFormSet(request_data) if formset_post.is_valid(): print('the formset is valid') If I could figure out how to validate the form as a string or convert the string to whatever format would work with .is_valid(). Original: I have searched for a few hours with no luck. Also, I'm new to programming. I am trying to perform form validation on a Django formset. I have multiple dynamically added (javascript) forms on one page. When a user submits the form/s, if there are errors in the form the forms are over wirtten by the redirct back to the registration page. I'm trying to retain thier inputs. My solution is to perform…
has answer: http://stackoverflow.com/a/51952964
score: 0
answer count: 1
has title: Django formset validation with axios
tagged with: jquery
tagged with: ajax

http://stackoverflow.com/a/51937218
score: 1
upvote count: 1
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/51937046
has comment: http://stackoverflow.com/comment/90824536
has body: The indentation of your code seems to be messed up, and I would suggest fixing that, as indentation is significant in python. However, it looks like you return driver from sign_in before you actually input the login and password information. This would cause the driver to be in the wrong state when you try to call load_emp_data, which would then cause it to fail.
has comment: http://stackoverflow.com/comment/90824601
has comment: http://stackoverflow.com/comment/90825184
has comment: http://stackoverflow.com/comment/90824832

http://stackoverflow.com/comment/90829717
type: Comment
type: QuestionComment
has text: @KevinFang Essentially, yes.
comment on: http://stackoverflow.com/q/51939716
score: 0

http://stackoverflow.com/comment/90688915
comment on: http://stackoverflow.com/q/51868455
has text: Why you want to create this `(kx, y)`? It sounds so weird
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/90862440
type: AnswerComment
type: Comment
score: 0
comment on: http://stackoverflow.com/a/51955814
has text: maybe I dont get how to input y ? just press it and click enter ?

http://stackoverflow.com/comment/90887377
type: QuestionComment
comment on: http://stackoverflow.com/q/51955020
has text: That's not what I need. I need to determine whether daylight savings time is in effect or not.
score: 0
type: Comment

http://stackoverflow.com/a/51921854
has comment: http://stackoverflow.com/comment/90799558
has comment: http://stackoverflow.com/comment/90797059
has comment: http://stackoverflow.com/comment/90911290
has comment: http://stackoverflow.com/comment/90903634
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/51921151
has body: I think that your file contains the correct UTF-8 encoded strings. The problems probably comes from the fact that you later read it as if it was latin1 (iso-8859-1) encoded. And you should be cautious that the APOSTROPHE (') is the unicode character U+0027, or the ASCII character of code 0x27, but in the HTML page you get, Fed’s contains a different character, a RIGHT SINGLE QUOTATION MARK which is the unicode character U+2019. Now everything can be explained: "Fed’s".encode('utf8') is the following byte string: b'Fed\xe2\x80\x99s'. If you try to read (decode) it as latin1, you get: &gt;&gt;&gt; "Fed’s".encode('utf8').decode('latin1') 'Fedâ\x80\x99s' because â is the unicode character U+00E2 or the iso-8859-1 character of code 0xe2. And in the Latin1 character set, both '\x80' and '\x99' are non printing characters, so you get: &gt;&gt;&gt; print("Fed’s".encode('utf8').decode('latin1')) Fedâs So your output file is correct, simply the way you display it is wrong: you should use an UTF-8 enable text editor, like the excellent vim (gvim) or notepad++ (google for them if you do not know them).
has comment: http://stackoverflow.com/comment/90928776
upvote count: 1
has comment: http://stackoverflow.com/comment/90929463
type: Answer

http://stackoverflow.com/comment/90580330
type: Comment
comment on: http://stackoverflow.com/a/51811994
score: 0
type: AnswerComment
has text: `tuple([1,2,3]) => (1,2,3)` instead of `([1,2,3],)`.

http://stackoverflow.com/a/60955108
answers question: http://stackoverflow.com/q/51912816
upvote count: 2
type: Answer
score: 2
downvote count: 0
has body: I had similar issue while using GraphvizerViewer which requires installing PySide2. So I initially installed PySide2 using pip. After uninstall it and reinstall it via conda conda install -c conda-forge pyside2, it works.

http://stackoverflow.com/comment/90764330
comment on: http://stackoverflow.com/q/51906929
score: 0
has text: yeah i think i could! how does the (.*?) separator work?
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/90840667
score: 0
type: AnswerComment
has text: May I see the rest of the code. The github link you provided in the comments brings me to a 404 page (page not found)
type: Comment
comment on: http://stackoverflow.com/a/51945554

http://stackoverflow.com/a/51890897
answers question: http://stackoverflow.com/q/51845170
has comment: http://stackoverflow.com/comment/132312926
upvote count: 4
has body: Is there any python environment configuration I should have performed before deployment? The answer is yes. If you want to run python script in Azure App Service,you need to install python environment in your application.Please refer to the steps below: Please refer to my work steps and see if the error still shows up. Step 1 : Add Extensions on the portal(here is Python 3.6.1 x64) Step 2: Switch to the Kudu CMD and commands cd Python364x64 and touch get-pip.py and copy the content of the url https://bootstrap.pypa.io/get-pip.py into the get-pip.py via Edit button, then run python get-pip.py to install the pip tool. Step 3 : Install any packages you need via python -m pip install requests Then you need to modify the python configuration of your code: var express = require('express'); var pythonShell = require('python-shell'); var router = express.Router(); var options = { pythonPath: 'D:/home/python364x64/python', scriptPath: 'D:/home/site/wwwroot' // args: // [ // req.query.term, // req.params.id, // req.session.user.searchName, // req.session.user.searchKey // ] }; var resultsByRel; pythonShell.run('TestRequests.py', options, function (err, data) { if (err) throw err; // results is an array consisting of messages collected during execution var values = JSON.parse(data[0]); resultsByRel = values; console.log('results: %j', resultsByRel); }); router.get('/', function(req, res, next) { res.send(resultsByRel); // res.render('executePython', resultsByRel ); }); module.exports = router; My simple python script: import requests r= requests.get("https://www.bing.com") print (r.status_code) Hope it helps you. Any concern ,please let me know.
downvote count: 0
score: 4
has comment: http://stackoverflow.com/comment/132312945
type: Answer

http://stackoverflow.com/a/51863585
has body: No - although the environment is 100% there, if someone else where to pull it down the path environment hasn't been exported not to mention Python version discrepancies will likely crop up. The best thing to do is to create what is known as a requirements.txt file. When you have created your environment, you can pip install this and pip install that. You'll start to built a number of project specific dependencies. Once you start to build up a number of project dependencies I would then freeze your local python environment (analogoues to a package.json for node.js package dependency management). I would recommend doing the following in your terminal: (local_python_environment) $ pip install django &amp;&amp; pip freeze &gt; requirements.txt (local_python_environment) $ pip install requests &amp;&amp; pip freeze &gt; requirements.txt That is to say, freeze your environment to a requirements.txt file every time a new dependency is installed. Once a collaborator pulls down your project - they can then install a fresh python environment: $ python3 -m venv local_python_environment (* Please use Python 3 and not Python 2!) And then activate that environment and install from your requirements.txt which you have included in your version control: $ source local_python_environment/bin/activate (local_python_environment) $ pip install -r requirements.txt Excluding your virtual environment is probably analogous to ignoring node_modules! :)
has comment: http://stackoverflow.com/comment/90682611
downvote count: 0
score: 8
answers question: http://stackoverflow.com/q/51863155
upvote count: 8
type: Answer

http://stackoverflow.com/comment/124218969
comment on: http://stackoverflow.com/a/51955985
has text: Also work with `matplotlib.pyplot`. That is, `plt.rcParams[...]`
type: Comment
score: 12
type: AnswerComment

http://stackoverflow.com/a/51922915
type: Answer
has comment: http://stackoverflow.com/comment/90796010
upvote count: 2
has comment: http://stackoverflow.com/comment/90795554
score: 2
has comment: http://stackoverflow.com/comment/90795937
has body: The correct way to upload multiple files as per the documentation would be.. files = request.FILES.getlist('file_field') #'file_field' --&gt; 'imagen' for you if form.is_valid(): for f in files: ... # Do something with each file. Your html looks ok. Replace your view code as per the above and check if its making to the POST in the view? Django Docs - Multiple File Upload
has comment: http://stackoverflow.com/comment/90795648
accepted answer of: http://stackoverflow.com/q/51922499
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51922499
has comment: http://stackoverflow.com/comment/90795890

http://stackoverflow.com/comment/90675316
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51860316
has text: It's not that straitforward

http://stackoverflow.com/comment/90578774
has text: what if the required index is below the given index? then it should give a negative example
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/51811815

http://stackoverflow.com/comment/90706878
has text: It’s ok to pull all those to one file. In this case 30Mb need not be considered. In my data this case rarely happens.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51875916

http://stackoverflow.com/a/51830904
type: Answer
downvote count: 0
has body: If that's your expected output, then you can do: for i in range(10, 0, -1): print('*' * i) In python 2, as yours is in: for i in range(10, 0, -1): print '*' * i Which can be shortened to: print(*('*' * i for i in range(10, 0, -1)), sep='\n') ...Which unpacks each line into a single print function and adds a new line between each. This shortened version only works with Python3. (I also recommended upgrading to python 3 if possible) The ideas behind this are the following: Strings can be multiplied to copy them Each line is a repeated * So... use a reverse range: `range(10, 0, -1) to get the decrease for each line Multiply the string * by the number from the range each time.
has comment: http://stackoverflow.com/comment/90616037
answers question: http://stackoverflow.com/q/51830857
score: 1
upvote count: 1

http://stackoverflow.com/comment/90884016
type: AnswerComment
comment on: http://stackoverflow.com/a/51818674
type: Comment
score: 2
has text: Indeed, I quite liked the bird `.gif` (and I feel loads of others did too :) ). I was also quite surprised by the amount of upvotes my question received as well as the number of views :) No problem! I also respect this answer as you've referred to @MarkSetchell's answer which I feel is quite nice, especially since his answer was the first and I was initially going to accept his answer back on the day on which I posted this question. I appreciate this! :)

http://stackoverflow.com/comment/90617558
has text: You should be using the mathematical operator, `+`, not logical operator `and`.
type: Comment
comment on: http://stackoverflow.com/q/51831709
type: QuestionComment
score: 0

http://stackoverflow.com/comment/90741158
score: 0
type: Comment
has text: the code is a bit long. was tying to summarize the coding issue i am facing
type: QuestionComment
comment on: http://stackoverflow.com/q/51895207

http://stackoverflow.com/comment/90852472
has text: of course reading excel files needs some extra packages. my answer was more about how to read the test input from a file
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51951000

http://stackoverflow.com/comment/129920959
type: QuestionComment
comment on: http://stackoverflow.com/q/51845606
has text: technically Mann-Whitney test doesn't say anything about median difference. It is still good choice for testing non-normal data.
score: 0
type: Comment

http://stackoverflow.com/comment/90757761
score: 0
comment on: http://stackoverflow.com/q/51903350
type: Comment
type: QuestionComment
has text: you don't seem to use the vectorized capabilities of numpy, list slicing etc... try to reduce the python loops.

http://stackoverflow.com/comment/90866241
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51951712
has text: @cwse, Sorry, I don't understand the problem. The above answers your *original* question as stated, right? If you have another, please [ask a new question](https://stackoverflow.com/questions/ask) with a more appropriate example.
type: AnswerComment

http://stackoverflow.com/q/51943596
downvote count: 0
answer count: 1
score: 2
favorite count: 0
has title: reading data from specified location
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90836821
tagged with: python
has answer: http://stackoverflow.com/a/51943778
has body: import CSV #Get high temperatures from file. filename = 'sitka_weather_07-2014.csv' with open(filename) as f: reader = csv.reader(f) header_row = next(reader) highs = [] for row in reader: highs.append(row[1]) print(highs) I encountered the code above when I am learning about extract and reading data. I didn’t quite get the usage of next(): header_row = next(reader) The book explains that because we have already read the header row,the loop will begins at the second line where the actual data begins What to do if we need to read from the third line? Is the following right? with open(filename) as f: reader = csv.reader(f) header_row = next(reader) row_1 = next(reader) highs = [] for row in reader: highs.append(row[2]) Print(highs) The question might be frivolous, but I’m very confused
type: Question

http://stackoverflow.com/q/51846590
has comment: http://stackoverflow.com/comment/90646579
tagged with: python
score: -2
has comment: http://stackoverflow.com/comment/90647009
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/90646970
has comment: http://stackoverflow.com/comment/90646543
has answer: http://stackoverflow.com/a/51846730
has comment: http://stackoverflow.com/comment/90646951
downvote count: 2
has comment: http://stackoverflow.com/comment/90646504
has answer: http://stackoverflow.com/a/51846786
has title: How to find the key of a minimum value in a nested dictionary?
type: Question
has comment: http://stackoverflow.com/comment/90646524
has comment: http://stackoverflow.com/comment/90646533
has comment: http://stackoverflow.com/comment/90646850
has comment: http://stackoverflow.com/comment/90646796
possible better answer: http://stackoverflow.com/a/51846786
has comment: http://stackoverflow.com/comment/90646763
has comment: http://stackoverflow.com/comment/90647174
has comment: http://stackoverflow.com/comment/90646619
accepted answer: http://stackoverflow.com/a/51846730
tagged with: numpy
answer count: 3
upvote count: 0
has comment: http://stackoverflow.com/comment/90646660
favorite count: 0
has comment: http://stackoverflow.com/comment/90646585
tagged with: python-3.x
has body: I have the following code that generates a nested dictionary. import random import numpy as np dict1 = {} for i in range(0,2): dict2 = {} for j in range(0,3): dict2[j] = random.randint(1,10) dict1[i] = dict2 For example it can generate the following content of dict1: {0: {0: 7, 1: 2, 2: 5}, 1: {0: 3, 1: 10, 2: 10}} I want to find the sub-key of a minimum value for the fixed key. For example, for the fixed key 0, the minimum value among the nested dictionary values is 2 which refers to thew sub-key 1. Therefore the result should be 1: result=find_min(dict1[0]) result 1 How can I develop such find_min function?
has comment: http://stackoverflow.com/comment/90646666
has answer: http://stackoverflow.com/a/51846821

http://stackoverflow.com/a/51807860
type: Answer
score: 2
has body: Try splitting such one-liners on some meaningful parts. def dictuse1(operator, x, y): # Stores mapping from operator names (strings) # to op implementations (functions == lambdas) optable = { 'add': lambda: x + y, 'sub': lambda: x - y, 'mul': lambda: x * y, 'div': lambda: x / y, } # Define a default op noop = lambda: None # Take the function by op name op = optable.get(operator, noop) # Exectute it and return a returning value of that function. return op() # remove () and you have a dictuse2 here. The only difference between dictuse1 and dictuse2 that the last one returns the function instead of the result of the invocation of that function.
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51807788
upvote count: 2
answers question: http://stackoverflow.com/q/51807788

h2o
tags question: http://stackoverflow.com/q/51863256
tags question: http://stackoverflow.com/q/51948440
tags question: http://stackoverflow.com/q/51942913
tag name: h2o
type: Tag
tags question: http://stackoverflow.com/q/51954502

http://stackoverflow.com/a/51884731
score: 0
has body: what you want to do is selkect all rows where Precio is not one of 'ON' and 'OFF' df[~df['Precio'].isin(['ON','OFF'])] Out[111]: Espacio País Precio 8 MARTIN * 0.5 9 MARTIN * 89 10 MARTIN * 198
type: Answer
answers question: http://stackoverflow.com/q/51883766

http://stackoverflow.com/comment/90705716
type: AnswerComment
has text: No problem :) Also if my answer helped you please consider accepting it by clicking the check-mark. This indicates to the wider community that you've found a solution and gives some reputation to both the answerer and yourself. There is no obligation to do this.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51876675

http://stackoverflow.com/comment/90897758
score: 0
has text: I'd be careful with eval... it can be very dangerous... but I guess so could this.
type: Comment
comment on: http://stackoverflow.com/a/51938414
type: AnswerComment

http://stackoverflow.com/a/51834193
answers question: http://stackoverflow.com/q/51834175
score: 4
has comment: http://stackoverflow.com/comment/90622312
upvote count: 4
has comment: http://stackoverflow.com/comment/90622350
downvote count: 0
has body: I think need factorize: df['col B'] = pd.factorize(df['col A'])[0] + 1 print (df) col A col B 0 A 1 1 B 2 2 C 3 3 A 1 4 A 1 5 B 2 Another solution: df['col B'] = pd.Categorical(df['col A']).codes + 1 print (df) col A col B 0 A 1 1 B 2 2 C 3 3 A 1 4 A 1 5 B 2
has comment: http://stackoverflow.com/comment/90622435
type: Answer

http://stackoverflow.com/q/51915286
answer count: 3
has title: Convert Dictionary values (arrays) into lists
tagged with: arrays
downvote count: 0
favorite count: 0
tagged with: key-value
accepted answer: http://stackoverflow.com/a/51915312
tagged with: python
tagged with: dictionary
has body: and I'm trying to convert dictionary's values to lists. Therefore, I can extend it to another dictionary's values (which are lists) with same keys. the dictionary looks like this: Q_VEC_DIC {'A':array([ 2623.8374 , -1392.9608 , 416.2083 , -1596.7402 ,],dtype=float32), 'B': array([ 1231.1268 , -963.2312 , 1823.7424 , -2295.1428 ,],dtype=float32)} I've tried the below, but it returns nothing: ARRAY_TO_LIST=[] for i in range(len(Q_VEC_DIC)): DOC=[] DOC.append(list(Q_VEC_DIC.values())[i].tolist) ARRAY_TO_LIST.append(DOC) How can I to convert values into lists by using loops? Thank you!
has answer: http://stackoverflow.com/a/51915922
type: AnsweredQuestion
tagged with: list
has answer: http://stackoverflow.com/a/51915299
upvote count: 1
type: Question
score: 1
possible better answer: http://stackoverflow.com/a/51915299
has answer: http://stackoverflow.com/a/51915312

http://stackoverflow.com/comment/90766037
type: Comment
type: QuestionComment
has text: Name your variables to reflect what they are: for instance, use `word` for a word, and `wdx` for the indice of a word in the list of words... that will help you understand the confusion
score: 3
comment on: http://stackoverflow.com/q/51907844

http://stackoverflow.com/comment/90770253
score: 1
has text: Yes, there is also venv in Python 3, but I don't think many people actually use it. If you're going to use Python 2 and Python 3, then you need pyenv, otherwise just virtualenv/virtualenvwrapper/venv will do. Here is a great overview of all these options: https://stackoverflow.com/questions/41573587/what-is-the-difference-between-venv-pyvenv-pyenv-virtualenv-virtualenvwrappe
comment on: http://stackoverflow.com/a/51909871
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/137103244
type: QuestionComment
has text: I believe this is a duplicate of https://stackoverflow.com/q/16989946/2954547
comment on: http://stackoverflow.com/q/51813621
score: 0
type: Comment

http://stackoverflow.com/comment/90629651
has text: It works fine, when I hardcode the date as the parameter to parse, since I am retrieving the date from mysql raise ValueError("Unknown string format:", timestr) ValueError: ('Unknown string format:', "('2016-04-15T12:24:20.707Z',)")
comment on: http://stackoverflow.com/a/51837510
type: Comment
score: 1
type: AnswerComment

http://stackoverflow.com/q/51917160
tagged with: recurrent-neural-network
linked to: http://stackoverflow.com/q/46189318
tagged with: lstm
linked to: http://stackoverflow.com/q/49242266
answer count: 1
downvote count: 0
has body: I'm building a multilayered bidirectional RNN using Tensorflow .I'm a bit confused about the implementation though . I have built two functions that creates multilayered bidirectional RNN the first one works fine , but I'm not sure about the predictions its making, as it is performing as a unidirectional multilayered RNN . below is my implementation : def encoding_layer_old(rnn_inputs, rnn_size, num_layers, keep_prob, source_sequence_length, source_vocab_size, encoding_embedding_size): """ Create encoding layer :param rnn_inputs: Inputs for the RNN :param rnn_size: RNN Size :param num_layers: Number of layers :param keep_prob: Dropout keep probability :param source_sequence_length: a list of the lengths of each sequence in the batch :param source_vocab_size: vocabulary size of source data :param encoding_embedding_size: embedding size of source data :return: tuple (RNN output, RNN state) """ # Encoder embedding enc_embed = tf.contrib.layers.embed_sequence(rnn_inputs, source_vocab_size, encoding_embedding_size) def create_cell_fw(rnn_size): with tf.variable_scope("create_cell_fw"): lstm_cell = tf.contrib.rnn.LSTMCell(rnn_size,initializer=tf.random_uniform_initializer(-0.1,0.1,seed=2), reuse=False) drop = tf.contrib.rnn.DropoutWrapper(lstm_cell, output_keep_prob=keep_prob) return drop def create_cell_bw(rnn_size): with tf.variable_scope("create_cell_bw"): lstm_cell = tf.contrib.rnn.LSTMCell(rnn_size,initializer=tf.random_uniform_initializer(-0.1,0.1,seed=2), reuse=False) drop = tf.contrib.rnn.DropoutWrapper(lstm_cell, output_keep_prob=keep_prob) return drop enc_cell_fw = tf.contrib.rnn.MultiRNNCell([create_cell_fw(rnn_size) for _ in range(num_layers)]) enc_cell_bw = tf.contrib.rnn.MultiRNNCell([create_cell_bw(rnn_size) for _ in range(num_layers)]) ((encoder_fw_outputs, encoder_bw_outputs),(encoder_fw_final_state,encoder_bw_final_state)) = tf.nn.bidirectional_dynamic_rnn(enc_cell_fw,enc_cell_bw, enc_embed, sequence_length=source_sequence_length,dtype=tf.float32) encode…
favorite count: 0
has answer: http://stackoverflow.com/a/51931965
accepted answer: http://stackoverflow.com/a/51931965
tagged with: python
type: AnsweredQuestion
score: 2
upvote count: 2
has title: Confused about multi-layered Bidirectional RNN in Tensorflow
tagged with: tensorflow
type: Question
tagged with: seq2seq

http://stackoverflow.com/comment/90587427
comment on: http://stackoverflow.com/q/51816284
score: 0
type: QuestionComment
type: Comment
has text: @AKX I want to load the data sample to relational table. Having nested Jsons means having sub table which I don't want... empty arrays are ok. each array will be a table. sometimes not all fields have values.

http://stackoverflow.com/q/51939437
downvote count: 2
has answer: http://stackoverflow.com/a/51939449
type: Question
has title: use map/lambda to create dicts
score: -1
upvote count: 1
answer count: 1
favorite count: 0
tagged with: python-3.x
has body: Here's my code: a = {} ins = ["foo", "bar"] for i in ins: a[i] = {} Output {'foo': {}, 'bar': {}} Basically, I want to create a dict for each item in the list. Is there any way to do this using map or lambda, in a more concise way?
tagged with: python
accepted answer: http://stackoverflow.com/a/51939449
tagged with: dictionary
tagged with: lambda
type: AnsweredQuestion

http://stackoverflow.com/comment/90698462
score: 0
has text: Thank you so much @pankaj and Cris. I used Erosion and it did the job of removing noise my next task is to somehow detect the lump and print a text. Any suggestion for the same?
comment on: http://stackoverflow.com/q/51873110
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51949536
has comment: http://stackoverflow.com/comment/90851692
has comment: http://stackoverflow.com/comment/90849109
type: Question
answer count: 2
has body: I am currently working on a program where I need to change the position of a widget. Here is my code: root = Tk() frame = Frame(root, bg="black") label1 = Label(frame, text="not important") label.grid(row=1, column=1) #some stuff happens x = aFunctionThatReturnsXCoordinate #not actual name y = aFunctionThatReturnsYCoordinate Now I want to change the position of label1 to the new coordinates. I have tried: label1.forget_grid() label1.grid(rows=x, columns=y) #Ive tried label1/frame.update after this code but it didnt do anything I've also tried to do it without the grid_forget. I didn't forget the frame.pack and root.mainloop. Is there a function to change the position?
has answer: http://stackoverflow.com/a/51951416
has comment: http://stackoverflow.com/comment/90849808
score: 0
has comment: http://stackoverflow.com/comment/90852283
favorite count: 0
tagged with: tkinter
has comment: http://stackoverflow.com/comment/90849153
has answer: http://stackoverflow.com/a/51954142
upvote count: 2
type: UnansweredQuestion
downvote count: 2
has title: Tkinter dynamically change a widget position with grid geometry manager
tagged with: python
has comment: http://stackoverflow.com/comment/90849991

http://stackoverflow.com/a/61187976
score: 4
has body: import requests from urllib3.util.ssl_ import create_urllib3_context from requests.adapters import HTTPAdapter cert_path = "path/to/certfile.crt" private_key_path = "path/to/private_certificate_file.pem" passphrase_key = "someSecretKey" class SSLAdapter(HTTPAdapter): def init_poolmanager(self, *args, **kwargs): context = create_urllib3_context() context.load_cert_chain(certfile=cert_path, keyfile=private_key_path, password=passphrase_key) kwargs['ssl_context'] = context return super().init_poolmanager(*args, **kwargs) session = requests.Session() session.verify = False # If you don't want to validate server's public certificate session.mount("https://", SSLAdapter()) response = session.post(url) print(response.json()) I was recently working on the same problem where I had an encrypted private certificate and I have to use the passphrase key to decrypt it during the rest api call in python. I just thought of sharing my code to answer this question. This code is working for me.
type: Answer
upvote count: 4
has comment: http://stackoverflow.com/comment/116100387
downvote count: 0
has comment: http://stackoverflow.com/comment/132009248
answers question: http://stackoverflow.com/q/51871661

http://stackoverflow.com/comment/90702309
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51869402
has text: Yeah..it had around 15 million records. I downloaded it from web. But, thing is that,with this same dataset , I am able to do it in Linux and Mac. But, I am getting this error only in windows

http://stackoverflow.com/comment/90839918
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51944980
has text: @Sathiyakugan As you have edited your question I have now updated my answer.

http://stackoverflow.com/a/51812826
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90580557
answers question: http://stackoverflow.com/q/51812656
type: Answer
accepted answer of: http://stackoverflow.com/q/51812656
score: 0
has body: I think you better first fix your models. In Django a ForeignKey is conceptually a reference to an object to which you refer, not the id. Of course in the database it is stored as an id, but that is a layer that you should not care much about. So I would advice to first rename the fields like weaponid to weapon: class Characterweapons(models.Model): character = models.ForeignKey(Characters, models.DO_NOTHING, db_column='CharacterID') weapon = models.ForeignKey(Weapons, models.DO_NOTHING, db_column='WeaponID', blank=True, null=True) category = models.ForeignKey(Category, models.DO_NOTHING, db_column='CategoryID', blank=True, null=True) quantity = models.IntegerField(db_column='Quantity', blank=True, null=True) # ... Now if you construct a ForeignKey with the name fieldname, Django actually introduces two fields: the fieldname which is - like said before - a reference to a model object to which the ForeignKey refers, and a field fieldname_id that stores the id (the primary key) of that object. These two fields thus act like "twins". We can then rewrite the submission view like: def submission(request): print("Registered successfully") name = request.POST["Name"] level = request.POST["Level"] credits = request.POST["Credits"] mainhand = request.POST["Mainhand"] offhand = request.POST["Offhand"] info = Characters.objects.create(name=name, level=level,credits=credits) if Weapons.objects.filter(weapon_id=mainhand).exists(): a = mainhand info_mh = Characterweapons.objects.create( character_id=info.pk, category_id=1, weapon_id=a ) return return_charnames(request) In the above I did some refactorings as well: In Python variables in functions typically have lowercase names; you do not need to loop over weapon_ids, you can use an EXISTS query, which is typically faster; Instead of first constructing a model instance, and then obj.save() it, you can use Model.objects.create(..) instead; you probably do not want to fetch the latest(..) value, but use the pk of the info object in…

http://stackoverflow.com/comment/90603569
has text: but when I create an Rscript with the same code and source it, it says 'No module named pandas'. I think it is using /usr/bin/python in this case
score: 0
type: Comment
comment on: http://stackoverflow.com/q/51817345
type: QuestionComment

series
tag name: series
type: Tag
tags question: http://stackoverflow.com/q/51917507
tags question: http://stackoverflow.com/q/51926036
tags question: http://stackoverflow.com/q/51882902
tags question: http://stackoverflow.com/q/51806731
tags question: http://stackoverflow.com/q/51843474
tags question: http://stackoverflow.com/q/51944476
tags question: http://stackoverflow.com/q/51921463
tags question: http://stackoverflow.com/q/51827099

http://stackoverflow.com/a/51876675
answers question: http://stackoverflow.com/q/51875932
has comment: http://stackoverflow.com/comment/90705250
has comment: http://stackoverflow.com/comment/90705452
has comment: http://stackoverflow.com/comment/90705041
upvote count: 2
has comment: http://stackoverflow.com/comment/90705309
has comment: http://stackoverflow.com/comment/90705716
has comment: http://stackoverflow.com/comment/90705415
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90705469
has comment: http://stackoverflow.com/comment/90704724
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/90705400
has body: Please try this. The date is in format year-month-day for example '2018-08-16'. from datetime import datetime a = input('Starting_Date: ') b = input('Ending_Date :') starting_date = datetime.strptime(a, "%Y-%m-%d").date() ending_date = datetime.strptime(b, "%Y-%m-%d").date() df.loc[starting_date:ending_date] Hope that works for you :)
downvote count: 0
accepted answer of: http://stackoverflow.com/q/51875932

http://stackoverflow.com/comment/90852786
type: QuestionComment
comment on: http://stackoverflow.com/q/51948331
score: 1
has text: Did you name your own file `text_summarizer.py`?
type: Comment

http://stackoverflow.com/comment/90721100
comment on: http://stackoverflow.com/a/51884507
has text: Sorry if this is a basic question, but is there a good reference for the order of execution for pytest? I figured that was the case, but I found it really hard to figure out what executed first.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/51931468
upvote count: 4
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/51930730
type: Answer
answers question: http://stackoverflow.com/q/51930730
score: 3
has body: After doing a restart of my machine after deleting python34 from my system path variables as @Talha Junaid mentioned in the comments, my python now defaults to python3.6 when accessed through command prompt, windows must load all the path variables on startup and hold them in memory until a restart occurs. Steps for anyone else starting the process. Windows 10 Type "System" into the search bar to go to system settings in the control panel (Control Panel\All Control Panel Items\System) Click "Advanced System Settings" -> "Environment Variables" For User Variables: Highlight the row for "Path" by clicking on it and then click the "Edit" button Highlight by clicking the version of python you want to remove from your environment variables and then click the "Delete" button. Repeat steps 3 and 4 for System Environment Variables. Close all the windows by clicking the "OK" buttons Restart your machine
downvote count: 1

http://stackoverflow.com/q/51909532
tagged with: opencv
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90772263
has title: extracting digits from image opencv python
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/90770544
score: 1
has comment: http://stackoverflow.com/comment/90770576
favorite count: 0
type: Question
tagged with: python
has body: I am trying to extract numbers / digits from below image: image from which to extract digits 1st I tried it with OCR, but the output is not relevant, so I planned to use opencv with python I have written the following code: import numpy as np import cv2 from matplotlib import pyplot as plt #cv2.IMREAD_COLOR = 1 , Loads a color image. Any transparency of image will be neglected. It is the default flag. #cv2.IMREAD_GRAYSCALE = 0 , Loads image in grayscale mode #cv2.IMREAD_UNCHANGED = -1 , Loads image as such including alpha channel image = cv2.imread( './in.png' , 1 ) gray = cv2.cvtColor( image, cv2.COLOR_BGR2GRAY ) ret1, thresh1 = cv2.threshold( gray, 127, 255, cv2.THRESH_BINARY ) image[ thresh1 == 0 ] = 255 kernal = cv2.getStructuringElement( cv2.MORPH_ELLIPSE, ( 5,5 ) ) erosion = cv2.erode( image, kernal, iterations = 1 ) cv2.imwrite( 'res.png', erosion ) and the output I got is: output result image at this point I am at least standing somewhere to accomplish my task, but I am not able to decide further step to extract things, I googled and found something contours from opencv so I tried using this code: from imutils.perspective import four_point_transform from imutils import contours import imutils import cv2 #cv2.IMREAD_COLOR = 1 , Loads a color image. Any transparency of image will be neglected. It is the default flag. #cv2.IMREAD_GRAYSCALE = 0 , Loads image in grayscale mode #cv2.IMREAD_UNCHANGED = -1 , Loads image as such including alpha channel image = cv2.imread( './input.png' , 1 ) image = imutils.resize(image, height=500) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) blurred = cv2.GaussianBlur(gray, (5, 5), 0) edged = cv2.Canny(blurred, 50, 200, 255) cv2.imwrite( 'res.png', edged ) and I got the output image as: again as per the contours logic I am not able to point out how I can find the placement of required digits inside the image. I am really confused, How can I extract digits from the image. I m looking for some hints or guide and even codes to accom…
upvote count: 1

http://stackoverflow.com/q/51895572
has comment: http://stackoverflow.com/comment/90742174
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51898231
upvote count: 1
downvote count: 1
type: Question
linked to: http://stackoverflow.com/q/15771472
accepted answer: http://stackoverflow.com/a/51898231
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/90743032
has body: I have some time series data which contains both day time and night time values. The time entries are parsed in DateTime format, and I have a routine that is able to determine the values corresponding to night periods. For my purposes, I would like to compute the rolling mean, but only using night time values. Is there an easy way of doing this? Any help is greatly appreciated! Update: A slice through the dataframe looks like this: 0 Time Value 1 2016-02-16 08:40:14.133000 12 2 2016-02-16 11:25:14.133000 4 3 2016-02-16 23:45:14.133000 8 4 2016-03-16 08:40:14.002700 17 5 2016-03-16 23:45:14.133000 2 6 2016-03-16 23:50:14.133000 6 7 2016-03-16 23:55:14.133000 9 8 2016-04-16 08:40:14.133000 10 9 2016-04-16 11:20:14.133000 2 10 2016-04-16 12:40:14.133000 7 11 2016-04-16 23:45:14.133000 5 12 2016-05-16 08:40:14.002700 11 13 2016-05-16 23:40:14.133000 3 14 2016-05-16 23:50:14.133000 4 15 2016-06-16 08:40:14.002700 11 16 2016-06-16 10:30:14.002700 27 17 2016-06-16 23:25:14.133000 3 18 2016-06-16 23:30:14.133000 5 19 2016-07-16 08:40:14.002700 7 20 2016-07-16 11:15:14.002700 9 21 2016-07-16 23:45:14.133000 18 I am interested in computing the weekly rolling-mean for night values only. In my examples, night time is between 11pm and 5am.
answer count: 1
has title: Python Pandas: Computing Rolling-Mean for Filtered Data
favorite count: 0
has comment: http://stackoverflow.com/comment/90741981
tagged with: python

http://stackoverflow.com/comment/90700987
has text: @anekix: for your specific example, the traceback won't actually change in length, the `raise ZeroDivisionError()` line only customised the exception message. But the `10/ac` expression shown in the traceback when you don't catch and re-raise tells the developer just as much that it was `ac` that was at fault there, catch and re-raise thus has little added value but you now have to content with 4 extra lines of code in your project with a new level of indentation. That's a small cost here, but that's still a cost you now carry for very little benefit.
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/51874480
type: Comment

http://stackoverflow.com/comment/90812299
has text: And it is not possible to create a dataframe without index?
comment on: http://stackoverflow.com/q/51930854
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51804592
has comment: http://stackoverflow.com/comment/90565049
type: Question
linked to: http://stackoverflow.com/q/45621722
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/90565064
favorite count: 0
duplicate of: http://stackoverflow.com/q/45621722
tagged with: python
has comment: http://stackoverflow.com/comment/90565053
has answer: http://stackoverflow.com/a/51804619
tagged with: file
downvote count: 1
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/51804619
score: -1
has title: python script error when writing to another file
has body: i am trying to write a python script to get all the content in one file to be written to another file . but i am getting the below error . the code i am using is : #!/user/bin/env python with open('log.txt', 'r') as file: line = file.read() with open('/etc/snort/rules/test.rules' , 'w') as f2: f2.write(line) the error i get is : in line 7 with open('/etc/snort/rules/test.rules' , 'w') as f2: ***IndentationError : expected an indented block***

http://stackoverflow.com/comment/90684831
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51865023
has text: Here is the stack trace you requested: `Traceback (most recent call last): File "C:/Users/<UserName>/Documents/PyCharm/PycharmProjects/html_to_excel.py", line 69, in <module> save_as_xlsx(r'C:\Users\<UserName>\Desktop\HTML_FOLDER') File "C:/Users/<UserName>/Documents/PyCharm/PycharmProjects/html_to_excel.py", line 67, in save_as_xlsx df_from_html.to_excel(str(save_path), index=False) AttributeError: 'list' object has no attribute 'to_excel'`

http://stackoverflow.com/a/51878998
accepted answer of: http://stackoverflow.com/q/51878706
answers question: http://stackoverflow.com/q/51878706
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/90750201
has body: Based upon the answer given to this question: json.loads allows duplicate keys in a dictionary, overwriting the first value , this should work: import json testjson = '{"data": {"key1": "val", "key2": "val", "key1": "val"}}' def parse_multimap(ordered_pairs): multimap = dict() for k, v in ordered_pairs: if k in multimap: multimap[k].append(v) else: multimap[k] = [v] return multimap parsed = json.loads(testjson, object_pairs_hook=parse_multimap) for key in parsed['data'][0]: print("Key: {} | Count: {}".format(key, len(parsed['data'][0][key]))) Output: Key: key2 | Count: 1 Key: key1 | Count: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/90709849
upvote count: 1
type: Answer

http://stackoverflow.com/a/51894840
downvote count: 0
has comment: http://stackoverflow.com/comment/90747110
has body: Replace this line: self.thread.started.connect(self.worker.work) with this: self.thread.started.connect(lambda: self.worker.work(10)) You can replace 10 with the value from the text box. Just remember to convert it to an int first. Checkout this article for a more detailed explanation.
type: Answer
has comment: http://stackoverflow.com/comment/90790249
has comment: http://stackoverflow.com/comment/90740854
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/51894098
answers question: http://stackoverflow.com/q/51894098
has comment: http://stackoverflow.com/comment/90740631
type: AcceptedAnswer

http://stackoverflow.com/comment/90622473
type: Comment
type: QuestionComment
has text: @skyboyer candidates is a list of integers
score: 0
comment on: http://stackoverflow.com/q/51804721

http://stackoverflow.com/comment/90723959
score: 0
type: AnswerComment
has text: the way to split on comma is -> https://stackoverflow.com/a/9436422/9302655 it's in perl ; do you know how do i do this in python
type: Comment
comment on: http://stackoverflow.com/a/51886092

http://stackoverflow.com/q/51811972
tagged with: matplotlib
possible better answer: http://stackoverflow.com/a/78301205
has answer: http://stackoverflow.com/a/78301205
downvote count: 0
score: 6
has answer: http://stackoverflow.com/a/51813562
type: Question
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/35042255
favorite count: 0
tagged with: python-3.x
has body: I am trying to put the following two plots onto the same figure: import seaborn as sns; sns.set(color_codes=True) import matplotlib.pyplot as plt f, (ax1, ax2) = plt.subplots(1, 2, sharey=True) iris = sns.load_dataset("iris") sns.boxplot(data=iris, orient="h", palette="Set2", ax = ax1) species = iris.pop("species") lut = dict(zip(species.unique(), "rbg")) row_colors = species.map(lut) sns.clustermap(iris, row_colors=row_colors, ax = ax2) I understand that clustermap returns a figure, so this doesn't work. However, I still need a way to present these plots next to each other (horizontal). sns.heatmap returns an axes, but it does not support clustering or color annotation . What is the best way to do this ?
tagged with: seaborn
answer count: 2
has title: Adding seaborn clustermap to figure with other plots
tagged with: python
accepted answer: http://stackoverflow.com/a/51813562
upvote count: 6

ajax
tags question: http://stackoverflow.com/q/51941827
type: Tag
tags question: http://stackoverflow.com/q/51915150
tags question: http://stackoverflow.com/q/51953016
tags question: http://stackoverflow.com/q/51829249
tags question: http://stackoverflow.com/q/51922381
tags question: http://stackoverflow.com/q/51910889
tags question: http://stackoverflow.com/q/51917816
tags question: http://stackoverflow.com/q/51876706
tags question: http://stackoverflow.com/q/51875020
tags question: http://stackoverflow.com/q/51897969
tags question: http://stackoverflow.com/q/51933714
tags question: http://stackoverflow.com/q/51945705
tags question: http://stackoverflow.com/q/51834791
tags question: http://stackoverflow.com/q/51922105
tags question: http://stackoverflow.com/q/51915943
tags question: http://stackoverflow.com/q/51920961
tags question: http://stackoverflow.com/q/51913220
tags question: http://stackoverflow.com/q/51849977
tag name: ajax

http://stackoverflow.com/comment/90684567
comment on: http://stackoverflow.com/a/51866129
type: Comment
type: AnswerComment
has text: @LioraHaydont they have made an attempt and they have trouble with `figuring out if I could call a previous variable.` This answer offers a solution to that and I believe a slightly more elegant design
score: 0

http://stackoverflow.com/comment/90683554
score: 0
type: Comment
type: QuestionComment
has text: `matplotlib` accumulates the graphs drawn by multiple calls to `plt.plot()` by default. This answer might help: https://stackoverflow.com/a/4805456/1102056
comment on: http://stackoverflow.com/q/51865607

http://stackoverflow.com/comment/90809560
has text: of course, I've added the whole models.py file above
comment on: http://stackoverflow.com/q/51929887
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51858011
favorite count: 0
downvote count: 3
has body: I am trying to sort the list (fruit) after I have appended the contents of another file to it, and prior to writing it to the the txt file "fruit_salad.txt". The problem I am having is that as soon as I write "fruit.sort()" it then fails to recognise output. What am I doing by sorting a list that causes this? Thank you in advance. ---CODE--- try: f = open("fruit.txt", mode='r', encoding='utf-8') fruit = f.readlines() print(fruit, "\n") f1 = open("more_fruit.txt", mode="r", encoding='utf-8') fruit.append(f1.readlines()) print(fruit) # fruit.sort() # WITHOUT THIS LINE IT WORKS FINE output = open("fruit_salad.txt", mode='w', encoding='utf-8') for line in fruit: output.writelines(line) except (FileNotFoundError, IOError): print("File Not Found!!") finally: f.close() f1.close() output.close() --OUTPUT-- ['pear\n', 'apple\n', 'orange \n', 'mandarin\n', 'watermelon\n', 'pomegranate\n', 'lemon\n', 'pineapple\n'] ['pear\n', 'apple\n', 'orange \n', 'mandarin\n', 'watermelon\n', 'pomegranate\n', 'lemon\n', 'pineapple\n', ['banana\n', 'raspberry\n', 'blueberry\n', 'lime\n', 'blackberry\n', 'cherry\n', 'grape']] The program 'python.exe' has exited with code 0 (0x0). ERR OUTPUT During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\Extensions\Microsoft\Python\Core\ptvsd_launcher.py", line 111, in &lt;module&gt; vspd.debug(filename, port_num, debug_id, debug_options, run_as) File "C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\Extensions\Microsoft\Python\Core\Packages\ptvsd\debugger.py", line 36, in debug run(address, filename, *args, **kwargs) File "C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\Extensions\Microsoft\Python\Core\Packages\ptvsd\_main.py", line 47, in run_file run(argv, addr, **kwargs) File "C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\Extensions\Microsoft\Py…
tagged with: python
upvote count: 0
tagged with: python-3.x
has title: Trying to sort a list with sort()
score: -3
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/51858108
accepted answer: http://stackoverflow.com/a/51858108
has comment: http://stackoverflow.com/comment/90668670
type: Question
answer count: 1

http://stackoverflow.com/q/51945601
linked to: http://stackoverflow.com/q/27335726
has answer: http://stackoverflow.com/a/51945965
downvote count: 1
type: Question
linked to: http://stackoverflow.com/q/11405549
score: 10
has comment: http://stackoverflow.com/comment/90842784
has comment: http://stackoverflow.com/comment/90840672
tagged with: security
answer count: 1
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/90899574
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90840683
tagged with: python
has comment: http://stackoverflow.com/comment/90842740
has title: How do I encrypt and decrypt a string in python 3.7?
upvote count: 11
has body: I've found this exactly same question. But PyCrypto doesn't install both on python 3.6.5 and 3.7.0. So, I implement some kind of Gronsfeld-like cipher. I know, that's awful, but I can simply encrypt and derypt string with password def encrypt(string, password): int_list = [] password_len = len(password) for cnt, sym in enumerate(string): password_sym = password[cnt % password_len] int_list.append(ord(sym)-ord(password_sym)) return int_list # got some list which contain mine key to Todoist api, yes, this can be bruteforced, but same as any other API key &gt;&gt;&gt; [-20, -20, -50, -14, -61, -54, 2, 0, 32, 27, -51, -21, -54, -53, 4, 3, 29, -14, -51, 29, -10, -6, 1, 4, 28, 29, -55, -17, -59, -42, 2, 50, -13, -14, -52, -15, -56, -59, -44, 4] def decrypt(int_list, password): output_string = "" password_len = len(password) for cnt, numb in enumerate(int_list): password_sym = password[cnt % password_len] output_string += chr(numb+ord(password_sym)) return output_string So, how to do it properly?

http://stackoverflow.com/a/52296094
downvote count: 0
score: 1
upvote count: 1
has body: Stumbled across this from my own Google search and found the solution elsewhere (and mentioned by @PM 2RING here). a = ('{:.53f}'.format(target)) The format option allows you to force the variable to explicitly contain 53 decimal points and then store this as a string.
type: Answer
answers question: http://stackoverflow.com/q/51914366

http://stackoverflow.com/comment/90574041
type: Comment
type: QuestionComment
has text: @RemcoGerlich Let us assume that no items are repeated in either lists.
comment on: http://stackoverflow.com/q/51809437
score: 0

http://stackoverflow.com/q/51888323
tagged with: mongodb
has title: PyMongo - name 'SON' is not defined
answer count: 1
has answer: http://stackoverflow.com/a/52185200
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/90731563
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90756332
has body: While learning MongoDB in Python with PyMongo package, I have an error when following "getting started" guide from MongoDB website here. Here is the code I have issue with cursor = db.inventory.find({"size": SON([("h", 14), ("w", 21), ("uom", "cm")])}) and here is the error message I get: NameError Traceback (most recent call last) 1 cursor = db.inventory.find( 2 {"size": SON([("h", 14), ("w", 21), ("uom", "cm")])}) NameError: name 'SON' is not defined I have successfully executed all pieces from start till this line and even I can run the code afterwards, but not this specific query. After a bit of Googling, I found this Post which explains SON but does not narrow down to troubleshooting. In case these info would help, I am running these code on Mac OS 10.13, Anaconda 1.8.1, with Jupyter. I tested on both Python 2.7 and 3.6 to ensure nothing is wrong with Python libraries. All relevant packages asked by tutorial are installed via Jupyter
score: 1
upvote count: 1
type: Question

http://stackoverflow.com/q/51803665
has comment: http://stackoverflow.com/comment/90563482
tagged with: python
has comment: http://stackoverflow.com/comment/90563493
answer count: 0
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90563444
score: 2
type: Question
has comment: http://stackoverflow.com/comment/90564043
has comment: http://stackoverflow.com/comment/90564045
downvote count: 0
tagged with: inheritance
favorite count: 0
tagged with: class
has title: Python class with variable parent class object
has body: Sorry that I am not using a general example to explain my problem. I know it has nothing to do with machine learning, but I tried to write a general example and it was a lot more confusing so I decided to go with that: I have two parent classes, let's say class MLP(object): def __init__(self, mlp_architecture): ... def forward(self): ... class CNN(object): def __init__(self, cnn_architecture): ... def forward(self): ... and I have a child class, let's say class Classifier(Model): def __init__(self, num_epochs, learning_rate, ... model_architecture): super(Classifier, self).__init__(model_architecture) def train(self): ... def predict(self, x): ... Now Classifier's methods work for both MLP and CNN and they require a forward method. I would like Classifier to be able to inherit forward from both MLP and CNN without having to define two child classes like this class ClassifierMLP(MLP): ... class ClassifierCNN(CNN): ... Instead, I would like to do something like this (I know what I wrote is wrong, but I hope you get it) clf = Classifier(MLP)(num_epochs=..., learning_rate=..., ... model_architecture=...) clf.train() What would be the proper way to do this? Also, if you are wondering "why bother", Classifier, MLP and CNN actually have a lot more methods and I also have more Parent classes from which I would like Classifier to inherit, so I think my program would be much simpler if I was able to do this. Thanks in advance!

http://stackoverflow.com/comment/90844746
score: 0
type: Comment
type: QuestionComment
has text: Just do a `self.data_reader = None` when it's no longer needed.
comment on: http://stackoverflow.com/q/51946818

http://stackoverflow.com/comment/90619118
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51832477
has text: Thank you for your thoughtful and thorough answer. I am a complete beginner to both system calls and git, and your answer was very easy to follow.
score: 0

http://stackoverflow.com/q/51799821
answer count: 1
has comment: http://stackoverflow.com/comment/90556045
has answer: http://stackoverflow.com/a/51800811
has title: Python threading module - GUI still freezing
has body: I built a twitter crawler with GUI that fetches the latest 20 tweets from any given Twitter Account and saves them into a csv file. The crawler should repeat crawling every x minutes (timeIntervall) for y times (times). The GUI freezes when the crawler is currently busy, so I tried to solve this with threading: app = QtWidgets.QApplication(sys.argv) class MainWindow(QtWidgets.QMainWindow): def __init__(self, parent=None): super().__init__(parent) self.setWindowTitle("Twitter Crawler") self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.pushButton.clicked.connect(self.onPushButtonClick) def onPushButtonClick(self): def working(self): url = self.ui.urlInput.text() timeIntervall = self.ui.timeIntervall.text() seconds = timeIntervall.split(":") seconds = int(seconds[0]) * 60 * 60 + int(seconds[1]) * 60 times = self.ui.crawlcount.value() fetcher = ArticleFetcher(url) print(times) firstFetch = True for count in range(0, times): if firstFetch: fetcher.fetch() firstFetch = False else: time.sleep(seconds) fetcher.fetch() worker = threading.Thread(target=working, args=(self,)) worker.start() worker.join() window = MainWindow() window.show() sys.exit(app.exec()) After entering timeIntervall, times and pushButton is clicked, a worker thread is started which handles the crawling. The application is running, but GUI is still freezing. I suspected that I would need another thread for the GUI and tried the following: def gui(): window = MainWindow() window.show() sys.exit(app.exec()) rungui = threading.Thread(target=gui) rungui.start() rungui.join() Now the GUI opens only very briefly and then closes again immediately. Any suggestions how to solve this? Or is it maybe silly not to use the PyQt threading module?
tagged with: web-crawler
type: UnansweredQuestion
score: 2
downvote count: 0
favorite count: 0
type: Question
upvote count: 2
tagged with: qtpy
tagged with: multithreading
tagged with: python

http://stackoverflow.com/comment/90847049
has text: Try [**Sieve of Eratosthenes**](https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes)
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/51948635

http://stackoverflow.com/comment/90626170
comment on: http://stackoverflow.com/a/51828062
type: AnswerComment
score: 0
type: Comment
has text: Thank you very much. This explains a lot to me. I will see what i (we) can change to make it work the normal way.

http://stackoverflow.com/comment/90842422
type: QuestionComment
has text: What have you tried so far? What kind of application? Command line or gui based?
score: 0
comment on: http://stackoverflow.com/q/51945846
type: Comment

http://stackoverflow.com/q/51825908
tagged with: python
downvote count: 1
type: AnsweredQuestion
upvote count: 0
has comment: http://stackoverflow.com/comment/90605985
type: Question
tagged with: counter
has comment: http://stackoverflow.com/comment/90605986
score: -1
has title: game counter in python
linked to: http://stackoverflow.com/q/49630723
answer count: 1
has comment: http://stackoverflow.com/comment/90606455
favorite count: 0
has body: I made the game rock, paper or scissors. I want to implement a game counter, but I can't figure out how to make it work. It is stopped at 1. I want to play more games and the counter to show me the numbers of played games. import random stop = False while (not stop): games_count = 0 you = input('Player 1: Please type your choice: rock, paper or scissors: ') oponent = ['rock', 'paper', 'scissors'] choice = random.choice(oponent) games_count += 1 print('the oponent choice is: ', choice) if choice == you: print('DRAW GAME') elif choice == 'rock' and you == 'paper': print('YOU LOST') elif choice == 'rock' and you == 'scissors': print('YOU WON') elif choice == 'paper' and you == 'rock': print('YOU WON') elif choice == 'paper' and you == 'scissors': print('YOU LOST') elif choice == 'scissors' and you == 'rock': print('YOU LOST') elif choice == 'scissors' and you == 'paper': print('YOU WON') else: print('Wrong answer, please type rock, paper or scissors in your next attempt!') answer = input('Do you want to start a new game? (y for yes, any for no): ') if answer == 'y': print('New game will start') print('jocuri terminate: ',games_count) elif answer == 'no': stop = True print('GAME OVER') else: print('Wrong answer, please type Yes or No in your next attempt!') stop = True
has answer: http://stackoverflow.com/a/51825961
accepted answer: http://stackoverflow.com/a/51825961

http://stackoverflow.com/comment/123837283
has text: How would this be modified to not send to rules?
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/67557619

http://stackoverflow.com/a/51909208
answers question: http://stackoverflow.com/q/51909070
upvote count: 1
type: Answer
downvote count: 0
score: 1
has body: Why because your conditionals boil down to if (block==456) or (742) or (327): Anything other than a 0 is evaluated to True. In this case, 742 evaluated to True and hence print('You found emerald!') gets executed. Change your tests to either if (block==456) or (block==742) or (block==327) or if block in (456,742,327)

http://stackoverflow.com/q/51894426
tagged with: shapely
tagged with: python
score: 2
type: AnsweredQuestion
upvote count: 2
has body: I need to get a convex_hull of a polygon. I'm using shapely. Nt sure how to apply convex_hull to get the result I need: from shapely.geometry import Polygon p = Polygon(((0,0),(2,0),(2,2),(0,2),(1,1))) The result I need. I don't know how to get the coordingates including repeating the first: In[]: p.convex_hull # How to get the resulted coordinates? Out[]: ((0,0),(2,0),(2,2),(0,2),(0,0)
has answer: http://stackoverflow.com/a/51894927
has title: convex_hull of a geometry
type: Question
accepted answer: http://stackoverflow.com/a/51894927
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/a/51932429
has comment: http://stackoverflow.com/comment/90825175
has comment: http://stackoverflow.com/comment/90825232
upvote count: 3
has comment: http://stackoverflow.com/comment/90825305
has comment: http://stackoverflow.com/comment/90814966
answers question: http://stackoverflow.com/q/51932428
downvote count: 1
score: 2
has comment: http://stackoverflow.com/comment/90825272
has comment: http://stackoverflow.com/comment/90815124
has comment: http://stackoverflow.com/comment/90820207
has comment: http://stackoverflow.com/comment/90824330
has body: UPDATE 2: The numpy solution of @piRSquared is the winner for what I would consider the most common cases. Here is his answers with a minimum modification to assign the columns to the original dataframe (which I did in all my tests, in order to be consistent with the example of the original question) col_mask = df.columns.str.startswith('option') options = df.columns[col_mask] v = np.column_stack([*map(df.get, options)]) df.assign(min_value = np.nanmin(v, axis=1), min_column = options[np.nanargmin(v, axis=1)]) You should be careful if you have a lot of columns (more than 10000), since in these extreme cases results could start changing significatively. UPDATE 1: According to my tests calling min and idxmin separatedly is the fastest you can do based on all the proposed answers. Although it is not at the same time(see direct answer below), you should be better of using DataFrame.lookup on the column indexes (min_column colum), in order to avoid the search for values (min_values). So, instead of traversing the entire matrix - which is O(n*m), you would only traverse the resulting min_column series - which is O(n): df = pd.DataFrame({ 'id': [0,1,2,3,4], 'option_1': [10, np.nan, np.nan, 400, 600], 'option_2': [np.nan, 20, 300, np.nan, 700], 'option_3': [np.nan, 200, 30, np.nan, 50], 'option_4': [110, np.nan, np.nan, 40, 50], }) df['min_column'] = df.filter(like='option').idxmin(1) df['min_value'] = df.lookup(df.index, df['min_column']) Direct answer (not as efficient) Since you asked about how to calculate the values "in the same call" (let's say because you simplified your example for the question), you can try a lambda expression: def min_idxmin(x): _idx = x.idxmin() return _idx, x[_idx] df['min_column'], df['min_value'] = zip(*df.filter(like='option').apply( lambda x: min_idxmin(x), axis=1)) To be clear, although here the 2nd search is removed (replaced by a direct acccess in x[_idx]), this will highly likely take much longer because you are not exploitng the vectori…
has comment: http://stackoverflow.com/comment/90825056
type: Answer

http://stackoverflow.com/q/51918941
tagged with: stream-processing
downvote count: 0
has comment: http://stackoverflow.com/comment/90790323
tagged with: kafka-python
type: AnsweredQuestion
tagged with: apache-kafka-streams
has answer: http://stackoverflow.com/a/77648289
accepted answer: http://stackoverflow.com/a/51919438
favorite count: 0
has answer: http://stackoverflow.com/a/74984926
upvote count: 30
has body: I have used Kafka Streams in Java. I could not find similar API in python. Do Apache Kafka support stream processing in python?
type: Question
has title: Does Kafka python API support stream processing?
tagged with: python
has answer: http://stackoverflow.com/a/66733537
has comment: http://stackoverflow.com/comment/90800494
possible better answer: http://stackoverflow.com/a/66733537
linked to: http://stackoverflow.com/q/60230124
tagged with: apache-kafka
answer count: 4
has answer: http://stackoverflow.com/a/51919438
score: 30

http://stackoverflow.com/a/55133321
has comment: http://stackoverflow.com/comment/131527977
score: 2
downvote count: 0
upvote count: 2
answers question: http://stackoverflow.com/q/51836242
has body: I ran into a similar problem yesterday and found this post, and I believe I know what you are running into. Problem is that while using @tf.custom_gradient, the function that it decorates can have multiple inputs (instead of a list of tensors). Look at the following code(note that it's just a test code with no actual meaning): @tf.custom_gradient def loop1(x,a): def grad(dy): return dy*3,dy*2 n = tf.multiply(x,a) return n,grad By using two inputs x and a, you have to return two gradients respectively in the grad function. dy*3 corresponds to the gradient of x and dy*2 corresponds to the gradient of a. I think in this function the documents make people very confusing, but you can still use multiple inputs, just make sure that you also have the same number of gradients, or else you will run into errors.
type: Answer

http://stackoverflow.com/comment/90778427
type: Comment
has text: I don't think this answers the question.
type: AnswerComment
comment on: http://stackoverflow.com/a/51914216
score: 0

http://stackoverflow.com/a/51955263
upvote count: 1
answers question: http://stackoverflow.com/q/51954975
accepted answer of: http://stackoverflow.com/q/51954975
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/90861516
has body: Generally speaking, Sublime build systems are executed by using the built in exec command. One of the things that the exec command does is manage the contents of the build output panel. That command is what is clearing the contents of the build output panel at the start of every build. There's no direct setting you can apply to have the command keep the previous build output in the panel, however. It's possible to add a target key in a sublime-build file, which tells Sublime to use a command other than exec to execute the build. So you could create a custom command similar to (and/or based on) the default exec command that wouldn't clear the output panel between runs if you wanted to, although that requires some knowledge of how plugins in Sublime work. Potentially there is a package or plugin already available on Package Control that already does this. Depending on how you're executing your builds and what they do, a potential workaround to this that doesn't involve writing a plugin would be to create a build that executes multiple commands one after the other, so that they all execute in a chain from within a single build.
type: Answer
has comment: http://stackoverflow.com/comment/90862114
has comment: http://stackoverflow.com/comment/90887062
has comment: http://stackoverflow.com/comment/90862174
has comment: http://stackoverflow.com/comment/90861968
has comment: http://stackoverflow.com/comment/90885225
score: 1

http://stackoverflow.com/q/51948687
favorite count: 0
has comment: http://stackoverflow.com/comment/90847129
has title: How can I expire entries to Django database cache?
has answer: http://stackoverflow.com/a/51948769
tagged with: python
has answer: http://stackoverflow.com/a/77342395
has comment: http://stackoverflow.com/comment/90847080
possible better answer: http://stackoverflow.com/a/51948769
tagged with: django-cache
tagged with: django
has body: I have a Django application with a registered database cache: CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.db.DatabaseCache', 'LOCATION': 'exchange_rate_cache', } } I want the entries in my cache to expire and be deleted after a week. To delete an entry from the cache all that is needed is the following: from django.core.cache import cache cache.delete(key) However I must only perform this if the entry has been stored in cache for longer than 1 week. How can this be done? Thank you.
has answer: http://stackoverflow.com/a/51948759
type: AnsweredQuestion
upvote count: 5
has comment: http://stackoverflow.com/comment/90847112
type: Question
answer count: 3
score: 5
downvote count: 0
accepted answer: http://stackoverflow.com/a/51948759

http://stackoverflow.com/comment/90611838
type: AnswerComment
score: 0
type: Comment
has text: It's working like a charm! Thank you so much for you time.I really appreciate your help.
comment on: http://stackoverflow.com/a/51828137

http://stackoverflow.com/a/51816382
downvote count: 0
type: Answer
score: 1
answers question: http://stackoverflow.com/q/51812291
upvote count: 1
has body: You don't need to import discord.voice. If you installed discord.py with pip from pypi (pip install discord.py), then you have installed async version of library (not rewrite as mentioned in tags). Check examples of voice usage, and library documentation

http://stackoverflow.com/comment/90578257
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51810242
has text: Was the `jupyter`'s environment active, when you issued `pip install num2words`?

http://stackoverflow.com/a/51951036
downvote count: 0
has body: Just change the .strftime() call to replace : (which cannot be used in file names) with . or something else. fname='Portals Statuses at '+datetime.now().strftime('%Y-%b-%d %H.%M.%S')+'.txt'
type: Answer
accepted answer of: http://stackoverflow.com/q/51949660
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/51949660
type: AcceptedAnswer

http://stackoverflow.com/comment/90597736
score: 0
type: AnswerComment
type: Comment
has text: So that only brings along strings. What I'm trying to do is use the [parameters](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.plot.html) of the pd.DataFrame.plot command. Is that just use **kwargs instead, or is it more complex?
comment on: http://stackoverflow.com/a/51821291

http://stackoverflow.com/comment/90600383
type: QuestionComment
comment on: http://stackoverflow.com/q/51822179
has text: @CBroe I updated the info. Using a system user token with granted access didn't change anything.
score: 0
type: Comment

http://stackoverflow.com/a/51887045
type: Answer
has body: If you want to create 0-list with the length of string letters. letters='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789' chars = [0 for _ in range(len(letters))]
answers question: http://stackoverflow.com/q/51887012
has comment: http://stackoverflow.com/comment/90726662
score: 0
upvote count: 1
downvote count: 1

http://stackoverflow.com/comment/90774176
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/51911742
type: Comment
has text: i have removed now. thanks.

http://stackoverflow.com/comment/90664767
has text: But then it will remove the Type: in the middle. I think a simple string split then slice is good enough for this. Avoids the bugs when you replacing or subsituting characters.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/51856208
type: AnswerComment

http://stackoverflow.com/q/51891743
tagged with: neural-network
has comment: http://stackoverflow.com/comment/90737572
has comment: http://stackoverflow.com/comment/101097549
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/90736637
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/90766209
has body: While working on Udacity's AI course I encountered the error in the title. At first it looks like the image isn't formatted for the model, however the instruction for the course has us format the images using resize, so I get an image dimension of 3x224x224, that's 3 color channels and 224 pixels by 224 pixels. The image array is in the required dimensions, [3,224,224]. Return/Output: (3, 224, 224) (3, 224, 224) torch.Size([1, 3, 224, 224]) Next, I figured it was the model, but when I go back, before the training loop and change the original model to fix this error I get a similar error in revers "up stream". I want this predict function to use my model to predict the category of an image. Posted are: Original classifier Save checkpoint block Process image function Predict image function classifier = nn.Sequential(OrderedDict([ ('fc1', nn.Linear(25088, 500)), ('relu', nn.ReLU()), ('drop', nn.Dropout(0.25)), ('fc2', nn.Linear(500, 102)), ('output', nn.LogSoftmax(dim=1)) ])) model.load_state_dict(state_dict) checkpoint= {'input_size': 672, 'output_size': 102, 'hidden_layers': 224, 'state_dict': model.state_dict()} torch.save(checkpoint, 'checkpoint.pth') def predict(image_path, model, topk=5): ''' Predict the class (or classes) of an image using a trained deep learning model. ''' model= model.cuda() model.eval() # TODO: Implement the code to predict the class from an image file pil_img= Image.open(image_path) #print(pil_img) processed_image= process_image(pil_img) print(processed_image.shape) torch_image= torch.from_numpy(processed_image) torch_image= torch_image.unsqueeze_(0) print(torch_image.shape) torch_image= torch_image.float().to('cuda') output= model.forward(torch_image) #top_k= predict.topk(topk) #print(top_k) return torch_img image_path = 'flowers/test/8/image_03299.jpg' predict(image_path, model, 5) &gt; RuntimeError Traceback (most recent call last) &lt;ipython-input-21-d84c5999ad68&gt; in &lt;module&gt;() 23 24 image_path = 'flowers/test/8/image_03299.jpg…
answer count: 0
tagged with: pytorch
upvote count: 3
has title: RuntimeError: size mismatch, m1: [672 x 224], m2: [672 x 224]
type: Question
score: 3
has comment: http://stackoverflow.com/comment/90737321

http://stackoverflow.com/q/51856012
has answer: http://stackoverflow.com/a/51856268
linked to: http://stackoverflow.com/q/35904584
answer count: 4
score: 2
has answer: http://stackoverflow.com/a/51856119
upvote count: 2
duplicate of: http://stackoverflow.com/q/35904584
has comment: http://stackoverflow.com/comment/90664475
tagged with: python
has comment: http://stackoverflow.com/comment/90664360
has answer: http://stackoverflow.com/a/51856151
type: AnsweredQuestion
has title: .strip('{}:'.format(key)) sometimes strips last characters
tagged with: scrapy
accepted answer: http://stackoverflow.com/a/51856119
possible better answer: http://stackoverflow.com/a/51856151
type: Question
has comment: http://stackoverflow.com/comment/90664683
has comment: http://stackoverflow.com/comment/90664496
downvote count: 0
has comment: http://stackoverflow.com/comment/90664285
has comment: http://stackoverflow.com/comment/90664273
has comment: http://stackoverflow.com/comment/90664290
favorite count: 0
has answer: http://stackoverflow.com/a/51856208
has body: value = div.xpath('normalize-space(.)').extract()[0].strip('{}:'.format(key)).strip() The code above sometimes strips the last character from the word. After removing the code after extract() all the data came back fine but in a list. Example : Unknown from Duration: Unknown turns into unknow Movie from Type: Movie turns into Movi Why does this happen? I tried this in Python shell and it also strips the last characters &gt;&gt;&gt; value = ['Type: Movie'] &gt;&gt;&gt; value[0].strip('{}:'.format('Type')).strip() 'Movi' I expect it to return Movie instead of e getting stripped. It seems that this .strip('{}:'.format('Type')) is responsible. I removed the last strip() it only return data with spaces. Edit: It seems that strip() takes characters in inputted string and remove them instead of removing exact strings. That is why the data came out broken. I think a string split then slice is good. Edit 2: Seems like answers by Austin and Pankaj Singhal is good and bug free for my use case.
has comment: http://stackoverflow.com/comment/90664385

http://stackoverflow.com/comment/90761708
type: QuestionComment
has text: In the script, if you import the PowerShell module containing `Connect-MsolService` does it run then?
comment on: http://stackoverflow.com/q/51905434
score: 0
type: Comment

http://stackoverflow.com/comment/121652190
has text: pip install --upgrade tensorflow --user worked for me
score: 0
comment on: http://stackoverflow.com/q/51912999
type: Comment
type: QuestionComment

http://stackoverflow.com/q/51851802
answer count: 0
score: 1
upvote count: 1
type: Question
downvote count: 0
tagged with: cross-validation
tagged with: training-data
favorite count: 0
has title: Split test and training data on multi-label data for imbalanced data on each class
has body: I would like to split my data in train and test data. My data includes 7 classes and each sample may have different labels so it is a multi-label classification. Also, my data is imbalanced which means the data in one class may have three times more samples than the data in another class. I wanted to do StratifiedKFold however it seems it is not suitable for multi-label classification. Can you please let me know what I can do in this situation? I have looked at this link and this Thanks.
type: UnansweredQuestion
tagged with: classification
tagged with: machine-learning
tagged with: python
has comment: http://stackoverflow.com/comment/90726955

http://stackoverflow.com/a/51897070
score: 1
upvote count: 1
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/51894809
has body: There is nothing to do with my code, but to do with the notebook. If you are using the notebook, run the code below, you will find out that the current loop is running. import asyncio as aio default_loop = aio.get_event_loop() if default_loop.is_running(): print("The current loop is running!") For further proving, if you then run the code below, your notebook will shutdown default_loop.stop() Then the notebook shell would automatically restart, and what was in your current notebook in the memory is gone. If you do this in the python shell, nothing would happen. Therefor, what needed to do is not to use run_until_complete and the task will automatically run through the current loop.

http://stackoverflow.com/comment/90867753
has text: Hi,any updates now? Any more details about your requirements?
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/51941041

http://stackoverflow.com/a/51953786
score: 7
upvote count: 7
accepted answer of: http://stackoverflow.com/q/51953728
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/51953728
has body: You can store Python functions in list as objects (because they're objects) and call them in loop: actions = [chrome.find_element_by_link_text, chrome.find_element_by_class_name] pages = ["Next Page", "pager_next"] for action, page in zip(actions, pages): try: page_element = action(page) except Exception as e: errors_log.add(e)
type: Answer

http://stackoverflow.com/comment/90631902
type: AnswerComment
type: Comment
has text: Really? Numpy is faster? According to my code timer it is the slowest. Or does is it the fastest longterm? (i tried it out on a very small piece of code)
comment on: http://stackoverflow.com/a/51838688
score: 0

http://stackoverflow.com/comment/90580926
has text: @MJP you need to convert your columns to numeric type. Fixed.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/51813023

http://stackoverflow.com/q/51863562
type: UnansweredQuestion
has body: I am working with a database in SQLite and am importing a bunch of csv files into my database. Unfortunately, as far as I can tell there is no way to add a primary key during the import, so I am using a work around in which I read in the csv file and use Pandas' to_sql and then executescript: df = pd.read_csv('filepath.csv', header = 0, index_col = False, encoding = 'UTF-8') df.to_sql(name = 'table1', con = conn, if_exists='replace', index=False) c.executescript(''' PRAGMA foreign_keys=off; BEGIN TRANSACTION; ALTER TABLE table1 RENAME TO table1_alt; /*create a new table with the same column names and types while defining a primary key for the desired column*/ CREATE TABLE Ass_info_table (column1 INT, column2 TEXT, column3 INT, column4 INT, column5 INT, column6 TEXT, column7 TEXT, column8 TEXT, column9 TEXT, column10 TEXT, column11 TEXT, column12 INT, column13 INT, ID INT PRIMARY KEY NOT NULL); INSERT INTO table1 SELECT * FROM table1_alt; DROP TABLE table1_alt; COMMIT TRANSACTION; PRAGMA foreign_keys=on;''') This works just fine, but I have a bunch of csv files that I wanted to glob through and import them all in a loop. My problem is that in order to do that I need to figure out a way to get the names of the tables and columns into that SQL script in a function. That function can go as the table is imported into the database or after, it doesn't really matter. Anyone who has any suggestions, it would be more than welcome!
tagged with: python
has comment: http://stackoverflow.com/comment/90680527
type: Question
has comment: http://stackoverflow.com/comment/90680803
has comment: http://stackoverflow.com/comment/90680435
tagged with: database
score: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/51863734
tagged with: sql
tagged with: sqlite
answer count: 1
has comment: http://stackoverflow.com/comment/90680716
has title: Make a function of SQL script usng Python's execute script
has comment: http://stackoverflow.com/comment/90680060

http://stackoverflow.com/q/51928222
type: UnansweredQuestion
tagged with: python
score: 2
has title: How to compare two HTML files in python and print only the differences?
type: Question
answer count: 2
downvote count: 0
tagged with: comparison
has body: I have two HTML reports generated from sonar showing the issues in my code. Problem Statement: I need to compare two sonar reports and find out the differences i.e. new issues that got introduced. Basically need to find differences in html and print those differences only. I tried a few things: import difflib file1 = open('sonarlint-report.html', 'r').readlines() file2 = open('sonarlint-report_latest.html', 'r').readlines() htmlDiffer = difflib.HtmlDiff() htmldiffs = htmlDiffer.make_file(file1, file2) with open('comparison.html', 'w') as outfile: outfile.write(htmldiffs) Now this gives me a comparison.html which is nothing but two html diff. Doesn't print only the different lines. Should I try HTML parsing and then somehow get the differences only to be printed?
tagged with: http://stackoverflow.com/tag/html
has answer: http://stackoverflow.com/a/51928549
has answer: http://stackoverflow.com/a/51928661
favorite count: 0
upvote count: 2

http://stackoverflow.com/comment/90804739
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/51927204
type: Comment
has text: Hi @Radan I specified in the text that 'progressive' should be the counter of the files you already created, and the app should manage to keep the counter updated, otherwise your solution counting the files is needed.

http://stackoverflow.com/comment/90859464
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/51954466
score: 1
has text: PHP hashes the file content, python the URL.

http://stackoverflow.com/comment/90737147
type: Comment
type: QuestionComment
has text: If all else fails you can `scipy.optimize.minimize` yourself.
score: 0
comment on: http://stackoverflow.com/q/51883058

http://stackoverflow.com/comment/90789261
comment on: http://stackoverflow.com/q/51919417
score: 0
has text: Yes I tried this , unfortunately the same error
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91649368
has text: I tried but it doesn't work, at the end I fixed the problem by use python 3.6
comment on: http://stackoverflow.com/a/52231485
type: AnswerComment
type: Comment
score: 1

http://stackoverflow.com/comment/90816605
type: QuestionComment
comment on: http://stackoverflow.com/q/51933273
has text: `slice()` is intself a function, check it out!
type: Comment
score: 0

http://stackoverflow.com/comment/90563299
score: 0
type: Comment
type: QuestionComment
has text: What do you mean by " Using pip install I can see that library is installed, but I can not find it in virtual environment directory."?
comment on: http://stackoverflow.com/q/51803559

http://stackoverflow.com/comment/90635668
type: AnswerComment
type: Comment
has text: @Chris_Rands.. Ok you win :)
comment on: http://stackoverflow.com/a/51840911
score: 0

http://stackoverflow.com/q/51905306
accepted answer: http://stackoverflow.com/a/51905365
type: AnsweredQuestion
tagged with: bots
score: 0
has body: still very new to programming so in my quest to learn git i am working on getting a chat bot for telegram up and running that i found on a github. iv never used mongoDB or any database and i see i need DB_NAME=os.environ['DB_NAME'] DB_USERNAME=os.environ['DB_USERNAME'] DB_HOST=os.environ['DB_HOST'] DB_PASSWORD=os.environ['DB_PASSWORD'] DB_URL="dbname='"+DB_NAME+"' user='"+DB_USERNAME+"' host='"+DB_HOST+"' password='"+DB_PASSWORD+"'" conn=psycopg2.connect(DB_URL) cur=conn.cursor() cur.execute("SELECT chat_id FROM users") users=cur.fetchall() id_list=[chat_id[0] for chat_id in users] cur.close() conn.close() the DB_NAME=os.environ['DB_NAME'] where does DB_NAME come from and why does os.environ throw an error. im using python 3. the github is here https://github.com/trinhvv/trading-analysis-bot
type: Question
tagged with: mongodb
has answer: http://stackoverflow.com/a/51905365
answer count: 1
has comment: http://stackoverflow.com/comment/90761335
tagged with: telegram
tagged with: python
has title: linking mongoDB to python code?

http://stackoverflow.com/comment/90692173
type: Comment
type: QuestionComment
has text: Added full code :) Any help would be greatly appreciated
score: 0
comment on: http://stackoverflow.com/q/51870321