http://stackoverflow.com/comment/82619122
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47818625
has text: You can just use `clf.score(...)`.
score: 0

http://stackoverflow.com/a/47802891
score: 1
downvote count: 0
upvote count: 1
has body: Here is another way to approach the problem without requiring imports. data = [[2, 6, 8, 9, 8, 6, 3], [4, 8, 10, 10, 7, 5], [5, 6, 8, 8, 9], [4, 6, 7, 8], [3, 5, 9], [3, 6], [4]] data.append([]) for city in range(len(data)): for missing in range(city): data[city].insert(missing, data[missing][city]) data[city].insert(city, 0) data will then contain: [[0, 2, 6, 8, 9, 8, 6, 3], [2, 0, 4, 8, 10, 10, 7, 5], [6, 4, 0, 5, 6, 8, 8, 9], [8, 8, 5, 0, 4, 6, 7, 8], [9, 10, 6, 4, 0, 3, 5, 9], [8, 10, 8, 6, 3, 0, 3, 6], [6, 7, 8, 7, 5, 3, 0, 4], [3, 5, 9, 8, 9, 6, 4, 0]]
answers question: http://stackoverflow.com/q/47802322
type: Answer

http://stackoverflow.com/comment/120782139
type: AnswerComment
comment on: http://stackoverflow.com/a/58616001
has text: Assume we are making recursive async calls inside the `abar()` function. If `abar()` calls another `async` function, ex: `async def abar_1`, should we make the call `run_coroutine(abar_1())` or `await abar_1()`. And would it be same if `abart_1()` calls another async function and so on? I have a library which as await func() definitions, as I understand I have to convert all into `run_coroutine(func())` format in order them to work along with your code. Could there be a wrapper() function for them?
score: 0
type: Comment

http://stackoverflow.com/q/47731284
type: Question
has comment: http://stackoverflow.com/comment/82423946
tagged with: port-scanning
answer count: 2
accepted answer: http://stackoverflow.com/a/47783428
has comment: http://stackoverflow.com/comment/82425355
has body: With this code I can get the hostname, used protocols, ports and states of the ports. How can I also get the service information? for host in nm.all_hosts(): print('----------------------------------------------------') print('Host : %s (%s)' % (host, nm[host].hostname())) print('State : %s' % nm[host].state()) for proto in nm[host].all_protocols(): print('----------') print('Protocol : %s' % proto) lport = list(nm[host][proto].keys()) lport.sort() for port in lport: print('port : %s\tstate : %s' % (port, nm[host][proto][port]['state'])) print('----------')
tagged with: nmap
downvote count: 0
possible better answer: http://stackoverflow.com/a/47740301
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47783428
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/82440685
tagged with: python
has comment: http://stackoverflow.com/comment/82423413
has answer: http://stackoverflow.com/a/47740301
has title: NMAP Service Information
favorite count: 0

http://stackoverflow.com/a/47788757
type: Answer
score: 0
answers question: http://stackoverflow.com/q/47788471
has body: Turns out, although the attribute is just srcset, you need to use data-srcset instead. This line works like a charm. (".item-thumb img").attr('data-srcset') I don't know what is the reason for this behavior though.

http://stackoverflow.com/a/54686250
type: Answer
upvote count: 4
has comment: http://stackoverflow.com/comment/116519874
answers question: http://stackoverflow.com/q/47743692
downvote count: 1
score: 3
has body: Telegram API had updated a method call sendMediaGroup for sending images as album. https://core.telegram.org/bots/api#sendmediagroup Have a look :)

http://stackoverflow.com/comment/82490273
has text: ah you beat me to it
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47764366

http://stackoverflow.com/comment/82498435
type: Comment
type: AnswerComment
has text: This works great. Please change the `index` to `axis` in IDW function and if possible please explain the IDW function in detail. Thanks for the help.
comment on: http://stackoverflow.com/a/47755171
score: 0

http://stackoverflow.com/q/47743714
has title: Error with copying values from one sheet to other
tagged with: excel
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82458255
score: 1
has body: I am trying to copy the values from some cells but it give me this error, i tried even without using the def cell(x,y) but still the same error. This is the error: learn_tar.cell(row=learn_tar, column=1).value = sheet.cell(row=learn_tar, column=1).value AttributeError: 'int' object has no attribute 'cell' Source: import openpyxl def cell(x,y): cell = sheet.cell(row=x,column=y).value return cell; def percentage(percent, whole): return int((percent * whole) / 100.0); ex = openpyxl.load_workbook("Final_excel2.xlsx") sheet = ex.get_sheet_by_name('Sheet1') num = [0,0,0] per = [0,0,0] for row in range(2,4798): if cell(row,1) == '1: Progression': num[0] = num[0] + 1 elif cell(row,1) == '2: Incidence': num[1] = num[1] + 1 elif cell(row,1) == '3: Non-exposed control group': num[2] = num[2] + 1 for column in range(2,49): #doing stuff per[0] = percentage(70,num[0]) per[1] = percentage(70,num[1]) per[2] = percentage(70,num[2]) learn_att = ex.create_sheet('Learn-Att',2) learn_tar = ex.create_sheet('Learn-Tar',3) test_att = ex.create_sheet('Test-Att',4) test_tar = ex.create_sheet('Test-Tar',5) learn_att = 1 learn_tar = 1 test_att = 1 test_tar = 1 for row in range(2,4798): if row&lt;=1391: if row&lt;=974: learn_tar.cell(row=learn_tar, column=1).value = cell(row,1) learn_att+= 1 learn_tar+= 1 else: test_tar.cell(row = test_tar,column = 1).value = cell(row,1) test_att+= 1 test_tar+= 1 for column in range(2,49): if row&lt;=1391: if row&lt;=974: learn_att.cell(row = learn_att,column = column - 1).value = cell(row,column) else: test_att.cell(row = test_att,column = column - 1).value = cell(row,column)
tagged with: openpyxl
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/47743752
upvote count: 1
favorite count: 0
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/47743752

http://stackoverflow.com/comment/82425241
score: 0
type: AnswerComment
has text: You were close! The path you added is `project/tests` but I need to add `project`. Thanks for pushing me in the right direction.
type: Comment
comment on: http://stackoverflow.com/a/47705273

http://stackoverflow.com/q/47731965
accepted answer: http://stackoverflow.com/a/47732063
has answer: http://stackoverflow.com/a/47732071
has comment: http://stackoverflow.com/comment/82424500
score: 1
has answer: http://stackoverflow.com/a/47732063
has answer: http://stackoverflow.com/a/47732079
tagged with: python
possible better answer: http://stackoverflow.com/a/47732071
type: AnsweredQuestion
has body: I am trying to write a program that will print all the primes within a given range. I have written it, the output is almost okay, it prints primes, but for some reason it prints 4, which is not a prime... Any assistant will be most appreciated ! def primes(): start = int(input("Enter the starting number: ")) end = int(input("Enter the ending number: ")) num = 0 i = 0 ctr = 0 for num in range(start,end+1,1): ctr = 0 for i in range(2,num//2,1): if num % i == 0 : ctr = ctr + 1 break if (ctr==0 and num != 1): print(num)
tagged with: for-loop
answer count: 3
downvote count: 0
has title: All prime numbers within a range
upvote count: 1
favorite count: 0
type: Question

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

http://stackoverflow.com/comment/82564353
type: QuestionComment
comment on: http://stackoverflow.com/q/47801548
score: 1
has text: Using `isin` df2.loc[df2.bb.isin(df1.bb),:]
type: Comment

http://stackoverflow.com/comment/82484250
has text: This right here is in Python2, but I will have to right it in Python3 as well.
comment on: http://stackoverflow.com/q/47761398
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/82516028
score: 0
type: Comment
type: AnswerComment
has text: This effectively does `'0'.split(',')`.
comment on: http://stackoverflow.com/a/47777216

http://stackoverflow.com/q/47757248
tagged with: python
has title: Testing TaskResult celery tasks fails
answer count: 0
score: 1
downvote count: 0
tagged with: django-celery
has comment: http://stackoverflow.com/comment/82482863
upvote count: 1
favorite count: 0
type: Question
type: UnansweredQuestion
has body: I am trying to use django_celery_results in my project. I created a task add and a function add_new(x, y) in tasks.py: from celery import shared_task from django_celery_results.models import TaskResult @shared_task(bind=True) def add(self, x, y): return(x, y) def add_new(x, y): task = add.delay(x, y) task_result = TaskResult(task_id=task.task_id) return task_result.as_dict() I am testing my functions in test_tasks.py like this: from tasks import add, add_new from nose.tools import eq_ from django.test import override_settings def test_add_task(): result = add.apply(args=(4, 4,)).get() eq_(result, 8) @override_settings(CELERY_TASK_ALWAYS_EAGER=True) def test_add_new_task(): result = add_new(4, 4) eq_(result['result'], 8) The first test passes, but the second one fails with: AssertionError: None != 8 Looking at the list of TaskResult objects the latest task is not present. Repeating the test, the task_id from the test before is there, but again the latest one is missing and the test fails. So I have the impression that the DB is not updated, even after the task has finished successfully. Trying to execute the functions add and add_new in a shell, it works perfectly fine. Only running the tests with nose do not work. What do I miss?

http://stackoverflow.com/q/47799280
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/47802898
upvote count: 1
tagged with: python
score: 1
has body: I'm creating an email using Python's email package (which is awesome!!). I found out that it's better to encode the headers that have some weird chars in them (accents, etc), like the subject, using email.Header. To do so, I'm doing the following, which is quite easy: Header(value, 'UTF-8').encode() It works great, but it also encode the fields that doesn't necessary require an encoding, lik X-Mailer: My Service that becomes X-Mailer: =?utf-8?q?My_Service?= I find it pretty useless in that case. So my question: Is there a way to encode headers only when it will be useful? I thought about playing with value.encode/decode() with a try/except, and call the Header().encode() function in the except, but I'm hoping there is a cleaner way to do so?
favorite count: 0
linked to: http://stackoverflow.com/q/196345
tagged with: email
has title: How to encode only the required headers in a Mime mail?
type: Question
tagged with: encoding
type: UnansweredQuestion

http://stackoverflow.com/comment/82590414
score: 0
has text: Why are you using pandas and not using `str.replace`?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47814506

http://stackoverflow.com/a/47809517
accepted answer of: http://stackoverflow.com/q/47809064
answers question: http://stackoverflow.com/q/47809064
downvote count: 0
has comment: http://stackoverflow.com/comment/82580211
has body: You're confused between request, which is a module imported at global level from django.http, and self.request, which is an attribute of the view instance. Although your code showed self.request, the error message shows that you were using request originally. You should change it to self.request.
type: AcceptedAnswer
score: 3
upvote count: 3
type: Answer

http://stackoverflow.com/comment/82472472
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47755522
score: 2
has text: Try `tickinterval=10` .

http://stackoverflow.com/comment/82602835
type: Comment
type: QuestionComment
score: 2
has text: I don't understand what would be the desired output, the fun will return a list o boolean? a dict of total:boolean?
comment on: http://stackoverflow.com/q/47820259

http://stackoverflow.com/q/47746758
downvote count: 0
tagged with: python
tagged with: variables
has title: What's the usage of variable_scope with name_or_scope = None
favorite count: 0
type: AnsweredQuestion
tagged with: gpu
score: 1
linked to: http://stackoverflow.com/q/38545362
tagged with: tensorflow
type: Question
has body: When we use variable_scope, we usually set the first argument (name_or_scope) as a name of variable_scope. And when we set the reuse variable as 'True', we can share the variable within the variable_scope. However, I found that inside the tensorflow API (such as Bahdanau attention, or tf.layers.Dense), there are variable scope whose first argument (name_or_scope) is set as None and the second argument (default_name) is set as what we thought as scope name. I checked the code of tf.variable_scope and found that: If name_or_scope is not None, it is used as is. If scope is None, then default_name is used. In that case, if the same name has been previously used in the same scope, it will be made unique by appending _N to it. In this case, I can't use it within for loop because each time the variable_scope is called, it will create new variable_scope with different name. I can't find anywhere explaining this function (I mean name_or_scope set as None). Anyone to explain this?
has comment: http://stackoverflow.com/comment/82453735
upvote count: 1
has comment: http://stackoverflow.com/comment/82455347
has answer: http://stackoverflow.com/a/47754940
accepted answer: http://stackoverflow.com/a/47754940
answer count: 1

http://stackoverflow.com/comment/82382610
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47709579
type: Comment
has text: If my answer helps you or solved your error then please mark (✔) as a answer.

python
tags question: http://stackoverflow.com/q/47785574
tags question: http://stackoverflow.com/q/47727714
tags question: http://stackoverflow.com/q/47740302
tags question: http://stackoverflow.com/q/47847071
tags question: http://stackoverflow.com/q/47850202
tags question: http://stackoverflow.com/q/47785101
tags question: http://stackoverflow.com/q/47840056
tags question: http://stackoverflow.com/q/47773976
tags question: http://stackoverflow.com/q/47823240
tags question: http://stackoverflow.com/q/47729693
tags question: http://stackoverflow.com/q/47742374
tags question: http://stackoverflow.com/q/47748998
tags question: http://stackoverflow.com/q/47707081
tags question: http://stackoverflow.com/q/47698065
tags question: http://stackoverflow.com/q/47829609
tags question: http://stackoverflow.com/q/47757397
tags question: http://stackoverflow.com/q/47757499
tags question: http://stackoverflow.com/q/47791384
tags question: http://stackoverflow.com/q/47802772
tags question: http://stackoverflow.com/q/47744919
tags question: http://stackoverflow.com/q/47812380
tags question: http://stackoverflow.com/q/47836902
tags question: http://stackoverflow.com/q/47800180
tags question: http://stackoverflow.com/q/47815456
tags question: http://stackoverflow.com/q/47758127
tags question: http://stackoverflow.com/q/47700149
tags question: http://stackoverflow.com/q/47842080
tags question: http://stackoverflow.com/q/47779169
tags question: http://stackoverflow.com/q/47833829
tags question: http://stackoverflow.com/q/47716630
tags question: http://stackoverflow.com/q/47724709
tags question: http://stackoverflow.com/q/47778761
tags question: http://stackoverflow.com/q/47725231
tags question: http://stackoverflow.com/q/47808926
tags question: http://stackoverflow.com/q/47826673
tags question: http://stackoverflow.com/q/47808033
tags question: http://stackoverflow.com/q/47805195
tags question: http://stackoverflow.com/q/47798471
tags question: http://stackoverflow.com/q/47703384
tags question: http://stackoverflow.com/q/47794595
tags question: http://stackoverflow.com/q/47780897
tags question: http://stackoverflow.com/q/47777683
tags question: http://stackoverflow.com/q/47832807
tags question: http://stackoverflow.com/q/47742823
tags question: http://stackoverflow.com/q/47809573
tags question: http://stackoverflow.com/q/47764359
tags question: http://stackoverflow.com/q/47853024
tags question: http://stackoverflow.com/q/47849366
tags question: http://stackoverflow.com/q/47756222
tags question: http://stackoverflow.com/q/47730944
tags question: http://stackoverflow.com/q/47732936
tags question: http://stackoverflow.com/q/47800782
tags question: http://stackoverflow.com/q/47719146
tags question: http://stackoverflow.com/q/47779076
tags question: http://stackoverflow.com/q/47834045
tags question: http://stackoverflow.com/q/47702855
tags question: http://stackoverflow.com/q/47745124
tags question: http://stackoverflow.com/q/47783954
tags question: http://stackoverflow.com/q/47824131
tags question: http://stackoverflow.com/q/47741606
tags question: http://stackoverflow.com/q/47711009
tags question: http://stackoverflow.com/q/47838519
tags question: http://stackoverflow.com/q/47735413
tags question: http://stackoverflow.com/q/47731479
tags question: http://stackoverflow.com/q/47804100
tags question: http://stackoverflow.com/q/47707108
tags question: http://stackoverflow.com/q/47779927
tags question: http://stackoverflow.com/q/47851080
tags question: http://stackoverflow.com/q/47742258
tags question: http://stackoverflow.com/q/47793768
tags question: http://stackoverflow.com/q/47820798
tags question: http://stackoverflow.com/q/47715950
tags question: http://stackoverflow.com/q/47739652
tags question: http://stackoverflow.com/q/47765771
tags question: http://stackoverflow.com/q/47705573
tags question: http://stackoverflow.com/q/47754654
tags question: http://stackoverflow.com/q/47819550
tags question: http://stackoverflow.com/q/47716768
tags question: http://stackoverflow.com/q/47734342
tags question: http://stackoverflow.com/q/47737636

http://stackoverflow.com/q/47816303
answer count: 0
score: 1
has body: I followed the instructions from here. Bazel version installed : 0.4.5 Tensorflow version installed : 1.0.0 I get the following when I import tensorflow Python 2.7.9 (default, Sep 17 2016, 20:26:04) [GCC 4.9.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import tensorflow Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "tensorflow/__init__.py", line 24, in &lt;module&gt; from tensorflow.python import * File "tensorflow/python/__init__.py", line 72, in &lt;module&gt; raise ImportError(msg) ImportError: Traceback (most recent call last): File "tensorflow/python/__init__.py", line 61, in &lt;module&gt; from tensorflow.python import pywrap_tensorflow ImportError: cannot import name pywrap_tensorflow Failed to load the native TensorFlow runtime. See https://github.com/tensorflow/tensorflow/blob/master/tensorflow/g3doc/get_started/os_setup.md#import_error for some common reasons and solutions. Include the entire stack trace above this error message when asking for help. &gt;&gt;&gt;
downvote count: 0
upvote count: 1
tagged with: raspberry-pi3
duplicate of: http://stackoverflow.com/q/35953210
tagged with: tensorflow
favorite count: 0
type: Question
tagged with: raspberry-pi
type: UnansweredQuestion
has title: Errors on importing tensorflow on raspberry pi 3
tagged with: python
linked to: http://stackoverflow.com/q/35953210

http://stackoverflow.com/comment/82665202
type: Comment
comment on: http://stackoverflow.com/a/47850062
score: 0
type: AnswerComment
has text: The logic of the `islower` test is wrong. The password is strongest when it contains a mixture of upper, lower, and digits. That is: the bigger the pool of possible characters, the harder the password is to crack. Ideally, there should be a check for punctuation, as well.

http://stackoverflow.com/comment/82523563
type: QuestionComment
type: Comment
has text: there are probably blank lines in your csv file.
score: 0
comment on: http://stackoverflow.com/q/47781076

http://stackoverflow.com/a/47782333
accepted answer of: http://stackoverflow.com/q/47782007
upvote count: 2
has body: The # is treated as a comment flag. Quoting doesn't make a difference: In [345]: txt=b'''1,85,104,2,"C" ...: 2,71,82,2,"C#" ...: 3,67,73,2,"D" ...: 4,105,108,2,"D#" ...: 5,103,100,2,"E"''' In [346]: In [346]: np.genfromtxt(txt.splitlines(),delimiter=',',dtype=None) Out[346]: array([(1, 85, 104, 2, b'"C"'), (2, 71, 82, 2, b'"C'), (3, 67, 73, 2, b'"D"'), (4, 105, 108, 2, b'"D'), (5, 103, 100, 2, b'"E"')], dtype=[('f0', '&lt;i4'), ('f1', '&lt;i4'), ('f2', '&lt;i4'), ('f3', '&lt;i4'), ('f4', 'S3')]) Turning off comments: In [347]: np.genfromtxt(txt.splitlines(),delimiter=',',dtype=None, comments=None ...: ) Out[347]: array([(1, 85, 104, 2, b'"C"'), (2, 71, 82, 2, b'"C#"'), (3, 67, 73, 2, b'"D"'), (4, 105, 108, 2, b'"D#"'), (5, 103, 100, 2, b'"E"')], dtype=[('f0', '&lt;i4'), ('f1', '&lt;i4'), ('f2', '&lt;i4'), ('f3', '&lt;i4'), ('f4', 'S4')])
downvote count: 0
answers question: http://stackoverflow.com/q/47782007
type: Answer
score: 2
type: AcceptedAnswer

http://stackoverflow.com/comment/82602666
has text: Thanks, see my reply also, this bug is fixed, but seems only for Django 2.0
comment on: http://stackoverflow.com/a/47820193
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47708238
has title: Django didn't save form to database
tagged with: django-forms
downvote count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/47708521
type: Question
has comment: http://stackoverflow.com/comment/82377658
has body: How can I save a form to the database with an image? It all works fine if I comment the line imagen = modelImageField so I think there is the problem in model.py. All the other parts of the form save to the database. If I comment out the line, no errors show, but the form is not saved to the database. Can anyone help me with this? This is my View Views.py class donacion_Form(CreateView): template_name='App/donacion.html' model=donacion fields="__all__" success_url=reverse_lazy('mi_donacion') This is the form Forms.py class donacion_Form(forms.ModelForm): class Meta: model=donacion fields="__all__" This is the Model Model.py class donacion(models.Model): nombre=models.CharField(max_length=50) estados = ( ('EC', 'Excelente condicion'), ('BP', 'Buena presentacin'), ('PD', 'Presenta desgaste'), ('MD', 'Muy desgastada'), ) prendas = ( ('TP', 'Tops'), ('BT', 'Bottoms'), ('CZ', 'Calzado'), ('AS', 'Accesorios'), ('CM', 'Chamarras'), ) generos = ( ('MJR', 'Mujer'), ('HMB', 'Hombre'), ('UXA', 'Unisex adulto'), ('CHO', 'Chicos'), ('CHA', 'Chicas'), ('UXI', 'Unisex infantil'), ('BEB', 'bebes'), ) tallas = ( ('EC', 'XS'), ('CH', 'S'), ('MD', 'M'), ('GD', 'L'), ('EG', 'XL'), ('SG', 'XXL'), ) autor=models.CharField(max_length=25) estado = models.CharField( max_length=2, choices=estados, default='EC', ) genero = models.CharField( max_length=3, choices=generos, default='UXA', ) prenda = models.CharField( max_length=2, choices=prendas, default='TP', ) talla = models.CharField( max_length=2, choices=tallas, default='CH', ) direccion = models.CharField(max_length=500) /*if i comment this line imagen work fine*/ imagen = models.ImageField(null = False,blank=False) descrip = models.TextField() def __str__(self): return '{}'.format(self.autor)
has answer: http://stackoverflow.com/a/47708521
has comment: http://stackoverflow.com/comment/82382871
tagged with: django
tagged with: django-models
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/82380523
type: AnsweredQuestion
upvote count: 0
answer count: 1

http://stackoverflow.com/comment/82579048
has text: Thanks you so much Furas, i'm a real begginer at scrapy so nothing is obvious for me ;) I will try your solution and see how can i iterate it in my spider. Again, thanks you a lot.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47761077
type: Comment

http://stackoverflow.com/comment/82433891
has text: Thanks, yes the file is intend to be read by external app. Can we also do same with CSR format ? 1) isn't storing so many list in memory, kill the python interpreter memory ?
score: 0
comment on: http://stackoverflow.com/a/47731564
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47822233
type: Question
has title: Pygame: Click event is affecting every sprite to the left of them
tagged with: python
tagged with: pygame
has body: I have an array with all the sprites inside of them, and in the loop, if the sprite is clicked then the sprite is killed. If I click the sprites from left to right, everything is fine. They are cleared one by one independent of each other. But, if I click the sprite most right of the screen, it kills everything to the left of it. Full code because I've no idea where the important region might be. import pygame from pygame.locals import * import random pygame.init() level = 1 cooldown = 1000 class test(pygame.sprite.Sprite): def __init__(self, w): super().__init__() self.image = pygame.Surface([600,600]) self.rect = self.image.get_rect() self.image = pygame.image.load("index.png") self.image = pygame.transform.scale(self.image, (w,w)) self.last = pygame.time.get_ticks() screen = pygame.display.set_mode([600,600]) clock = pygame.time.Clock() background = pygame.Surface(screen.get_size()) background.fill([0,0,0]) rX = random.randint(0, 500) rX2 = random.randint(0, 500) screen.blit(background, (0,0)) sp = [] all_sprites_list = pygame.sprite.Group() a_1 = test(random.randint(40,60)) a_1.rect.x = rX a_1.rect.y = -400 sp.append(a_1) all_sprites_list.add(a_1) #The steps for a_1 is repeated to make variables a_2, a_3, a_4... Running = True while Running: now = pygame.time.get_ticks() for x in sp: x.rect.y+=level m_pos = pygame.mouse.get_pos() for event in pygame.event.get(): if event.type == QUIT: Running = False if event.type == MOUSEBUTTONDOWN: for s in sp: if s.rect.collidepoint(m_pos): s.kill() pygame.display.flip() all_sprites_list.clear(screen, background) all_sprites_list.draw(screen) all_sprites_list.update() clock.tick(60)
has comment: http://stackoverflow.com/comment/82614923
has comment: http://stackoverflow.com/comment/82610646
has answer: http://stackoverflow.com/a/47824307
accepted answer: http://stackoverflow.com/a/47824307
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82610975
upvote count: 1
score: 1
answer count: 1
downvote count: 0
tagged with: sprite
favorite count: 0

http://stackoverflow.com/comment/82429239
has text: Interesting have a point there, I totally forgot that the keys won't be sorted. Have edited the code for that.Thanks for pointing that out.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47734306
type: AnswerComment

http://stackoverflow.com/comment/82673758
comment on: http://stackoverflow.com/q/47854863
has text: These modes are not specific to PNG images. They are just different ways to represent image data in digital form.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/82624186
type: QuestionComment
has text: @skrubber: yes, that is the table
comment on: http://stackoverflow.com/q/47830384
score: 0
type: Comment

http://stackoverflow.com/q/47798187
tagged with: transpose
tagged with: python
has title: convert multiple rows to columns in Linux using Python or Bash
score: 0
tagged with: bash
answer count: 0
linked to: http://stackoverflow.com/q/47152691
has comment: http://stackoverflow.com/comment/82562756
tagged with: awk
has comment: http://stackoverflow.com/comment/82557237
has body: I have the input as below Input Name1 Subject1 Marks Name1 Subject2 Marks Name2 Subject1 Marks Name2 Subject2 Marks and want to convert to output as below Output Name Subject1 Subject2 Name1 Marks Marks Name2 Marks Marks
type: Question
duplicate of: http://stackoverflow.com/q/47152691
has comment: http://stackoverflow.com/comment/82557519
tagged with: sed
type: UnansweredQuestion

http://stackoverflow.com/a/47782793
has comment: http://stackoverflow.com/comment/118226592
downvote count: 0
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47781125
has comment: http://stackoverflow.com/comment/82560804
score: 1
type: Answer
answers question: http://stackoverflow.com/q/47781125
has body: There are two issues here. The first one is understandable. As the documentation of figure.add_axes says: If the figure already has an axes with the same parameters, then it will simply make that axes current and return it. This behavior has been deprecated as of Matplotlib 2.1. Meanwhile, if you do not want this behavior (i.e., you want to force the creation of a new Axes), you must use a unique set of args and kwargs. The axes label attribute has been exposed for this purpose: if you want two axes that are otherwise identical to be added to the figure, make sure you give them unique labels. This means that if you call plt.axes([0, 0, 1, 1]) several times, it will not create a new axes after all. The solution would be to add a label, e.g. by supplying the loop variable i together with the data to the function and calling plt.axes([0, 0, 1, 1], label=str(i)) Unfortunately this is not enough and the above will still not work as expected. This is not understandable to me. However by trial and error one may find that using different coordinates for the initial position of the axes makes this work. Below I'm using ax2 = plt.axes([0.0, 0.0, 0.1, 0.1], label=str(i)), but e.g. [0.2, 0.0, 0.5, 0.1] seems to work as well, while [0.2, 0.2, 0.5, 0.1] does not work. Even more strange, [0.0, 0.2, 0.5, 0.1] would create an inset in the second and third plot, but not in the first. All of this seems a bit arbitrary, but sufficient for a solution: import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1.inset_locator import InsetPosition def test(ax_main, pos, Data,i): ax2 = plt.axes([0.0, 0.0, 0.1, 0.1], label=str(i)) ip = InsetPosition(ax_main, pos) ax2.set_axes_locator(ip) ax2.plot(Data) for i in range(3): ax=plt.subplot(1,3,i+1) test(ax, [.3,.3,.6,.6], [1,2], i) plt.show()

http://stackoverflow.com/a/47842615
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/47839705
type: Answer
has body: You can simply use enumerate : One line solution: a=[12,31,45,67,100,101] target=101 print([i if j==target else -1 for i,j in enumerate(a)]) output: [-1, -1, -1, -1, -1, 5] Detailed solution: Above list comprehension is same as : final_result=[] for i,j in enumerate(a): if j==target: final_result.append(i) else: final_result.append(-1) print(final_result)
downvote count: 0

http://stackoverflow.com/comment/89025653
comment on: http://stackoverflow.com/q/47745541
type: Comment
type: QuestionComment
score: 0
has text: Hello A. Hendry, did you make it work? I'm trying to remove shadow from some leaves to segment it.

http://stackoverflow.com/q/47853828
has title: Sort list of lists first by year, then by month
tagged with: python
tagged with: sorting
has body: I have a list of lists that looks something like this: dateList = [['2014', '4'], ['2015', '6'], ['2017', '6'], ['2016', '2'], ['2016', '3'], ['2017', '9'], ['2016', '6'], ['2017', '3'], ['2014', '8'], ['2014', '10'], ['2017', '10'], ['2014', '9'], ['2014', '3'], ['2015', '11'], ['2015', '2']] I have been trying to sort it by year first, and then by month. I've been successful in sorting it by year using sortedList = sorted(dateList, key = lambda x: int(x[0])) However, I can't figure out a way to sort it by month afterwards while keeping the years in ascending order.
has answer: http://stackoverflow.com/a/47853853
has comment: http://stackoverflow.com/comment/82671730
linked to: http://stackoverflow.com/q/5212870
type: AnsweredQuestion
tagged with: list
answer count: 2
has comment: http://stackoverflow.com/comment/82671773
has comment: http://stackoverflow.com/comment/82671762
duplicate of: http://stackoverflow.com/q/5212870
upvote count: 3
downvote count: 0
favorite count: 0
type: Question
tagged with: python-3.x
score: 3
possible better answer: http://stackoverflow.com/a/47853866
accepted answer: http://stackoverflow.com/a/47853853
has answer: http://stackoverflow.com/a/47853866

http://stackoverflow.com/comment/82545500
has text: The characters U+D86B and friends are surrogate characters, ie. (phony) codepoints that are used by UTF16 to encode (actual) codepoints above U+FFFF. String `a` has thus not been properly decoded. As @snakecharmerb noted, recent Python versions see this string as broken; however Python 2.7 seems to allow this.
type: Comment
score: 6
comment on: http://stackoverflow.com/q/47791990
type: QuestionComment

http://stackoverflow.com/comment/82676238
comment on: http://stackoverflow.com/q/47855758
score: 0
type: Comment
type: QuestionComment
has text: Wavelength for visible light is usually given in nm, I understand from your definition of `Lab` that you stick to this convention(though it is barely in the visible range). Never heard of this Sellmeier equation, but [Wikipedia says](https://en.wikipedia.org/wiki/Sellmeier_equation) that the coefficients are given for wavelengths in µm. You should convert your wavelengths with `lam /= 1000` into µm. I would do my calculation first with BK7 values and compare my results with those in the Wikipedia diagram.

http://stackoverflow.com/q/47710022
tagged with: anaconda
has answer: http://stackoverflow.com/a/48825297
tagged with: matplotlib
has answer: http://stackoverflow.com/a/50286101
tagged with: python
has comment: http://stackoverflow.com/comment/84844448
has comment: http://stackoverflow.com/comment/82495614
type: Question
upvote count: 9
score: 9
downvote count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/56490314
has title: import matplotlib.pyplot as plt, ImportError: libGL.so.1: cannot open shared object file: No such file or directory
favorite count: 0
has body: import matplotlib.pyplot as plt is erroring with python2.7, anaconda3. The error is ImportError: libGL.so.1: cannot open shared object file: No such file or directory Error report Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; File "/serving/anaconda3/envs/python27/lib/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 "/serving/anaconda3/envs/python27/lib/python2.7/site-packages/matplotlib/backends/__init__.py", line 32, in pylab_setup globals(),locals(),[backend_name],0) File "/serving/anaconda3/envs/python27/lib/python2.7/site-packages/matplotlib/backends/backend_qt5agg.py", line 16, in &lt;module&gt; from .backend_qt5 import QtCore File "/serving/anaconda3/envs/python27/lib/python2.7/site-packages/matplotlib/backends/backend_qt5.py", line 26, in &lt;module&gt; import matplotlib.backends.qt_editor.figureoptions as figureoptions File "/serving/anaconda3/envs/python27/lib/python2.7/site-packages/matplotlib/backends/qt_editor/figureoptions.py", line 20, in &lt;module&gt; import matplotlib.backends.qt_editor.formlayout as formlayout File "/serving/anaconda3/envs/python27/lib/python2.7/site-packages/matplotlib/backends/qt_editor/formlayout.py", line 56, in &lt;module&gt; from matplotlib.backends.qt_compat import QtGui, QtWidgets, QtCore File "/serving/anaconda3/envs/python27/lib/python2.7/site-packages/matplotlib/backends/qt_compat.py", line 128, in &lt;module&gt; from PyQt5 import QtCore, QtGui, QtWidgets ImportError: libGL.so.1: cannot open shared object file: No such file or directory conda list is $conda list cairo 1.14.8 0 defaults certifi 2016.2.28 py27_0 defaults cycler 0.10.0 py27_0 defaults dbus 1.10.20 0 defaults expat 2.1.0 0 defaults fontconfig 2.12.1 3 defaults freetype 2.5.5 2 defaults functools32 3.2.3.2 py27_0 defaults glib 2.50.2 1 defaults gst-plugins-base 1.8.0 0 defaults gstreamer 1.8.0 0 defaults harfbuzz 0…
answer count: 3

http://stackoverflow.com/comment/82404008
comment on: http://stackoverflow.com/q/47721524
has text: @quamrana but a realistic make-work function should also return a result. I'm working on adapting the code so that the function is mapped across the input list. Then serial/multiprocessing can be assessed fairly.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/47825840
answers question: http://stackoverflow.com/q/47825709
has body: Here's a pivot_table solution, should be really fast - df = df.pivot_table( index=['shop_id', 'item_id'], columns=['date'], values=['sales'], fill_value=0)\ .add_prefix('date_').reset_index() df shop_id item_id date_sales date date_0 date_1 date_2 date_3 0 0 19 1 0 13 11 1 1 19 0 3 0 0 Make sure you test out both solutions on your data before deciding which one to use!
type: Answer
score: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/47836772
has title: How to pass an array as argument (in Python) when solving ODE by odeint function
favorite count: 0
type: Question
has body: My ODE is given as Mx''+Lx'+f(x)=0 where f(x) is a polynomial function. Please look at my FULL CODE where I defined the differential equation in a function namely 'diff'. Then I use 'odeint' which calls 'diff' along with the necessary arguments to solve the differential equaion. Now I consider f(x)=ax. Here I have to pass three parameters in total (M,L,a) as the argument to the 'diff' function. As a matter of fact the code works if I write: (see full code) sol = odeint(diff, y0, t, args=(M,L, a)) But when f(x) is a polynomial up to 10 power of 'x', then the parameter list becomes too long. Therefore I want to put all the parameters in an array and then pass that array as argument. I tried in this way: def diff(y, t, inertia): M=inertia[0] L=inertia[1] a=inertia[2] x,v = y dydt = [v, (-L*v - a*x)/M] return dydt M=5 L = 0.5 a = 5.0 Inertia=(M,L,a) sol = odeint(diff, y0, t, args=Inertia) But this approach doen't work. It says 'TypeError: diff() takes 3 positional arguments but 5 were given'. How can I can I make this approach work, or how to send a list of parameters as argument? Full Code: import numpy as np from scipy.integrate import odeint import matplotlib.pyplot as plt def diff(y, t, M, L, a): x,v = y dydt = [v, (-L*v - a*x)/M] return dydt M=5 L = 0.5 a = 5.0 #Inertia=(M,L,a) #But I cant pass the 'Inertia' as an argument y0 = [- 0.1, 0.0] t = np.linspace(0, 10, 101) sol = odeint(diff, y0, t, args=(M,L, a)) plt.plot(t, sol[:, 0], 'b', label='x(t)') plt.plot(t, sol[:, 1], 'g', label='v(t)') plt.legend(loc='best') plt.show()
answer count: 2
has answer: http://stackoverflow.com/a/47837124
accepted answer: http://stackoverflow.com/a/47837195
upvote count: 1
tagged with: python
tagged with: ode
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/47837124
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/47837195

http://stackoverflow.com/comment/85479120
has text: I get a very similar error - I wish I could find a _working_ Python example to see what I'm doing wrong - I suspect the JSON is missing some braces or header or something.
type: QuestionComment
comment on: http://stackoverflow.com/q/47803765
score: 0
type: Comment

http://stackoverflow.com/q/47769453
upvote count: 19
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/47769479
favorite count: 0
type: Question
has body: I have a DataFrame in Pandas PRICE Name PER CATEGORY STORENAME 0 9.99 MF gram Indica Store1 1 9.99 HY gram Herb Store2 2 9.99 FF gram Herb Store2 What I want to do is split these into multiple data frames to have unique names, then in those split to category. Current code: names = df['STORENAME'].unique().tolist() #find unique values store1 = df[df['STORENAME']==names[0]] store2 = df[df['STORENAME']==names[1]] This code works perfectly but I am wondering if there is a Pythonic way since the number of stores may change. This is needed to plot the difference in prices in categories in stores. Thanks!
score: 19
has answer: http://stackoverflow.com/a/47769479
tagged with: pandas
has title: PANDAS split dataframe to multiple by unique values rows
tagged with: dataframe
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/47790528
downvote count: 0
upvote count: 1
favorite count: 0
type: AnsweredQuestion
has body: I'm new to Pandas and I have a data frame of this form: date category value 0 2017-11-30 13:58:57 A 901 1 2017-11-30 13:59:41 B 905 2 2017-11-30 13:59:41 C 925 First column is a date, second column is categorical with known three categories. It was generated by: import pandas as pd df = pd.DataFrame.from_items( [('date', ['2017-11-30 13:58:57', '2017-11-30 13:59:41', '2017-11-30 13:59:41']),('category',['A','B', 'C']),("value", [901, 905, 925])]) df['date'] = pd.to_datetime(df['date']) df['category'] = df['category'].astype('category') The problem is that for each date, not all categories are there. I wish to add the missing categories with missing values to get: date category value 0 2017-11-30 13:58:57 A 901 1 2017-11-30 13:58:57 B nan 2 2017-11-30 13:58:57 C nan 3 2017-11-30 13:59:41 A nan 4 2017-11-30 13:59:41 B 905 5 2017-11-30 13:59:41 C 925 Is there a built-in way to do so without iterating the rows?
tagged with: pandas
score: 1
has title: Adding missing values in Pandas by categories
tagged with: python
has answer: http://stackoverflow.com/a/47790602
type: Question
answer count: 1
accepted answer: http://stackoverflow.com/a/47790602

http://stackoverflow.com/comment/82613577
score: 0
has text: It still doesn't work for me Max, I'm getting rows with Y and F combinations even after applying the above logic.
type: Comment
comment on: http://stackoverflow.com/a/47822405
type: AnswerComment

http://stackoverflow.com/comment/82471801
type: Comment
type: QuestionComment
has text: Any matrix or some uniformly-sampled matrix?
comment on: http://stackoverflow.com/q/47754210
score: 0

http://stackoverflow.com/q/47821554
answer count: 1
type: Question
type: UnansweredQuestion
tagged with: python
tagged with: weka
score: 0
has body: I have used the Weka plugin in Fiji to create a classifier and it gives back an arff file and a .model file (this is the classifier). Do you know if I can implement this into python for use in SVM somehow? This is how I am using Weka in the image.
has answer: http://stackoverflow.com/a/47831120
has title: Weka plugin to Fiji can it be used in python?

http://stackoverflow.com/q/47830176
has title: How can I find the angle between two contours in Python+Opencv
accepted answer: http://stackoverflow.com/a/47830663
type: AnsweredQuestion
tagged with: angle
has answer: http://stackoverflow.com/a/47830663
score: 1
answer count: 1
downvote count: 0
upvote count: 1
has body: I'm trying to find the angle between the two contours in this image. However the center point of the contour far right is twitching all over the place. I'm using this code: if len(contours) &gt; 1: cnt1 = contours[0] cnt2 = contours[1] area = cv2.contourArea(cnt1) M1 = cv2.moments(cnt1) M2 = cv2.moments(cnt2) if area &gt; 30: cv2.drawContours(frame, contours, -1, (0, 255, 255), 3) X1_px = int(M1['m10'] / M1['m00']) Y1_px = int(M1['m01'] / M1['m00']) X2_px = int(M2['m10'] / M1['m00']) Y2_px = int(M2['m01'] / M1['m00']) cv2.circle(frame, (X1_px, Y1_px), 3, (0, 0, 255), -1) cv2.circle(frame, (X2_px, Y2_px), 3, (0, 0, 255), -1) if (X2_px-X1_px) != 0: angle = math.atan((Y2_px-Y1_px)/(X2_px-X1_px)) angle = int(angle * (180 / math.pi)) print(angle) I think the cnt1, cnt2 part of my code is causing the problem, I don't know how openCV orders the contours in this array. Can anyone help me fix this code?
favorite count: 0
type: Question
tagged with: opencv
tagged with: python

http://stackoverflow.com/q/47745749
answer count: 1
downvote count: 0
tagged with: url
has body: I have this P2P python code, and I am trying to send a POST request from it to flask: On my P2P side I have: ... for reply in con: jsonData = json.loads(reply) print(jsonData) print(type(jsonData) is dict, tuple) data = urlencode(jsonData) print(data + " : urlencode") data = data.encode() print(data.__class__) req = urllib.request.Request("http://0.0.0.0:5000/validate", data) response = urllib.request.urlopen(req) #res = response.read() print(response.read().decode('utf8') + " : response in alice") For my flask code I have: @app.route('/validate', methods=['POST']) def validate(): print(request.args) request args is always output as: ImmutableMultiDict([]) The output for the P2P side is: {'index': 2043, 'message': 'New Block Forged', 'previous_hash': 'fa4a49cd092869db788490e79a933e7a45107ce513523500e5cd9c85e25426de', 'proof': 168158, 'transactions': [{'amount': 1, 'recipient': '6760d061731c493e94897164c2362476', 'sender': '0'}]} True &lt;class 'tuple'&gt; index=2043&amp;message=New+Block+Forged&amp;previous_hash=fa4a49cd092869db788490e79a933e7a45107ce513523500e5cd9c85e25426de&amp;proof=168158&amp;transactions=%5B%7B%27amount%27%3A+1%2C+%27recipient%27%3A+%276760d061731c493e94897164c2362476%27%2C+%27sender%27%3A+%270%27%7D%5D : urlencode &lt;class 'bytes'&gt; { "add": true } : response in alice As you can see, the data for urllib.request.urlopen looks correct. Why isn't it getting through to the flask side?
tagged with: request
tagged with: flask
has comment: http://stackoverflow.com/comment/82452049
accepted answer: http://stackoverflow.com/a/47747484
has comment: http://stackoverflow.com/comment/82451753
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47747484
has title: Python - urllib.request and flask
tagged with: python
favorite count: 0
tagged with: post
type: Question
score: 2
has comment: http://stackoverflow.com/comment/82451980
upvote count: 2

http://stackoverflow.com/comment/82595762
has text: I beg to differ about there not being a similar question: https://stackoverflow.com/q/14827650/2988730. In fact the other poster was able to find more docs than you were apparently.
type: Comment
comment on: http://stackoverflow.com/q/47817024
score: 0
type: QuestionComment

django-models
tag name: django-models
tags question: http://stackoverflow.com/q/47716033
tags question: http://stackoverflow.com/q/47724666
tags question: http://stackoverflow.com/q/47758585
tags question: http://stackoverflow.com/q/47851314
tags question: http://stackoverflow.com/q/47801453
tags question: http://stackoverflow.com/q/47744014
tags question: http://stackoverflow.com/q/47707377
tags question: http://stackoverflow.com/q/47820798
tags question: http://stackoverflow.com/q/47804965
tags question: http://stackoverflow.com/q/47727735
tags question: http://stackoverflow.com/q/47742878
tags question: http://stackoverflow.com/q/47790517
tags question: http://stackoverflow.com/q/47702625
tags question: http://stackoverflow.com/q/47821864
tags question: http://stackoverflow.com/q/47736769
tags question: http://stackoverflow.com/q/47778513
tags question: http://stackoverflow.com/q/47727525
tags question: http://stackoverflow.com/q/47725669
tags question: http://stackoverflow.com/q/47780489
tags question: http://stackoverflow.com/q/47834997
tags question: http://stackoverflow.com/q/47705427
tags question: http://stackoverflow.com/q/47718382
tags question: http://stackoverflow.com/q/47739057
tags question: http://stackoverflow.com/q/47771940
tags question: http://stackoverflow.com/q/47787991
tags question: http://stackoverflow.com/q/47846311
tags question: http://stackoverflow.com/q/47804372
tags question: http://stackoverflow.com/q/47756222
tags question: http://stackoverflow.com/q/47819550
tags question: http://stackoverflow.com/q/47737061
tags question: http://stackoverflow.com/q/47708238
tags question: http://stackoverflow.com/q/47711724
tags question: http://stackoverflow.com/q/47741486
tags question: http://stackoverflow.com/q/47823045
tags question: http://stackoverflow.com/q/47852845
tags question: http://stackoverflow.com/q/47813447
tags question: http://stackoverflow.com/q/47813315
tags question: http://stackoverflow.com/q/47842654
type: Tag
tags question: http://stackoverflow.com/q/47800768
tags question: http://stackoverflow.com/q/47830633
tags question: http://stackoverflow.com/q/47720488

http://stackoverflow.com/q/47818314
possible better answer: http://stackoverflow.com/a/47818902
has title: Split lists into multiple columns in a pandas DataFrame
tagged with: multiple-columns
favorite count: 0
has comment: http://stackoverflow.com/comment/82599925
has answer: http://stackoverflow.com/a/47818718
type: Question
tagged with: pivot
linked to: http://stackoverflow.com/q/52028442
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/54492607
has comment: http://stackoverflow.com/comment/82598929
has answer: http://stackoverflow.com/a/47818902
has body: I have a source system that gives me data like this: Name |Hobbies ---------------------------------- "Han" |"Art;Soccer;Writing" "Leia" |"Art;Baking;Golf;Singing" "Luke" |"Baking;Writing" Each hobby list is semicolon delimited. I want to turn this into a table like structure with a column for each hobby and a flag to indicate if a person selected that hobby: Name |Art |Baking |Golf |Singing |Soccer |Writing -------------------------------------------------------------- "Han" |1 |0 |0 |0 |1 |1 "Leia" |1 |1 |1 |1 |0 |0 "Luke" |0 |1 |0 |0 |0 |1 Here's code to generate the sample data in a pandas dataframe: &gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; df = pd.DataFrame( ... [ ... {'name': 'Han', 'hobbies': 'Art;Soccer;Writing'}, ... {'name': 'Leia', 'hobbies': 'Art;Baking;Golf;Singing'}, ... {'name': 'Luke', 'hobbies': 'Baking;Writing'}, ... ] ... ) &gt;&gt;&gt; df hobbies name 0 Art;Soccer;Writing Han 1 Art;Baking;Golf;Singing Leia 2 Baking;Writing Luke Right now, I'm using the following code to get the data into a datatrame that has the structure I want, but it is really slow (my actual data set has about 1.5 million rows): &gt;&gt;&gt; df2 = pd.DataFrame(columns=['name', 'hobby']) &gt;&gt;&gt; &gt;&gt;&gt; for index, row in df.iterrows(): ... for value in str(row['hobbies']).split(';'): ... d = {'name':row['name'], 'value':value} ... df2 = df2.append(d, ignore_index=True) ... &gt;&gt;&gt; df2 = df2.groupby('name')['value'].value_counts() &gt;&gt;&gt; df2 = df2.unstack(level=-1).fillna(0) &gt;&gt;&gt; &gt;&gt;&gt; df2 value Art Baking Golf Singing Soccer Writing name Han 1.0 0.0 0.0 0.0 1.0 1.0 Leia 1.0 1.0 1.0 1.0 0.0 0.0 Luke 0.0 1.0 0.0 0.0 0.0 1.0 Is there a more efficient way to do this?
accepted answer: http://stackoverflow.com/a/47818718
linked to: http://stackoverflow.com/q/37600711
tagged with: pandas
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/34376053
score: 3
upvote count: 3
answer count: 3
downvote count: 0

http://stackoverflow.com/comment/82610975
score: 0
has text: I tried code and it works correctly for me.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47822233

http://stackoverflow.com/q/47735684
has body: On searching for how to call system commands, I found there to be many methods in Python. How does one choose between different methods of calling system commands: Method 1: os.system('ls -l *.py') Method 2: os.popen("ls -l").read() Method 3: subprocess.check_output(["ls", "-l", "*.py"]); Method 4: p = subprocess.Popen("ls -l *.py", stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, shell=True) (out, err) = p.communicate() Method 5: from shell_command import shell_call shell_call("ls -l *.py") What are the relative advantages and disadvantages of each? Which ones are especially recommended for python3 versus python2. Are there any methods which will work in both versions?
tagged with: operating-system
answer count: 1
tagged with: python
tagged with: exec
favorite count: 0
has answer: http://stackoverflow.com/a/47737836
score: -1
has title: Different methods of calling system commands
type: Question
tagged with: python-3.x
type: UnansweredQuestion
downvote count: 2
upvote count: 1

http://stackoverflow.com/q/47855488
tagged with: oop
has comment: http://stackoverflow.com/comment/82676681
has comment: http://stackoverflow.com/comment/82675097
type: AnsweredQuestion
score: 0
has body: I have an error when running this section codes: def foo(a=1, b=None, unit=1, *arg): # some process print(a + min(arg)) foo(arg=3,4) Out[0]: SyntaxError: non-keyword arg after keyword arg What is the best way for calling .foo() method? I want get minimum of some numbers then added to 'a' value as static. Note: Assume .foo() has some static input variables. Note: I expected "4" to be printed. I know that we can't define .foo() method such as bellow: def foo(*arg, a=1, b=None, unit=1): pass And I don't want assign any value to static .foo() variables (a, b, unit)
upvote count: 1
downvote count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/47881416
has title: What is the shortest and the best approach to calling a complicated method in python?
possible better answer: http://stackoverflow.com/a/47855569
type: Question
has answer: http://stackoverflow.com/a/47881416
has answer: http://stackoverflow.com/a/47855569
answer count: 2
tagged with: python
tagged with: design-patterns
has comment: http://stackoverflow.com/comment/82690528

http://stackoverflow.com/comment/82530555
has text: thank you for your help. Python sip can binding for protobuf message. I solved this problem and have a simple example code: https://github.com/tuanakka0101/python-sip-example
score: 0
comment on: http://stackoverflow.com/q/47768868
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47771648
upvote count: 1
answers question: http://stackoverflow.com/q/47771647
has comment: http://stackoverflow.com/comment/82504377
score: 1
downvote count: 0
has body: Answering my own question, you can use the size() function of the resulting <class 'pyquery.pyquery.PyQuery'> object, like this. dom = ' Whoah! there ' pq = PyQuery(m) result = pq('p').find('em') print( result.size() ) #output: 2 Edit: As @MatiasCicero pointed out in comments, using len on the <class 'pyquery.pyquery.PyQuery'> object is a more pythonic way. Example: print( len(result) ) #output: 2
type: Answer

http://stackoverflow.com/comment/82447786
type: Comment
type: QuestionComment
has text: better show real url so we could test it.
comment on: http://stackoverflow.com/q/47717129
score: 0

http://stackoverflow.com/q/47735074
downvote count: 0
has answer: http://stackoverflow.com/a/47735346
has comment: http://stackoverflow.com/comment/82430953
has title: an array for every process in [ multiprocessing ] want one list with all sub-lists merged
favorite count: 0
tagged with: multiprocessing
type: Question
has comment: http://stackoverflow.com/comment/82430986
has body: I'm doing a program were there are multiple processes working in parallel. For every process, I wanna collect some information and then, at the end of the program, I want that information to be written into a binary file. I got everything working fine (the parallel stuff and the written file stuff), but there's a problem with the information I'm collecting... I'm trying to save the info in a multiprocessing.Array, but the thing is that it seems like every process is creating an array of it's own. When the processes finish doing what they need to do, I printed the array so that I could see what was going on, and this printed: ['6554,a,0.109375,2;', '6554,c,0.099609375,2;'] ['6557,g,0.109375,2;'] ['6555,b,0.099609375,2;', '6555,f,0.109375,2;'] ['6556,d,0.109375,2;'] [] Note: the strings are the information I'm collecting from the processes. What's the problem? I have a long code, so I'm trying to explain myself as good as I can. ------------------------- UPDATE ----------------------------- The project I'm doing receives a file, or files, and compresses that file into a zip file. When multiple files, there are multiple processes, and each of them, when compressing, collects info from the file it is zipping and saves it into a multiprocessing.Array. In the end, I call for another function that writes a binary file with the information within that array. I'm expecting one array ( list ) like this: ['6554,a,0.109375,2;', '6554,c,0.099609375,2;', '6557,g,0.109375,2;', '6555,b,0.099609375,2;', '6555,f,0.109375,2;', '6556,d,0.109375,2;']
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47750465
tagged with: arrays
tagged with: python
linked to: http://stackoverflow.com/q/47728862
has answer: http://stackoverflow.com/a/47735864
answer count: 4
tagged with: parallel-processing
score: 2
upvote count: 2
has answer: http://stackoverflow.com/a/47735114
has comment: http://stackoverflow.com/comment/82431179

http://stackoverflow.com/q/47798708
has title: how to Convert list of tuple into column from text file
linked to: http://stackoverflow.com/q/9535954
type: Question
has body: I have a text file which contains a list of tuples. I want to convert this list into columns. The file contains the following data: [(0, u'0.025*"minimalism" + 0.018*"diwali" + 0.018*"sunday" + 0.018*"minimalistics" + 0.018*"plant" + 0.010*"thought" + 0.010*"take" + 0.010*"httpstcog21yvu1vyo" + 0.010*"time" + 0.010*"cause"'), (1, u'0.029*"panshet" + 0.022*"im" + 0.015*"video" + 0.015*"project" + 0.015*"shade" + 0.015*"nature" + 0.015*"motionphotography…" + 0.015*"motionjpeg" + 0.015*"trip" + 0.015*"lake"'), (2, u'0.013*"light" + 0.013*"take" + 0.013*"minimalist" + 0.013*"unm4sk" + 0.013*"first" + 0.013*"minimalism…" + 0.013*"minimal" + 0.013*"possible" + 0.013*"quick" + 0.013*"story"')] I want the output in THE following format: topic 0 topic 1 topic 2 minimalism panshet light diwali im take sunday video minimalist minimalistics project unm4sk plant shade first EDIT 1 with open('LDA.txt') as f: lis = [x.split() for x in f] cols=[x for x in zip(*lis)] for x in cols: print(x)
has comment: http://stackoverflow.com/comment/82558354
tagged with: http://stackoverflow.com/tag/csv
possible better answer: http://stackoverflow.com/a/47805569
has comment: http://stackoverflow.com/comment/82558396
has comment: http://stackoverflow.com/comment/82558417
has comment: http://stackoverflow.com/comment/82558858
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/47805569
tagged with: nlp
has comment: http://stackoverflow.com/comment/82558723
tagged with: topic-modeling
type: AnsweredQuestion
tagged with: python-2.7
upvote count: 0
answer count: 2
has comment: http://stackoverflow.com/comment/82558904
has comment: http://stackoverflow.com/comment/82558666
downvote count: 1
has comment: http://stackoverflow.com/comment/82558538
has answer: http://stackoverflow.com/a/47798946
accepted answer: http://stackoverflow.com/a/47798946
has comment: http://stackoverflow.com/comment/82558589
favorite count: 0

http://stackoverflow.com/q/47814401
has comment: http://stackoverflow.com/comment/82593865
score: 0
tagged with: conv-neural-network
tagged with: batch-normalization
answer count: 0
has body: I am trying to implement batch-normalization on my CNN that currently applies dropout. One problem is that I do not know how the mean and variance are calculated during test time. On the documentation it says that if training=False is set then the normalization is done with moving statistics. What does this mean? In addition, since my test data has lots of machine-generated samples I cannot use population mean and variance and just apply tf.nn.batch_normalization(). These samples are used to prevent hand labeling and are excluded when scoring my model
tagged with: tensorflow
type: Question
has title: How does tf.layers.batch_normalization calculate mean and variance during test time? (test data has machine-generated samples)
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82591713
has comment: http://stackoverflow.com/comment/82593300
tagged with: python

http://stackoverflow.com/comment/82557994
has text: Good point. But from here I'll proceed on my own. Being fairly new to Python, I wanted to have the clarification as to why a tuple would print out such results. The plan was that I print out the numerics like you showed and then proceed after getting the clarity (after all thats how nice programs are built). But the prints prevented me from looping it further because of the dual results (I need a single `item` to calculate a total). This will also help me in the future when looping over tuples to print exact values.
type: Comment
comment on: http://stackoverflow.com/a/47796364
score: 0
type: AnswerComment

http://stackoverflow.com/comment/82398729
comment on: http://stackoverflow.com/a/47706072
type: AnswerComment
score: 1
has text: I just posted a memory_saving version, see if it works for you. If you write a PR, a parameter is probably best because everyone's CPU / memory balance is different, there is no threshold that works well for all. Also, the current method supports metric='precomputed' which the memory-saving version does not (so the "saving" parameter will need to be ignored if the metric is precomputed).
type: Comment

http://stackoverflow.com/q/47782007
has comment: http://stackoverflow.com/comment/82525430
score: 1
accepted answer: http://stackoverflow.com/a/47782333
has title: numpy genfromtxt strings int mixed data types
favorite count: 0
has answer: http://stackoverflow.com/a/47782333
type: AnsweredQuestion
has body: I'm trying to read a csv file with the following content into a numpy array: 1,85,104,2,"C" 2,71,82,2,"C#" 3,67,73,2,"D" 4,105,108,2,"D#" 5,103,100,2,"E" This is the attempt of coding: import numpy as np twg=np.genfromtxt(r'./Documents/gears.txt', delimiter=',',dtype=(int,int,int,int,object)) print (twg) But this eats up the #-sign in the source: [( 1, 85, 104, 2, b'"C"') ( 2, 71, 82, 2, b'"C') ( 3, 67, 73, 2, b'"D"') ( 4, 105, 108, 2, b'"D') ( 5, 103, 100, 2, b'"E"')]
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
type: Question
tagged with: numpy
answer count: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/47850236
has body: Consider adding midnight records into your dataframe that is forward filled with last row's HVAC state (except for first record which is back-filled). Below prints out each step of the process: Initial data from io import StringIO import pandas as pd txt = """ timestamp date hvac_state 0 "2017-11-09 18:43:45" "12-09-17" off 1 "2017-11-09 20:15:27" "12-09-17" heating 2 "2017-11-09 22:29:00" "12-09-17" heating 3 "2017-11-09 23:42:34" "12-09-17" off 4 "2017-11-10 00:09:40" "12-10-17" heating 5 "2017-11-10 00:23:14" "12-10-17" heating 6 "2017-11-10 03:32:17" "12-10-17" off 7 "2017-11-10 10:59:24" "12-10-17" heating 8 "2017-11-10 11:12:59" "12-10-17" off 9 "2017-11-10 13:49:09" "12-10-17" off 10 "2017-11-10 16:58:11" "12-10-17" heating 11 "2017-11-10 17:11:45" "12-10-17" heating 12 "2017-11-10 17:25:19" "12-10-17" off 13 "2017-11-10 23:53:44" "12-10-17" off 14 "2017-11-11 00:25:22" "12-11-17" off 15 "2017-11-11 03:29:53" "12-11-17" heating 16 "2017-11-11 03:43:26" "12-11-17" heating 17 "2017-11-11 04:01:31" "12-11-17" off""" month_df = pd.read_table(StringIO(txt), sep="\s+", index_col=0, parse_dates=[0,1]) Midnight Appends midnights_df = pd.DataFrame({'timestamp':pd.date_range(month_df['timestamp'].min().normalize(), month_df['timestamp'].max()), 'date': pd.date_range(month_df['date'].min(), month_df['date'].max())}) print(midnights_df) # date timestamp # 0 2017-12-09 2017-11-09 # 1 2017-12-10 2017-11-10 # 2 2017-12-11 2017-11-11 month_df = pd.concat([month_df, midnights_df], ignore_index=True)\ .sort_values(['date', 'timestamp'])\ .append({'date': month_df['date'].max(), 'timestamp': month_df['timestamp'].max().normalize() + pd.DateOffset(days=1)}, ignore_index=True)\ .fillna(method='ffill').reset_index(drop=True) # BACK FILL month_df.loc[0, 'hvac_state'] = month_df.loc[1, 'hvac_state'] print(month_df) # date hvac_state timestamp # 0 2017-12-09 off 2017-11-09 00:00:00 # 1 2017-12-09 off 2017-11-09 18:43:45 # 2 2017-12-09 heating 2017-11-09 20:15:27 # 3 2017-12-09 heatin…
score: 0
has comment: http://stackoverflow.com/comment/82707858
type: Answer
has comment: http://stackoverflow.com/comment/82675694
has comment: http://stackoverflow.com/comment/82689887
answers question: http://stackoverflow.com/q/47849196
accepted answer of: http://stackoverflow.com/q/47849196
type: AcceptedAnswer

http://stackoverflow.com/q/47759982
tagged with: python
has answer: http://stackoverflow.com/a/47774418
type: Question
score: 2
has comment: http://stackoverflow.com/comment/82482458
answer count: 2
tagged with: pandas
upvote count: 2
has body: I have a report that I am working on to show variance between two quarterly periods. I have an SQL query that I am reading into a pandas dataframe, and then pivoting. Here is my code for that piece: df = pd.read_sql_query(mtd_query, cnxn, params=[report_start, end_mtd, report_start, end_mtd, whse]) ##(m-1)//3 + 1 Determine which Quarter each month is ## Create the "Period" column by combining the Quater and the Month df['QUARTER'] = (df['INV_MONTH'].astype(int) - 1)//3 + 1 df['PERIOD'] = df['INV_YEAR'].astype(str) + 'Q' + df['QUARTER'].astype(int).astype(str) df['MARGIN'] = (df['PROFIT'].astype(float) / df['SALES'].astype(float)) df = df.drop('INV_MONTH', axis=1) df = df.drop('INV_YEAR', axis=1) df = pd.pivot_table(df, index=['REP', 'REP_NAME', 'CUST_NO', 'CUST_NAME', 'TOTALSALES'], columns=['PERIOD'], values=['SALES', 'PROFIT', 'MARGIN'], fill_value=0) df = df.reorder_levels([1, 0], axis=1).sort_index(axis=1, ascending=False) df = df.sortlevel(level=0, ascending=True) I am trying to determine the difference between the 'MARGIN' columns between 'PERIOD'. I have been unable to find any way to accomplish this. Any suggestion is appreciated. Current Output shows: PERIOD 2017Q4 2017Q3 2017Q2 2017Q1 2016Q4 SALES PROFIT MARGIN SALES PROFIT MARGIN SALES PROFIT MARGIN SALES PROFIT MARGIN SALES PROFIT MARGIN REP REP_NAME CUST_NO CUST_NAME TOTALSALES 1.0 Greensboro - House 245.0 TE CONNECTIVITY CORPORATION 103361.05 0.000000 0.000000 0.000000 434.500000 69.520000 0.160000 20391.666667 3262.666667 0.160000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 1789.0 GOOD HOUSEKEEPER 50108.47 678.508182 80.170909 0.145883 585.301429 64.180476 0.121915 718.685000 92.033125 0.130453 720.729333 97.955333 0.134821 1237.308333 88.210000 0.099450 Desired Output would look like below: PERIOD 2017Q4 2017Q3 2017Q2 2017Q1 2016Q4 SALES PROFIT MARGIN VARIANCE SALES PROFIT MARGIN VARIANCE SALES PROFIT MARGIN VARIANCE SALES PROFIT MARGIN VARIANCE SALES PROFIT MARGIN REP REP_NAME CUST_NO CUST…
downvote count: 0
has title: Add calculated Field between Pivot 'Columns' based on 'Values' data
accepted answer: http://stackoverflow.com/a/47838571
has answer: http://stackoverflow.com/a/47838571
favorite count: 0
type: AnsweredQuestion
tagged with: pivot-table
has comment: http://stackoverflow.com/comment/82507076
possible better answer: http://stackoverflow.com/a/47774418
has comment: http://stackoverflow.com/comment/82482328

http://stackoverflow.com/comment/82396693
comment on: http://stackoverflow.com/q/47718013
type: Comment
has text: Yes, I want to force the placement. I tried to make this clearer in the question.
type: QuestionComment
score: 0

http://stackoverflow.com/comment/82373359
score: 0
comment on: http://stackoverflow.com/q/47706382
type: QuestionComment
type: Comment
has text: Oh, my bad! I looked back and forth between them and missed that like a dummy. This is a good question. Good luck.

http://stackoverflow.com/q/47801548
type: Question
score: 0
has comment: http://stackoverflow.com/comment/82564741
tagged with: pandas
has comment: http://stackoverflow.com/comment/82564724
tagged with: dataframe
tagged with: python
has title: Use values from one DataFrame to keep values from another DataFrame
answer count: 0
has body: I have created two dataframes, lets call them, df1 df2 where print(df1) a b 1 0.375241 1.0 2 NaN 2.0 3 0.448792 3.0 4 NaN 4.0 df1 = df1[np.isfinite(df1['a'])] print(df1) a b 1 0.375241 1.0 3 0.448792 3.0 print(df2) aa bb 1 0.047606 1.0 2 0.202927 1.0 3 0.205663 1.0 4 NaN 1.0 5 1.388080 1.0 6 0.097084 1.0 7 0.136873 1.0 8 NaN 1.0 9 NaN 1.0 10 NaN 1.0 12 0.084676 2.0 13 0.236850 2.0 14 0.532835 2.0 15 NaN 2.0 16 NaN 2.0 17 0.035106 2.0 18 NaN 2.0 19 NaN 2.0 20 NaN 2.0 22 0.419956 3.0 23 0.267132 3.0 24 0.944217 3.0 25 0.403024 3.0 26 NaN 3.0 27 0.184425 3.0 28 0.473998 3.0 29 NaN 3.0 30 NaN 3.0 31 NaN 3.0 33 0.465454 4.0 34 0.240867 4.0 35 NaN 4.0 36 NaN 4.0 37 0.323195 4.0 38 0.193764 4.0 39 NaN 4.0 40 NaN 4.0 41 NaN 4.0 42 NaN 4.0 based on the results from df1['b'] where I only have 1 &amp; 3 as valid numbers now, how would I go about keeping df2['bb'] 1 &amp; 3, and setting all other values in df2 to np.nan so that this would be the final product df2 = df2[np.isfinite(df2['aa'])] print(df2) aa bb 1 0.047606 1.0 2 0.202927 1.0 3 0.205663 1.0 5 1.388080 1.0 6 0.097084 1.0 7 0.136873 1.0 22 0.419956 3.0 23 0.267132 3.0 24 0.944217 3.0 25 0.403024 3.0 27 0.184425 3.0 28 0.473998 3.0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82564353

http://stackoverflow.com/comment/82429991
has text: @Blckknght, In Circassian language there is one feature, some sounds are denoted by several symbols, for example, the sound "кхъу", in the Circassian language this is considered to be one letter, not four.
comment on: http://stackoverflow.com/q/47734554
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47706765
type: Answer
score: 2
upvote count: 2
downvote count: 0
has body: There seems to be a missing line here for the dataframe, but I will assume you have it. If you don't, then read your data using pandas.read_csv. Also, your columns seem to have data that is both categorical and numerical. For example, the "SmokedBefore" column is likely 1/0 whereas your "Age" column is likely numbers such as 20 or 30. This makes a difference, because in "SmokedBefore" the intent is not to say that 1>0. The intent is to say Yes/No. If your model assumes that higher (or lower) is better, then this will cause an issue. Therefore it is categorical and should not be treated like a numerical value. It is simply a tag to indicate whether someone has smoked before. However, in "Age" the intent is to say that 30 is different than 20 by 10. Therefore, it is numerical and should be treated as such. To treat this, you will need to transform your categorical features into another set of binary features that will balance out this effect and handle it for you. This is called One Hot Encoding. Instead of 1/0 on your "SmokedBefore", it will become "is_1" and "is_0" with corresponding data. Like that, each column will have a 1 and a 0. You can simply use the onehotencoder function provided in sklearn. Use the categorical_features argument to specify which columns have categorical features
answers question: http://stackoverflow.com/q/47703641

pyqt
type: Tag
tags question: http://stackoverflow.com/q/47854621
tags question: http://stackoverflow.com/q/47841688
tags question: http://stackoverflow.com/q/47836001
tags question: http://stackoverflow.com/q/47741032
tags question: http://stackoverflow.com/q/47792631
tags question: http://stackoverflow.com/q/47772138
tags question: http://stackoverflow.com/q/47855870
tags question: http://stackoverflow.com/q/47739191
tags question: http://stackoverflow.com/q/47728191
tags question: http://stackoverflow.com/q/47851152
tags question: http://stackoverflow.com/q/47852697
tags question: http://stackoverflow.com/q/47846834
tags question: http://stackoverflow.com/q/47777315
tags question: http://stackoverflow.com/q/47789229
tags question: http://stackoverflow.com/q/47718444
tags question: http://stackoverflow.com/q/47746641
tags question: http://stackoverflow.com/q/47780485
tags question: http://stackoverflow.com/q/47716408
tags question: http://stackoverflow.com/q/47850504
tags question: http://stackoverflow.com/q/47844741
tags question: http://stackoverflow.com/q/47835929
tags question: http://stackoverflow.com/q/47773371
tags question: http://stackoverflow.com/q/47721201
tags question: http://stackoverflow.com/q/47735664
tag name: pyqt
tags question: http://stackoverflow.com/q/47749631
tags question: http://stackoverflow.com/q/47754276
tags question: http://stackoverflow.com/q/47788675
tags question: http://stackoverflow.com/q/47731064
tags question: http://stackoverflow.com/q/47849366
tags question: http://stackoverflow.com/q/47839895

http://stackoverflow.com/q/47831379
score: -2
accepted answer: http://stackoverflow.com/a/47831410
tagged with: python
has answer: http://stackoverflow.com/a/47831410
type: AnsweredQuestion
tagged with: python-2.7
answer count: 1
downvote count: 3
upvote count: 1
has comment: http://stackoverflow.com/comment/82625570
tagged with: python-requests
favorite count: 0
type: Question
tagged with: python-3.x
has body: I am reading from a variable "RF" from CSV file and then I have an "array" data. I want to put some equation between both variables. Therefore, I am converting my array dataset into "RF" data format. In my CSV file I have 8 variables but presently I am reading only one variable. When I am executing the code it is giving some error. import numpy as np import pandas as pd import csv data_df = pd.read_csv('poly2_decpred_juneRF.csv', header=0, nrows=67) y1 = data_df['RF'] y1.head(67) finalpred1=[2.22, 2.33, 3.33, 1.21, 2.22, 2.33, 3.33, 1.21, 2.22, 2.33, 3.33, 1.21, 2.22, 2.33, 3.33, 1.21, 2.33] s = pd.Series(finalpred1, name='RF') print(s) y111=y1[50:67] print(y111) diff = ((y111-s)/y111)*100 print(diff) The output is coming like this: 0 NaN 1 NaN 2 NaN 3 NaN 4 NaN 5 NaN 6 NaN 7 NaN 8 NaN 9 NaN 10 NaN 11 NaN 12 NaN 13 NaN 14 NaN 15 NaN 16 NaN 50 NaN 51 NaN 52 NaN 53 NaN 54 NaN 55 NaN 56 NaN 57 NaN 58 NaN 59 NaN 60 NaN 61 NaN 62 NaN 63 NaN 64 NaN 65 NaN 66 NaN Name: RF, dtype: float64 The CSV dataset is given in this format: RF,Nino,IOD,SOI,NAO,TNA,TSA,MEI 103.77,-1.04,0.20,2.70,-1.02,0.18,-0.92,-1.26 83.99,0.71,0.16,-1.70,1.32,-0.07,0.00,0.48 86.97,-0.55,0.21,-1.30,-0.43,0.55,-0.14,-0.12 152.58,0.15,0.11,-1.00,-0.47,0.17,-0.41,0.32 230.83,-0.79,0.18,0.60,0.69,-0.30,-0.23,-1.11 223.45,-1.52,-0.06,-0.50,0.17,0.30,-0.57,-1.88 118.26,-0.58,0.08,1.50,0.10,0.05,-0.49,-1.02 93.58,1.18,-0.02,-0.60,0.12,0.17,-0.16,1.25 .......................................... 132.30,2.56,0.49,0.10,2.24,0.42,0.70,2.11 110.00,-0.51,-0.07,0.40,0.48,0.52,0.67,-0.12 Total rows are 67: Please help me out
has title: Error while getting re-arrange np.array to float64 data during calculation

http://stackoverflow.com/q/47852394
type: Question
has body: so when I'm im in my root directory (where manage.py lives), if I do manage.py runserver it says command not found. I have to do ~/&lt;project_name&gt;/manage.py runserver for it to work. Why is this?
answer count: 2
type: UnansweredQuestion
upvote count: 0
has comment: http://stackoverflow.com/comment/82669174
tagged with: django
downvote count: 1
tagged with: terminal
has answer: http://stackoverflow.com/a/47852727
has comment: http://stackoverflow.com/comment/82669183
has answer: http://stackoverflow.com/a/47852713
tagged with: python
has comment: http://stackoverflow.com/comment/82669155
tagged with: unix
has title: how to use manage.py inexplicitely
favorite count: 0
score: -1

http://stackoverflow.com/a/47899940
upvote count: 11
has body: Sean answer won't make any difference. Your code works for older Telethon versions. In the new versions, a new argument hash is added to GetParticipantsRequest method. Therefore, you need to pass hash as an argument too. Add hash=0 like this: result = client(GetParticipantsRequest(InputChannel(channel.chats[0].id, channel.chats[0].access_hash), filter, num, 100, 0)) Note that the hash of the request is not the channel hash. It's a special hash calculated based on the participants you already know about, so Telegram can avoid resending the whole thing. You can just leave it to 0. Here is an up-to-date example from official Telethon wiki.
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47698756
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47698756
type: Answer
score: 11

http://stackoverflow.com/comment/82532586
type: QuestionComment
score: 0
has text: do you have anything more in error message ? Do you have two Pythons on computer ? Do you run notebook on local computer ?
comment on: http://stackoverflow.com/q/47785483
type: Comment

http://stackoverflow.com/q/47782377
has answer: http://stackoverflow.com/a/48248257
type: UnansweredQuestion
has title: When using a PIL image object with reportlab drawImage gives
tagged with: python
has answer: http://stackoverflow.com/a/55155482
score: 3
upvote count: 3
tagged with: python-imaging-library
downvote count: 0
answer count: 3
tagged with: reportlab
has body: I am trying to insert a PIL image object into a pdf using reportlab drawImage method. im=Image.open('back_ground.png') side_im=im.crop((2,2,277,819)) c=canvas.Canvas('report.pdf') c.drawImage(side_im,200,700) And I get this error AttributeError: 'Image' object has no attribute 'rfind'
has answer: http://stackoverflow.com/a/60943706
favorite count: 0
type: Question

http://stackoverflow.com/comment/82859391
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47837976
has text: I have no idea. And it seems like you are driving away from your original question now.

http://stackoverflow.com/comment/82674550
score: 0
type: QuestionComment
has text: As it can have many people called "Sue" in the family, you need a unique identifier for each people to be able to update their children without problem.
type: Comment
comment on: http://stackoverflow.com/q/47854980

http://stackoverflow.com/q/47746161
has answer: http://stackoverflow.com/a/47747468
tagged with: python
has title: Python How to get integers from the list?
has comment: http://stackoverflow.com/comment/82452487
has body: I have a list with integers with white space in between. I'd like to retrieve all those individual integer and make a new list with an index. &gt;&gt;&gt; x = ['1 2 3 4'] &gt;&gt;&gt; type(x) &lt;class 'list'&gt; &gt;&gt;&gt; len(x) 1 I want to convert the list into &gt;&gt;&gt; x = [1, 2, 3, 4] &gt;&gt;&gt; type(x) &lt;class 'list'&gt; &gt;&gt;&gt; len(x) 4 I'm trying with split, it didn't work. How do I do the conversion?
type: Question
tagged with: integer
score: 0
has answer: http://stackoverflow.com/a/47746172
tagged with: list
upvote count: 2
type: UnansweredQuestion
downvote count: 2
has comment: http://stackoverflow.com/comment/82452419
favorite count: 0
has answer: http://stackoverflow.com/a/47746175
answer count: 3

http://stackoverflow.com/comment/82534189
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47775083
has text: are your images numbered padded? as `test.001.jpg`

http://stackoverflow.com/comment/82579294
type: Comment
type: QuestionComment
has text: PS: confirmed on linux's cython, not sure about windows.
comment on: http://stackoverflow.com/q/47808851
score: 0

http://stackoverflow.com/a/47838026
answers question: http://stackoverflow.com/q/47837839
type: Answer
has body: Looking at your code you can immediately see that the indexes at the right most side of the target list never get a value in these loops, as the index n only iterates up to the length of either input list. The index to add a product to is determined by the sum of the indexes in the input lists: def polyprod(a,v): prodav = [0]*(len(a)+len(v)-1) for n in range(len(a)): for m in range(len(v)): prodav[n+m] += v[m]*a[n] return prodav print(polyprod([1,1,1], [0,2,6])) # [0, 2, 8, 8, 6]
score: 1
accepted answer of: http://stackoverflow.com/q/47837839
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/82639955

http://stackoverflow.com/a/47758593
has body: By using a combination of assigning a group with unstack and shift its possible to avoid the usage of apply, resulting in a great speedup. def compute_shift(df): df['group_no'] = df.groupby(['id1','id2']).ngroup() tmp = df'date','vals','group_no'.set_index(['group_no','date'])\ .unstack('group_no')\ .resample('D').asfreq() tmp1 = tmp.shift(1).stack('group_no')['vals'].rename('t_1') tmp2 = tmp.shift(2).stack('group_no')['vals'].rename('t_2') df = df.join(tmp1, on=['date','group_no']) df = df.join(tmp2, on=['date','group_no']) return df compute_shift(df) date id1 id2 vals group_no t_1 t_2 0 2017-01-01 1 45 0.10 1 NaN NaN 1 2017-01-02 1 45 0.20 1 0.10 NaN 2 2017-01-01 1 33 0.60 0 NaN NaN 3 2017-04-01 1 33 0.10 0 NaN NaN 4 2017-04-02 1 33 0.15 0 0.10 NaN 5 2017-01-01 4 1 0.34 2 NaN NaN 6 2017-01-02 4 1 0.12 2 0.34 NaN 7 2017-01-03 4 1 0.50 2 0.12 0.34 8 2017-01-04 6 34 0.40 3 NaN NaN 9 2017-01-05 6 34 0.45 3 0.40 NaN To compare performance I created a fake dataset of reasonable size: df = pd.DataFrame({'date':np.random.randint(1, 1000, 10**6), 'id1':np.random.randint(1, 100, 10**6), 'id2':np.random.randint(1, 100, 10**6), 'vals':np.random.random(10**6)}) df = df.drop_duplicates(subset=['date','id1','id2'], keep='last') df = df.sort_values('date') dates = pd.date_range('20150101','20180101').to_series().reset_index(drop=True) df['date'] = df['date'].map(dates) If we compare performance with the solution of Wen and Scott: %timeit df.groupby(['id1','id2'],sort=False).apply(lambda x : x['vals'].shift()*((x['date'] - pd.to_timedelta(1, unit='d')).isin(x['date'].tolist())).replace(False,np.nan)) 824 ms ± 19.3 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) %timeit df.groupby(['id1','id2'], as_index=False)\ .apply(lambda x: x.assign(t_1=x.vals.resample('D').asfreq().shift(1),\ t_2=x.vals.resample('D').asfreq().shift(2))) 1.38 s ± 25.3 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) %timeit compute_shift(df) 96.4 ms ± 2.14 ms per loop (mean ± std. dev. of 7 runs…
type: AcceptedAnswer
downvote count: 0
upvote count: 8
has comment: http://stackoverflow.com/comment/82478809
type: Answer
has comment: http://stackoverflow.com/comment/82497361
answers question: http://stackoverflow.com/q/47755584
score: 8
accepted answer of: http://stackoverflow.com/q/47755584

http://stackoverflow.com/a/47726570
has comment: http://stackoverflow.com/comment/82414568
type: Answer
has comment: http://stackoverflow.com/comment/82418047
downvote count: 1
upvote count: 6
answers question: http://stackoverflow.com/q/47726550
score: 5
has body: ^ is a meta-character in regular expressions, and it should be escaped, i.e. re.sub('\\^M', '', line) # 2 backslashes because the backslash needs to be escaped or re.sub(r'\^M') # no escape needed because of a raw string. But then, this is a fixed string, so you should use str.replace, i.e. line.replace('^M', '') But then, not always does the ^ and M mean that there is ^ and M, as the ^M can also be used to mean the ASCII carriage return (U+0013, or Control-M); which in a Python string is \r: line.replace('\r', '') ... but then there is already a utility that will strip these Windows line endings from a file: dos2unix.

http://stackoverflow.com/comment/83568112
has text: @fralau Could you add an DOCX example of your comment above?
type: Comment
comment on: http://stackoverflow.com/a/48277477
score: 0
type: AnswerComment

http://stackoverflow.com/comment/82388470
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47714011
score: 0
has text: Hi, thanks for the comments. @yasin, i have also tried DATA_SET_PATH = (r'fordTestA.csv') dataset = pd.read_csv(DATA_SET_PATH) for line in datset: but this gives error too, FlyinTeller, thank you, that does the trick but the model is treating this as one feature. Forcetti, thank you for the comment, Each row contains 30 features, which the model is expecting.

http://stackoverflow.com/comment/94040103
has text: @edyvedy13, please, visit https://support.upwork.com and press "Get Help" button right after "Contact Upwork Customer Service" label. The Support Team will help you to handle the request and update with the details.
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47750740

http://stackoverflow.com/comment/82452026
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47745677
type: QuestionComment
has text: @Ignacio-Vazquez-Abrams: It wouldbe helpful if those who mark as duplicate would also tell how they determined that it was a duplicate, including search terms used. This would help me to become a better contributor and to avoid superfluous contributions.

http://stackoverflow.com/a/47835765
type: Answer
score: 0
answers question: http://stackoverflow.com/q/47831176
has body: Perhaps a different approach is to tell the users they must ask specific questions. Have your harness read the output character by character (I know), and as soon as it EXACTLY matches a particular expected question, then it injects the matching answer as input, but only one time per match. Of course, once all questions have been satisfied, you can switch to a faster batched read. You can then stream the byte-by-byte output, and the injected responses to the log file in a natural order which matches what your harness is doing. It may be good for the harness to have a time-out and print the un-consumed questions as a diagnostic aid. This allows for question ordering, optional questions, etc that have been mentioned, but hard-wires a part of the design spec to customer requirements. Make it clear to the students that they will lose marks for not matching the prompts well enough for the automated processor, or say, for a client who provides a local language translation.

http://stackoverflow.com/a/47811695
score: 0
has comment: http://stackoverflow.com/comment/82601883
answers question: http://stackoverflow.com/q/47810814
has comment: http://stackoverflow.com/comment/82605791
has body: You want the letter with the index increased by 1 or decreased by 25 for each letter, so if 'a' is index 0 'b' will be index 1 or index -25 (in english alphabet). starting from the tail of the list does not generate index out of range. with this theory, you can write: import string alphabet = string.ascii_lowercase def kcrypt(word): return ''.join(alphabet[alphabet.index(l)-len(alphabet)+1] for l in word) print kcrypt(word)
type: Answer

http://stackoverflow.com/comment/82431985
score: 0
type: Comment
has text: I think our two approaches would be the same, as I think Django would be executing the same number of queries (maybe even the same query?). However I think the loop approach would be slower as my understanding is that `aggregate()` uses database level APIs to do the calculation, which would be faster than Python code.
type: AnswerComment
comment on: http://stackoverflow.com/a/47735671

http://stackoverflow.com/comment/82471009
has text: `or` doesn't work element-wise. You must use `|`. Because of operator precedence you will then also have to put parentheses around the individual conditions.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47754887

http://stackoverflow.com/q/47840479
upvote count: 0
has answer: http://stackoverflow.com/a/47840558
answer count: 1
favorite count: 0
type: Question
type: UnansweredQuestion
score: -2
downvote count: 2
tagged with: python
has title: Python - writing a loop output to a file
has body: I am able to print this in the format I want, how would I write this to a file? import json #myfile = open('us-west-2-offering-script.txt', 'w') with open('Pricing_Json_Cli.json', 'r') as f: rawData = json.load(f) for each in rawData['ReservedInstancesOfferings']: print('PDX', ',' , each['InstanceType'], ',' , each['InstanceTenancy'], ',' , each['ProductDescription'], ',' , each['OfferingType'], ',' , each['Duration'], ',' , each['ReservedInstancesOfferingId'], ',' , each['FixedPrice'], ',', end='' ) if not each['RecurringCharges']: print("0.0") else: print(each['RecurringCharges'][0].get('Amount')) myfile.close()

http://stackoverflow.com/comment/82528938
type: Comment
comment on: http://stackoverflow.com/a/47778957
type: AnswerComment
has text: Yeah adding names to the scope fixed it, I was following a legacy guide on the latest Tensorflow which is always a horrible idea. Also separating the optimizers is a grand idea, so it doesn't lead to issues later when training. I saw this answer slightly too late so I had already made that mistake. Thanks for the insight, if anyone else comes across this my bit of advice is read the official documentation _along_ with whatever guide you're following
score: 1

http://stackoverflow.com/q/47784705
has comment: http://stackoverflow.com/comment/82530877
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/82530925
has comment: http://stackoverflow.com/comment/82530889
downvote count: 0
has comment: http://stackoverflow.com/comment/82531077
has comment: http://stackoverflow.com/comment/82530898
favorite count: 0
has title: How to reduce on a list of tuples in python
has body: I have an array and I want to count the occurrence of each item in the array. I have managed to use a map function to produce a list of tuples. def mapper(a): return (a, 1) r = list(map(lambda a: mapper(a), arr)); //output example: //(11817685, 1), (2014036792, 1), (2014047115, 1), (11817685, 1) I'm expecting the reduce function can help me to group counts by the first number (id) in each tuple. For example: (11817685, 2), (2014036792, 1), (2014047115, 1) I tried cnt = reduce(lambda a, b: a + b, r); and some other ways but they all don't do the trick. NOTE Thanks for all the advice on other ways to solve the problems, but I'm just learning Python and how to implement a map-reduce here, and I have simplified my real business problem a lot to make it easy to understand, so please kindly show me a correct way of doing map-reduce.
has comment: http://stackoverflow.com/comment/82530995
type: Question
has comment: http://stackoverflow.com/comment/82530811
has comment: http://stackoverflow.com/comment/82530958
has answer: http://stackoverflow.com/a/47784789
tagged with: python
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/48274851
tagged with: mapreduce
has answer: http://stackoverflow.com/a/47784797
linked to: http://stackoverflow.com/q/29933189
tagged with: python-2.7
has answer: http://stackoverflow.com/a/48343896
has answer: http://stackoverflow.com/a/47785989
answer count: 4
has comment: http://stackoverflow.com/comment/82530916

http://stackoverflow.com/q/47826040
has body: I have a path with a file list that I want to show in kivy like this: excel_file.xlsx D.xlsx U.xlsx another_route.xlsx test.txt G.xlsx When I'm implementing the same algorithm to show them in kivy as a list of items, I only got a list exactly like this: G . x l s x I want to know what exactly what I'm doing wrong. Let me show you my code: class Routes_List_Screen(Screen): path = "/home/pi/Documents/myRoutes" dirs = os.listdir(path) for file in dirs: my_data = ListProperty(file) print(file) # this is just to know what exactly is printing file variable the kv file: &lt;Routes_List_Screen&gt;: canvas: Color: rgb: [.30, .30, .30] Rectangle: pos: self.pos size: self.size BoxLayout: orientation: 'vertical' ListView: size_hint_y: .8 adapter: ListAdapter(data=root.my_data, selection_mode='single', allow_empty_selection=False, cls=ListItemButton) Button: text: 'Load' My output:
has title: How to show files list with ListView? Python - Kivy
type: AnsweredQuestion
score: 0
tagged with: kivy
type: Question
has answer: http://stackoverflow.com/a/47826543
accepted answer: http://stackoverflow.com/a/47826543
answer count: 1
tagged with: python

http://stackoverflow.com/q/47824510
type: Question
has comment: http://stackoverflow.com/comment/82611712
has comment: http://stackoverflow.com/comment/82611755
downvote count: 0
accepted answer: http://stackoverflow.com/a/47824729
tagged with: python
has answer: http://stackoverflow.com/a/47824729
has body: I want to output the following format: addr&lt;-9-&gt;bit&lt;-15-&gt;value&lt;-13-&gt;name&lt;-26-&gt;type .... ... ...... ...... ...... #..... is the content of each row I used the str.format to achieve it: STRING_FORMATTER = '{0:13}{1:18}{2:18}{3:30}{4:10}\n' content = STRING_FORMATTER.format('addr', 'bit', 'value', 'name', 'type') content = content + STRING_FORMATTER.format('0123', 'LONG STRING THAT EXCEEDS 18 SPACES!!!!!!!!!!!!!!!!', '', '', 'reg') content = content + STRING_FORMATTER.format('00', '0', '0xAD', 'NAME', 'bit') ..... I basically construct the string by the type. The above is a problem that when the 2nd string exceeds 18 char spaces, the string behind is pushed. Is there a way to solve it? Or is there a better way to format the string to start at a fixed spacing in front?
has title: Python str.format string start at a fixed spacing
type: AnsweredQuestion
answer count: 2
score: 1
possible better answer: http://stackoverflow.com/a/47824606
upvote count: 1
tagged with: string
has answer: http://stackoverflow.com/a/47824606
favorite count: 0

http://stackoverflow.com/a/47737571
answers question: http://stackoverflow.com/q/47711431
has body: Tried the following code. In [1]: list1 = ['name', 'age', 'gender', 'location'] In [2]: list2 = ['name', 'age'] In [3]: list3 = list(set(list1) - set(list2)) In [4]: list3 Out[4]: ['gender', 'location'] This method is similar to @Aidan Dowling answer that is by using sets. I think this would be better than using for loops.
type: Answer
score: 0

http://stackoverflow.com/a/47861857
has body: As you are using macOS, you need to download a wkhtmltopdf binary by your own: pydf comes bundled with a wkhtmltopdf binary which will only work on Linux amd64 architectures. If you're on another OS or architecture your milage may vary, it is likely that you'll need to supply your own wkhtmltopdf binary and point pydf towards it by setting the WKHTMLTOPDF_PATH variable.
has comment: http://stackoverflow.com/comment/82690023
type: Answer
answers question: http://stackoverflow.com/q/47840125
upvote count: 2
has comment: http://stackoverflow.com/comment/82690104
has comment: http://stackoverflow.com/comment/82708820
downvote count: 0
has comment: http://stackoverflow.com/comment/82768628
score: 2

http://stackoverflow.com/comment/82887512
comment on: http://stackoverflow.com/a/47898836
type: Comment
score: 0
type: AnswerComment
has text: If no one answers (which seems likely at this point) the bounty is yours tomorrow, I also went through some of your questions/ answers and upvoted some.

http://stackoverflow.com/q/47791972
tagged with: python
tagged with: python-requests
has answer: http://stackoverflow.com/a/47793905
has comment: http://stackoverflow.com/comment/82552047
favorite count: 0
score: 0
has body: I know that this question is asked several times in SO but none of them solved my problem. I want to login to a site via script so that I can scrape some data. Here's my login function : def login(self): s = requests.Session() r0 = s.get('https://www.example.com/') loginCsrfParam= r0.cookies['loginCsrfParam'] payload = {'username': 'xxxx', 'loginCsrfParam': loginCsrfParam, 'next': '', 'password': 'xxxxxx'} head={'User-Agent':"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36"} p = s.post('https://www.example.com/list', data=payload, headers=head) print p.text.encode('utf-8') but it's not logging in .any help ? EDIT As @furas has mentioned in a comment, in the previous code, I was setting the csrftoken from cookies which is not the same in the hidden field.. so I have changed the code using beautifulsoup like so : def login(self): head={'User-Agent':"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36"} with session() as s: soup = BeautifulSoup(s.get("https://www.example.com/").content) form_data = soup.select("form[action^=/login] input") print form_data[0]['value'] payload = {'username': 'rahma', 'csrfmiddlewaretoken': form_data[0]['value'], 'next': '', 'password': 'gamboladmin'} print '********', form_data s.post('https://www.example.com/', data=payload, headers=head) resp = s.get('https://www.example.com/secured_page/') print resp.text.encode('utf-8') form_data[0]['value'] prints the same csrf token in the hidden input .. but I couldn't access to the secured page :/
has comment: http://stackoverflow.com/comment/82545097
has title: Login to website using python requests not working
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/82545650
tagged with: authentication
has comment: http://stackoverflow.com/comment/82548061
type: Question
has comment: http://stackoverflow.com/comment/82545683
upvote count: 1
type: UnansweredQuestion
tagged with: session-cookies
has comment: http://stackoverflow.com/comment/82545912

http://stackoverflow.com/comment/82540586
score: 0
has text: @hek2mgl understood! is there any possible optimized way of doing the same using python?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47788748

http://stackoverflow.com/q/47731409
tagged with: tensorflow
favorite count: 0
type: Question
tagged with: python-3.x
upvote count: 2
type: UnansweredQuestion
has title: How to update a sub-tensor inside a tensor in tensorflow?
has body: I'm working with MNIST and I have a tensor of gradients with size [?,28,28,1] and I want to zero out a few of the [28,28,1] sub-tensors inside it, how should I accomplish this? I know the indices (as a list) where I need to zero out the sub-tensors. I tried doing something like this (given below) but, scatter.update can only change variables not tensors. I also tried stacking up the required sub-tensors of zeroes and ones but couldn't build up the required result. dy_dx, = tf.gradients(loss, x_adv) zeroes = tf.zeros(dy_dx[0].get_shape(), tf.float32) dy_dx = tf.scatter_update(dy_dx, indices, zeroes) Thanks!
answer count: 1
downvote count: 0
tagged with: python
score: 2
has answer: http://stackoverflow.com/a/47768798

http://stackoverflow.com/a/47715439
has comment: http://stackoverflow.com/comment/82462487
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47714969
has comment: http://stackoverflow.com/comment/82463381
score: 0
accepted answer of: http://stackoverflow.com/q/47714969
type: Answer
has body: What is agent_id? What you need is $match. Try this. timestamp = 1500000000 r = db.task_queue.aggregate( [ {"$match": {"$and": [ { "executed_timestamp": {"$eq": 0}, "planned_timestamp": {"$lte": timestamp} } ]}}, {"$group" : { "_id" : "$owner", "tasks": { "$push": "$$ROOT" } } }, {"$project": { "_id": 0, "owner": "$_id.owner", "tasks": 1 }} ] )

http://stackoverflow.com/q/47738171
answer count: 2
has comment: http://stackoverflow.com/comment/82436583
has comment: http://stackoverflow.com/comment/82436659
accepted answer: http://stackoverflow.com/a/47738211
has body: I want to remove the list [1,2,3] inside the outer list. I tried or isinstance(item, list) but that didn't work, the nested list was still there. messy_list = ["a", 2, 3, 1, False, [1, 2, 3]] # Your code goes below here messy_list.pop(3) messy_list.insert(0,1) for item in messy_list: if isinstance(item, str) or isinstance(item, bool): messy_list.remove(item) messy_list.pop(-1) print(messy_list) I would like to know if there wasn't a better way to check if there's a list inside the list, and then remove from the outer list, instead of having to hardcode it with .pop(-1)
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82436662
has answer: http://stackoverflow.com/a/56329523
has title: Remove a list inside a list
tagged with: nested-lists
upvote count: 5
tagged with: python
score: 4
possible better answer: http://stackoverflow.com/a/56329523
has answer: http://stackoverflow.com/a/47738211
type: AnsweredQuestion
tagged with: list

http://stackoverflow.com/comment/82638042
type: Comment
type: AnswerComment
has text: Man, my searching was unsuccesful. Could youhelp me with that nevertheless ? Here is the new question https://stackoverflow.com/questions/47837122/converting-group-to-float-or-int-format
comment on: http://stackoverflow.com/a/47821271
score: 0

http://stackoverflow.com/a/47814378
has comment: http://stackoverflow.com/comment/123503982
type: Answer
has body: The simplest possible implementation is just to brute-force it. We need to try all possible start points in one of the graphs: for all start points v1 in G1 try to find an isomorphism rooted at v1 in G1 to any of v2 in G2 but what does the second line mean?! Well, something like: for each neighbour i in G1[v1] for each neighbour j in G2[v2] match(i, j) note that we also have to keep track of the nodes we have matched so far and return true as soon as we find a match. We can improve matters by using the degree sequence - obviously vertices of the same degree in each graph must match, so only consider these as candidates for a match. There are, of course, much more elaborate algorithms out there, but that only really matters if you need speed or have large graphs. For reference, consider the VF2 algorithm: VF2 algorithm steps with example
score: -1
has comment: http://stackoverflow.com/comment/123509878
upvote count: 0
has comment: http://stackoverflow.com/comment/123493478
downvote count: 1
answers question: http://stackoverflow.com/q/47720207

http://stackoverflow.com/a/47790770
has body: check this link out. You can use the identifier CV_CAP_PROP_FRAME_COUNT to get the Number of frames in the video file.
answers question: http://stackoverflow.com/q/47788247
score: 1
has comment: http://stackoverflow.com/comment/82752785
downvote count: 0
upvote count: 1
type: Answer

http://stackoverflow.com/comment/82662593
type: QuestionComment
comment on: http://stackoverflow.com/q/47849106
has text: A floating point is *not* represented internally decimally, but binary. As a result `0.1` is for instance *not* a representable float. It is approximated with something `0.099999...`ish, or `0.1000...`ish. So it would be terribly unstable.
score: 7
type: Comment

http://stackoverflow.com/a/47725332
has comment: http://stackoverflow.com/comment/82411435
type: Answer
has comment: http://stackoverflow.com/comment/82411460
answers question: http://stackoverflow.com/q/47725016
has comment: http://stackoverflow.com/comment/82411418
score: 0
has body: Add after your ʼfor row in dataʼ... teams = row.split()[4] # if the number of occurrences of the first item (which is a team)... is equal to the length of the list of teams, then, all the players are from the same team. if teams.count(teams[0]) == len(teams): #same lines, but one indentation block due to the `if` condition.

http://stackoverflow.com/comment/82438028
comment on: http://stackoverflow.com/a/47738871
type: Comment
has text: Any comments on downvote?
score: 0
type: AnswerComment

http://stackoverflow.com/comment/82431305
type: QuestionComment
comment on: http://stackoverflow.com/q/47735269
has text: use `print()` to check values in variables which you use to draw - like `self.visual`. BTW: why do you create `Battleship()` everytime you draw `rect()` ?
score: 0
type: Comment

http://stackoverflow.com/comment/82375159
comment on: http://stackoverflow.com/a/47707580
has text: Thank you. In trying these code, I get TypeError: ("'Series' objects are mutable, thus they cannot be hashed", 'occurred at index 0'). Am I missing something?
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/82372945
type: QuestionComment
has text: This is similar to the question at https://stackoverflow.com/questions/38630421/how-to-execute-shell-command-and-stream-output-with-python-and-flask-upon-http-r so you may find the answer there helpful.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47706226

http://stackoverflow.com/q/47770163
score: 1
answer count: 1
tagged with: selenium
favorite count: 0
has comment: http://stackoverflow.com/comment/82503974
type: Question
has body: Trying to enter text in the active element but failing.. Can anyone help? Code is as follows. element is commented on. Using python and selenium and web driver. using time to give breaks between code to wait for loading keyboard shortcuts are used to enter the elements as names for gmail are not available. from selenium import webdriver import time from selenium.webdriver.common.keys import Keys u = input("Enter username: ") p = input("Enter password: ") a = input("Enter email address(multiple separated by comma: ") s = input("Enter subject: ") t = input("Enter text: ") browser = webdriver.Firefox() browser.get('https://accounts.google.com/ServiceLogin/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=AddSession') userid = browser.find_element_by_name("identifier") userid.send_keys(u) userid.send_keys(u'\ue007') time.sleep(2) passw = browser.find_element_by_name("password") passw.send_keys(p) passw.send_keys(u'\ue007') time.sleep(10) browser.get('https://mail.google.com/mail/u/0/#inbox?compose=new') time.sleep(5) to = browser.find_element_by_name("to") to.send_keys(a) fr = browser.find_element_by_name("subjectbox") fr.send_keys(s) fr.send_keys(Keys.TAB) x = browser.switch_to.active_element time.sleep(1) x.send_keys(t) #THIS IS NOT WORKING
accepted answer: http://stackoverflow.com/a/47770593
downvote count: 0
has answer: http://stackoverflow.com/a/47770593
upvote count: 1
tagged with: python
has title: Selenium: Trying to enter text in the active element without id but failing
type: AnsweredQuestion

http://stackoverflow.com/q/47839370
tagged with: python
has comment: http://stackoverflow.com/comment/83456757
linked to: http://stackoverflow.com/q/28365331
score: 0
tagged with: django-views
answer count: 0
has body: I have a master model with 1 to 10,000 related objects, when I choose to delete one of them, confirmation delete view takes too long to show and I really do not need to show them in that confirmation in admin. How can I overrides intermediate confirmation queryset? Thanks in advance.
has comment: http://stackoverflow.com/comment/83443608
tagged with: admin
has comment: http://stackoverflow.com/comment/82648306
type: Question
type: UnansweredQuestion
has title: How to override intermediate delete confirmation queryset in admin, I need not show related objects
tagged with: django

http://stackoverflow.com/comment/82668047
type: Comment
score: 0
type: AnswerComment
has text: Thank you for your reply! In fact, I tried this method, but still take up all the memory, I do not know why, is it because I use Supervisor, and then use sess = sv.prepare_or_wait_for_session (server.target, config = sess_config) reasons?
comment on: http://stackoverflow.com/a/47816842

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

http://stackoverflow.com/comment/82376960
comment on: http://stackoverflow.com/a/47708188
has text: @SteveDallas good idea re: `parse_dates=[0]`. Where is this new error coming from? If you haven't already, try keeping `parse_dates=[0]` and also commenting out the entire `to_datetime` line. Alternatively, if you don't mind dates being sorted in lexicographic order (Apr, Feb, ...), you can try not using `parse_dates` and also not calling the `to_datetime` line. Then, if you wanted, you could cast the `Date` column from string to datetime in the final step, sort, and write to CSV.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/82462025
type: QuestionComment
comment on: http://stackoverflow.com/q/47750684
score: 2
type: Comment
has text: What happens if the first element of the list is `"No 1"`?

http://stackoverflow.com/comment/82604962
comment on: http://stackoverflow.com/a/47786168
score: 0
type: Comment
has text: that did not seem to work for me, but you're probably right that I should look into the factory design pattern. Not quite there yet. The goal is to let anyone create a plugin by dropping a .py file into the exchanges folder
type: AnswerComment

http://stackoverflow.com/q/47803233
has answer: http://stackoverflow.com/a/47803463
possible better answer: http://stackoverflow.com/a/47803463
answer count: 2
has comment: http://stackoverflow.com/comment/82567932
downvote count: 0
favorite count: 0
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47803376
upvote count: 3
score: 3
accepted answer: http://stackoverflow.com/a/47803376
has comment: http://stackoverflow.com/comment/82568363
has comment: http://stackoverflow.com/comment/82568458
has body: For example, I understand float is usually represented by a C double, and integers have unlimited precision, per the docs. NumPy of course offers more specific types. Does, for example, the type of float in NumPy in any way impact the number's precision in memory? Or are numbers for various types stored with the same precision, and the type just implements the number differently at a higher level?
tagged with: python
has title: Do python's numeric types impact the low-level precision of a number?
has comment: http://stackoverflow.com/comment/82568564
type: Question
tagged with: numpy

http://stackoverflow.com/a/47749703
answers question: http://stackoverflow.com/q/47749674
type: Answer
score: -1
has comment: http://stackoverflow.com/comment/82459665
has comment: http://stackoverflow.com/comment/82459737
has body: The __name__ value when a module is run directly is __main__, not _main_. Change the value you check against and you should be good to go. (Remember to actually pass in some arguments though!)
downvote count: 2
upvote count: 1

http://stackoverflow.com/q/47801945
has comment: http://stackoverflow.com/comment/82697728
has answer: http://stackoverflow.com/a/47802133
accepted answer: http://stackoverflow.com/a/47802133
tagged with: excel
has comment: http://stackoverflow.com/comment/82565418
has body: I have table with several thousand lines. I need to create a function what makes urls like in pictures column. It takes npictures number, url and create new urls separate "|". | npictures | url | pictures | |-----------|----------------------|------------------------------------------------------------------------| | 2 | test.com/img/abc.jpg | test.com/img/abc.jpg | test.com/img/abc_2.jpg | | 3 | test.com/img/def.jpg | test.com/img/def.jpg | test.com/img/def_2.jpg | test.com/img/def_3.jpg | | 1 | test.com/img/ghi.jpg | test.com/img/ghi.jpg If it possible to make in Excel or make a function in python.
type: AnsweredQuestion
score: 0
has title: Python: generate filename by column value
has comment: http://stackoverflow.com/comment/82565517
has comment: http://stackoverflow.com/comment/82566143
answer count: 1
has comment: http://stackoverflow.com/comment/82565618
has comment: http://stackoverflow.com/comment/82565207
type: Question
has comment: http://stackoverflow.com/comment/82565287
has comment: http://stackoverflow.com/comment/82565213
tagged with: python

http://stackoverflow.com/q/47847891
tagged with: python
has answer: http://stackoverflow.com/a/47848029
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47849174
score: 0
has title: beautifulsoup - Fetching text either side of a br tag
answer count: 3
has body: I have unfortunately become stuck with the following problem: &lt;a href="someurl"&gt; "TEXT ONE" &lt;br&gt; "TEXT TWO" &lt;/a&gt; I need text one and text two separately. I can only obtain them as a whole providing "TEXT ONE TEXT TWO" by using "text = container.a.text", with the container being a parent of the a tags. I have tried as many ways as I could find with no success. I can't manage to use br tag properly. Thank you for any help.
type: Question
tagged with: beautifulsoup
accepted answer: http://stackoverflow.com/a/47847962
has comment: http://stackoverflow.com/comment/82660182
has comment: http://stackoverflow.com/comment/82660075
has answer: http://stackoverflow.com/a/47847962
possible better answer: http://stackoverflow.com/a/47848029

http://stackoverflow.com/comment/82391635
comment on: http://stackoverflow.com/q/47715465
has text: post sample input and expected output.
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/comment/82611610
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47824103
has text: @CharlesDuffy I think that what the OP is saying is that he's _purposefully_ not using `subprocess` because he's trying to learn about how the OS handles forks.

http://stackoverflow.com/q/47729254
answer count: 2
tagged with: pyqt5
upvote count: 1
has answer: http://stackoverflow.com/a/47776168
downvote count: 1
favorite count: 0
type: Question
has body: Here is a simple program to create 2 pushbuttons and a third pushbutton when either of the first two buttons is clicked. But it doesn't work. When I click one of the first two buttons I get the message in the console indicating it has been clicked but no 3rd button appears. Why?? Thanks! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_Form(object): def setupUi(self, Form): Form.setObjectName("Form") Form.resize(400, 300) def setup_pushButton(self, word, x, y, width, height): self.pushButton = QtWidgets.QPushButton(Form) self.pushButton.setGeometry(QtCore.QRect(x, y, width, height)) self.pushButton.setText(word) self.pushButton.clicked.connect(self.but_clicked) def create_pushButtons(self): self.setup_pushButton('apple', 100, 110, 75, 23) self.setup_pushButton('car', 20, 110, 75, 23) def but_clicked(self): print('clicked') self.setup_pushButton('house', 250, 110, 75, 23) if __name__ == "__main__": import sys app = QtWidgets.QApplication(sys.argv) Form = QtWidgets.QWidget() ui = Ui_Form() ui.setupUi(Form) ui.create_pushButtons() Form.show() sys.exit(app.exec_())
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/47755180
has title: PyQt5 - how to enable a new (third) button that fail to show after running clicked pushButton?
tagged with: qpushbutton
has comment: http://stackoverflow.com/comment/82502598
score: 0

http://stackoverflow.com/q/47705840
answer count: 2
tagged with: for-loop
has answer: http://stackoverflow.com/a/47705993
has comment: http://stackoverflow.com/comment/82371870
type: UnansweredQuestion
score: 0
has title: Error takes exactly 2 arguments (3 given)
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/82371813
has body: Hi i am trying to plot points in a google map by indexing the dictionary with a foor loop, have this dictionary of lat:long latlon = {32.1243973: -101.8856125, 32.666694: -104.233502, 32.222012: -101.819122, 32.53151: -103.353018, 32.668496: -104.235722, 32.1041336: -101.8818588} And i have this code: if __name__ == "__main__": map = Map() for latitude, longitude in latlon.iteritems(): map.add_point(latitude, longitude) I get the error TypeError: add_point() takes exactly 2 arguments (3 given) I am giving only latitude and longitude why it says i am giving 3 arguments? Thanks in advance! Edit: addint the class map: class Map(object): def __init__(self): self._points = [] def add_point(self, coordinates): self._points.append(coordinates) def __str__(self): centerLat = sum(( x[0] for x in self._points )) / len(self._points) centerLon = sum(( x[1] for x in self._points )) / len(self._points) markersCode = "\n".join( [ """new google.maps.Marker({{ position: new google.maps.LatLng({lat}, {lon}), map: map }});""".format(lat=x[0], lon=x[1]) for x in self._points ]) return """ &lt;script src="https://maps.googleapis.com/maps/api/js?v=3.exp&amp;sensor=false"&gt;&lt;/script&gt; &lt;div id="map-canvas" style="height: 100%; width: 100%"&gt;&lt;/div&gt; &lt;script type="text/javascript"&gt; var map; function show_map() {{ map = new google.maps.Map(document.getElementById("map-canvas"), {{ zoom: 8, center: new google.maps.LatLng({centerLat}, {centerLon}) }}); {markersCode} }} google.maps.event.addDomListener(window, 'load', show_map); &lt;/script&gt; """.format(centerLat=centerLat, centerLon=centerLon, markersCode=markersCode)
type: Question
has comment: http://stackoverflow.com/comment/82371808
has answer: http://stackoverflow.com/a/47705890

http://stackoverflow.com/q/47746539
favorite count: 0
tagged with: optimization
type: Question
score: 1
tagged with: python
tagged with: linear-programming
has comment: http://stackoverflow.com/comment/82509162
has comment: http://stackoverflow.com/comment/82477062
has answer: http://stackoverflow.com/a/61019980
type: UnansweredQuestion
has body: The following code gives me the best places to go to vacation keeping the costs low : from pulp import * import numpy as np import pandas as pd import re #write a scaper before hand data = pd.read_csv('clymb_adventures.csv') problem_name = 'GoingOnVacation' aval_vacation_days = 10 def optimize_vacation_schedule(aval_vacation_days): # create the LP object, set up as a minimization problem --&gt; since we want to minimize the costs prob = pulp.LpProblem(problem_name, pulp.LpMinimize) #create decision variables decision_variables = [] for rownum, row in data.iterrows(): variable = str('x' + str(rownum)) variable = pulp.LpVariable(str(variable), lowBound = 0, upBound = 1, cat= 'Integer') #make variables binary decision_variables.append(variable) print ("Total number of decision_variables: " + str(len(decision_variables))) #create objective Function -minimize the costs for the trip total_cost = "" for rownum, row in data.iterrows(): for i, schedule in enumerate(decision_variables): if rownum == i: formula = row['cost']*schedule total_cost += formula prob += total_cost print ("Optimization function: " + str(total_cost)) #create constrains - total vacation days should be no more than 14 total_vacation_days = "" for rownum, row in data.iterrows(): for i, schedule in enumerate(decision_variables): if rownum == i: formula = row['duration']*schedule total_vacation_days += formula prob += (total_vacation_days == aval_vacation_days) #now run optimization optimization_result = prob.solve() assert optimization_result == pulp.LpStatusOptimal prob.writeLP(problem_name + ".lp" ) print("Status:", LpStatus[prob.status]) print("Optimal Solution to the problem: ", value(prob.objective)) print ("Individual decision_variables: ") for v in prob.variables(): print(v.name, "=", v.varValue) if __name__ == "__main__": optimize_vacation_schedule(aval_vacation_days) Sample Dataset: destination duration cost description location 0 Baja 7 899 Hike Bike [31223,23123] 1 Nepal 11 899 culture of the Hi…
downvote count: 0
answer count: 1
tagged with: pulp
upvote count: 1
has comment: http://stackoverflow.com/comment/82490419
tagged with: operations-research
has title: Adding a constraint in Linear Programming Optimization using PULP

http://stackoverflow.com/comment/82587067
comment on: http://stackoverflow.com/q/47812615
score: 0
has text: so what is the rule for creating D_a and D_c? I understand the rationale in wanting to remove duplicates, but what do you hope to do with D_a and D_c? Sounds like there may be a better way to achieve the end goal.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47787869
answer count: 1
tagged with: django
tagged with: python
has body: I recently met a logging issue about set logging level. I have a demo django project, which is to test set log level. below is the page: The log will be written to /tmp/run.log. When I deploy it with gunicoryn + nginx(proxy static file), and has 4 gunicorn workes. Set log level only have effect to one of the workers: Above the two pictures, I set log level to ERROR, but only effect worker 74096. Here are some information and Django code. System Info: System: Centos 7.4 x64 Python: 2.7.5 Django: 1.11.2 Gunicorn: 19.7.1 Django logging config: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '[%(asctime)s] %(levelname)s [%(filename)s:%(lineno)s] %(message)s' } }, 'handlers': { 'file': { 'level': 'DEBUG', 'class': 'logging.handlers.RotatingFileHandler', 'maxBytes': 1024, 'backupCount': 5, 'filename': '/tmp/run.log', 'formatter': 'verbose' }, 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'verbose' set log level function name = "django_docker" bind = "unix:/var/run/django_docker.sock" worker_class = "egg:meinheld#gunicorn_worker" #workers = multiprocessing.cpu_count() * 2 + 1 workers = 4 reload = True umask = 0002 user = 'nginx' group = 'nginx' accesslog = "/tmp/gunicorn.access.log" errorlog = "/tmp/gunicorn.error.log" raw_env = ["DJANGO_SETTINGS_MODULE=django_docker.settings"] chdir = " /home/user/workspace/django_docker/" pidfile = "/var/run/gunicorn.pid" daemon = True logconfig_dict = { 'version':1, 'disable_existing_loggers': False, 'loggers':{ "root": {"level": "INFO", "handlers": ["console"]}, "gunicorn.error": { "level": "INFO", "handlers": ["error_file"], "propagate": 1, "qualname": "gunicorn.error" }, "gunicorn.access": { "level": "INFO", "handlers": ["access_file"], "propagate": 0, "qualname": "gunicorn.access" } }, 'handlers':{ "console": { "class": "logging.StreamHandler", "formatter": "generic", "stream": "sys.stdout" }, "error_file": { "class": "logging.FileHandler", "formatte…
accepted answer: http://stackoverflow.com/a/48129810
tagged with: logging
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48129810
linked to: http://stackoverflow.com/q/38425620
has title: Python, set log level in Django project, deployed with gunicorn and 4 workers
favorite count: 0
type: Question
tagged with: gunicorn
upvote count: 2
downvote count: 0

http://stackoverflow.com/comment/82648230
has text: Thank you as well for the quick answer, I tried implementing it and it worked I appreciate it!
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47841958
type: Comment

http://stackoverflow.com/q/47819697
has title: How to add an image to PDF using Python and create a report from esri geodatabase tables
tagged with: pdf-generation
has answer: http://stackoverflow.com/a/48507987
type: UnansweredQuestion
has body: I have an old script that uses SSReport to create and generate a PDF adding some basic data. I want to update it to include an image file and loop through some esri geodatabase tables. I don't see much documentation on the SSReport library, using 2.7. Is there a newer/better way? I don't want to have to install 3rd party package, if possible. import SSReport as REPORT pdfOutput = REPORT.openPDF(fileName) #Set up Table NumColumns = 4 report = REPORT.startNewReport(NumColumns, title = 'Report ', landscape = False, numRows = "", # probably empty titleFont = REPORT.ssTitleFont) grid = report.grid grid.writeCell((grid.rowCount, 1),"hello world",justify = "left",) grid.finalizeTable() # Will fill empty rows with spaces. report.write(pdfOutput) # write to PDF
downvote count: 0
answer count: 1
upvote count: 1
tagged with: esri
favorite count: 0
type: Question
tagged with: arcpy
score: 1
tagged with: matplotlib
tagged with: python

http://stackoverflow.com/a/47767604
has body: https://www.lfd.uci.edu/~gohlke/pythonlibs/ go to this link and search for virtualenv and download the proper wheel file and the from the downloads folder use pip install the_wheel_name
upvote count: 3
type: AcceptedAnswer
downvote count: 0
score: 3
type: Answer
accepted answer of: http://stackoverflow.com/q/47767236
answers question: http://stackoverflow.com/q/47767236

http://stackoverflow.com/comment/82360193
type: Comment
has text: While correct, this answer is much more convoluted than it needs to be.
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/47700063

http://stackoverflow.com/a/47819414
upvote count: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82601208
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/82601044
has comment: http://stackoverflow.com/comment/82601017
has body: Sounds like you could have the wrong version of OpenCV. Inside a python console run import cv2 cv2.__version__ if the version is 2.x that is likely your problem. cv2.inRange() definitely works for the recent OpenCV versions 3.2.0 +.
score: 2
has comment: http://stackoverflow.com/comment/82600886
accepted answer of: http://stackoverflow.com/q/47819168
answers question: http://stackoverflow.com/q/47819168

http://stackoverflow.com/comment/82636639
type: Comment
comment on: http://stackoverflow.com/a/47821887
has text: I got it working. It reduced the size by 700kbs haha, so not a great deal but it worked.
type: AnswerComment
score: 0

http://stackoverflow.com/q/47832354
answer count: 3
tagged with: pandas
upvote count: 3
tagged with: dataframe
has answer: http://stackoverflow.com/a/47832410
has comment: http://stackoverflow.com/comment/82627606
tagged with: string
has title: Delete specific symbols (unicode) from Pandas DataFrame Column
favorite count: 0
has answer: http://stackoverflow.com/a/47832486
accepted answer: http://stackoverflow.com/a/47832604
type: Question
has comment: http://stackoverflow.com/comment/82627574
has answer: http://stackoverflow.com/a/47832604
linked to: http://stackoverflow.com/q/50444346
has comment: http://stackoverflow.com/comment/82627484
downvote count: 0
has comment: http://stackoverflow.com/comment/82627700
tagged with: python
possible better answer: http://stackoverflow.com/a/47832486
has comment: http://stackoverflow.com/comment/82627551
has comment: http://stackoverflow.com/comment/82627687
has body: I have DataFrame (pandas): data1 = pandas.DataFrame(['привет, Вася', 'как дела?', 'уиии!!']) As you see it contains unicode symbols (cyrillic): &gt;&gt;&gt; data1 0 0 привет, Вася 1 как дела? 2 уиии!! I try to delete all specific symbols from dataframe column. I tryied: data1.apply(replace ???) data1[0].replace() and even something with lambda. But I dont know how to call replace correctly. So as I want to show all symbols must be deleted by range: x in '!@#$%^&amp;*()' or if chr(x) not in range(1040,1072) # chr() of cyrillic
duplicate of: http://stackoverflow.com/q/50444346
type: AnsweredQuestion
score: 3
tagged with: char

http://stackoverflow.com/a/47750799
has body: It's clear that you're trying to run before you can walk here. Firstly, you should concentrate on getting a simple list view to work, without getting confused about the additional complexity involved in displaying a list in a form view. So, make your view inherit from ListView, and remove all the methods. Then fix your template, so that it iterates over stock_list or object_list rather than just stock. Secondly, once you've got that working, you could try to integrate it with a form. When you do that, learn what methods to override. get_queryset must return a queryset, it should not render a template. In any case, you should almost never need to render a template manually in a class-based view, because the existing logic will do that for you. And if you want to add a queryset to the template context in a create view, for example, you should be overriding get_context_data; which needs to return a dictionary. Thirdly, if at some point you do need to render a template manually, read the documentation to learn the order of parameters to render: it is request, template_name, context, not as you have it.
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82474527
accepted answer of: http://stackoverflow.com/q/47749622
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/47749622
score: 2

http://stackoverflow.com/comment/82511411
has text: @JamesKent I have made necessary changes in code but still giving error
type: QuestionComment
comment on: http://stackoverflow.com/q/47774809
score: 0
type: Comment

http://stackoverflow.com/comment/82565263
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47801989
has text: How do I know if they are in canonical form?
type: AnswerComment

http://stackoverflow.com/q/47739050
has answer: http://stackoverflow.com/a/47893381
has title: How to erase "forwarded message" title and unwanted content from body of Enron emails?
score: 1
has answer: http://stackoverflow.com/a/51061271
tagged with: email
type: Question
answer count: 2
downvote count: 0
upvote count: 1
tagged with: nltk
type: UnansweredQuestion
has body: I am trying to append all the bodies of Enron Emails in one file so that I could process the text of these emails by eliminating Stop words and splitting it into sentences with NLTK. My problem is with forwarded and replied messages, I am not sure how to clean them. This is my code so far: import os, email, sys, re,nltk, pprint from email.parser import Parser rootdir = '/Users/art/Desktop/maildir/lay-k/elizabeth' #function that appends all the body parts of Emails def email_analyse(inputfile, email_body): with open(inputfile, "r") as f: data = f.read() email = Parser().parsestr(data) email_body.append(email.get_payload()) #end of function #defining a list that will contain bodies email_body = [] #call the function email_analyse for every function in directory for directory, subdirectory, filenames in os.walk(rootdir): for filename in filenames: email_analyse(os.path.join(directory, filename), email_body ) #the stage where I clean the emails with open("email_body.txt", "w") as f: for val in email_body: if(val): val = val.replace("\n", "") val = val.replace("=01", "") #for some reason I had many of ==20 and =01 in my text val = val.replace("==20", "") f.write(val) f.write("\n") This is the partial output: Well, with the photographer and the band, I would say we've pretty much outdone our budget! Here's the information on the photographer. I have a feeling for some of the major packages we could negotiate at least a couple of hours at the rehearsal dinner. I have no idea how much this normally costs, but he isn't cheap!---------------------- Forwarded by Elizabeth Lay/HOU/AZURIX on 09/13/99 07:34 PM ---------------------------acollins@reggienet.com on 09/13/99 05:37:37 PMPlease respond to acollins@reggienet.com To: Elizabeth Lay/HOU/AZURIX@AZURIXcc: Subject: Denis Reggie Wedding PhotographyHello Elizabeth:Congratulations on your upcoming marriage! I am Ashley Collins, Mr.Reggie's Coordinator. Linda Kessler forwarded your e.mail address to me sothat I may provide you wi…
tagged with: python
tagged with: text-processing
favorite count: 0

http://stackoverflow.com/comment/82633256
type: Comment
comment on: http://stackoverflow.com/a/47834489
has text: Sorry but I'm having difficulty in reading your code. Could you explain a little bit? Also I just realized there are words that belong to more than one class and sentences that have more than one keyword.
type: AnswerComment
score: 1

http://stackoverflow.com/comment/82665010
comment on: http://stackoverflow.com/q/47850132
type: Comment
type: QuestionComment
has text: I was making an example. Actually, the raw data is picosecond, and I want to label it as nanosecond. And I would like to manually add some words to the tick makers, e.g. change "1,2,3" to "Atom 1, Atom 2, Atom 3".
score: 0

http://stackoverflow.com/comment/82634858
type: Comment
comment on: http://stackoverflow.com/q/47835565
has text: I am not entirely sure what you are asking. Can you please provide some sample data to work with? The data provided should be a before and after.
type: QuestionComment
score: 1

http://stackoverflow.com/q/47709854
tagged with: python
upvote count: 10
has answer: http://stackoverflow.com/a/65519166
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/45874928
downvote count: 0
has comment: http://stackoverflow.com/comment/82380189
tagged with: machine-learning
has body: How could I get covariance matrix in tensorflow? Like numpy.cov() in numpy. For example, I want to get covariance matrix of tensor A, now I have to use numpy instead A = sess.run(model.A, feed) cov = np.cov(np.transpose(A)) Is there anyway to get cov by tensorflow instead of numpy? It is differnet from the problem how to compute covariance in tensorflow, where their problem is to compute covariance for two vector, while mine is to compute covariance matrix of a matrix(a 2D tensor) effectively using tensorflow API
has title: how to get covariance matrix in tensorflow?
tagged with: tensorflow
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/55431224
has comment: http://stackoverflow.com/comment/82389384
has answer: http://stackoverflow.com/a/54724463
has answer: http://stackoverflow.com/a/67528677
accepted answer: http://stackoverflow.com/a/49850652
has answer: http://stackoverflow.com/a/55431224
answer count: 5
has answer: http://stackoverflow.com/a/49850652
score: 10

http://stackoverflow.com/q/47710833
has title: the number of items at a given depth in all sub-lists of a list
tagged with: recursion
type: AnsweredQuestion
tagged with: list
downvote count: 0
score: 1
upvote count: 1
answer count: 1
accepted answer: http://stackoverflow.com/a/47710971
has comment: http://stackoverflow.com/comment/82381762
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47710971
tagged with: python
has body: I feel like i'm going at it all wrong. I am recursing at the depth of a list as if it was a Tree. This causes problems because It's an arbitrary list that can have strings, ints ... Here's what I have def visit_depth(list_, depth): if depth == 0: return 1 elif depth &gt;0: return sum([visit_depth(l, depth - 1) for l in list_]) else: return 0

http://stackoverflow.com/q/47738316
has comment: http://stackoverflow.com/comment/82436904
has title: Why is Python giving me a Variable Scope Error even after declaring global variables?
has body: I'm a Python beginner, and I'm trying to create a basic program where the user creates an account by entering a username, password and confirms the password. I've seen other questions and answers on this site, but none of them work for me. The following is my code (I am using Python 2.7): global username, password, surePassword def createAcc(): print "Welcome! Create an account below: " username = raw_input("Select a username: ") password = raw_input("Select a password: ") surePassword = raw_input("Confirm your password: ") confirmPassword() def confirmPassword(): if surePassword == password: print "Account created successfully!" else: surePassword = raw_input("Error: Incorrect confirmation. Re-enter password: ") confirmPassword() createAcc() When I run this program, I am able to enter a username and password. However, once I confirm the password, it gives me the following errors: Traceback (most recent call last): line 17, in &lt;module&gt; createAcc() line 8, in createAcc confirmPassword() line 11, in confirmPassword if surePassword == password: UnboundLocalError: local variable 'surePassword' referenced before assignment The program was supposed to just tell me whether my confirmed password is correct, and if it isn't, then tell me to re-enter the password until it is correct. Any help is appreciated, thanks in advance!
tagged with: global-variables
has comment: http://stackoverflow.com/comment/82436914
type: Question
answer count: 0
tagged with: function
type: UnansweredQuestion
tagged with: python
tagged with: variables
tagged with: scope
score: 0
has comment: http://stackoverflow.com/comment/82436839

http://stackoverflow.com/a/49496115
has body: Let's assume we have stride of 2 and kernel size of 3. Using tf.layers.conv2d with padding SAME: Case 1: pad| |pad inputs: 0 |1 2 3 4 5 |0 |_______| |_______| |_______| Case 2: |pad inputs: 1 2 3 4 5 6 |0 |_______| |_______| |_______| You can see the padding will depend on the input size. The padding with same is determined such that the output size is Math.ceil(input_size / stride). You can read more about that here. Using the fixed padding implementation of resnet: Case 1: pad| |pad inputs: 0 |1 2 3 4 5 |0 |_______| |_______| |_______| Case 2: pad| |pad inputs: 0 |1 2 3 4 5 6 |0 |_______| |_______| |_______| Padding is uniquely defined by the kernel size and stays independent of the input size.
type: Answer
score: 8
downvote count: 0
answers question: http://stackoverflow.com/q/47745397
upvote count: 8

http://stackoverflow.com/a/47812162
answers question: http://stackoverflow.com/q/47792304
downvote count: 0
upvote count: 1
score: 1
type: Answer
has body: Didn't actually figure out the exact cause but I found that it starts working if you provide additional information such as state and country and not just the address! For example: origins = ['Nordmarksvägen 15'] should be written origins = ['Nordmarksvägen 15, State, Country' ] This solved the issue in my case and now all entries are working!

http://stackoverflow.com/comment/82584432
type: QuestionComment
score: 4
has text: `[(x, data) for x in range(20, 24)]`? Keep in mind that you are only duplicating the reference. Change one dict and they all change.
type: Comment
comment on: http://stackoverflow.com/q/47811564

http://stackoverflow.com/comment/82706970
type: AnswerComment
score: 3
type: Comment
has text: One option to make all this "easier" is to use the Apache Toree project
comment on: http://stackoverflow.com/a/47870277

http://stackoverflow.com/comment/82488319
comment on: http://stackoverflow.com/q/47763342
type: Comment
type: QuestionComment
score: 0
has text: Please read this thread on what questions are on-topic for stack overflow, specifically item #4; https://stackoverflow.com/help/on-topic

http://stackoverflow.com/comment/82469496
comment on: http://stackoverflow.com/q/47754122
has text: And really, takes a bit time to learn Python - at least the basics like how to iterate over a `list` ;)
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47819819
score: 0
has comment: http://stackoverflow.com/comment/82601933
has comment: http://stackoverflow.com/comment/82602162
answer count: 0
has comment: http://stackoverflow.com/comment/82602022
has comment: http://stackoverflow.com/comment/82602313
type: Question
has body: I need to determine the business day number of a specific date. For example, if I were to enter the date December 14, 2017, I need the output to be 10th business day (the day of the month excluding weekends and holidays). I also have a custom list of holidays that I would want to provide. I'm sure I can figure this out doing the date math myself, but I was wondering if there's something already available in python that could handle this for me. I've done some searching myself and found several questions about add and subtracting business days from a date, but not returning the business day number of a specific date.
linked to: http://stackoverflow.com/q/2224742
type: UnansweredQuestion
has title: Getting the business day number using a date and holiday calendar in python
duplicate of: http://stackoverflow.com/q/2224742
tagged with: python
tagged with: date
has comment: http://stackoverflow.com/comment/82602230

http://stackoverflow.com/a/47774956
downvote count: 0
has body: In pure tensorflow: In [1]: a[1, 2, 3, 4].eval(session=sess) Out[1]: 2.1795652 In numpy: In [1]: a_np = a.eval(session=sess) In [2]: a_np[1, 2, 3, 4] Out[2]: 2.1795652 You can basically treat a tensor like a numpy array, with the difference that tf has a session to run operations.
type: Answer
answers question: http://stackoverflow.com/q/47766091
score: 1
upvote count: 1

http://stackoverflow.com/comment/82652344
has text: That is right arguments are passed by assignment in Python. but my link is correct. i edited my answer.
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/47844076
type: Comment

http://stackoverflow.com/q/47710333
accepted answer: http://stackoverflow.com/a/47711052
answer count: 1
downvote count: 0
has title: Scipy: What's the difference between fit using loc=0, floc=0?
has answer: http://stackoverflow.com/a/47711052
linked to: http://stackoverflow.com/q/21610034
favorite count: 0
has body: As I'm fitting a Weibull distribution, and also find in other questions as Fitting distribution with fixed parameters in SciPy There is a difference between fit using floc=0, and loc=0 weibull_params = 1, 2.0755160030790547, 0, 16.273031221223277 data = sp.stats.exponweib.rvs(*weibull_params, size=50000) data = data.astype(int) x = linspace(0, 55) weibull_params1 = sp.stats.weibull_min.fit(data) weibull_params2 = sp.stats.weibull_min.fit(data, loc=0) weibull_params3 = sp.stats.weibull_min.fit(data, floc=0) for weibull_params, line_style in zip([weibull_params1, weibull_params2, weibull_params3],['-','--','-.']): plt.figure() plt.hist(data, bins=arange(0,55),alpha=0.5, normed=True) y_weibull = sp.stats.weibull_min.pdf(x, *weibull_params) plot(x, y_weibull, line_style, color='black') print(weibull_params) would produce the Weibull like these: Weibull params: (0.50240047370945606, -4.501644985259555e-28, 2.9918077253782287) (2.0610053128948245, -0.45099484072568979, 16.299110670854041) #loc=0 (1.0, 0, 1.05) #floc=0 What is the difference? When should I use which one?
type: AnsweredQuestion
score: 3
tagged with: python
tagged with: scipy
type: Question
tagged with: numpy
upvote count: 3

http://stackoverflow.com/q/47755804
has body: I have this method: @api.multi @api.depends('order_picking', 'order_picking.isbn', 'contract_worksheet', 'state') def accounting_scenarios(self): for record in self: if not len(record.transporter): raise Warning('Please Enter Transporter !') elif not len(record.transporter.transp_transit): raise Warning('Please assign transit account to the transporter !') if record.state in ('awaitingraw'): record.temp = record.contract_worksheet.total_alles - record.contract_worksheet.total_totals acc_move = self.env['account.move'] move_lines = [ (0, 0, { 'name': 'name', 'debit': record.temp, 'credit': 0, 'account_id': record.transporter.transp_transit, 'date': date, 'partner_id': record.transporter, }), ] journal_id = False if record.transporter.property_account_payable: journals = self.env['account.journal'].search([ ('default_debit_account_id', '=', record.transporter.property_account_payable.id) ]) if journals: journal_id = journals[0].id acc_move.create({ 'journal_id': journal_id, 'date':date, 'state': 'draft', 'line_id': move_lines, }) elif record.state in ('work_in_progress'): record.temp2 = record.contract_worksheet.total_totals elif record.state in ('delivered'): record.transporter.transp_transit.debit = record.contract_worksheet.total_alles Whenever I try to creaet (or change to the awaitingraw) state, it throws me this: Traceback (most recent call last): File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\http.py", line 546, in _handle_exception File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\http.py", line 583, in dispatch File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\http.py", line 319, in _call_function File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\service\model.py", line 118, in wrapper File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\http.py", line 316, in checked_call File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\http.py", line 812, in __call__ File "C:\Program Files …
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47759636
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47759636
tagged with: odoo
tagged with: odoo-8
has title: Syntax error 'date' field on custom account.move - Odoo v8
tagged with: python
answer count: 1
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/comment/82401362
has text: Related: [How can I tell if a string repeats itself in Python?](https://stackoverflow.com/questions/29481088/how-can-i-tell-if-a-string-repeats-itself-in-python)
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47716298
type: QuestionComment

http://stackoverflow.com/q/47718341
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47724104
type: Question
has comment: http://stackoverflow.com/comment/82422412
has comment: http://stackoverflow.com/comment/82406160
has title: Matplotlib imshow() issues: title on top of top xlabels, and ylabels not aligned in pdf
has comment: http://stackoverflow.com/comment/82422762
tagged with: python
has comment: http://stackoverflow.com/comment/82408026
accepted answer: http://stackoverflow.com/a/47724104
has comment: http://stackoverflow.com/comment/82397646
has comment: http://stackoverflow.com/comment/82397917
has comment: http://stackoverflow.com/comment/82397103
has comment: http://stackoverflow.com/comment/82422354
has body: I'm having some issues in using imshow() from matplotlib, in specific with creating a pdf from it. I'm dealing with a 500x500 matrix which, for the sake of this question, will be just random values: np.random.seed(1) arr = np.array(np.random.random((500, 500))) The rows and columns are all labelled with different names, but for the sake of this question, let's just make them simple: labels = ["Big_Label" if x % 2 == 0 else "Bigger_Big_Label" for x in range(500)] So, I have the following code to plot that matrix: plt.rc('figure', figsize=(5,5), dpi=500) fig = plt.figure() ax = fig.add_subplot(111) im = ax.imshow(arr) # defining the same labels for rows and columns ax.set_xticklabels([''] + labels) ax.set_yticklabels([''] + labels) # showing the labels for all the ticks ax.xaxis.set_major_locator(ticker.MultipleLocator(1)) ax.yaxis.set_major_locator(ticker.MultipleLocator(1)) # personalising the ticks. In particular, labels on top ax.tick_params(axis='both', which='both', labelsize=0.5, length=0) ax.tick_params(axis='x',which='both', labelbottom='off', labeltop='on') ax.tick_params(axis='both', pad=1) # vertical labels for label in im.axes.xaxis.get_ticklabels(): label.set_rotation(90) plt.colorbar(im) plt.title("Just a Big Title With Words") # Removing outer lines because they hide part of the lines/columns ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) ax.spines['bottom'].set_visible(False) ax.spines['left'].set_visible(False) plt.savefig("fig.pdf") plt.show() The first issue is with the title because is on top of the xlabels: The second issue is, when zooming to see the ylabels and xlabels, they are not aligned. With regards the left labels, they have varying spaces between them and the plot, when I specifically coded ax.tick_params(axis='both', pad=1); if I execute this python code in an IDE or in terminal, this issue doesn't happen (they are all close to the plot). So I guess something is going on when putting this image into a pdf?. Wi…
has comment: http://stackoverflow.com/comment/82398037
has comment: http://stackoverflow.com/comment/82422183
upvote count: 2
type: AnsweredQuestion
score: 2
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/82397598
downvote count: 0
has comment: http://stackoverflow.com/comment/82422316
has comment: http://stackoverflow.com/comment/82399712
linked to: http://stackoverflow.com/q/12750355
has comment: http://stackoverflow.com/comment/82396953
answer count: 1
has comment: http://stackoverflow.com/comment/82397984
favorite count: 0
has comment: http://stackoverflow.com/comment/82397423
has comment: http://stackoverflow.com/comment/82399253

django
tags question: http://stackoverflow.com/q/47767808
tags question: http://stackoverflow.com/q/47710323
tags question: http://stackoverflow.com/q/47725993
tags question: http://stackoverflow.com/q/47839536
tags question: http://stackoverflow.com/q/47825900
tags question: http://stackoverflow.com/q/47729643
tags question: http://stackoverflow.com/q/47812089
tags question: http://stackoverflow.com/q/47843436
tags question: http://stackoverflow.com/q/47716050
tags question: http://stackoverflow.com/q/47758212
tags question: http://stackoverflow.com/q/47767236
tags question: http://stackoverflow.com/q/47801453
tags question: http://stackoverflow.com/q/47788080
tags question: http://stackoverflow.com/q/47819173
tags question: http://stackoverflow.com/q/47700347
tags question: http://stackoverflow.com/q/47851268
tags question: http://stackoverflow.com/q/47833991
tags question: http://stackoverflow.com/q/47783812
tags question: http://stackoverflow.com/q/47774470
tags question: http://stackoverflow.com/q/47707377
tags question: http://stackoverflow.com/q/47783475
tags question: http://stackoverflow.com/q/47763192
tags question: http://stackoverflow.com/q/47698836
tags question: http://stackoverflow.com/q/47823543
tags question: http://stackoverflow.com/q/47777090
tags question: http://stackoverflow.com/q/47780834
tags question: http://stackoverflow.com/q/47781196
tags question: http://stackoverflow.com/q/47769927
tags question: http://stackoverflow.com/q/47711644
tags question: http://stackoverflow.com/q/47757499
tags question: http://stackoverflow.com/q/47791384
tags question: http://stackoverflow.com/q/47836902
tags question: http://stackoverflow.com/q/47725231
tags question: http://stackoverflow.com/q/47820798
tags question: http://stackoverflow.com/q/47765771
tags question: http://stackoverflow.com/q/47827258
tags question: http://stackoverflow.com/q/47752313
tags question: http://stackoverflow.com/q/47817209
tags question: http://stackoverflow.com/q/47727735
tags question: http://stackoverflow.com/q/47780602
tags question: http://stackoverflow.com/q/47846116
tags question: http://stackoverflow.com/q/47736347
tags question: http://stackoverflow.com/q/47787869
tags question: http://stackoverflow.com/q/47790517
tags question: http://stackoverflow.com/q/47824092
tags question: http://stackoverflow.com/q/47775919
tags question: http://stackoverflow.com/q/47842368
tags question: http://stackoverflow.com/q/47766146
tags question: http://stackoverflow.com/q/47729323
tags question: http://stackoverflow.com/q/47717797
tags question: http://stackoverflow.com/q/47817872
tags question: http://stackoverflow.com/q/47751798
tags question: http://stackoverflow.com/q/47702625
tags question: http://stackoverflow.com/q/47827938
tags question: http://stackoverflow.com/q/47716841
tags question: http://stackoverflow.com/q/47855792
tags question: http://stackoverflow.com/q/47790581
tags question: http://stackoverflow.com/q/47811265
tags question: http://stackoverflow.com/q/47816044
tags question: http://stackoverflow.com/q/47839606
tags question: http://stackoverflow.com/q/47827641
tags question: http://stackoverflow.com/q/47732203
tags question: http://stackoverflow.com/q/47838059
tags question: http://stackoverflow.com/q/47844977
tags question: http://stackoverflow.com/q/47808863
tags question: http://stackoverflow.com/q/47711724
tags question: http://stackoverflow.com/q/47813004
tags question: http://stackoverflow.com/q/47809064
tags question: http://stackoverflow.com/q/47772831
tags question: http://stackoverflow.com/q/47741486
tags question: http://stackoverflow.com/q/47731160
tags question: http://stackoverflow.com/q/47706946
tags question: http://stackoverflow.com/q/47727306
tags question: http://stackoverflow.com/q/47767901
tags question: http://stackoverflow.com/q/47800567
tags question: http://stackoverflow.com/q/47777917
tags question: http://stackoverflow.com/q/47785608
tags question: http://stackoverflow.com/q/47770378
tags question: http://stackoverflow.com/q/47743447
tags question: http://stackoverflow.com/q/47739659

http://stackoverflow.com/comment/82603445
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47820550
score: 0
has text: Wow I'm silly for not remembering to do this. Thank you so much! I'll accept your answer as soon as I can :)

http://stackoverflow.com/a/47778417
type: Answer
score: 2
upvote count: 2
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82548234
answers question: http://stackoverflow.com/q/47770723
has comment: http://stackoverflow.com/comment/82533902
accepted answer of: http://stackoverflow.com/q/47770723
has body: Pandas merge has an option to add an indicator column which tells you where the data comes from. Combining this with an outer merge should give you what you are looking for. a_b = pd.merge(a, b, on=['x', 'y'],how="outer",indicator="string") a.loc[~(a_b.string=="both"),:] Testing on some made up dataframes a_rand = np.reshape(np.random.randint(8,size=40),[10,4]) b_rand = np.reshape(np.random.randint(8,size=40),[10,4]) a = pd.DataFrame(a_rand, columns = ['x','y','a1','a2']) b = pd.DataFrame(b_rand, columns = ['x','y','b1','b2']) The shared rows pd.merge(a, b, on=['x', 'y']) x y a1 a2 b1 b2 0 0 6 2 3 1 6 1 3 1 5 5 0 5 2 3 0 4 0 3 2 The outer join showing where the rows come from pd.merge(a, b, on=['x', 'y'],how="outer",indicator="string") x y a1 a2 b1 b2 string 0 0 4 1.0 7.0 NaN NaN left_only 1 0 4 2.0 1.0 NaN NaN left_only 2 0 6 2.0 3.0 1.0 6.0 both 3 5 7 0.0 6.0 NaN NaN left_only 4 5 7 2.0 5.0 NaN NaN left_only 5 3 1 5.0 5.0 0.0 5.0 both 6 3 0 4.0 0.0 3.0 2.0 both 7 1 5 2.0 5.0 NaN NaN left_only 8 6 2 0.0 2.0 NaN NaN left_only 9 4 6 6.0 5.0 NaN NaN left_only 10 0 5 NaN NaN 0.0 2.0 right_only 11 1 4 NaN NaN 4.0 4.0 right_only 12 2 7 NaN NaN 4.0 1.0 right_only 13 5 6 NaN NaN 7.0 1.0 right_only 14 3 5 NaN NaN 0.0 0.0 right_only 15 4 7 NaN NaN 3.0 4.0 right_only 16 7 2 NaN NaN 3.0 4.0 right_only Finally, your desired output a.loc[~(a_b.string=="both"),:] x y a1 a2 0 0 4 1 7 1 0 6 2 3 3 0 4 2 1 4 3 1 5 5 7 1 5 2 5 8 6 2 0 2 9 4 6 6 5

http://stackoverflow.com/q/47818858
has comment: http://stackoverflow.com/comment/82600314
has title: Python - Getting the first child of the parent element with BeautifulSoup4
accepted answer: http://stackoverflow.com/a/47819235
favorite count: 0
tagged with: beautifulsoup
type: Question
has comment: http://stackoverflow.com/comment/82599980
upvote count: 2
tagged with: python
tagged with: parent-child
score: 2
has answer: http://stackoverflow.com/a/47819235
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82600035
tagged with: http://stackoverflow.com/tag/html
answer count: 1
downvote count: 0
has body: I have the following HTML: abc1 abc2 abc3 Data1 Data2 no yes Updated def1 def2 def3 Data3 Data4 no no Updated hij1 hij2 hij3 Data5 Data6 no no Updated klm1 klm2 klm3 Data7 Data8 no yes Updated There are multiples of these tags so I am doing the following to find one where there is a child tag with class="hx" and a text of yes: if (Soup.find('table', {'id' : 'mytable'}).find('td', text='yes', attrs={'class' : 'hx'})): print "Found 'yes'" But I am interested in the first tag in the that is found. I tried doing the following, but it doesn't seem to work: print Soup.find('table', {'id' : 'mytable'}).find('td', text='yes', attrs={'class' : 'hx'}).parent.find('td')[0].text Alternatively, the following works but it seems like a really drawn out way of doing this, especially if I am not sure how many tags will be present between the two: print Soup.find('table', {'id' : 'mytable'}).find('td', text='yes', attrs={'class' : 'hx'}).previousSibling.previousSibling.previousSibling.previousSibling.previousSibling.previousSibling.text Is there a better way of doing this? Am I missing something?

http://stackoverflow.com/q/47707299
has body: I am a beginner at phyton,i\ve been using it as a proxy to my retrocomputing hobby. tghw has done this code ( https://github.com/tghw/macproxy) that filters everything but the links so that it can be opened in Macintosh classic. I wanna adapt it to windows 3.1, how can I add a beautiful soup tag that won't filter images? thank you in advance from bs4 import BeautifulSoup def macify(html): soup = BeautifulSoup(html) for tag in soup(['script', 'link', 'style', 'noscript']): tag.extract() for tag in soup(['div', 'span']): tag.replaceWithChildren() for tag in soup(): for attr in ['style', 'onclick',]: del tag[attr] return str(soup) if __name__ == '__main__': import requests html = requests.get('http://stackoverflow.com/questions/5598524/can-i-remove-script-tags-with-beautifulsoup').content html = macify(html) with open('macified.html', 'w') as fd: fd.write(html)
has title: Filtering URL and leaving links and images
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/40760441
score: 0
linked to: http://stackoverflow.com/q/5598524
answer count: 0
has comment: http://stackoverflow.com/comment/82394915
type: Question
tagged with: proxy
has comment: http://stackoverflow.com/comment/82374843

http://stackoverflow.com/a/47833977
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47833578
has body: I think your holdup is that iglob returns a generator. It is a one-use iterator that gets used during the first "for item in files" loop. You need to either replace iglob with glob (returns a list instead of a one-time use iterator), or re-invoke iglob for every loop. Read more about generators: https://wiki.python.org/moin/Generators Understanding generators in Python http://intermediatepythonista.com/python-generators And glob documentations: https://docs.python.org/3/library/glob.html Hope this helps set you in the right direction! Edit (Note): The advantage of iglob over glob is that it doesn't work with the entire list in memory. If you have a really huge list (lots of items * size in memory per item), then iglob may be expected to have performance advantages over glob.
type: Answer
accepted answer of: http://stackoverflow.com/q/47833578
score: 1

http://stackoverflow.com/a/47754659
type: Answer
answers question: http://stackoverflow.com/q/47754101
score: 0
has body: I hope this helps your case : counter = 1 currenttime = 2000 while counter &lt;=5: counter += 1 currenttime -= 314 print currenttime if you need a counter using a for loop: max_count = 5 currenttime = 2000 for counter in range(max_count): currenttime -= 314 print currenttime

http://stackoverflow.com/q/47706285
has comment: http://stackoverflow.com/comment/82372695
has comment: http://stackoverflow.com/comment/82374228
has comment: http://stackoverflow.com/comment/82372941
score: 0
has comment: http://stackoverflow.com/comment/82373064
has comment: http://stackoverflow.com/comment/82373057
has answer: http://stackoverflow.com/a/47707401
has comment: http://stackoverflow.com/comment/82372715
has comment: http://stackoverflow.com/comment/82372759
tagged with: python
answer count: 4
type: Question
has title: How can I use an 'update' function to 'open' and update if the object is not yet open?
has answer: http://stackoverflow.com/a/47707750
has comment: http://stackoverflow.com/comment/82372733
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48835732
has answer: http://stackoverflow.com/a/47706508
has comment: http://stackoverflow.com/comment/82372897
has body: My example is a progress bar In its simplest form a progress bar is bar = ProgressBar.Open() for item in list: bar.Update(count, len(list)) I would instead like my calling code to be for item in list: bar.Update(count, len(list)) I want my Update() function to Open() a bar for the caller if one is not open. The caller doesn't need any other access to the bar than to update it so there's no value in having the meter` handle. How can I retain state to tell if the Update had been previously called? I could create a global variable and keep track that way, but I have a gut sense there's a Pythonista way of doing it. Trying again, but in a way that has no application to stumble on. The base question is: I have a function that will be called multiple times. I want to do something different the first time it is called. How can a function in Python do that? In C, that of course would be a... static variable I'm just now kinda figuring it out as I type, sorry. ======================== I'm sure all these edits are not how stackoverflow is supposed to work. I'm sorry for not getting it right yet, but am very appreciative of the replies. Despite it sounding like I'm breaking all the rules of good practices, it's when looked at from the CALLER'S point of view that I had hoped to make an impact. What if the only thing you needed to do to add a progress meter, even for debugging, to your program was make a call to a progress meter update in the location you want to show progress? That's the underlying motivation. Slide in 1-line, get something cool for the trouble. This progress meter was added to my otherwise boring file de-duplicator by adding just the single call: msg = f'Deduplicating {idx} of {total_files} files\n' f'{dup_count} Dupes found\n' f'{small_count} Too small' not_cancelled = sGUI.ProgressBar('De-dupe', msg, idx, total_files)
has comment: http://stackoverflow.com/comment/82372716

http://stackoverflow.com/comment/82382594
comment on: http://stackoverflow.com/q/47711255
score: 0
type: Comment
type: QuestionComment
has text: Pls fix your indentation, and f=define `l`

http://stackoverflow.com/comment/82610593
has text: @Farhan.K This `foo()` method only accepts **un**named arguments; `**kwargs` would only accept named arguments.
type: Comment
comment on: http://stackoverflow.com/a/47818490
score: 0
type: AnswerComment

http://stackoverflow.com/q/47853063
has answer: http://stackoverflow.com/a/47853131
type: Question
downvote count: 3
has title: getting day from string timestamp
favorite count: 0
has comment: http://stackoverflow.com/comment/82670430
has body: I have a dictionary with keys which are time-stamps in string format ("2016-01-02"). Im trying to convert these keys into the day of the week (Monday, Tuesday etc..) based on name preferably and not the numbers 0-6. I've been trying to do it using different versions of the code below which I found on SE, but am having trouble. Ive been getting different errors like it doesn't take strings but when ive tried to do it with ints it doesn't work either, can anyone give a hand for key, value in adict.iteritems(): key = key.date() calendar.day_name[key.weekday()] This isn't the exact code im using ive just been doing all sorts of stuff with this main code to try to get it to work.
upvote count: 0
type: UnansweredQuestion
score: -3
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/82670417

http://stackoverflow.com/a/47823358
answers question: http://stackoverflow.com/q/47803741
score: 0
has body: I'm unable to install these packages on my machine in order to check, but this likely isn't an issue with PyCharm. Try Ctrl+Click on QtCore. I'm guessing this will take you to a file. Is pyqtProperty in that file? I'm guessing not. However, I'm guessing pyqtSignal and pyqtSlot are. A couple reasons come to mind for why this might be happening pyqtProperty is not supported with version 5.6.0 and you need to install a different version The the Python interpreter which you are using does not actually have the version installed which you think Is PyQt a python wrapper around a c++ package? I've seen it before where essentially the package was made wrong and the calls still went to c++ correctly, but they did not add in the Python object declarations correctly such that IDEs recognized them and a bug needed to be placed on the package's github.
has comment: http://stackoverflow.com/comment/86575002
type: Answer

http://stackoverflow.com/a/47827210
downvote count: 0
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/82617159
has body: Your x_val is reshaped with only 10000 rows: x_val = x_val.reshape(10000, 784).astype('float32') / 255.0 But train_rand_idxs has index values up to 50000: train_rand_idxs = np.random.choice(50000, 700) When you attempt to subset x_val with your train indices: x_val = x_val[train_rand_idxs] you are getting an error because some of the indices sampled in [0,50000) are larger than the [0,10000) range of x_val indices. Try sampling x_val with x_val[val_rand_idxs] instead.
type: Answer
answers question: http://stackoverflow.com/q/47825940
has comment: http://stackoverflow.com/comment/82617137
accepted answer of: http://stackoverflow.com/q/47825940
type: AcceptedAnswer

http://stackoverflow.com/comment/82392433
score: 0
has text: I think the best would be to give an example of the output you want, and maybe an example of how you expect you should be able to get it.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47715733

http://stackoverflow.com/q/47855605
has body: My code currently checks the username and password entered my the user and then returns to the label with the corresponding text. As shown below: from tkinter import * def Login(): global AnameEL global ApwordEL # More globals :D global ArootA global f1 global f2 ArootA = Tk() # This now makes a new window. ArootA.geometry('1280x720') ArootA.title('Admin login') # This makes the window title 'login' f1 = Frame(width=200, height=200, background="#D3D3D3") f2 = Frame(ArootA, width=400, height=200) f1.pack(fill="both", expand=True, padx=0, pady=0) f2.place(in_=f1, anchor="c", relx=.5, rely=.5) AnameL = Label(f2, text='Username: ') # More labels ApwordL = Label(f2, text='Password: ') # ^ AnameL.grid(row=1, sticky=W) ApwordL.grid(row=2, sticky=W) AnameEL = Entry(f2) # The entry input ApwordEL = Entry(f2, show='*') AnameEL.grid(row=1, column=1) ApwordEL.grid(row=2, column=1) AloginB = Button(f2, text='Login', command=CheckLogin) # This makes the login button, which will go to the CheckLogin def. AloginB.grid(columnspan=2, sticky=W) ArootA.mainloop() def CheckLogin(): checkP = Label(f2, text='') checkP.grid(row=3, column=1) if AnameEL.get() == "test" and ApwordEL.get() == "123": # Checks to see if you entered the correct data. checkP.config(text='sucess') else: checkP.config(text='fail') Login() I would like to add another feature where after 2 seconds new lines of code are ran depending on the login failed/success. For example when the user enters a wrong login I would like the text "fail" to disappear after 2 seconds and if the user enters the correct password I would like a new function to be ran after 2 seconds of the "success" being displayed. So I tried this: (also importing time at the top of my code) if AnameEL.get() == "test" and ApwordEL.get() == "123": # Checks to see if you entered the correct data. checkP.config(text='sucess') time.sleep(2) nextpage() else: checkP.config(text='fail') time.sleep(2) checkP.config(text='') def nextpage(): f1.destroy() However, th…
type: AnsweredQuestion
score: 0
tagged with: tkinter
linked to: http://stackoverflow.com/q/1918005
tagged with: python-3.5
has title: Making a label remove after a set time TkInter
answer count: 1
accepted answer: http://stackoverflow.com/a/47855846
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47855846
tagged with: time
tagged with: python

http://stackoverflow.com/q/47822077
has title: Check for a condition within an array
accepted answer: http://stackoverflow.com/a/47822151
score: 1
has answer: http://stackoverflow.com/a/47822151
answer count: 1
tagged with: arrays
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
tagged with: conditional-statements
has comment: http://stackoverflow.com/comment/82606763
tagged with: python
has body: I would like to check a condition inside an array and perform an operation on the position where the condition is met. For example, this piece of code does the job: res = somefunction(x) for i in range(x.shape[0]): for j in range(x.shape[1]): if not 6 &lt; res[i,j] &lt; 18: x[i,j] = float('nan') But I thought a faster (and shorter) way would maybe be something like this: x[not 6 &lt; somefunction(x) &lt; 18] = float('nan') But python gives the error that condition checking doesn't work in array with more than element. Is there a way to make my code go faster?
tagged with: numpy
type: AnsweredQuestion

http://stackoverflow.com/a/47757519
answers question: http://stackoverflow.com/q/47757499
upvote count: 2
score: 2
type: AcceptedAnswer
downvote count: 0
has body: This has nothing to do with the path function. As the error says, Python syntax does not allow keyword arguments - eg name='useralias_member' - before non-keyword arguments. Your extra dictionary should be before that name argument. Note however that you're also confusing path with url. The new path function doesn't use regexes, it uses the special &lt;arg:type&gt; format. If you want to use regexes, switch back to url.
has comment: http://stackoverflow.com/comment/82476716
has comment: http://stackoverflow.com/comment/82476385
type: Answer
accepted answer of: http://stackoverflow.com/q/47757499
has comment: http://stackoverflow.com/comment/82476617
has comment: http://stackoverflow.com/comment/82476579

http://stackoverflow.com/a/47842398
has body: You can also try with list comprehension : new_data=((0,'a'),(1,'b'),(2,'c')) print(tuple([(i[1],i[0])for i in new_data])) output: (('a', 0), ('b', 1), ('c', 2))
downvote count: 0
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/47841254
type: Answer

http://stackoverflow.com/q/47800755
has comment: http://stackoverflow.com/comment/82576746
type: Question
has comment: http://stackoverflow.com/comment/82576714
has body: I am trying to change my code from PyQt5 to PySide2. Most of the my scripts I simply have to change imports from PyQt5 to PySide2 and it works the same. However I tried to rework the licensewizard example in the Qt documentation from PyQt5 to PySide2. In PyQt5 it works perfectly, However, in PySide2 I get a error with exit code 139 (interrupted by signal 11: SIGSEGV). The PySide2 qwizard code for linear wizards like the class wizard example, works fine. Does anyone knows why it fails with the non linear wizards and why I get that error? Thanks The code below works for PyQt5. Replacing PyQt5 with PySide2 I get an error Process finished with exit code 132 (interrupted by signal 4: SIGILL) class IntroductionPage(QtWidgets.QWizardPage): def __init__(self): super(IntroductionPage, self).__init__() self.setTitle("Introduction") self.label = QtWidgets.QLabel("set this up") self.label.setWordWrap(True) self.layout = QtWidgets.QVBoxLayout() self.layout.addWidget(self.label) self.setLayout(self.layout) def nextId(self): return Wizard.class1 class ClassesPage1(QtWidgets.QWizardPage): def __init__(self): super(ClassesPage1, self).__init__() self.setTitle("Choices") self.setSubTitle("Choose 1") self.radButton1 = QtWidgets.QRadioButton('1A') self.radButton2 = QtWidgets.QRadioButton('1B') self.radButton3 = QtWidgets.QRadioButton('1C') self.layout = QtWidgets.QVBoxLayout() self.layout.addWidget(self.radButton1) self.layout.addWidget(self.radButton2) self.layout.addWidget(self.radButton3) self.class_selected1 = QtWidgets.QLineEdit() self.setLayout(self.layout) def nextId(self): if self.radButton2.isChecked(): return Wizard.class2 elif self.radButton3.isChecked(): return Wizard.class2 else: return Wizard.conclusion class ClassesPage2(QtWidgets.QWizardPage): def __init__(self): super(ClassesPage2, self).__init__() #self.page = QWizardPage() self.setTitle("Classes for grade 2") self.setSubTitle("Please select a Class") self.radButton1 = QtWidgets.QRadioButton('2A') self.radButton2 = Qt…
has comment: http://stackoverflow.com/comment/82562947
has answer: http://stackoverflow.com/a/47808125
tagged with: pyside2
answer count: 1
downvote count: 0
tagged with: qwizard
tagged with: pyqt5
upvote count: 1
favorite count: 0
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47808125
has comment: http://stackoverflow.com/comment/82576618
score: 1
has title: PySide2 QWizard non linear pages
tagged with: python

tensorflow
tags question: http://stackoverflow.com/q/47846236
tags question: http://stackoverflow.com/q/47759123
tags question: http://stackoverflow.com/q/47745027
tags question: http://stackoverflow.com/q/47847423
type: Tag
tags question: http://stackoverflow.com/q/47746247
tags question: http://stackoverflow.com/q/47762881
tags question: http://stackoverflow.com/q/47837880
tags question: http://stackoverflow.com/q/47821890
tags question: http://stackoverflow.com/q/47742120
tags question: http://stackoverflow.com/q/47727679
tags question: http://stackoverflow.com/q/47824318
tags question: http://stackoverflow.com/q/47784433
tags question: http://stackoverflow.com/q/47836295
tags question: http://stackoverflow.com/q/47835350
tags question: http://stackoverflow.com/q/47746646
tags question: http://stackoverflow.com/q/47803066
tags question: http://stackoverflow.com/q/47796396
tags question: http://stackoverflow.com/q/47787615
tags question: http://stackoverflow.com/q/47816231
tags question: http://stackoverflow.com/q/47848606
tags question: http://stackoverflow.com/q/47765595
tags question: http://stackoverflow.com/q/47720893
tags question: http://stackoverflow.com/q/47795309
tags question: http://stackoverflow.com/q/47739284
tags question: http://stackoverflow.com/q/47775771
tags question: http://stackoverflow.com/q/47729101
tags question: http://stackoverflow.com/q/47817135
tags question: http://stackoverflow.com/q/47813919
tags question: http://stackoverflow.com/q/47750291
tags question: http://stackoverflow.com/q/47754614
tags question: http://stackoverflow.com/q/47833697
tags question: http://stackoverflow.com/q/47840527
tags question: http://stackoverflow.com/q/47725080
tags question: http://stackoverflow.com/q/47783391
tags question: http://stackoverflow.com/q/47796534
tags question: http://stackoverflow.com/q/47723705
tags question: http://stackoverflow.com/q/47737307
tags question: http://stackoverflow.com/q/47783481
tags question: http://stackoverflow.com/q/47709715
tags question: http://stackoverflow.com/q/47734748
tags question: http://stackoverflow.com/q/47843875
tags question: http://stackoverflow.com/q/47775067
tags question: http://stackoverflow.com/q/47793584
tags question: http://stackoverflow.com/q/47753736
tags question: http://stackoverflow.com/q/47804792
tags question: http://stackoverflow.com/q/47703393
tags question: http://stackoverflow.com/q/47795391
tags question: http://stackoverflow.com/q/47724077
tags question: http://stackoverflow.com/q/47826706
tags question: http://stackoverflow.com/q/47766440
tags question: http://stackoverflow.com/q/47716395
tags question: http://stackoverflow.com/q/47762691
tags question: http://stackoverflow.com/q/47725664
tags question: http://stackoverflow.com/q/47842339
tags question: http://stackoverflow.com/q/47836670
tags question: http://stackoverflow.com/q/47726203
tags question: http://stackoverflow.com/q/47707793
tags question: http://stackoverflow.com/q/47763565
tags question: http://stackoverflow.com/q/47744964
tags question: http://stackoverflow.com/q/47699506
tags question: http://stackoverflow.com/q/47785317
tags question: http://stackoverflow.com/q/47804120
tags question: http://stackoverflow.com/q/47816303
tags question: http://stackoverflow.com/q/47698121
tags question: http://stackoverflow.com/q/47699569
tags question: http://stackoverflow.com/q/47841879
tags question: http://stackoverflow.com/q/47822996
tags question: http://stackoverflow.com/q/47808093
tags question: http://stackoverflow.com/q/47766091
tags question: http://stackoverflow.com/q/47708375
tags question: http://stackoverflow.com/q/47762287
tags question: http://stackoverflow.com/q/47746758
tags question: http://stackoverflow.com/q/47770361
tags question: http://stackoverflow.com/q/47709854
tags question: http://stackoverflow.com/q/47834768
tags question: http://stackoverflow.com/q/47815701
tags question: http://stackoverflow.com/q/47722292
tags question: http://stackoverflow.com/q/47760111
tags question: http://stackoverflow.com/q/47770096

http://stackoverflow.com/q/47732604
tagged with: key
favorite count: 0
has title: Python game keys are not responding
score: 1
has answer: http://stackoverflow.com/a/47732686
has answer: http://stackoverflow.com/a/47732773
has body: I am trying to implement a Python game (aliens.py from the PyGame package) but when I run it, I can't move my player or do any shooting... I run it on Mac OS X, python3 and have a french keyboard. Could this have anything to do the fact that it does not take any of my keyboard commands? On the screen of my terminal I see: ^[ (when I press esc), ^[[D (when I press the left arrow), ^[[C (when I press the right arrow), ^[[A (when I press the upwards arrow), ^[[B (when I press the downwards arrow ... Is this normal? It does not help replacing K_RIGHT with ^[[C. #!/usr/bin/env python import random, os.path #import basic pygame modules import pygame from pygame.locals import * #see if we can load more than standard BMP if not pygame.image.get_extended(): raise SystemExit("Sorry, extended image module required") #game constants MAX_SHOTS = 2 #most player bullets onscreen ALIEN_ODDS = 22 #ances a new alien appears BOMB_ODDS = 60 #chances a new bomb will drop ALIEN_RELOAD = 12 #frames between new aliens SCREENRECT = Rect(0, 0, 940, 480) SCORE = 0 main_dir = os.path.split(os.path.abspath(__file__))[0] def load_image(file): "loads an image, prepares it for play" file = os.path.join(main_dir, 'data', file) try: surface = pygame.image.load(file) except pygame.error: raise SystemExit('Could not load image "%s" %s'%(file, pygame.get_error())) return surface.convert() def load_images(*files): imgs = [] for file in files: imgs.append(load_image(file)) return imgs class dummysound: def play(self): pass def load_sound(file): if not pygame.mixer: return dummysound() file = os.path.join(main_dir, 'data', file) try: sound = pygame.mixer.Sound(file) return sound except pygame.error: print ('Warning, unable to load, %s' % file) return dummysound() # each type of game object gets an init and an # update function. the update function is called # once per frame, and it is when each object should # change it's current position and state. the Player # object actually gets a "move" function inst…
tagged with: pygame
has comment: http://stackoverflow.com/comment/82426087
tagged with: macos
type: Question
answer count: 2
type: UnansweredQuestion
downvote count: 0
upvote count: 1
tagged with: python

http://stackoverflow.com/comment/82450421
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47742575
has text: Seems to me like you've just moved the problem from one class to another. Also, injecting responsibility into a class via a decorator seems like just a sneaky way of getting around a crucial restriction imposed by the SRP design methodology.
score: 1

list
tags question: http://stackoverflow.com/q/47855220
tags question: http://stackoverflow.com/q/47793608
type: Tag
tags question: http://stackoverflow.com/q/47708608
tags question: http://stackoverflow.com/q/47851320
tags question: http://stackoverflow.com/q/47726797
tags question: http://stackoverflow.com/q/47834078
tags question: http://stackoverflow.com/q/47765206
tags question: http://stackoverflow.com/q/47833313
tags question: http://stackoverflow.com/q/47825127
tags question: http://stackoverflow.com/q/47713028
tags question: http://stackoverflow.com/q/47854248
tags question: http://stackoverflow.com/q/47738372
tags question: http://stackoverflow.com/q/47742481
tags question: http://stackoverflow.com/q/47815193
tags question: http://stackoverflow.com/q/47852113
tags question: http://stackoverflow.com/q/47769111
tags question: http://stackoverflow.com/q/47732330
tags question: http://stackoverflow.com/q/47741763
tags question: http://stackoverflow.com/q/47701545
tags question: http://stackoverflow.com/q/47832880
tags question: http://stackoverflow.com/q/47785229
tags question: http://stackoverflow.com/q/47757494
tags question: http://stackoverflow.com/q/47729256
tags question: http://stackoverflow.com/q/47740909
tags question: http://stackoverflow.com/q/47802324
tags question: http://stackoverflow.com/q/47804572
tags question: http://stackoverflow.com/q/47837839
tags question: http://stackoverflow.com/q/47826694
tags question: http://stackoverflow.com/q/47840847
tags question: http://stackoverflow.com/q/47758510
tags question: http://stackoverflow.com/q/47824935
tags question: http://stackoverflow.com/q/47760454
tags question: http://stackoverflow.com/q/47855766
tags question: http://stackoverflow.com/q/47702966
tags question: http://stackoverflow.com/q/47741420
tags question: http://stackoverflow.com/q/47843707
tags question: http://stackoverflow.com/q/47784843
tags question: http://stackoverflow.com/q/47708123
tags question: http://stackoverflow.com/q/47724521
tags question: http://stackoverflow.com/q/47722356
tags question: http://stackoverflow.com/q/47842743
tags question: http://stackoverflow.com/q/47740456
tags question: http://stackoverflow.com/q/47722693
tags question: http://stackoverflow.com/q/47724017
tags question: http://stackoverflow.com/q/47766038
tags question: http://stackoverflow.com/q/47719483
tags question: http://stackoverflow.com/q/47791929
tags question: http://stackoverflow.com/q/47748320
tags question: http://stackoverflow.com/q/47814968
tags question: http://stackoverflow.com/q/47706170
tags question: http://stackoverflow.com/q/47706644
tags question: http://stackoverflow.com/q/47796541
tags question: http://stackoverflow.com/q/47750482
tags question: http://stackoverflow.com/q/47733554
tags question: http://stackoverflow.com/q/47716630
tags question: http://stackoverflow.com/q/47742258
tags question: http://stackoverflow.com/q/47704461
tags question: http://stackoverflow.com/q/47719240
tags question: http://stackoverflow.com/q/47825367
tags question: http://stackoverflow.com/q/47728148
tags question: http://stackoverflow.com/q/47791633
tags question: http://stackoverflow.com/q/47777718
tags question: http://stackoverflow.com/q/47706418
tags question: http://stackoverflow.com/q/47762345
tags question: http://stackoverflow.com/q/47779876
tags question: http://stackoverflow.com/q/47704612
tags question: http://stackoverflow.com/q/47776052
tags question: http://stackoverflow.com/q/47758858
tags question: http://stackoverflow.com/q/47795746
tags question: http://stackoverflow.com/q/47760355
tags question: http://stackoverflow.com/q/47836242
tags question: http://stackoverflow.com/q/47819417
tags question: http://stackoverflow.com/q/47775026
tags question: http://stackoverflow.com/q/47854710
tags question: http://stackoverflow.com/q/47845258
tags question: http://stackoverflow.com/q/47715666
tags question: http://stackoverflow.com/q/47726706
tags question: http://stackoverflow.com/q/47710681
tags question: http://stackoverflow.com/q/47850270

http://stackoverflow.com/q/47769192
tagged with: autohotkey
has comment: http://stackoverflow.com/comment/82501017
tagged with: python
has comment: http://stackoverflow.com/comment/82511581
has answer: http://stackoverflow.com/a/55830393
score: 2
has body: I tried to write a ahk script which allows me to bind the currently opened window to a hotkey. The way it works is that if you press ALTGR + , + any character, the ProcessPath of the current window gets saved. Now, using ALTGR + the choosen character, i either switch to this window if its already opened (Activate) or run the .exe file for this process. To delete the hotkey i use ALTGR + . + respective key. All hotkeys get saved in an .ini file so the settings don't get lost. It all works fine..... but the thing is: I had to copy the code for every key (i wrote a python script to copy it for me). Is there a way to set dynamic hotkeys in ahk? Here is my code: iniFile := "winshortcut.ini" Runs a certain process or switches to the window if already running. The loop works around some delays that might occur. RunOrActivate(key, Target) { SplitPath, Target, TargetNameOnly, , TargetEXE Process, Exist, %TargetNameOnly% If (ErrorLevel &gt; 0){ WinActivate, ahk_pid %ErrorLevel% } else { if (Target != "ERROR") { Run, %Target% if (TargetEXE != "exe"){ WinGetTitle, x, A if (x != TargetNameOnly){ Loop, 5 { Sleep, 100 Run, %Target% } } } } else { TrayTip AltGr+%key%, No binding, 2 } } } This line reads the path for a key from the ini file. I had to copy it for every single key: IniRead, PATH_w, %iniFile%, savedKeys, w IniRead, PATH_r, %iniFile%, savedKeys, r ... This block handles the hotkeys for saving, deleting or changing the process for a single key (w). This is copied and changed 23 times: ; ############## w ############## &lt;^&gt;!w:: if (GetKeyState(",")){ if (PATH_w != "ERROR") { SplitPath, PATH_w, TITLE_w_old } WinGet PATH_w, ProcessPath, A SplitPath, PATH_w, TITLE_w if (TITLE_w == "Explorer.EXE"){ WinGetTitle, TITLE_w, A for w in ComObjCreate("Shell.Application").Windows if (TITLE_w = w.Document.Folder.Self.Name) { PATH_w := % w.Document.Folder.Self.Path } } IniWrite, %PATH_w%, %iniFile%, savedKeys, w if (TITLE_w_old) { if (TITLE_w_old != TITLE_w){ TrayTip Changing bind…
tagged with: dynamic
upvote count: 2
type: UnansweredQuestion
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/82511470
favorite count: 0
type: Question
has title: AutoHotKey dynamic hotkeys
tagged with: hotkeys
tagged with: shortcut

http://stackoverflow.com/comment/82564689
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47801694
type: AnswerComment
has text: As I said I can't use bs4 or any other third party module

http://stackoverflow.com/q/47766045
has body: I'm looking to create a Django form with a checkbox.Irrespective of weather I check or uncheck the box,it is not detected in POST request.Here is the code of the template- {% csrf_token %} Repeat Sentence? Next Here is my forms.py- from django import forms class AnnotateForm(forms.Form): repeat=forms.BooleanField(required=False) Here is my views logic- if request.method=="POST": form = AnnotateForm(request.POST) if form.is_valid(): print(request.POST)#prints only csrf_token in Query_dict print(form.cleaned_data["repeat"])#Always false Irrespective of weather the checkbox is checked or not,the print statement always gives False. I know there are questions similar,but they don't solve my problem.
upvote count: 2
has answer: http://stackoverflow.com/a/47766087
tagged with: django
possible better answer: http://stackoverflow.com/a/77146838
downvote count: 1
type: Question
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47766087
has title: Django form with checkbox is always False
has comment: http://stackoverflow.com/comment/82493358
score: 1
tagged with: python
tagged with: checkbox
favorite count: 0
has answer: http://stackoverflow.com/a/77146838
has comment: http://stackoverflow.com/comment/82493390
answer count: 2

http://stackoverflow.com/comment/82457631
has text: Thanks @Ben Darnell!
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47739848
type: Comment

http://stackoverflow.com/q/47756139
tagged with: python
accepted answer: http://stackoverflow.com/a/47809530
type: Question
has answer: http://stackoverflow.com/a/47809530
tagged with: multithreading
answer count: 1
upvote count: 1
downvote count: 1
favorite count: 0
type: AnsweredQuestion
score: 0
has title: Make multiple threads exec a single command
tagged with: python-multithreading
has body: I'm actually working on a little script that creates dummy files, used to fill a disk (usb key in general), for security purpose. Actually, I use the threading module, and even if I kind of know how to use it, I'm still struggling with something. Here's a bit of code that introduce my problem. import sys if sys.version_info[0] &gt;= 3: # Check Python's version, and dismiss Python 3 raise Exception('You must use Python 2 to launch this program') from threading import Thread index, running = 0, True def main(): multiThreading() def multiThreading(): thread1 = Thread(target=fill) # Both threads targets fill() thread1.daemon = True thread1.start() thread2 = Thread(target=fill) thread2.daemon = True thread2.start() while running: # Without this infinite loop, the program exits while the threads are still on, which is not really a problem in this bit of code, # as they finish their tasks, but it is one in the original script. Anyway. if running is False: return None def fill(): # this function normally fills a chosen drive with data global index global running while running: index += 1 print index if index &gt;= 10: running = False # The index is used AFTER index += 1 is executed, which causes a problem if __name__ == '__main__': main() print 'End' Which returns 12 34 56 78 910 End &gt;&gt;&gt; The thing is that actually, I want it to print 1 2 3 ... 10 End &gt;&gt;&gt; But both thread pass by the index, which adds 2 instead of 1 (2 because there is two thread of course) I tried with watch dogs, with other functions, but the result is the same. And also, a one-time watch dog isn't the solution, as I want to make a loop as many times as needed. Predicted question: Why use multi-threads ? Because it makes the file creation much faster. Do you have a solution ? Thanks a lot for reading ! PS: Please forgive my few English mistakes, not being my mother tongue :p ; double-PS: if you got a better idea for the title, my ears are all open

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

http://stackoverflow.com/q/47704137
has answer: http://stackoverflow.com/a/47704242
answer count: 2
downvote count: 0
accepted answer: http://stackoverflow.com/a/47704191
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/47704242
linked to: http://stackoverflow.com/q/913590
has answer: http://stackoverflow.com/a/47704191
tagged with: django
tagged with: python
has title: Django - ValueError: too many values to unpack (expected 2)
has body: I try to use make a droplist from model. USER_TYPE = { 'admin': "Admin", 'patient': "Patient", 'helper': "Helper", 'therapist': "Therapist", } class User(AbstractBaseUser): user_type = models.CharField(max_length=10, choices=USER_TYPE, default="patient") However, I get this error: ValueError: too many values to unpack (expected 2) Thanks in advance!
upvote count: 2
type: AnsweredQuestion
score: 2

http://stackoverflow.com/comment/82676291
type: QuestionComment
has text: `key.pressed()` always returns list with `True/False` for all keys. Use `event.key` it get pressed key.
score: 0
comment on: http://stackoverflow.com/q/47855725
type: Comment

http://stackoverflow.com/q/47850817
score: 2
type: AnsweredQuestion
answer count: 3
has body: I would like the current window to be replaced with the contents instead of a new window opening up. Here is my code: from tkinter import * def adminLogin(): global AnameEL global ApwordEL # More globals :D global ArootA ArootA = Tk() # This now makes a new window. ArootA.geometry('1280x720') ArootA.title('Admin login') # This makes the window title 'login' f1 = Frame(width=200, height=200, background="#D3D3D3") f2 = Frame(ArootA, width=400, height=200) f1.pack(fill="both", expand=True, padx=0, pady=0) f2.place(in_=f1, anchor="c", relx=.5, rely=.5) AnameL = Label(f2, text='Username: ') # More labels ApwordL = Label(f2, text='Password: ') # ^ AnameL.grid(row=1, sticky=W) ApwordL.grid(row=2, sticky=W) AnameEL = Entry(f2) # The entry input ApwordEL = Entry(f2, show='*') AnameEL.grid(row=1, column=1) ApwordEL.grid(row=2, column=1) AloginB = Button(f2, text='Login', command=CheckAdmin) # This makes the login button, which will go to the CheckLogin def. AloginB.grid(columnspan=2, sticky=W) def CheckAdmin(): if AnameEL.get() == "test" and ApwordEL.get() == "123" : # Checks to see if you entered the correct data. r = Tk() # Opens new window r.title('Sucess') loginC = Button(r, text='Add new login', command=Signup) loginC.grid(columnspan=2, sticky=W) r.mainloop() else: r = Tk() r.title('Error') r.geometry('550x450') rlbl = Label(r, text='\n[!] Invalid Login') rlbl.pack() r.mainloop() def Signup(): # This is the signup definition, global pwordE # These globals just make the variables global to the entire script, meaning any definition can use them global nameE global roots roots = Tk() # This creates the window, just a blank one. roots.title('Signup') # This renames the title of said window to 'signup' intruction = Label(roots, text='Please Enter new Credidentials\n') # This puts a label, so just a piece of text saying 'please enter blah' intruction.grid(row=0, column=0, sticky=E) # This just puts it in the window, on row 0, col 0. If you want to learn more look up a tkinter …
downvote count: 0
has answer: http://stackoverflow.com/a/47853322
accepted answer: http://stackoverflow.com/a/47851159
possible better answer: http://stackoverflow.com/a/47853322
favorite count: 0
type: Question
upvote count: 2
tagged with: python-3.x
tagged with: tkinter
tagged with: python-3.5
has answer: http://stackoverflow.com/a/47851713
tagged with: python
has answer: http://stackoverflow.com/a/47851159
has title: How to replace window TKInter

http://stackoverflow.com/q/47847283
tagged with: recursion
has comment: http://stackoverflow.com/comment/82659106
answer count: 3
possible better answer: http://stackoverflow.com/a/47847481
tagged with: python
has comment: http://stackoverflow.com/comment/82660167
has comment: http://stackoverflow.com/comment/82670725
has answer: http://stackoverflow.com/a/47847391
has comment: http://stackoverflow.com/comment/82658885
has answer: http://stackoverflow.com/a/47853147
has comment: http://stackoverflow.com/comment/82658821
type: AnsweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/82667432
upvote count: 3
has title: How to write a function to get if a family is balanced on not?
has answer: http://stackoverflow.com/a/47847481
accepted answer: http://stackoverflow.com/a/47847391
has body: The goal is to find out if a family is balanced or not. For example we have the following 2 arrays: kids= { "Adam": ["Matjaž", "Cilka", "Daniel"], "Aleksander": [], "Alenka": [], "Barbara": [], "Cilka": [], "Daniel": ["Elizabeta", "Hans"], "Erik": [], "Elizabeta": ["Ludvik", "Jurij", "Barbara"], "Franc": [], "Herman": ["Margareta"], "Hans": ["Herman", "Erik"], "Jožef": ["Alenka", "Aleksander", "Petra"], "Jurij": ["Franc", "Jožef"], "Ludvik": [], "Margareta": [], "Matjaž": ["Viljem"], "Petra": [], "Tadeja": [], "Viljem": ["Tadeja"], } The kids array tells you who's family member is who's kid. (It's a global array) money= { "Adam": 42, "Aleksander": 3, "Alenka": 3, "Barbara": 37, "Cilka": 242, "Daniel": 4, "Erik": 32, "Elizabeta": 8, "Franc": 16, "Herman": 12, "Hans": 55, "Jožef": 7, "Jurij": 5, "Ludvik": 37, "Margareta": 20, "Matjaž": 142, "Petra": 3, "Tadeja": 45, "Viljem": 55 } The money array tells you how much money does every person have. We have this function: def balanced(person, money): #should return true if the family is balanced or not, if not returns false For example: we call the function: balanced("Adam", money) It should return true because Adam has 3 kids and those kids have kids. And if we add their amount of money we get the same value. Matjaž (142) Viljem (55) Tadeja (45) SUM = 242 Cilka (242) no kids SUM = 242 Daniel (4) Elizabeta (8) Ludvik (37) Jurij (5) Franc (16) Jožef (7) Alenka (3) Aleksander (3) Petra (3) Barbara (37) Hans (55) Herman (12) Margareta (20) Erik (32) SUM = 242 All 3 kids return total money value of 242 and because all 3 do that it returns TRUE as a balanced family. I have already written a function to calculate the money of a family member and their descendants: def amount_of_money(person, money): amount = 0 for kid in kids[person]: amount += amount_of_money(kid, money) return amount + money[person] Now how would I write the function balanced for it to return true if this happens?
downvote count: 1
has comment: http://stackoverflow.com/comment/82658868
favorite count: 0
type: Question

http://stackoverflow.com/a/47742800
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/82446068
answers question: http://stackoverflow.com/q/47742557
type: Answer
has body: There are a few things wrong here. The biggest problem is that it's not valid in HTML to have multiple elements with the same ID; but you are assigning every div in your loop the id likes. You should add that to the list of classes and bind your jQuery even to .likes instead.
has comment: http://stackoverflow.com/comment/82446102
downvote count: 0

http://stackoverflow.com/comment/82577686
has text: I want to delete by bootbox. I don't understand what should i write in bootbox confirm block. I want to delete by clicking bootbox confirm, not redirecting another page.
type: Comment
score: 1
comment on: http://stackoverflow.com/q/47806862
type: QuestionComment

http://stackoverflow.com/q/47760454
upvote count: 1
has comment: http://stackoverflow.com/comment/82482171
has title: Python - How to sum a certain section of a list
has answer: http://stackoverflow.com/a/47760482
downvote count: 1
has answer: http://stackoverflow.com/a/47760485
favorite count: 0
has body: I have a list of 90 values and I would like to find the value of the sum of the first 30 of these values. Is there a way I can do this easily?
type: Question
type: UnansweredQuestion
tagged with: sum
tagged with: python
score: 0
tagged with: list
answer count: 3
has answer: http://stackoverflow.com/a/47775467

http://stackoverflow.com/q/47762432
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82486427
tagged with: vector
downvote count: 0
answer count: 1
score: 6
accepted answer: http://stackoverflow.com/a/47762594
has body: I have a large number of numpy vectors, each of shape (3,) with 8 bit integer values: vec = np.random.randint(2**8, size=3) I'd like to quantize those vectors to a smaller space by some known reduction factor. I know I can hammer this out in a series of operations by defining another vector with values that define the amount of information loss, dividing vec by that vector, then cooercing the resulting values back to integers: &gt;&gt;&gt; vec = np.random.randint(2**8, size=3) &gt;&gt;&gt; denominator = np.full(3, 8) &gt;&gt;&gt; divided = vec / denominator &gt;&gt;&gt; ints = divided.astype(int) &gt;&gt;&gt; ints *= denominator &gt;&gt;&gt; &gt;&gt;&gt; vec array([205, 182, 99]) &gt;&gt;&gt; ints array([200, 176, 96]) Is there a faster way to quantize these numpy vectors though? I'd be very grateful for any ideas others can share on this question.
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47762594
has title: Fast way to quantize numpy vectors
has comment: http://stackoverflow.com/comment/82486397
has comment: http://stackoverflow.com/comment/82486649
tagged with: python
has comment: http://stackoverflow.com/comment/82486572
upvote count: 6
tagged with: numpy

http://stackoverflow.com/q/47703599
type: AnsweredQuestion
score: 0
tagged with: list
tagged with: random
answer count: 2
has comment: http://stackoverflow.com/comment/82367332
has answer: http://stackoverflow.com/a/47703628
has comment: http://stackoverflow.com/comment/82367966
has title: Deleting elements from list depending on randomly generated number
has body: This function should take a list of viruses like [ATCG, GTAC.....] and a mortalityProb (float between 0 and 1) that represents the chance of a virus to die / get deleted from the list. It should return a new list with the remaining viruses. Each of the viruses has an individual chance to die, so with a mortalityProb of say 0.6, there should be around 60% of the viruses remaining. It should be doable in 2 lines (including def kill(viruses, mortalityProb):) and my line of code using list comprehensions. def kill(viruses, mortalityProb): for i in viruses: if random.randint(0, 100) &lt; (mortalityProb * 100): del i return viruses This does not quite work, but I can't get a grasp on why.
type: Question
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/47703628
has answer: http://stackoverflow.com/a/47703693
accepted answer: http://stackoverflow.com/a/47703693
tagged with: python
has comment: http://stackoverflow.com/comment/82367389

http://stackoverflow.com/a/47761073
accepted answer of: http://stackoverflow.com/q/47749014
score: 1
answers question: http://stackoverflow.com/q/47749014
type: Answer
has body: this is not connected to the django / python and I think this is more likely OS specific question, so my suggestion would be to use cron: 0 9 * * * __user__ /abs/path/to/service start 59 23 * * * __user__ /abs/path/to/service stop cron job timing format is following: minute | hour | day | month | day of week | user | command 0 9 * * * (1) (2) 59 23 * * * (1) (2) writing only minutes and hours, means that this job should run everyday. for user section (1) it indicates which user runs the command and for command section (2), this is the indicator what command should be run hope this helps
downvote count: 0
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/82638084
type: Comment
type: QuestionComment
has text: Yes. I did `pip`, I did `conda`. I can see my libs in local. But within spark, I dont see anythin.
score: 0
comment on: http://stackoverflow.com/q/47810164

http://stackoverflow.com/q/47820798
tagged with: python
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/82606911
score: 0
has comment: http://stackoverflow.com/comment/82757108
has title: Form does not save time in database with generic class
tagged with: django-models
has body: Good afternoon, I have a form with different types of fields, including one where one hour is required (where I do not use a timepicker but a textinput). For the development of this form I use a .form class next to a generic view createview; where all the data except those that require the entry of an hour are saved. When presenting the data using another generic view, this field appears as None. I have tried, among several things, using the TextInput instead of the TimeInput, but without any difference. This is my model: class Reserva(models.Model): ESTADOS_CHOICES = ( ('AP', 'Aprobado'), ('PE', 'Pendiente'), ('NE', 'Negado'), ) SALONES_CHOICES = ( ('S1', 'Salon 1'), ('S2', 'Salon 2'), ('S3', 'Salon 3'), ('CA', 'Cafeteria'), ) usuario = models.ForeignKey(User) fecha_peticion = models.DateTimeField(auto_now_add=True, blank=True, null=True) asunto = models.CharField(max_length=80) fecha_inicio = models.DateField(blank=True, null=True) fecha_fin = models.DateField(blank=True, null=True) salon = models.CharField(max_length=2, choices=SALONES_CHOICES, blank=True, null=True) hora_inicio = models.TimeField() hora_fin = models.TimeField() estado = models.CharField(max_length=2, choices=ESTADOS_CHOICES, blank=True, null=True) observaciones = models.CharField(max_length=100, blank=True, null=True) Este es mi formulario de la clase .form. class F_EnvioPeticion(forms.ModelForm): hora_inicio = forms.TimeField(input_formats=('%H:%M'), widget=forms.TimeInput(format='%H:%M')), class Meta: model = Reserva fields =[ 'asunto', 'fecha_inicio', 'fecha_fin', 'salon', 'hora_inicio', 'estado', ] labels = { 'asunto' :'Este es mi asunto:', 'fecha_inicio' :'Día de inicio', 'fecha_fin' :'Día de fin', 'salon' :'Elija un salón:', 'hora_inicio' :'Ingrese una hora de inicio', 'estado' :'Estado', } widgets = { 'asunto' : forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Ejm: Reunión de docentes'}), 'fecha_inicio' : forms.DateInput(attrs={'class': 'form-control', 'placeholder': 'dia/m…
tagged with: django-forms
has comment: http://stackoverflow.com/comment/82604068
type: Question
answer count: 0
tagged with: django
type: UnansweredQuestion

http://stackoverflow.com/comment/82664434
has text: If I try `python3`, i get this error: https://imgur.com/a/aHrqp
comment on: http://stackoverflow.com/q/47849923
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82385442
comment on: http://stackoverflow.com/q/47712751
type: Comment
type: QuestionComment
score: 0
has text: Split the string and take the element by index

http://stackoverflow.com/comment/82651114
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47843557
type: Comment
has text: what does mean "the third"? Can you paste how e.g. the first line should look like?

http://stackoverflow.com/a/47752936
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/47752723
answers question: http://stackoverflow.com/q/47752723
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82467069
has body: The documentation states that: notifier.loop() The call to this method is blocking until we type c-c (sigint) So that's what you need to do. Send a sigint signal. Some ways of doing that: How to send a SIGINT to Python from a bash script? How to pass SIGINT to child process with Python subprocess.Popen() using shell = true Send SIGINT in python to os.system Send SIGINT to Python subprocess using os.kill as if pressing Ctrl+C
score: 3
upvote count: 3

http://stackoverflow.com/comment/82494351
score: 0
type: Comment
type: QuestionComment
has text: Why would `r.text[2]` return "b" in your example?
comment on: http://stackoverflow.com/q/47766577

http://stackoverflow.com/q/47848857
has comment: http://stackoverflow.com/comment/82662088
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/47848937
favorite count: 0
type: Question
has body: First of all, I have to say that I am beginer in Python programming.I have connected sensor to RPi 3 UART port. I found out in Internet working program for this sensor. With a little bit my modifications, it writes me to file result of measuring. The code is below: import serial import time import sys import json import datetime import binascii class pmsA003(): def __init__(self, dev): self.serial = serial.Serial(dev, baudrate=9600, timeout=3) def __exit__(self, exc_type, exc_value, traceback): self.serial.close() def setIdel(self): idelcmd = b'\x42\x4d\xe4\x00\x00\x01\x73' ary = bytearray(idelcmd) self.serial.write(ary) def setNormal(self): normalcmd = b'\x42\x4d\xe4\x00\x01\x01\x74' ary = bytearray(normalcmd) self.serial.write(ary) def vertify_data(self): if not self.data: return False return True def read_data(self): while True: b = self.serial.read(1) if b == b'\x42': data = self.serial.read(31) if data[0] == b'\x4d': self.data = bytearray(b'\x42' + data) if self.vertify_data(): return self._PMdata() def _PMdata(self): d = {} d['apm10'] = self.data[4] * 256 + self.data[5] d['apm25'] = self.data[6] * 256 + self.data[7] d['apm100'] = self.data[8] * 256 + self.data[9] return d if __name__ == '__main__': con = pmsA003('/dev/ttyAMA0') d = con.read_data() print(d) with open('/home/pi/ramdisk/PMA003', 'a') as f: f.write("%s" % (d)) As the result, I got on console and in the file string like this: {'apm10': 150, 'apm100': 244, 'apm25': 228} But my goal is to have CSV like file in the form: ,value_of_apm10, value_of_apm25, value_of_apm100 Can anybody help me to modify the code above?
upvote count: 0
type: UnansweredQuestion
tagged with: raspberry-pi3
downvote count: 1
has title: Changing output form of Python script
answer count: 1

http://stackoverflow.com/comment/82663949
type: Comment
type: QuestionComment
has text: As a start, you can try write correct python code from what you understand of javascript code...
comment on: http://stackoverflow.com/q/47849713
score: 1

http://stackoverflow.com/q/47712093
downvote count: 0
has answer: http://stackoverflow.com/a/47713042
has body: This code pings various machines. Could you please help me change this code so if a process of pinging hangs for more then 7 seconds it shuts down and returns some flag? (I'd like to pull various data from machines using WMI. For that I'll change ping function to something else. The issue is on some machines WMI is corrupted and process of pulling data hangs indefinitely. Timeout is needed.) import multiprocessing.dummy import subprocess import numpy as np import time start_time = time.time() def ping(ipadd): try: response = subprocess.check_output(['ping', ipadd]) return True except subprocess.CalledProcessError as e: return False #print(ping('10.25.59.20')) machine_names = \ ''' ya.ru microsoft.com www.google.com www.amazon.com www.nasa.com '''.split() np_machine_names = np.array(machine_names) p = multiprocessing.dummy.Pool(7) ping_status = p.map(ping, machine_names) np_ping_status = np.fromiter(ping_status, dtype=bool) print(*np_machine_names[np_ping_status], sep = '\n') run_time = time.time() - start_time print(f'Runtime: {run_time:.0f}') UPDATE: While I appreciate for the tip on adding timeout to subprocess the question remains. How do I shutdown hanged function? Let's say I've changed pinging to pulling WMI data from a machine (this one pulls list of installed software from Windows machine). There is no subprocess to set timer on: #pip install pypiwin32 import win32com.client strComputer = "." objWMIService = win32com.client.Dispatch("WbemScripting.SWbemLocator") objSWbemServices = objWMIService.ConnectServer(strComputer,"root\cimv2") colItems = objSWbemServices.ExecQuery("Select * from Win32_Product") for objItem in colItems: print( "Caption: ", objItem.Caption )
linked to: http://stackoverflow.com/q/44522089
has comment: http://stackoverflow.com/comment/82386018
favorite count: 0
type: Question
tagged with: python-multiprocessing
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47712621
linked to: http://stackoverflow.com/q/13606867
tagged with: multithreading
score: 6
tagged with: python
has title: Timeout for multiprocessing?
upvote count: 6
linked to: http://stackoverflow.com/q/29494001
accepted answer: http://stackoverflow.com/a/47731786
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47731786
answer count: 3
has comment: http://stackoverflow.com/comment/82386497
has comment: http://stackoverflow.com/comment/111075437
possible better answer: http://stackoverflow.com/a/47713042
has comment: http://stackoverflow.com/comment/82386384
linked to: http://stackoverflow.com/q/26063877
has comment: http://stackoverflow.com/comment/82424800

http://stackoverflow.com/comment/82660970
has text: use button `{}` to format code and results.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47844877
type: QuestionComment

http://stackoverflow.com/q/47717248
accepted answer: http://stackoverflow.com/a/47717319
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/82394815
has answer: http://stackoverflow.com/a/47717319
possible better answer: http://stackoverflow.com/a/47725682
has answer: http://stackoverflow.com/a/47725682
has comment: http://stackoverflow.com/comment/82395200
tagged with: iteration
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82394827
answer count: 2
tagged with: for-loop
has comment: http://stackoverflow.com/comment/82394801
has title: Appending a value from a list to an empty list in python
upvote count: 0
score: -2
downvote count: 2
has comment: http://stackoverflow.com/comment/82395355
tagged with: python
has comment: http://stackoverflow.com/comment/82394783
has body: One list contains values and one is empty. I want to take out two values from the list with data and place it into the empty list using a for loop. I know how to get one value. However, I am not sure how to get the other. Here is my code below: all_fruits = ['apples', 'cherry', 'pear', 'strawberry', 'peach'] # The above list is a list of all fruits # Now lets creat a blank list called favorite fruit favorite_fruit = [] # The objective is to choose two fruits from the all fruits list and append them to the favorite fruit list for fruit in all_fruits: if fruit == 'apples': favorite_fruit.append(fruit) print favorite_fruit Output: ['apples'] I want the favorite_fruit variable to output ['apples', 'peaches'] or ['apples', 'cherry']. How do I go about doing this? Thanks

http://stackoverflow.com/comment/82652824
type: Comment
type: QuestionComment
has text: Does the function in [this lookalike](https://stackoverflow.com/q/22996833/2564301) question help?
score: 0
comment on: http://stackoverflow.com/q/47844219

http://stackoverflow.com/q/47777776
answer count: 2
has body: I want to keep a track of exceptions inside a dictionary and return the same. However when I do so, finally block gives me an empty dictionary. The logic pretty much works for scalars. Can someone explain the behavior please. In scalar context: def test(): temp = 1 try: raise ValueError("sdfs") except: temp = 2 finally: temp = temp + 3 return temp test() 5 With dictionary: def test(): temp = dict() try: raise ValueError("something") except Exception as error: print("error is :{}".format(error)) temp['except'] = "something" + error finally: return temp test() error is : something {}
possible better answer: http://stackoverflow.com/a/47777951
downvote count: 0
has comment: http://stackoverflow.com/comment/82520640
has title: Why does return inside finally gives empty dictionary?
has comment: http://stackoverflow.com/comment/82517556
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47777938
tagged with: try-catch
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47777938
tagged with: exception
score: 5
upvote count: 5
has answer: http://stackoverflow.com/a/47777951
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82516815

http://stackoverflow.com/comment/82389996
type: AnswerComment
score: 0
type: Comment
has text: Make sure the list comprehension is properly formatted as a single line.
comment on: http://stackoverflow.com/a/47714611

http://stackoverflow.com/comment/82713163
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47850765
has text: @jason-r-coombs I find this works in site.py main file, but when I use this decorator on a different part of the site in another file, it is in the namespace, but not found in the "Toolbox": @cherrypy.tools.validate_user() AttributeError: 'Toolbox' object has no attribute 'validate_user'

http://stackoverflow.com/q/47774903
tagged with: python-pbr
type: Question
tagged with: setuptools
score: 1
has comment: http://stackoverflow.com/comment/99836858
favorite count: 0
has comment: http://stackoverflow.com/comment/99813907
upvote count: 2
answer count: 0
tagged with: pybind11
tagged with: python
type: UnansweredQuestion
has title: using a custom build with pbr
downvote count: 1
has body: I am trying to use pbr for a python package that has an extension module that uses pybind11. There is a pybind11 cmake example repo showing how to use cmake to build an extension module from setup.py. My question is: How can I incorporate this custom extension module build into a pbr-based setup.py setup.cfg? In particular, how do I use the custom extension classes, CMakeBuild and CMakeExtension, from setup.cfg?

http://stackoverflow.com/comment/82504653
type: Comment
type: QuestionComment
has text: So what is the question? I don't get it.
score: 0
comment on: http://stackoverflow.com/q/47771106

wincrypt
type: Tag
tag name: wincrypt
tags question: http://stackoverflow.com/q/47773488

http://stackoverflow.com/comment/82493369
comment on: http://stackoverflow.com/q/47765824
type: QuestionComment
has text: @Gary02127 I've tried `if notes is None: notes = 'N/A'` and other variations but I still get the same probelm. If I remove 'notes' then the error happens with 'Office', and so on.
type: Comment
score: 0

http://stackoverflow.com/q/47761619
has title: When trying to run a test train split, I am running into a key error, what should I do?
has answer: http://stackoverflow.com/a/47761788
upvote count: 2
tagged with: pandas
answer count: 1
score: 1
downvote count: 1
favorite count: 0
type: Question
tagged with: keyerror
type: UnansweredQuestion
has body: I'm having an issue when running the following code, I have no idea what to do: fd2['Close'] = fd2['Close'].apply(lambda x: 1 if x == '300' else 0) X_train, X_test, y_train, y_test = \ train_test_split(fd2['Volume_(BTC)'].values, fd2['Close'].values) KeyError Traceback (most recent call last) /Users/traviskerr/anaconda3/lib/python3.6/site- packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance) 2392 try: -&gt; 2393 return self._engine.get_loc(key) 2394 except KeyError: pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc (pandas/_libs/index.c:5239)() pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc (pandas/_libs/index.c:5085)() pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item (pandas/_libs/hashtable.c:20405)() pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item (pandas/_libs/hashtable.c:20359)() KeyError: 'Close' During handling of the above exception, another exception occurred: KeyError Please help! Thanks!
tagged with: python

http://stackoverflow.com/comment/118575724
type: Comment
has text: Any nice link for *wheels* (rather than source)?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/58632080

http://stackoverflow.com/q/47706246
upvote count: 0
has comment: http://stackoverflow.com/comment/82373212
downvote count: 2
answer count: 1
has comment: http://stackoverflow.com/comment/82373156
tagged with: selenium
has title: selenium python get weird
has comment: http://stackoverflow.com/comment/82373203
tagged with: web-scraping
favorite count: 0
has body: This code is meant to scrape google translate, I use selenium to scrape every possible translation for a given word. Here is the code: from selenium import webdriver driver = webdriver.Chrome("E:\Tutorial\Driver\chromedriver.exe") words = ['girl', 'cat', 'dog', 'bird', 'man'] for word in words: driver.get("https://translate.google.com.eg/?hl=en&tab=wT#en/fr/" + word) translations = driver.find_elements_by_class_name('gt-baf-word-clickable') for text in translations: print(text.text) And the thing is the scraper just do the job for the first word only.
type: Question
type: AnsweredQuestion
score: -2
accepted answer: http://stackoverflow.com/a/47706550
tagged with: python
has answer: http://stackoverflow.com/a/47706550

http://stackoverflow.com/q/47766521
type: AnsweredQuestion
score: 0
has body: After upgrading one of my packages (django-registration), I received this error while trying to run python manage.py runserver The output was as I have shown below. I thought that python3.5/site-packages/confusable_homoglyphs/categories.py might be missing and I re installed the package confusable_homoglyphs , but to no avail .It threw the same error Also after that, a file name =3.0.0.txt was created inside my project folder which had this written below Requirement already satisfied: confusable_homoglyphs in ./myvenv/lib/python3.5/site-packages I tried to remove the package and add that package (even inside n outside my virtual env). But it threw the same error as below. (myvenv) shubhendu@shubhendu-HP-Pavilion-g6-Notebook-PC:/home/foodballbear$ python manage.py runserver Performing system checks... Unhandled exception in thread started by &lt;function check_errors.&lt;locals&gt;.wrapper at 0x7f320538d400&gt; Traceback (most recent call last): File "/home/foodballbear/myvenv/lib/python3.5/site-packages/confusable_homoglyphs/categories.py", line 141, in &lt;module&gt; categories_data = load('categories.json') File "/home/foodballbear/myvenv/lib/python3.5/site-packages/confusable_homoglyphs/utils.py", line 33, in load with open('{}/{}'.format(os.getcwd(), filename), 'r') as file: FileNotFoundError: [Errno 2] No such file or directory: '/home/foodballbear/categories.json' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/foodballbear/myvenv/lib/python3.5/site-packages/confusable_homoglyphs/categories.py", line 144, in &lt;module&gt; if generate(): File "/home/foodballbear/myvenv/lib/python3.5/site-packages/confusable_homoglyphs/categories.py", line 111, in generate file = get(url) File "/home/foodballbear/myvenv/lib/python3.5/site-packages/confusable_homoglyphs/utils.py", line 24, in get return urlopen(url).read().decode('utf-8').split('\n') File "/usr/lib/python3.5/http/client.py", line 461, in read s =…
has comment: http://stackoverflow.com/comment/82495125
tagged with: package
has answer: http://stackoverflow.com/a/47766779
has answer: http://stackoverflow.com/a/47766855
accepted answer: http://stackoverflow.com/a/47766855
tagged with: python
has comment: http://stackoverflow.com/comment/82494324
type: Question
answer count: 2
has title: Django python manage.py runserver giving exception Datafile not found, datafile generation failed
possible better answer: http://stackoverflow.com/a/47766779
tagged with: django
tagged with: virtualenv

http://stackoverflow.com/comment/82489201
type: QuestionComment
score: 0
has text: Thank you, How can I make head function only return the print statement?
type: Comment
comment on: http://stackoverflow.com/q/47763887

http://stackoverflow.com/a/47768570
has comment: http://stackoverflow.com/comment/83717040
has comment: http://stackoverflow.com/comment/83718489
upvote count: 1
has comment: http://stackoverflow.com/comment/83744584
has body: That's not how it works. Whenever you add a new property to a existing model you have to put the old entities again into the datastore to get that property. To get it at all no matter what the default value is.
downvote count: 1
has comment: http://stackoverflow.com/comment/83689388
type: Answer
has comment: http://stackoverflow.com/comment/82614181
has comment: http://stackoverflow.com/comment/83660713
answers question: http://stackoverflow.com/q/47749851
score: 0

http://stackoverflow.com/comment/82646279
comment on: http://stackoverflow.com/a/47839410
type: Comment
score: 0
type: AnswerComment
has text: Actually the program is working perfectly fine, it just gives me that error (multiple times), after a few hours of runtime, and gets slower and slower. If silencing this Error helps, that would be enough already. I will let it run and check it tomorrow and respond here how it worked. Thanks!

http://stackoverflow.com/comment/82457594
comment on: http://stackoverflow.com/a/47748616
type: Comment
has text: Yes, my fault. Need swap values in `in1d` - `mask = np.in1d(df_hourly.index.date, df_outlayers.index.date)`
score: 0
type: AnswerComment

http://stackoverflow.com/comment/82477494
type: Comment
has text: @user5996916 I think, when you use `set` it gives only the unique synonyms. For example, I tried for `good` and I for 65 synonyms and when I used `set` i got only 37.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47757700

http://stackoverflow.com/a/47792670
downvote count: 0
score: 3
has body: An alternative if you do want to encode multiple categorical features is to use a Pipeline with a FeatureUnion and a couple custom Transformers. First need two transformers - one for selecting a single column and one for making LabelEncoder usable in a Pipeline (The fit_transform method only takes X, it needs to take an optional y to work in a Pipeline). from sklearn.base import BaseEstimator, TransformerMixin class SingleColumnSelector(TransformerMixin, BaseEstimator): def __init__(self, column): self.column = column def transform(self, X, y=None): return X[:, self.column].reshape(-1, 1) def fit(self, X, y=None): return self class PipelineAwareLabelEncoder(TransformerMixin, BaseEstimator): def fit(self, X, y=None): return self def transform(self, X, y=None): return LabelEncoder().fit_transform(X).reshape(-1, 1) Next create a Pipeline (or just a FeatureUnion) which has 2 branches - one for each of the categorical columns. Within each select 1 column, encode the labels and then one hot encode. import pandas as pd import numpy as np from sklearn.preprocessing import LabelEncoder, OneHotEncoder, FunctionTransformer from sklearn.pipeline import Pipeline, make_pipeline, FeatureUnion pipeline = Pipeline([( 'encoded_features', FeatureUnion([('countries', make_pipeline( SingleColumnSelector(0), PipelineAwareLabelEncoder(), OneHotEncoder() )), ('names', make_pipeline( SingleColumnSelector(1), PipelineAwareLabelEncoder(), OneHotEncoder() )) ])) ]) Finally run your full dataframe through the Pipeline - it will one hot encode each column separately and concatenate at the end. df = pd.DataFrame([["AUS", "Sri"],["USA","Vignesh"],["IND", "Pechi"],["USA","Raj"]], columns=['Country', 'Name']) X = df.values transformed_X = pipeline.fit_transform(X) print(transformed_X.toarray()) Which returns (first 3 columns are the countries, second 4 are the names) [[ 1. 0. 0. 0. 0. 1. 0.] [ 0. 0. 1. 0. 0. 0. 1.] [ 0. 1. 0. 1. 0. 0. 0.] [ 0. 0. 1. 0. 1. 0. 0.]]
type: Answer
answers question: http://stackoverflow.com/q/47790854
upvote count: 3

http://stackoverflow.com/comment/82674896
score: 0
comment on: http://stackoverflow.com/q/47855193
type: Comment
has text: Just tried. Not facing the same error but got a new one. "The operation is neither 'array op array' (where arrays have the same size and the same number of channels), nor 'array op scalar', nor 'scalar op array' in function arithm_op" at the line **base_image=cv2.addWeighted(base_image,0.5,im,0.5,0)** Which is weird because I have used the resize function to make sure the size remains same after each iteration.
type: QuestionComment

http://stackoverflow.com/comment/82503482
comment on: http://stackoverflow.com/a/47770905
score: 0
has text: http://www.peterjbentley.com/heartchallenge/spectrograms1.jpg Help me out a bit more on this If you look at the plot above, I need to identify the max peak. I had a look at the f[m] values, can you explain what those values are exactly and how do I obtain the single highest point in the frequence vs time plot?
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/82518849
score: 0
type: Comment
type: QuestionComment
has text: @MCBama thanks for the intro to sets, they may be quite useful for another separate speedup I am trying to do.
comment on: http://stackoverflow.com/q/47778162

http://stackoverflow.com/comment/82590049
type: Comment
type: AnswerComment
has text: Isn't there any other way to accomplish that without converting all numbers in strings? This solution is definitely not pythonic and unbelievably ugly.
comment on: http://stackoverflow.com/a/47814192
score: 0

http://stackoverflow.com/q/47851571
tagged with: range
tagged with: python
score: 4
tagged with: slice
upvote count: 6
has title: Why doesn't Python3's range/slice object support containment testing for other ranges/slices?
possible better answer: http://stackoverflow.com/a/47851621
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/44565297
downvote count: 2
has answer: http://stackoverflow.com/a/47851798
has answer: http://stackoverflow.com/a/47851621
has body: Python3's range objects support O(1) containment checking for integers (1) (2) So one can do 15 in range(3, 19, 2) and get the correct answer True However, it doesn't support containment checking b/w two ranges a = range(0, 10) b = range(3, 7) a in b # False b in a # False, even though every element in b is also in a a &lt; b # TypeError: '&lt;' not supported between instances of 'range' and 'range' It seems that b in a is interpreted as is any element in the range 'a' equal to the object 'b'? However, since the range cannot contain anything but integers, range(...) in range(...) will always return False. IMHO, such a query should be answered as is every element in range 'b' also in range 'a'? Given that range only stores the start, stop, step and length, this query can also be answered in O(1). The slice object doesn't help either. It doesn't implement the __contains__ method, and the __lt__ method simply compares two slices as tuples (which makes no sense) Is there a reason behind the current implementation of these, or is it just a "it happened to be implemented this way" thing?
favorite count: 0
type: Question
answer count: 3
linked to: http://stackoverflow.com/q/30081275
has answer: http://stackoverflow.com/a/47851627
accepted answer: http://stackoverflow.com/a/47851627

http://stackoverflow.com/comment/123454705
comment on: http://stackoverflow.com/a/69454134
score: 0
type: Comment
has text: @gboffi Thanks. It's not really sawing off my branch though, it's putting gitk onto a branch, sawing off that branch, then noticing gitk is a bird that depends on its wings and doesn't care if the branch is there or not. gitk needs git and nothing from the Anaconda environment as far as I can tell. And it's in a subshell so it doesn't affect anything else.
type: AnswerComment

http://stackoverflow.com/q/47808562
favorite count: 0
tagged with: messaging
type: AnsweredQuestion
upvote count: 8
tagged with: state-management
tagged with: webserver
tagged with: python
score: 8
tagged with: reactive-programming
type: Question
has comment: http://stackoverflow.com/comment/82579275
has comment: http://stackoverflow.com/comment/82578707
has title: Are there reactive state libraries like Mobx for Python?
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/53109664
has body: I'm looking for reactive state libraries like Mobx for Python, i.e. on server-side rather than client-side of a web application. Mobx is similar to classic reactive libraries like RxPY, but has a different focus: It is not so much avout the low-level event dispatching, but reacting on data changes, recalculating derived values (but only those affected, and being lazy on non-observed dependent values). And Mobx determines dependencies of calculated values automatically. Also, the Vue framework has such functionality built-in, with an even better syntax, with the upside (as well as downside) by being closely tied to the framework. Alas, both are JavaScript and targeted at client-side / user interface. So my specific questions are: Are there similar reactive state libraries for Python? Do these provide integration for storing/observing data in files? (This would essentially be an inotify-based build system, but more fine-grained and more flexible.) Do these provide integration with relational databases? (Yes, there is a conceptual gap to be bridged, and it probably works only as long a single server instance accesses the database. It would still be very useful for wide range of applications.) Do these provide integration with webserver frameworks? (i.e. received HTTP requests trigger state changed and reclaculations, some calculated values are JSON structures which are observed by the client through web sockets, long polling or messaging systems.)
has answer: http://stackoverflow.com/a/53109664

http://stackoverflow.com/comment/82562720
type: Comment
has text: Sounds like most XML I've worked with. That's why a library like BeautifulSoup can be helpful cause you can pull out odd bits of XML as long as the oddness is consistent between months.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47800599

http://stackoverflow.com/comment/82483743
type: Comment
comment on: http://stackoverflow.com/a/47761118
type: AnswerComment
has text: I like this idea with list :) If in list use tuples `(text, time)` then it can display every text with different time :) Almost like slide show.
score: 0

http://stackoverflow.com/comment/82618314
score: 0
type: Comment
has text: @Callie you're going to have to update your question to include how you're using pytest and a representative DataFrame... it's possibly a wild goose chase otherwise...
comment on: http://stackoverflow.com/a/47827561
type: AnswerComment

http://stackoverflow.com/q/47841820
downvote count: 0
has comment: http://stackoverflow.com/comment/82649662
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/89847701
has comment: http://stackoverflow.com/comment/82670647
tagged with: docker
has body: I've my django application running using gunicorn inside docker container. Randomly, the container stops responding to network calls. Container is up and running. I've checked the stats too for cpu or memory usages and they seem to be fine. My docker version: Client: Version: 1.13.0 API version: 1.25 Go version: go1.7.3 Git commit: 49bf474 Built: Tue Jan 17 09:50:17 2017 OS/Arch: linux/amd64 Server: Version: 1.13.0 API version: 1.25 (minimum version 1.12) Go version: go1.7.3 Git commit: 49bf474 Built: Tue Jan 17 09:50:17 2017 OS/Arch: linux/amd64 Experimental: false Curl command response: * Hostname was NOT found in DNS cache * Trying 127.0.0.1... * Connected to localhost (127.0.0.1) port 8001 (#0) &gt; GET /api/health/ HTTP/1.1 &gt; User-Agent: curl/7.35.0 &gt; Host: localhost:8001 &gt; Accept: */* &gt; No response for above is received. Although ping inside the container works fine. My fabfile looks like this: def create_gunicorn_container(tag_name, version, port, network=None): docker_options = env.copy() docker_options.update({'tag_name': tag_name, 'version': version, 'port': port}) if network: docker_options['network'] = network env.sudo( 'docker run -v %(log_root)s:/ebs1/logs --name my_app_server -p%(port)s:8001 --network=%(network)s ' \ '--env-file=%(env_file)s -itd %(DOCKER_REGISTRY)s/%(tag_name)s:%(version)s ' \ '%(gunicorn_script_path)s' % docker_options) Docker File: # Dockerfile # FROM directive instructing base image to build upon FROM python:2-alpine ARG req_file=requirements.txt RUN mkdir -p /usr/src/app WORKDIR /usr/src/app COPY requirements /usr/src/app/requirements COPY requirements.txt /usr/src/app COPY external_config /usr/src/app/external_config RUN apk add --update bash \ &amp;&amp; rm -rf /var/cache/apk/* \ &amp;&amp; apk add --no-cache --virtual .build-deps \ build-base libxslt libxml2 libxslt-dev libxml2-dev postgresql-dev libffi-dev \ &amp;&amp; pip install -r $req_file \ &amp;&amp; find /usr/local \ \( -type d -a -name test -o -name tests …
answer count: 0
score: 3
upvote count: 3
has title: Docker container stops responding to network calls
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/89472360
tagged with: gunicorn
has comment: http://stackoverflow.com/comment/82648642
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82647865

http://stackoverflow.com/q/47783106
has answer: http://stackoverflow.com/a/47783160
accepted answer: http://stackoverflow.com/a/47783160
favorite count: 0
type: Question
type: AnsweredQuestion
score: 3
upvote count: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/47783341
possible better answer: http://stackoverflow.com/a/47783341
tagged with: python
tagged with: date
has body: I have this problem where 1 of the columns in my df is entered in as string, but I want to convert it into end of date month in python. For example, Id Name Date Number 0 1 A 201601 5 1 2 B 201602 6 2 3 C 201603 4 The Date column has the year and month as string. Ideally, my goal is: Id Name Date Number 0 1 A 01/31/2016 5 1 2 B 02/29/2016 6 2 3 C 03/31/2016 4 I was able to do this on excel using Endmonth and cut string, but when I tried pd.to_datetime in python, it didn't work. Thanks!
answer count: 2
has title: Pandas convert string to end of month date
downvote count: 0

http://stackoverflow.com/q/47790430
score: 0
has body: When I check a checkbox in Tkinter the value of checkbox gets vanished. This problem appears in Linux only. The same code I am using in windows and it is working Fine. I Referred this link to make this gui How to create a tree view with checkboxes in Python Code: import Tkinter as tk import Tix as tix def selectItem(item): if cl.getstatus(item) == 'on': print("Checked") if cl.getstatus(item) == 'off': print("Unchecked") root = tix.Tk() cl = tix.CheckList(root,browsecmd=selectItem) cl.pack() cl.hlist.add("CL1", text="Test") cl.setstatus("CL1","off") cl.hlist.add("CL1.Item1", text="child") cl.setstatus("CL1.Item1","off") root.mainloop() Before check : After check : As you can see in the image that checkbox Test disappears after click on Test.This problem is happening only in Linux.Can anyone Give me any Solution ?
answer count: 1
tagged with: python
type: Question
tagged with: tkinter
tagged with: tix
has title: Value gets vanished when i check a checkbox in Tkinter
tagged with: checkbox
linked to: http://stackoverflow.com/q/5104330
accepted answer: http://stackoverflow.com/a/47809070
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47809070

http://stackoverflow.com/a/47710687
has body: It seems like Z_{e_x} is the computation of Z for whatever e_x is. So the formula you have is just for a single english word e_x. So you'd probably need a vector/map for each word. Might look something like this Z = {x: 0 for x in all_english_words} for x in Z.keys(): for y in all_foreign_words: for s in S: Z[x] += &lt;your_function&gt;
type: Answer
answers question: http://stackoverflow.com/q/47710588
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47710588
has comment: http://stackoverflow.com/comment/82381276

http://stackoverflow.com/comment/82434422
comment on: http://stackoverflow.com/q/47737021
type: Comment
has text: After the edit you made, the error changed, so should your post be updated, because your code and the error mentioned are not related now
type: QuestionComment
score: 0

http://stackoverflow.com/comment/82638184
score: 0
type: QuestionComment
has text: @bigbounty what will be the correct way to do this?
type: Comment
comment on: http://stackoverflow.com/q/47837093

http://stackoverflow.com/comment/82396836
type: AnswerComment
has text: stats.binom_test(1500, store.answered.sum(), 0.0233, alternative = 'two-sided') I applied binom this way: 1500 observed amount, store.answered.sum() - sum over all observations, 0.0233 - expected frequency of that label
type: Comment
score: 0
comment on: http://stackoverflow.com/a/47708736

http://stackoverflow.com/q/47831176
tagged with: shell
has comment: http://stackoverflow.com/comment/82625208
has comment: http://stackoverflow.com/comment/82625697
has title: shell script, executing program with input and save input combined with output in output
type: Question
has body: I am developing an assignment server, where students can upload their program solutions. It should work wither several programming languages. For testing the programs I am executing a shell script and passing the test-cases and file as arguments like that: printf '10\n3\n+\n' | ./eval_python steps.py Its working, that's not the problem. For the output I am getting something like that: running python script with shell script: $ How much steps? Step size? Counting up (+) or down (-) ? Step 0: 3 $ Step 1: 6 $ Step 2: 9 $ Step 3: 12 $ Step 4: 15 $ [..] This format makes evaluation quite difficult and also maybe confuse students, because they don't see the inputs (when you run the python script from shell, the output looks like in the example below). For the evaluation the difficulty is, the students must not name their inputs like in this solution, it would be also okay if they just ask Steps? instead of How much steps? . running python script directly from shell: $ How much steps? 10 $ Step size? 3 $ Counting up (+) or down (-)? + $ Step 0: 3 $ Step 1: 6 $ Step 2: 9 $ Step 3: 12 $ Step 4: 15 $ [..] Is there a way to combine the inputs in the output? Or maybe other ideas how I can solve this problems? Thanks a lot!
upvote count: 2
possible better answer: http://stackoverflow.com/a/47831920
has comment: http://stackoverflow.com/comment/82630499
has answer: http://stackoverflow.com/a/47835765
downvote count: 0
accepted answer: http://stackoverflow.com/a/47832728
has comment: http://stackoverflow.com/comment/82625444
has comment: http://stackoverflow.com/comment/82625262
has answer: http://stackoverflow.com/a/47831920
favorite count: 0
has comment: http://stackoverflow.com/comment/82625125
has comment: http://stackoverflow.com/comment/82625150
has answer: http://stackoverflow.com/a/47832728
score: 2
type: AnsweredQuestion
tagged with: linux
tagged with: bash
answer count: 3
has comment: http://stackoverflow.com/comment/82627481
has comment: http://stackoverflow.com/comment/82625338
tagged with: python

http://stackoverflow.com/comment/82443807
score: 0
type: AnswerComment
has text: I have large list of choices is there a way to read it directly from html?
type: Comment
comment on: http://stackoverflow.com/a/47741789

http://stackoverflow.com/comment/82480408
has text: Sorry, I forgot your `reset_index` statement, with that it works great! :) Thanks
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47759488
score: 0

http://stackoverflow.com/a/47776702
has comment: http://stackoverflow.com/comment/82593044
type: AcceptedAnswer
type: Answer
score: 3
has comment: http://stackoverflow.com/comment/82591080
accepted answer of: http://stackoverflow.com/q/47776460
upvote count: 3
has comment: http://stackoverflow.com/comment/82592996
downvote count: 0
answers question: http://stackoverflow.com/q/47776460
has comment: http://stackoverflow.com/comment/82591320
has body: Given that all of your webpages are have the same structure you can parse the html with this code. It will look for the first div with the id product_bullets_section. An id in html should be unique but the given website has two equal id's so we obtain the first one through slicing and convert the parsed div back to a string containing your html. import csv import urllib.request from bs4 import BeautifulSoup with open("urls.csv", "r", newline="", encoding="cp1252") as f_input: csv_reader = csv.reader(f_input, delimiter=";", quotechar="|") header = next(csv_reader) items = [row[0] for row in csv_reader] items = ['https://www.kramerav.com/de/Product/VM-2N'] with open("results.csv", "w", newline="") as f_output: csv_writer = csv.writer(f_output, delimiter=";") for item in items: html = urllib.request.urlopen(item).read() the_div = str(BeautifulSoup(html).select('div#product_bullets_section')[0])

http://stackoverflow.com/q/47843515
has title: How to store multiple fields in redis and get top 10 result on basis of some field
tagged with: http://stackoverflow.com/tag/csv
answer count: 1
tagged with: python
favorite count: 0
type: Question
has body: I want to store multiple fields in redis from a CSV file My file.CSV looks looks this. SC_CODE,SC_NAME,OPEN,HIGH,LOW,CLOSE, 500002,ABB LTD.,1372,1372.40,1339.95,1348.45, 500003,AEGIS LOGIS,275.00,275.00,261.50,266.70, 500008,AMAR RAJA BA,787.00,788.00,768.05,771.85, I have written the following code to insert data into redis. import csv with open('file.CSV', 'r') as csvfile: csvReader = csv.reader(csvfile) next(csvReader) for row in csvReader: print ('HMSET {} open {} other \"{},{},{},{}\"\r'.format(row[0], row[2], row[1], row[3], row[4], row[5])) and I am running this: python redis.py | redis-cli --pipe which basically means on redis-cli HMSET 500002 open 1372 other "ABB LTD.,1372.40,1339.95,1348.45" But I am not able to know how should I get top 10 stocks on the basis of different fields from above. So I want to get the top 10, lowest 10 and sorting and other things.
tagged with: redis
score: 0
upvote count: 1
downvote count: 1
accepted answer: http://stackoverflow.com/a/47843951
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47843951

http://stackoverflow.com/q/47762772
has comment: http://stackoverflow.com/comment/82521744
tagged with: python
has title: How to include cython code from another file
has comment: http://stackoverflow.com/comment/82522985
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82522409
accepted answer: http://stackoverflow.com/a/47780615
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/47780615
tagged with: cython
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/82521798
favorite count: 0
has comment: http://stackoverflow.com/comment/82516684
type: Question
has comment: http://stackoverflow.com/comment/82498967
has body: I would like to include code from a file for use in another file, much like importing a module, but I don't want to compile the first file in order to do so. My project pipeline looks something like this: file A defines an extension type object as so: cdef class Thing(object): ... There will be many different versions of this kind of file, each one defining a class called "Thing". file B does all types of neat stuff using the class "Thing" but does not define it in file B, as file B is able to perform general actions on many different kinds of objects called "thing" defined in file A. e.g. cdef int do_cool_stuff(Thing a, Thing b): ... Basically. I can copy-paste the code from file B into each file A and it will all work properly. But I would like to organize my project better, and these two types of files do very different tasks, and I will want to be mixing and matching these tasks. Any advice? In addition, it would be nice to be able to do something like this: in file A: ctypedef ... newtype and in file B: cdef newtype... If it helps, the newtype will be very similar to a double, but may carry more information. I will be overloading comparison operators &lt;, >, ==, etc, but I want the newtype to carry more information than a double. Edit: I will add some more information, as it seems that most readers feel this problem is more trivial than it is. I have several programs that are very long, and the files can all be partitioned into two distinct parts, the second half of each of these parts is identical codewise, but they all use a type that is defined in the first part. The second part cannot stand on its own because it depends on the ctypedef statement in part one. So what I would like is this: file1: cdef class Thing:... file2: stuff(Thing one, Thing two) file3: import file1 import file2 and compile file3, with files 1 and 2 uncompiled. If I make file1 and file2 .pxd files and use cimport I get complaints about def statements not allowed and that all cdef statem…
has comment: http://stackoverflow.com/comment/82515628

http://stackoverflow.com/q/47709407
has comment: http://stackoverflow.com/comment/82378784
has comment: http://stackoverflow.com/comment/82378702
score: -1
accepted answer: http://stackoverflow.com/a/47709547
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47709547
answer count: 3
duplicate of: http://stackoverflow.com/q/89228
upvote count: 0
has answer: http://stackoverflow.com/a/47709443
has comment: http://stackoverflow.com/comment/82378569
has title: How to make commands using str array in for loop by Python
has answer: http://stackoverflow.com/a/47709530
downvote count: 1
has comment: http://stackoverflow.com/comment/82378647
favorite count: 0
type: Question
has body: I want to do something like this CMD_LIST = ['ls -l', 'echo Mama Mia', 'echo bla bla bla'] for i in range(len(CMD_LIST)): subprocess.call(CMD_LIST[1]) How can i do list of commands in for loop?
possible better answer: http://stackoverflow.com/a/47709443
linked to: http://stackoverflow.com/q/89228
tagged with: python

http://stackoverflow.com/comment/82672004
type: Comment
comment on: http://stackoverflow.com/a/47853853
type: AnswerComment
has text: You're welcome. The 2nd one is more pythonic.
score: 1

http://stackoverflow.com/q/47703748
has title: Why does the simplest requests_mock example fail with pytest?
has body: I have a peculiar problem with requests_mock. I want to use it with pytest to test my API wrapper library. I've tried to use the first example in the requests_mock docs, except I put it in a test_mock()-function and added an assert-statement for pytest to discover it. The following code fails: # tests/test_mock.py import requests import requests_mock with requests_mock.Mocker() as m: def test_mock(): m.get('http://test.com', text='resp') assert requests.get('http://test.com').text == 'resp' However, when running the following example in ipython, it works as expected. This is the exact code from the example: with requests_mock.Mocker() as m: m.get('http://test.com', text='resp') print(requests.get('http://test.com').text) # prints 'resp' Because I can make requests_mock work from ipython, I assume the issue is with pytest, but I might be wrong. It seems like the adapter isn't used at all, so that requests sends a real http request to the target url instead of using the mocked object. I'm using Python 3.6.3 (Anaconda3), requests_mock 1.3.0 and pytest 3.3.0 Output from running the code that fails: C:\dev\mylib>pytest -v ============================= test session starts ============================= platform win32 -- Python 3.6.3, pytest-3.3.0, py-1.5.2, pluggy-0.6.0 -- e:\anaconda3\envs\benv\python.exe cachedir: .cache rootdir: C:\dev\mylib, inifile: setup.cfg collected 1 item tests/test_mocks.py::test_mock FAILED [100%] ================================== FAILURES =================================== __________________________________ test_mock __________________________________ def test_mock(): m.get('http://test.com', text='resp') > assert requests.get('http://test.com').text == 'resp' E assert ' \n \n' == 'resp' E + resp E - E - E - E - Client Validation E - E - function setCookie(c_name, value, expiredays) {... E E ...Full output truncated (26 lines hidden), use '-vv' to show tests\test_mocks.py:9: AssertionError ------------------------------ Captured log call ----…
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47717618
tagged with: mocking
answer count: 1
score: 6
upvote count: 6
tagged with: python
tagged with: python-requests
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47717618
downvote count: 0
tagged with: pytest

http://stackoverflow.com/comment/82673688
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47854806
has text: Can you update your answer with the contents of the output?

http://stackoverflow.com/comment/82449560
type: QuestionComment
has text: or maybe you need `item.text` or `item.get_text()`
comment on: http://stackoverflow.com/q/47744697
score: 0
type: Comment

http://stackoverflow.com/comment/82582714
has text: Thanks for your reply jmunsch. I done the steps as mentioned and now just made the hacky edit to the pigpio makefile as suggested, so L34 now shows: prefix = $(pwd)/venv_test. I then managed to 'make' the file successfully. However, at the 'make install 'step, I got an error: (venv_test) pi@raspberrypi:~/pigpio $ make install install -m 0755 -d /opt/pigpio/cgi install -m 0755 -d /venv_test/include install: cannot create directory ‘/venv_test’: Permission denied Makefile:80: recipe for target 'install' failed make: *** [install] Error 1 .Any ideas why?
type: AnswerComment
comment on: http://stackoverflow.com/a/47802221
score: 0
type: Comment

http://stackoverflow.com/q/47757283
downvote count: 0
tagged with: pip
has body: A couple of months ago, I wrote a small Python service using systemd.journal. Pip list shows that I have python-systemd (231) installed in the corresponding virtualenv. When I just tried to install the python-systemd package, I got python-systemd (0.0.9) instead, which does not have a .journal submodule. The python-systemd documentation says the module is available from pypi as python-systemd, however it seems that it is instead available as systemd-python (now in version 234). Does anybody know if the package name has been changed? I could not find anything in the documentation.
tagged with: pypi
has title: Pip/PyPi: python-systemd vs systemd-python
favorite count: 0
type: Question
tagged with: systemd
score: 3
accepted answer: http://stackoverflow.com/a/47757381
tagged with: python
has answer: http://stackoverflow.com/a/47757381
type: AnsweredQuestion
upvote count: 3
answer count: 1

http://stackoverflow.com/q/47778550
type: AnsweredQuestion
tagged with: tkinter
answer count: 3
has comment: http://stackoverflow.com/comment/82520166
has comment: http://stackoverflow.com/comment/82520728
has comment: http://stackoverflow.com/comment/82518314
has comment: http://stackoverflow.com/comment/82519842
has answer: http://stackoverflow.com/a/47780704
downvote count: 0
possible better answer: http://stackoverflow.com/a/49988999
has comment: http://stackoverflow.com/comment/82518369
has answer: http://stackoverflow.com/a/49988999
favorite count: 0
has body: I'm running Python 3.6 on a Windows 10 machine. I want to display a simple matplotlib plot like this: import numpy as np import matplotlib.pyplot as plt x = np.arange(0, 5, 0.1); y = np.sin(x) plt.plot(x, y) Unfortunately, I get the error: ModuleNotFoundError: No module named 'tkinter' I try installing tkinter through my terminal: &gt; pip install tkinter Collecting tkinter Could not find a version that satisfies the requirement tkinter (from versions: ) No matching distribution found for tkinter I also tried pip install python3-tk but without success. I found a couple of posts on StackOverflow explaining how to install tkinter properly, but they're all about Python 2 and/or Linux systems. I couldn't find a post particularly for Python 3.6 on Windows 10.
type: Question
has comment: http://stackoverflow.com/comment/82520789
accepted answer: http://stackoverflow.com/a/47780704
has comment: http://stackoverflow.com/comment/82520857
has comment: http://stackoverflow.com/comment/82521897
has title: Need tkinter on my python 3.6 installation (Windows 10)
tagged with: matplotlib
has answer: http://stackoverflow.com/a/56401144
tagged with: python
score: 4
upvote count: 4

http://stackoverflow.com/a/47707895
has comment: http://stackoverflow.com/comment/82376261
downvote count: 0
has comment: http://stackoverflow.com/comment/82375841
has comment: http://stackoverflow.com/comment/82375882
has body: I added animated=True and vmin=0, vmax=255, in the imshow() function below. I also changed the stand() line to arr[x][y] = arr[x][y] + 10. #!/usr/bin/env python3 import matplotlib as mpl from matplotlib import pyplot as plt from matplotlib import animation as anim import numpy as np import sys import random length = int(sys.argv[1]) fig = plt.figure() ax = plt.axes(xlim=(0, length-1), ylim=(0, length-1)) arr = np.zeros((length, length), dtype = int) cmap = mpl.colors.LinearSegmentedColormap.from_list('my_colormap', ['black','green','white'], 256) bounds=[0,0,10,10] norm = mpl.colors.BoundaryNorm(bounds, cmap.N) im=plt.imshow(arr, interpolation='nearest', cmap = cmap, vmin=0, vmax=255, origin='lower', animated=True) # small changes here x = int(np.random.random_sample() * length) y = int(np.random.random_sample() * length) def walk(): global x, y rand = np.random.random_sample() if rand &lt; 0.25 : if x == length - 1: x = 0 else: x = x + 1 elif rand &lt; 0.5 : if x == 0: x = length - 1 else: x = x - 1 elif rand &lt; 0.75 : if y == length - 1: y = 0 else: y = y + 1 else: if y == 0: y = length - 1 else: y = y - 1 return def stand(arr): global x,y arr[x][y] = arr[x][y] + 1000 return arr def animate(i): global x,y arr=im.get_array() walk() #print(a) arr = stand(arr) im.set_array(arr) return [im] anim = anim.FuncAnimation(fig, animate, frames=200, interval=20, blit=True) plt.show() And I ran it with length = 50 and I get an animation. See it here. So you may have to play around with your color choices a bit.
answers question: http://stackoverflow.com/q/47707508
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82376084
type: Answer
has comment: http://stackoverflow.com/comment/82375815
has comment: http://stackoverflow.com/comment/82376038
has comment: http://stackoverflow.com/comment/82375947
accepted answer of: http://stackoverflow.com/q/47707508
score: 1
upvote count: 1

http://stackoverflow.com/q/47726023
has answer: http://stackoverflow.com/a/47726711
has comment: http://stackoverflow.com/comment/82413797
downvote count: 0
has body: I'm creating a game for my cs class right now and the model is Tron. Basically, I have my two players going at all times and they can either turn left or right (at 90° angles) whilst creating lines behind them. I want to create a function that will draw those lines given the last position of the player. However, what I can't figure out is how to create new lines when the player turns while keeping the old one functioning as it should (I will get to what this means in a bit). Also, since I will be calling this "draw lines" function from the same variable every time, will I be able to detect a collision between the player and any given line by calling that one variable, even though the lines are all technically different? Is this an optmical situation for a dictionary? So far me and my partner have tried elongating one rect, creating a list (although I don't have much experience in this area, so maybe I just messed it up royally) and otherwise literally creating mulitple variables... My code (if you decide to check out the code and play the game just keep in mind the next button from the instructions screen is broken for some reason and requires spam clicking).
has title: Pygame – Creating multiple lines with the same function while keeping individual functionality
upvote count: 1
tagged with: python
tagged with: dictionary
accepted answer: http://stackoverflow.com/a/47726711
has comment: http://stackoverflow.com/comment/82413774
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82412884
answer count: 1
has comment: http://stackoverflow.com/comment/82424563
tagged with: pygame
score: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82413151

http://stackoverflow.com/a/47717334
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82395279
answers question: http://stackoverflow.com/q/47717077
score: 2
has body: You first need to alter your processed_data table to add the X10 column, and then you can update the X10 field based on the codes field. For example: cursor = connection.cursor() # fetch a cursor from your SQLite connection # let's first check if we already have the X10 column in our table x10_exists = False cursor.execute("PRAGMA table_info(processed_data)") # get info on the table for column in cursor: if column[1] == 'X10': x10_exists = True break if not x10_exists: # if X10 doesn't exist... cursor.execute("ALTER TABLE processed_data ADD COLUMN X10") # add the X10 column cursor.execute(''' UPDATE processed_data SET X10=CASE WHEN codes LIKE 'X10' THEN 1 ELSE 0 END ''') # update the values db.commit() # commit the transaction
has comment: http://stackoverflow.com/comment/82395538
type: Answer
has comment: http://stackoverflow.com/comment/82395379
accepted answer of: http://stackoverflow.com/q/47717077
upvote count: 2
has comment: http://stackoverflow.com/comment/82399819
has comment: http://stackoverflow.com/comment/82400171

http://stackoverflow.com/a/47779829
has body: It's unclear if this geometry is fixed or if other layouts are possible. As you have excellent contrast of the object wrt the background, you can detect a few points by finding the first and last transitions along a probe line. Pairs of points give you a direction. More points allow you to do line fitting, and you can use all the points in your orange and gree areas. It is even possible to do simultaneous fitting of two parallel lines. Note that if you only need an angle, there is no need to find the axis of the tubes.
upvote count: 2
answers question: http://stackoverflow.com/q/47777585
downvote count: 0
type: Answer
score: 2

http://stackoverflow.com/q/47775715
has body: So far everything is working correctly, however I am struggling with getting the data below, once highlighted by the mouse and once hitting the select button to populate the correct entry boxes. This may be asking too much. Listbox display 2-12312 Bob Seesaw Active 4-1212 Jim Beene Off So if I highlight the Bob Seesaw row and hit select. The 2-12312 will pretype 'num_input', Bob 'nam_input' and so on. The purpose of this is so I can then type a new assignment and update the database for that entry. ( I pasted code specific to my initiative. from tkinter import * import pymysql as mdb from tkinter import ttk from tkinter import Listbox def viewroster(): rosterList.delete(0, "end") dbi = mdb.connect("localhost", port=3306, user="user", passwd="pass", db="interactive_db") cursor = dbi.cursor() cursor.execute("""SELECT number, firstname, surname, assign FROM active_roster""") rows=cursor.fetchall() dbi.close() print (rows) for results in rows: rosterList.insert("end", results) #Input Fields num_input=StringVar() num_input=Entry(root,textvariable=num_input) num_input.grid(row=0,column=1) ass_input=StringVar() ass_input=Entry(root,textvariable=ass_input) ass_input.grid(row=0,column=3) nam_input=StringVar() nam_input=Entry(root,textvariable=nam_input) nam_input.grid(row=1,column=1) sur_input=StringVar() sur_input=Entry(root,textvariable=sur_input) sur_input.grid(row=1,column=3) # This is to select mouse highlighted data rosSelButt=Button(root, text="Select", width=12) rosSelButt.grid(row=13, column=0) - Number [2-12312] Firstname [Bob] Surname [Seesaw] Assign [......] (ready for text) I do not want to loose the capability of typing a name or number as an entry and searching the database.
has answer: http://stackoverflow.com/a/47777031
has title: How to select Python listbox data and populate it to specific enty box - pretype
has comment: http://stackoverflow.com/comment/82514976
tagged with: python
has comment: http://stackoverflow.com/comment/82514491
has comment: http://stackoverflow.com/comment/82514193
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82512740
score: 0
answer count: 1
tagged with: mysql
type: Question
has comment: http://stackoverflow.com/comment/82514696
accepted answer: http://stackoverflow.com/a/47777031
tagged with: tkinter

http://stackoverflow.com/q/47762068
tagged with: gpio
has body: Project: I am creating a light switch panel to control my LIFX WiFi lights. I have 3 buttons hooked up to GPIO pins 6, 20 and 22 and I'm using the GPIO.add_event_detect to capture when the button is pressed. Problem: My issue is that if I push one button, sometimes it triggers one or more of the other channels. For example pressing button channel 6 will also trigger 20 and/or 22. The odd thing is that it works perfectly fine 80% of the time so I really don't believe its anything physical like signals crossing wires. I've been at this on and off for about 2 weeks. What I've Tried: Originally I made a little protoboard which I soldered leads to a 40 pin header and I thought that there was a chance a wire was crossing causing this phantom button press. I then bought a $20 board off Amazon that has screw terminals for each GPIO pin... same issue. I tried switching up the GPIO pins I was using to be further apart on the board, in case somehow they were crossing. I've tried updating the GPIO library but I have the latest. I've tried different push buttons to see if they where faulty. I've checked that pressing one button doesnt wiggle the other buttons enough that they trigger. I've tried using GPIO.input(channel) to see if the button is pressed in the buttonPressed callback but more times than not that makes it so that no buttons are pressed (even the one I actually pressed). I've tried removing other code for the LIFX lan library and the TCP server that I start. The buttons are screwed into a piece of wood and have several inches between them so I know wires are not crossing there. Next I'm going to try swapping to another PI but I have everything screwed down into a cabinet and its difficult to get to. Setup: Raspberry Pi 2 B+ Python 2.7 Code: I've omitted irrelevant code to make it easier to read import os import sys from time import sleep import time import random import threading import json import itertools, glob from socket import error as SocketError from TcpClie…
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/82486356
score: 1
tagged with: python
has title: Raspberry PI GPIO add_event_detect triggering multiple channels on one button press
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82486476
tagged with: raspberry-pi
answer count: 0
has comment: http://stackoverflow.com/comment/100938503
type: UnansweredQuestion

http://stackoverflow.com/a/47849796
upvote count: 1
has comment: http://stackoverflow.com/comment/82664200
answers question: http://stackoverflow.com/q/47849713
has body: q = [1, 2,3, 4] for dice in q: if dice == 1: q.remove(dice) break print(q);
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/82664418
has comment: http://stackoverflow.com/comment/82664143
downvote count: 0

http://stackoverflow.com/q/47698654
favorite count: 0
type: Question
downvote count: 4
has comment: http://stackoverflow.com/comment/82357293
upvote count: 0
type: UnansweredQuestion
score: -4
has answer: http://stackoverflow.com/a/47699100
tagged with: multithreading
tagged with: python
has title: run multiple for loop session simultaneously python
has body: I have a list of input. serverfarm = ''' server1 = 10.1 server2 = 10.2 server3 = 10.3 server4 = 10.4 server5 = 10.5 server6 = 10.6 server7 = 10.7 server8 = 10.8 server9 = 10.9 server10 = 10.10 server11 = 10.11 server12 = 10.12 server13 = 10.13 server14 = 10.14 server15 = 10.15 server16 = 10.16 server17 = 10.17 server18 = 10.18 server19 = 10.19 server20 = 10.20 ''' i do run a for loop for each server: for server in serverfarm:&lt;br&gt; . ssh each server and do config # its take 5 min to complete a server. the total time to complete the is list is 100 min. I need to reduce this time. I need to run multiple for loop simultaneously. i.e. in this case the for loop run for 5 or 10 servers at once. let consider 10, in this case the script is taking just 10 min to complete the config on each server. I am not worry about the resource on my script server. just need to reduce the time at any cost. OR if there is any way to run a master script which make copy of for loop in back-end and update the master script which return the value in 10 min.
has comment: http://stackoverflow.com/comment/82357267
answer count: 1

http://stackoverflow.com/comment/82427651
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47733532
has text: When I'm using reesults instead of json if 'person' not in results['items'][profile]['pagemap']: I am getting the KeyError org = results['items'][profile]['pagemap']['person'][0]['org'] KeyError: 'org'
type: Comment

http://stackoverflow.com/a/47802958
type: Answer
answers question: http://stackoverflow.com/q/47802772
score: 1
downvote count: 0
has body: If you have all in Frame then you can move Frame and it will move with all elements inside. Use place_forget() to remove it from window, and use place() again to put in new position. import tkinter as tk import random # --- funtions --- def move(): # hide frame f.place_forget() # random positiom new_x = random.randint(0, 100) new_y = random.randint(0, 150) # show in new place f.place(x=new_x, y=new_y) # --- main --- root = tk.Tk() f = tk.Frame(root) f.place(x=0, y=0) tk.Label(f, text='HELLO!').pack() tk.Button(f, text='Move it', command=move).pack() root.mainloop()
upvote count: 1

http://stackoverflow.com/q/47829049
tagged with: python
has comment: http://stackoverflow.com/comment/82620782
type: Question
has title: tkinter deiconify() method does not draw window in the same location (on linux)
tagged with: tkinter
answer count: 0
has comment: http://stackoverflow.com/comment/82620944
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82620685
has comment: http://stackoverflow.com/comment/82620889
has comment: http://stackoverflow.com/comment/82620614
score: 0
has comment: http://stackoverflow.com/comment/82621276
has body: The problem is on linux (ubuntu 16.04). On windows, it works correctly. When I withdraw() the main window and later deiconify() it, the window gets shifted (up) by a small amount. If I reset the geometry before the deiconify call, it still doesn't work as expected. What can I do to prevent the shifting of the window? Following is the code - def win(): def run_again(): root.deiconify() root.after(6000, run_again) root = Tk() root.title('Reminder') root.geometry('-0-40') root.minsize(width=300,height=100) root.attributes("-topmost", True) root.rowconfigure(0, weight=1) root.columnconfigure(0, weight=1) Label(root, text='test').grid(padx=20, pady=20, sticky=NW) btn = Button(root, text='Ok', command=root.withdraw) btn.grid(pady=5) btn.bind('&lt;Return&gt;', lambda e: root.quit()) root.withdraw() root.after(6000, run_again) root.protocol("WM_DELETE_WINDOW", root.withdraw) root.mainloop() win()
has comment: http://stackoverflow.com/comment/82630871
has comment: http://stackoverflow.com/comment/82621041
has comment: http://stackoverflow.com/comment/82628509

http://stackoverflow.com/comment/82428906
type: QuestionComment
score: 2
has text: And what is your question?
comment on: http://stackoverflow.com/q/47734174
type: Comment

http://stackoverflow.com/q/47834754
tagged with: webapp2
answer count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/47835029
has body: I have a webapp2 logout request handler like: class EditorLogoutHandler(base.LogoutPage): def get(self): self.request.get('return_url') I want to change the 'return_url' and call the inherited method in base.LogoutPage. Is there a way to do it? I looked through the docs but can't find it.
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/47835029
has title: is there a way to modify request parameters in webapp2
type: Question

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

http://stackoverflow.com/comment/82447736
score: 0
comment on: http://stackoverflow.com/q/47735214
type: QuestionComment
has text: @JaredSmith Found the Solution. It seems someone at raised an issue in GitHub for Python3 (sorry I missed when I searched on the first time). Basically they changed the encrypt and decrypt function and encode each char to 'latin1'. Check solution here: https://github.com/softScheck/tplink-smartplug/issues/20
type: Comment

http://stackoverflow.com/a/47767778
answers question: http://stackoverflow.com/q/47765002
type: Answer
has comment: http://stackoverflow.com/comment/82522821
has comment: http://stackoverflow.com/comment/82498713
has body: Recognizing the next section is a bit vague - perhaps we can rely on Abstract-section ending with two newlines? ABSTRACT\n(.*)\n\n Or maybe we'll just assume that the next section-title will start with an uppercase letter and be followed by any number of word-characters. (Also that's rather vague, too, and assumes there'l be no \n\n within the Abstract. ABSTRACT\n(.*)\n\n\U[\w\s]*\n\n Maybe that stimulates further fiddling on your end... Feel free to post examples where this did not match - maybe we can stepwise refine it. N.B: as Wiktor pointed out, I could not use the case-insensitive modifiers. So the whole rx should be used with switches for case-insenstive matching. Update1: the challenge here is really how to identify that a new section has begun...and not to confuse that with paragraph-breaks within the Abstract. Perhaps that can also be dealt with by changing the rather tolerant [\w\s]*with [\w\s]{1,100} which would only recognize text in a new paragraph as a title of the "abstract-successor" if it had between 2 and 100 characters (note: 2 characters, although the limit is set to 1 because of the \U (uppercase character). ABSTRACT\n(.*)\n\n\U[\w\s]{1,100}\n\n
has comment: http://stackoverflow.com/comment/82498488
has comment: http://stackoverflow.com/comment/82530982
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47765002
has comment: http://stackoverflow.com/comment/82524497

http://stackoverflow.com/comment/82499011
type: Comment
has text: Well, OK, I just installed the prerequisites `pip install cython pytest numpy` and still get the same error. Seems to me like that's not the problem.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47768878

dialogflow-es
tags question: http://stackoverflow.com/q/47761673
tag name: dialogflow-es
type: Tag

http://stackoverflow.com/comment/82628655
comment on: http://stackoverflow.com/q/47832820
type: QuestionComment
has text: Have you tried using `pd.read_csv`, you can look at the docs its basic https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html
type: Comment
score: 0

http://stackoverflow.com/comment/82651853
comment on: http://stackoverflow.com/q/47843889
type: Comment
score: 0
has text: Are you on Windows? Do the backslashes need escaped? Can you try either `selenium\webdriver\remote\getAttribute.js` or `selenium/webdriver/remote/getAttribute.js`?
type: QuestionComment

http://stackoverflow.com/q/47822473
favorite count: 0
has comment: http://stackoverflow.com/comment/82607867
has comment: http://stackoverflow.com/comment/82607649
has comment: http://stackoverflow.com/comment/82607790
has comment: http://stackoverflow.com/comment/82610292
tagged with: python-3.x
tagged with: algorithm
has comment: http://stackoverflow.com/comment/82607824
tagged with: python
has body: I have the following code: comments = sorted(comments, key=lambda k: k['time_created']) How to sort correctly if some elements have the different format, like 2017-12-14T17:42:30.345244+0000 and 2017-12-14 00:23:23.468560 and my code fail when trying to compare? I need to save seconds accuracy. Is it the good solution? comments = sorted(comments, key=lambda k: self.unix_time_millis(k['time_created']), reverse=True) @staticmethod def unix_time_millis(dt): epoch = datetime.datetime.utcfromtimestamp(0) return (dt - epoch).total_seconds() * 1000.0
has comment: http://stackoverflow.com/comment/82607848
has answer: http://stackoverflow.com/a/47823098
has comment: http://stackoverflow.com/comment/82607737
type: Question
has comment: http://stackoverflow.com/comment/82607683
has answer: http://stackoverflow.com/a/47822549
answer count: 2
has title: How to sort different date time formats?
upvote count: 1
type: UnansweredQuestion
score: 1
linked to: http://stackoverflow.com/q/23581128
downvote count: 0

http://stackoverflow.com/q/47803005
score: -2
downvote count: 2
has comment: http://stackoverflow.com/comment/82567455
has comment: http://stackoverflow.com/comment/82568341
tagged with: python
accepted answer: http://stackoverflow.com/a/47803145
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82567444
has body: Okay so I either don't understand the code in the other questions, or my question is different. Here's my code: import random, math, sys, time userinput = 0 while "quit" != userinput: def lol(): global userinput, why why = userinput = input("What the heck are you doing? ") print(why, userinput) lol() lol() why = userinput = input("Type: ") When I type "quit" in the "Type:" the program quits. However, when I type "quit" in my function, it keeps going. Why is this?
answer count: 2
has comment: http://stackoverflow.com/comment/82567593
has comment: http://stackoverflow.com/comment/82567632
has comment: http://stackoverflow.com/comment/82567489
has comment: http://stackoverflow.com/comment/82567471
has answer: http://stackoverflow.com/a/47803112
possible better answer: http://stackoverflow.com/a/47803112
has comment: http://stackoverflow.com/comment/82567453
has comment: http://stackoverflow.com/comment/82567583
has answer: http://stackoverflow.com/a/47803145
favorite count: 0
has comment: http://stackoverflow.com/comment/82567505
type: Question
has title: Why does my while loop not stop when used in a function?
has comment: http://stackoverflow.com/comment/82567479
upvote count: 0

http://stackoverflow.com/q/47844064
tagged with: python-3.x
score: -2
has comment: http://stackoverflow.com/comment/82652334
tagged with: python
accepted answer: http://stackoverflow.com/a/47844414
has answer: http://stackoverflow.com/a/47844414
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82652253
has title: Password auth hashing with python 3
tagged with: api
upvote count: 0
downvote count: 2
answer count: 1
tagged with: authentication
favorite count: 0
type: Question
has body: I have to calculate a password to connect to an api service. The requirement is: Password = base64 encoded(sha1(nonce+created+secret)) where: nonce = 186269 created = 2015-07-08T11:31:53+01:00 secret = Ok4IWYLBHbKn8juM1gFPvQxadieZmS2 must giving ZDg3MTZiZTgwYTMwYWY4Nzc4OGFjMmZhYjA5YzM3MTdlYmQ1M2ZkMw== as password. I'm approaching with: psw = hashlib.sha1() psw.update(b"186269") psw.update(b"2015-07-08T11:31:53+01:00") psw.update(b"Ok4IWYLBHbKn8juM1gFPvQxadieZmS2") enc_psw = base64.b64encode(psw.digest()) but it give me 2HFr6Aowr4d4isL6sJw3F+vVP9M= as result

http://stackoverflow.com/q/47723921
type: Question
tagged with: nonlinear-optimization
has body: Based on this post I am trying to use brute to do a grid serach on a ARIMA model but I cannot make it run. I am doign this proof of principle, but what am I doing wrong with the arguments? y = pd.DataFrame([0,1,4,9,16]) + 3 def objfunc(coeffs, endog): exp = coeffs[0] const = coeffs[1] print(exp, const, endog) out = 0 for i in range(4): out += i**exp + const return out from scipy.optimize import brute grid = (slice(0, 2, 1), slice(3, 4, 1)) brute(objfunc, ranges=grid, args=y) (0, 3, 0) (0, 3, 0) (1, 3, 0) ... TypeError: objfunc() takes exactly 2 arguments (1 given) Once I solve this my aim is actually to optimize this function on order and seasonal_order being tuples like this ( _ , _ , _ ) and this ( _ , _ , _ ,12), respectively. def objfunc(coeffs, endog): order = coeffs[0] seasonal = coeffs[1] fit = sm.tsa.statespace.SARIMAX(endog, trend='n', order=order, seasonal_order=seasonal).fit() return fit.aic() EDIT: this code works (thanks to @sasha), variable names are more clear, and makes more sense (I minimize the function on the error). import pandas as pd y = np.array([0,1,4,9,16]) + 3 #polynomial x^2+3 with x=0:4 def objfunc(coeffs, *args): arr = args[0] # access first element of tuple: y exp = coeffs[0] # assuming y should become endog const = coeffs[1] pol = [i**exp + const for i in range(len(y))] print coeffs return abs(sum(pol) - sum(arr)) from scipy.optimize import brute grid = (slice(1, 3, 1), slice(2, 5, 1)) resbrute = brute(objfunc, ranges=grid, args=(y,), full_output=True, finish=None) print("Best coeffs: {}".format(resbrute[0])) print("Score with best coeffs: {}".format(resbrute[1])) print("Grid: {}".format(resbrute[2].tolist())) print("Scores for grid: {}".format(resbrute[3].tolist()))
has answer: http://stackoverflow.com/a/47724001
accepted answer: http://stackoverflow.com/a/47724001
downvote count: 0
tagged with: arima
answer count: 1
tagged with: python
type: AnsweredQuestion
has title: Using scipy.optimize.brute
score: 1
upvote count: 1
linked to: http://stackoverflow.com/q/22770352
tagged with: scipy
favorite count: 0

http://stackoverflow.com/comment/82434972
score: 0
type: Comment
has text: @Nain Yes, of course! Thank you. If you want to turn your comment into an answer, I shall accept it.
type: QuestionComment
comment on: http://stackoverflow.com/q/47737350

http://stackoverflow.com/comment/82450175
type: Comment
type: QuestionComment
has text: Is your focus on getting many random numbers or on creating an array by iteration? If the latter, just use `np.array(mylist)` at the end. For iteration, lists are better.
score: 0
comment on: http://stackoverflow.com/q/47744725

http://stackoverflow.com/comment/82496525
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47767596
has text: I check most of your files and I found `import threading` only in `coin/indicator.py` but you never use it to create new threads. So where do you create those threads ?

http://stackoverflow.com/q/47855892
score: 0
has comment: http://stackoverflow.com/comment/82677073
has comment: http://stackoverflow.com/comment/82675864
tagged with: pandas
answer count: 0
type: UnansweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/82675929
has title: pandas dataframe: groupby will give duplicate groupby
linked to: http://stackoverflow.com/q/21390035
tagged with: python
duplicate of: http://stackoverflow.com/q/21390035
has body: Here is a working example # create dataframe df = pd.DataFrame({"a":range(10), "b":[1,1,1,2,2,2,3,3,4,1]}) # group by 'b' column and print every group df.groupby("b").apply(lambda x:print(x)) Here is the result, as you can see, the first 2 group contains the same elements. How do I correct this? a b 0 0 1 1 1 1 2 2 1 9 9 1 a b 0 0 1 1 1 1 2 2 1 9 9 1 a b 3 3 2 4 4 2 5 5 2 a b 6 6 3 7 7 3 a b 8 8 4

http://stackoverflow.com/a/47714212
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82411474
has comment: http://stackoverflow.com/comment/82400294
has comment: http://stackoverflow.com/comment/82398343
accepted answer of: http://stackoverflow.com/q/47706580
type: Answer
upvote count: 4
has comment: http://stackoverflow.com/comment/82392759
score: 4
answers question: http://stackoverflow.com/q/47706580
has body: def run(tasks): # ... loop = asyncio.get_event_loop() loop.run_until_complete(aysnc_wrapper()) Usually it's not how people write async programs: event loop should be global and be started as main entry point of whole script. Doing like you do (running event loop inside single function run) makes unable for upper code to run other coroutines in same event loop. If you understand this and all you want is blocking run function that can't be used alongside with other async stuff, read further. Problem with your async_wrapper is that it awaits next update_ocr_task() coroutine only after previous one been done. For loop is not what we call "blocking", but it's just not concurrent - it doesn't use benefits provided by asynchronous paradigm. To achieve benefits of using asyncio you should run multiple coroutines concurrently. Common way to do it is to use asyncio.gather(): async def async_wrapper(): async def process_single_task(task): resolver = aiohttp.AsyncResolver() connector = aiohttp.TCPConnector(resolver=resolver, family=socket.AF_INET) async with aiohttp.ClientSession(connector=connector) as session: await session.get(...) # do all job for *single* local task here. # Run multiple task processing coroutines concurrently: await asyncio.gather( *[process_single_task(t) for t in tasks] ) If you want you can also read this little answer about asyncio in general.

http://stackoverflow.com/a/47709161
score: 3
upvote count: 3
downvote count: 0
type: AcceptedAnswer
has body: pydicom supports reading pixel data. Refer this documentation. pydicom tends to be “lazy” in interpreting DICOM data. For example, by default it doesn’t do anything with pixel data except read in the raw bytes: import dicom ds=dicom.read_file("MR_small.dcm") ds.PixelData '\x89\x03\xfb\x03\xcb\x04\xeb\x04\xf9\x02\x94\x01\x7f ... ... About pixel_array A property of Dataset called pixel_array provides more useful pixel data for uncompressed images. The NumPy numerical package must be installed on your system to use this property, because pixel_array returns a NumPy array: import dicom ds=dicom.read_file("MR_small.dcm") ds.pixel_array array([[ 905, 1019, 1227, ..., 302, 304, 328], [ 628, 770, 907, ..., 298, 331, 355], [ 498, 566, 706, ..., 280, 285, 320], ..., [ 334, 400, 431, ..., 1094, 1068, 1083], [ 339, 377, 413, ..., 1318, 1346, 1336], [ 378, 374, 422, ..., 1369, 1129, 862]], dtype=int16) ds.pixel_array.shape (64, 64) Document also explains about viewing images at http://pydicom.readthedocs.io/en/stable/viewing_images.html. As explained in error message (and by @kritzel_sw in comment) the pydicom does not support the Transfer Syntax of source image yet. Change the Transfer Syntax using some other tool before attempting to extract the frames. Another helpful blog of Rony http://dicomiseasy.blogspot.in/2012/08/chapter-12-pixel-data.html Also check this Stack Overflow question; it is about old version but may be helpful.
accepted answer of: http://stackoverflow.com/q/47707756
type: Answer
answers question: http://stackoverflow.com/q/47707756

http://stackoverflow.com/a/47722187
score: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47721956
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47721956
type: Answer
has body: Let's define a test matrix and a function to get all neighbours of the cell: m = [[i for i in range(10)] for i in range(10)] # Size of "board" X = len(m) Y = len(m[0]) neighbors = lambda x, y : [(x2, y2) for x2 in range(x-1, x+2) for y2 in range(y-1, y+2) if (-1 &lt; x &lt;= X and -1 &lt; y &lt;= Y and (x != x2 or y != y2) and (0 &lt;= x2 &lt;= X) and (0 &lt;= y2 &lt;= Y))] Then for calculating the differences: def get_differences(point, neigh, m): px, py = point return [m[px][py] - m[nx][ny] for nx, ny in neigh] And test both for a single point: point = (1,1) print('Neighbours: ', neighbors(*(point))) print('Differences: ') print(get_differences(point, neighbors(*(point)), m)) The part with this elegant neighbours function is taken from this post.

http://stackoverflow.com/comment/82547948
score: 0
has text: Can you elaborate a bit what you mean by `need to save just first view`?
comment on: http://stackoverflow.com/q/47788417
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47701399
has comment: http://stackoverflow.com/comment/82362770
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82363123
has title: How to print list of lists without extra brackets and quotes?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82363164
tagged with: python
has answer: http://stackoverflow.com/a/47706061
has comment: http://stackoverflow.com/comment/82363601
has comment: http://stackoverflow.com/comment/82363931
score: 0
has comment: http://stackoverflow.com/comment/82363694
answer count: 1
has body: I'm working on assignment for my Python 3 programming class. It's a database to look up movies and the year they came out. However, I'm having a hard time printing the output without extra brackets and quotes: # Build a dictionary containing the specified movie collection list_2005 = "Munich", "Steven Spielberg" list_2006 = [["The Departed", "Martin Scorsese"], ["The Prestige", "Christopher Nolan"]] list_2007 = "Into the Wild", "Sean Penn" movies = { '2005': list_2005, '2006': list_2006, '2007': list_2007 } # Prompt the user for a year # Displaying the title(s) and directors(s) from that year user_year = str(input("Enter a year between 2005 and 2007:\n")) if user_year in movies: for name in movies[user_year]: print("%s" % ', '.join(name)) print() elif user_year not in movies: print("N/A") # Display menu user_choice = '' while user_choice != 'q': print("MENU\nSort by:\ny - Year\nd - Director\nt - Movie title\nq - Quit") print() user_choice = str(input("Choose an option:\n")) if user_choice == 'y': for key, value in sorted(movies.items()): print("%s:" % key) print(" %s" % ''.join(str(movies[key]))) # Carry out the desired option: Display movies by year, # display movies by director, display movies by movie title, or quit I would like this output to be: 2005: Munich, Steven Spielberg 2006: The Prestige, Christopher Nolan The Departed, Martin Scorsese etc. The output I am getting: 2005: ['Munich', 'Steven Spielberg'] 2006: [['The Prestige', 'Christopher Nolan'], ['The Departed', 'Martin Scorsese']] etc.
upvote count: 1
downvote count: 1
favorite count: 0

http://stackoverflow.com/q/47721726
upvote count: 1
favorite count: 0
type: Question
has title: How to cleanly pass down keyword args?
tagged with: python
possible better answer: http://stackoverflow.com/a/47721918
type: AnsweredQuestion
tagged with: python-2.7
answer count: 2
has answer: http://stackoverflow.com/a/47721918
has body: When writing functions that call other sub-functions I often want to allow the caller to pass in arbitrary keyword arguments for those subfunctions. However, the current way that I implement this is messy and I am looking for a more clear, concise, and maintainable way. Below is an example of how I currently implement this: def foo(a, print_line="Hello World!"): print a, print_line def bar(a, number=2, multiple=4): print a, number * multiple def baz(a, **kwargs): if "print_line" in kwargs: foo(a, print_line=kwargs["print_line"]) else: foo(a) bar_kwargs = dict() if "number" in kwargs: bar_kwargs["number"] = kwargs["number"] if "multiple" in kwargs: bar_kwargs["multiple"] = kwargs["multiple"] bar(a, **bar_kwargs) This method is error-prone and I need to implement every kwarg that I want to express. I can sometimes get away with foo(a, print_line=kwargs.get("print_line", False) but I would like to preserve the default argument of the kwarg.
score: 1
accepted answer: http://stackoverflow.com/a/47721827
downvote count: 0
has answer: http://stackoverflow.com/a/47721827
tagged with: keyword-argument

http://stackoverflow.com/q/47851117
upvote count: 1
tagged with: python
has title: Converting pandas Dataframe to nested json key pair
tagged with: pandas
score: 1
tagged with: http://stackoverflow.com/tag/json
has body: Here is a sample data from a csv file, where every generation is children of previous generation. parant,gen1,gen2,get3,gen4,gen5,gen6 query1,AggregateExpression,abc,def,emg,cdf,bcf query1,And,cse,rds,acd,, query2,Arithmetic,cbd,rsd,msd,, query2,Average,as,vs,ve,ew, query2,BinaryExpression,avsd,sfds,sdf,, query2,Comparison,sdfs,sdfsx,,, query3,Count,sfsd,,,, query3,methods1,add,asd,fdds,sdf,sdf query3,methods1,average,sdfs,bf,fd, query4,methods2,distinct,cz,asd,ada, query4,methods2,eq,sdfs,sdfxcv,sdf,rtyr query4,methods3,eq,vcx,xcv,cdf, I need to create a json file of following format, where parents are the index and children are always list of dictionaries and there is a size for the last generation which is calculated no. of time their parent appear (in previous generation). Example of the first row breakdown: { "name": "query1", "children": [ { "name": "AggregateExpression", "children": [ { "name": "abc", "children": [ { "name": "def", "children": [ { "name": "emg", "children": [ { "name": "cdf", "children": [ { "name": "bcf", "size": 1 } ] } ] } ] } ] } ] } ] } I have tried to use groupby() and to_json() but was not able to complete. But still struggling to build the logic if I need to use lambda or looping. Any suggestion or solution is welcome. Thanks.
favorite count: 0
type: Question
answer count: 0
type: UnansweredQuestion
downvote count: 0

http://stackoverflow.com/q/47705838
has comment: http://stackoverflow.com/comment/82372051
favorite count: 0
has comment: http://stackoverflow.com/comment/82371867
type: Question
has title: How do I make an SOQL Query with Spaces in Column Names?
has comment: http://stackoverflow.com/comment/82371918
tagged with: python
accepted answer: http://stackoverflow.com/a/47708334
has answer: http://stackoverflow.com/a/47708334
tagged with: soql
type: AnsweredQuestion
has body: I'm trying to make an SOQL query using the simple_salesforce python package. I'm having a bit of trouble querying columns which have spaces in the column names: sf.query_all("SELECT Id, Name, Email FROM Lead WHERE `Lead Source`=Calculator (Website)") I'm trying to use the conventional SQL syntax of dealing with pesky column names (I have also tried [] brackets) but I keep getting a SalesforceMalformedRequest. I want to get a python dict which contains the IDs, Names and Emails of any leads that have a lead source of 'Calculator (Website)'. I don't have privileges to change the column names, so any help on how to query, or how to access the column names in some other way, would be a lot of help!
has comment: http://stackoverflow.com/comment/82372129
downvote count: 0
tagged with: salesforce
score: 1
upvote count: 1
answer count: 1

javascript
tags question: http://stackoverflow.com/q/47833910
tags question: http://stackoverflow.com/q/47721021
tags question: http://stackoverflow.com/q/47723301
tags question: http://stackoverflow.com/q/47737685
tags question: http://stackoverflow.com/q/47776797
tags question: http://stackoverflow.com/q/47748174
tags question: http://stackoverflow.com/q/47812543
tags question: http://stackoverflow.com/q/47848845
tags question: http://stackoverflow.com/q/47783475
tags question: http://stackoverflow.com/q/47739065
tags question: http://stackoverflow.com/q/47759445
tags question: http://stackoverflow.com/q/47762460
tags question: http://stackoverflow.com/q/47839218
tags question: http://stackoverflow.com/q/47851288
tags question: http://stackoverflow.com/q/47849713
tags question: http://stackoverflow.com/q/47706644
tags question: http://stackoverflow.com/q/47794722
tags question: http://stackoverflow.com/q/47842660
tags question: http://stackoverflow.com/q/47774281
tags question: http://stackoverflow.com/q/47759956
tags question: http://stackoverflow.com/q/47728841
tags question: http://stackoverflow.com/q/47825131
tags question: http://stackoverflow.com/q/47845783
tags question: http://stackoverflow.com/q/47749627
tags question: http://stackoverflow.com/q/47742557
tags question: http://stackoverflow.com/q/47847067
tag name: javascript
tags question: http://stackoverflow.com/q/47779454
tags question: http://stackoverflow.com/q/47732069
tags question: http://stackoverflow.com/q/47836276
tags question: http://stackoverflow.com/q/47734706
tags question: http://stackoverflow.com/q/47727390
tags question: http://stackoverflow.com/q/47766881
tags question: http://stackoverflow.com/q/47791643
tags question: http://stackoverflow.com/q/47855082
tags question: http://stackoverflow.com/q/47731485
tags question: http://stackoverflow.com/q/47760436
tags question: http://stackoverflow.com/q/47841851
tags question: http://stackoverflow.com/q/47763852
tags question: http://stackoverflow.com/q/47728288
tags question: http://stackoverflow.com/q/47828926
tags question: http://stackoverflow.com/q/47725714
tags question: http://stackoverflow.com/q/47754487
tags question: http://stackoverflow.com/q/47771698
tags question: http://stackoverflow.com/q/47729643
tags question: http://stackoverflow.com/q/47716050
tags question: http://stackoverflow.com/q/47823543
tags question: http://stackoverflow.com/q/47829609
tags question: http://stackoverflow.com/q/47765771
tags question: http://stackoverflow.com/q/47827258
tags question: http://stackoverflow.com/q/47805239
tags question: http://stackoverflow.com/q/47704080
tags question: http://stackoverflow.com/q/47824092
type: Tag
tags question: http://stackoverflow.com/q/47713659
tags question: http://stackoverflow.com/q/47783718
tags question: http://stackoverflow.com/q/47840010
tags question: http://stackoverflow.com/q/47744558

http://stackoverflow.com/a/47715258
has body: The basic idea in Python 2 (note I have not tested this, but it should be close or work as is): search = '5356' # supply this as your search search = 'E'+search fh = open('textfile.txt') for line in fh: elements = line.split(',') if len(elements) == 6: if elements[0] == search: print 'For Estimate #'+search print 'date:'+elements[1] print 'cust:'+elements[2] print 'totl:'+elements[3] print 'stat:'+elements[4] print 'paid:'+elements[5] fh.close() Now... go look up each statement in that example in the Python 2 documentation and see what the various items in it do. That'll give you a little kickstart towards learning the language, if you are ever going to do any more in it. Keep in mind that failure is possible: What if the text file name is wrong, for instance, and the file open fails? You'll want to look at the try and except Python language elements. Everyone needs to start somewhere, which is why I didn't give you a snarky "show your work" answer. So here's your start. Go forth and learn. :)
type: Answer
accepted answer of: http://stackoverflow.com/q/47714609
has comment: http://stackoverflow.com/comment/82421226
has comment: http://stackoverflow.com/comment/82420989
has comment: http://stackoverflow.com/comment/82394304
has comment: http://stackoverflow.com/comment/82415306
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/82415325
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82415315
answers question: http://stackoverflow.com/q/47714609

http://stackoverflow.com/q/47815594
upvote count: 2
downvote count: 0
answer count: 1
has title: Copying a NamedTemporaryFile in Linux results in empty file
has body: I am writing some contents to a tempfile.NamedTemporaryFile in Python 3 under Ubuntu 16.04. Under certain circumstances, I want to copy that file to a different location after the writing is done. The problem is reproduced with the following code: import tempfile import shutil with tempfile.NamedTemporaryFile('w+t') as tmp_file: print('Hello, world', file=tmp_file) shutil.copy2(tmp_file.name, 'mytest.txt') mytest.txt is empty once the execution is over. If I use delete=False when creating the NamedTemporaryFile I can inspect its content in /tmp/ and they are fine. I know the file cannot be open again while open under Windows as per the documentation, but Linux should be fine, so I wouldn't expect it to be that. What is happening and how can it be resolved?
favorite count: 0
type: Question
tagged with: linux
tagged with: python
accepted answer: http://stackoverflow.com/a/47815757
score: 2
has answer: http://stackoverflow.com/a/47815757
type: AnsweredQuestion
tagged with: temp

http://stackoverflow.com/a/47759916
downvote count: 0
has comment: http://stackoverflow.com/comment/82481617
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/82481640
has comment: http://stackoverflow.com/comment/82481499
has comment: http://stackoverflow.com/comment/82481187
type: Answer
has body: I'm guessing that you just don't want to see the terminal window after you launch the script. In this case, it is a matter of how you execute the script. Try these things. If you are using a windows computer you can try using pythonw.exe: pythonw.exe example_script.py If you are using linux (maybe OSx) you may want to use 'nohup' in the terminal. nohup python example_script.py More or less the reason you have to do this comes down to how the Operating system handles processes. I am not an expert on this subject matter, but generally if you launch a script from a terminal, that script becomes a child process of the terminal. So if you exit that terminal, it will also terminate any child processes. The only way to get around that is to either detach the process from the terminal with something like nohup. Now if you end up adding the #!/usr/bin/env python shebang line, your os could possibly just run the script without a terminal window if you just double click the script. YMMV (Again depends on how your OS works)
answers question: http://stackoverflow.com/q/47759603
has comment: http://stackoverflow.com/comment/82482112
has comment: http://stackoverflow.com/comment/82481364

http://stackoverflow.com/q/47746039
tagged with: python-3.x
tagged with: tkinter
has comment: http://stackoverflow.com/comment/82452461
accepted answer: http://stackoverflow.com/a/47746206
upvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/47746206
downvote count: 1
has comment: http://stackoverflow.com/comment/82452177
type: AnsweredQuestion
has title: Assign dynamic buttons with name tkinter
has comment: http://stackoverflow.com/comment/82452460
tagged with: python
has comment: http://stackoverflow.com/comment/82452566
has body: I'm trying to make it so that once I put in the rows and columns of my generation for dynamic buttons, it will automatically assign each one with a name. For instance, row 1(A), column 1 will be A1. from tkinter import * from functools import partial root = Tk() def redClick(button_num): list_of_buttons[button_num].configure(bg="red") def buttonsMake(): ctr = 0 ## button number / offset number in the list for columns in range(10): for rows in range(3): movieSeats=Button(root, text="Empty", bg="green", fg="white", width=5, height=1, command=partial(redClick, ctr)) movieSeats.grid(row=rows,column=columns) list_of_buttons.append(movieSeats) ctr += 1 list_of_buttons=[] ## global variable buttonsMake() root.mainloop() I expect it to assign each button to a name. I think the global variable can do this, but don't know how. This is something else(alternative solution) that someone suggested. seats= [["A", "a1", "a2", "a3", "a4", "a5"], ["B", "b1", "b2", "b3", "b4", "b5"], ["C", "c1", "c2", "c3", "c4", "c5"], ["D", "d1", "d2", "d3", "d4", "d5"], ["E", "e1", "e2", "e3", "e4", "e5"]] def make_buttons(): for r, row in enumerate(seats): for c, seat in enumerate(row[1:]): # N.B. skip first element btn = Button(root, text="Empty", bg="#00CC00", height=1,width=6) btn.name = seat # arbitrary attribute on Button object btn.grid(row=r,column=c, padx=10, pady=10)
has comment: http://stackoverflow.com/comment/82452526
favorite count: 0
score: -1
type: Question

http://stackoverflow.com/a/47784018
has comment: http://stackoverflow.com/comment/82529481
has comment: http://stackoverflow.com/comment/82529695
downvote count: 0
upvote count: 7
score: 7
answers question: http://stackoverflow.com/q/47783833
has comment: http://stackoverflow.com/comment/82530732
has comment: http://stackoverflow.com/comment/82529474
type: Answer
has body: The following method: Define lst Find all unique strings in lst Count occurrences in each tuple within the list Create dataframe Is implemented here: import pandas as pd import numpy as np lst = [('apple','banana','carrots'),('apple',),('banana','carrots',)] cols = np.unique(sum(tuple(lst),())) data = [[i.count(j) for j in cols] for i in lst] df = pd.DataFrame(columns=cols, data=data) Output: apple banana carrots 0 1 1 1 1 1 0 0 2 0 1 1

http://stackoverflow.com/comment/83029832
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47895926
has text: It works well now! Thank you so much! So, how do I mark this as "answered"? Also, do I "upvote" or something?
score: 0

http://stackoverflow.com/a/47776539
type: Answer
has comment: http://stackoverflow.com/comment/82516174
has body: We using pd.concat +drop_duplicates df1=pd.concat([df1,df2]).drop_duplicates(keep=False) df1 Out[1085]: ID PROGRAM_CODE Status 0 123 888 Active 0 123 888 BLAH Then we groupby create the table you need df1.groupby('ID').Status.apply(list).apply(pd.Series).add_prefix('Status_') Out[1094]: Status_0 Status_1 ID 123 Active BLAH Updated df=pd.concat([df1,df2]).drop_duplicates(keep=False) dd=df.groupby('ID').agg(lambda x:sorted(set(x), key=list(x).index)).stack() dd[dd.apply(len)&gt;1] Out[1194]: ID 123 STATUS [Active, Inactive] 345 PROGRAM_CODE [777, 999] I_CODE [125, 111] INSTITUTION [GUB, ZBD]
has comment: http://stackoverflow.com/comment/82514847
accepted answer of: http://stackoverflow.com/q/47776356
upvote count: 3
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82518890
downvote count: 0
has comment: http://stackoverflow.com/comment/82515597
answers question: http://stackoverflow.com/q/47776356
score: 3

http://stackoverflow.com/a/47852140
score: 0
accepted answer of: http://stackoverflow.com/q/47852102
type: Answer
has comment: http://stackoverflow.com/comment/82668665
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47852102
has comment: http://stackoverflow.com/comment/82668723
has body: Try this: from matplotlib import pyplot as plt def onclick(event): if event.dblclick: fig, ax = plt.subplots() circle = plt.Circle((event.xdata,event.ydata),2.5,color='black') ax.set_xlim([-40, 40]) ax.set_ylim([-40, 40]) ax.set_aspect('equal') ax.add_artist(circle) plt.show() cid = fig.canvas.mpl_connect('button_press_event',onclick)

http://stackoverflow.com/a/47826996
answers question: http://stackoverflow.com/q/47826907
downvote count: 0
has comment: http://stackoverflow.com/comment/82616580
upvote count: 1
score: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47826907
has comment: http://stackoverflow.com/comment/82616555
has body: Is this line RUN important? Can we exclude it when we don't need it? Yes if your code doesn't need the packages then you can exclude it. But I want it to be running always in the background like a Linux service. How to do that? If you want to run it as background then use below command. docker run -d --restart=always python-hello-world This will start container in background and will start automatically when system reboots.
type: Answer
has comment: http://stackoverflow.com/comment/82616373

http://stackoverflow.com/q/47725484
has comment: http://stackoverflow.com/comment/82412110
score: 2
answer count: 0
upvote count: 3
linked to: http://stackoverflow.com/q/53497
has comment: http://stackoverflow.com/comment/82412091
has comment: http://stackoverflow.com/comment/82412040
has comment: http://stackoverflow.com/comment/82412286
tagged with: string
downvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
duplicate of: http://stackoverflow.com/q/53497
tagged with: ipv6
has comment: http://stackoverflow.com/comment/82411757
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82412144
tagged with: python
has body: I'm trying to find out IPv6 address from a string. I've done this on IPv4 part by using re.findall(re.compile('\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}'),addr). How can I modify this to IPv6? Here's my string: addr = "......IP address is 2001:0000:3238:DFE1:63::FEFB. SUbnet mask is.........." Any help is appreciated. :)
has title: How to parseIPv6 address in a string using Python 3.x
has comment: http://stackoverflow.com/comment/82412304
has comment: http://stackoverflow.com/comment/82411850
tagged with: regex
has comment: http://stackoverflow.com/comment/82411644

http://stackoverflow.com/a/47820313
downvote count: 0
score: 1
type: Answer
answers question: http://stackoverflow.com/q/47819144
upvote count: 1
has body: You can try something like this : first get the from to index numbers when splitter appeared then just chuck the list according to those index: sl = ['splitter001','stringA','stringB','splitter_1234','stringC'] si = [index for index, value in enumerate(sl) if value.startswith('splitter')] for i in range(0,len(si),1): slice=si[i:i+2] if len(slice)==2: print(sl[slice[0]:slice[1]]) else: print(sl[slice[0]:]) output: ['splitter001', 'stringA', 'stringB'] ['splitter_1234', 'stringC']

http://stackoverflow.com/comment/82412468
comment on: http://stackoverflow.com/q/47725949
has text: can you post the entire data
type: Comment
type: QuestionComment
score: 0

python-requests
tags question: http://stackoverflow.com/q/47832170
tags question: http://stackoverflow.com/q/47706382
tags question: http://stackoverflow.com/q/47745133
tags question: http://stackoverflow.com/q/47849077
tags question: http://stackoverflow.com/q/47705743
tags question: http://stackoverflow.com/q/47828090
tags question: http://stackoverflow.com/q/47837771
tags question: http://stackoverflow.com/q/47820743
tags question: http://stackoverflow.com/q/47800065
tags question: http://stackoverflow.com/q/47706295
tags question: http://stackoverflow.com/q/47836456
tags question: http://stackoverflow.com/q/47756936
tags question: http://stackoverflow.com/q/47766158
tags question: http://stackoverflow.com/q/47852181
tags question: http://stackoverflow.com/q/47748567
tags question: http://stackoverflow.com/q/47805205
tags question: http://stackoverflow.com/q/47832807
tags question: http://stackoverflow.com/q/47741606
type: Tag
tags question: http://stackoverflow.com/q/47720520
tags question: http://stackoverflow.com/q/47722844
tags question: http://stackoverflow.com/q/47698199
tags question: http://stackoverflow.com/q/47731658
tags question: http://stackoverflow.com/q/47755026
tags question: http://stackoverflow.com/q/47784668
tags question: http://stackoverflow.com/q/47722154
tags question: http://stackoverflow.com/q/47854507
tags question: http://stackoverflow.com/q/47831379
tags question: http://stackoverflow.com/q/47832232
tags question: http://stackoverflow.com/q/47824080
tags question: http://stackoverflow.com/q/47759085
tags question: http://stackoverflow.com/q/47782111
tags question: http://stackoverflow.com/q/47769040
tags question: http://stackoverflow.com/q/47781895
tag name: python-requests
tags question: http://stackoverflow.com/q/47834956
tags question: http://stackoverflow.com/q/47818790
tags question: http://stackoverflow.com/q/47826177
tags question: http://stackoverflow.com/q/47781633
tags question: http://stackoverflow.com/q/47723797
tags question: http://stackoverflow.com/q/47780198
tags question: http://stackoverflow.com/q/47767596
tags question: http://stackoverflow.com/q/47752535
tags question: http://stackoverflow.com/q/47791972
tags question: http://stackoverflow.com/q/47723537
tags question: http://stackoverflow.com/q/47728949
tags question: http://stackoverflow.com/q/47730671
tags question: http://stackoverflow.com/q/47802350
tags question: http://stackoverflow.com/q/47752447
tags question: http://stackoverflow.com/q/47777908
tags question: http://stackoverflow.com/q/47811129
tags question: http://stackoverflow.com/q/47703748
tags question: http://stackoverflow.com/q/47782788

http://stackoverflow.com/q/47749851
tagged with: google-app-engine
has answer: http://stackoverflow.com/a/47768570
tagged with: app-engine-ndb
downvote count: 0
answer count: 1
tagged with: default-value
tagged with: python
has body: I'm working in Google App Engine, Python 2.7, Standard Environment, using the ndb datastore. I'm doing some updates to some of my NDB models, and one of the updates requires me to add a new property (a floating-point number) to my "Restaurant" model. In the past, when I've needed to add properties to a model, I've always liked how NDB lets you specify default values when defining the model, like so: class Restaurant(ndb.Model): ... some properties ... resto_fullresyncstamp = ndb.FloatProperty(default=0.0) My understanding of this default value was, when the entity was fetched from the datastore, if there is no resto_fullresyncstamp property for a given entity, one is added to the local copy of the model, with the default value. That way, I don't have to keep checking to see if everything is None, and I can assume the property will always have a value in my code. So I should be able to do something like this ... lastsync = ... resto = Restaurant.query()....get() if not resto: logging.warning("Failed to get restauraunt: %s" % username) self.error(404) return if lastsync != 0.0 and resto.resto_fullresyncstamp &gt; lastsync: logging.warning("Requiring client to perform full resynchronization") self.error(510) return ... and expect that, even if "resto_fullresyncstamp" is a new property in my model, and the particular restaurant has never had that property set explicitly anywhere, that I will still get a valid (0.0) value to compare against. What I'm actually getting is this error message: Traceback (most recent call last): .... File "/base/data/home/apps/s~virt-som/1.406133528491612487/virtsom.py", line 5399, in post if lastsync != 0.0 and resto.resto_fullresyncstamp &gt; lastsync: AttributeError: 'Restaurant' object has no attribute 'resto_fullresyncstamp' Shouldn't this work? I've been working with NDB for ages, and I've used the "default" parameter in my Models like this successfully before. Am I missing something?
favorite count: 0
score: 2
has title: Google App Engine NDB FloatProperty default value not working?
type: Question
upvote count: 2
type: UnansweredQuestion

http://stackoverflow.com/comment/82529509
type: Comment
has text: @AntonvBR What is the dictionary comprehension equivalent to the following code?Can you please help me in this? human_sp = {} for record in sp_records: if record.id.find("HUMAN") > -1: human_sp[record.id] = record
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47784026

http://stackoverflow.com/comment/82610741
type: AnswerComment
comment on: http://stackoverflow.com/a/47823587
score: 0
has text: @Lycopersicum I am using Python 2.7.12. I tried all of them but I still get errors! With the first and third syntax I get: SyntaxError: identifier starts immediately after numeric literal. With the second syntaxI get: Could not parse the remainder. thank you for your help!
type: Comment

http://stackoverflow.com/q/47816182
has body: I'm compiling protobuf schema files to python 3 using protoc, but after importing via an __init__.py's __all__, I'm getting an AttributeError from the dependencies list of the FileDescriptor object. I think my situation is intuitive, but it requires a lengthy description. I have one protobuf schema that imports another one, both in the same package. This almost seems like a circular dependency problem, where the module is not yet initialized before the generated python file tries to reference it. This is my directory structure, before compilation: company_package \ project_package \ bar.proto # imports foo.proto \ foo.proto \ __init__.py # exposes classes via __all__ \ __init__.py # has extend_path from pkgutil build.sh with a build.sh containing: protoc --python_out=. company_package/project_package/foo.proto protoc --python_out=. company_package/project_package/bar.proto an independent foo.proto containing: syntax = "proto2"; package company; message Foo { required string msg = 1; } and, as stated above, a dependent bar.proto containing: syntax = "proto2"; import "company_package/project_package/foo.proto"; package company; message Bar { required Foo foo = 1; } The __init__.py of company_package has the usual pkgutil.extend_path code. The __init__.py of project_package contains: from .foo_pb2 import Foo from .bar_pb2 import Bar __all__ = ['Foo', 'Bar'] After invoking sh build.sh, the directory structure is: company_package \ project_package \ bar_pb2.py \ bar.proto \ foo_pb2.py \ foo.proto \ __init__.py \ __init__.py build.sh and if I open up a REPL in an isolated virtual environment and execute the following line, I get this error: In [1]: from company_package.project_package import * --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) &lt;ipython-input-1-70765a748bd5&gt; in &lt;module&gt;() ----&gt; 1 from company_package.project_package import * {omitted}/company_package/project_package/__…
tagged with: python
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/47832387
answer count: 1
type: Question
accepted answer: http://stackoverflow.com/a/47832387
tagged with: python-3.x
tagged with: protocol-buffers
has title: Python 3 Protobuf AttributeError from FileDescriptor dependencies list

http://stackoverflow.com/q/47747195
tagged with: scikit-learn
has body: How Can I create csv file containing words and its frequency of occurrence in python . I removed the stop words, tokenized and countvectorized the text data My code data['Clean_addr'] = data['Adj_Addr'].apply(lambda x: ' '.join([item.lower() for item in x.split()])) data['Clean_addr']=data['Clean_addr'].apply(lambda x:"".join([item.lower() for item in x if not item.isdigit()])) data['Clean_addr']=data['Clean_addr'].apply(lambda x:"".join([item.lower() for item in x if item not in string.punctuation])) data['Clean_addr'] = data['Clean_addr'].apply(lambda x: ' '.join([item.lower() for item in x.split() if item not in (new_stop_words)])) cv = CountVectorizer( max_features = 200,analyzer='word') cv_addr = cv.fit_transform(data.pop('Clean_addr')) Sample Dump of the File I am using https://www.dropbox.com/s/allhfdxni0kfyn6/Test.csv?dl=0 **Expected output** Word Freq Industry 40 Limited 23 House 45 flat 56
favorite count: 0
type: Question
has title: how to find and write a frequency of occurrence of words inside text data into csv file using pandas
has answer: http://stackoverflow.com/a/47747481
has comment: http://stackoverflow.com/comment/82454898
tagged with: python
tagged with: nlp
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82454750
accepted answer: http://stackoverflow.com/a/47747481
downvote count: 0
tagged with: pandas
upvote count: 1
score: 1
answer count: 1

indices
tags question: http://stackoverflow.com/q/47734392
tag name: indices
type: Tag

http://stackoverflow.com/q/47836641
has body: I've managed to have to the Evernote Python API work and display notes (using the getNoteContent(noteguid) directive). But I would just like to display the title of the note (not the notebook). The one that is referred as : note.title = "Test note from EDAMTest.py" When creating a note with NoteStore.createNote(note) I tried a thousand things, never made it work. Searched on the Internet for it, nothing. And to be honest, the Evernote API doc is lame and outdated. So please, does someone know how to do it? Right now, this is how I display the content of the note : note = note_store.getNoteContent(noteguid) notestr = ET.fromstring(note) for child in notestr: chose = check,' ',child.tail # that's the en-todo checklist type of note... Thank you in advance for any clue or answer!
score: 0
tagged with: evernote
type: Question
has title: Evernote Python API Display Title of note
tagged with: api
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47837817
answer count: 1
tagged with: python

http://stackoverflow.com/comment/82674941
type: Comment
has text: if you need an array of points, you can use an array, or numpy. And of course you do - because if you had just one point, you wouldn't be concerned about its memory consumption!
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47853968

web-scraping
tags question: http://stackoverflow.com/q/47825938
tags question: http://stackoverflow.com/q/47855539
tags question: http://stackoverflow.com/q/47855765
tags question: http://stackoverflow.com/q/47851832
tags question: http://stackoverflow.com/q/47836276
tags question: http://stackoverflow.com/q/47744558
tags question: http://stackoverflow.com/q/47773179
tags question: http://stackoverflow.com/q/47800256
tags question: http://stackoverflow.com/q/47745751
tags question: http://stackoverflow.com/q/47734744
tags question: http://stackoverflow.com/q/47852596
tags question: http://stackoverflow.com/q/47760220
tags question: http://stackoverflow.com/q/47817006
tags question: http://stackoverflow.com/q/47721045
tag name: web-scraping
tags question: http://stackoverflow.com/q/47762060
tags question: http://stackoverflow.com/q/47771698
tags question: http://stackoverflow.com/q/47822369
tags question: http://stackoverflow.com/q/47725804
tags question: http://stackoverflow.com/q/47852373
tags question: http://stackoverflow.com/q/47782041
tags question: http://stackoverflow.com/q/47761481
tags question: http://stackoverflow.com/q/47741606
tags question: http://stackoverflow.com/q/47838519
tags question: http://stackoverflow.com/q/47718163
tags question: http://stackoverflow.com/q/47731658
tags question: http://stackoverflow.com/q/47708331
tags question: http://stackoverflow.com/q/47801788
tags question: http://stackoverflow.com/q/47855373
tags question: http://stackoverflow.com/q/47828773
tags question: http://stackoverflow.com/q/47708122
tags question: http://stackoverflow.com/q/47730671
tags question: http://stackoverflow.com/q/47803004
type: Tag
tags question: http://stackoverflow.com/q/47741815
tags question: http://stackoverflow.com/q/47726484
tags question: http://stackoverflow.com/q/47753932
tags question: http://stackoverflow.com/q/47706246
tags question: http://stackoverflow.com/q/47813718
tags question: http://stackoverflow.com/q/47738285
tags question: http://stackoverflow.com/q/47704682
tags question: http://stackoverflow.com/q/47720832
tags question: http://stackoverflow.com/q/47721021
tags question: http://stackoverflow.com/q/47713819
tags question: http://stackoverflow.com/q/47781895
tags question: http://stackoverflow.com/q/47849191
tags question: http://stackoverflow.com/q/47780213
tags question: http://stackoverflow.com/q/47735375
tags question: http://stackoverflow.com/q/47795262
tags question: http://stackoverflow.com/q/47850153
tags question: http://stackoverflow.com/q/47780198
tags question: http://stackoverflow.com/q/47752535
tags question: http://stackoverflow.com/q/47740151
tags question: http://stackoverflow.com/q/47749796
tags question: http://stackoverflow.com/q/47851288
tags question: http://stackoverflow.com/q/47720520
tags question: http://stackoverflow.com/q/47817800
tags question: http://stackoverflow.com/q/47745106
tags question: http://stackoverflow.com/q/47830384
tags question: http://stackoverflow.com/q/47700618
tags question: http://stackoverflow.com/q/47793131
tags question: http://stackoverflow.com/q/47765195
tags question: http://stackoverflow.com/q/47723537
tags question: http://stackoverflow.com/q/47832281
tags question: http://stackoverflow.com/q/47796867
tags question: http://stackoverflow.com/q/47744697
tags question: http://stackoverflow.com/q/47846306
tags question: http://stackoverflow.com/q/47853248
tags question: http://stackoverflow.com/q/47730869

http://stackoverflow.com/a/47830625
accepted answer of: http://stackoverflow.com/q/47829457
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47829457
score: 1
type: Answer
has body: Here's a simple version. It's an alternative to the other answers and diverges from instructions by randomly setting elements to zero as is suggested for exponential decay rather than removing a deterministic 1/2 at each round. This prints the entire array each round but alternatives could include the first element, print(a[0]), or the number remaining, print(a.sum()). a = np.ones(100) while any(a): print(a) for i, _ in enumerate(a): if random.random() &gt; 0.5: a[i] = 0

http://stackoverflow.com/comment/82638967
type: Comment
type: QuestionComment
has text: The Octave code has a number if `if` clauses to handle various `n`, odd and a couple of `mod(n,4)` cases.
comment on: http://stackoverflow.com/q/47834140
score: 0

http://stackoverflow.com/a/47731786
answers question: http://stackoverflow.com/q/47712093
upvote count: 12
accepted answer of: http://stackoverflow.com/q/47712093
has comment: http://stackoverflow.com/comment/82424498
type: Answer
has comment: http://stackoverflow.com/comment/110972737
has body: There are several ways to tackle long running executions. Each way has its benefits and drawbacks. APIs As already suggested, the simplest ways is to rely on the APIs timeouts. Modules such as subprocess, socket, requests etc... expose timeout parameters within their APIs. This is the preferable approach whenever feasible. Threads The long-running/hanging logic is executed within a separate thread. The main loop can continue undisturbed and ignore the hanging execution. import threading TIMEOUT = 60 def hanging_function(): hang_here() thread = threading.Tread(target=hanging_function) thread.daemon = True thread.start() thread.join(TIMEOUT) if thread.is_alive(): print("Function is hanging!") One of the issue with this approach is that the hanging thread will continue to execute in the background consuming resources. Another limitation is due to the fact that threads share memory. If your your function happens to crash badly it might affect your main execution as well. Processes My favourite approach is to execute the problematic logic in a separate process using the multiprocessing facilities. As processes do not share memory, whatever happens in the problematic function remains limited to the child process which you can terminate at any point in time. import multiprocessing TIMEOUT = 60 def hanging_function(): hang_here() process = multiprocessing.Process(target=hanging_function) process.daemon = True process.start() process.join(TIMEOUT) if process.is_alive(): print("Function is hanging!") process.terminate() print("Kidding, just terminated!") The pebble library was built on top of this principle. Allowing to easily separate problematic code and deal with failures and catastrophes. The drawback of using processes is that they are a bit heavier than the other two approaches. Moreover, as memory between processes is isolated, it's a bit more complicated to share data.
score: 12
has comment: http://stackoverflow.com/comment/113805974
downvote count: 0
has comment: http://stackoverflow.com/comment/110975302
has comment: http://stackoverflow.com/comment/113803981
has comment: http://stackoverflow.com/comment/82424604
type: AcceptedAnswer

http://stackoverflow.com/q/47715950
upvote count: 1
has comment: http://stackoverflow.com/comment/82392410
has comment: http://stackoverflow.com/comment/82392387
tagged with: window
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82392336
type: UnansweredQuestion
tagged with: icons
tagged with: python
has comment: http://stackoverflow.com/comment/82392211
has title: How to get icon info of specific window in python?
has body: I'm building an auto time logger and i group the tasks by window title and process. But there are some tasks that are done in browser (chrome, firefox, etc.). From what i understood searching the net is that it's a bit more difficult to obtain the current url. So on second thought i figured out that i just need to know the site that is opened and probably i could get this info if i know what is the icon displayed in the tab. I'm using win32gui, psutil and win32process. fWin = win32gui.GetForegroundWindow() parentWindow = win32gui.GetParent(fWin) fWinText = win32gui.GetWindowText(fWin) if parentWindow is not 0: fWinText = win32gui.GetWindowText(parentWindow) fWinPID = win32process.GetWindowThreadProcessId(fWin) fWinProc = psutil.Process(fWinPID[1]) That's the main info i'm getting. Also with: win32ui.GetForegroundWindow() I get the object of the window, but still can't find function that give me the icon info. If anyone has ideas, will be great : )
answer count: 0
downvote count: 0
score: 1

http://stackoverflow.com/q/47777469
upvote count: 3
has answer: http://stackoverflow.com/a/47777939
has title: Capitalize first character of first string, first two characters of second string,
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47777784
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82516640
has answer: http://stackoverflow.com/a/47777609
score: -1
has comment: http://stackoverflow.com/comment/82516271
has body: I have a list as follows: days = ['monday', 'tuesday', 'wednesday', 'thursday'] and I want to print this: Monday # 1 uppercase letter TUesday # 2 uppercase letters WEDnesday # ... THURsday This is what I have so far: for day in days: print day[0].upper() = day[1:] which prints: Monday Tuesday Wednesday Thursday How can I get the desired result?
has answer: http://stackoverflow.com/a/47777598
downvote count: 4
answer count: 4

http://stackoverflow.com/q/47833829
type: AnsweredQuestion
score: 2
tagged with: pandas
upvote count: 3
has body: Suppose I have the dataframe: A B C 1 2 3 4 5 6 7 8 9 I want to convert the rows into a single column: Column 1 2 3 4 5 6 7 8 9
tagged with: dataframe
tagged with: python
accepted answer: http://stackoverflow.com/a/47833875
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47834657
has answer: http://stackoverflow.com/a/47833875
answer count: 2
possible better answer: http://stackoverflow.com/a/47834657
has title: Most efficient way to convert rows into one single column
downvote count: 1

http://stackoverflow.com/a/47861863
score: 0
has body: You didn't mention the third possibility: that a tweet matched both "canada" and "usa". Still, the solution is simply to test if either or both filter words are present in the tweet. So: def on_data(self, data): text = data.text.lower() if "canada" in text: do_canada() if "usa" in text: do_usa() return True
answers question: http://stackoverflow.com/q/47852557
type: Answer

http://stackoverflow.com/a/47783578
type: Answer
answers question: http://stackoverflow.com/q/47783480
has comment: http://stackoverflow.com/comment/82529010
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/82528654
has body: Each line in the file has a newline character at the end. If you don't want it to print, strip it off print("Line read","'",str(line.strip()),"'") print("'",str(line.strip()),"'-&gt;'",line2,"'") s1 = ',,s.8,ymsw5w-86 \n' s2 = ' ,,s.8,ymsw5w-86\n' s3 = ' s8ymsw5w86 \n' Using f-strings: If you want single quotes in the string, enclose the string in double quotes and vis-versa print(f"'{s1.strip()}'") print(f"'{s2.strip()}' --&gt; '{s3.strip()}'") &gt;&gt;&gt; ',,s.8,ymsw5w-86' ',,s.8,ymsw5w-86' --&gt; 's8ymsw5w86' &gt;&gt;&gt; or s1 = ',,s.8,ymsw5w-86 \n' s2 = "".join(filter(str.isalnum,s1)) print(f"Line read ... '{s1.strip()}'") print(f"'{s1.strip()}' --&gt; '{s2.strip()}'") &gt;&gt;&gt; Line read ... ',,s.8,ymsw5w-86' ',,s.8,ymsw5w-86' --&gt; 's8ymsw5w86' &gt;&gt;&gt;
accepted answer of: http://stackoverflow.com/q/47783480
has comment: http://stackoverflow.com/comment/82529116

http://stackoverflow.com/comment/82672006
score: 0
has text: This works perfectly while the Tkinter window is open! There is, however, a runtime error that occurs upon closing the window and it says that the main thread is not present in the main loop. Out of curiosity, why does this happen and how can I fix it?
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47846364

http://stackoverflow.com/q/47815329
upvote count: 1
has comment: http://stackoverflow.com/comment/82592858
has answer: http://stackoverflow.com/a/47817696
accepted answer: http://stackoverflow.com/a/47817696
tagged with: equality
has comment: http://stackoverflow.com/comment/82592280
has comment: http://stackoverflow.com/comment/82601787
favorite count: 0
type: Question
tagged with: numpy
has body: I have a long list and its element type is int. I want to find the index of element that equals to a certain number and I use np.where to achieve this. The following is my original code, # suppose x is [1, 1, 2, 3] y = np.array(x, dtype=np.float32) idx = list(np.where(y==1)[0]) # output is [0, 1] After inspecting the code after some time, I realize that I should not use dtype=np.float32 because it would change the datatype of y to float. The correct code should be the following, # suppose x is [1, 1, 2, 3] y = np.array(x) idx = list(np.where(y==1)[0]) # output is also [0, 1] Surprisingly, these two code snippet produce exactly the same result. my question My does the condition for test of equality is handled in numpy.where when the datatype of array and target are not compatible (int vs float, e.g.)?
tagged with: arrays
has comment: http://stackoverflow.com/comment/82593024
answer count: 1
has title: how does numpy.where() method handle the equality condition when the array element and target are not the same data type
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82592733
downvote count: 0
score: 1

http://stackoverflow.com/comment/82517747
type: Comment
type: QuestionComment
score: 0
has text: Ah. I misunderstood the question.
comment on: http://stackoverflow.com/q/47778162

http://stackoverflow.com/comment/82609226
score: 1
type: Comment
type: QuestionComment
has text: what is "0x00000000004087b8 "?? A string?
comment on: http://stackoverflow.com/q/47823221

vtk
tags question: http://stackoverflow.com/q/47794066
tags question: http://stackoverflow.com/q/47776121
type: Tag
tags question: http://stackoverflow.com/q/47738246
tag name: vtk
tags question: http://stackoverflow.com/q/47714565

dictionary
tags question: http://stackoverflow.com/q/47851181
tags question: http://stackoverflow.com/q/47758806
tags question: http://stackoverflow.com/q/47703921
tags question: http://stackoverflow.com/q/47847282
tags question: http://stackoverflow.com/q/47807446
tags question: http://stackoverflow.com/q/47705840
tags question: http://stackoverflow.com/q/47804241
tags question: http://stackoverflow.com/q/47698334
tags question: http://stackoverflow.com/q/47707527
tags question: http://stackoverflow.com/q/47728915
tags question: http://stackoverflow.com/q/47719384
tags question: http://stackoverflow.com/q/47716598
tags question: http://stackoverflow.com/q/47814362
tags question: http://stackoverflow.com/q/47730869
tags question: http://stackoverflow.com/q/47705412
tags question: http://stackoverflow.com/q/47754103
tags question: http://stackoverflow.com/q/47813091
tags question: http://stackoverflow.com/q/47782922
tags question: http://stackoverflow.com/q/47734244
tags question: http://stackoverflow.com/q/47854248
tags question: http://stackoverflow.com/q/47837548
tags question: http://stackoverflow.com/q/47742481
tags question: http://stackoverflow.com/q/47852113
tags question: http://stackoverflow.com/q/47737470
tags question: http://stackoverflow.com/q/47701545
tags question: http://stackoverflow.com/q/47782052
tags question: http://stackoverflow.com/q/47733402
tags question: http://stackoverflow.com/q/47720439
tags question: http://stackoverflow.com/q/47844961
tags question: http://stackoverflow.com/q/47729256
tags question: http://stackoverflow.com/q/47700386
tags question: http://stackoverflow.com/q/47726023
tags question: http://stackoverflow.com/q/47845494
tags question: http://stackoverflow.com/q/47758510
tags question: http://stackoverflow.com/q/47796263
tags question: http://stackoverflow.com/q/47801211
tags question: http://stackoverflow.com/q/47818970
tags question: http://stackoverflow.com/q/47700690
tags question: http://stackoverflow.com/q/47796474
tags question: http://stackoverflow.com/q/47832762
tags question: http://stackoverflow.com/q/47780390
tags question: http://stackoverflow.com/q/47842743
tags question: http://stackoverflow.com/q/47762563
tags question: http://stackoverflow.com/q/47780418
tags question: http://stackoverflow.com/q/47761907
tags question: http://stackoverflow.com/q/47766038
tags question: http://stackoverflow.com/q/47800625
tags question: http://stackoverflow.com/q/47754354
tags question: http://stackoverflow.com/q/47821883
tags question: http://stackoverflow.com/q/47736316
tags question: http://stackoverflow.com/q/47787204
tags question: http://stackoverflow.com/q/47815456
tags question: http://stackoverflow.com/q/47798471
tags question: http://stackoverflow.com/q/47793442
tags question: http://stackoverflow.com/q/47780687
tags question: http://stackoverflow.com/q/47715457
tags question: http://stackoverflow.com/q/47757946
tags question: http://stackoverflow.com/q/47727236
tags question: http://stackoverflow.com/q/47849533
tags question: http://stackoverflow.com/q/47823477
tags question: http://stackoverflow.com/q/47742004
tags question: http://stackoverflow.com/q/47728941
tags question: http://stackoverflow.com/q/47790687
tags question: http://stackoverflow.com/q/47732878
tags question: http://stackoverflow.com/q/47823141
tags question: http://stackoverflow.com/q/47745869
tags question: http://stackoverflow.com/q/47762272
tags question: http://stackoverflow.com/q/47783748
tags question: http://stackoverflow.com/q/47710393
tags question: http://stackoverflow.com/q/47731301
tags question: http://stackoverflow.com/q/47777776
tags question: http://stackoverflow.com/q/47795746
tags question: http://stackoverflow.com/q/47760355
tags question: http://stackoverflow.com/q/47846283
tags question: http://stackoverflow.com/q/47819417
tags question: http://stackoverflow.com/q/47752233
tags question: http://stackoverflow.com/q/47753912
tags question: http://stackoverflow.com/q/47755080
type: Tag
tags question: http://stackoverflow.com/q/47840093

http://stackoverflow.com/q/47701162
answer count: 3
has comment: http://stackoverflow.com/comment/82878164
score: 1
has title: Like button with Ajax
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/66525258
favorite count: 0
type: Question
tagged with: python-3.x
type: UnansweredQuestion
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/47701740
tagged with: ajax
has answer: http://stackoverflow.com/a/47713934
has body: I am trying to create a like button with ajax. This is my architecture: models.py class Comentario (models.Model): titulo = models.CharField(max_length=50) texto = models.CharField(max_length=200) autor = models.ForeignKey (Perfil, null=True, blank=True, on_delete=models.CASCADE) fecha_publicacion = models.DateTimeField(auto_now_add=True) tag = models.ManyToManyField(Tags, blank=True) slug = models.SlugField(null=True) likes = models.ManyToManyField(Perfil, blank=True, related_name="likes") def __str__(self): return (self.titulo) @property def total_likes(self): return self.likes.count() def save(self, *args, **kwargs): self.slug = slugify(self.titulo) super(Comentario, self).save(*args, **kwargs) views.py def like(request): if request.method == 'POST': perfil = request.user slug = request.POST.get('slug', None) comentario = get_object_or_404(Comentario, slug=slug) if comentario.objects.filter(id=user.id).exists(): comentario.likes.remove(user) else: comentario.likes.add(user) contexto = {'likes_count': comentario.total_likes } return HttpResponse(json.dumps(contexto), content_type='application/json') urls.py url(r'^like$', login_required(like), name='like'), html &lt;input type="button" id="like" name="{{ company_slug }}" value="Like" /&gt; &lt;script&gt; $('#like').click(function(){ $.ajax({ type: "POST", url: "{% url 'home:like' %}", data: {'slug': $(this).attr('titulo'), 'csrfmiddlewaretoken': '{{ csrf_token }}'}, dataType: "json", success: function(response) { alert(response.message); alert(' likes count is now ' + response.likes_count); }, error: function(rs, e) { alert(rs.responseText); } }); }) &lt;/script&gt; When I push the button like it does not do anything. The console tells me: POST htt jquery.min.js:4 p:/127.0.0.1.8000/home/like/404 (not found) and: http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js What is the problem?

http://stackoverflow.com/a/47721340
downvote count: 0
type: Answer
has body: By subquerying a join you can achieve a multiple join : query = select([u.id, u.name]).select_from(join(join(u,add, u.id = add.user_id),po, po.id = add.id)) print(query)
answers question: http://stackoverflow.com/q/47719657
type: AcceptedAnswer
score: 8
upvote count: 8
accepted answer of: http://stackoverflow.com/q/47719657

python-imageio
type: Tag
tags question: http://stackoverflow.com/q/47775083
tags question: http://stackoverflow.com/q/47822318
tags question: http://stackoverflow.com/q/47725161
tag name: python-imageio

http://stackoverflow.com/comment/82428500
comment on: http://stackoverflow.com/q/47733919
score: 1
type: Comment
type: QuestionComment
has text: Don't post unindented Python code. Make the effort to post code that makes sense.

http://stackoverflow.com/q/47797507
has body: What is the recommended method for logging variables using Python logging, and why is it better? Old-style interpolation: apple = "green" logger.debug("apple is %s", apple) or New-style .format() logger.debug("apple is {}".format(apple)) I have heard that interpolation is preferred, because it only evaluates the string if it's going to be printed, but I haven’t verified if it actually matters.
tagged with: python
linked to: http://stackoverflow.com/q/32000934
accepted answer: http://stackoverflow.com/a/65211129
linked to: http://stackoverflow.com/q/34619790
score: 9
type: AnsweredQuestion
answer count: 2
has comment: http://stackoverflow.com/comment/82556511
has title: Python logging variables: interpolation or format?
has comment: http://stackoverflow.com/comment/82555942
has comment: http://stackoverflow.com/comment/82561022
downvote count: 0
tagged with: logging
favorite count: 0
possible better answer: http://stackoverflow.com/a/65614918
type: Question
has comment: http://stackoverflow.com/comment/82555948
has answer: http://stackoverflow.com/a/65211129
has comment: http://stackoverflow.com/comment/82557387
has answer: http://stackoverflow.com/a/65614918
upvote count: 9

http://stackoverflow.com/comment/82685015
comment on: http://stackoverflow.com/a/47859099
type: Comment
type: AnswerComment
has text: Yes! Sorry, I'm new to this. Thank you so much.
score: 1

http://stackoverflow.com/comment/82522482
comment on: http://stackoverflow.com/q/47780550
type: Comment
type: QuestionComment
has text: I suggest you post the code that you're working with and explain specifically what you're trying to do with reference to it. This appears to be a classic [XY problem](http://xyproblem.info/) at the moment.
score: 2

http://stackoverflow.com/q/47841373
type: AnsweredQuestion
downvote count: 0
has title: How do I rearrange/reorder (not necessarily sort) a pandas dataframe index?
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/63343412
accepted answer: http://stackoverflow.com/a/47841417
has body: How do I rearrange/reorder (not necessarily sort) a pandas dataframe index? I have the following dataframe: df = pd.DataFrame({'A': [1, 2, 3, 4, 5, 6, 7], 'B': [0, 1, 0, 2, 1, 7, 1]}, index=['Sat', 'Tue', 'Sun', 'Fri', 'Wed', 'Mon', 'Thu']) which gives: A B Sat 1 0 Tue 2 1 Sun 3 0 Fri 4 2 Wed 5 1 Mon 6 7 Thu 7 1 I want to order the index by day of week (i.e., Sun, Mon, Tue, Wed, Thu, Fri, Sat). The dataframe with the rearranged/reordered index should look something like this: A B Sun 3 0 Mon 6 7 Tue 2 1 Wed 5 1 Thu 7 1 Fri 4 2 But using df.sort_index() results in an alphabetically-sorted index for df. How do I explicitly specify the ordering of a dataframe index? The solution I can think of is to pass the desired index ordering as a list during dataframe creation: df = pd.DataFrame(df, index=['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri']) What's another way to do this without creating another dataframe? Thank you.
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/47841417
upvote count: 13
score: 13
has answer: http://stackoverflow.com/a/47841485
possible better answer: http://stackoverflow.com/a/63343412
answer count: 3
tagged with: pandas

opencv
tags question: http://stackoverflow.com/q/47848911
tags question: http://stackoverflow.com/q/47710086
tags question: http://stackoverflow.com/q/47834070
tags question: http://stackoverflow.com/q/47772909
tags question: http://stackoverflow.com/q/47855220
tags question: http://stackoverflow.com/q/47850280
tags question: http://stackoverflow.com/q/47745934
type: Tag
tags question: http://stackoverflow.com/q/47786850
tags question: http://stackoverflow.com/q/47795163
tags question: http://stackoverflow.com/q/47823332
tags question: http://stackoverflow.com/q/47704818
tags question: http://stackoverflow.com/q/47788247
tags question: http://stackoverflow.com/q/47729708
tags question: http://stackoverflow.com/q/47772299
tags question: http://stackoverflow.com/q/47772806
tags question: http://stackoverflow.com/q/47739116
tags question: http://stackoverflow.com/q/47804333
tags question: http://stackoverflow.com/q/47808519
tags question: http://stackoverflow.com/q/47755377
tags question: http://stackoverflow.com/q/47721998
tags question: http://stackoverflow.com/q/47845059
tags question: http://stackoverflow.com/q/47786734
tags question: http://stackoverflow.com/q/47847238
tags question: http://stackoverflow.com/q/47704895
tags question: http://stackoverflow.com/q/47736968
tags question: http://stackoverflow.com/q/47709192
tags question: http://stackoverflow.com/q/47774652
tags question: http://stackoverflow.com/q/47855193
tags question: http://stackoverflow.com/q/47737307
tags question: http://stackoverflow.com/q/47749021
tags question: http://stackoverflow.com/q/47809355
tags question: http://stackoverflow.com/q/47740128
tags question: http://stackoverflow.com/q/47821174
tags question: http://stackoverflow.com/q/47830176
tags question: http://stackoverflow.com/q/47827245
tags question: http://stackoverflow.com/q/47732102
tags question: http://stackoverflow.com/q/47748968
tags question: http://stackoverflow.com/q/47792905
tags question: http://stackoverflow.com/q/47794365
tags question: http://stackoverflow.com/q/47761632
tags question: http://stackoverflow.com/q/47712950
tags question: http://stackoverflow.com/q/47783149
tags question: http://stackoverflow.com/q/47782595
tags question: http://stackoverflow.com/q/47843124
tags question: http://stackoverflow.com/q/47746772
tags question: http://stackoverflow.com/q/47835138
tags question: http://stackoverflow.com/q/47726854
tags question: http://stackoverflow.com/q/47802751
tags question: http://stackoverflow.com/q/47841688
tags question: http://stackoverflow.com/q/47840595
tags question: http://stackoverflow.com/q/47759764
tags question: http://stackoverflow.com/q/47745541
tags question: http://stackoverflow.com/q/47816940
tags question: http://stackoverflow.com/q/47716746
tags question: http://stackoverflow.com/q/47746868
tags question: http://stackoverflow.com/q/47833315
tags question: http://stackoverflow.com/q/47855046
tags question: http://stackoverflow.com/q/47851566
tags question: http://stackoverflow.com/q/47736640
tags question: http://stackoverflow.com/q/47784542
tags question: http://stackoverflow.com/q/47787803
tags question: http://stackoverflow.com/q/47789968
tags question: http://stackoverflow.com/q/47819168
tags question: http://stackoverflow.com/q/47782311
tags question: http://stackoverflow.com/q/47743246
tags question: http://stackoverflow.com/q/47810910
tags question: http://stackoverflow.com/q/47853415
tags question: http://stackoverflow.com/q/47854318
tags question: http://stackoverflow.com/q/47824785
tags question: http://stackoverflow.com/q/47733478
tag name: opencv
tags question: http://stackoverflow.com/q/47749852
tags question: http://stackoverflow.com/q/47734513
tags question: http://stackoverflow.com/q/47844276
tags question: http://stackoverflow.com/q/47783371
tags question: http://stackoverflow.com/q/47734322
tags question: http://stackoverflow.com/q/47777585
tags question: http://stackoverflow.com/q/47709162
tags question: http://stackoverflow.com/q/47756176

merge
type: Tag
tags question: http://stackoverflow.com/q/47761983
tags question: http://stackoverflow.com/q/47713679
tags question: http://stackoverflow.com/q/47758806
tags question: http://stackoverflow.com/q/47778267
tag name: merge
tags question: http://stackoverflow.com/q/47818984
tags question: http://stackoverflow.com/q/47793302
tags question: http://stackoverflow.com/q/47842009

http://stackoverflow.com/q/47745209
linked to: http://stackoverflow.com/q/4383571
accepted answer: http://stackoverflow.com/a/47755082
tagged with: terminal
has answer: http://stackoverflow.com/a/47755082
has title: Proper way of importing Python scripts from separate folders
tagged with: python
has comment: http://stackoverflow.com/comment/82450637
type: AnsweredQuestion
score: 0
has body: So I have been fiddling around as well as conducting some serious work with Python for quite some time. Though, I still have some issues with it every once in a while. I find it to be the most comfortable using PyCharm CE when working with Python. The typical scenario is that I just create a new virtualenv, launch PyCharm and open up my virtualenv there. And from there on out, it's like on auto-pilot, PyCharm handles all the dirty work related to which site-packages and Python runtime to use. I always like to keep my virtualenvs clean and organized, so I often find myself semantically organizing my source code into submodules/subfolders. So whenever I want to import some code, or class, or whatever from another folder I just import it. Imagine I have the following structure in my virtualenv: ├── bin ├── include ├── lib └── src ├── foo.py ├── important_scripts ├── some_script.py └── some_other_script.py └── pip-selfcheck.json Now, somewhere in foo.py, I want to use a function named A() that is implemented in some_script.py. The obvious way would be to add a simple line to foo.py - something like from some_script import A. Doing such works perfectly when I run and debug my code (foo.py in this case) from PyCharm. As opposed to the the typical scenario I have described above, I wanted to do the same from the Terminal.app. So I fire up the Terminal, cd to my virtualenv and activate it. Then, what I do is, using the Python executable that is under the bin folder in my virtualenv, I try to run foo.py (At least this is what I think is the equivalent of right-clicking and running foo.py from the PyCharm window). Unfortunately, I get the error ModuleNotFoundError: No module named 'some_script'. I think I am missing a simple detail or something. Because like I said, it works like magic when run from PyCharm. Anyways, any advice or help will be highly appreciated. Thanks in advance.
linked to: http://stackoverflow.com/q/1260792
tagged with: pycharm
answer count: 1
tagged with: virtualenv
type: Question

http://stackoverflow.com/comment/82411664
type: Comment
type: AnswerComment
has text: The brackets are `[` and `]` - they are how you define a list in Python. `seatCapacity = []` creates an empty list. If `line[10:].split()` contains more than one number, you could use a second for loop to append each individual number to `seatCapacity`.
score: 0
comment on: http://stackoverflow.com/a/47724968

http://stackoverflow.com/a/47794428
type: Answer
score: 0
has body: I think you meant to get the header cells from the first row of the table (once, before the loop) and iterate over the tr elements instead of td. You can also use a regular find() instead of find_all()[0] and enumerate() to handle the loop increment variable more nicely: table = soup.find('table') rows = table.find_all('tr') headers = [th.get_text(strip=True) for th in rows[0].find_all('th')] for ct, row in enumerate(rows[1:]): values = [td.get_text(strip=True) for td in row.find_all('td')] d = dict(zip(headers, values)) print(d)
answers question: http://stackoverflow.com/q/47786886

http://stackoverflow.com/a/51822482
score: 1
type: Answer
downvote count: 0
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47791879
has body: I'm not sure if this is consistent across all images, but for official images all it takes is prefixing an image name with the architecture: docker run s390x/python:3.7-alpine3.8 python --version docker run arm64v8/alpine uname -a You can check the above repo for supported architectures for each release.
answers question: http://stackoverflow.com/q/47791879

http://stackoverflow.com/q/47804317
type: AnsweredQuestion
score: 0
type: Question
accepted answer: http://stackoverflow.com/a/47861860
has body: Question I've read up some on accessing status from a Celery worker from a Flask application, like in this tutorial, but can you go the other way? Send an interrupt or get introspection into a Celery worker after it's been started? I've read a bit about signals, but either don't understand them yet or it's not what I'm looking for. Possibly both. Background I'm using Celery to kick off a long-running loop that subscribes to an MQTT topic, I'd like to be able to also shut down that process/subscription from another endpoint in my Flask app. What's the best way to do this? Or a way? Example Code from flask import Flask from celery import Celery import time app = Flask(__name__) app.config['CELERY_BROKER_URL'] = 'redis://localhost:6379/0' app.config['CELERY_RESULT_BACKEND'] = 'redis://localhost:6379/0' celery = Celery(app.name, broker=app.config['CELERY_BROKER_URL']) celery.conf.update(app.config) @celery.task(bind=True) def test_loop(self): i=0 running = True while running: i = i+1 print "loop running %d" % i time.sleep(1) @app.route('/') def index(): return 'index page' @app.route('/start') def start(): global task task = test_loop.delay() return "started loop" @app.route('/stop') def stop(): global task ### What I'm having trouble with task.running = False ### How can I interrupt/introspect into the task? return "stopped loop" TL/DR Is there a way to send an interrupt or get introspection into a Celery worker after it's been started? How can I stop a long-running loop started in a Celery Worker from Flask?
tagged with: signals
has answer: http://stackoverflow.com/a/47861860
answer count: 1
tagged with: python
tagged with: flask
has title: How to send interrupt to Celery worker from Flask?
tagged with: interrupt
tagged with: celery

http://stackoverflow.com/a/47814170
answers question: http://stackoverflow.com/q/47814032
has body: instead of that line: rename(path.join(dirpath, f), path.join(dirpath, path.split(dirpath)[-1] + '_' + f)) generate a new name using str.replace: newf = f.replace("example",os.path.basename(dirpath)+"_") then rename(path.join(dirpath, f), path.join(dirpath,newf)) of course if you don't know the extension or the "prefix" of the input file, and only want to keep the number &amp; extension, there's a way: import re number = (re.findall("\d+",f) or ['000'])[0] this extracts the number from the name, and if not found, issues 000. Then rebuild newf with the folder name, the extracted number &amp; the original extension: newf = "{}_{}.{}".format(os.path.basename(dirpath),number,os.path.splitext(f)[1])
has comment: http://stackoverflow.com/comment/82590727
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82590020
score: 0
accepted answer of: http://stackoverflow.com/q/47814032
type: Answer
has comment: http://stackoverflow.com/comment/82591783
has comment: http://stackoverflow.com/comment/82590098
has comment: http://stackoverflow.com/comment/82591642

http://stackoverflow.com/q/47705124
upvote count: 1
tagged with: python
possible better answer: http://stackoverflow.com/a/47706156
type: AnsweredQuestion
answer count: 3
has answer: http://stackoverflow.com/a/47706156
accepted answer: http://stackoverflow.com/a/47760137
tagged with: azure
tagged with: azure-cosmosdb
has answer: http://stackoverflow.com/a/47760137
downvote count: 0
score: 1
has title: How do I set continuation tokens for Cosmos DB queries sent by document_client objects in Python?
favorite count: 0
type: Question
has body: I have an API that retrieves documents based on keywords that appear in document fields. I would like to paginate results so that I can return documents to a client sending a request, as well as allowing them to request more documents if they want. The query itself only takes a second or so in the browser when I am in the Azure Data Explorer, but it takes about a minute when I query using the Python DocumentDB library. Looking at the Microsoft Cosmos DB REST API, it appears as if there are two tokens, x-ms_continuation and x-ms-max-item-count that are used. It doesn't appear that putting these as entries in the options dictionary of document_client.QueryDocuments() does the trick. In the GitHub repository, the Read() method references the options parameter: headers = base.GetHeaders(self, initial_headers, 'get', path, id, type, options) # Read will use ReadEndpoint since it uses GET operation url_connection = self._global_endpoint_manager.ReadEndpoint result, self.last_response_headers = self.__Get(url_connection, path, headers) Looking in base.py, where the file is located, I saw these two blocks of code if options.get('continuation'): headers[http_constants.HttpHeaders.Continuation] = ( options['continuation']) if options.get('maxItemCount'): headers[http_constants.HttpHeaders.PageSize] = options['maxItemCount'] This would appear to correspond to the two parameters above. However, when I set them as options in the query ({'continuation':True,'maxItemCount':10}), nothing changes. The final query looks like client.QueryDocuments(collection_link, query, {'continuation':True,'maxItemCount':10}) I have also tried using a string instead of an int for maxItemCount. What am I doing incorrectly here? Edit: The headers are the same as the two from the documentation above, from http_constants.py: # Our custom DocDB headers Continuation = 'x-ms-continuation' PageSize = 'x-ms-max-item-count'
has answer: http://stackoverflow.com/a/49391755

http://stackoverflow.com/comment/82646414
score: 1
type: Comment
comment on: http://stackoverflow.com/a/47840964
type: AnswerComment
has text: Did you mean to say that *he* needs to look at the Python tuturial?

http://stackoverflow.com/a/47782259
type: Answer
answers question: http://stackoverflow.com/q/47782111
downvote count: 1
has comment: http://stackoverflow.com/comment/82563344
has comment: http://stackoverflow.com/comment/82565201
has comment: http://stackoverflow.com/comment/82563315
has comment: http://stackoverflow.com/comment/82526356
upvote count: 3
type: AcceptedAnswer
has body: By capturing network events, I have come to this conclusion. The button is defined as this in the webpage: ... Notice the two things, data-key data-ajaxurl After clicking the button, the web browser loads this URL via AJAX: http://www.imdb.com/title/tt1392170/reviews/_ajax?paginationKey=xxdr3yxoixpwgjg7c6vq44huu6hi6xe5qywg3adr43xlnl5sas6df5ed53iunemqakizscc53xq32 or http://www.imdb.com/{data-ajaxurl}?paginationKey={data-key}
score: 2
accepted answer of: http://stackoverflow.com/q/47782111

http://stackoverflow.com/comment/82382778
has text: I may have many other points other than those forming a line. E.g. a triangle detected far away from the main line. Or I may have multiple lines in different orientations.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47710086

http://stackoverflow.com/a/47718031
score: 0
has body: Using the help danihp gave me in the answer and obeying the hint DDeMartini gave in the comment I was able to create a lightweight xml parser that returns a dict structure of the xml: import re def xml_loads(xml_text): matches = re.findall(r'<([^<>]+)>([\s\S]*)</(\1)>', xml_text) if not matches: return xml_text.strip() d = {} for k, s2, _ in matches: d[k] = xml_loads(s2) return d s = ''' 1 52 Abc 21 ''' d = xml_loads(s) print(d)
answers question: http://stackoverflow.com/q/47716948
type: Answer

http://stackoverflow.com/comment/82543736
comment on: http://stackoverflow.com/q/47790591
score: 0
type: Comment
type: QuestionComment
has text: But your dictionary, if it indeed has `int` keys, will also lose the leading zero. If you do: `my_dict[int("018904837646")] = "foo"` you'll be able to retrieve the value back with `my_dict[18904837646]` and if your `acc_id = "018904837646"` as a string, you'd still be able to retrieve the value from `my_dict` with: `my_dict[int(acc_id)]`. You just cannot have integers with leading 0 and you have to ensure that your `my_dict` keys are of the same type as your `acc_id` that you want to use for lookup.

http://stackoverflow.com/comment/82618106
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47827561
type: AnswerComment
has text: @JonClements, I get a KeyError on your solution. On the first solution from Jezrael, I get the error: IndexingError: Unalignable boolean Series key provided.

http://stackoverflow.com/comment/112515449
has text: @Vishnu, you could try it. i thing the second one performs better.
comment on: http://stackoverflow.com/a/47714013
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/82530269
type: Comment
score: 0
type: AnswerComment
has text: Thank you. What's the difference between the two declarations `defaultdict(lambda: MyClass)` and `defaultdict(MyClass)`?
comment on: http://stackoverflow.com/a/47784391

http://stackoverflow.com/q/47849057
tagged with: python
has comment: http://stackoverflow.com/comment/82662658
type: AnsweredQuestion
has title: Argparse: too few arguments translation API
tagged with: argparse
has comment: http://stackoverflow.com/comment/82663044
score: 1
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/82662618
favorite count: 0
accepted answer: http://stackoverflow.com/a/47849395
has body: I am using a google translation API and it is showing error: translate boy -d french usage: [-h] [-d DEST] [-s SRC] [-c] text : error: too few arguments The code of API is #!/usr/bin/env python # -*- coding: utf-8 -*- import argparse import sys from googletrans import Translator def main(): parser = argparse.ArgumentParser( description='Python Google Translator as a command-line tool') parser.add_argument('text', help='The text you want to translate.') parser.add_argument('-d', '--dest', default='en', help='The destination language you want to translate. (Default: en)') parser.add_argument('-s', '--src', default='auto', help='The source language you want to translate. (Default: auto)') parser.add_argument('-c', '--detect', action='store_true', default=False, help='') args = parser.parse_args() translator = Translator() if args.detect: result = translator.detect(args.text) result = """ [{lang}, {confidence}] {text} """.strip().format(text=args.text, lang=result.lang, confidence=result.confidence) print(result) return result = translator.translate(args.text, dest=args.dest, src=args.src) result = u""" [{src}] {original} -&gt; [{dest}] {text} [pron.] {pronunciation} """.strip().format(src=result.src, dest=result.dest, original=result.origin, text=result.text, pronunciation=result.pronunciation) print(result) if __name__ == '__main__': main() I think it is due to argparse module but I am not sure. I am a newbie so please explain completely. Thanks in advance.
type: Question
has answer: http://stackoverflow.com/a/47849395
tagged with: api
has comment: http://stackoverflow.com/comment/82662636
upvote count: 1

http://stackoverflow.com/q/47841056
type: Question
tagged with: python-3.x
has body: I am working a system which should make one of my raspberry pi GPIO pins to HIGH for about 2 seconds. I split this in 2 different files. The "website" file(named app.py) and the "GPIO" file(named test.ty). The test file is requested in this way: from flask import Flask, render_template from test import open_door app = Flask(__name__) @app.route('/opendoor') def openDoor(): open_door() if __name__ == '__main__': app.run(debug=True, host='0.0.0.0') The test.py file looks like this: import RPi.GPIO as GPIO import time testPin = 18 GPIO.setmode(GPIO.BCM) GPIO.setup(testPin, GPIO.OUT) counter =0 def open_door(): try: print ("Everthing is fine") while counter &lt; 900000: print ("Everything is good") GPIO.output(testPin, GPIO.HIGH) counter += 1 except: print ("Everything is oke!") finally: GPIO.cleanup() I get the messages "everything is fine" and "everything is oke!" but not the message "everything is good". This seems to me that the while loop does not execute. Anybody any idea why it does not work?
tagged with: while-loop
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/47824519
tagged with: python
has title: while loop does not loop or execute for that matter
has answer: http://stackoverflow.com/a/47841082
has answer: http://stackoverflow.com/a/47841440
answer count: 3
downvote count: 0
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/82646555
has answer: http://stackoverflow.com/a/47841143
has comment: http://stackoverflow.com/comment/82646385
favorite count: 0

http://stackoverflow.com/comment/114947206
has text: @AkshayHazari sounds like you have a different problem entirely unrelated to this question or answer. Try [here](https://stackoverflow.com/a/55417280/5747944) or ask a new question.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47808940
score: 1

http://stackoverflow.com/comment/82367515
comment on: http://stackoverflow.com/a/47703628
has text: pop removes that element from the list and returns it's value.
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/82452852
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47746229
type: Comment
has text: will take note, thanks. but accessing docker is not the issue here. I neeed to run simple scripts with requests.

http://stackoverflow.com/comment/82503316
has text: Do I need to compile anything? I downloaded/installed primesieve using pip.
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47768878

http://stackoverflow.com/a/47859099
accepted answer of: http://stackoverflow.com/q/47852769
type: Answer
answers question: http://stackoverflow.com/q/47852769
score: 0
has comment: http://stackoverflow.com/comment/82685015
has body: At every iteration of your for loop you are overwriting the entire "zip_code" with output satdata["zip_code"]= output so the output with same value in all row is easily explained. You could initialize: satdata["zip_code"]='' and then do satdata.loc[satdata['DBN']==adress,"zip_code"]= output in the for loop. Let me know if that works
type: AcceptedAnswer

http://stackoverflow.com/q/47744347
tagged with: scikit-learn
tagged with: kaggle
has title: Incorrect ROC score for Kaggle competition?
tagged with: logistic-regression
type: AnsweredQuestion
has body: I was researching a Kaggle competition and used a Logistic Regression classifier to test the top 10 competitiors' approaches. Link to the competition: https://www.kaggle.com/c/detecting-insults-in-social-commentary/leaderboard I'm still fairly new to the classification problems so I just tested classifiers without too much modifications. In this case I used scikit-learn's logreg. I cleaned the test/train data and used it to generate a ROC curve. My area under the curve was 0.89 which would have placed me in 1st place with a significant lead and this seems quite impossible to me considering my implementation's simplicity. Could someone tell me if my program is doing something incorrectly that gives such a score (Ex. somehow overfitting or bug in code)? import csv import preprocessor as p import matplotlib.pyplot as plt from sklearn import linear_model from sklearn.feature_extraction.text import TfidfVectorizer from nltk.stem.snowball import SnowballStemmer from nltk.tokenize import word_tokenize from sklearn.metrics import roc_curve from sklearn.metrics import auc path = "C:\\Users\\Mike\\Desktop" def vectorize_dataset(subpath, stem, vectorizer): comments = [] labels = [] stemmer = SnowballStemmer("english") with open(path + subpath + '.csv', 'r') as f: data_csv = csv.reader(f) for row in data_csv: clean_txt = p.clean(row[2]) clean_txt = clean_txt.strip().replace('"', '').replace('\\\\', '\\').replace('_', ' ') clean_txt = bytes(clean_txt, 'utf-8').decode('unicode_escape', 'ignore') if stem: clean_txt = [stemmer.stem(word.lower()) for word in word_tokenize(clean_txt)] clean_txt = [word for word in clean_txt if word.isalpha()] clean_txt = " ".join(clean_txt) if clean_txt != "": if row[0] == str(1) or row[0] == str(0): comments.append(clean_txt) labels.append(int(row[0])) if subpath == "\\train": return (vectorizer.fit_transform(comments), labels) return (vectorizer.transform(comments), labels) def print_auroc_for_classifier(vect_tuple, classifier): y_true, y_score = […
tagged with: python
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47750365
tagged with: classification
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/47750365
upvote count: 1
score: 1

http://stackoverflow.com/comment/82569667
comment on: http://stackoverflow.com/q/47804023
score: 0
type: Comment
has text: all systems can save console output using `>` - ie. `python script.py > output.txt`
type: QuestionComment

http://stackoverflow.com/a/75043621
score: 1
type: Answer
has body: After some looking, I think the closest tool I could find easily is darglint but it was recently put into archive-mode on GitHub (December 2022) so long term support is not guaranteed or even likely. One option, inspired by this discussion from torchvision is to use Sphinx-Napoleon and pydocstyle with almost everything turned off, except D417 which is a check for missing arguments in the docstring. So pydocstyle can check for missing arguments but it cannot currently check for extra arguments. Edit: seems pylint can do this with an extension https://pylint.pycqa.org/en/latest/user_guide/checkers/extensions.html#pylint-extensions-docparams but there is some functional overlap between the various linters and style checkers so you might need to just pick which ones you go with. For catching renamed arguments, you could also enforce 100% coverage in your tests, but that wouldn't catch refactors to non-keyword arguments. Of some other packages available: doctest is good for checking if your docstring examples run correctly, but it doesn't do any signature validation. So if you set a default parameter like the example in the question, it will still pass doctest. If you used keyword arguments for all your examples, you could use this as a check, but it's a bit verbose. interrogate is capable of checking docstring coverage, but not much else (as far as I can tell?) I'm not sure whether other tools actually check coverage though, so this is potentially a good tool to use in tandem.
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47704552

http://stackoverflow.com/q/47756551
type: UnansweredQuestion
tagged with: apache
has body: I´m newbie to python and selenium. I´m creating app with GUI in web browser and the logic is executed in python under Apache. I have written some selenium scripts that work perfect when testing seperately outside Apache. But when I try to execute Selenium script under Apache on localhost, new Chrome or Firefox window won´t open. Apache with Python is confugured correctly --> able to run other python scripts. So here is my code: PYTHON !#path to python from selenium import webdriver import selenium.webdriver.chrome.service as service service = service.Service('C:\\wamp64\\www\\chromedriver.exe') service.start() capabilities = {'chrome.binary': 'c:/Program Files (x86)/Google/Chrome/Application/chrome.exe'} driver = webdriver.Remote(service.service_url, capabilities) driver.get('https://www.google.com/') #Here is code to get var div_text print("Content-type: text/html\n\n") print(div_text) I am quite lost here, because new Chrome window won't open a Apache error log is empty. What am I missing here? Tested on python 3.4.0 and 3.6.3 with same results --> works fine from prompt (no Apache), doesn't work on localhost(Apache) Only thing that came to my mind was that scripts on Apache server do not have the permission to execute WIN apps. Thanks for your advice
has title: Cannot run python Selenium script under localhost
tagged with: python
tagged with: localhost
score: 2
answer count: 0
tagged with: selenium
downvote count: 0
favorite count: 0
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/93000882

http://stackoverflow.com/q/47788056
has comment: http://stackoverflow.com/comment/82538057
tagged with: terminal
has title: -q command in terminal, PyQt5 on Python2.7
score: 1
tagged with: python
tagged with: macos
answer count: 0
has comment: http://stackoverflow.com/comment/82537207
type: UnansweredQuestion
downvote count: 0
tagged with: pyqt5
upvote count: 1
has body: I have spent the last hour or two trying to install PyQt5 for Python2.7. It is a pretty straight forward task, however I am running into an error following this github guide. So far, I have been able to get through to line 21. Here I run into an error, configure.py: error: no such option: -q. I have typed the code exactly and cannot find any information online about what -q is. Or what it does. Here is my full terminal input/output: $ python configure.py -q /Users/development/Qt/5.9.1/clang_64/bin/qmake -d /Library/Python/2.7/site-packages/ --sip /System/Library/Frameworks/Python.framework/Versions/2.7/bin/sip This is SIP 4.16.7 for Python 2.7.10 on darwin. Usage: python configure.py [opts] [macro=value] [macro+=value] configure.py: error: no such option: -q Thank you in advance. Updated with --help Zacharys-MacBook-Pro:sip-4.16.7 development$ python configure.py --help This is SIP 4.16.7 for Python 2.7.10 on darwin. Usage: python configure.py [opts] [macro=value] [macro+=value] Options: --version show program's version number and exit -h, --help show this help message and exit -k, --static build the SIP module as a static library -p PLATFORM, --platform=PLATFORM the platform/compiler configuration [default: macx-g++] -u, --debug build with debugging symbols --sip-module=NAME the package.module name of the sip module [default: sip] --configuration=FILE FILE contains the target configuration --target-py-version=VERSION the major.minor version of the target Python [default: 2.7] --sysroot=DIR DIR is the target system root directory --no-tools disable the building of the code generator and the installation of the build system [default: enabled] --use-qmake generate qmake .pro files instead of Makefiles MacOS X Configuration: --arch=ARCH build for architecture ARCH --deployment-target=VERSION set the value of the MACOSX_DEPLOYMENT_TARGET environment variable in generated Makefiles -n, --universal build the SIP code generator and module as universal binaries -s SDK, --sd…
has comment: http://stackoverflow.com/comment/82560149
favorite count: 0
type: Question

http://stackoverflow.com/comment/82629589
score: 1
type: Comment
comment on: http://stackoverflow.com/q/47833192
type: QuestionComment
has text: If you want to plot individual bars, the arguments still have to be lists or arrays. Hence, `ax.bar(xs, ys, zs, ...)` should be `ax.bar([xs], [ys], [zs], ...)`.

http://stackoverflow.com/comment/82672956
type: QuestionComment
score: 0
has text: Note that you are using os.path.expanduser in second imread but not in first imread
type: Comment
comment on: http://stackoverflow.com/q/47854318

http://stackoverflow.com/a/48332301
type: Answer
accepted answer of: http://stackoverflow.com/q/47743936
answers question: http://stackoverflow.com/q/47743936
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: Batches have variable length, so smaller batches may pass without OOM while larger ones may not. Depending on your implementation, you can print out the batches lengths (the largest length of the batch such that all other sequences are padded up to that length) and determine whether this is causing your issue. To fix this, lower your batch size, or set a max length for your iterator. This is not a memory leak.
score: 1

http://stackoverflow.com/comment/82412574
type: QuestionComment
score: 0
has text: Yes exactly as what @ChrisMartin said
type: Comment
comment on: http://stackoverflow.com/q/47725949

http://stackoverflow.com/comment/82494823
type: AnswerComment
has text: list of strings [ ' ' ]
type: Comment
comment on: http://stackoverflow.com/a/47766820
score: 0

http://stackoverflow.com/comment/82425732
type: AnswerComment
comment on: http://stackoverflow.com/a/47732357
type: Comment
has text: @Kongstad This looks like a fun project. Want some help with it? If you put the complete code on github or similar I'll clean it up for you.
score: 0

http://stackoverflow.com/comment/82410651
has text: Yes, Exactly! this is the problem
comment on: http://stackoverflow.com/a/47722573
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/82543548
has text: @Alfe Huh... I don't follow. The `[0-9]+` matches as many as it **can**, but at least one. If the decimal part, or an integer number, is single digit, the `[0-9]+` matches the single digit and there's nothing left for `[^.*+=<>]` to match. Greedy or not has nothing to do with it failing. It would matter what would be **matched** though, if the decimal part (or integer) is more than two digit. `1.2345` -> greedy matches `1.234` + `5`, non greedy matches `1.2` + `3`.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47775235

http://stackoverflow.com/q/47779071
type: Question
has comment: http://stackoverflow.com/comment/82519325
score: -2
has body: I'm currently trying to scrape a huge number of small web pages from a website. I already know what to do when I have the page, but to run through all of the pages (more than 5000), I found all of the individual page URLs were just like: blablabla?id=1957-002A-02. I divided the URL into 4 sections: the first 4 digits (just a year fom 1957 to 2017), then after the hyphen 3 digits (just counting up) and a letter (same) and after another hyphen 2 digits (counting up). What I know: there's a limit (let me explain): 1957-002A-01 have some text I care about 1957-002A-02 have some text I care about 1957-002A-03 don't have any interesting text (I can detect it) and I can skip directly to: 1957-002B-01 have some text I care about 1957-002B-02 have some text I care about 1957-002B-03 have some text I care about 1957-002B-04 don't have any interesting text, I skip: 1957-002C-01 don't have anything interesting, I skip: 1957-002D-02 is the second in a row to now have anything, so I skip to the next letter: 1957-003A-01, and so on... How can I roll through a lot of ID's while being able to skip at any moment?
has comment: http://stackoverflow.com/comment/82519482
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/82519301
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47779143
possible better answer: http://stackoverflow.com/a/47779320
answer count: 2
has answer: http://stackoverflow.com/a/47779143
has answer: http://stackoverflow.com/a/47779320
has comment: http://stackoverflow.com/comment/82519977
downvote count: 3
has title: How to run through a lot of id's quickly?
favorite count: 0

recursion
type: Tag
tags question: http://stackoverflow.com/q/47846798
tags question: http://stackoverflow.com/q/47778342
tags question: http://stackoverflow.com/q/47705947
tags question: http://stackoverflow.com/q/47740347
tags question: http://stackoverflow.com/q/47841025
tags question: http://stackoverflow.com/q/47763326
tags question: http://stackoverflow.com/q/47703686
tags question: http://stackoverflow.com/q/47748556
tags question: http://stackoverflow.com/q/47727786
tags question: http://stackoverflow.com/q/47710833
tag name: recursion
tags question: http://stackoverflow.com/q/47778513
tags question: http://stackoverflow.com/q/47835260
tags question: http://stackoverflow.com/q/47846686
tags question: http://stackoverflow.com/q/47761340
tags question: http://stackoverflow.com/q/47847283
tags question: http://stackoverflow.com/q/47704591
tags question: http://stackoverflow.com/q/47721083
tags question: http://stackoverflow.com/q/47736752
tags question: http://stackoverflow.com/q/47765846
tags question: http://stackoverflow.com/q/47785574
tags question: http://stackoverflow.com/q/47807738
tags question: http://stackoverflow.com/q/47750334
tags question: http://stackoverflow.com/q/47783822

http://stackoverflow.com/comment/82580032
comment on: http://stackoverflow.com/a/47792885
has text: I don't know what is the most efficient. You can improve it as your hope.
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/a/47732771
downvote count: 0
has comment: http://stackoverflow.com/comment/90610627
accepted answer of: http://stackoverflow.com/q/47722238
upvote count: 37
answers question: http://stackoverflow.com/q/47722238
type: Answer
has comment: http://stackoverflow.com/comment/90650834
score: 37
has body: The documentation includes an example, although if I'm reading it right, helpers.scan by default sets search_type=scan, which was removed in ES 5.1. This causes the example code to fail with ES returning No search type for [scan]. We can amend this with preserve_order=True (I am however not sure about the performance implications here): import elasticsearch import elasticsearch.helpers es = elasticsearch.Elasticsearch() results = elasticsearch.helpers.scan(es, index="test_index", doc_type="my_document", preserve_order=True, query={"query": {"match_all": {}}}, ) for item in results: print(item['_id'], item['_source']['name']) This helper returns an object which you can iterate to obtain the actual results from the query. item is of form {'_index': &lt;str&gt;, '_type': &lt;str&gt;, '_id': &lt;str&gt;, '_score': &lt;float or None&gt;, '_source': {'key': val}, 'sort': [&lt;int&gt;]}
type: AcceptedAnswer

http://stackoverflow.com/q/47803986
has answer: http://stackoverflow.com/a/47804069
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/47804074
has comment: http://stackoverflow.com/comment/82569570
has comment: http://stackoverflow.com/comment/82569546
has comment: http://stackoverflow.com/comment/82569603
tagged with: function
answer count: 2
downvote count: 0
has body: I'm a noobie at Python and got this task, which I'm having trouble in starting. I've an IP.log file with this info: 12.0.0.1 120 x 188.1.1.1 12 x 199.1.1.1 3 99.1.5.5 1 Bassically I've to make an app with such functionalities: Sorting the file by IP, deleting records, adding record, markinf /unmarking the IP address, editing the records, reseting the count to zero. The read file should display something like this: 1 | 12.0.0.1 | 120 | x 2 | 188.1.1.1 | 12 | x 3 | 199.1.1.1 | 3 | 4 | 99.1.5.5 | 1 | Any help to help me get on track would be appreciated.
upvote count: 1
tagged with: loops
type: UnansweredQuestion
score: 1
favorite count: 0
has title: Python IP address management module

http://stackoverflow.com/comment/120013819
score: 0
comment on: http://stackoverflow.com/q/47767576
has text: Does this worked? for me the code returns None from the answer
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47814547
has answer: http://stackoverflow.com/a/47818745
type: Question
has comment: http://stackoverflow.com/comment/82592513
tagged with: appium
has comment: http://stackoverflow.com/comment/82591315
tagged with: python
accepted answer: http://stackoverflow.com/a/47833125
has comment: http://stackoverflow.com/comment/82590946
tagged with: python-appium
has body: I got a quesition for you, On my application, i would like to click multiple time (10) on a button. But the application doesn't accept the tap option, so the following code doesnt work : multi_click = TouchAction(self.driver) multi_click.tap(self.driver.find_element_by_id('logo'),0,0,8) And the click action are too slow to be compted as multiple click if i set a "while" : while i &lt; 10: self.driver.find_element_by_id('logo').click() i+= 1 print (i) Have you any idea ? Regards
has answer: http://stackoverflow.com/a/47833125
type: AnsweredQuestion
score: 0
answer count: 2
has title: Appium python : multiple click
possible better answer: http://stackoverflow.com/a/47818745

http://stackoverflow.com/comment/82574050
score: 1
type: Comment
has text: @ScottBoston it went from taking 3.894 seconds to 0.376 seconds for the entire python program, so roughly a 10x speedup.
type: AnswerComment
comment on: http://stackoverflow.com/a/47806109

http://stackoverflow.com/q/47818546
has answer: http://stackoverflow.com/a/47818641
accepted answer: http://stackoverflow.com/a/47818641
answer count: 1
downvote count: 1
duplicate of: http://stackoverflow.com/q/10084436
favorite count: 0
type: Question
has title: Splitting a list of number into N even subsections
tagged with: split
has body: I have a list of numbers, and I want to split them up into N evenly spaced numbers, while the first and last number must be in the resulting list, all numbers should be an integer, so I'm ok with the space between the last two being off by a little. For example I have a range of 1-100 and the I want the resulting list in three numbers, so it would be [1, 50, 100]. Is there a python way to split them? Or what could be an equation to get the increment? Getting the increment by (last-first)/N will not work because it will results in more numbers. I couldn't come up with a working equation to get the increment, the best I have is (last-first-2)/N-2, but that fails to give an even split on some combinations.
has comment: http://stackoverflow.com/comment/82599076
tagged with: python
score: -1
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/10084436
upvote count: 0
tagged with: list

http://stackoverflow.com/comment/118201767
has text: Nice :) This also did the trick for me! Ps: It works already without the `import codecs` -part, so you can choose to take that out if you want :)
type: AnswerComment
comment on: http://stackoverflow.com/a/47722635
score: 0
type: Comment

http://stackoverflow.com/a/47874841
answers question: http://stackoverflow.com/q/47848606
has comment: http://stackoverflow.com/comment/82795177
has comment: http://stackoverflow.com/comment/82795709
type: Answer
has body: Never heard of it.... but there are quite a few ways you can implement that yourself using a functional API model and custom functions. Below, there is a possible answer to this, but first, is this really the best to do?? If you're trying to create an autoencoder, you should not care about limiting the outputs. Otherwise, your model will not really learn much. Maybe the best to do is simply normalizing the inputs first (between -1 and +1), and using the tanh activation at the end. Funtional API model to preserve the input: inputTensor = Input(n_timesteps_in, n_features) out = LSTM(150, input_shape=)(inputTensor) out = RepeatVector(n_timesteps_in)(out) #this line sounds funny in your model... out = LSTM(150, return_sequences=True)(out) out = TimeDistributed(Dense(n_features))(out) out = Activation(chooseOneActivation)(out) out = Lambda(chooseACustomFunction)([out,inputTensor]) model = Model(inputTensor,out) model.compile(...) Custom limit options There are infinite ways of doing this, here are some examples that may or may not be what you need. But from this you are free to develop anything similar. The options below limits the individual outputs to the respective individual inputs. But you may prefer to use all outputs confined to the maximum input instead. If so, use this below: maxInput = max(originalInput, axis=1, keepdims=True) 1 - A simple stretched 'tanh': You can simply define both top and bottom limits by using a tanh (that ranges from -1 to +1) and multiplying it by the inputs. Use the Activation('tanh') layer, and the following custom function in the Lambda layer: import keras.backend as K def stretchedTanh(x): originalOutput = x[0] originalInput = x[1] return K.abs(originalInput) * originalOutput I'm not totally sure this will be a healthy option. If the idea is to create an autoencoder, this model will easily find a solution of outputing all tanh activations as close to 1 as possible, without really looking at the inputs. 2 - Modified 'relu' First, you c…
upvote count: 4
downvote count: 0
has comment: http://stackoverflow.com/comment/82839207
score: 4

http://stackoverflow.com/q/47853067
tagged with: python
type: UnansweredQuestion
has title: Why python interactive shell makes 'invalid syntax' error in end of indentation
has body: Code: Python 3.5.2 (default, Nov 23 2017, 16:37:01) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; for i in range(3): ... print(1) ... print(2) File "&lt;stdin&gt;", line 3 print(2) ^ SyntaxError: invalid syntax Expected output: 1 1 1 2 With several test, I knew python interactive shell return invalid syntax error when the indentation block has lower. Test code: if true: print("test") print(test) output: File "&lt;stdin&gt;", line 3 print("test") ^ SyntaxError: invalid syntax To solve this problem, I must using Enter key. &gt;&gt;&gt; for i in range(3): ... print(1) ... 1 1 1 &gt;&gt;&gt; print(2) 2 But why? why I have to separate two code using enter? I want to know the reason. Note: I'm bad at English and it's hard to describe it. "end of indentation" and "indentation block has lower" means that situation if true: //no indentation, no tab or space print(1) //in if syntax, we have to make indentation print(2) //when if end, We don't make indentation. Compare to line 2, 'indentation block has lower' and 'indentation had ended' I don't think it's right expression, So you may a little confused. if you understand this, please edit this question and make it right.
linked to: http://stackoverflow.com/q/46016327
score: 0
tagged with: shell
upvote count: 1
has comment: http://stackoverflow.com/comment/82670530
downvote count: 1
duplicate of: http://stackoverflow.com/q/46016327
has comment: http://stackoverflow.com/comment/82670514
favorite count: 0
type: Question
answer count: 0

http://stackoverflow.com/comment/103507984
type: QuestionComment
has text: You could run iPython from VS Code's console, and then use `%run -d code.py` or `%debug my_function()` etc. You will have tab-completion, but no debug-session integration with VS Code like variable inspection, jump to definition, etc.
comment on: http://stackoverflow.com/q/47701629
score: 0
type: Comment

http://stackoverflow.com/q/47822369
has comment: http://stackoverflow.com/comment/82607978
has comment: http://stackoverflow.com/comment/82650364
has comment: http://stackoverflow.com/comment/82607773
has comment: http://stackoverflow.com/comment/82607669
type: AnsweredQuestion
downvote count: 0
has body: I am running this script that fetches some content after finding an id, which will be populated by AJAX call, it should go to the second URL. After going to the second URL it doesn't find any content with the same id. Code snippet is here: from selenium import webdriver from selenium.webdriver.remote.webelement import WebElement from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait import json from selenium.webdriver.support import expected_conditions as EC path_to_chromedriver = 'D:\Mangilal\Downloads\chromedriver_win32\chromedriver.exe' #Change path as needed. browser = webdriver.Chrome(executable_path=path_to_chromedriver) #Sample list of URLs. lists_of_url = ['http://facebook.com', 'http://twitter.com', 'http://google.com', 'http://youtube.com', 'http://linkedin.com', 'http://wordpress.org', 'http://instagram.com', 'http://pinterest.com', 'http://wikipedia.org', 'http://wordpress.com', 'http://slideshare.net', 'http://e-recht24.de', 'http://washingtonpost.com', 'http://etsy.com', 'http://eventbrite.com', 'http://archive.org', 'http://cpanel.net', 'http://miibeian.gov.cn', 'http://sourceforge.net', 'http://telegraph.co.uk', 'http://ameblo.jp', 'http://amazon.co.uk', 'http://ebay.com', 'http://fc2.com', 'http://free.fr', 'http://bing.com'] for i in range(10): url = 'https://www.shareaholic.com/sharecounter?url=' + lists_of_url[i] browser.get(url) element = WebDriverWait(browser, 10).until(EC.presence_of_element_located((By.XPATH, '//*[@id="container"]/div[1]/div[2]/div[3]/div/div/h1/span'))) str = '' #Finding element here. count = browser.find_element_by_xpath('//*[@id="container"]/div[1]/div[2]/div[3]/div/div/h1/span') str = count.get_attribute('innerHTML') print(str) Output of this is shown in the image, which fetches content for the first URL after that null value:
tagged with: web-scraping
upvote count: 1
tagged with: python
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/82607504
type: Question
accepted answer: http://stackoverflow.com/a/47825500
has title: Selenium script is returning null to the element
has comment: http://stackoverflow.com/comment/82607592
tagged with: selenium
has comment: http://stackoverflow.com/comment/82650374
has answer: http://stackoverflow.com/a/47825500
score: 1

methods
tags question: http://stackoverflow.com/q/47853592
tags question: http://stackoverflow.com/q/47836792
tag name: methods
tags question: http://stackoverflow.com/q/47710955
tags question: http://stackoverflow.com/q/47706620
tags question: http://stackoverflow.com/q/47773065
type: Tag
tags question: http://stackoverflow.com/q/47724075
tags question: http://stackoverflow.com/q/47715070

http://stackoverflow.com/q/47823586
tagged with: tkinter
answer count: 2
has body: I have a Python/Tkinter program and I am trying to increment some numbers that are at the end of a variable used for tk.Entry boxes. For example, self.output0, self.output1, self.output2, etc (Sorry, my code is long so I tried shortening it up for an example.) self.entries = [] self.output0 = tk.Entry(self, width=149, justify='center', bd='0', bg='#E0E0E0') self.output0.grid(column=0, row=6, columnspan=5, padx=1) self.output1 = tk.Entry(self, width=149, justify='center', bd='0', bg='#E0E0E0') self.output1.grid(column=0, row=7, columnspan=5, padx=1) I grab the users input with another entry box such as 'self.first_entry' and run a SQL query on the user input. For example: class Adder(ttk.Frame): """The adders gui and functions.""" def __init__(self, parent, *args, **kwargs): ttk.Frame.__init__(self, parent, *args, **kwargs) self.root = parent self.init_gui() def authenticate(self): return pypyodbc.connect('Driver={SQL Server};Server=MYSERVERNAME;Database=MYDATABASENAME;Trusted_Connection=yes;') def calculate(self): firstname = str(self.first_entry.get()) # converts user entry into variable lastname = str(self.last_entry.get()) license = str(self.lic_entry.get()) try: connection = self.authenticate() except pypyodbc.Error as ex: sqlstate = ex.args[0] if sqlstate == '28000': self.output0.delete(0, END) self.output0.insert(0,"You do not have access.") cursor = connection.cursor() if (firstname and not lastname and not license): # "You entered first name." SQLCommand = ("SELECT LASTNAME, FIRSTNAME, LICNUMBER " "FROM MyTABLEName " # table name "with (nolock)" "WHERE FIRSTNAME LIKE ?") Values = [firstname + '%'] else: SQLCommand = ("SELECT LASTNAME, FIRSTNAME, LICNUMBER " "FROM MyTABLEName " # table name "(nolock)" "WHERE FIRSTNAME LIKE ? AND LASTNAME LIKE ? AND LICNUMBER LIKE ?") Values = [firstname + '%', lastname + '%', '%' + license + '%'] cursor.execute(SQLCommand,Values) results = cursor.fetchmany(10) if results: self.output0.delete(0, END) # clears entry self.output…
type: UnansweredQuestion
tagged with: python
has title: How to increment the number in results[0]?
score: 0
has answer: http://stackoverflow.com/a/47823728
has answer: http://stackoverflow.com/a/47823634
type: Question
tagged with: python-3.x

http://stackoverflow.com/a/48791563
type: AcceptedAnswer
score: 18
answers question: http://stackoverflow.com/q/47840527
has comment: http://stackoverflow.com/comment/84596521
upvote count: 18
type: Answer
has body: I came here with the exact same question. The accepted answer uses logcosh which may have similar properties, but it isn't exactly Huber Loss. Here's how I implemented Huber Loss for Keras (note that I'm using Keras from Tensorflow 1.5). import numpy as np import tensorflow as tf ''' ' Huber loss. ' https://jaromiru.com/2017/05/27/on-using-huber-loss-in-deep-q-learning/ ' https://en.wikipedia.org/wiki/Huber_loss ''' def huber_loss(y_true, y_pred, clip_delta=1.0): error = y_true - y_pred cond = tf.keras.backend.abs(error) &lt; clip_delta squared_loss = 0.5 * tf.keras.backend.square(error) linear_loss = clip_delta * (tf.keras.backend.abs(error) - 0.5 * clip_delta) return tf.where(cond, squared_loss, linear_loss) ''' ' Same as above but returns the mean loss. ''' def huber_loss_mean(y_true, y_pred, clip_delta=1.0): return tf.keras.backend.mean(huber_loss(y_true, y_pred, clip_delta)) Depending if you want to reduce the loss or the mean of the loss, use the corresponding function above.
has comment: http://stackoverflow.com/comment/84596715
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47840527

http://stackoverflow.com/comment/82530717
score: 0
type: Comment
has text: Fair enough. I suppose it would be better to stick with the parenthesis based on that. What about the class form? Should that be done?
type: AnswerComment
comment on: http://stackoverflow.com/a/47784164

http://stackoverflow.com/comment/82677050
comment on: http://stackoverflow.com/a/47856111
has text: EDIT: For whatever reason, the same _base = "https://fr.example.com/things?t={category}&p={index}"_ that worked for other domains, didn't for FR and US. I just added www. to fr.example.com and it worked. Having _base = "https://www.fr.example.com/things?t={category}&p={index}"_ works. No idea why.
type: Comment
score: 0
type: AnswerComment

seaborn
tags question: http://stackoverflow.com/q/47814048
tags question: http://stackoverflow.com/q/47730500
tags question: http://stackoverflow.com/q/47699689
tags question: http://stackoverflow.com/q/47757375
tags question: http://stackoverflow.com/q/47796389
tags question: http://stackoverflow.com/q/47717740
tag name: seaborn
tags question: http://stackoverflow.com/q/47848096
tags question: http://stackoverflow.com/q/47796264
tags question: http://stackoverflow.com/q/47784215
type: Tag
tags question: http://stackoverflow.com/q/47816175
tags question: http://stackoverflow.com/q/47760194

http://stackoverflow.com/q/47714070
tagged with: security
score: 5
has title: Safe way to store mysql server credentials in flask?
answer count: 3
has body: I was wondering about the safety of some thing in my app.py flask app. First the database, I'm using mysql and currently I am connecting to it in the following way: # Config MySQL app.config['MYSQL_HOST'] = 'localhost' app.config['MYSQL_USER'] = 'root' app.config['MYSQL_PASSWORD'] = 'password' app.config['MYSQL_DB'] = 'databasename' app.config['MYSQL_CURSORCLASS'] = 'DictCursor' And to me this feels very weird, just putting in your password in plain text etc. I've been searching online but have not found any other way of doing this other than putting it in a seperate python file and just importing it. Which kinda feels like doing nothing at all.. Is there a better way to do this security wise? Then the secret key I use for password encoding. Which is also just stored in plain text in my code, is there also a way to make this more secure or make it less obvious? Thanks in advance!
has answer: http://stackoverflow.com/a/72617566
has comment: http://stackoverflow.com/comment/82388526
downvote count: 0
tagged with: mysql
has comment: http://stackoverflow.com/comment/87244805
tagged with: flask
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47714539
has answer: http://stackoverflow.com/a/67271152
type: UnansweredQuestion
upvote count: 5
tagged with: python
tagged with: secret-key

http://stackoverflow.com/q/47775220
downvote count: 4
possible better answer: http://stackoverflow.com/a/47791257
tagged with: python
accepted answer: http://stackoverflow.com/a/47775293
score: 27
tagged with: data-science
tagged with: plot
has body: I have dataframe total_year, which contains three columns (year, action, comedy). How can I plot two columns (action and comedy) on y-axis? My code plots only one: total_year[-15:].plot(x='year', y='action', figsize=(10,5), grid=True)
has answer: http://stackoverflow.com/a/47775293
type: AnsweredQuestion
answer count: 3
tagged with: pandas
upvote count: 31
tagged with: matplotlib
has answer: http://stackoverflow.com/a/47791257
has title: How to plot multiple pandas columns
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/65349789

http://stackoverflow.com/comment/82539476
type: Comment
type: QuestionComment
has text: @jezrael Okay i'm going to post my own answer to this. This worked for me.
score: 1
comment on: http://stackoverflow.com/q/47788448

http://stackoverflow.com/comment/82499752
has text: Welcome to [so]. It is common for questions to have a [mcve]. Your code example sadly does not meet these criteria as it's not complete (python code is missing), not minimal (code comments and other code) and does not provide with the actual response.
score: 0
comment on: http://stackoverflow.com/q/47765335
type: Comment
type: QuestionComment

http://stackoverflow.com/a/70095422
downvote count: 2
score: -2
type: Answer
answers question: http://stackoverflow.com/q/47833775
has comment: http://stackoverflow.com/comment/134056095
has body: Installation dateutil The dateutil module provides powerful extensions to the standard datetime module, available in Python. Install from PyPI using pip pip install python-dateutil Download from PyPI https://pypi.org/project/python-dateutil/
upvote count: 0

http://stackoverflow.com/comment/82357756
type: QuestionComment
has text: but bottom line, if you open a file for read-write, and try to write to it at a specific location, wouldn't you be overwriting the contents of the next character? I don't know Python, so...? But if it is that way, you need to open it for read, read the whole contents, replace the ";" like @pault suggests (minus the `\r`), and then write the contents back out to the file. Right?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47698647

http://stackoverflow.com/comment/82462757
type: Comment
type: QuestionComment
score: 0
has text: You might need to specify the delimiter as ','
comment on: http://stackoverflow.com/q/47751164

http://stackoverflow.com/a/47841954
has body: When you append board to board_list you're adding a reference to the original board. Perhaps a better option would be to add the previous state for the changed cell when you make a move: moves.append([x, y, board[x][y]]) And then when you undo you reapply that state: undo_move = moves[-1] board[undo_move[0]][undo_move[1]] = undo_move[2] del moves[-1] Or more pythonically: x, y, board[x][y] = moves.pop() Alternatively, you could make a copy of the entire board and store that in the list instead.
type: AcceptedAnswer
upvote count: 5
type: Answer
has comment: http://stackoverflow.com/comment/82648220
has comment: http://stackoverflow.com/comment/82648478
has comment: http://stackoverflow.com/comment/82648104
has comment: http://stackoverflow.com/comment/82648621
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47841934
has comment: http://stackoverflow.com/comment/82648467
score: 5
answers question: http://stackoverflow.com/q/47841934

http://stackoverflow.com/a/47841732
has body: You must make sure to iterate over all movies (for i in movies) until you can decide if the movie was found or not. So: iterate over all movies, print the movie and return from the function if you find it. If you haven't found the movie after iterating over all them then ask the user to try again. from tabulate import tabulate def search_movie_title(): movies = open('movies.txt','r').readlines() title = input("Input movie title: ").lower() for i in movies: movie = i.strip("\n").split("|") if title == movie[0].lower(): table = [['Name:',movie[0]],['Genre:',movie[1]],['Running:',movie[2]],['Director:',movie[3]],['Starring:', movie[4]],['Country:', movie[5]], ['Realised:', movie[6]]] print (tabulate(table)) return print("Nothing found! Try again.") search_movie_title() I would suggest just printing "Nothing found" and then return instead of calling the function recursively though.
answers question: http://stackoverflow.com/q/47841705
type: Answer
score: 0

http://stackoverflow.com/q/47775772
score: 4
has comment: http://stackoverflow.com/comment/82514091
answer count: 3
has answer: http://stackoverflow.com/a/47776747
has answer: http://stackoverflow.com/a/47777065
tagged with: python
has answer: http://stackoverflow.com/a/47777697
favorite count: 0
has title: why accessing an objects attribute "characters_written" throws exception, while dir() can lists it?
type: Question
upvote count: 4
has body: I was trying to list all attributes/values of an object in interactive shell of python3.6: e = FileExistsError() dir(e) gives an attribute list like ['\__cause__',...,'characters_written',...] but e.characters_written throws an error: AttributeError: characters_written when FileExistsError.characters_written executes normally. Why is characters_written attribute special in this case?
tagged with: python-3.x
type: UnansweredQuestion
downvote count: 0

http://stackoverflow.com/comment/82449419
type: QuestionComment
has text: @Simon If `from .. import lib_common` is what you mean, that doesn't help either.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47744580

http://stackoverflow.com/comment/82581676
type: QuestionComment
has text: and where answer for that question is stored?
score: 0
comment on: http://stackoverflow.com/q/47810110
type: Comment

http://stackoverflow.com/q/47751919
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47752115
has answer: http://stackoverflow.com/a/47752115
tagged with: os.system
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/82464411
type: Question
has body: I want my raspberry pi to speak this print command print label + " is " + spos + " and the distance is " + str(distance) + "cm" which has three variables in it. And this is the command i use in shell that i need to use in python $espeak -s110 "label + " is " + spos + " and the distance is " + str(distance) + "cm"" --stdout | aplay -D sysdefault:CARD=2 I've tried it with os.system because i'm not familiar with subprocess commands. os.system('espeak -s110 "'label' + is + 'spos' + and the distance is + 'str(distance)' + cm" --stdout | aplay -D sysdefault:CARD=2') I'm getting an invalid sytax error. I've tried every version of it and couldn't make it work.
tagged with: raspberry-pi
tagged with: subprocess
tagged with: espeak
answer count: 1
downvote count: 0
has title: Need to use a variable in os.system with espeak and aplay commands in python
upvote count: 1
score: 1

http://stackoverflow.com/comment/82613571
comment on: http://stackoverflow.com/a/47824865
type: Comment
has text: retval shows true. The camera works with anything else, like skype and whatnot.
score: 0
type: AnswerComment

http://stackoverflow.com/a/47825302
has comment: http://stackoverflow.com/comment/82649332
downvote count: 0
has comment: http://stackoverflow.com/comment/82648523
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/47825221
score: 1
accepted answer of: http://stackoverflow.com/q/47825221
has body: You need to fix your function, because it looks like it needs an elif ...: instead of an else: And you need to actually invoke the function, too, once you've gotten your input. So... def is_hot (N): if N/2&gt;1 and N-1&gt;1: # N &gt; 2 print (N, "is hot") elif N/2&lt;1 and N-1&lt;1: # N &lt; 2 print (N, "is cold") else: # N is 2 print (N, "is just right!") n = float(input(("Enter Number: "))) is_hot(n) Note that I did not use N in both places, when calling the func and when defining the func. It would work, but it's not always the best thing as far as code readability. Also, it's best practice to list your functions at the top of your code. Also, you can, and probably should, use a different variable names in the function than in the calling code. This is not for functionality, but for readability. If someone is not paying attention, they may see the same name and think it's a global variable. Again, you do not have to use a different variable name, but it's good practice to use different variable names. If nothing else, the variable names in the function will often be more generic, and the variable names in the calling code more specific. Here's an example: def merge_lists(list1, list2): # generic.. return zip(list1, list2) my_merged_inventory_list = merge_lists(list_of_stock_items, list_of_item_prices)
has comment: http://stackoverflow.com/comment/82613350
type: AcceptedAnswer

python-twitter
tag name: python-twitter
tags question: http://stackoverflow.com/q/47725645
type: Tag

http://stackoverflow.com/comment/82523568
has text: Oh yes furas, that is exactly my problem, now i looked for some solution, to set a default column/row size, but i didn't find anything useful. :( "minsize" option has no effect if the row/column is completely empty. So can you give any advice please? :)
score: 0
comment on: http://stackoverflow.com/q/47759657
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82447114
type: Comment
has text: You could do a first pass where you just separate words and put them into a list, e.g. interpret "two spaces", and then handle this list of individual words in a second pass (this time, you only need to worry about "one space"). Put the translated words back into a list one by one, and print that list (separated by space). You seem to already know all the required tools in Python, good luck.
type: QuestionComment
comment on: http://stackoverflow.com/q/47743442
score: 2

http://stackoverflow.com/comment/82601037
type: QuestionComment
has text: works for me with python3.5 in windows 7
comment on: http://stackoverflow.com/q/47738922
score: 0
type: Comment

http://stackoverflow.com/comment/82407499
type: QuestionComment
comment on: http://stackoverflow.com/q/47722693
has text: I don't think uniqueness is a requirement for the index to pivot on because I think it'll just concatenate different records matching the same index into a single line for that index value. So all rows with the same date join into one row. You might end up with a multi-index but I really doubt it. I think the problem is something else.
score: 0
type: Comment

http://stackoverflow.com/q/47742374
score: 0
possible better answer: http://stackoverflow.com/a/47742508
tagged with: python
has answer: http://stackoverflow.com/a/47742508
tagged with: import
type: Question
has title: Import contents of Text file into a List in Python
has answer: http://stackoverflow.com/a/47742400
has answer: http://stackoverflow.com/a/47742511
has body: This is Regarding the projecteuler problem 42. I want to import the content of this text file (https://projecteuler.net/project/resources/p042_words.txt) in to a list in python. I want the list to be like list = ["A","ABILITY",........] Any help is greatly appreciated.
answer count: 3
has comment: http://stackoverflow.com/comment/82444889
accepted answer: http://stackoverflow.com/a/47742400
tagged with: text
type: AnsweredQuestion

http://stackoverflow.com/a/51465838
score: 4
upvote count: 4
has body: Note that the solution from @Maxim will create new operations in the graph each time it runs. If you run the function very frequently this will cause your code to get slower and slower. Two solutions to work around this problem: Create the assign operations at the same time as the rest of the graph and reuse them: assign_ops = [] for var_name in tf.trainable_variables(): assign_placeholder = tf.placeholder(var.dtype, shape=value.shape) assign_op = var.assign(assign_placeholder) assign_ops.append(assign_op) Use the load function on the variables, I prefer this one as it removes the need for the code above: self.params = tf.trainable_variables() def get_weights(self): values = tf.get_default_session().run(self.params) return values def set_weights(self, weights): for i, value in enumerate(weights): value = np.asarray(value) self.params[i].load(value, self.sess) (I can't comment so I put this as an answer instead)
answers question: http://stackoverflow.com/q/47716395
downvote count: 0
type: Answer

http://stackoverflow.com/comment/82462719
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47751179
has text: Also, I only see AAA in column2, and None in column3. Can you please clarify your question?
score: 0

http://stackoverflow.com/comment/83097761
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47781496
has text: You might also be interested in https://gist.github.com/pelson/9785576 which demonstrates the masking using shapely.vectorized. It should be quite performant. If this turns out to be your solution, please do consider adding another answer to the question.
score: 1

http://stackoverflow.com/q/47855834
has answer: http://stackoverflow.com/a/47855982
has title: pygame - make a stickman jump using arrow keys but goes no higher than 10 units
tagged with: python
tagged with: pygame
has body: the stickman I have is able to move and all, using the arrow keys, and but, when the up arrow key is pressed, I want him to only be able to go about 10 units every time the key is pressed, no matter how long it is pressed for. In other words I want him to jump, and have a limit to how high he can jump. I've tried a couple things but nothing has worked. import pygame def drawMan(screen,x,y): #head pygame.draw.ellipse(screen,BLACK,[0+x,0+y,10,10], 0) #body pygame.draw.line(screen,BLACK,[4+x,17+y],[4+x,7+y], 2) #legs pygame.draw.line(screen,BLACK,[4+x,17+y],[9+x,27+y], 2) pygame.draw.line(screen,BLACK,[4+x,17+y],[-1+x,27+y], 2) #arms pygame.draw.line(screen,BLACK,[4+x,7+y],[8+x,17+y], 2) pygame.draw.line(screen,BLACK,[4+x,7+y],[0+x,17+y], 2) BLACK = (0, 0, 0) WHITE = (255, 255, 255) BORDER = (100,100,100) pygame.init() size = (800, 500) screen = pygame.display.set_mode(size) pygame.display.set_caption("Jump") done = False clock = pygame.time.Clock() pygame.mouse.set_visible(1) xCoord = 11 yCoord = 463 xSpeed = 0 ySpeed = 0 while not done: for event in pygame.event.get(): if event.type == pygame.QUIT: done = True if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: xSpeed = -3 if event.key == pygame.K_RIGHT: xSpeed = 3 if event.key == pygame.K_UP: ySpeed = -3 if event.type == pygame.KEYUP: if event.key == pygame.K_LEFT: xSpeed = 0 if event.key == pygame.K_RIGHT: xSpeed = 0 if event.key == pygame.K_UP: ySpeed = 3 if xCoord &gt;= 780: xSpeed = 0 xCoord -= 1 elif xCoord &lt;= 13: xSpeed = 0 xCoord += 1 elif yCoord &gt; 465: ySpeed = 0 yCoord -= 1 elif yCoord &lt;= 13: ySpeed = 0 yCoord += 1 else: xCoord += xSpeed yCoord += ySpeed screen.fill(WHITE) pygame.draw.line(screen, BORDER, [0,0],[800,0], 20) pygame.draw.line(screen, BORDER, [0,0],[0,500], 20) pygame.draw.line(screen, BORDER, [0,500],[800,500], 20) pygame.draw.line(screen, BORDER, [800,500],[800,0], 20) drawMan(screen,xCoord,yCoord) pygame.display.flip() clock.tick(60) pygame.quit()
answer count: 2
score: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/71068833
type: Question

http://stackoverflow.com/comment/82664100
comment on: http://stackoverflow.com/q/47849791
type: QuestionComment
score: 0
has text: "I am unsure whether this is a logical or syntax error of some sort": you should know: you're the first one to try to run this code.
type: Comment

http://stackoverflow.com/comment/82441756
score: 0
has text: @epalm One possibility, but can't test right now so comment rather than answer: Maybe DRF is not using the default 0..maxint that forms/admin are using but EmailField doesn't need any parameters defined so it works. If that's true, try adding parameters (good idea anyway) in the Model - e.g., min_value=0, max_value=120 and see if that carries through to DRF.
type: Comment
comment on: http://stackoverflow.com/q/47740302
type: QuestionComment

http://stackoverflow.com/a/47813144
has comment: http://stackoverflow.com/comment/82587923
has comment: http://stackoverflow.com/comment/82588374
type: Answer
has comment: http://stackoverflow.com/comment/82588016
has body: Regex-based with str.replace This regex pattern with str.replace should do nicely. s.str.replace(r'\.(?=.*?\.)', '') 0 1234.5 1 123.5 2 2345.6 3 678.9 dtype: object The idea is that, as long as there are more characters to replace, keep replacing. Here's a breakdown of the regular expression used. \. # '.' (?= # positive lookahead .*? # match anything \. # look for '.' ) Fun with np.vectorize If you want to do this using count, it isn't impossible, but it is a challenge. You can make this easier with np.vectorize. First, define a function, def foo(r, c): return r.replace('.', '', c) Vectorize it, v = np.vectorize(foo) Now, call the function v, passing s and the counts to replace. pd.Series(v(s, s.str.count(r'\.') - 1)) 0 1234.5 1 123.5 2 2345.6 3 678.9 dtype: object Keep in mind that this is basically a glorified loop. Loopy/List Comprehension The python equivalent of vectorize would be, r = [] for x, y in zip(s, s.str.count(r'\.') - 1): r.append(x.replace('.', '', y)) pd.Series(r) 0 1234.5 1 123.5 2 2345.6 3 678.9 dtype: object Or, using a list comprehension: pd.Series([x.replace('.', '', y) for x, y in zip(s, s.str.count(r'\.') - 1)]) 0 1234.5 1 123.5 2 2345.6 3 678.9 dtype: object
accepted answer of: http://stackoverflow.com/q/47813099
score: 9
has comment: http://stackoverflow.com/comment/82587886
downvote count: 0
answers question: http://stackoverflow.com/q/47813099
has comment: http://stackoverflow.com/comment/82589133
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82587832
has comment: http://stackoverflow.com/comment/82588277
upvote count: 9

http://stackoverflow.com/comment/82392697
score: 0
type: Comment
has text: It's unclear what your actual question is.
type: QuestionComment
comment on: http://stackoverflow.com/q/47716239

http://stackoverflow.com/q/47715781
has body: I am trying to get started with Sphinx for documenting Python, and I seem to be missing some very basic step in getting started. I'm following the http://www.sphinx-doc.org/en/stable/tutorial.html and have installed and configured (with defaults, wherever possible) the tool. The problem is that I am unable to link another RST file to index. My index file is as below: Welcome to FirstProject's documentation! ==================================== .. toctree:: :maxdepth: 2 intro Note that intro.rst is in the same directory with the following content: Introduction to the FirstProject project!! ====================================== .. toctree:: :maxdepth: 2 The output type is html. When I try make html I get a warning saying: /home/ngk/Code/Projects/Twitter/botscore/doc/intro.rst: WARNING: document isn't included in any toctree I expected that a hyperlink with 'the intro' string would be created in index.html with the link pointing to intro.html Instead, there is just a string 'intro' in the expected location in the index.html file. Note that the intro.html file is created, but not hyperlinked from index.html Can someone suggest what seemingly small step I have missed?
tagged with: python
upvote count: 7
accepted answer: http://stackoverflow.com/a/47716000
tagged with: restructuredtext
type: AnsweredQuestion
tagged with: toctree
score: 7
has comment: http://stackoverflow.com/comment/82415389
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/47716000
favorite count: 0
type: Question
has title: How to add a toctree entry?
tagged with: python-sphinx

http://stackoverflow.com/a/47839573
upvote count: 2
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47839456
downvote count: 0
score: 2
has body: How can I install catalyst? It's in their documentation. pip install enigma-catalyst matplotlib And you need matplotlib because it depends on Numpy for linear algebra routines The easiest way to get Numpy on your machine would probably be using Anaconda, not pure Python, as also mentioned on that page The preferred method to install Catalyst is via the conda package manager
type: Answer
accepted answer of: http://stackoverflow.com/q/47839456

http://stackoverflow.com/a/47702499
answers question: http://stackoverflow.com/q/47702285
has body: You can do something like this: import random def mutate(virus): mutations = ['A', 'T', 'C', 'G'] r = random.randint(0, len(virus)-1) virus = list(virus) virus[r] = random.choice(mutations) return ''.join(virus)
type: Answer
score: 0

http://stackoverflow.com/comment/82408890
score: 0
type: AnswerComment
has text: @Mathi: I don't understand your question. I thought it is about selecting rows not columns? I assumed you are talking about indexes; what do you man by floats in this context or do I misunderstand?
type: Comment
comment on: http://stackoverflow.com/a/47723651

http://stackoverflow.com/a/52413427
has body: If you go deeper to library you see, that request to google translate site returns something like 503 error or other. For me it was 503 error and text: This page appears when Google automatically detects requests coming from your computer network which appear to be in violation of the Terms of Service. The block will expire shortly after those requests stop. This traffic may have been sent by malicious software, a browser plug-in, or ascript that sends automated requests. If you share your network connection, ask your administrator for help — a different computer using the same IP address may be responsible. Learn more Sometimes you may see this page if you are using advanced terms that robots are known to use, or sending requests very quickly. This means, and README of project says it: If you get HTTP 5xx error or errors like #6, it’s probably because Google has banned your client IP address. Try to use proxy.
score: 0
answers question: http://stackoverflow.com/q/47725342
type: Answer

http://stackoverflow.com/a/47712945
type: Answer
answers question: http://stackoverflow.com/q/47712813
has body: Simple use str.split() method and this function. def split_names(input:str): splitted = input.split(".") return splitted[0], splitted[1] A, B = split_names("name.surname.csv")
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/q/47718488
score: 0
has body: I want to populate a fresh database with inital data stored in csv files. I tried to use odo to populate an existing table with the content of a csv file. My files do not have a primary key and the number of columns do not match as the database has additional columns defined. How can I use odo to achieve this? from sqlalchemy import Column, String, Integer, create_engine from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class Test(Base): __tablename__ = 'testtable' uid = Column(Integer, primary_key=True) colA = Column(String(50)) colB = Column(String(50)) comment = Column(String(100)) engine = create_engine('sqlite:///testdb.db') Base.metadata.create_all(engine) My csvfile looks like this: col A;col B aa;bb ax;bx This does not work: from odo import odo odo('csvfile.csv', 'sqlite:///testdb.db::testtable', has_header=True) Error message: expected 4 columns but found 3 - filling the rest with NULL INSERT failed: datatype mismatch
tagged with: sqlite
answer count: 1
has comment: http://stackoverflow.com/comment/82461663
tagged with: sqlalchemy
type: Question
has answer: http://stackoverflow.com/a/47782165
has title: How can I import a csv file without primary key to sqlite3
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
tagged with: odo
has comment: http://stackoverflow.com/comment/82434763
has comment: http://stackoverflow.com/comment/82419606

http://stackoverflow.com/comment/82464808
score: 0
has text: Welcome to SO! Could you try to turn your code into a [minimal, runnable example](https://stackoverflow.com/help/mcve)? That would make it easier for us to figure out how the code works, where the problem lies and to give you tips on how to fix them.
type: QuestionComment
comment on: http://stackoverflow.com/q/47751594
type: Comment

http://stackoverflow.com/q/47805778
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47805832
accepted answer: http://stackoverflow.com/a/47805832
answer count: 1
has title: Get an image from string Python
downvote count: 1
favorite count: 0
type: Question
upvote count: 0
tagged with: base64
tagged with: python
score: -1
tagged with: http://stackoverflow.com/tag/png
has body: I use a google API and now I want to get viewable png image from string, gained from API result. screenshot": { "data": "iVBORw0KGgoAAAANSU...VERY_LONG_STRING", "mimeType": "image/png" } I have seen that I should use base64 lib, but It needs byte object, instead of string. Finally I want to view that image manually, so I need to store it to disk. How should I convert and save it?

http://stackoverflow.com/q/47703921
linked to: http://stackoverflow.com/q/613183
has comment: http://stackoverflow.com/comment/82368086
has comment: http://stackoverflow.com/comment/82368460
has comment: http://stackoverflow.com/comment/82368565
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/82367957
type: Question
duplicate of: http://stackoverflow.com/q/613183
has answer: http://stackoverflow.com/a/47703938
type: UnansweredQuestion
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/82367979
has comment: http://stackoverflow.com/comment/82368056
has body: So I have a dictionary, with keys and values, and the values are letters. I want to sort the dictionary so that it prints alphabetically according to the values, but I just can't figure out how to go about it. For example, I have this dictionary: dict = {5 : 'B', 7 : 'A', 9 : 'C'} How do I get this to be sorted so that it prints out as follows?: {7 : 'A', 5 : 'B', 9 : 'C'}
has comment: http://stackoverflow.com/comment/82368422
tagged with: sorting
has comment: http://stackoverflow.com/comment/82368030
has comment: http://stackoverflow.com/comment/82368301
has title: how to sort dictionary by value alphabeticallly?
has comment: http://stackoverflow.com/comment/82367984

http://stackoverflow.com/comment/82377972
has text: Duplicate of https://stackoverflow.com/questions/3419147/appending-values-to-dictionary-in-python
type: QuestionComment
comment on: http://stackoverflow.com/q/47709058
type: Comment
score: 0

http://stackoverflow.com/q/47791469
tagged with: pandas
linked to: http://stackoverflow.com/q/22211737
has comment: http://stackoverflow.com/comment/82544028
tagged with: multi-index
has comment: http://stackoverflow.com/comment/82543996
duplicate of: http://stackoverflow.com/q/22211737
has comment: http://stackoverflow.com/comment/82543943
score: 0
has body: I have data stored in a SQL database. When I call this data, it gets back to me as a DataFrame (I am using pandas). I then set_index to organized it as a MultiIndex level DataFrame. data.set_index(['colname1', 'colname2', 'colname3'],inplace=True) However, my Data isn't shaped in a fully organized way. Meaning I would like this data to be stored this way: How I would like it to be: And currently it's returned this way, in a non organized way:
answer count: 0
has comment: http://stackoverflow.com/comment/82544408
tagged with: python
type: UnansweredQuestion
tagged with: structure
type: Question
has title: Organizing a MultiIndex DataFrame after set_index

http://stackoverflow.com/comment/82366977
type: QuestionComment
has text: Or in other words, *why* is the second input `1 4` if you want it to be a second integer.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47703384

http://stackoverflow.com/q/47732816
type: AnsweredQuestion
score: 0
has title: none returned when trying to get tag value
answer count: 1
has answer: http://stackoverflow.com/a/47733374
has comment: http://stackoverflow.com/comment/82426208
type: Question
tagged with: beautifulsoup
has comment: http://stackoverflow.com/comment/82426147
tagged with: python
accepted answer: http://stackoverflow.com/a/47733374
has body: In this html snippet from https://letterboxd.com/shesnicky/list/top-50-favourite-films/, I'm trying to go through all the different li tags and get the info from 'data-target-link' so I can then use that to create a new link that takes me to the page for that film, however every time I try and get the data it simply returns None or an error along those lines. 1 I'm going to be using the links to grab imgs for a twitter bot, so I tried doing this within my code: class BotStreamer(tweepy.StreamListener): print "Bot Streamer" #on_data method of Tweepy’s StreamListener #passes data from statuses to the on_status method def on_status(self, status): print "on status" link = 'https://letterboxd.com/shesnicky/list/top-50-favourite-films/' page = requests.get(link) soup = BS(page.content, 'html.parser') movies_ul = soup.find('ul', {'class':'poster-list -p125 -grid film-list'}) movies = [] for mov in movies_ul.find('data-film-slug'): movies.append(mov) rand = randint(0,51) newLink = "https://letterboxd.com%s" % (str(movies[rand])) newPage = requests.get(newLink) code = BS(newPage.content, 'html.parser') code_div = code.find\ ('div', {'class':'react-component film-poster film-poster-51910 poster'}) image = code_div.find('img') url = image.get('src') username = status.user.screen_name status_id = status.id tweet_reply(url, username, status_id) However, I kept getting errors about list being out of range, or not being able to iterate over NoneType. So I made a test prgrm just to see if I could somehow get the data: import requests from bs4 import BeautifulSoup as BS link = 'https://letterboxd.com/shesnicky/list/top-50-favourite-films/' page = requests.get(link) soup = BS(page.content, 'html.parser') movies_ul = soup.find('ul', {'class':'poster-list -p125 -grid film-list'}) more = movies_ul.find('li', {'class':'poster-container numbered-list-item'}) k = more.find('data-target-link') print k And again, all I get is None. Any help greatly appreciated.

http://stackoverflow.com/comment/82591311
score: 0
comment on: http://stackoverflow.com/q/47812689
type: QuestionComment
has text: What is pdb? Python debugger?
type: Comment

http://stackoverflow.com/q/47716897
has comment: http://stackoverflow.com/comment/82394661
type: Question
has comment: http://stackoverflow.com/comment/82394936
tagged with: python
has comment: http://stackoverflow.com/comment/82394078
has comment: http://stackoverflow.com/comment/82394081
score: 1
tagged with: python-3.x
has title: index(max(my_list)) in list comprehension gives all instances of the max value instead of just the first occurrence
has comment: http://stackoverflow.com/comment/82394823
has comment: http://stackoverflow.com/comment/82397805
accepted answer: http://stackoverflow.com/a/47716964
has comment: http://stackoverflow.com/comment/82394161
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47716964
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/82394721
answer count: 1
favorite count: 0
has body: Consider the following code snippet --> li = [3,1,2,3] print([x+99 if li.index(x)!=li.index(max(li)) else x-(99*(len(li)-1)) for x in li ]) I was expecting the output to be : [-294, 100, 101, 102] but the actual output on running the program was : [-294, 100, 101, -294] Why do i get both instances of the maximum value in the list instead of just the first occurrence? How exactly are list comprehensions evaluated and how is that responsible for the output in my program ?

http://stackoverflow.com/comment/82425917
type: AnswerComment
score: 0
has text: That's understandable. When I started like this my reasoning was that tkinter would be tricky enough without having to learn about classes, too. As it turns out, all you really need to know about classes here is to use `self` and that `self.variable` can be used anywhere the class and persists outside the methods that create them. That last bit is incredibly useful for a tkinter GUI. P.S. Please consider an upvote or selecting my post as the answer. Thank you.
type: Comment
comment on: http://stackoverflow.com/a/47722770

http://stackoverflow.com/comment/82409209
type: Comment
has text: I have already one dataframe with only ONE column! The question was how to parse it and create 3 columns. You can assume that tab is the only separator. I do not want to read the file as you suggest because it does not exists.
comment on: http://stackoverflow.com/a/47724222
score: 0
type: AnswerComment

http://stackoverflow.com/comment/82609936
comment on: http://stackoverflow.com/a/47823457
has text: Oh, this database has a lot of ForeignKey's it may be best to leave it alone then, or to recreate it manually.
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47854450
score: -1
has answer: http://stackoverflow.com/a/47854487
tagged with: python-2.7
downvote count: 2
answer count: 1
upvote count: 1
has body: I have no prior experience in Python beside some messing around I did almost 10 years ago. I am trying to read data from the OMDB API and keep getting an error in Python 2.7.14. This is an example of what should be returned: &gt; {"Title":"The Matrix","Year":"1999","Rated":"R","Released":"31 Mar &gt; 1999","Runtime":"136 min","Genre":"Action, Sci-Fi","Director":"Lana &gt; Wachowski, Lilly Wachowski","Writer":"Lilly Wachowski, Lana &gt; Wachowski","Actors":"Keanu Reeves, Laurence Fishburne, Carrie-Anne &gt; Moss, Hugo Weaving","Plot":"A computer hacker learns from mysterious &gt; rebels about the true nature of his reality and his role in the war &gt; against its &gt; controllers.","Language":"English","Country":"USA","Awards":"Won 4 &gt; Oscars. Another 34 wins &amp; 45 &gt; nominations.","Poster":"https://images-na.ssl-images-amazon.com/images/M/MV5BNzQzOTk3OTAtNDQ0Zi00ZTVkLWI0MTEtMDllZjNkYzNjNTc4L2ltYWdlXkEyXkFqcGdeQXVyNjU0OTQ0OTY@._V1_SX300.jpg","Ratings":[{"Source":"Internet &gt; Movie Database","Value":"8.7/10"},{"Source":"Rotten &gt; Tomatoes","Value":"87%"},{"Source":"Metacritic","Value":"73/100"}],"Metascore":"73","imdbRating":"8.7","imdbVotes":"1,354,586","imdbID":"tt0133093","Type":"movie","DVD":"21 &gt; Sep 1999","BoxOffice":"N/A","Production":"Warner Bros. &gt; Pictures","Website":"http://www.whatisthematrix.com","Response":"True"} This is my Python code so far: import requests API_KEY = '******' Movie = 'The Matrix' results = requests.get("http://www.omdbapi.com/", params={'apikey': API_KEY, 't': Movie}) I get a in results. After importing json after this stage I try to run json.dumps(results) which gives me the error: Traceback (most recent call last): File "&lt;pyshell#12&gt;", line 1, in &lt;module&gt; json.dumps(results) File "C:\Python27\lib\json\__init__.py", line 244, in dumps return _default_encoder.encode(obj) File "C:\Python27\lib\json\encoder.py", line 207, in encode chunks = self.iterencode(o, _one_shot=True) File "C:\Python27\lib\json\encod…
favorite count: 0
type: Question
has title: Error trying to dump JSON
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/82673073
tagged with: python

http://stackoverflow.com/comment/82568341
type: QuestionComment
comment on: http://stackoverflow.com/q/47803005
score: 0
has text: Type "quit" 1000 times and I promise it **will** quit.
type: Comment

http://stackoverflow.com/comment/82535993
type: Comment
comment on: http://stackoverflow.com/a/47785853
has text: Thanks for the response, but that actually is one of the things I tried. Sadly, I got the same error. I got the answer from the previous person though.
type: AnswerComment
score: 0

http://stackoverflow.com/q/47847807
tagged with: filter
has answer: http://stackoverflow.com/a/47847878
downvote count: 0
answer count: 3
has comment: http://stackoverflow.com/comment/82659806
has comment: http://stackoverflow.com/comment/82659866
tagged with: string
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82659860
type: UnansweredQuestion
tagged with: python
has body: I have this nested list of strings which is in it's final stage of cleaning. I want to replace the non letters in the nested list with spaces or create a new list without the non-letters. Here is my list: list = [['hello', 'mr.', 'smith', ',', 'how', 'are', 'you', 'doing', 'today', '?'], ['the', 'weather', 'is', 'great', ',', 'and', 'python', 'is', 'awesome', '.'], ['the', 'sky', 'is', 'pinkish-blue', '.'], ['you', 'should', "n't", 'eat', 'cardboard', '.']] And this is the pattern that I want to use in order to clean it all pattern = re.compile(r'\W+') newlist = list(filter(pattern.search, list)) print(newlist) the code doesn't work and this is the error that I get: Traceback (most recent call last): File "/Users/art/Desktop/TxtProcessing/regexp", line 28, in &lt;module&gt; newlist = [list(filter(pattern.search, list))] TypeError: expected string or bytes-like object I understand that list is not a string but a list of lists of strings, how do I fix it? Any help will be very much Appreciated!
tagged with: regex
has comment: http://stackoverflow.com/comment/82659847
score: 3
upvote count: 3
has title: TypeError: expected string or bytes-like object while filtering the nested list of strings with RegEx
has answer: http://stackoverflow.com/a/47847850
has answer: http://stackoverflow.com/a/47847849

http://stackoverflow.com/q/47790226
tagged with: python
has body: I have a dataframe like this import pandas as pd year = [2005, 2006, 2007] A = [4, 5, 7] B = [3, 3, 9] C = [1, 7, 6] df_old = pd.DataFrame({'year' : year, 'A' : A, 'B' : B, 'C' : C}) Out[25]: A B C year 0 4 3 1 2005 1 5 3 7 2006 2 7 9 6 2007 I want to transform this to a new dataframe where the column headers ´A´, ´B´ and ´C´ are in the rows. I have this hack, which sorta does the job df_new = pd.DataFrame({'year' : list(df_old['year']) + list(df_old['year'])\ + list(df_old['year']), 'col' : ['A']*len(df_old['A']) + ['B']*len(df_old['B'])\ + ['C']*len(df_old['C']), 'val' : list(df_old['A']) + list(df_old['B'])\ + list(df_old['C'])}) Out[27]: col val year 0 A 4 2005 1 A 5 2006 2 A 7 2007 3 B 3 2005 4 B 3 2006 5 B 9 2007 6 C 1 2005 7 C 7 2006 8 C 6 2007 Is there a better, more compressed way to do this? Needless to say, this becomes cumbersome when there are a lot of columns.
has title: Transform dataframe column headers to row entries in Python
downvote count: 0
upvote count: 1
answer count: 1
has answer: http://stackoverflow.com/a/47790247
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47790247
type: AnsweredQuestion
tagged with: pandas
score: 1
tagged with: dataframe

http://stackoverflow.com/comment/82505898
comment on: http://stackoverflow.com/q/47770575
score: 1
type: Comment
type: QuestionComment
has text: @VadimKotov thats arguing about semantics and not actually helpful ;) Then again 3 GB is not actually that big and normally not your bottleneck.

http://stackoverflow.com/comment/82593907
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47809130
has text: `wls:/offline> print (version) WebLogic Server 12.2.1.2.0 wls:/offline> wls:/offline> wls:/offline> print sys.version 2.2.1 wls:/offline>`
score: 2

http://stackoverflow.com/comment/82434882
score: 0
has text: I am not trying to play an audio file in a loop. It's just one long audio file, that I need to interrupt. This line `while self.alarm_status == True: winsound.PlaySound("alarm.wav", winsound.SND_FILENAME)` will work only when the audio file is being played in a loop. It can only check the condition after each full playback. It won't check the condition in between playing the audio file.
type: Comment
comment on: http://stackoverflow.com/a/47726291
type: AnswerComment

flask
tags question: http://stackoverflow.com/q/47786463
tags question: http://stackoverflow.com/q/47736059
tags question: http://stackoverflow.com/q/47836728
tags question: http://stackoverflow.com/q/47716539
tags question: http://stackoverflow.com/q/47706343
tags question: http://stackoverflow.com/q/47780712
tags question: http://stackoverflow.com/q/47775876
tags question: http://stackoverflow.com/q/47839127
tags question: http://stackoverflow.com/q/47745749
tags question: http://stackoverflow.com/q/47788484
tags question: http://stackoverflow.com/q/47761973
tags question: http://stackoverflow.com/q/47711689
tags question: http://stackoverflow.com/q/47757167
tags question: http://stackoverflow.com/q/47810843
tags question: http://stackoverflow.com/q/47832257
tags question: http://stackoverflow.com/q/47819976
tags question: http://stackoverflow.com/q/47740186
tags question: http://stackoverflow.com/q/47838575
tags question: http://stackoverflow.com/q/47826740
tags question: http://stackoverflow.com/q/47855364
tags question: http://stackoverflow.com/q/47714070
tags question: http://stackoverflow.com/q/47744815
tags question: http://stackoverflow.com/q/47832309
tags question: http://stackoverflow.com/q/47710463
tags question: http://stackoverflow.com/q/47826097
tags question: http://stackoverflow.com/q/47809298
tags question: http://stackoverflow.com/q/47845380
tags question: http://stackoverflow.com/q/47710139
tags question: http://stackoverflow.com/q/47732512
tags question: http://stackoverflow.com/q/47752716
tags question: http://stackoverflow.com/q/47828486
tags question: http://stackoverflow.com/q/47714613
tags question: http://stackoverflow.com/q/47736881
tags question: http://stackoverflow.com/q/47743154
tags question: http://stackoverflow.com/q/47716237
tags question: http://stackoverflow.com/q/47705344
tags question: http://stackoverflow.com/q/47732490
tags question: http://stackoverflow.com/q/47733364
tags question: http://stackoverflow.com/q/47849926
tags question: http://stackoverflow.com/q/47739116
tags question: http://stackoverflow.com/q/47819230
tags question: http://stackoverflow.com/q/47703227
tags question: http://stackoverflow.com/q/47762512
tags question: http://stackoverflow.com/q/47789624
tags question: http://stackoverflow.com/q/47778551
tags question: http://stackoverflow.com/q/47730535
tags question: http://stackoverflow.com/q/47854951
tags question: http://stackoverflow.com/q/47854616
tags question: http://stackoverflow.com/q/47761033
tags question: http://stackoverflow.com/q/47732461
tags question: http://stackoverflow.com/q/47793315
tags question: http://stackoverflow.com/q/47805088
tags question: http://stackoverflow.com/q/47825384
tags question: http://stackoverflow.com/q/47841108
tags question: http://stackoverflow.com/q/47769348
tags question: http://stackoverflow.com/q/47814014
tags question: http://stackoverflow.com/q/47828700
tag name: flask
tags question: http://stackoverflow.com/q/47735809
tags question: http://stackoverflow.com/q/47717132
tags question: http://stackoverflow.com/q/47749188
tags question: http://stackoverflow.com/q/47779169
tags question: http://stackoverflow.com/q/47841985
tags question: http://stackoverflow.com/q/47747586
tags question: http://stackoverflow.com/q/47778277
tags question: http://stackoverflow.com/q/47813825
tags question: http://stackoverflow.com/q/47736056
tags question: http://stackoverflow.com/q/47749965
tags question: http://stackoverflow.com/q/47818088
tags question: http://stackoverflow.com/q/47849798
tags question: http://stackoverflow.com/q/47716555
tags question: http://stackoverflow.com/q/47781698
type: Tag
tags question: http://stackoverflow.com/q/47784685
tags question: http://stackoverflow.com/q/47799171
tags question: http://stackoverflow.com/q/47834382
tags question: http://stackoverflow.com/q/47829903
tags question: http://stackoverflow.com/q/47804317
tags question: http://stackoverflow.com/q/47711880
tags question: http://stackoverflow.com/q/47727390

http://stackoverflow.com/a/47798311
downvote count: 0
answers question: http://stackoverflow.com/q/47798178
upvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/82563287
has body: It is clearly being deleted but somewhere you have a upsert creating an entry for gemini. See how the price, volume and timestamp change. I should say that the reason for the error is INT has a maximum signed value of 2147483647. Your attempt at trying to insert a higher value(2465337307) apparently gets truncated down to the max which in this case is true, you already have an entry for gemini, 2147483647. Try inserting INSERT INTO `trades` VALUES("gemini",2147483646,17317.010000,0.008923,1513178949); using your python program.
score: 2
accepted answer of: http://stackoverflow.com/q/47798178
type: AcceptedAnswer

http://stackoverflow.com/comment/82595887
comment on: http://stackoverflow.com/a/47816419
type: Comment
has text: And how would that be formatted if the `Key1` was missing?
score: 0
type: AnswerComment

http://stackoverflow.com/comment/82640914
type: Comment
type: AnswerComment
has text: Other than either passing `Popen(cmd, input="string")` or with `shell=True` like this answer suggests...? Why can't you use either of those?
score: 0
comment on: http://stackoverflow.com/a/47830618

http://stackoverflow.com/q/47847301
has comment: http://stackoverflow.com/comment/82661668
linked to: http://stackoverflow.com/q/5875177
tagged with: python
has comment: http://stackoverflow.com/comment/82662326
has comment: http://stackoverflow.com/comment/82659885
answer count: 0
score: 1
has comment: http://stackoverflow.com/comment/82658962
downvote count: 0
upvote count: 1
has title: How to safely exit a socket if the python process is forcibly quit?
has comment: http://stackoverflow.com/comment/82660484
favorite count: 0
type: Question
has body: I'm attempting to get a simple server up and running with sockets, where it will send out the same information to any connected client. I've successfully managed to handle threads and stopping them in the case of KeyboardInterrupt, but I can't figure out how to close the socket if the script is ended early (such as the python process closed or you force run the script again). A very basic example would be this: import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) socket_process.bind(('localhost', 60000)) socket_process.listen(5) conn, addr = socket_process.accept() If you run that (on Windows at least), and then hit F5 to run it again, you get error: [Errno 10048] Only one usage of each socket address (protocol/network address/port) is normally permitted.. It does eventually close after half a minute or something, but I'd like it to instantly close if the script that spawned it no longer exists. Even if a timeout is set, it doesn't cause the error to go away any time sooner. For the record, those types of exit aren't caught by atexit. I'm thinking something similar to the multiprocessing daemon option could work if it exists.
type: UnansweredQuestion
tagged with: sockets

http://stackoverflow.com/a/47723106
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47721998
has body: If you just need the base module. pip install opencv-python
answers question: http://stackoverflow.com/q/47721998
type: Answer
score: 0

http://stackoverflow.com/a/47778957
score: 2
has comment: http://stackoverflow.com/comment/94884979
accepted answer of: http://stackoverflow.com/q/47775771
upvote count: 2
has body: So, you're creating three AdamOptimizer instances. If you want to separate them, the best solution is to create each one in an own scope: with tf.variable_scope('fake-optimizer'): d_trainer_fake = tf.train.AdamOptimizer(0.0003).minimize(d_loss_fake, var_list=d_vars) with tf.variable_scope('real-optimizer'): d_trainer_real = tf.train.AdamOptimizer(0.0003).minimize(d_loss_real, var_list=d_vars) with tf.variable_scope('optimizer'): g_trainer = tf.train.AdamOptimizer(0.0001).minimize(g_loss, var_list=g_vars) If, for some reason, you wish to share their internal parameters, the first optimizer should be created with reuse=None, the next two with reuse=True. Or all three with reuse=tf.AUTO_REUSE (supported in tensorflow 1.4), which does the same.
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82528938
type: Answer
answers question: http://stackoverflow.com/q/47775771

http://stackoverflow.com/q/47828176
type: AnsweredQuestion
tagged with: python-2.7
answer count: 2
score: 1
upvote count: 3
downvote count: 2
possible better answer: http://stackoverflow.com/a/47828445
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82618975
has comment: http://stackoverflow.com/comment/82618997
accepted answer: http://stackoverflow.com/a/47831744
has answer: http://stackoverflow.com/a/47831744
tagged with: python
has body: I need to parse both var & group root elements. Code import xml.etree.ElementTree as ET tree_ownCloud = ET.parse('0020-syslog_rules.xml') root = tree_ownCloud.getroot() Error xml.etree.ElementTree.ParseError: junk after document element: line 17, column 0 Sample XML core_dumped|failure|error|attack| bad |illegal |denied|refused|unauthorized|fatal|failed|Segmentation Fault|Corrupted ^Couldn't open /etc/securetty File missing. Root access unrestricted. pci_dss_10.2.4,gpg13_4.1, $BAD_WORDS alert_by_email Unknown problem somewhere in the system. gpg13_4.3, I tried following couple of other questions on stackoverflow here, but none helped. I know the reason, due to which it is not getting parsed, people have usually tried hacks. IMO it's a very common usecase to have multiple root elements in XML, and something must be there in ET parsing library to get this done.
tagged with: parsing
tagged with: http://stackoverflow.com/tag/xml
has answer: http://stackoverflow.com/a/47828445
has title: how to parse xml with multiple root element

http://stackoverflow.com/comment/82482843
type: QuestionComment
comment on: http://stackoverflow.com/q/47760335
has text: wow, so many things are wrong here, don't know where to start :/ But in any case, you need another thread to check your client/server
score: 0
type: Comment

http://stackoverflow.com/comment/82610940
comment on: http://stackoverflow.com/a/47824154
score: 0
type: Comment
type: AnswerComment
has text: I'll try to run your code anyway. I currently don't have a raspberry Pi to try it, but I'll take a look at this as soon as I can.

http://stackoverflow.com/a/47832154
downvote count: 0
has body: You can use boolean indexing or query for filter first and then drop_duplicates: df = df[df['score'] &lt;= 0.4].drop_duplicates('group') df = df.query('score &lt;= 0.4').drop_duplicates('group') print (df) group obsnum score 0 a 1 0.374540 4 b 1 0.156019 10 c 3 0.020584
accepted answer of: http://stackoverflow.com/q/47832114
type: Answer
score: 3
answers question: http://stackoverflow.com/q/47832114
upvote count: 3
type: AcceptedAnswer

http://stackoverflow.com/q/47725231
upvote count: 1
answer count: 1
downvote count: 0
tagged with: django
favorite count: 0
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47736487
tagged with: http://stackoverflow.com/tag/csv
score: 1
tagged with: http://stackoverflow.com/tag/pdf
tagged with: python
has title: Export a File (CSV, PDF) From Django Admin Form Inputs
has body: All within the Django admin, I'd like to enter form fields related to generating a report. Fields you'd expect in a report: report name, report type, start and end dates, report fields, etc. How would one take these inputs, grab the inputs from the request, pass these inputs to an API (in the background), then process it (in queue-like fashion), finally create a CSV or PDF to download? I'm fine with creating the admin model form and I think grabbing the inputs when the form is submitted in the admin, then I think I simply pass those inputs to my other API code to process... My questions are: When the third-party API is processing the request, is there a special way to handle this lag time? Where and how would I return the result - which is a CSV or PDF - in the admin interface? The /change/ page? Is there best-practice for this? I haven't been able to find an example of this when dealing with the admin. I'm not new to Python but am somewhat new to Django.
type: Question
accepted answer: http://stackoverflow.com/a/47736487
tagged with: django-admin

http://stackoverflow.com/comment/82797334
comment on: http://stackoverflow.com/a/47732357
type: Comment
type: AnswerComment
has text: Hey @Novel , sorry I didn't see your comment until now! Unfortunately I have to do it as my own project. If it's too picture perfect, it won't look like a student project. But it's coming along nicely and I'll gladly show you the code after it's been accepted :) All it really needs now is to be able to project satellite location back or forth in time. But that might not make it in for the final release. :)
score: 0

http://stackoverflow.com/a/62428043
has body: First check which python you've installed with $ which python /usr/bin/python Then check if it's executable python -V Python 2.7.5 If you run a py file with dos format on linux you also will get this issue. Method a: check dos fileformat with cat -v filepath to see if the line end with ^M. Method b: vim filepath -> :set ff to check it, for example "eni.py" [dos] 64L, 2151C Method c: file filepath to check if it has CRLF file_path: Python script, UTF-8 Unicode text executable, with CRLF line terminators Solution: you can set the filefort to unix with vim filepath then :set ff unix
upvote count: 9
type: Answer
score: 9
downvote count: 0
answers question: http://stackoverflow.com/q/47822600
has comment: http://stackoverflow.com/comment/115775746

http://stackoverflow.com/a/47829163
upvote count: 2
has body: It seems you need pivot with plot: df.pivot('timestamp','City','HUMI').plot() And alternative with unstack: df.set_index(['timestamp','City'])['HUMI'].unstack().plot() Detail: print (df.pivot('timestamp','City','HUMI')) City Beijing Chengdu timestamp 10100 43.0 81.20 10101 47.0 86.99 10102 43.0 86.99 10103 55.0 86.89 10104 51.0 86.79 10105 47.0 93.13
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47829141
has comment: http://stackoverflow.com/comment/82621317
type: Answer
accepted answer of: http://stackoverflow.com/q/47829141
score: 2

http://stackoverflow.com/q/47719580
linked to: http://stackoverflow.com/q/1883980
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82399848
upvote count: 2
has body: Input: blalasdl8ujd "key":"value", blblabla asdw "alo":"ebobo",blabla"www":"zzzz" or blalasdl8ujd key [any_chars_here] "value", blabla asdw "alo":"ebobo", bla"www":"zzzz" I'm tring to extract value having only key and knowing that value is covered with " Following regex key.*"(.*?)" returns the last match covered with " ("zzzz"). I need to fix it to return first. https://regex101.com/r/CDfhBT/1
has title: Regex find string after key inside qoutes
linked to: http://stackoverflow.com/q/22444
has comment: http://stackoverflow.com/comment/82399972
has answer: http://stackoverflow.com/a/47720272
tagged with: python
tagged with: regex
answer count: 4
has comment: http://stackoverflow.com/comment/82399790
duplicate of: http://stackoverflow.com/q/22444
has comment: http://stackoverflow.com/comment/82399766
possible better answer: http://stackoverflow.com/a/47719902
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47719843
has answer: http://stackoverflow.com/a/47719902
accepted answer: http://stackoverflow.com/a/47719664
score: 1
has answer: http://stackoverflow.com/a/47719664
downvote count: 1

http://stackoverflow.com/comment/82522690
comment on: http://stackoverflow.com/q/47780352
score: 0
type: QuestionComment
has text: Why do you copy 7 lines into a new file anyway if you just need to add minnuts to the 7nth line ? You could return every 7nth line of a new file that goes into your 'write_assignment_file' function and return it to your next function 'add_minutes' without reading it from another file.
type: Comment

http://stackoverflow.com/comment/82414044
score: 0
comment on: http://stackoverflow.com/q/47726795
has text: like stated in above comment, use `print(a)` or if you want each index individually then use a loop ( figure out that part yourself )
type: Comment
type: QuestionComment

http://stackoverflow.com/a/50334988
has body: I think this is a late replay, but it may be usefull for others this post Installing Latest Tensorflow and keras on Raspberry pi, has .whl of tensorflow which can be installed on Raspberry pi 2/3 and Raspberry pi one/zero with openblas hope it helps.
type: Answer
score: -1
upvote count: 0
downvote count: 1
answers question: http://stackoverflow.com/q/47813824

http://stackoverflow.com/comment/82507560
has text: I dont know why did I upvote this... Sorry, but it is wrong, it does the same that your first snippet does, calling `columnconfigure()` in whatever `grid()` returns which happens to be `None`.
type: AnswerComment
comment on: http://stackoverflow.com/a/47773031
type: Comment
score: 0

http://stackoverflow.com/comment/82564230
type: Comment
comment on: http://stackoverflow.com/a/47801226
has text: You are my hero @Bertrand Martel. I owe you big time. I wish i could hit the upvote button million times. It was just awesome. Could you please give a oneliner explanation as to why the code worked when the two fields were taken out. Thankssssssssssssss again.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/83064412
has text: @Allen You save your session using saver.save, then call on that saver to restore the model from the latest checkpoint. It should look something like: `sess = tf.Session() new_saver = tf.train.import_meta_graph('my-model.meta') new_saver.restore(sess, tf.train.latest_checkpoint('./'))` More details about saving and loading models can be found [here](https://stackoverflow.com/questions/33759623/tensorflow-how-to-save-restore-a-model)
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47936808

http://stackoverflow.com/comment/82677028
has text: For whatever reason, the same '(base = "https://fr.example.com/things?t={category}&p={index}")' that worked for other domains, didn't for FR and US. I just added www. to fr.example.com and it worked. Having '(base = "https://www.fr.example.com/things?t={category}&p={index}")' works. No idea why.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47855765
type: Comment

http://stackoverflow.com/q/47752233
tagged with: numpy
has title: Populating a NumPy array using dictionary containing indices
tagged with: arrays
downvote count: 0
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47752329
score: 3
has body: I am trying to populate a numpy array based on a dictionary of values. My dictionary looks like this: A = {(12, 15): 4, (532, 31): 7, (742, 1757): 1, ...} I am trying to populate the array so that (using my above example) 4 is at the index (12,15) and so on. The keys in A are called 'd','s' and the value is referred to as 'count'. A = {(d,s): count} At the moment my code to populate the array looks like this: N = len(seen) Am = np.zeros((N,N), 'i') for key, count in A.items(): Am[d,s] = count But this just leads to multiple arrays mostly full of zeros being created. Thank you
has answer: http://stackoverflow.com/a/47752329
has comment: http://stackoverflow.com/comment/82464797
upvote count: 3
answer count: 1
has comment: http://stackoverflow.com/comment/82464857
favorite count: 0
type: Question

http://stackoverflow.com/comment/82419889
has text: like the error says, `open(your_file, 'rb')` without and encoding argument. But notice that the readed data will be in binary mod.
score: 0
comment on: http://stackoverflow.com/q/47729452
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82381371
type: QuestionComment
has text: @Hiten I have defined it as static, and it worked. but my question is, is that good practice?
comment on: http://stackoverflow.com/q/47710144
score: 0
type: Comment

http://stackoverflow.com/q/47819696
tagged with: http://stackoverflow.com/tag/html
has body: I need to create an API end point like : @app.route('/user/&lt;username&gt;') def user(username) -- do something with the username in the index.html the code for input box is : &lt;input type="username" name="user_name" id="uname" placeholder="Input your name"&gt; Pls advise how I can pass this input as the 'username' variable?
tagged with: python
has comment: http://stackoverflow.com/comment/82602081
tagged with: flask
score: 0
has answer: http://stackoverflow.com/a/47820067
upvote count: 1
answer count: 1
downvote count: 1
linked to: http://stackoverflow.com/q/10434599
tagged with: jinja2
tagged with: http
favorite count: 0
has comment: http://stackoverflow.com/comment/82602016
type: Question
has title: How to get a data from a input box in html and pass it as a parameter in Rest API request in Flask Python
duplicate of: http://stackoverflow.com/q/36143283
duplicate of: http://stackoverflow.com/q/10434599
type: UnansweredQuestion

user-interface
tags question: http://stackoverflow.com/q/47802375
tags question: http://stackoverflow.com/q/47718444
tags question: http://stackoverflow.com/q/47735793
tags question: http://stackoverflow.com/q/47844381
tags question: http://stackoverflow.com/q/47855329
tags question: http://stackoverflow.com/q/47732254
tags question: http://stackoverflow.com/q/47799765
tags question: http://stackoverflow.com/q/47732734
type: Tag
tags question: http://stackoverflow.com/q/47744596
tags question: http://stackoverflow.com/q/47748918
tags question: http://stackoverflow.com/q/47855762
tags question: http://stackoverflow.com/q/47704736
tags question: http://stackoverflow.com/q/47837339
tags question: http://stackoverflow.com/q/47836001
tags question: http://stackoverflow.com/q/47743497
tags question: http://stackoverflow.com/q/47772138
tags question: http://stackoverflow.com/q/47851698
tags question: http://stackoverflow.com/q/47742295
tags question: http://stackoverflow.com/q/47824811
tag name: user-interface
tags question: http://stackoverflow.com/q/47841182
tags question: http://stackoverflow.com/q/47716776

http://stackoverflow.com/q/47758127
has body: i'm trying to preprocess data especially dealing with missing values. I have a list of words and two columns having text data. If word from list is in at least one of two text-columns, i fill missing with the word import pandas as pd a=['coffee', 'milk', 'sugar'] test=pd.DataFrame({'col':['missing', 'missing', 'missing'], 'text1': ['i drink tea', 'i drink coffee', 'i drink whiskey'], 'text2': ['i drink juice', 'i drink nothing', 'i drink milk'] }) So the dataframe looks like and a column "col" has "missing" as a result of applying fillna("missing") Out[19]: col text1 text2 0 missing i drink tea i drink juice 1 missing i drink coffee i drink nothing 2 missing i drink whiskey i drink milk I came up with such code applying loop for word in a: test.loc[(test["col"]=='missing') &amp; ((test["text1"].str.count(word)&gt;0) | (test['text2'].str.count(word)&gt;0)), "col"]=word With 100 000 rows and 2000 element in the list "a" it takes around 870 seconds to finish the job. Is there any solution to make it faster for a huge dataframe? Thanks in advance
has comment: http://stackoverflow.com/comment/82479806
has comment: http://stackoverflow.com/comment/82477637
downvote count: 1
has answer: http://stackoverflow.com/a/47769579
favorite count: 0
type: Question
has title: Filling missing value with word from list on condition
upvote count: 0
tagged with: missing-data
tagged with: python
score: -1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82478310
tagged with: pandas
accepted answer: http://stackoverflow.com/a/47769579
answer count: 1
has comment: http://stackoverflow.com/comment/82478723

http://stackoverflow.com/q/47838306
has title: Getting No loop matching the specified signature and casting error
has answer: http://stackoverflow.com/a/62937535
favorite count: 0
score: 39
has comment: http://stackoverflow.com/comment/82642706
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/50206328
answer count: 5
has body: I'm a beginner to python and machine learning . I get below error when i try to fit data into statsmodels.formula.api OLS.fit() Traceback (most recent call last): File "", line 47, in regressor_OLS = sm.OLS(y , X_opt).fit() File "E:\Anaconda\lib\site-packages\statsmodels\regression\linear_model.py", line 190, in fit self.pinv_wexog, singular_values = pinv_extended(self.wexog) File "E:\Anaconda\lib\site-packages\statsmodels\tools\tools.py", line 342, in pinv_extended u, s, vt = np.linalg.svd(X, 0) File "E:\Anaconda\lib\site-packages\numpy\linalg\linalg.py", line 1404, in svd u, s, vt = gufunc(a, signature=signature, extobj=extobj) TypeError: No loop matching the specified signature and casting was found for ufunc svd_n_s code #Importing Libraries import numpy as np # linear algebra import pandas as pd # data processing import matplotlib.pyplot as plt #Visualization #Importing the dataset dataset = pd.read_csv('Video_Games_Sales_as_at_22_Dec_2016.csv') #dataset.head(10) #Encoding categorical data using panda get_dummies function . Easier and straight forward than OneHotEncoder in sklearn #dataset = pd.get_dummies(data = dataset , columns=['Platform' , 'Genre' , 'Rating' ] , drop_first = True ) #drop_first use to fix dummy varible trap dataset=dataset.replace('tbd',np.nan) #Separating Independent &amp; Dependant Varibles #X = pd.concat([dataset.iloc[:,[11,13]], dataset.iloc[:,13: ]] , axis=1).values #Getting important variables X = dataset.iloc[:,[10,12]].values y = dataset.iloc[:,9].values #Dependant Varible (Global sales) #Taking care of missing data from sklearn.preprocessing import Imputer imputer = Imputer(missing_values = 'NaN' , strategy = 'mean' , axis = 0) imputer = imputer.fit(X[:,0:2]) X[:,0:2] = imputer.transform(X[:,0:2]) #Splitting the dataset into the Training set and Test set from sklearn.cross_validation import train_test_split X_train, X_test, y_train, y_test = train_test_split(X,y,test_size = 0.2 , random_state = 0) #Fitting Mutiple Linear Regression…
possible better answer: http://stackoverflow.com/a/62394102
tagged with: machine-learning
tagged with: scikit-learn
tagged with: python
has answer: http://stackoverflow.com/a/62394102
upvote count: 39
has answer: http://stackoverflow.com/a/62121252
has answer: http://stackoverflow.com/a/53808440
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/50206328
downvote count: 0

http://stackoverflow.com/q/47783326
has body: Here is a sample text: initiated to address the deviation to SOP-020583v11.0 Section SOP-016248v2.0 john doe, john doe SOP-020583 fake text, this is all fake. I have hundreds of passages just like this: initiated to address the deviation to acafjd Section abgcej john doe, john doe fake text, this is all fake I created the following function to find unique SOP numbers: def regex_list(regex,input_doc): result = re.compile(regex) regex_list = [result.findall(x) for x in input_doc] final_regex_list = [x for l in regex_list for x in l] final_regex_list = list(set(final_regex_list)) return final_regex_list I'd like to take it a step further and replace it as I'm finding the SOP numbers. So after it has run through this function it would like this: I want to replace it with some text representation of the number. I'm thinking of using the character that is associated with that number.
type: Question
accepted answer: http://stackoverflow.com/a/47783378
has title: Trying to find and replace general expressions within my text
upvote count: 0
tagged with: string
downvote count: 1
favorite count: 0
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82528091
has answer: http://stackoverflow.com/a/47783378
answer count: 1
tagged with: python
score: -1
tagged with: regex

http://stackoverflow.com/comment/82407767
score: 0
comment on: http://stackoverflow.com/a/47700674
type: Comment
type: AnswerComment
has text: @reno_libiii Please accept an answer since this question is answered and upvote the answers that gave you a good hint. Your comment introduces the need for another new question where you can paste the complete error message.

http://stackoverflow.com/comment/82675582
type: AnswerComment
has text: @user9109814: So what is in the session dictionary now? Print it out, compare between methods. Does not storing anything in `profile` help?
comment on: http://stackoverflow.com/a/47855507
type: Comment
score: 0

graphics
tag name: graphics
tags question: http://stackoverflow.com/q/47841025
tags question: http://stackoverflow.com/q/47803432
tags question: http://stackoverflow.com/q/47794365
type: Tag
tags question: http://stackoverflow.com/q/47741229

http://stackoverflow.com/a/47706037
has comment: http://stackoverflow.com/comment/82372822
has comment: http://stackoverflow.com/comment/82372454
type: Answer
has body: Sort your data before plotting: import matplotlib.pyplot as plt import numpy as np x = {5:289, 8:341, 1:1565, 4:655, 2:1337, 9:226, 7:399, 3:967, 6:405} new_x = sorted(x.items(), key=lambda x:x[0]) plt.hist([i[-1] for i in new_x], normed=True, bins=len(new_x), color='g', label = "Real distribution") plt.show()
score: 2
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/82372429
answers question: http://stackoverflow.com/q/47705972

http://stackoverflow.com/a/47775094
type: Answer
upvote count: 4
has body: tf.get_default_graph() always returns the current computation graph. E.g., it is the graph where x and loss nodes are defined even before the session has started. When you create a session with tf.Session() you can optionally specify a non-default graph to work with. In your example, it's not specified: If no graph argument is specified when constructing the session, the default graph will be launched in the session. It's rate to have multiple graphs in one script, but possible, for instance, when a graph is restored from the disk. Also note that after the session is done, the default graph is still there, so their lifetime is different.
answers question: http://stackoverflow.com/q/47774994
score: 4
downvote count: 0

http://stackoverflow.com/q/47766881
has body: I am developing chrome extension and from my javascript file, I am getting the url of the active tab. Now I want to pass this url to my python function in python code. How can I achieve this. I have tried few solutions posted here, but its no help. I need to send the "myurl" in the below code to my python function and get back results too. chrome.tabs.query({currentWindow: true, active: true}, function(tabs){ var myurl = tabs[0].url; console.log(myurl); });
type: Question
upvote count: 3
type: UnansweredQuestion
answer count: 1
linked to: http://stackoverflow.com/q/12056380
downvote count: 0
tagged with: javascript
favorite count: 0
score: 3
has answer: http://stackoverflow.com/a/47819316
tagged with: google-chrome-extension
has title: Google Chrome Extension:Call Python function from javascript
tagged with: python

http://stackoverflow.com/comment/82373468
type: Comment
type: QuestionComment
score: 0
has text: There may be an arbitrary number as a first element sometimes, but generally the order always goes the same: Type, section, days, time, building, room, available seats, capacity. It can be either in Python or JS, though I've been using Python for all the scraping.
comment on: http://stackoverflow.com/q/47706644

http://stackoverflow.com/q/47769818
linked to: http://stackoverflow.com/q/48049087
answer count: 1
has comment: http://stackoverflow.com/comment/82502837
downvote count: 0
has comment: http://stackoverflow.com/comment/82503000
linked to: http://stackoverflow.com/q/41674573
has comment: http://stackoverflow.com/comment/82502807
favorite count: 0
has comment: http://stackoverflow.com/comment/82535840
has comment: http://stackoverflow.com/comment/82537076
type: Question
upvote count: 4
has comment: http://stackoverflow.com/comment/82502696
has comment: http://stackoverflow.com/comment/82503997
tagged with: nltk
has comment: http://stackoverflow.com/comment/82503242
has answer: http://stackoverflow.com/a/47788736
tagged with: python
has body: I am trying to run through a function with my million lines in a datasets. I read the data from CSV in a dataframe I use drop list to drop data i don't need I pass it through a NLTK function in a for loop. code: def nlkt(val): val=repr(val) clean_txt = [word for word in val.split() if word.lower() not in stopwords.words('english')] nopunc = [char for char in str(clean_txt) if char not in string.punctuation] nonum = [char for char in nopunc if not char.isdigit()] words_string = ''.join(nonum) return words_string Now i am calling the above function using a for loop to run through by million records. Even though i am on a heavy weight server with 24 core cpu and 88 GB Ram i see the loop is taking too much time and not using the computational power that is there I am calling the above function like this data = pd.read_excel(scrPath + "UserData_Full.xlsx", encoding='utf-8') droplist = ['Submitter', 'Environment'] data.drop(droplist,axis=1,inplace=True) #Merging the columns company and detailed description data['Anylize_Text']= data['Company'].astype(str) + ' ' + data['Detailed_Description'].astype(str) finallist =[] for eachlist in data['Anylize_Text']: z = nlkt(eachlist) finallist.append(z) The above code works perfectly OK just too slow when we have few million record. It is just a sample record in excel but actual data will be in DB which will run in few hundred millions. Is there any way I can speed up the operation to pass the data through the function faster - use more computational power instead?
score: 4
tagged with: optimization
has comment: http://stackoverflow.com/comment/82531612
has comment: http://stackoverflow.com/comment/82502500
has comment: http://stackoverflow.com/comment/82537920
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82537888
has title: Why is my NLTK function slow when processing the DataFrame?
accepted answer: http://stackoverflow.com/a/47788736

http://stackoverflow.com/q/47702458
linked to: http://stackoverflow.com/q/34804756
answer count: 0
has title: SQLAlchemy: Query Parent with Efficient Child Search & Filter
score: 1
tagged with: orm
downvote count: 0
tagged with: mysql
upvote count: 1
tagged with: flask-sqlalchemy
tagged with: sqlalchemy
favorite count: 0
type: Question
has body: I've seen a few topics that are similar, but can't seem to get any of them to work efficiently. E.g.: SQLAlchemy: filter many-to-one relationship where the one object has a list containing a specific value I have a DB structure like so: class Base(db.Model): __abstract__ = True id = db.Column(db.Integer, primary_key=True) class Items(Base): title = db.Column(db.String(250)) class Criteria(Base): _name = db.Column('name', db.String(250), nullable=False, unique=False) class Response(Base): item_id = db.Column(db.Integer(), db.ForeignKey('items.id')) criterion_id = db.Column(db.Integer(), db.ForeignKey('criteria.id')) value = db.Column('value', db.Text(), nullable=True) item = db.relationship('Items', backref=db.backref('responses', lazy='joined', cascade='all, delete')) I'm trying to filter Items by a series of Response values like so: filters = [{'c_id':5, 'value': 'yes'}, {'c_id':6, 'value': 'no'}] items = Items.query for f in filters: items = items.filter(Item.responses.any(and_(Response.value == f['value'], Response.criterion_id == f['c_id']))) The query succeeds and I get my Items but the query is very slow on datasets as small as 100 Items with less than 2,000 combined Responses. I'm paginating the results so only 25 results are returned to the user max. My questions is there a more efficient way to return these results using join()? Python 3.6, Flask-sqlalchemy, MySQL
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/47823271
tagged with: dataframe
tagged with: python
tagged with: date
has body: I have a panda dataframe (stock prices) with an index in a date format. It is daily but only for working days. I basically try to compute some price performance YTD and from a year ago. To get the first date of the actual year in my dataframe I used the following method: today = str(datetime.date.today()) curr_year = int(today[:4]) curr_month = int(today[5:7]) first_date_year = (df[str(curr_year)].first_valid_index()) Now I try to get the closest date a year ago (exactly one year from the last_valid_index()). I could extract the month and the year but then it wouldn't be as precise. Any suggestion ? Thanks
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/47823636
tagged with: pandas
has title: Python Date Index: finding the closest date a year ago from today
answer count: 1
type: Question
accepted answer: http://stackoverflow.com/a/47823636
has comment: http://stackoverflow.com/comment/82609362
has comment: http://stackoverflow.com/comment/82610087
tagged with: datetime

http://stackoverflow.com/q/47842106
has comment: http://stackoverflow.com/comment/95035070
tagged with: pubnub
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/82657257
upvote count: 1
favorite count: 0
type: Question
has title: No handlers could be found for logger "pubnub" Error when asking for message
type: UnansweredQuestion
has body: I am using pubnub at the moment. I am sending some messages to my pubnub account (status:on and status:off) but when I want to run my python script on my raspberry pi. I get this error. No handlers could be found for logger "pubnub" I have the newest python version I have the newest pubnub version code: from pubnub.pnconfiguration import PNConfiguration from pubnub.pubnub import PubNub from pubnub.callbacks import SubscribeCallback from pubnub.enums import PNOperationType, PNStatusCategory from pubnub.pubnub import PubNub, SubscribeListener import time import RPi.GPIO as GPIO pnconf = PNConfiguration() pnconf.subscribe_key = "sub-c-e1af6266-e1d0-11e7-ad36-deb77ae39924" pnconf.publish_key = "pub-c-6dbd1d39-2915-4df0-b99a-5b358cf69209" pnconf.ssl = True pubnub = PubNub(pnconf) def my_publish_callback(envelope, status): # Check whether request successfully completed or not if not status.is_error(): pass # Message successfully published to specified channel. else: pass # Handle message publish error. Check 'category' property to find out possible issue # because of which request did fail. # Request can be resent using: [status retry]; class MySubscribeCallback(SubscribeCallback): def presence(self, pubnub, presence): pass # handle incoming presence data def status(self, pubnub, status): if status.category == PNStatusCategory.PNUnexpectedDisconnectCategory: pass # This event happens when radio / connectivity is lost elif status.category == PNStatusCategory.PNConnectedCategory: # Connect event. You can do stuff like publish, and know you'll get it. # Or just use the connected event to confirm you are subscribed for # UI / internal notifications, etc pubnub.publish().channel("led").message("hello!!").async(my_publish_callback) elif status.category == PNStatusCategory.PNReconnectedCategory: pass # Happens as part of our regular operation. This event happens when # radio / connectivity is lost, then regained. elif status.category == PNStatusCategory.PNDecryptionErrorCategory…
score: 1
has comment: http://stackoverflow.com/comment/82648581
tagged with: python
has comment: http://stackoverflow.com/comment/82648628
tagged with: raspberry-pi
has answer: http://stackoverflow.com/a/54101501

http://stackoverflow.com/comment/82367097
score: 0
has text: Also, if you use Python 2, use `raw_input()`, because plain `input()` interprets the string; try typing `exit()` and see what happens.
type: Comment
comment on: http://stackoverflow.com/q/47703384
type: QuestionComment

http://stackoverflow.com/comment/82463873
score: 0
type: AnswerComment
has text: Thanks, I already try that (as describe in point #2 above), it didn't solve my issue.
comment on: http://stackoverflow.com/a/47750608
type: Comment

http://stackoverflow.com/q/47779673
tagged with: python
has answer: http://stackoverflow.com/a/47779745
has comment: http://stackoverflow.com/comment/82520581
type: AnsweredQuestion
score: 3
upvote count: 3
tagged with: list
linked to: http://stackoverflow.com/q/231767
answer count: 2
downvote count: 0
accepted answer: http://stackoverflow.com/a/47779745
has title: Return multiple lists in Python
has answer: http://stackoverflow.com/a/47779974
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82520650
has body: I have this part of a code: def readTXT(): part_result = [] '''Reading all data from text file''' with open('dataset/sometext.txt', 'r') as txt: for lines in txt: part = lines.split() part_result = [int(i) for i in part] #sorted([(p[0], p[14]) for p in part_result], key=lambda x: x[1]) print(part_result) return part_result And I'm trying to get all lists as a return, but for now I'll get only the first one, what is quite obvious, because my return is inside the for loop. But still, shouldn't the loop go through every line and return the corresponding list? After doing research, all I found was return list1, list2 etc. But have should I manage it, if my lists will be generated from a text file line by line? It frustates me, not being able to return multiple lists at once.
possible better answer: http://stackoverflow.com/a/47779974

http://stackoverflow.com/q/47847156
has comment: http://stackoverflow.com/comment/82658608
type: AnsweredQuestion
downvote count: 0
tagged with: pandas
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/82658585
answer count: 1
has answer: http://stackoverflow.com/a/47847254
accepted answer: http://stackoverflow.com/a/47847254
favorite count: 0
has title: Finding matching columns in pandas including NaNs
type: Question
has body: I have a quite specific question regarding pandas. I have two DataFrames, both are binary : One containing multiple patterns to match lets say : 0 : 1,NaN,1,Nan,Nan 1 : Nan,1,1,Nan,Nan and one containing records of actual data 0 : 1,0,0,1,0 1 : 0,0,0,0,1 2 : 1,0,1,0,0 I want to perform an operation that tells me which lines of the record data match which rules. In the example rule 0 would match record 2. The missing values don't have to match anything, and therein lies my problem : if there wouldn't be any missing values I could simply use pd.merge(df1,df2,how="inner"), but an inner join doesn't match NaNs with anything. Is there a simple elegant solution without doing all the loops? Edit to add (for clarity): This: 0 : 1,1,NaN,NaN,NaN should match with both of these: 0 : 1,1,0,0,0 1 : 1,1,0,0,1
tagged with: python

http://stackoverflow.com/q/47726484
has comment: http://stackoverflow.com/comment/82414708
has comment: http://stackoverflow.com/comment/82413430
has comment: http://stackoverflow.com/comment/82424270
tagged with: tweets
type: UnansweredQuestion
has title: tweet_search() got an unexpected keyword argument 'tweet_mode'
tagged with: python
tagged with: tweepy
linked to: http://stackoverflow.com/q/47697667
score: 0
has body: I am using Tweepy library for tweets acquisition. But most of the tweets are not complete and end with a link where the whole tweet is present. I'm using tweet_mode="extended" but its giving an error message. Here is the code: tweets, max_id = tweet_search(api, search_phrase, max_tweets, max_id=max_id, since_id=since_id, tweet_mode="extended", geocode=USA)
answer count: 0
tagged with: twitter
tagged with: web-scraping
type: Question

http://stackoverflow.com/a/47732704
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/82435775
accepted answer of: http://stackoverflow.com/q/47732236
upvote count: 1
type: AcceptedAnswer
downvote count: 0
has body: That isn't a behavior of python but your output StreamHandler. The \b doesn't cancel the character before it, it instructs your output handler device (terminal/console) to move the cursor backward. What basically happens is, that you are placing the cursor one character to the left and continue streaming what is following. It visually look like you are putting a space as the next following character is aspace. In Both Unix based and Windows the output behavior is the same: Unix test / Mac Terminal: echo -e "Hello test\b" &gt;Hello test Windows test / CMD / Powershell : echo "Hello test`b" &gt;Hello test
answers question: http://stackoverflow.com/q/47732236

http://stackoverflow.com/a/47733686
accepted answer of: http://stackoverflow.com/q/47733554
type: Answer
has comment: http://stackoverflow.com/comment/82427923
has body: Here is a sample code: import os from collections import Counter cities = [i for i in os.listdir(".") if i.endswith(".txt")] d = Counter() for file in cities: with open(file) as f: # Adjust the code below to put the strings in a list data = f.read().split(",") d.update(Counter(data)) out = d.most_common(10) print(out)
has comment: http://stackoverflow.com/comment/82427903
answers question: http://stackoverflow.com/q/47733554
type: AcceptedAnswer
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/q/47807709
has body: I am new to Python. Installed Anaconda on my system. I installed PyCharm too. When I try to run a file from PyCharm I get this error message: C:\Python\Test\venv\Scripts\python.exe python 3.6 C:/Python/Test/while.py C:\Python\Test\venv\Scripts\python.exe: can't open file 'python': [Errno 2] No such file or directory
has title: PyCharm not finding Anaconda Python, giving "can't open file 'python': [Errno 2] No such file or directory?"
answer count: 6
downvote count: 1
has answer: http://stackoverflow.com/a/47810185
favorite count: 0
has comment: http://stackoverflow.com/comment/82576547
upvote count: 8
tagged with: anaconda
has answer: http://stackoverflow.com/a/56523032
has answer: http://stackoverflow.com/a/50320959
has comment: http://stackoverflow.com/comment/82576606
has answer: http://stackoverflow.com/a/56228150
score: 7
linked to: http://stackoverflow.com/q/55040884
has comment: http://stackoverflow.com/comment/82576853
tagged with: python
type: Question
has answer: http://stackoverflow.com/a/56841154
has answer: http://stackoverflow.com/a/62389507
tagged with: pycharm
tagged with: installation
type: UnansweredQuestion

http://stackoverflow.com/comment/104014620
score: 1
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/51945256
has text: @s.k By using `CSVLogger` the history file is saved in .csv format by default. If I understand your purpose with loading it that way is to continue training you model. Then, you set argument `append=True` as in `keras.callbacks.callbacks.CSVLogger(filename, separator=',', append=True)` while at the same time specifying the `initial_epoch` argument to the epoch you want to continue training on when fitting the model onto the data again. See the documentation for [callbacks](https://keras.io/callbacks/) as well as for [fitting sequential models](https://keras.io/models/sequential/).

http://stackoverflow.com/q/47744526
has title: Python Index Error on 2.7.6 version
tagged with: sandbox
has comment: http://stackoverflow.com/comment/82449961
type: Question
has comment: http://stackoverflow.com/comment/82449260
has comment: http://stackoverflow.com/comment/82449204
has comment: http://stackoverflow.com/comment/82449307
has comment: http://stackoverflow.com/comment/82449199
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82450238
has comment: http://stackoverflow.com/comment/82449247
tagged with: python
tagged with: python-2.7
answer count: 0
score: 0
has body: When I run my code in python version 3 it works fine but when I run in python 2.7.6 sandbox I get an index error always. The portion of the code that throws index error is: def matrix_multiply(A,B): result = [[0 for i in range(len(B[0]))] for i in range(len(A))] for i in range(len(A)): for j in range(len(B[0])): for k in range(len(B)): result[i][j] += A[i][k] * B[k][j] return result[0] #This throws index error A and B are multidimensional lists representing matrices. Could you please help me resolve this issue thanks.:)
has comment: http://stackoverflow.com/comment/82449170

http://stackoverflow.com/a/47703920
upvote count: 2
downvote count: 0
has body: If you have not standard values - true and false instead of True and False you can do the following: df['bool_column'] = df['bool_column'].eq('true')
answers question: http://stackoverflow.com/q/47703471
type: Answer
score: 2

http://stackoverflow.com/comment/82495003
type: Comment
type: QuestionComment
has text: You can use `df.TIME.dtype` to check the datatype. If `TIME` is not registered as a datetime object, try the [`parse_dates`](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_sql.html) argument in `read_sql()`.
score: 0
comment on: http://stackoverflow.com/q/47766805

http://stackoverflow.com/comment/115129063
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47754749
has text: Yeah, it helped me to just set up the settings you need in the official site and copy the appropriate command to install PyTorch.
score: 0

http://stackoverflow.com/comment/82664623
type: QuestionComment
has text: When you say "I ultimately would like both forms on the same page," do you mean you want one single URL to point to a page with both forms?
score: 0
comment on: http://stackoverflow.com/q/47789661
type: Comment

http://stackoverflow.com/a/47731555
answers question: http://stackoverflow.com/q/47731201
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/82423718
has comment: http://stackoverflow.com/comment/82423918
has comment: http://stackoverflow.com/comment/82423747
downvote count: 0
has comment: http://stackoverflow.com/comment/82423770
upvote count: 1
has body: You aren't setting StreamHandler anywhere, modified your example below. import logging output_dir = "/tmp/somefile" logger = logging.getLogger() logger.setLevel(logging.DEBUG) handler = logging.FileHandler(output_dir, "w") handler.setLevel(logging.DEBUG) formatter = logging.Formatter("%(levelname)s - %(message)s") handler.setFormatter(formatter) logger.addHandler(handler) # HERE ch = logging.StreamHandler() logger.addHandler(ch) logger.info("test") logger.info("test") logger.info("test") logger.info("test") This gives me both output on console as well as in file. EDIT: Not the best idea, agree, but taken straight from documentation import logging import unittest logger = None class TestStringMethods(unittest.TestCase): def test_upper(self): self.assertEqual('foo'.upper(), 'FOO') logger.info(self) def test_isupper(self): self.assertTrue('FOO'.isupper()) self.assertFalse('Foo'.isupper()) logger.info(self) def test_split(self): s = 'hello world' self.assertEqual(s.split(), ['hello', 'world']) # check that s.split fails when the separator is not a string with self.assertRaises(TypeError): s.split(2) logger.info(self) def setup_log(): global logger output_dir = "/tmp/somefile" logger = logging.getLogger() logger.setLevel(logging.DEBUG) handler = logging.FileHandler(output_dir, "w") handler.setLevel(logging.DEBUG) formatter = logging.Formatter("%(levelname)s - %(message)s") handler.setFormatter(formatter) logger.addHandler(handler) ch = logging.StreamHandler() logger.addHandler(ch) logger.info("Logger ready") if __name__ == '__main__': setup_log() unittest.main() It works, so probably you have some other problem in your code, if you update with more elaborate version, perhaps we can help.
has comment: http://stackoverflow.com/comment/82423733
has comment: http://stackoverflow.com/comment/82423716
has comment: http://stackoverflow.com/comment/82423793
has comment: http://stackoverflow.com/comment/82423694

http://stackoverflow.com/comment/82439658
comment on: http://stackoverflow.com/a/47737172
type: AnswerComment
has text: If I update my customer's profile, same customers name come again with in loop my table. But I don't want this.
score: 0
type: Comment

http://stackoverflow.com/q/47759436
has comment: http://stackoverflow.com/comment/82480167
answer count: 1
has comment: http://stackoverflow.com/comment/82481609
type: Question
has comment: http://stackoverflow.com/comment/82480413
tagged with: python
has comment: http://stackoverflow.com/comment/82480977
tagged with: tic-tac-toe
has comment: http://stackoverflow.com/comment/82480211
has title: Is using nested for loops good practice?
type: AnsweredQuestion
has body: I am working on a tic-tac-toe game, everything is going smoothly but I was wondering if there was a better way to carry out the following code: def straight_check(play_board, item): inc_up = 1 inc_down = 1 for num in range(3): for second in range(3): if play_board[second][num] == 'x': if inc_up == 3: return True inc_up += 1 else: continue if play_board[num][second] == 'x': if inc_down == 3: return True inc_down += 1 else: continue return False This function takes in the board for the game (a 3x3 nested list) along with the users char (x or o). This function checks if the users char occurs 3 times in a row on the board (horizontally or vertically). Is there another way I could do this without using a nested for loop along with variables? Also, is this kind of programming along with the size of the programming good practice?
tagged with: python-2.7
score: 0
has answer: http://stackoverflow.com/a/47759659
accepted answer: http://stackoverflow.com/a/47759659
has comment: http://stackoverflow.com/comment/82480417

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

http://stackoverflow.com/comment/82659276
type: AnswerComment
score: 0
has text: @Lucky No, compute the euclidian distances before TSNE and print the distance matrix.
type: Comment
comment on: http://stackoverflow.com/a/47845473

http://stackoverflow.com/comment/82414041
has text: @Ankit as I said in my answer, `Then how to judge whether the region is complete or not, it's upto your math knowledge.` First `you should define what is complete`? In your situation, `the complete tile means it is a quadrilateral, four corner points, almost equal lengths of side`. Then you `program the condition to tell the computer how to judge`. `It's your job, you should try to solve it by yourself`.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47710320

http://stackoverflow.com/a/47763572
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47763521
has body: You need to use merge df1.merge(df2, on = ['ID', 'Name'],how = 'outer').merge(df3, on = ['ID', 'Name'], how = 'outer') ID Name XCount YCount_x YCount_y 0 111 aaa 3.0 NaN 2.0 1 222 bbb 2.0 2.0 3.0 2 333 ccc 3.0 NaN NaN 3 111 abc NaN 3.0 NaN 4 444 ddd NaN 1.0 NaN 5 555 eee NaN NaN 4
type: Answer
score: 4
has comment: http://stackoverflow.com/comment/82488827
upvote count: 4
has comment: http://stackoverflow.com/comment/82488795
answers question: http://stackoverflow.com/q/47763521
has comment: http://stackoverflow.com/comment/82488741
has comment: http://stackoverflow.com/comment/82488727

http://stackoverflow.com/q/47834912
score: 0
answer count: 3
has body: I want to get a link from multiple attributes example : &lt;img id="ucCPCItemList_rptItems_ucItemListLayout_0_itemImage1_0" onerror="if(this.src=='http://pics.auction.co.kr/renewa/lp/img_none.gif') return; this.src='http://pics.auction.co.kr/renewal/lp/img_none.gif';" imageresizeonload="False" blockadultitems="True" src="http://image.auction.co.kr/itemimage/12/5c/c6/125cc6ccc2.jpg" style="height:130px;width:130px;" width="130"&gt; There are three image sources in the tag but only last source has a image So I want to take last one but I don't know how to take the last one using Beautiful Soup.
accepted answer: http://stackoverflow.com/a/47834940
has title: Getting img source link from multiple elements
tagged with: beautifulsoup
type: Question
has answer: http://stackoverflow.com/a/47836078
possible better answer: http://stackoverflow.com/a/47836078
tagged with: python
has answer: http://stackoverflow.com/a/47834940
has answer: http://stackoverflow.com/a/47836810
type: AnsweredQuestion

http://stackoverflow.com/a/47821413
type: Answer
has body: Use gedit and run: gedit ~/opencv/cmake/OpenCVDetectedPython.cmake Go to the last lines (the if statement that says if(PYTHON2INTERP_FOUND) and change the whole if block to: if(PYTHON3INTERP_FOUND) set(PYTHON_DEFAULT_AVAILABLE "TRUE") set(PYTHON_DEFAULT_EXECUTABLE "/home/tex/miniconda3/bin/python") endif() Worked for me...
downvote count: 0
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/47821174
has comment: http://stackoverflow.com/comment/82605687
has comment: http://stackoverflow.com/comment/82605673

http://stackoverflow.com/a/47752134
upvote count: 3
downvote count: 0
has body: Use DataFrame.join: df2 = df1.join(pd.DataFrame(columns=df2['HeaderName'])) Or assign: df2 = df1.assign(**pd.Series(index=df2['HeaderName']))
has comment: http://stackoverflow.com/comment/82464504
score: 3
type: Answer
answers question: http://stackoverflow.com/q/47752091

http://stackoverflow.com/a/47812744
type: Answer
accepted answer of: http://stackoverflow.com/q/47812635
has body: The Python syntax is very similar, but please note that the step size goes at the end of the slicing syntax: import numpy as np M1 = np.ones((100, 100)) M = [M1[1:20:3,1:20:3], M1[21:40,21:40], M1[41:70:3,41:70:3]]
answers question: http://stackoverflow.com/q/47812635
type: AcceptedAnswer
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/q/47819724
score: 0
accepted answer: http://stackoverflow.com/a/47819915
answer count: 1
tagged with: file-writing
has answer: http://stackoverflow.com/a/47819915
has title: How can I change the filewriting function so it writes ";" instead of "," when it's inside of "(" ")"?
type: Question
has body: This is what my function is writting: Marianne Thibault, french, ('phones',), 11:09, 230 This is what I want it to write: Marianne Thibault, french, (phones; computers), 11:09, 230 This is the function I am using: header='\n'.join(header) out_file=open(file_name,'w') out_file.write(str(header)+ '\n') out_file.write('Operators:'+'\n') for i in range(len(operators)): out_file.write(', '.join(map(str, operators[i]))) out_file.write('\n') out_file.close()
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/47743660
type: AnsweredQuestion
score: 3
accepted answer: http://stackoverflow.com/a/47744926
upvote count: 3
downvote count: 0
answer count: 1
favorite count: 0
type: Question
tagged with: pycharm
has answer: http://stackoverflow.com/a/47744926
has title: What PyCharm run configuration does and what makes it different from just run?
tagged with: python
has body: I just started using python and pycharm. I'm a bit confused of what is the run configuration in pycharm do and what is the different between the just run ?

http://stackoverflow.com/a/47781772
type: Answer
answers question: http://stackoverflow.com/q/47781215
has comment: http://stackoverflow.com/comment/82526196
has comment: http://stackoverflow.com/comment/82868839
score: 0
has comment: http://stackoverflow.com/comment/82868864
has comment: http://stackoverflow.com/comment/83019154
has body: I have Python 3.5.2 an 3.6.3 installed on a 16.04 Ubuntu Box. 3.5.2 is the system installed version at /usr/bin Symlinks for python3 and python3.5 point to this version 3.6.3 is installed at /usr/local/bin python3.6 points to this version For me the following works: wget https://bootstrap.pypa.io/get-pip.py python3.6 get-pip.py mkdir /home/ubuntu/myproj/venv python3.6 -m venv /home/ubuntu/myproj/venv #Activate the venv source /home/ubuntu/myproj/venv/bin/activate python3 now points to 3.6 inside my virtual environment. How did you install Python 3.6 on 16.04. I had a world of hurt getting it to not break things. In the end I built from source. See this gist for details. This question explains why. And this blog post gave me the solution.

http://stackoverflow.com/comment/82427284
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47733345
has text: Check previous line for extra '('.!!

http://stackoverflow.com/comment/82527708
type: Comment
comment on: http://stackoverflow.com/q/47783157
has text: That's a list of tuples, not a `Counter` object
score: 0
type: QuestionComment

http://stackoverflow.com/comment/82548118
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47793358
type: Comment
has text: Unless we cast the `driver` instance and invoke the `EC`, we shouldn't expect the `WebElement` anyway, right? We would see the instance only.

http://stackoverflow.com/q/47765595
type: AnsweredQuestion
has title: Tensorflow: Attempting to use uninitialized value beta1_power
tagged with: python
has body: I got the following error when I try to run the code at the end of the post. But it is not clear to me what is wrong with my code. Could anybody let me know the tricks in debugging a tensorflow program? $ ./main.py Extracting /tmp/data/train-images-idx3-ubyte.gz Extracting /tmp/data/train-labels-idx1-ubyte.gz Extracting /tmp/data/t10k-images-idx3-ubyte.gz Extracting /tmp/data/t10k-labels-idx1-ubyte.gz 2017-12-11 22:53:16.061163: I tensorflow/core/platform/cpu_feature_guard.cc:137] Your CPU supports instructions that this TensorFlow binary was not compiled to use: SSE4.1 SSE4.2 AVX AVX2 FMA Traceback (most recent call last): File "./main.py", line 55, in &lt;module&gt; sess.run(opt, feed_dict={x: batch_x, y: batch_y}) File "/usr/local/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 889, in run run_metadata_ptr) File "/usr/local/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 1120, in _run feed_dict_tensor, options, run_metadata) File "/usr/local/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 1317, in _do_run options, run_metadata) File "/usr/local/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 1336, in _do_call raise type(e)(node_def, op, message) tensorflow.python.framework.errors_impl.FailedPreconditionError: Attempting to use uninitialized value beta1_power [[Node: beta1_power/read = Identity[T=DT_FLOAT, _class=["loc:@Variable"], _device="/job:localhost/replica:0/task:0/device:CPU:0"](beta1_power)]] Caused by op u'beta1_power/read', defined at: File "./main.py", line 46, in &lt;module&gt; opt=tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(loss) File "/usr/local/lib/python2.7/site-packages/tensorflow/python/training/optimizer.py", line 353, in minimize name=name) File "/usr/local/lib/python2.7/site-packages/tensorflow/python/training/optimizer.py", line 474, in apply_gradients self._create_slots([_get_variable_for(v) for v in var_list]) File "/usr/local/lib/p…
tagged with: recurrent-neural-network
tagged with: lstm
favorite count: 0
has comment: http://stackoverflow.com/comment/82504496
type: Question
downvote count: 0
tagged with: machine-learning
answer count: 1
tagged with: tensorflow
accepted answer: http://stackoverflow.com/a/47780342
score: 19
upvote count: 19
has answer: http://stackoverflow.com/a/47780342

http://stackoverflow.com/comment/82570117
comment on: http://stackoverflow.com/a/47804321
type: Comment
type: AnswerComment
has text: What about this "Noting that each letter only appears once in the same generated string."?
score: 0

http://stackoverflow.com/q/47797596
tagged with: pandas
has answer: http://stackoverflow.com/a/47797696
downvote count: 0
possible better answer: http://stackoverflow.com/a/47797701
favorite count: 0
type: Question
has body: I would like find the row (index) where the cumulative sum of the values in some column exceeds a threshold. I can, and do, find this location using a simple loop, like below: def sum_to(df, col, threshold): s = 0 for r in df.iterrows(): if s + r[1][col] &gt; threshold: return r[0] else: s += r[1][col] return len(df) However, I would like to know if there is a better/nicer way to achieve this in Pandas.
has answer: http://stackoverflow.com/a/47797701
score: 6
has comment: http://stackoverflow.com/comment/82555953
has title: In pandas, how to find the row/index where the cumulative sum is greater than a threshold?
tagged with: python
upvote count: 6
type: AnsweredQuestion
answer count: 2
accepted answer: http://stackoverflow.com/a/47797696

http://stackoverflow.com/q/47726854
linked to: http://stackoverflow.com/q/20953273
type: UnansweredQuestion
has body: I am using this code Link but it displays error of module object has no attribute i tried to pip install freetype but nothing happened. Can anyone please guide me with this. import cv2 import numpy as np img = np.zeros((100, 300, 3), dtype=np.uint8) ft = cv2.freetype.createFreeType2() ft.loadFontData(fontFileName='Ubuntu-R.ttf', id=0) ft.putText(img=img, text='Quick Fox', org=(15, 70), fontHeight=60, color=(255, 255, 255), thickness=-1, line_type=cv2.LINE_AA, bottomLeftOrigin=True) cv2.imwrite('image.png', img)
has answer: http://stackoverflow.com/a/57984529
downvote count: 0
tagged with: python
has answer: http://stackoverflow.com/a/51061771
has comment: http://stackoverflow.com/comment/82414361
has comment: http://stackoverflow.com/comment/82414243
has comment: http://stackoverflow.com/comment/82414183
favorite count: 0
has comment: http://stackoverflow.com/comment/82415297
has comment: http://stackoverflow.com/comment/82414234
tagged with: opencv
has answer: http://stackoverflow.com/a/69548132
tagged with: freetype2
tagged with: freetype
has title: Error 'module' object has no attribute 'freetype'
has comment: http://stackoverflow.com/comment/82415203
score: 7
upvote count: 7
has answer: http://stackoverflow.com/a/55324396
has comment: http://stackoverflow.com/comment/82414646
has answer: http://stackoverflow.com/a/61402349
type: Question
tagged with: numpy
answer count: 5

http://stackoverflow.com/q/47853415
favorite count: 0
has comment: http://stackoverflow.com/comment/82671024
score: 1
has body: Environment ：windows10 on mac，python3.6，opencv3.3 Problem： The code can run rightly on the windows 7 + python 3.5， the window and the frame of the video display rightly. But the same code can appear the window all the time，but the frame can not display rightly sometimes，sometimes the frame can be displayed normally. And the output of the variable ： ‘frame’ sometimes is ‘0’，while the right output should not be ‘0’： cam = cv2.VideoCapture(0) ret, frame = cam.read() print(frame) The video can be opened normally when i have the Video phone call with my friend on the windows 10 of the mac. Is the reason of the Camera drive of the mac run the windows 10？
tagged with: python
type: Question
answer count: 0
tagged with: video-capture
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82674161
downvote count: 0
upvote count: 1
has title: windows 10 on mac + opencv + python,open the video but the frame is not displayed all the time
tagged with: opencv

http://stackoverflow.com/q/47828481
type: Question
tagged with: html-table
possible better answer: http://stackoverflow.com/a/47832943
answer count: 2
upvote count: 1
tagged with: selenium
has answer: http://stackoverflow.com/a/47828663
accepted answer: http://stackoverflow.com/a/47828663
favorite count: 0
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/82619641
tagged with: pandas
has body: Running Python 3.6.1 |Anaconda 4.4.0 (64-bit) on a Windows device. Using selenium I gather the following html source: from selenium import webdriver from selenium.webdriver.common.keys import Keys url = "https://nextgenstats.nfl.com/stats/receiving#yards" driver = webdriver.Chrome(executable_path=r"C:/Program Files (x86)/Google/Chrome/chromedriver.exe") driver.get(url) htmlSource = driver.page_source If one checks the url, they will see a nice table that is dynamically loaded. I am unsure how this table can be extracted from htmlsource so that a Pandas dataframe can be constructed from it.
downvote count: 1
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/82619781
has title: Convert dynamically loaded table into Pandas Dataframe
has comment: http://stackoverflow.com/comment/82620018
has answer: http://stackoverflow.com/a/47832943

http://stackoverflow.com/q/47782878
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47782958
upvote count: 2
has answer: http://stackoverflow.com/a/47782948
has comment: http://stackoverflow.com/comment/82527302
downvote count: 0
possible better answer: http://stackoverflow.com/a/47783009
has body: My question is about optimizing how I'm currently doing text replacement. I have a script I'm building that presents questions with variables inside that get replaced with random actual values when the script is run. My script currently performs this similar to the following (using the random library): def rand_var(): rndvar = ['one', 'two', 'three'] shuffle(rndvar) return rndvar rndvar = rand_var() x = 'blah blah VAR1 blah blah VAR2 blah blah' x = x.replace('VAR1', rndvar[0]) x = x.replace('VAR2', rndvar[1]) The rndvar list is randomized, and within string x VAR1 is replaced with the first randomized element, VAR2 is replaced with the second. I am wondering if there is a way to rewrite the multiple x = x.replace lines so that I can still specify the variables within the string (the question) as VAR1 VAR2 etc, but have the single replacement line know that VAR1 means replace with rndvar[0] and VAR2 means replace with rndvar[1] etc. My questions (strings) will contain elements from multiple lists representing different things (but all strings). Thank you for all the responses, I appreciate it!
has answer: http://stackoverflow.com/a/47783009
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47782958
tagged with: python-3.x
has title: Python3 text replacement optimization
has answer: http://stackoverflow.com/a/47782950
tagged with: python
answer count: 4

http://stackoverflow.com/q/47752041
score: 1
has title: How to copy file from FTP server to another FTP server (platform independently)
favorite count: 0
accepted answer: http://stackoverflow.com/a/47760932
type: Question
tagged with: ftp
linked to: http://stackoverflow.com/q/3808799
tagged with: ftplib
has answer: http://stackoverflow.com/a/47760932
has body: I have made a script which copy file from local machine to FTP server. I referred this link to make script Upload folders from local system to FTP using Python script, but now I want to copy file from FTP to another remote FTP machine on different location using Python script. How to do this? File copy can be done using rsync command, but I want to do this using Python script. Code: import ftplib import os server = 'host' username = 'name' password = 'pass' ftp = ftplib.FTP(server, username, password) Path = 'path'#source val = "/des/"#destination def copy(source,destination): print(source) print(destination) os.chdir(source) ftp.cwd(destination) if "C:\\" in Path or "c:\\" in Path: ftp_path = (source).split("\\")[-1] else: ftp_path = (source).split("/")[-1] directory = destination+ftp_path mkdir(directory) ftp.cwd(directory) read = os.listdir(source) for file in read: print(file) if "C:\\" in Path or "c:\\" in Path: Type = source + "\\" + file else: Type = source + "/" + file print(Type) print() if os.path.isdir(Type):#If Type is Folder then it will create new folder copy(Type,directory+"/") elif os.path.isfile(Type):#If Type is file then it will create file print(Type) current_dir = ftp.pwd() + "/" f = Type fh = open(f, 'rb') ftp.storbinary('STOR %s' % current_dir + file, fh) fh.close() def mkdir(path): #print(path) ftp.mkd(path) copy(Path,val) ftp.close()
answer count: 1
downvote count: 0
upvote count: 1
tagged with: python
linked to: http://stackoverflow.com/q/5663787
type: AnsweredQuestion

http://stackoverflow.com/q/47777608
answer count: 1
has body: Hi I am a beginner with python and i don't know why I get these results using this two versions of code 1. q = input('write something with spaces') print(q.split()[::-1]) RESULTS: write something hello everybody ['everybody', 'hello'] 2. q = input('write something') q.split() print(q[::-1]) RESULTS: write something hello everybody ydobyreve olleh My question is: Why outputs are not the same ? Thanks !
has comment: http://stackoverflow.com/comment/82516370
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82516475
has title: Why outputs are different?
tagged with: python
accepted answer: http://stackoverflow.com/a/47777664
has answer: http://stackoverflow.com/a/47777664
score: 2
type: AnsweredQuestion
upvote count: 3

http://stackoverflow.com/comment/82517318
type: AnswerComment
comment on: http://stackoverflow.com/a/47778056
has text: `"I want to print the first instance of the row that didn't match"` - do you mean `print(df1[m.argmax()])`?
score: 0
type: Comment

http://stackoverflow.com/q/47847071
upvote count: 0
downvote count: 2
answer count: 1
has title: The output of my list of lists makes no sense. using .pop and .insert
accepted answer: http://stackoverflow.com/a/47851074
has comment: http://stackoverflow.com/comment/82658381
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47851074
type: AnsweredQuestion
score: -2
tagged with: python
has body: if you run this small GUI, and insert a few examples (q1, a1, h1) hit "save/next" (q2, a2, h1,) save/next (q3, a3, h3) save/next. then click the edit/confirm save Button. it'll bring the first (q1, a1, h1) Change some of the contents to ex: (question 1, answer 1, hint 1) hit "save Entry #0" button. it saves it at the correct place [[0][]] which is list[item0]. now the next edit, change contents to (question 2, answer 2, hint 2) Then hit "save Entry #1" again. This is where i need help. The print output i used to debug shows that both the list item [[0][1]] zero and one have both been changed with the item that was supposed to be in list 1 only. and then i lose the stuff in list 0. Why could this be?? from tkinter import * root= Tk() n=0 x = 10 y = 10 single_questions = [] all_questions = [] # clear all the entries or Text def clear(event=None): l = [Quest_Entry, Ans_Entry, Hint_Entry] for i in l: i.delete(1.0, 'end') # add single questions to all questions def add_to_all_questions(new_list): print ("appending : " + str(list(new_list))) all_questions.append(list(new_list)) # saves single questions, call add_to_all_question and clears screen. def save_next(event=None): l = [Quest_Entry, Ans_Entry, Hint_Entry] for i in l: single_questions.append(i.get(1.0,'end').strip()) clear() Quest_Entry.focus() add_to_all_questions(single_questions) single_questions.clear() # first method of button check confirm def check_confirm(event=None): ''' should disappear after initiation and set back to n=0''' global n print ("Confirm btn pressed") save_next.configure(state="disabled") confirm_btn.grid_forget() confirm.grid(column=2, row=4, padx=x, pady=y) clear() n=0 Incrementer() # Increment then display the following questions def Incrementer(event=None): global n root.update_idletasks() if n &lt; len(all_questions): Quest_Entry.insert(1.0,all_questions[n][0]) Ans_Entry.insert(1.0,all_questions[n][1]) Hint_Entry.insert(1.0,all_questions[n][2]) confirm.configure(text="Save Entry #{}".for…
tagged with: list
tagged with: tkinter

http://stackoverflow.com/q/47849713
type: Question
has answer: http://stackoverflow.com/a/47849796
answer count: 2
has comment: http://stackoverflow.com/comment/82664045
score: -11
has comment: http://stackoverflow.com/comment/82663991
accepted answer: http://stackoverflow.com/a/47849786
has title: convert javascript to python : looping for in python
downvote count: 12
tagged with: javascript
upvote count: 1
has comment: http://stackoverflow.com/comment/82664275
has body: I have the javascript code and i want to convert it to python. var dice = [1, 3, 4, 1] for(let i = 0; i &lt; dice.length; i++) { if(dice[i] == 1 ) { dice.splice(i, 1) break; } } whats wrong? q = [1, 2,3, 4] for i, dice in q: if dice[i] == 1: dice = splice(i, 1) break print dice I want if the number one appears simultaneously then the number 1 is discarded. How the python code for the js code above?
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82663949
tagged with: python
has answer: http://stackoverflow.com/a/47849786
possible better answer: http://stackoverflow.com/a/47849796
favorite count: 0
has comment: http://stackoverflow.com/comment/82664044

http://stackoverflow.com/comment/82434538
type: Comment
type: QuestionComment
has text: Thanks! I updated `WSGIScriptAlias` to `/rrfexpire`, restarted Apache, and received the 500 Internal Server Error
comment on: http://stackoverflow.com/q/47736881
score: 0

http://stackoverflow.com/a/68909975
has body: List item I had an issue where I had an extra -&gt; returnobject in my file. So it was a syntax error.
downvote count: 1
answers question: http://stackoverflow.com/q/47776315
upvote count: 0
type: Answer
score: -1

http://stackoverflow.com/comment/82543914
comment on: http://stackoverflow.com/q/47791378
has text: It looks like you need to pick up a book on exception handling in python.
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/a/47838322
has comment: http://stackoverflow.com/comment/82773335
has comment: http://stackoverflow.com/comment/82706822
upvote count: 2
has comment: http://stackoverflow.com/comment/82641299
has comment: http://stackoverflow.com/comment/82641709
downvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/82745868
type: Answer
has comment: http://stackoverflow.com/comment/82740985
answers question: http://stackoverflow.com/q/47838058
has body: You haven't mentioned if you're using a BR2_EXTERNAL path or not, in any case I suggest following the official user manual - https://buildroot.org/downloads/manual/manual.html You have to add the your package's Config.in to package/Config.in (or BR2_EXTERNAL/Config.in, then it should show up as a menu option either under the section you added it or under "External options" if using BR2_EXTERNAL. Your package should contain atleast Config.in and a .mk file

http://stackoverflow.com/a/47704368
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82369191
upvote count: 8
score: 8
accepted answer of: http://stackoverflow.com/q/47704224
has comment: http://stackoverflow.com/comment/82369974
has comment: http://stackoverflow.com/comment/82369885
has comment: http://stackoverflow.com/comment/82369351
has comment: http://stackoverflow.com/comment/82369953
type: Answer
answers question: http://stackoverflow.com/q/47704224
has comment: http://stackoverflow.com/comment/82369279
has comment: http://stackoverflow.com/comment/82369396
has body: read_csv() has many useful options header=None - and first row is not treated as headers. sep='\s+' - and it uses spaces to split columns (instead of comma ,). It is regex. . import pandas as pd url ='http://www2.conectiv.com/cpd/tps/archives/nj/2017/12/20171205NJA1.txt' df = pd.read_csv(url, skiprows=4, header=None, sep='\s+') After you load data you can change values in columns. This removes Segments: in first column df[0] = df[0].str.replace('Segment:', '')

http://stackoverflow.com/comment/82480849
comment on: http://stackoverflow.com/q/47702548
type: Comment
type: QuestionComment
score: 0
has text: I was wrong - comma list is how I do it as well. However, look at your message data. I don't think you are supposed to literally put in '0x00~0xFF'. I think that means you need a single value within that range. In the documentation, can you find an example of a successful send-packet?

http://stackoverflow.com/q/47750711
upvote count: 1
tagged with: string
favorite count: 0
type: Question
has title: How to check a txt contain all the element in a list?
tagged with: python
accepted answer: http://stackoverflow.com/a/47750783
score: -3
has answer: http://stackoverflow.com/a/47750783
type: AnsweredQuestion
downvote count: 4
has body: Like I have a text file and read it already using with open(full_path,'r') as f2: contents = f2.read() content like: sadasdasdasdsa dasdasdasdffsdf [sdas] aaa dfdsfdsfdfds bbb and I have a list like: a = ['aaa','bbb'] b = ['343242','bbb'] We could see all element in lista are in content,elements in b are not all in content. but how could I check it in a loop? Like if a in content print ok else print not. Thanks!!
linked to: http://stackoverflow.com/q/2783969
has comment: http://stackoverflow.com/comment/82462307
answer count: 1
has comment: http://stackoverflow.com/comment/82461695

class
tags question: http://stackoverflow.com/q/47736568
tags question: http://stackoverflow.com/q/47776052
tags question: http://stackoverflow.com/q/47709927
type: Tag
tags question: http://stackoverflow.com/q/47740953
tags question: http://stackoverflow.com/q/47727573
tags question: http://stackoverflow.com/q/47724075
tags question: http://stackoverflow.com/q/47732461
tags question: http://stackoverflow.com/q/47719651
tags question: http://stackoverflow.com/q/47782596
tags question: http://stackoverflow.com/q/47759792
tags question: http://stackoverflow.com/q/47801335
tags question: http://stackoverflow.com/q/47767538
tags question: http://stackoverflow.com/q/47840006
tags question: http://stackoverflow.com/q/47853592
tags question: http://stackoverflow.com/q/47760611
tags question: http://stackoverflow.com/q/47807770
tags question: http://stackoverflow.com/q/47769658
tag name: class
tags question: http://stackoverflow.com/q/47706620
tags question: http://stackoverflow.com/q/47715733
tags question: http://stackoverflow.com/q/47836792
tags question: http://stackoverflow.com/q/47819741
tags question: http://stackoverflow.com/q/47756183
tags question: http://stackoverflow.com/q/47762286
tags question: http://stackoverflow.com/q/47777484
tags question: http://stackoverflow.com/q/47847724
tags question: http://stackoverflow.com/q/47754103
tags question: http://stackoverflow.com/q/47732590
tags question: http://stackoverflow.com/q/47724268
tags question: http://stackoverflow.com/q/47794452
tags question: http://stackoverflow.com/q/47738634
tags question: http://stackoverflow.com/q/47726113
tags question: http://stackoverflow.com/q/47767042
tags question: http://stackoverflow.com/q/47743798
tags question: http://stackoverflow.com/q/47786082
tags question: http://stackoverflow.com/q/47787134
tags question: http://stackoverflow.com/q/47802801
tags question: http://stackoverflow.com/q/47774147
tags question: http://stackoverflow.com/q/47806824
tags question: http://stackoverflow.com/q/47707081
tags question: http://stackoverflow.com/q/47797790
tags question: http://stackoverflow.com/q/47729174

http://stackoverflow.com/comment/82528290
score: 0
type: Comment
has text: there are two more tables , how can I access those details , should I use placeholder instead ? @David
type: AnswerComment
comment on: http://stackoverflow.com/a/47782384

http://stackoverflow.com/comment/82591642
has text: ca fonctione , ennormement merci J-F je suis rester bloquee depuis 9h du mat :-)
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47814170

http://stackoverflow.com/comment/82670514
type: QuestionComment
comment on: http://stackoverflow.com/q/47853067
type: Comment
score: 0
has text: My answer in the duplicate also explains *why* this happens (`exec(... 'single')`)

http://stackoverflow.com/comment/82606676
has text: Are you using Python 2 or 3?
type: Comment
comment on: http://stackoverflow.com/q/47821883
type: QuestionComment
score: 0

http://stackoverflow.com/a/47852184
accepted answer of: http://stackoverflow.com/q/47852110
has comment: http://stackoverflow.com/comment/82677963
downvote count: 0
upvote count: 1
score: 1
has body: Your code will be (almost) correct if you strip the trailing slash from path, but in any case you should use os.path.relpath to compute the relative file paths: import os def f(path): path = path.rstrip(os.sep) parent = os.path.dirname(path) for p, dirs, files in os.walk(path): for file in files: print(os.path.relpath(os.path.join(p, file), parent)) For what it's worth, pathlib makes path manipulation easier: from pathlib import Path def f(path): path = Path(path) for x in path.rglob('*'): if not x.is_dir(): print(x.relative_to(path.parent))
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82668776
answers question: http://stackoverflow.com/q/47852110
has comment: http://stackoverflow.com/comment/82678665
type: Answer

http://stackoverflow.com/q/47846465
has body: I dont know what is wrong with this code. But I actually want to get my query so I use User.objects.get(pk=mail) while the mail is an string that I got from request.POST.get('email') . I try to access my data through the Django Shell, it working fine. but I dont know. here is the code in models.py: class User(models.Model): email = models.EmailField(max_length=150, primary_key=True) pw = models.CharField(max_length=255) in views.py: if request.method == 'POST': mail = request.POST.get('email') pwd = request.POST.get('pw') a = User.objects.get(pk=mail) Thanks in advance.
has comment: http://stackoverflow.com/comment/82657011
score: 0
has comment: http://stackoverflow.com/comment/82657215
answer count: 0
type: UnansweredQuestion
has title: Why DoesNotExist while query is exist?
has comment: http://stackoverflow.com/comment/82656899
has comment: http://stackoverflow.com/comment/82657045
has comment: http://stackoverflow.com/comment/82657168
has comment: http://stackoverflow.com/comment/82657025
type: Question
has comment: http://stackoverflow.com/comment/82656948
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/82657119
has comment: http://stackoverflow.com/comment/82657282

sniffer
tags question: http://stackoverflow.com/q/47769535
type: Tag
tag name: sniffer

http://stackoverflow.com/a/47763174
has body: For binary search to work, your items need to be sorted properly. In your version of the algorithm, you're doing direct tuple comparisons. That means the tuples need to be sorted according to their comparison rules, i.e. first by the first element and—when the result of that is inconclusive—then by the second. If you try your algorithm on this list, you'd see it work: &gt;&gt;&gt; list(sorted(names)) [('Daisy', 'Fox'), ('Dina', 'Ram'), ('Elin', 'Grosefield'), ('Josh', 'Belluga'), ('Mike', 'Levinsan')] If you want to have the list sorted by last name, you first need put ('Mike', 'Levinsan') in the right position. The result should be: &gt;&gt;&gt; list(sorted(names, key=lambda x: (x[1], x[0]))) [('Josh', 'Belluga'), ('Daisy', 'Fox'), ('Elin', 'Grosefield'), ('Mike', 'Levinsan'), ('Dina', 'Ram')] Next, you need to change this line in your algorithm: if lst[middle] &gt; name: to something like: if (lst[middle][1], lst[middle][0]) &gt; (name[1], name[0]): so that you're comparing last names before names.
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47761340
score: 5
upvote count: 5
answers question: http://stackoverflow.com/q/47761340
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/q/47814809
tagged with: validation
type: UnansweredQuestion
downvote count: 0
tagged with: keras
favorite count: 0
has answer: http://stackoverflow.com/a/54814640
upvote count: 5
tagged with: python
type: Question
has answer: http://stackoverflow.com/a/47816686
answer count: 2
score: 5
has body: How do I use keras function fit_generator() to train and simultaneously save the model weights with lowest validation loss?
has title: fit_generator() to save model with least validation loss

http://stackoverflow.com/q/47838575
has comment: http://stackoverflow.com/comment/82653942
has title: Submit form with flask wtforms with GET method
tagged with: flask
favorite count: 0
has comment: http://stackoverflow.com/comment/82654729
type: Question
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82640959
tagged with: wtforms
has comment: http://stackoverflow.com/comment/82651925
has body: I have 2 routes : @app.route('/activity', methods=["GET"]) def addactivity(): return render_template('activity.html') In acitvity.html I have a form with some fields and I want to submit this form to another route : @app.route('/students', methods=["GET"]) def addstudents(): return render_template('students.html') So when I submit the form in acitvity.html I will be redirected to /students?field1=value1&amp;field2=value2 etc... For activity form i am using wtforms with validators: DataRequired() or InputRequired() The problem is that when i am using form.validate() in addstudents route even if form is validated or not it will redirect me to students.html route.I want in case the form is not validated to display the errors in activity.html.How is that possible? I am new to flask and maybe my whole code is wrong, but the concept is that if the activity form is validated i will be redirected to the students route, if not errors will be displayed in activity route.. Furthermore i need to submit the the form in students route with the args of the previous form.
score: 4
tagged with: forms
upvote count: 4
has comment: http://stackoverflow.com/comment/82641079
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/55988594

http://stackoverflow.com/q/47767179
answer count: 4
downvote count: 0
has answer: http://stackoverflow.com/a/51029067
upvote count: 1
score: 1
has answer: http://stackoverflow.com/a/54884414
has body: I am trying to upload my newly created project to app engine but receiving "permission denied" when running appcfg.py update . in my project directory. Things I have tried: Tried specifying the full path to project appcfg.py update **path** Tried checking permissions on appcfg.py and appcfg.pyc are read &amp; write Tried following all answers found on the only relevant post I can find: google app engine - permission denied error Ran gcloud auth login and logged into google via Chrome. No idea what else I can do, I'm new to this and this problem is just confusing me further.
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/55186110
type: UnansweredQuestion
tagged with: google-app-engine
has answer: http://stackoverflow.com/a/47767453
tagged with: python
has title: Cannot upload project - appcfg.py permission denied
linked to: http://stackoverflow.com/q/34683112

http://stackoverflow.com/comment/82540817
score: 0
has text: @GabbarSingh no
type: QuestionComment
comment on: http://stackoverflow.com/q/47788748
type: Comment

pyspark
tags question: http://stackoverflow.com/q/47774601
tags question: http://stackoverflow.com/q/47847285
tags question: http://stackoverflow.com/q/47722948
tags question: http://stackoverflow.com/q/47780567
tags question: http://stackoverflow.com/q/47726552
tags question: http://stackoverflow.com/q/47828443
tags question: http://stackoverflow.com/q/47819888
tags question: http://stackoverflow.com/q/47829089
tags question: http://stackoverflow.com/q/47844999
tags question: http://stackoverflow.com/q/47702406
tags question: http://stackoverflow.com/q/47785723
tags question: http://stackoverflow.com/q/47815669
tags question: http://stackoverflow.com/q/47719089
tags question: http://stackoverflow.com/q/47778868
tags question: http://stackoverflow.com/q/47736702
tags question: http://stackoverflow.com/q/47722936
tags question: http://stackoverflow.com/q/47734675
tags question: http://stackoverflow.com/q/47765716
tags question: http://stackoverflow.com/q/47824131
tags question: http://stackoverflow.com/q/47721453
tags question: http://stackoverflow.com/q/47705919
tags question: http://stackoverflow.com/q/47766256
tags question: http://stackoverflow.com/q/47807845
tags question: http://stackoverflow.com/q/47787075
tags question: http://stackoverflow.com/q/47783682
type: Tag
tags question: http://stackoverflow.com/q/47751542
tags question: http://stackoverflow.com/q/47779919
tags question: http://stackoverflow.com/q/47707405
tags question: http://stackoverflow.com/q/47801317
tags question: http://stackoverflow.com/q/47755665
tags question: http://stackoverflow.com/q/47812526
tags question: http://stackoverflow.com/q/47803784
tags question: http://stackoverflow.com/q/47730265
tags question: http://stackoverflow.com/q/47701769
tags question: http://stackoverflow.com/q/47754440
tag name: pyspark
tags question: http://stackoverflow.com/q/47793412
tags question: http://stackoverflow.com/q/47832817
tags question: http://stackoverflow.com/q/47699922
tags question: http://stackoverflow.com/q/47810164
tags question: http://stackoverflow.com/q/47828907
tags question: http://stackoverflow.com/q/47791878
tags question: http://stackoverflow.com/q/47805216
tags question: http://stackoverflow.com/q/47770674
tags question: http://stackoverflow.com/q/47764902

http://stackoverflow.com/comment/82409722
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47724417
has text: If you see documentation and/or check source code (path: `import turtle ; print( turtle.__file__ )`) then you will see there is only one `listen()` but it can be accessible directly or with `getscreen()`, etc. Besides you can assing turtle to different variables `window`, `screen`, `hello_world` but it is still the same function.
type: Comment

http://stackoverflow.com/a/47760761
score: 1
accepted answer of: http://stackoverflow.com/q/47737160
type: Answer
answers question: http://stackoverflow.com/q/47737160
has body: In most versions of LibreOffice, the name of the default style is "Default Style". In Apache OpenOffice, it is named "Default" instead. Here is the complete code. For example, name the file change_settings.py. import uno def set_page_style_margins(): document = XSCRIPTCONTEXT.getDocument() pageStyle = document.getStyleFamilies().getByName("PageStyles") page = pageStyle.getByName("Default Style") page.LeftMargin = 500 g_exportedScripts = set_page_style_margins, On my Windows 10 system, this script is located under the directory C:\Users\&lt;your username&gt;\AppData\Roaming\LibreOffice\4\user\Scripts\python. You will need to create the last two directories, and case must match. Now, in LibreOffice Writer, go to Tools -> Macros -> Run Macro. Expand to My Macros -> change_settings and select the macro name set_page_style_margins. For a full introduction to Python with LibreOffice: https://wiki.openoffice.org/wiki/Python/Transfer_from_Basic_to_Python http://christopher5106.github.io/office/2015/12/06/openoffice-libreoffice-automate-your-office-tasks-with-python-macros.html
type: AcceptedAnswer
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/47816564
upvote count: 1
has body: There is no simple API to do this. You could call df.map_partitions(len) to determine which partitions are empty and then remove them explicitly, perhaps by using df.to_delayed() and dask.dataframe.from_delayed(...). In the future if you are willing to raise issues when you find a function that does not work well with empty partitions that would be greatly appreciated. https://github.com/dask/dask/issues/new
answers question: http://stackoverflow.com/q/47812785
score: 1
type: Answer
downvote count: 0

http://stackoverflow.com/a/47742737
has body: UPDATED Based on my experience when you write event binding in the plain tags, like you have, it won't bind. There are 2 solutions, which I'll cover step by step: 1) bind on document ready. Also please note that I am binding using class, not id, so you have to change your html also HTML button would look like this: {% for comentario in objects %} {% if user.is_authenticated %} &lt;button id="likes-{{forloop.counter0}}" data-comid="{{comentario.id}} class="btn btn-warning btn-sm btn-like" type="button"&gt; ...(continue as you have) ajax.js file would look like this: $(document).ready(function () { $(".btn-like").on("click", function (event) { let comid = $(this).attr("data-comid"); $.get("/home/like/", {"comentario_id": comid}, function (data, status) { $(this).hide(); }); }); )}; 2) The second solution is to bind function call directly in the HTML, I will only write button definition: &lt;button id="likes-{{forloop.counter0}}" class="btn btn-warning btn-sm" type="button" onclick="likeThisComment('{{comentario.id}}')&gt; ...(continue as you have) in this HTML you will notice that I've removed class (".likes") and also "data-comid" attribute, since onclick I directly pass them to the function as argument. ajax.js file function likeThisComment (comid) { $.get("/home/like/", {"comentario_id": comid}, function (data, status) { $(this).hide(); }); } hope this makes things lot clear. and don't forget to take a look to this tutorial: which has good examples
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82446365
has comment: http://stackoverflow.com/comment/82479118
has comment: http://stackoverflow.com/comment/82445765
has comment: http://stackoverflow.com/comment/82445921
has comment: http://stackoverflow.com/comment/82446314
has comment: http://stackoverflow.com/comment/82445902
has comment: http://stackoverflow.com/comment/82446050
answers question: http://stackoverflow.com/q/47742557
type: Answer
has comment: http://stackoverflow.com/comment/82446273
accepted answer of: http://stackoverflow.com/q/47742557
has comment: http://stackoverflow.com/comment/82446037
has comment: http://stackoverflow.com/comment/82445886

http://stackoverflow.com/a/47724125
type: Answer
has comment: http://stackoverflow.com/comment/82409656
score: 0
has comment: http://stackoverflow.com/comment/134632483
answers question: http://stackoverflow.com/q/47724124
has body: The answer is "yes": Create new Python files as a "folder" to hold your imports Add the import statements to that Python file Import the assets from that file (Will update this Q with more detail when I have time.)

http://stackoverflow.com/q/47738372
tagged with: list
has body: n=[1,2,3,4,5,6,7,8] n[:6:-2] #[8] I think the result should be [6,4,2] not [8] and what surprised me more is when I slice the list explicitly n[0:6,-2] then the output is [] I've checked documents, and noticed shallow copy,thus still no idea what happend under the hood
answer count: 3
has answer: http://stackoverflow.com/a/47738544
has answer: http://stackoverflow.com/a/47742064
has comment: http://stackoverflow.com/comment/82436989
has comment: http://stackoverflow.com/comment/82436979
has comment: http://stackoverflow.com/comment/82437189
type: Question
possible better answer: http://stackoverflow.com/a/47738477
accepted answer: http://stackoverflow.com/a/47742064
score: 2
has answer: http://stackoverflow.com/a/47738477
upvote count: 3
tagged with: python
tagged with: data-structures
has title: why n=[1,2,3,4,5,6,7,8],n[:6:-2] is [8] in Python?
linked to: http://stackoverflow.com/q/509211
downvote count: 1
favorite count: 0
type: AnsweredQuestion

http://stackoverflow.com/comment/82521897
has text: I currently have version `3.6.1`. I will reinstall python to the latest version and let you know what happens :-)
type: Comment
comment on: http://stackoverflow.com/q/47778550
score: 0
type: QuestionComment

http://stackoverflow.com/q/47748816
score: 1
downvote count: 0
answer count: 1
upvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/53560951
type: Question
has body: I want to sort my result based on the distance calculated in the geodjango query. I tried with two methods but they are throwing errors. models.py class Partner(models.Model): name = models.CharField(max_length=255) address = models.CharField(max_length=255) location = models.PointField(u"longitude/latitude",geography=True, blank=True, null=True) views.py method 1: testing = Partner.objects.filter(location__distance_lte=(pnt, D(km=40))).annotate(distance=Distance('location', pnt)).order_by('distance') print(testing) Error: Internal Server Error: /partner/filter/ Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/prasanna/Projects/partner_server/partner/views.py", line 79, in Filter_function print(testing.annotate(distance=Distance('location', pnt)).order_by('distance')) TypeError: __init__() takes from 1 to 2 positional arguments but 3 were given method 2: testing = Partner.objects.filter(location__distance_lte=(pnt, D(km=40))).annotate(distance=Distance('location', pnt)).order_by('distance') print(testing) Error: Internal Server Error: /partner/filter/ Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(req…
tagged with: geodjango
type: UnansweredQuestion
tagged with: python
has title: Geodjango-query with distance lookupsss

global
type: Tag
tags question: http://stackoverflow.com/q/47799171
tags question: http://stackoverflow.com/q/47783867
tag name: global
tags question: http://stackoverflow.com/q/47774147
tags question: http://stackoverflow.com/q/47707081
tags question: http://stackoverflow.com/q/47839582

http://stackoverflow.com/comment/91173471
type: Comment
comment on: http://stackoverflow.com/a/47842394
score: 0
type: AnswerComment
has text: Very thorough answer but even more errors result from 'sudo apt install python3.6-venv' so I got lazy and went with Orny's answer which seemed to work.

http://stackoverflow.com/a/47847614
has comment: http://stackoverflow.com/comment/94539634
downvote count: 4
upvote count: 3
has body: This is probably because there may be bot scripts running which are targeting your server with different HTTP_HOST headers (this is common). and in django you have Allowed Hosts set to a particular host. So if a Host Header different from one specified in Allowed Hosts come then django would give 400 error. By default django loggers are configured to send mail on each error. To stop getting the mails you need to configure loggers in django and add the following logger 'django.security.DisallowedHost': { 'handlers': ['null'], 'propagate': False, }, Refer https://www.calazan.com/how-to-disable-the-invalid-http_host-header-emails-in-django/
type: Answer
answers question: http://stackoverflow.com/q/47846521
score: -1
has comment: http://stackoverflow.com/comment/82667525

http://stackoverflow.com/a/47734465
score: 1
upvote count: 1
has body: movieSeats is local variable in buttonsMake() so it doesn't exist in redClick and you get error name 'movieSeats' is not defined You have to use global movieSeats in buttonsMake() to create global variable. BTW: You assing all buttons to the same variable so you have access only to last button. You can keep all buttons on list or send it to redClick as parameter import tkinter as tk # --- functions --- def make_buttons(): for c in range(10): for r in range(3): btn = tk.Button(root, text="Empty") btn['command'] = lambda c=c, r=r, b=btn:red_click(c, r, b) btn.grid(row=r,column=c) def red_click(c, r, btn): btn.configure(bg="red") # --- main --- root = tk.Tk() make_buttons() root.mainloop()
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47733961
type: Answer
accepted answer of: http://stackoverflow.com/q/47733961
downvote count: 0

http://stackoverflow.com/q/47833705
has title: How to correct the 'IOError: [Errno 6]' when I want to get IP address using python script?
upvote count: 1
tagged with: python
answer count: 0
score: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82632569
has body: when I use this python script to get my OSX IP addr,always hit IOError: [Errno 6] Device not configured, and not get the point of this problem. import socket import fcntl import struct def get_ip_address(ifname): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) return socket.inet_ntoa(fcntl.ioctl( s.fileno(), 0x8915, # SIOCGIFADDR struct.pack('256s', ifname[:15]) )[20:24]) get_ip_address('lo') # '127.0.0.1' get_ip_address('eth0') # '38.113.228.130' get_ip_address('ppp0') # '123.163.166.00' thanks for your help. Frank
linked to: http://stackoverflow.com/q/24196932
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/82631041

http://stackoverflow.com/comment/82387142
score: 0
comment on: http://stackoverflow.com/q/47712985
type: Comment
has text: Please try to read your code again and identify simple errors, before posting here. You can use pylint for identify your errors in your python code.
type: QuestionComment

http://stackoverflow.com/q/47851492
tagged with: matplotlib
tagged with: python
accepted answer: http://stackoverflow.com/a/47856091
tagged with: image
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/72393908
answer count: 2
downvote count: 0
linked to: http://stackoverflow.com/q/43132300
has title: Plot curve with blending line colors with matplotlib/pyplot
has answer: http://stackoverflow.com/a/72393908
has answer: http://stackoverflow.com/a/47856091
tagged with: plot
favorite count: 0
type: Question
score: 5
upvote count: 5
tagged with: colors
has body: I want to start the curve with one color and progressively blend into another color until the end. The following function in my MCVE works, but surely, there has to be a better way I haven't found out about, yet?! import numpy as np import matplotlib.pyplot as plt def colorlist(color1, color2, num): """Generate list of num colors blending from color1 to color2""" result = [np.array(color1), np.array(color2)] while len(result) &lt; num: temp = [result[0]] for i in range(len(result)-1): temp.append(np.sqrt((result[i]**2+result[i+1]**2)/2)) temp.append(result[i+1]) result = temp indices = np.linspace(0, len(result)-1, num).round().astype(int) return [result[i] for i in indices] x = np.linspace(0, 2*np.pi, 100) y = np.sin(x) colors = colorlist((1, 0, 0), (0, 0, 1), len(x)) for i in range(len(x)-1): xi = x[i:i+1+1] yi = y[i:i+1+1] ci = colors[i] plt.plot(xi, yi, color=ci, linestyle='solid', linewidth='10') plt.show()

http://stackoverflow.com/comment/82669454
type: AnswerComment
type: Comment
has text: after making your suggested change i receive a `TypeError: string indices must be integers` for this line `date = player_info['competition']['startTime']`
comment on: http://stackoverflow.com/a/47852549
score: 0

http://stackoverflow.com/a/47760052
has comment: http://stackoverflow.com/comment/82481726
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47759947
has body: You can use apply to get the mask, then .loc: y.loc[:, y.apply(lambda col: col.d in myset)] Output: one two a 76 94 b 46 36 c 28 86 d 83 17 e 15 98
score: 2
answers question: http://stackoverflow.com/q/47759947
type: Answer
has comment: http://stackoverflow.com/comment/82481653
upvote count: 2

http://stackoverflow.com/comment/82668785
has text: I tried the base image with python:latest, but I still got the same error.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47848155
type: Comment

http://stackoverflow.com/q/47855781
tagged with: python
has comment: http://stackoverflow.com/comment/82676303
tagged with: xpath
score: 1
answer count: 1
downvote count: 0
tagged with: selenium
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82675700
tagged with: python-3.x
type: AnsweredQuestion
has title: Job navigates to one page and does not count down pages
accepted answer: http://stackoverflow.com/a/47861415
has comment: http://stackoverflow.com/comment/82675689
has answer: http://stackoverflow.com/a/47861415
has body: I'm navigating to all the links on this page, but the page counter is not working. Any idea why that is? I've tried to adjust the xpath in the hopes that would fix the issue. Why is it doing this? driver = webdriver.Chrome() def page_counter(): for x in range(1000): yield x count = page_counter() driver.get('https://www.betfair.com.au/exchange/plus/football') elements = [x.get_attribute("href") for x in driver.find_elements_by_xpath("//nav//a[starts-with(@href, ('football'))]")] shuffle(elements) import operator import collections links = dict((next(count) + 1, e) for e in elements) desc_links = collections.OrderedDict(sorted(links.items(), reverse=True)) for key, value in desc_links.items(): driver.get(value) print('At Page: ' + str(key))
has comment: http://stackoverflow.com/comment/82676370
has comment: http://stackoverflow.com/comment/82676036
has comment: http://stackoverflow.com/comment/82676204

http://stackoverflow.com/a/47756483
accepted answer of: http://stackoverflow.com/q/47756449
score: 4
answers question: http://stackoverflow.com/q/47756449
upvote count: 4
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82474031
has comment: http://stackoverflow.com/comment/82473984
has body: Adding the .values at the end df.iloc[0,:]=df.iloc[0,:][::-1].values df Out[783]: col1 col2 col3 0 1 34 65 1 1 2 3 2 1 2 3
type: Answer

linear-programming
tags question: http://stackoverflow.com/q/47728184
type: Tag
tags question: http://stackoverflow.com/q/47729215
tags question: http://stackoverflow.com/q/47746539
tags question: http://stackoverflow.com/q/47717012
tags question: http://stackoverflow.com/q/47751187
tag name: linear-programming

filtering
tags question: http://stackoverflow.com/q/47746180
tags question: http://stackoverflow.com/q/47769705
tag name: filtering
tags question: http://stackoverflow.com/q/47762379
type: Tag
tags question: http://stackoverflow.com/q/47723737

http://stackoverflow.com/comment/82675929
type: Comment
type: QuestionComment
has text: You haven't actually shown your `groupby` code
comment on: http://stackoverflow.com/q/47855892
score: 1

http://stackoverflow.com/a/47794980
downvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/47794595
score: 0
has body: Python only allows immutable (cannot be changed) data types for 'key' of a dictionary. This would include variables. In this case, running my understanding of your requirement, this is what I get from the python shell.
upvote count: 1

http://stackoverflow.com/q/47802245
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47802342
accepted answer: http://stackoverflow.com/a/47802342
possible better answer: http://stackoverflow.com/a/47802760
tagged with: comparison-operators
has title: Why is OrderedDict not implementing comparison operators
tagged with: python
score: 2
type: AnsweredQuestion
answer count: 2
has answer: http://stackoverflow.com/a/47802760
upvote count: 2
downvote count: 0
linked to: http://stackoverflow.com/q/47797346
has body: Earlier today i asked a question because I was not able to really understand the implementation of comparison operators using rich comparison methods. Thank you, to the accepted answer for well explaining the differences between the two. Basically, from what I understood, Python 3 stopped the use of __cmp__() magic method. From now on, The ordering comparison operators (&lt;, &lt;=, >=, >) raise a TypeError exception when the operands don’t have a meaningful natural ordering. Thus, I thought that OrderedDict would be valid. But, to my surprise, d1 = OrderedDict([(1,1)]) d2 = OrderedDict([(2,2)]) &gt;&gt;&gt; dict1 &lt; dict2 Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: '&lt;' not supported between instances of 'collections.OrderedDict' and 'collections.OrderedDict' &gt;&gt;&gt; dict1.__lt__(dict2) NotImplemented So, why does OrderedDict is not implementing comparison operators ? Note that in the comments of the answer of the linked question, we started to talk on the topic. One thing that was underlined, is why assume insertion order is how you want to compare things? You can always implement your own way to compare them explicitly. Then why (even in Python 3), list1 = [1,2,3] list2 = [4,5,6] &gt;&gt;&gt; list1 &lt; list2 True Isn't a similar situation ?

http://stackoverflow.com/a/47839723
answers question: http://stackoverflow.com/q/47839668
type: Answer
score: 0
has body: I found the answer shortly after posting: include the parameter end='' in the first print statement. for each in rawData['ReservedInstancesOfferings']: print('PDX', ',' , each['InstanceType'], ',' , each['InstanceTenancy'], ',' , each['ProductDescription'], ',' , each['OfferingType'], ',' , each['Duration'], ',' , each['ReservedInstancesOfferingId'], ',' , each['FixedPrice'], ',', end='' ) if not each['RecurringCharges']: print("0.0") else: print(each['RecurringCharges'][0].get('Amount'))

http://stackoverflow.com/q/47840320
favorite count: 0
type: Question
tagged with: python-os
tagged with: glob
linked to: http://stackoverflow.com/q/4568580
has comment: http://stackoverflow.com/comment/82644939
tagged with: python
has comment: http://stackoverflow.com/comment/120188713
has title: Use multiple file extensions for glob to find files
tagged with: filepath
upvote count: 4
has comment: http://stackoverflow.com/comment/82644882
type: AnsweredQuestion
has body: I am using glob to list out all my python files in the home directory by this line of code. I want to find all .json files too along with py files, but I couldn't found any to scan for multiple file types in one line code. for file in glob.glob('/home/mohan/**/*.py', recursive=True): print(file)
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/47840805
tagged with: directory
score: 4
has answer: http://stackoverflow.com/a/47840805

http://stackoverflow.com/a/47762807
upvote count: 0
has body: To simply take rows to columns by using tf.expand_dims() y = tf.placeholder(tf.int32, shape=[None], name='target') y = tf.expand_dims(y,axis=1) However, you have another problem in feeding data as simply adding a dimension to the tensor is not going define its shape, its simply going to add an additional index. This is another question which you can post independently.
downvote count: 1
answers question: http://stackoverflow.com/q/47762055
type: Answer
score: -1

http://stackoverflow.com/q/47786134
tagged with: python
has answer: http://stackoverflow.com/a/47786301
has body: I am trying to install flask and a few other modules for Python2. When I try to install them using command pip install flask, it installs these for Python3. This has created major issues because things like django are not compatible with Python3. When I want to run a program using Python2, I cant use any of these modules. Question How do I use pip to install modules into a specified version of Python?
type: Question
answer count: 2
score: 2
has comment: http://stackoverflow.com/comment/82533423
upvote count: 3
type: UnansweredQuestion
tagged with: pip
has title: install flask for python2 when python 3 is default
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/47786175

deepl
tag name: deepl
type: Tag
tags question: http://stackoverflow.com/q/47731211

http://stackoverflow.com/comment/82531873
score: 0
type: Comment
type: QuestionComment
has text: In original CSV the header is separated by comma.
comment on: http://stackoverflow.com/q/47784761

http://stackoverflow.com/q/47734648
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/82430085
has body: I have a code that the key R and P emits a sound and saves them in a list the times the keys are pressed, my question is how do I change the name of the keys each time they are pressed? Here is a part of the code: from array import array import pygame from pygame.mixer import Sound, get_init, pre_init class Note(pygame.mixer.Sound): def __init__(self,key, frequency, volume=.1): self.frequency = frequency Sound.__init__(self, self.build_samples()) self.set_volume(volume) self.key=key def build_samples(self): period = int(round(get_init()[0] / self.frequency)) samples = array("h", [0] * period) amplitude = 2 ** (abs(get_init()[1]) - 1) - 1 for time in range(period): if time &lt; period / 2: samples[time] = amplitude else: samples[time] = -amplitude return samples def __repr__(self): return 'Note({})'.format(self.key) pre_init(44100, -16, 1, 1024) pygame.init() screen = pygame.display.set_mode([640, 480], 0) sounds = {} keymap = {pygame.K_p: 880, pygame.K_r: 440} key_pressed=[] while True: evt = pygame.event.wait() if evt.type == pygame.QUIT: break elif evt.type == pygame.KEYDOWN: if evt.key in keymap: note = Note(keymap[evt.key]) note.play(-1) sounds[evt.key] = note key_pressed.append(note) elif evt.type == pygame.KEYUP: if evt.key in sounds: sounds.pop(evt.key).stop() print(key_pressed) Image of how the keys come out when pressed
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47734794
score: 1
has title: how to change the name of the keys in pygame?
tagged with: python
tagged with: pygame
has comment: http://stackoverflow.com/comment/82429865
tagged with: python-3.x
type: UnansweredQuestion
answer count: 1

for-loop
tags question: http://stackoverflow.com/q/47847803
tags question: http://stackoverflow.com/q/47710681
tags question: http://stackoverflow.com/q/47822713
tags question: http://stackoverflow.com/q/47700554
tags question: http://stackoverflow.com/q/47802572
tags question: http://stackoverflow.com/q/47802564
tags question: http://stackoverflow.com/q/47702999
tags question: http://stackoverflow.com/q/47727821
tags question: http://stackoverflow.com/q/47852441
tags question: http://stackoverflow.com/q/47793628
tags question: http://stackoverflow.com/q/47719483
tags question: http://stackoverflow.com/q/47717038
tags question: http://stackoverflow.com/q/47750482
tags question: http://stackoverflow.com/q/47704461
tags question: http://stackoverflow.com/q/47777718
tags question: http://stackoverflow.com/q/47698751
tags question: http://stackoverflow.com/q/47835564
tags question: http://stackoverflow.com/q/47731965
type: Tag
tags question: http://stackoverflow.com/q/47768590
tags question: http://stackoverflow.com/q/47800252
tags question: http://stackoverflow.com/q/47740198
tags question: http://stackoverflow.com/q/47743737
tags question: http://stackoverflow.com/q/47825514
tags question: http://stackoverflow.com/q/47717248
tag name: for-loop
tags question: http://stackoverflow.com/q/47780390
tags question: http://stackoverflow.com/q/47780180
tags question: http://stackoverflow.com/q/47750718
tags question: http://stackoverflow.com/q/47745106
tags question: http://stackoverflow.com/q/47762839
tags question: http://stackoverflow.com/q/47824325
tags question: http://stackoverflow.com/q/47848269
tags question: http://stackoverflow.com/q/47705840
tags question: http://stackoverflow.com/q/47700271
tags question: http://stackoverflow.com/q/47801393
tags question: http://stackoverflow.com/q/47719249
tags question: http://stackoverflow.com/q/47733919
tags question: http://stackoverflow.com/q/47699197
tags question: http://stackoverflow.com/q/47705228
tags question: http://stackoverflow.com/q/47790230
tags question: http://stackoverflow.com/q/47854710
tags question: http://stackoverflow.com/q/47823696

http://stackoverflow.com/a/47704242
answers question: http://stackoverflow.com/q/47704137
score: 1
has comment: http://stackoverflow.com/comment/82369356
has comment: http://stackoverflow.com/comment/82368675
type: Answer
has body: You are using a CharField, but if you want a dropdown, you should be using a ChoiceField You are supplying USER_TYPE as a dictionary but choices Either an iterable (e.g., a list or tuple) of 2-tuples to use as choices for this field, or a callable that returns such an iterable. This argument accepts the same formats as the choices argument to a model field. See the model field reference documentation on choices for more details. If the argument is a callable, it is evaluated each time the field’s form is initialized. Defaults to an empty list. https://docs.djangoproject.com/en/1.11/ref/forms/fields/#django.forms.ChoiceField.choices So try something like: USER_TYPE = [ ('admin', "Admin"), ('patient', "Patient"), (..., ...), ]
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/47778392
type: Answer
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47778321
score: 5
has body: You created a new timestamp and put it in the Europe/London timezone. That is not the same thing as UTC. The Europe/London timezone from the PyTZ database includes historical offsets, and those affect how datetime.datetime() interprets the timezone. Just use the datetime.timestamp() method on the datetime object you already parsed from the string: &gt;&gt;&gt; import datetime &gt;&gt;&gt; temp_time1 = datetime.datetime.strptime('2017-12-03T20:38:00.971261Z', '%Y-%m-%dT%H:%M:%S.%fZ') &gt;&gt;&gt; temp_time1.timestamp() 1512333480.971261 Your original temp_time1 datetime object is timezone agnostic, so the timestamp() object already assumes no timezone conversion has to take place. If you must apply the Europe/London timezone first for whatever reason, then at least use the timezone.localize() method to get the right offset applied: &gt;&gt;&gt; import pytz &gt;&gt;&gt; pytz.timezone('Europe/London').localize(temp_time1) datetime.datetime(2017, 12, 3, 20, 38, 0, 971261, tzinfo=&lt;DstTzInfo 'Europe/London' GMT0:00:00 STD&gt;) &gt;&gt;&gt; pytz.timezone('Europe/London').localize(temp_time1).timestamp() 1512333480.971261 See How to make an unaware datetime timezone aware in python For Python 2 and Python 3.0, 3.1 or 3.2, where datetime.timestamp() is not available, subtract the epoch date: &gt;&gt;&gt; (temp_time1 - datetime.datetime(1970, 1, 1)).total_seconds() 1512333480.971261 Add in the UTC timezone when dealing with timezone-aware datetime instances: &gt;&gt;&gt; (pytz.timezone('Europe/London').localize(temp_time1) - datetime.datetime(1970, 1, 1, tzinfo=pytz.utc)).total_seconds() 1512333480.971261 Combined into a function: def datetime_to_timestamp(dt, epoch=datetime.datetime(1970, 1, 1)): if dt.tzinfo is not None: epoch = pytz.utc.localize(epoch) return (dt - epoch).total_seconds()
answers question: http://stackoverflow.com/q/47778321
upvote count: 5

http://stackoverflow.com/comment/82550538
has text: Could you change the function so that it always returns a list? (So `[5]` when it now returns `5`)
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47794440

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

http://stackoverflow.com/comment/82641227
has text: I will give that a go! They are meant to be used on a website, hence the need for the small file size.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47837808

http://stackoverflow.com/comment/82440276
comment on: http://stackoverflow.com/q/47739967
type: Comment
score: 1
type: QuestionComment
has text: Why thumbs down? I really want to know the answer to start developing my app lol...

http://stackoverflow.com/comment/82395237
comment on: http://stackoverflow.com/q/47703942
has text: I am processing satellite images with earth engine ..Earth Engine provides a API with an export2cloudstorage function. I can't set a header. Do you think this could be the problem ? I thought about implementing a function which reads the content in the bucket and write it backs with a header like options={b'x-goog-acl': b'public-read', b'cache-control': b'private, max-age=0, no-cache'})
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82401754
comment on: http://stackoverflow.com/q/47720520
type: Comment
type: QuestionComment
score: 0
has text: I found that from [this](https://stackoverflow.com/questions/47506092/python-requests-get-always-get-404/47506205#comment81981070_47506205) answer and further discussion.

http://stackoverflow.com/comment/82430928
type: QuestionComment
has text: Just a nitpick, it is called a `list` in python, not an `array` :-)
score: 0
comment on: http://stackoverflow.com/q/47735206
type: Comment

http://stackoverflow.com/q/47784652
downvote count: 2
answer count: 1
favorite count: 0
type: Question
has title: How to use python generators in reduce function?
type: AnsweredQuestion
has body: Can someone please help me to understand the execution of this code? from functools import reduce def foo(): for i in range(10): yield i gen = foo() print (gen == 0, gen.__next__ == 0, gen.__next__ == 1, reduce(lambda a,b:a+b, gen)) My questions are the following: What are the multiple print arguments doing? What does gen == 0 mean? Isn't the gen a generator object? Also how is the reduce function remembering what to assign to a and b? And after gen = foo() is called, does execution just switch between the function and the reduce statement? If someone could please map out the functionalities of the generator and the reduce function, that would help a lot! Thanks!
has answer: http://stackoverflow.com/a/47784741
tagged with: reduce
score: -2
tagged with: python
tagged with: generator
upvote count: 0
accepted answer: http://stackoverflow.com/a/47784741

http://stackoverflow.com/q/47740602
tagged with: jupyter
type: AnsweredQuestion
upvote count: 1
downvote count: 0
answer count: 1
has title: Reload common packages in jupyter
has answer: http://stackoverflow.com/a/47740800
accepted answer: http://stackoverflow.com/a/47740800
favorite count: 0
type: Question
tagged with: package
has body: I ran a jupyter notebook experimenting with itertools and accidentally overrode itertools.tee() with None. I then tried to reload itertools (using importlib.reload), didn't work. Tried to reset the variables using %reset, didn't work. (%autoreload obviously won't work because it doesn't involve changes to one of my packages) Only way I can think of to fix this is to reset the jupyter notebook, works. But I ask you, kind, good people of Rome, is this sort of thing justified!? Is there no other way!!??
score: 1
tagged with: python

http://stackoverflow.com/comment/82576438
comment on: http://stackoverflow.com/q/47807271
has text: what is it confused you? len(mylist) = 304?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82610946
has text: The string itself does not have a newline character. It is one big chunk.
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47824148

http://stackoverflow.com/a/47722942
has comment: http://stackoverflow.com/comment/82406514
score: 2
has comment: http://stackoverflow.com/comment/82406858
has comment: http://stackoverflow.com/comment/82406558
type: Answer
answers question: http://stackoverflow.com/q/47722919
has comment: http://stackoverflow.com/comment/82406629
upvote count: 2
downvote count: 0
has body: This is shorter: def method(a,b) if a &lt;= b: a, b = b, a I suppose you could compress it into one line, but I don't know if it counts as more readable: (a,b) = (b,a) if a &lt;= b else (a,b)

http://stackoverflow.com/q/47721929
tagged with: parsing
type: Question
tagged with: stringio
has body: I am working on a project that requires me to get data from a SAP HANA database. I utilized SAP Cloud Connector and PyHDB for the job. I execute my select statement and obtain the result data. One of the fields is a TEXT type, containing large articles. While iterating each row I need to somehow get the data from the TEXT field into a string. However I am only able to get the first 1024 characters. The object that stores the TEXT appears to be a StringIO type. How can I read the entire text data instead of the first 1024 characters only? import pyhdb connection_from = pyhdb.connect( host="localhost", port=00000, user="user", password="password" ) cursor_from = connection_from.cursor() cursor_from.execute('SELECT * FROM SCHEMA.TABLE') results= cursor_from.fetchall() for row in results: text = row[2].data.getvalue() connection_from.close() This is the what the object looks like: NClob I need to get the whole text into a string then print it. Thank you.
type: UnansweredQuestion
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/47726644
has comment: http://stackoverflow.com/comment/82413667
has title: Reading TEXT type from SAP HANA into python
tagged with: hana
tagged with: sql
tagged with: python

http://stackoverflow.com/comment/82678713
has text: Does the container have a healtheck field, when you inspect the container ? `docker inspect <id> --format "{{.Config.Healthcheck}}"` I tried the `HEALTCHECK` line and got after building: `Unknown type "\\" in HEALTHCHECK (try CMD)` After removing the backslash between `start-period` and `CMD` it worked
type: Comment
comment on: http://stackoverflow.com/q/47855615
type: QuestionComment
score: 0

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

http://stackoverflow.com/q/47744558
has comment: http://stackoverflow.com/comment/82449541
type: UnansweredQuestion
has body: I've entered a competition and have answered all the questions except this "Bonus: Elite" question. It has five links, all with the same URL, the only difference being the "clock" part of it. e.g. 1st link = https....clock-pt1 2nd link = https....clock-pt2 etc. When that URL is clicked, it comes up with a code and my plan was to gather these codes together for the validation URL (a separate sixth URL) - https....clock-pts. The problem is that it's programmed so that the contents of the links will change after 10 seconds and that isn't enough time for me to gather all the codes, put it in the validation link to get the answer code. People have told me to use Python Request, but I can't download that because it isn't compatible with my laptop. Can anybody help? If I'm not making sense, let me know (kindly, please)
has comment: http://stackoverflow.com/comment/82449493
tagged with: javascript
tagged with: python
has title: How do I web scrape from 5 different webpages to create a string for a validation url if the content on the pages keeps changing every 10 seconds?
has comment: http://stackoverflow.com/comment/82449518
score: 0
has comment: http://stackoverflow.com/comment/82449810
has comment: http://stackoverflow.com/comment/82449470
answer count: 0
tagged with: web-scraping
type: Question
has comment: http://stackoverflow.com/comment/82449285

http://stackoverflow.com/comment/82415481
type: QuestionComment
score: 0
has text: if there can be different word then you can use `split` because there is alway `, '` before `70` and `');` after `70` - `'''2010-08'''.split(" '", 1)[1].split("'", 1)[0]`
type: Comment
comment on: http://stackoverflow.com/q/47726626

http://stackoverflow.com/a/65211129
accepted answer of: http://stackoverflow.com/q/47797507
upvote count: 3
type: AcceptedAnswer
downvote count: 0
has body: logger.debug("apple is {}".format(apple)) logger.debug(f"apple is {apple}") New-style formatting will always build a string. If this is expensive (e.g. logging a large pandas DataFrame), this will impact performance. logger.debug("apple is %s", apple) Old-style interpolation only builds the logging string if the message will actually end up being logged. If you app's loglevel is one of INFO/WARNING/ERROR/CRITICAL, it will only log messages of at least that loglevel. So this DEBUG-level message would not get logged and the interpolation is skipped. In conclusion, yes, interpolation saves formatting effort (effectively calls to __str__) -- if this actually matters depends on your app.
type: Answer
answers question: http://stackoverflow.com/q/47797507
score: 3

http://stackoverflow.com/comment/82501800
comment on: http://stackoverflow.com/q/47749744
has text: @JunPark : It worked. Have updated the edit you suggested
score: 0
type: Comment
type: QuestionComment

dockerfile
tags question: http://stackoverflow.com/q/47758657
tag name: dockerfile
type: Tag

http://stackoverflow.com/comment/82572955
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47804023
score: 0
has text: Also I am aware of subprocess; but won't fit my needs; since in that way the application will halt for as long as the subprocess is running; which is not ideal too. I think that the only way to go at this point is a custom stdout class; although this means that I won't get any output while the app is running. I am amazed that there is no easy way to get the output of the script via code, so you don't need to rely on the redirection in the shell. Thanks for the suggestions!

http://stackoverflow.com/comment/82454923
type: Comment
has text: That's it! Just simplifies things so it's easier to read.
type: QuestionComment
comment on: http://stackoverflow.com/q/47747299
score: 0

http://stackoverflow.com/q/47729013
has comment: http://stackoverflow.com/comment/82418530
answer count: 3
has answer: http://stackoverflow.com/a/47729249
upvote count: 0
type: UnansweredQuestion
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47729210
has title: How to search a item from a list?
tagged with: python
has answer: http://stackoverflow.com/a/47729209
score: -6
downvote count: 6
has body: Could anyone tell me why this code cannot work, please? list=[5,9,2,5,13] item=input("Please enter the search item.") found=false for search = 0 to list.length -1 if item==list[search]: found= True next search if found==True: print("The item is in the list.") else: print("The item is not in the list.")

http://stackoverflow.com/q/47724525
has comment: http://stackoverflow.com/comment/82409826
tagged with: set
has body: basically, my defines this nodes = ['Unix', 'BSD', 'Linux'] and when I try this print(set(nodes)) I expect the result of it {'Unix', 'BSD', 'Linux'} but I got this {'BSD', 'Linux', 'Unix'} I don't want to break order of nodes is there good way for it?
has answer: http://stackoverflow.com/a/47724839
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82411132
tagged with: python
possible better answer: http://stackoverflow.com/a/47725519
type: Question
has answer: http://stackoverflow.com/a/47725519
tagged with: python-3.x
score: 0
tagged with: list
answer count: 2
has title: Data structure converting order sorting from list to set
has comment: http://stackoverflow.com/comment/82410151
accepted answer: http://stackoverflow.com/a/47724839
has comment: http://stackoverflow.com/comment/82410067

http://stackoverflow.com/a/47798905
has body: Filter the string: source_string='My String' allow_chars=['a','e','i','o','u'] #whatever characters you want to accept source_string_list=list(source_string) source_string_filtered=list(filter(lambda x: x in allow_chars,source_string_list)) the count would be: len(source_string_filtered)
score: 0
answers question: http://stackoverflow.com/q/47798510
type: Answer

http://stackoverflow.com/comment/82568033
type: QuestionComment
comment on: http://stackoverflow.com/q/47803203
score: 0
has text: What would the output be in your example?
type: Comment

http://stackoverflow.com/comment/82608490
type: Comment
has text: @timgeb I've used stackoverflow to supplement CSC my education for a long time. I am using it here to clarify a key semantic with the range() fn I didn't understand and need to before moving forward. If I had just run the interpreter, that wouldn't have really helped me learn; it isn't going to explain any of it (tell me the "why"), it'll just produce an answer I don't understand. I'll continue to use this forum this way, even when some don't support beginners. The community is for everyone.
type: AnswerComment
comment on: http://stackoverflow.com/a/47822757
score: 0

http://stackoverflow.com/a/61401775
has body: The OS module in python provides functions for interacting with the operating system. It could be of use here: import os os.system('scrapy crawl book -o book.json')
downvote count: 3
upvote count: 1
has comment: http://stackoverflow.com/comment/122387554
answers question: http://stackoverflow.com/q/47793131
score: -2
type: Answer

http://stackoverflow.com/comment/82409269
score: 0
type: Comment
type: QuestionComment
has text: now your problem is database, not code in question. Do you have problems when you use this database in Django ?
comment on: http://stackoverflow.com/q/47723790

http://stackoverflow.com/a/47785009
score: 0
answers question: http://stackoverflow.com/q/47782501
has body: I suggest decompose the problem. Right now you're trying to solve several things at once: Upload the file Save the file Parse the file Render a view of the file I'd put 1) and 2) to the side and work on the XSLX loading/viewing part independently. For example, you could hard-code the path of the file in the view and get it rock solid that way. It's just development after all. Once it's good, remove the hard-coded file and connect up the real upload/save logic. Realistically, you'll want to create a model class that represents say UploadedExcelFile. When the file is uploaded, create an instance and save it (i.e. a row in the database). Then you write a view that loads that model instance, which in turn can load the Excel file. You might also want to consider ingesting the file rather than just storing on disk, or using some kind of async approach (e.g. django-q). This depends on a few factors, like what kind of information needs to be extracted from the file, is it editable etc. If it were me, and not knowing the bounds of your system, I'd do something like this: Upload file Store file in a temp area Create a model object (i.e. database row) to represent the file and say the state is "processing". Fire up a django-q job to ingest the file, giving it the filename Return a view to this model. The async job loads the file, parses the relevant aspects to json, stores the data in the model object (i.e. in the database), marks the model state as "ready". The user can reload the page to see the data (or use websockets etc to tell it to reload).
type: Answer

http://stackoverflow.com/comment/82585529
type: Comment
score: 0
type: AnswerComment
has text: yes it is working but only name filed value is printed.
comment on: http://stackoverflow.com/a/47811761

http://stackoverflow.com/q/47823221
has answer: http://stackoverflow.com/a/47823277
upvote count: 0
type: UnansweredQuestion
tagged with: python
score: -1
linked to: http://stackoverflow.com/q/13142347
has answer: http://stackoverflow.com/a/47823294
has comment: http://stackoverflow.com/comment/82609226
answer count: 2
tagged with: llvmlite
has comment: http://stackoverflow.com/comment/82609186
has comment: http://stackoverflow.com/comment/82609159
has title: How to convert my hex address?
has comment: http://stackoverflow.com/comment/92679343
downvote count: 1
has body: I have the following hex number 0x00000000004087b8 and I have to convert this to 0x4087b8 so I would be able to append it to my list. Does anyone have any Idea how can I do this conversion in python?
favorite count: 0
tagged with: hex
type: Question
tagged with: python-3.x

http://stackoverflow.com/q/47808037
tagged with: filter
has answer: http://stackoverflow.com/a/47808799
tagged with: set
upvote count: 1
score: 1
tagged with: string
has answer: http://stackoverflow.com/a/47808334
has comment: http://stackoverflow.com/comment/82577569
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/47808799
has comment: http://stackoverflow.com/comment/82577402
has comment: http://stackoverflow.com/comment/82577329
downvote count: 0
accepted answer: http://stackoverflow.com/a/47808334
tagged with: python
has comment: http://stackoverflow.com/comment/82577500
has title: How to Filter text from a set in Python
has body: I am running through text and I want to save the items that do not contain certain text. The text consists of single words, and multiple words. so far i have: def check_data(text): filter_words = ['subscribe','entertaining'] filter_bigrams = [{'free', 'ticket'}, {'current', 'price'}] for filter in filter_words: if filter in text: return(0) for filter in filter_bigrams: if filter in text: return(0) return(1) mytext = 'free xubscribes tickets now' found = check_data(mytext) print(found) and the error i get it: TypeError: 'in &lt;string&gt;' requires string as left operand, not set In the above filter bigrams does not work. Please help? Thanks
type: AnsweredQuestion
tagged with: list
answer count: 2

http://stackoverflow.com/q/47841525
type: AnsweredQuestion
answer count: 2
accepted answer: http://stackoverflow.com/a/47841633
tagged with: pandas
score: 1
has answer: http://stackoverflow.com/a/47841633
linked to: http://stackoverflow.com/q/47152691
has comment: http://stackoverflow.com/comment/82647866
downvote count: 0
has body: I have a dataframe df of the following type: ID Result Other_val 1 A y 2 B x 2 A x 3 C abc After using pd.crosstab(df.ID, df.Result), I get a crosstab like this: Result A B C ID 1 1 0 0 2 1 1 0 3 0 0 1 I wish to now concatenate these values to the end of my original dataframe (after removing the already present Result column) to get something like this: ID A B C Other_val 1 1 0 0 y 2 1 1 0 x 3 0 0 1 abc However, I am stumped. I can't seem to use pd.concat() to form the above table because of the strange way the cross-tab table is indexed. Any help?
upvote count: 1
has comment: http://stackoverflow.com/comment/82647347
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82647363
tagged with: data-manipulation
has comment: http://stackoverflow.com/comment/82648164
has comment: http://stackoverflow.com/comment/82648167
tagged with: dataframe
tagged with: python
possible better answer: http://stackoverflow.com/a/47841639
has title: Concatenate cross tab values with dataframe?
has answer: http://stackoverflow.com/a/47841639

http://stackoverflow.com/a/47707633
has body: You have something called the reverse generic relation for this purpose: Reverse Generic Relations Add the reverse generic relation to your post model and you can get the count of the number of likes and then order it based on likes for popularity based ordering. In your post model add: likes = GenericRelation(Like) Maybe use annotate for ordering: Post.objects.annotate(like_count=Count('likes')).order_by('-like_count') You would get an additional field 'like_count' for each post object plus it will be ordered based on the number of likes.
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47707377
answers question: http://stackoverflow.com/q/47707377
has comment: http://stackoverflow.com/comment/82982818
has comment: http://stackoverflow.com/comment/82540350
upvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/82573462
score: 2

http://stackoverflow.com/comment/82658537
score: 0
comment on: http://stackoverflow.com/a/47847173
type: Comment
has text: Interesting. Never heard of that before. Thanks @Elisha!
type: AnswerComment

http://stackoverflow.com/q/47756749
type: Question
has comment: http://stackoverflow.com/comment/82475187
has comment: http://stackoverflow.com/comment/82475393
has title: How to find maximum value in the column using pandas?
accepted answer: http://stackoverflow.com/a/47757220
downvote count: 0
answer count: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/82474729
favorite count: 0
has body: This is my code.I will try to read file and find the maximum temperature value(11th column) import pandas as pd fn = 'Excel.xlsx' df = pd.read_excel(fn, header=None) df1 = df.iloc[:,11:12] m1 = df.iloc[:,11:12].max() print (m1) What I got is not want I wanted python n0.py 11 Value dtype: object I will show how the 11-th column looks like 0 Value 1 18.71 2 20.86 3 18.37 4 12.3 5 5.54 6 3.96 7 8.33 8 12.23 9 11.02 10 4.18 11 7.62 12 15.06 13 20 14 20.39 15 18.26 16 14.54 17 3.81 18 0.93 19 7.74 20 12.42 21 6.59 22 0.12 23 8.32 24 16.82 25 19.46 26 11.8 27 6.25 28 1.96 29 17.13 ... 756 15.59 757 6.82 758 7.48 759 14.99 760 17.61 761 19.48 762 16.8 763 9.65 764 1.63 765 9.26 766 16.25 767 24.85 768 14.08 769 0.11 770 6.56 771 12.75 772 21.94 773 20.57 774 17.97 775 12.73 776 6.16 777 9.12 778 19.03 779 17.39 780 14.06 781 1.76 782 8.25 783 17.41 784 20.61 785 20.73 From these values 24.85 would be the max and it is on 767 position. I have not worked with pandas lately but this was supposed to be simple job. Where is my mistake? Should I use idmax or something else?
type: AnsweredQuestion
tagged with: pandas
score: 1
has answer: http://stackoverflow.com/a/47757220
tagged with: python

http://stackoverflow.com/q/47730500
answer count: 2
tagged with: seaborn
tagged with: python
possible better answer: http://stackoverflow.com/a/47734966
has answer: http://stackoverflow.com/a/47730817
accepted answer: http://stackoverflow.com/a/47730817
tagged with: heatmap
type: AnsweredQuestion
score: 3
upvote count: 3
tagged with: matplotlib
has body: I'm trying to get a heatmap using seaborn in python. Unfortunately it is not using scientific notation even though the numbers are very large. I was wondering if there's any simple way to convert to scientific notation or any other reasonable format. Here's a piece of code that shows the problem: import seaborn as sns import numpy as np C_vals = np.logspace(3, 10, 8) g_vals = np.logspace(-6, 2, 9) score = np.random.rand(len(g_vals), len(C_vals)) sns.heatmap(score, xticklabels=C_vals, yticklabels=g_vals) The resulting plot is the following
downvote count: 0
has answer: http://stackoverflow.com/a/47734966
favorite count: 0
type: Question
has title: How to use scientific notation in seaborn heatmap labels?
tagged with: format

http://stackoverflow.com/a/47731333
type: Answer
answers question: http://stackoverflow.com/q/47726778
downvote count: 0
has comment: http://stackoverflow.com/comment/105299165
has comment: http://stackoverflow.com/comment/88993150
upvote count: 9
score: 9
has body: I guess what you want is modify exit status of pytest command, there is a nonpublic hook, named pytest_sessionfinish, could do this. consider you have following tests: def test_spam(): assert 0 def test_ham(): pass def test_eggs(): pass and a hook in conftest.py: import pytest, _pytest ACCEPTABLE_FAILURE_RATE = 50 @pytest.hookimpl() def pytest_sessionfinish(session, exitstatus): if exitstatus != _pytest.main.EXIT_TESTSFAILED: return failure_rate = (100.0 * session.testsfailed) / session.testscollected if failure_rate &lt;= ACCEPTABLE_FAILURE_RATE: session.exitstatus = 0 then invoke pytest: $ pytest --tb=no -q tests.py F.. [100%] 1 failed, 2 passed in 0.06 seconds here the failure rate is 1 / 3 == 33.3%, below 50%: $ echo $? 0 you could see the exit status of pytest is 0.
has comment: http://stackoverflow.com/comment/88992956

http://stackoverflow.com/comment/82634264
score: 0
has text: How are you achieving the total amount of money for each person? Are you summing the amounts for each child the person has?
comment on: http://stackoverflow.com/q/47835260
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82603416
comment on: http://stackoverflow.com/a/47820455
type: Comment
has text: have to wait 2 minutes ;) btw another problem appeared meanwhile, the input results are being displayed all on top of each other, do you know how to stop that from happening? (screenshot: https://gyazo.com/b8ed1218674eb610c2882b7eba936bae)
type: AnswerComment
score: 0

http://stackoverflow.com/a/47759047
has comment: http://stackoverflow.com/comment/82479578
has comment: http://stackoverflow.com/comment/82480113
has comment: http://stackoverflow.com/comment/82479537
has comment: http://stackoverflow.com/comment/82479401
downvote count: 0
has body: Use numpy.unique because DatetmeIndex.strftime return numpy array: rng = pd.date_range('9/1/2017', '12/31/2017') print (np.unique(rng.strftime('%m/%Y')).tolist()) ['09/2017', '10/2017', '11/2017', '12/2017'] If input is column of DataFrame use Anton vBR's solution: print(df['date'].dt.strftime("%m/%y").unique().tolist()) Or drop_duplicates: print(df['date'].dt.strftime("%m/%y").drop_duplicates().tolist()) Timings: All solution have same performance - unique vs drop_duplicates: rng = pd.date_range('9/1/1900', '12/31/2017') df = pd.DataFrame({'date': rng}) In [54]: %timeit (df['date'].dt.strftime("%m/%y").unique().tolist()) 1 loop, best of 3: 469 ms per loop In [56]: %timeit (df['date'].dt.strftime("%m/%y").drop_duplicates().tolist()) 1 loop, best of 3: 466 ms per loop
score: 9
upvote count: 9
answers question: http://stackoverflow.com/q/47759009
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/82480068
has comment: http://stackoverflow.com/comment/82479516
accepted answer of: http://stackoverflow.com/q/47759009

http://stackoverflow.com/q/47779169
favorite count: 0
type: Question
tagged with: http://stackoverflow.com/tag/json
has answer: http://stackoverflow.com/a/47779305
tagged with: python
has comment: http://stackoverflow.com/comment/82519877
tagged with: uwsgi
score: 2
linked to: http://stackoverflow.com/q/489861
has title: uWSGI Workers writing to same JSON File
upvote count: 2
type: UnansweredQuestion
tagged with: multithreading
downvote count: 0
answer count: 1
has body: I have a Python flask API wrapped with uWSGI+Nginx for production setup. I have 4 Nginx workers and 1 thread per worker configured as follows, processes = 4 threads = 1. When I issue an API Post, the post writes and reads a json file at different parts of my code. When I issue multiple API requests in parallel , it gets distributed to these 4 Nginx workers as expected. And they go ahead and process the request in parallel. Sometimes this causes json ValueErrors as multiple processes are reading and writing to the same file. How do I overcome this scenario? This is not multiprocessing within my API. So using python's multiprocessing Lock within my json update code will not fix my problem. I want to be able to update the json files one worker at a time. Is there a way to share locks within uwsgi workers?
tagged with: flask
duplicate of: http://stackoverflow.com/q/489861

http://stackoverflow.com/comment/82546164
has text: @cᴏʟᴅsᴘᴇᴇᴅ I thought they were and have removed them...I tried a lot of troubleshooting before posting here and that was just on step haha :) Thanks for confirming that for me.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47792415

http://stackoverflow.com/comment/82625570
score: 0
comment on: http://stackoverflow.com/q/47831379
has text: Are you even aware of the tags that you are using?
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47807533
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/129372997
downvote count: 0
answers question: http://stackoverflow.com/q/47807446
type: Answer
has body: import datetime lista = [('Lebron James', datetime.date(2017, 12, 23), 500), ('Julie Peralta', datetime.date(2017, 12, 13), 1500), ('Reynaldo Pahay', datetime.date(2017, 12, 11), 2500)] output = [{"name":a[0], "date":a[1],'penalty':a[2]} for a in lista] print(output)

http://stackoverflow.com/comment/82406629
score: 0
comment on: http://stackoverflow.com/a/47722942
type: Comment
has text: Forgive this Python beginner question - what is the point of switching equal values?
type: AnswerComment

http://stackoverflow.com/q/47783463
has comment: http://stackoverflow.com/comment/82568304
type: Question
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82528714
answer count: 1
tagged with: python
has answer: http://stackoverflow.com/a/47783564
has title: What options in python to define your primary unix group for file/folder/links to be created?
has body: EDITED on Dec.13th 3:00PM PST: I have a python3 program that I used pyinstaller to packaged into an executable before deploying. This program will allow an admin-group of users to setup/package an environment based on data that is in a restricted environment. I have the followings: Because it is access to a restricted area, the executable is owned by "app-admin" and will be run as "app-admin". This was achieved via setuid. The script should only be allowed to run by group: "app-administrators"; so I have the group ownership of this script as app-administrators. So, I have the below when I do a ls -l: -rwsr-s--- 1 app-admin app-administrators 10926616 Nov 1 11:38 myscript Part of the operation of the myscript will be creating file, symlinks and folders; I like the group owner for those objects to be group "app-users". The app-admin belongs to many groups including "app-administrators", "app-users" and other at the moment. What are my options to do that programmatically? Maybe what I did so far is incorrect? I am currently looking at the 2 approaches: Approach 1: run os.chown right after the creation, but I don't like the overhead. Approach 2: Use subprocess.call() and execute the unix command usermode to change the primary group in the beginning of my python script. Thanks.
score: 0

http://stackoverflow.com/comment/82630185
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47823973
type: AnswerComment
has text: That works, though would it be the correct way to do it? Since now I am just moving all the init stuff outside

http://stackoverflow.com/comment/82403726
has text: when I delete the 0.0 and 0 of the entrys to put other values //// Exception in Tkinter callback Traceback (most recent call last): File "C:\Python36-32\lib\tkinter\__init__.py", line 505, in get return self._tk.getint(value) _tkinter.TclError: expected integer but got ""
comment on: http://stackoverflow.com/a/47721118
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/a/47944769
answers question: http://stackoverflow.com/q/47773827
has body: I think I found out the reason. I have to close the logger properly. so my code for closing a logger is... handlers = logger.handlers[:] #close logger for handler in handlers: handler.flush() handler.close() logger.removeHandler(handler) # was not removing handler logging.shutdown() Please correct me if I am wrong. Thank you @Treyten Carey
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47773827
type: Answer

arrays
tags question: http://stackoverflow.com/q/47703022
tag name: arrays
tags question: http://stackoverflow.com/q/47740020
tags question: http://stackoverflow.com/q/47804141
tags question: http://stackoverflow.com/q/47788110
tags question: http://stackoverflow.com/q/47838811
tags question: http://stackoverflow.com/q/47703598
tags question: http://stackoverflow.com/q/47735074
tags question: http://stackoverflow.com/q/47836242
tags question: http://stackoverflow.com/q/47848525
tags question: http://stackoverflow.com/q/47763061
tags question: http://stackoverflow.com/q/47801152
tags question: http://stackoverflow.com/q/47708471
tags question: http://stackoverflow.com/q/47737602
tags question: http://stackoverflow.com/q/47752233
tags question: http://stackoverflow.com/q/47713659
tags question: http://stackoverflow.com/q/47796207
tags question: http://stackoverflow.com/q/47846438
type: Tag
tags question: http://stackoverflow.com/q/47822873
tags question: http://stackoverflow.com/q/47755979
tags question: http://stackoverflow.com/q/47756555
tags question: http://stackoverflow.com/q/47826874
tags question: http://stackoverflow.com/q/47845327
tags question: http://stackoverflow.com/q/47710467
tags question: http://stackoverflow.com/q/47813091
tags question: http://stackoverflow.com/q/47785237
tags question: http://stackoverflow.com/q/47814557
tags question: http://stackoverflow.com/q/47830763
tags question: http://stackoverflow.com/q/47821540
tags question: http://stackoverflow.com/q/47802480
tags question: http://stackoverflow.com/q/47846569
tags question: http://stackoverflow.com/q/47807144
tags question: http://stackoverflow.com/q/47793591
tags question: http://stackoverflow.com/q/47783476
tags question: http://stackoverflow.com/q/47828625
tags question: http://stackoverflow.com/q/47848534
tags question: http://stackoverflow.com/q/47738833
tags question: http://stackoverflow.com/q/47736326
tags question: http://stackoverflow.com/q/47819146
tags question: http://stackoverflow.com/q/47785229
tags question: http://stackoverflow.com/q/47749459
tags question: http://stackoverflow.com/q/47791116
tags question: http://stackoverflow.com/q/47771401
tags question: http://stackoverflow.com/q/47755025
tags question: http://stackoverflow.com/q/47833749
tags question: http://stackoverflow.com/q/47785835
tags question: http://stackoverflow.com/q/47837093
tags question: http://stackoverflow.com/q/47815329
tags question: http://stackoverflow.com/q/47764893
tags question: http://stackoverflow.com/q/47749796
tags question: http://stackoverflow.com/q/47776176
tags question: http://stackoverflow.com/q/47754122
tags question: http://stackoverflow.com/q/47724273
tags question: http://stackoverflow.com/q/47751253
tags question: http://stackoverflow.com/q/47813444
tags question: http://stackoverflow.com/q/47781076
tags question: http://stackoverflow.com/q/47796886
tags question: http://stackoverflow.com/q/47817537
tags question: http://stackoverflow.com/q/47846013
tags question: http://stackoverflow.com/q/47774660
tags question: http://stackoverflow.com/q/47777497
tags question: http://stackoverflow.com/q/47743615
tags question: http://stackoverflow.com/q/47777148
tags question: http://stackoverflow.com/q/47812635
tags question: http://stackoverflow.com/q/47826446
tags question: http://stackoverflow.com/q/47823335
tags question: http://stackoverflow.com/q/47783829
tags question: http://stackoverflow.com/q/47767546
tags question: http://stackoverflow.com/q/47774453
tags question: http://stackoverflow.com/q/47750639
tags question: http://stackoverflow.com/q/47847389
tags question: http://stackoverflow.com/q/47762639
tags question: http://stackoverflow.com/q/47752324
tags question: http://stackoverflow.com/q/47764984
tags question: http://stackoverflow.com/q/47804572
tags question: http://stackoverflow.com/q/47721464
tags question: http://stackoverflow.com/q/47835565
tags question: http://stackoverflow.com/q/47848500
tags question: http://stackoverflow.com/q/47799875

http://stackoverflow.com/q/47738451
has title: How to create new column in excel sheet with corresponding values
type: Question
has comment: http://stackoverflow.com/comment/82437984
tagged with: dataframe
tagged with: python
has body: I have an excel sheet and another like this I want to add the aisle_id in the first sheet according to the product_id like this I need help for doing this preferably using python dataframes or sql server
score: 2
upvote count: 2
type: AnsweredQuestion
downvote count: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/47738854
answer count: 1
accepted answer: http://stackoverflow.com/a/47738854
has comment: http://stackoverflow.com/comment/82437174
tagged with: excel
favorite count: 0

http://stackoverflow.com/comment/88749491
comment on: http://stackoverflow.com/q/47703695
score: 0
has text: Possible duplicate of [How to enable X11 forwarding in PyCharm SSH session?](https://stackoverflow.com/questions/41892039/how-to-enable-x11-forwarding-in-pycharm-ssh-session)
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82500589
has text: How does that answer the question exactly ?
type: Comment
comment on: http://stackoverflow.com/a/47769736
type: AnswerComment
score: 0

http://stackoverflow.com/a/47851923
has body: Product name, image, price: import urllib.request from bs4 import BeautifulSoup url='https://fr.aliexpress.com/category/205000316/men-clothing-accessories.html' headers = {} headers['User-Agent'] = "Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:48.0) Gecko/20100101 Firefox/48.0,Mozilla/5.0 (Windows NT 6.3; rv:36.0) Gecko/20100101 Firefox/36.0',Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10; rv:33.0) Gecko/20100101 Firefox/33.0',Mozilla/5.0 (compatible, MSIE 11, Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko',Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; EN; rv:11.0) like Gecko',Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)',Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/5.0)',Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.75.14 (KHTML, like Gecko) Version/7.0.3 Safari/7046A194A'" req = urllib.request.Request(url, headers = headers) html = urllib.request.urlopen(req).read() soup = BeautifulSoup(html.decode('utf8', 'ignore'), "html.parser") products = soup.find_all('div', class_='item') for item in products: print(' item:', item.find(class_='info').find("a").text) print('price:', item.find(class_="price").find(class_='value').text) print('image:', item.find(class_="pic").find("img")['src']) print('--') Result: item: Rocksir punisher t chemises pour hommes t-shirt Coton de mode marque t shirt hommes Casual Manches Courtes le punisher T-shirt h... price: € 12,05 - 12,92 image: //ae01.alicdn.com/kf/HTB1ByVZSpXXXXcxaXXXq6xXFXXXW/New-Design-Male-Novelty-Men-T-shirt-Fashion-Cotton-O-neck-Hip-Hop-T-shirt-.jpg_220x220.jpg -- item: DIFFELEMENT 2017 Nouveau style long Manteau Hommes marque vêtements mode Long Vestes Manteaux marque-vêtements hommes Pardessus ... price: € 44,82 image: //ae01.alicdn.com/kf/HTB12IqMXEAKL1JjSZFkq6y8cFXa2/DIFFELEMENT-2017-New-style-long-Coat-Men-brand-clothing-fashion-Long-Jackets-Coats-brand-clothing-mens.jpg_220x220.jpg --
type: Answer
score: 0
answers question: http://stackoverflow.com/q/47851832

python-3.x
tags question: http://stackoverflow.com/q/47730524
tags question: http://stackoverflow.com/q/47773461
tags question: http://stackoverflow.com/q/47776068
tags question: http://stackoverflow.com/q/47735214
tags question: http://stackoverflow.com/q/47704301
tags question: http://stackoverflow.com/q/47817800
tags question: http://stackoverflow.com/q/47724994
tags question: http://stackoverflow.com/q/47833578
tags question: http://stackoverflow.com/q/47775392
tags question: http://stackoverflow.com/q/47789564
tags question: http://stackoverflow.com/q/47702625
tags question: http://stackoverflow.com/q/47782924
tags question: http://stackoverflow.com/q/47758248
tags question: http://stackoverflow.com/q/47720824
tags question: http://stackoverflow.com/q/47749438
tags question: http://stackoverflow.com/q/47724459
tags question: http://stackoverflow.com/q/47731457
tags question: http://stackoverflow.com/q/47759491
tags question: http://stackoverflow.com/q/47841510
tags question: http://stackoverflow.com/q/47813448
tags question: http://stackoverflow.com/q/47776577
tags question: http://stackoverflow.com/q/47738537
tags question: http://stackoverflow.com/q/47788448
tags question: http://stackoverflow.com/q/47733599
tags question: http://stackoverflow.com/q/47822402
tags question: http://stackoverflow.com/q/47826517
tags question: http://stackoverflow.com/q/47844949
tags question: http://stackoverflow.com/q/47731409
tags question: http://stackoverflow.com/q/47814765
tags question: http://stackoverflow.com/q/47710694
tags question: http://stackoverflow.com/q/47814864
tags question: http://stackoverflow.com/q/47698221
tags question: http://stackoverflow.com/q/47780384
tags question: http://stackoverflow.com/q/47796867
tags question: http://stackoverflow.com/q/47732891
tags question: http://stackoverflow.com/q/47743936
tags question: http://stackoverflow.com/q/47780379
tags question: http://stackoverflow.com/q/47741844
tags question: http://stackoverflow.com/q/47784668
tags question: http://stackoverflow.com/q/47708771
tags question: http://stackoverflow.com/q/47722877
tags question: http://stackoverflow.com/q/47841056
tags question: http://stackoverflow.com/q/47765236
tags question: http://stackoverflow.com/q/47838558
tags question: http://stackoverflow.com/q/47843036
tags question: http://stackoverflow.com/q/47776516
tags question: http://stackoverflow.com/q/47800655
tags question: http://stackoverflow.com/q/47727170
tags question: http://stackoverflow.com/q/47732419
tags question: http://stackoverflow.com/q/47755844
tags question: http://stackoverflow.com/q/47822635
tags question: http://stackoverflow.com/q/47850817
tags question: http://stackoverflow.com/q/47787213
tags question: http://stackoverflow.com/q/47712425
tags question: http://stackoverflow.com/q/47849837
tags question: http://stackoverflow.com/q/47727371
tags question: http://stackoverflow.com/q/47741833
tags question: http://stackoverflow.com/q/47815762
tags question: http://stackoverflow.com/q/47841991
tags question: http://stackoverflow.com/q/47850992
tags question: http://stackoverflow.com/q/47819741
tags question: http://stackoverflow.com/q/47724740
tags question: http://stackoverflow.com/q/47775661
tags question: http://stackoverflow.com/q/47817819
tags question: http://stackoverflow.com/q/47821229
tags question: http://stackoverflow.com/q/47738003
tags question: http://stackoverflow.com/q/47767259
tags question: http://stackoverflow.com/q/47705882
tags question: http://stackoverflow.com/q/47772976
tags question: http://stackoverflow.com/q/47710581
tags question: http://stackoverflow.com/q/47776486
tags question: http://stackoverflow.com/q/47823941
tags question: http://stackoverflow.com/q/47781523
tags question: http://stackoverflow.com/q/47843453
tags question: http://stackoverflow.com/q/47853248
tags question: http://stackoverflow.com/q/47748918
tags question: http://stackoverflow.com/q/47827174
tags question: http://stackoverflow.com/q/47723011
tags question: http://stackoverflow.com/q/47781460
tags question: http://stackoverflow.com/q/47851127

http://stackoverflow.com/q/47838632
upvote count: 13
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47838688
downvote count: 0
has comment: http://stackoverflow.com/comment/82641125
tagged with: django-forms
possible better answer: http://stackoverflow.com/a/57871810
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47838688
has title: Django - Adding password validations in a ModelForm
has answer: http://stackoverflow.com/a/57871810
answer count: 2
has comment: http://stackoverflow.com/comment/82641151
has comment: http://stackoverflow.com/comment/82641610
has body: I have made a ModelForm in Django for the registration of a new user. It has 4 fields (username, email, password, and confirm_password). I want to add some validations for the password field. For example, if the password is shorter than 8 characters or the password is similar to the username, then raise an error message. How can I do this? Here is my forms.py file: from django.contrib.auth.models import User from django import forms class user_form(forms.ModelForm): password = forms.CharField(widget = forms.PasswordInput) confirm_password = forms.CharField(widget = forms.PasswordInput) class Meta: model = User fields = ['username','email', 'password','confirm_password'] My settings.py already contains the following validators: AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimila‌​rityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValida‌​tor', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValid‌​ator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordVali‌​dator', } ] It's already in settings.py, but my form's password is not being validated.
tagged with: django
score: 13

http://stackoverflow.com/q/47732165
tagged with: python
has body: I'm writing a regular expression code to extract items from a SQL statement. I want to pull out a tuple of the items after SELECT * FROM and WHERE statements. pattern = ''' SELECT\s\*\sFROM\s ([a-zA-Z\s*\,*\=\.]+) \sWHERE \s*([a-zA-Z\d*\s*\,*\=*\.*]+)''' From the pattern above, I'm using it for the SQL statement below, and get the following results: ('A, B, C\n ', 'A.ColA = B.ColB AND B.ColB2=C.ColC') I know it's because of the huge break before the WHERE, but how do I factor that in and get rid of the huge space and /n after my first tuple? q = """SELECT * FROM A, B, C WHERE A.ColA = B.ColB AND B.ColB2=C.ColC"""
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/47732195
has answer: http://stackoverflow.com/a/47732195
answer count: 1
type: Question
has title: Regular Expression python sql statements

http://stackoverflow.com/comment/82424563
type: QuestionComment
has text: @skrx oh. sorry. Not very learned in stack exchange etiquette yet. Ill work on a more concise example right now
comment on: http://stackoverflow.com/q/47726023
score: 1
type: Comment

http://stackoverflow.com/a/47821531
has comment: http://stackoverflow.com/comment/82605677
answers question: http://stackoverflow.com/q/47821346
has comment: http://stackoverflow.com/comment/94406178
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47821346
upvote count: 1
has body: At the moment (Dec 2017), there is no built-in support for passing a Pyomo model to scipy.optimize. That said, it would not be a very difficult task to write a reasonably general purpose object that could generate the necessary (value, Jacobian, Hessian) evaluation functions to pass to scipy.optimize.minimize().
has comment: http://stackoverflow.com/comment/82605966
score: 1
type: Answer

http://stackoverflow.com/comment/82520304
has text: I don't think this is what the OP wants. It's not about the validity of the URL, it is about the content. He wants to avoid scraping a series of URL's that he knows will not yield any results
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47779320

http://stackoverflow.com/comment/82358320
comment on: http://stackoverflow.com/q/47698721
type: Comment
type: QuestionComment
score: 0
has text: @ctwheels: Yes, and it's an output. If I did omj, dataframe again, my output will still be obik.

http://stackoverflow.com/comment/87797792
comment on: http://stackoverflow.com/a/47788734
has text: @Nitish without a complete view of your code I cannot help you. If you have a persistent problem, consider creating a new question with details.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/47834045
has body: I am currently pulling some data from SQL Server via python, Using the below: import pyodbc data = [] con = pyodbc.connect('Trusted_Connection=yes', driver = '{SQL Server}',server = 'bhxsql2014-dev', database = 'BMAnalytics') cursor = con.cursor() cursor.execute(" select * from dbo.EUActiveStores ") for columns in cursor.fetchall(): data.append(columns[0:]) print(data) It returns data in the following format (Top 2 rows as sample): [(1.0, 'Bradford', 'Main', 1.0, 'UK', 850.3489216, 79.0, 'Sharon Watson', 'Malcolm Bateman', 0.0, '199446', 199602.0, 'ST1', 1201.0, '12', 53.794851, -1.755584, 'COMP', 'Main', 'MALL', None), (4.0, 'EASTBOURNE', 'Main', 1.0, 'UK', 646.9788276755199, 60.10629999999999, 'Jocelyn Hill', 'Andrea Varley', 0.0, '199642', 199750.0, 'ST1', 1304.0, '13', 50.7696, 0.2859, 'COMP', 'Main', 'MALL', None), Seems each Row is contained within parenthesis, and separated by a comma. I have no idea how to turn this into a data frame, any advice ?
accepted answer: http://stackoverflow.com/a/47834064
has answer: http://stackoverflow.com/a/47834064
tagged with: sql-server
has title: Turn a List into a Data frame PYTHON - SQL
tagged with: pandas
type: AnsweredQuestion
score: 1
possible better answer: http://stackoverflow.com/a/47834111
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/47834111
type: Question
upvote count: 2
answer count: 2
tagged with: dataframe
tagged with: python

http://stackoverflow.com/a/47854670
type: Answer
answers question: http://stackoverflow.com/q/47854635
score: 15
downvote count: 0
has comment: http://stackoverflow.com/comment/136269845
has body: Just use the decimal module: &gt;&gt;&gt; from decimal import * &gt;&gt;&gt; Decimal(10**2000).sqrt() Decimal('1.000000000000000000000000000E+1000') &gt;&gt;&gt; Decimal(10**200000).sqrt() Decimal('1.000000000000000000000000000E+100000') &gt;&gt;&gt; Decimal(15**35315).sqrt() Decimal('6.782765081358674922386659760E+20766') You can also use the gmpy2 library. &gt;&gt;&gt; import gmpy2 &gt;&gt;&gt; n = gmpy2.mpz(99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999982920000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000726067) &gt;&gt;&gt; gmpy2.get_context().precision=2048 &gt;&gt;&gt; x = gmpy2.sqrt(n) Useful links: Decimal - Python Documentation
upvote count: 15
has comment: http://stackoverflow.com/comment/82678106
has comment: http://stackoverflow.com/comment/136266720

http://stackoverflow.com/comment/82400489
comment on: http://stackoverflow.com/q/47719838
score: 0
has text: @ChrisCharles Just now i tried the same one. still not catching the exception
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82537920
comment on: http://stackoverflow.com/q/47769818
has text: It's slow because you're looping through each row 3 times!!
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/50456589
upvote count: 18
has body: Comment out the #'django.contrib.auth.middleware.SessionAuthenticationMiddleware', in your settings.py file in Middleware
answers question: http://stackoverflow.com/q/47800726
downvote count: 0
has comment: http://stackoverflow.com/comment/89461718
score: 18
type: Answer

http://stackoverflow.com/comment/82470128
comment on: http://stackoverflow.com/q/47754759
has text: I think you are looking for `np.where`
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/comment/82413009
comment on: http://stackoverflow.com/a/47726068
type: AnswerComment
has text: @nimbus7 You're welcome! Also see my second edit - you should probably just save the data from the API directly into the file, there's no need to actually parse the JSON inside your loop unless you need to do other things with it as well. It will load correctly.
score: 1
type: Comment

http://stackoverflow.com/comment/82567240
comment on: http://stackoverflow.com/a/47802897
has text: Oh thats totally my bad. I meant to keep duplicates! Oops! But that is awesome, that's exactly what I was looking for. Thanks! (I'll edit my question to get rid of my little mistake)
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/82607963
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47821861
has text: no i dont have excel so i just made that dataframe from you and have made edit to the answer to read the data from csv
score: 0

http://stackoverflow.com/comment/82531819
type: Comment
type: AnswerComment
has text: Thanks it solved the first problem, do you have a suggestion for the second problem?
comment on: http://stackoverflow.com/a/47784861
score: 0

http://stackoverflow.com/comment/82604661
comment on: http://stackoverflow.com/q/47819741
score: 0
type: Comment
has text: You could just do the sane thing and check this condition outside of `__init__`, and set the object to `None` if the condition is not satisfied.
type: QuestionComment

http://stackoverflow.com/comment/82647326
type: Comment
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/47841510
has text: The brackets are irrelevant. In Python2 `print('done')` is `print ('done')` which is `print 'done'`.

http://stackoverflow.com/q/47817800
tagged with: beautifulsoup
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/82598038
tagged with: http://stackoverflow.com/tag/html
answer count: 1
has comment: http://stackoverflow.com/comment/82598867
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82599289
has comment: http://stackoverflow.com/comment/82597461
has body: I have this little project to web scrape a website. I completed another website for a competitor but I am having a hard time with the current one. What the code is currently doing is creating a csv file (which is what I want), and in the csv file, I have the headers shown, but no data under it. Can someone help me with my for loop script. I believe it's not capturing the data in order to write it into the csv file. Thank you for your help. Below is the python script: from urllib.request import urlopen as uReq from bs4 import BeautifulSoup as soup # setting my_url to the wesite urls = ['https://www.extraspace.com/Storage/Facilities/US/North_Carolina/Charlotte/1000000398/Facility.aspx' , 'https://www.extraspace.com/Storage/Facilities/US/North_Carolina/Charlotte/1000000404/Facility.aspx'] #https://www.extraspace.com/Storage/Facilities/US/North_Carolina/Charlotte/1000000398/Facility.aspx?cid=org::maps&utm_source=google&utm_medium=organic&utm_campaign=org::maps filename = "extraspace.csv" open(filename, 'w').close() f = open(filename, "a") num = 0 headers = "unit_size, size_dim1, unit_type, online_price, reg_price, street_address, store_city, store_postalcode\n" f.write(headers) for my_url in urls: # Opening up connection, grabbing the page uClient = uReq(my_url) # naming uClient to page_html page_html = uClient.read() # closing uClient uClient.close() # this does my html parsing page_soup = soup(page_html, "html.parser") # setting container to capture where the actual info is using inspect element #----- ==$0 -------this is body of each unit container #----- ==$0 -------this is body of each unit container #grabs each product containers = page_soup.findAll("div", {"itemprop": "makesOffer"}) #----- ==$0 -----this is body of address #grabs address store_locator = page_soup.findAll("div", {"itemprop": "address"}) f.write("website " + str(num) + ": \n") for container in containers: for store_location in store_locator: street_address = store_location.findAll("span", {"itempro…
tagged with: web-scraping
tagged with: python
has answer: http://stackoverflow.com/a/47819017
accepted answer: http://stackoverflow.com/a/47819017
has title: Python Web Scrape - For Loop Issue

http://stackoverflow.com/q/47840786
tagged with: python
accepted answer: http://stackoverflow.com/a/47841435
tagged with: crud
type: AnsweredQuestion
has body: I am trying to implement simple CRUD operation in Django Rest. I have successfully created, GET and POST . Now, I want to update the row data with PUT and delete a row with DELETE. Currently, my table looks like :- id item_1 item_2 item_3 date_created date_modified 1 test1 test2 test3 16-12-2017 16-12-2017 2 ex1 ex2 ex3 16-12-2017 16-12-2017 API End point :- localhost/itemlist If we GET localhost/itemlist it returns the list of items. If we POST localhost/itemlist with fields item_1, item_2, item_3 , it creates the row. Now, I want to use PUT to update a particular row. Like, if I want to update the value of item_3 where item_1 == "test1" DELETE should delete the row where item_1 == ex1 urls.py from django.conf.urls import url, include from rest_framework.urlpatterns import format_suffix_patterns from .views import ItemView urlpatterns = { url(r'^itemlists/$', ItemView.as_view(), name="create"), } urlpatterns = format_suffix_patterns(urlpatterns) views.py : from rest_framework import generics from .serializers import itemlistSerializer from .models import itemlist class ItemView(generics.ListCreateAPIView): queryset = itemlist.objects.all() serializer_class = itemlistSerializer def perform_create(self, serializer): serializer.save() serializers.py from rest_framework import serializers from .models import itemlist class itemlistSerializer(serializers.ModelSerializer): class Meta: """Meta class to map serializer's fields with the model fields.""" model = itemlist fields = ('id', 'item_1', 'item_2', 'item_3', 'date_created', 'date_modified') read_only_fields = ('date_created', 'date_modified') models.py from django.db import models class itemlist(models.Model): """This class represents the itemlist model.""" item_1 = models.CharField(max_length=255, blank=True, unique=False) item_2 = models.CharField(max_length=255, blank=True, unique=False) item_3 = models.CharField(max_length=255, blank=True, unique=False) date_created = models.DateTimeField(auto_now_add=True) date_…
has answer: http://stackoverflow.com/a/47841435
score: 0
answer count: 1
type: Question
tagged with: rest
has title: UPDATE and DELETE Operation in Python Django REST
tagged with: django

http://stackoverflow.com/comment/82524331
comment on: http://stackoverflow.com/a/47779220
score: 0
type: Comment
has text: @chepner thank you for your help your answer is good, I'm going to try to improve it
type: AnswerComment

http://stackoverflow.com/q/47854438
has comment: http://stackoverflow.com/comment/82673088
type: UnansweredQuestion
has title: How to check column value among all others values in same column in Pandas Data frame?
has answer: http://stackoverflow.com/a/47854512
answer count: 1
tagged with: python
score: 0
tagged with: pandas
tagged with: dataframe
type: Question
has body: I have a pandas data frame which having three columns. Normally for the Loan type it has 5 values. Let's say Conso, Immo, Pro, Autre, Tous. For this data frame only contain loan type 'Immo'. (At the beginning we don't know what the Loan type is). How do I check what the loan type is among all this loan type? CodeProduit LoanType Year 301 Immo 2003 301 Immo 2004 301 Immo 2005 301 Immo 2006 ... ... .... 301 Immo 2017 def check_type_pret(p): if p == 'Immo': return p elif p == 'Conso': return p elif p == 'Pro': return p elif p == 'Autres': return p elif p == 'Tous': return p else: return 0 df1['Answer']=df1.LoanType.map(check_type_pret) As a output I'm getting 0 for Answer Column. How do I get expected out put as I explained?

http://stackoverflow.com/q/47721524
has comment: http://stackoverflow.com/comment/82403887
tagged with: multiprocessing
type: Question
has comment: http://stackoverflow.com/comment/82405232
has comment: http://stackoverflow.com/comment/82404073
has comment: http://stackoverflow.com/comment/82404008
has comment: http://stackoverflow.com/comment/82403965
has comment: http://stackoverflow.com/comment/82403914
has comment: http://stackoverflow.com/comment/82404148
accepted answer: http://stackoverflow.com/a/47721936
tagged with: python
tagged with: parallel-processing
tagged with: python-multiprocessing
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82403796
score: 0
has body: I'm trying to learn how to do parallel programming in python. I wrote a simple int square function and then ran it in serial, multi-thread, and multi-process: import time import multiprocessing, threading import random def calc_square(numbers): sq = 0 for n in numbers: sq = n*n def splita(list, n): a = [[] for i in range(n)] counter = 0 for i in range(0,len(list)): a[counter].append(list[i]) if len(a[counter]) == len(list)/n: counter = counter +1 continue return a if __name__ == "__main__": random.seed(1) arr = [random.randint(1, 11) for i in xrange(1000000)] print "init completed" start_time2 = time.time() calc_square(arr) end_time2 = time.time() print "serial: " + str(end_time2 - start_time2) newarr = splita(arr,8) print 'split complete' start_time = time.time() for i in range(8): t1 = threading.Thread(target=calc_square, args=(newarr[i],)) t1.start() t1.join() end_time = time.time() print "mt: " + str(end_time - start_time) start_time = time.time() for i in range(8): p1 = multiprocessing.Process(target=calc_square, args=(newarr[i],)) p1.start() p1.join() end_time = time.time() print "mp: " + str(end_time - start_time) Output: init completed serial: 0.0640001296997 split complete mt: 0.0599999427795 mp: 2.97099995613 However, as you can see, something weird happened and mt is taking the same time as serial and mp is actually taking significantly longer (almost 50 times longer). What am I doing wrong? Could someone push me in the right direction to learn parallel programming in python? Edit 01 Looking at the comments, I see that perhaps the function not returning anything seems pointless. The reason I'm even trying this is because previously I tried the following add function: def addi(numbers): sq = 0 for n in numbers: sq = sq + n return sq I tried returning the addition of each part to a serial number adder, so at least I could see some performance improvement over a pure serial implementation. However, I couldn't figure out how to store and use the returned valu…
tagged with: multithreading
linked to: http://stackoverflow.com/q/44521931
has answer: http://stackoverflow.com/a/47721936
answer count: 1
has comment: http://stackoverflow.com/comment/82403888
has comment: http://stackoverflow.com/comment/82403777
has title: Parallelizing through Multi-threading and Multi-processing taking significantly more time than serial
has comment: http://stackoverflow.com/comment/82403741

http://stackoverflow.com/comment/82414100
type: QuestionComment
comment on: http://stackoverflow.com/q/47726706
score: 1
has text: there are plenty of collatz related questions on SO even some with nice optimizations for computing them - if you want to go for longest till number xxx: https://stackoverflow.com/search?q=python+collatz
type: Comment

http://stackoverflow.com/comment/82537591
type: Comment
type: QuestionComment
has text: @AliZuhair : It's what your traceback is showing : you're trying to assign an int64 variable, but the datatype is not supported (the only supported are boolean, int32 and float). It's not related to the building/compiling step. **Your model is using a datatype that the Tensorflow library don't handle on ARM.**
comment on: http://stackoverflow.com/q/47773474
score: 1

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

http://stackoverflow.com/comment/82425225
has text: a one-off case that comes to mind is if I want to run a script that manipulates the DB data using the django ORM e.g. I added a column to a table and want to run a script that goes through the list of objects in that table and populates the columns for entries already in there (maybe inferred from another column)
score: 1
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47731495

http://stackoverflow.com/a/47721906
has comment: http://stackoverflow.com/comment/82407299
has comment: http://stackoverflow.com/comment/82407500
has comment: http://stackoverflow.com/comment/82405311
upvote count: 6
type: Answer
score: 6
has comment: http://stackoverflow.com/comment/82405364
answers question: http://stackoverflow.com/q/47721635
has comment: http://stackoverflow.com/comment/82406116
has comment: http://stackoverflow.com/comment/82404772
has comment: http://stackoverflow.com/comment/82406759
downvote count: 0
has body: One thing worth mentioning is that numpy arrays do behave as expected: a = np.array((np.nan,)) a[0] in a # False Variations of the theme: [np.nan]==[np.nan] # True [float('nan')]==[float('nan')] # False {np.nan: 0}[np.nan] # 0 {float('nan'): 0}[float('nan')] # Traceback (most recent call last): # File "&lt;stdin&gt;", line 1, in &lt;module&gt; # KeyError: nan Everything else is covered in @AlexRiley's excellent answer.
has comment: http://stackoverflow.com/comment/82405713
has comment: http://stackoverflow.com/comment/82406257

http://stackoverflow.com/q/47841158
has comment: http://stackoverflow.com/comment/82647490
type: Question
tagged with: ubuntu-16.04
tagged with: django
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82646753
has answer: http://stackoverflow.com/a/47841334
has title: ImportError: No module named 'posts.urls'
has body: I am new to Django and started making my first Django app using django official tutorial from https://docs.djangoproject.com/en/2.0/intro/tutorial01/. I have installed python3.5.2 and pip 9.0.1, using Ubuntu 16.04, Django version is 2.0. my urls.py file has following code from django.contrib import admin from django.urls import path from django.conf.urls import url, include urlpatterns = [ path('posts/', include('posts.urls')), path('admin/', admin.site.urls), ] If there is anything you can help me work this out. below is the error i am getting after running command - python manage.py runserver here is the error i am getting Performing system checks... Unhandled exception in thread started by &lt;function check_errors.&lt;locals&gt;.wrapper at 0x7fe20fe92d08&gt; Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.5/dist-packages/django/core/management/commands/runserver.py", line 120, in inner_run self.check(display_num_errors=True) File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 364, in check include_deployment_checks=include_deployment_checks, File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 351, in _run_checks return checks.run_checks(**kwargs) File "/usr/local/lib/python3.5/dist-packages/django/core/checks/registry.py", line 73, in run_checks new_errors = check(app_configs=app_configs) File "/usr/local/lib/python3.5/dist-packages/django/core/checks/urls.py", line 40, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "/usr/local/lib/python3.5/dist-packages/django/core/checks/urls.py", line 57, in _load_all_namespaces url_patterns = getattr(resolver, 'url_patterns', []) File "/usr/local/lib/python3.5/dist-packages/django/utils/functional.py", line 36, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/usr/local/lib…
score: 0
has comment: http://stackoverflow.com/comment/82647023
answer count: 1
has comment: http://stackoverflow.com/comment/82668311

http://stackoverflow.com/comment/82478779
type: QuestionComment
has text: `cron` won't be looking in `/CEEGEX/crontab` for its configuration. Install the file as `/etc/crontab`.
comment on: http://stackoverflow.com/q/47758657
score: 0
type: Comment

http://stackoverflow.com/a/47813188
accepted answer of: http://stackoverflow.com/q/47781496
has body: It looks like you have started well! Geometries loaded from shapefiles expose various geospatial comparison methods, and in this case you need the contains method. You can use this to test each point in your cube's horizontal grid for being contained within your British Columbia geometry. (Note that this is not a fast operation!) You can use this comparison to build up a 2D mask array, which could be applied to your cube's data or used in other ways. I've written a Python function to do the above – it takes a cube and a geometry and produces a mask for the (specified) horizontal coordinates of the cube, and applies the mask to the cube's data. The function is below: def geom_to_masked_cube(cube, geometry, x_coord, y_coord, mask_excludes=False): """ Convert a shapefile geometry into a mask for a cube's data. Args: * cube: The cube to mask. * geometry: A geometry from a shapefile to define a mask. * x_coord: (str or coord) A reference to a coord describing the cube's x-axis. * y_coord: (str or coord) A reference to a coord describing the cube's y-axis. Kwargs: * mask_excludes: (bool, default False) If False, the mask will exclude the area of the geometry from the cube's data. If True, the mask will include *only* the area of the geometry in the cube's data. .. note:: This function does *not* preserve lazy cube data. """ # Get horizontal coords for masking purposes. lats = cube.coord(y_coord).points lons = cube.coord(x_coord).points lon2d, lat2d = np.meshgrid(lons,lats) # Reshape to 1D for easier iteration. lon2 = lon2d.reshape(-1) lat2 = lat2d.reshape(-1) mask = [] # Iterate through all horizontal points in cube, and # check for containment within the specified geometry. for lat, lon in zip(lat2, lon2): this_point = gpd.geoseries.Point(lon, lat) res = geometry.contains(this_point) mask.append(res.values[0]) mask = np.array(mask).reshape(lon2d.shape) if mask_excludes: # Invert the mask if we want to include the geometry's area. mask = ~mask # Make sure the mask is the …
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82633876
answers question: http://stackoverflow.com/q/47781496
upvote count: 9
score: 9
type: Answer
has comment: http://stackoverflow.com/comment/82632416
downvote count: 0

http://stackoverflow.com/q/47737482
answer count: 1
tagged with: python
has title: List attributes of a sublass instance in Python
type: Question
tagged with: legacy
accepted answer: http://stackoverflow.com/a/47738611
has answer: http://stackoverflow.com/a/47738611
has body: I'm trying to build some "ORM like" behavior in Python. To do this I have a Model class and would like to produce any kind of subclasses. My problem is when I try to list the attributes of my subclasses instances. Here is my Model class: class Model: def __init__(self): self.className = type(self).__name__ def listAttributes(self): from modules.users.user import User instance = User() meta = vars(instance) And a User subclass : class User(models.Model): name = models.FieldChar() password = models.FieldChar() age = models.FieldInteger() When I invoke the listAttributes method from a User instance, I don't have what I expect, but probably what I should: the meta var contains only className. Here's how I invoke the method: from modules.users import user user = user.User() user.listAttributes() Same behavior when I override the listAttributes method in User(): def listAttributes(self): meta = vars(self) print(meta) Is there a way to list the attribute of the object from which I call the listAttributes method? Thanks for your lights!
type: AnsweredQuestion
score: 0
tagged with: introspection

http://stackoverflow.com/q/47701815
tagged with: python
accepted answer: http://stackoverflow.com/a/47704831
has answer: http://stackoverflow.com/a/47701906
possible better answer: http://stackoverflow.com/a/47701906
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/47701965
answer count: 3
tagged with: pandas
upvote count: 1
downvote count: 1
has title: Python Pandas Set Value in DataFrame where Index has Multiple Identical Label Values
has answer: http://stackoverflow.com/a/47704831
favorite count: 0
type: Question
has body: I want to set a value in a row in a pandas dataframe where the row index has duplicate values and the value of a date column is the max value for the selected index value. My dataframe: Index Start_Date End_Date A 2017-10-01 2017-10-13 B 2017-10-07 2017-10-15 B 2017-10-18 np.Nat C 2017-10-09 2017-10-30 so I want to set the End_Date for index value 'B' where the Start_Date is the Max for 'B' What is the best way to do this? EDIT: My dataframe: Index Start_Date End_Date A 2017-10-01 2017-10-13 B 2017-10-07 2017-10-15 B 2017-10-18 np.Nat C 2017-10-09 2017-10-30 D 2017-11-01 np.Nat E 2017-11-03 2017-11-09 E 2017-11-13 np.Nat Through separate processes I come to learn that the End_Date corresponding to row #3 (Index == 'B', Start_Date == '2017-10-18 is 2017-10-25. I also separately find that row #5(Index == 'D', Start_Date == '2017-11-01' is 2017-11-03. So I want to fill those values into End_Date one at a time. Since I don't have an End_Date value for the last row (Index = 'E', Start_Date == '2017-11-13') that will stay empty. Note that 'D' is unique while 'B' is not. Output: My dataframe: Index Start_Date End_Date A 2017-10-01 2017-10-13 B 2017-10-07 2017-10-15 B 2017-10-18 2017-10-25 C 2017-10-09 2017-10-30 D 2017-11-01 2017-11-03 E 2017-11-03 2017-11-09 E 2017-11-13 np.Nat Not that the values 2017-10-25 in row 3 and 2017-11-03 came from another process and we can assume they are stored in variables - that can then be used to populate the initial dataframe to obtain the output.

http://stackoverflow.com/comment/82393422
has text: you can use `for` or `while` loop and catch end of pages when it can't read page. Link to next page is also in button '>' on page so you can get it with `BeautifulSoup`.
comment on: http://stackoverflow.com/q/47716519
score: 1
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/82598491
type: Comment
score: 0
type: AnswerComment
has text: Each try has different initial values and thus gives different solutions to the ODE. Thus the need for the integration. Which also means that you should avoid to recompute the same value over and over again.
comment on: http://stackoverflow.com/a/47793867

http://stackoverflow.com/q/47763192
has comment: http://stackoverflow.com/comment/82488943
has answer: http://stackoverflow.com/a/47764134
score: 0
has comment: http://stackoverflow.com/comment/82489141
answer count: 1
has body: Using Django, I have a model and a class based view based on the provided CreateView class. Everything works fine - I can have a template that renders the form, validation occurs, the data is properly saved and the success_url redirected to on completion. The problem occurs in that I have a unique_together constraint on two of the fields. If this error is hit, it appears that form_valid() doesn't catch it, and an error page is produced instead. My goal is to be able to catch this ahead of time and return the user to the form - with the data filled in from their last attempt - and display a message to them. Feels like this should be simple, and I added code to form_valid() in the view to identify the problem, but I have no clue what to do next. A redirect doesn't work because I can't add the context in (or can I?) and I really don't want to put everything in the URL. Any ideas where to look? The Model: class Client(BaseModel): name = models.CharField(max_length=240, db_index=True, verbose_name='Client Name') organization_link = models.ForeignKey(Organization, on_delete=models.PROTECT, verbose_name='Organization') client_group_link = models.ForeignKey(ClientGroup, blank=True, on_delete=models.SET_NULL, null=True, verbose_name='Client Group') policy_link = models.ManyToManyField(OrganizationPolicy, related_name='attached_clients', verbose_name='Policies') active = models.BooleanField(default=True, db_index=True, verbose_name='Active') class Meta: unique_together = (('name', 'organization_link'),) The View: class ClientCreateView(CreateView): model = Client fields = ['name', 'client_group_link', 'active'] success_url = reverse_lazy('entities_client_roster') def form_valid(self, form): organization = get_object_or_404(Organization, id=self.kwargs['organization']) form.instance.organization_link_id = organization.id return super().form_valid(form) The snippet URL config: url(r'^client_create/(?P&lt;organization&gt;[0-9a-f-]+)', ClientCreateView.as_view(template_name='enti…
type: Question
has comment: http://stackoverflow.com/comment/82488361
has comment: http://stackoverflow.com/comment/82489408
has title: How to Handle Error during Django CreateView
tagged with: django
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/82580376
type: Comment
has text: State = "'" + "','".join(a) + "'" Name = "'" + "','".join(c) + "'" cursor.execute("select Sno,Name,State,MailId,UserName,Password from user_master WHERE Status='" + State + "',Name='" + Name + "'") Is this correct for select a table based on State and Name column
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47792995

http://stackoverflow.com/comment/82378009
type: QuestionComment
has text: Oh that is a huge topic for another day. I was reading this. https://quant.stackexchange.com/questions/29572/building-financial-data-time-series-database-from-scratch
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47709010

http://stackoverflow.com/q/47805088
tagged with: localhost
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47817597
has title: python and threading- code after thread.start() not being ran -- code stops
has comment: http://stackoverflow.com/comment/82591890
tagged with: python
type: Question
score: 0
has body: I am attempting to get this function to run: def local_server(): # Start local unix_python_bin = "py_env/bin/python" unix_script_file = "./run.py" win_python_bin = "win_py_env/Scripts/python" win_script_file = "./run.py" try: system = platform.system() if "windows" in system.lower(): theproc = subprocess.Popen([win_python_bin, win_script_file]) theproc.communicate() else: subprocess.Popen([unix_python_bin, unix_script_file]) set_server_connected(True) except: set_server_connected(False) as a thread because this process starts a localhost server and takes up the terminal causing the user to have to press Ctrl+C to close the localhost. I am wanting to get the localhost started in the background and keep it going as the python app will interact with it. As of now I call that function with: server = Thread(target = local_server) server.start() The call works and the localhost gets started but the code never gets to set_server_connected(). The terminal is also held up by the server waiting for Ctrl+C. How can I make this code run without stopping?
tagged with: subprocess
has comment: http://stackoverflow.com/comment/82593562
tagged with: multithreading
answer count: 1
has answer: http://stackoverflow.com/a/47817597
tagged with: flask
has comment: http://stackoverflow.com/comment/82572668

http://stackoverflow.com/comment/82517067
comment on: http://stackoverflow.com/q/47775640
score: 0
has text: I suspected that it was an illegal operation, but not being totally familiar with WSGI, I wasn't sure. I know that Perl and PHP will both hurl expletives about having a header already started, but it seems the RFCs say it should be possible... but we all know RFCs are not really the final word on how certain software implements anything (just like at historical trash from M$ like IE)
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47716023
accepted answer of: http://stackoverflow.com/q/47715753
downvote count: 0
type: AcceptedAnswer
has body: The error you are getting is because of the arguments you are passing into super. In Python 2 it takes 2 arguments: The first argument is the current class (Object2), and the second argument is the current instance (self). The issue is you've passed the parent class instead of the current class. So you want: class Object2(Object): def __init__(self): super(Object2, self).__init__() # Current class: Object2 self.field.append(1) In Python 3, it is no longer required to pass these arguments into super. So you would just do: class Object2(Object): def __init__(self): super().__init__() self.field.append(1) See also: https://stackoverflow.com/a/5066411/7220776 Python 2 docs: https://docs.python.org/2/library/functions.html#super Python 3 docs: https://docs.python.org/3/library/functions.html#super
answers question: http://stackoverflow.com/q/47715753
type: Answer
upvote count: 3
score: 3

http://stackoverflow.com/q/47739140
has comment: http://stackoverflow.com/comment/82438558
tagged with: dataframe
tagged with: python
possible better answer: http://stackoverflow.com/a/47739183
accepted answer: http://stackoverflow.com/a/47739274
has answer: http://stackoverflow.com/a/47739183
tagged with: numpy
has title: python pandas data-frame - duplicate rows according to a column value
has answer: http://stackoverflow.com/a/47739274
tagged with: pandas
type: AnsweredQuestion
score: 2
upvote count: 3
answer count: 2
has body: I want to duplicate the rows of dataframe "this" according to 2 column values and save them as a new dataframe named "newThis": this = pd.DataFrame(columns=['a','b','c'], index=[1,2,3]) this.a = [1, 2, 0] this.b = [5, 0, 4] this.c = [2, 3, 2] newThis = [] for i in range(len(this)): if int(this.iloc[i, 1]) != 0: that = np.array([this.iloc[i,:]] * int(this.iloc[i, 1])) elif int(this.iloc[i, 1]) == 0: that = np.array([this.iloc[i,:]]) if int(this.iloc[i, 2]) != 0: those = np.array([this.iloc[i,:]] * int(this.iloc[i, 2])) elif int(this.iloc[i, 2]) == 0: those = np.array([this.iloc[i,:]]) newThis.append(that) newThis.append(those) I want one big array of concatenated rows, but Instead I get this mess: [array([[1, 5, 2], [1, 5, 2], [1, 5, 2], [1, 5, 2], [1, 5, 2]], dtype=int64), array([[1, 5, 2], [1, 5, 2]], dtype=int64), array([[2, 0, 3]], dtype=int64), array([[2, 0, 3], [2, 0, 3], [2, 0, 3]], dtype=int64), array([[0, 4, 2], [0, 4, 2], [0, 4, 2], [0, 4, 2]], dtype=int64), array([[0, 4, 2], [0, 4, 2]], dtype=int64)] Thanks
downvote count: 1
favorite count: 0
tagged with: python-3.x
type: Question

http://stackoverflow.com/comment/91267402
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47827633
score: 1
has text: Yeah when people use cluster, they are forking the main node process. So for 8 cores you will have 8 identical processes handling requests which should roughly increase the amount of requests/per second the server can handle by x8. But for your case, it wont work, although its probably technically possible to have each process run different code and connect to different sockets, you definately shouldn't do that, sounds like a big anti-pattern.

http://stackoverflow.com/a/47763990
accepted answer of: http://stackoverflow.com/q/47762286
downvote count: 0
upvote count: 1
score: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47762286
has body: If I've understood your main goal properly, it sounds to me like you could use a metaclass to turn your 12 OrderedDict instances into separate classes and conserving memory by eliminating (or at least minimizing) duplicate code and data. Here's one way to do that: from collections import OrderedDict class MetaDefaultAsset(type): def __new__(cls, name, bases, namespace, **kwargs): clsobj = type.__new__(cls, name, bases, namespace) # create class object # Use "defaults" keyword argument to create __slots__ and default # attributes and their values. if 'defaults' in kwargs: setattr(clsobj, '__slots__', kwargs['defaults'].keys()) for key, default_value in kwargs['defaults'].items(): setattr(clsobj, key, default_value) # Define some methods to be added to class object created. def items(self): yield from ((slot, getattr(self, slot)) for slot in self.__slots__) def values(self): yield (getattr(self, slot) for slot in self.__slots__) # Add the above methods to the class object. for name, method in {'items': items, 'values': values}.items(): setattr(clsobj, name, method) return clsobj DEFAULT_ASSET_ORDERED_DICT = OrderedDict( [('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)]) class DefaultAsset(metaclass=MetaDefaultAsset, defaults=DEFAULT_ASSET_ORDERED_DICT): pass NEW_ASSETS_ORDERED_DICT = OrderedDict( [('computer', 1), ('monitor', 2), ('keyboard', 3), ('mouse', 4)]) class DefaultNewAsset(metaclass=MetaDefaultAsset, defaults=NEW_ASSETS_ORDERED_DICT): pass da = DefaultAsset() print(list(da.items())) dna = DefaultNewAsset() print(list(dna.items())) Output: [('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)] [('computer', 1), ('monitor', 2), ('keyboard', 3), ('mouse', 4)]
type: Answer

http://stackoverflow.com/q/47851127
has body: I try to run Django project in Docker container. Until now, everything was working fine. I didn't change anything but I get error shown at the bottom. Any ideas what is wrong? My PostgreSQL settings look in this way: DATABASES = { "default": { 'ENGINE': 'django.db.backends.postgresql', "NAME": 'myproject', "HOST": "db", "PORT": "5432", } } DATABASES = {'default': dj_database_url.config(default='postgres://addw...@ec2-31-11-107-127.compute-1.amazonaws.com:5432/qdsfks')} docker-compose.yml: version: '3' services: db: image: postgres environment: POSTGRES_USER: myproject POSTGRES_PASSWORD: somepass volumes: - "./local_pgdata:/var/lib/postgresql/data/pgdata" django: build: . command: python3 manage.py runserver 0.0.0.0:8001 volumes: - .:/code ports: - "8001:8001" depends_on: - db Logs: db_1 | The files belonging to this database system will be owned by user "postgres". db_1 | This user must also own the server process. db_1 | db_1 | The database cluster will be initialized with locale "en_US.utf8". db_1 | The default database encoding has accordingly been set to "UTF8". db_1 | The default text search configuration will be set to "english". db_1 | db_1 | Data page checksums are disabled. db_1 | db_1 | initdb: directory "/var/lib/postgresql/data" exists but is not empty db_1 | If you want to create a new database system, either remove or empty db_1 | the directory "/var/lib/postgresql/data" or run initdb db_1 | with an argument other than "/var/lib/postgresql/data".
has comment: http://stackoverflow.com/comment/82667161
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47851532
tagged with: python
has comment: http://stackoverflow.com/comment/82667094
linked to: http://stackoverflow.com/q/26598738
has title: Django project with PostgreSQL database in Docker container - directory /var/lib/postgresql/data exists but is not empty
score: 0
has comment: http://stackoverflow.com/comment/82667088
answer count: 1
tagged with: django
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82667268
tagged with: heroku
tagged with: postgresql

http://stackoverflow.com/q/47798002
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/82557824
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82557790
tagged with: tkinter
has title: Buttons not changing to full when clicked apart from the final one
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82557838
downvote count: 2
has comment: http://stackoverflow.com/comment/82557459
has answer: http://stackoverflow.com/a/47798790
answer count: 1
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/82557493
has body: I want all the buttons to change to full when clicked, but I only got the last one to work. This is my code, but I can't get the others to work. Help would be appreciated. from tkinter import* root = Tk() root.geometry("500x500") root.resizable (0, 0) def button(): for x in range(5): for y in range(5): seat2=Button(root,text="empty",bg="green",fg="black",height=5,width=10) seat2['command']=lambda s1=seat1:(toggle_text(s1)) seat2.grid(row=x, column=y) button() def toggle_text(s1): """toggle Button text between empty and Full""" if s1["text"]== "empty": #switch to Full s1["text"]= "Full"

http://stackoverflow.com/q/47778551
tagged with: python
upvote count: 4
score: 4
has answer: http://stackoverflow.com/a/47779831
accepted answer: http://stackoverflow.com/a/47779831
downvote count: 0
answer count: 1
has title: Flask app using app factory can't find template
tagged with: flask
tagged with: jinja2
favorite count: 0
type: Question
has body: I am using an app factory and blueprints to modularize my application. The templates folder is located under the app package and contains the index.html template. However, I get a TemplateNotFoundError when viewing the page. Why isn't my template found? project/ ├── app │ ├── __init__.py │ └── templates │ └── index.html └── run.py app/__init__.py from flask import Flask, Blueprint, render_template def create_app(): app = Flask('__name__') app.register_blueprint(home) return app home = Blueprint('home', __name__) @home.route('/') def homepage(): return render_template('home/index.html') run.py from app import create_app app = create_app() app.run() File "/Users/saikrishnamohan/Projects/VirtualEnvs/flaskVue/lib/python2.7/site-packages/werkzeug/serving.py", line 267, in run_wsgi execute(self.server.app) File "/Users/saikrishnamohan/Projects/VirtualEnvs/flaskVue/lib/python2.7/site-packages/werkzeug/serving.py", line 255, in execute application_iter = app(environ, start_response) File "/Users/saikrishnamohan/Projects/VirtualEnvs/flaskVue/lib/python2.7/site-packages/flask/app.py", line 1997, in __call__ return self.wsgi_app(environ, start_response) File "/Users/saikrishnamohan/Projects/VirtualEnvs/flaskVue/lib/python2.7/site-packages/flask/app.py", line 1985, in wsgi_app response = self.handle_exception(e) File "/Users/saikrishnamohan/Projects/VirtualEnvs/flaskVue/lib/python2.7/site-packages/flask/app.py", line 1540, in handle_exception reraise(exc_type, exc_value, tb) File "/Users/saikrishnamohan/Projects/VirtualEnvs/flaskVue/lib/python2.7/site-packages/flask/app.py", line 1982, in wsgi_app response = self.full_dispatch_request() File "/Users/saikrishnamohan/Projects/VirtualEnvs/flaskVue/lib/python2.7/site-packages/flask/app.py", line 1614, in full_dispatch_request rv = self.handle_user_exception(e) File "/Users/saikrishnamohan/Projects/VirtualEnvs/flaskVue/lib/python2.7/site-packages/flask/app.py", line 1517, in handle_user_exception reraise(exc_type, exc_value, tb) Fil…
type: AnsweredQuestion

http://stackoverflow.com/a/47783666
has body: As can be seen when not turning the axes invisible, the colorbar is correctly representing the color of the data in the image. If this is not what you want you should start by establishing how the data is represented in the image. Introducing a Normalization for the data to the colormap range is usually the way this is accomplished. Here a BoundaryNorm makes sense. import matplotlib.pyplot as plt import matplotlib.colors import numpy as np a = np.array([[0,10000,100000,400000,500000]]) plt.figure(figsize=(4, 2.5)) mycmap = matplotlib.colors.ListedColormap(['yellow','orange','red','darkred']) norm = matplotlib.colors.BoundaryNorm(a[0], len(a[0])-1) img = plt.imshow(a, cmap=mycmap, norm=norm) cax = plt.axes([0.1, 0.1, 0.8, 0.1]) cbar=plt.colorbar(orientation='horizontal', cax=cax,spacing='proportional'); plt.show() This now gives a meaningful representation with ticks at the edges of the colorranges.
accepted answer of: http://stackoverflow.com/q/47774935
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47774935
score: 1
type: Answer

http://stackoverflow.com/comment/82430482
score: 0
comment on: http://stackoverflow.com/q/47734979
type: Comment
type: QuestionComment
has text: you should create list with all data in function before you send it to template.

loops
tags question: http://stackoverflow.com/q/47717038
tags question: http://stackoverflow.com/q/47706620
tags question: http://stackoverflow.com/q/47825106
tags question: http://stackoverflow.com/q/47842283
tags question: http://stackoverflow.com/q/47784197
tags question: http://stackoverflow.com/q/47707630
tags question: http://stackoverflow.com/q/47819292
tag name: loops
tags question: http://stackoverflow.com/q/47803490
tags question: http://stackoverflow.com/q/47846357
tags question: http://stackoverflow.com/q/47723919
tags question: http://stackoverflow.com/q/47783594
tags question: http://stackoverflow.com/q/47700082
tags question: http://stackoverflow.com/q/47754101
tags question: http://stackoverflow.com/q/47852441
tags question: http://stackoverflow.com/q/47804748
tags question: http://stackoverflow.com/q/47754131
tags question: http://stackoverflow.com/q/47850124
tags question: http://stackoverflow.com/q/47822082
tags question: http://stackoverflow.com/q/47734981
tags question: http://stackoverflow.com/q/47848114
tags question: http://stackoverflow.com/q/47844719
tags question: http://stackoverflow.com/q/47716682
tags question: http://stackoverflow.com/q/47700618
tags question: http://stackoverflow.com/q/47699473
tags question: http://stackoverflow.com/q/47842009
tags question: http://stackoverflow.com/q/47700271
tags question: http://stackoverflow.com/q/47855220
tags question: http://stackoverflow.com/q/47764235
tags question: http://stackoverflow.com/q/47706673
type: Tag
tags question: http://stackoverflow.com/q/47833920
tags question: http://stackoverflow.com/q/47717860
tags question: http://stackoverflow.com/q/47847389
tags question: http://stackoverflow.com/q/47726626
tags question: http://stackoverflow.com/q/47803977
tags question: http://stackoverflow.com/q/47803986
tags question: http://stackoverflow.com/q/47826052
tags question: http://stackoverflow.com/q/47707526
tags question: http://stackoverflow.com/q/47733250
tags question: http://stackoverflow.com/q/47702999

file-format
type: Tag
tags question: http://stackoverflow.com/q/47839776
tag name: file-format

http://stackoverflow.com/comment/82414516
type: Comment
comment on: http://stackoverflow.com/q/47726984
score: 1
has text: Put a [mcve], **in text form**, in the question itself. Also don't name your scripts after existing modules...
type: QuestionComment

http://stackoverflow.com/comment/97737817
type: AnswerComment
comment on: http://stackoverflow.com/a/50177664
score: 1
has text: What happens when the aiohttp wsgi worker is used ? https://aiohttp-wsgi.readthedocs.io/en/stable/index.html. Will the event loop in the worker be blocked even then?
type: Comment

http://stackoverflow.com/comment/82431375
comment on: http://stackoverflow.com/a/47735385
type: Comment
has text: Ah, it seems like you want `diags` then instead of `spdiags`. See my edit.
type: AnswerComment
score: 0

http://stackoverflow.com/q/47804703
has title: (Set) Comprehension from multiple values
has comment: http://stackoverflow.com/comment/82571057
upvote count: 2
score: 1
has comment: http://stackoverflow.com/comment/82572676
has comment: http://stackoverflow.com/comment/82572471
has comment: http://stackoverflow.com/comment/82572048
has comment: http://stackoverflow.com/comment/82572594
has answer: http://stackoverflow.com/a/47805694
possible better answer: http://stackoverflow.com/a/47805694
has answer: http://stackoverflow.com/a/47805378
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82572162
tagged with: set-comprehension
has comment: http://stackoverflow.com/comment/82572290
has comment: http://stackoverflow.com/comment/82572637
has comment: http://stackoverflow.com/comment/82572559
accepted answer: http://stackoverflow.com/a/47805378
tagged with: python
type: AnsweredQuestion
has body: Suppose I’ve got a list l = [1,2,3] and I want to create a set of all numbers in that list and their squares. Ideally, in a single comprehension expression. Best I can come up with is (two iterations over the list): set(_ for _ in l).union(_ * _ for _ in l)
answer count: 2

http://stackoverflow.com/q/47710588
favorite count: 0
type: Question
answer count: 1
downvote count: 0
upvote count: 1
accepted answer: http://stackoverflow.com/a/47710687
has answer: http://stackoverflow.com/a/47710687
type: AnsweredQuestion
has body: I have to implement the formula above in python, but I am having a difficulty fully understanding it. I wrote a pseudo code for doing this and I really need someone to correct it. Given Info So, I am running this code in a parallel corpus for Machine translation that consists of S sentence pairs (f (s), e(s)), where 1 ≤ s ≤ S. So f(s) and e(s) represents s'th sentence in the corpus in f:foreign language and e: english. e_x is the x'th words in the sentence e(s) I understood this formula as the following pseudo-code: for a fixed english word e_x in all sentences: for all foreign word f_y in the sentence where f_y and e_x appears together: Z += apply the count in &lt;.. I have the function for calculating this..&gt; Am I understanding this formula correctly?
has title: Correcting the double summation formula written in pseudo-code
score: 1
tagged with: python

http://stackoverflow.com/q/47720081
favorite count: 0
tagged with: integer
duplicate of: http://stackoverflow.com/q/4265988
tagged with: raspberry-pi
type: Question
has comment: http://stackoverflow.com/comment/82400601
score: 0
answer count: 0
upvote count: 1
type: UnansweredQuestion
tagged with: python
downvote count: 1
has comment: http://stackoverflow.com/comment/82400603
has body: i am creating a slot machine with python and now I have the numbers 1-12, choosen randomly by "randint", the problem is now that some of the numbers (3,8,12) trigger an extremly high winning and now I want to add a "higher chance" for the rest of the numbers and for these winning numbers a lower chance. How do I realize this? Regards, Simon
tagged with: random
has comment: http://stackoverflow.com/comment/82401108
has title: Python - random numbers, higher and lower chances
linked to: http://stackoverflow.com/q/4265988

http://stackoverflow.com/q/47723967
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82408688
tagged with: exception
answer count: 5
has answer: http://stackoverflow.com/a/59869265
has title: Python get an error code from exception
linked to: http://stackoverflow.com/q/6180185
tagged with: python
upvote count: 19
has answer: http://stackoverflow.com/a/47724159
has body: In python, I have code that handles exceptions and prints error codes and messages. try: somecode() #raises NameError except Exception as e: print('Error! Code: {c}, Message, {m}'.format(c = e.code, m = str(e)) However, e.code is not the proper way to get the error name (NameError), and I cannot find the answer to this. How am I supossed to get the error code?
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/64814782
has answer: http://stackoverflow.com/a/69411548
possible better answer: http://stackoverflow.com/a/59869265
downvote count: 0
tagged with: try-except
has comment: http://stackoverflow.com/comment/82408657
has comment: http://stackoverflow.com/comment/82408664
has answer: http://stackoverflow.com/a/63845239
has comment: http://stackoverflow.com/comment/82408687
linked to: http://stackoverflow.com/q/9823936
accepted answer: http://stackoverflow.com/a/47724159
score: 19

http://stackoverflow.com/comment/82438823
comment on: http://stackoverflow.com/q/47739262
score: 0
type: QuestionComment
has text: Have you looked at `os.path.abspath`? And errr, isn't this what facilities such as logrotate are for?
type: Comment

http://stackoverflow.com/q/47738690
has comment: http://stackoverflow.com/comment/82437689
tagged with: python
has answer: http://stackoverflow.com/a/50964300
has body: I am doing a program that prevents certain applications from opening. But it uses a lot of CPU. Because the program is always trying to terminate that application. I want this program to use less of the CPU. How can I do this? PS: I could not reach this result for 2 hours. My Python Version : 3.6.3 I don't want any 3rd party modules. My code that uses a lot of CPU: si = subprocess.STARTUPINFO() si.dwFlags |= subprocess.STARTF_USESHOWWINDOW while True: subprocess.call("taskkill /F /IM chrome.exe", startupinfo=si) subprocess.call("taskkill /F /IM opera.exe", startupinfo=si) subprocess.call("taskkill /F /IM iexplore.exe", startupinfo=si) subprocess.call("taskkill /F /IM firefox.exe", startupinfo=si) sleep(1)
has answer: http://stackoverflow.com/a/47739062
has comment: http://stackoverflow.com/comment/82438004
type: Question
linked to: http://stackoverflow.com/q/44008243
answer count: 2
has comment: http://stackoverflow.com/comment/82437668
upvote count: 1
tagged with: python-3.6
downvote count: 1
has comment: http://stackoverflow.com/comment/82437753
favorite count: 0
type: AnsweredQuestion
score: 0
has title: How to check if a process is running in Python?
possible better answer: http://stackoverflow.com/a/50964300
has comment: http://stackoverflow.com/comment/82437805
accepted answer: http://stackoverflow.com/a/47739062

http://stackoverflow.com/comment/82561811
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47800065
has text: Can you clarify a bit? Are you attempting to concurrently GET a request, then pipe that to a POST request? The reason I ask is because you've referenced node.js which should be able to pipe GET content into POST request simultaneously. Python can do that too but it's a bit tricky and it involves more than just `requests`
type: Comment

http://stackoverflow.com/comment/82676882
score: 0
has text: location_id & pricelist_id are fields that are not available in the database? https://photos.app.goo.gl/yRmNnUgBgnXUe9Vr2 Also, i would probably have to create a purchase_order_line. How can it be done in one step?
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47853795

http://stackoverflow.com/a/76763833
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/47836998
downvote count: 0
has body: You can also use the Linux head command as follows: Also, it's recommended to use cumtime for sorting. python -m cProfile -s cumulative main.py | head -n 15 -n 15: This tells you how many lines of the cProfile output you need. By choosing 15, it will show the top 10 code lines (5 for formatting and reports of cProfile).&quot;
score: 2

http://stackoverflow.com/comment/82506957
type: Comment
type: QuestionComment
has text: Err... what does that show apart from what you've already put in your question? Smells like differences between environments regarding line endings or buffering...
score: 0
comment on: http://stackoverflow.com/q/47772711

http://stackoverflow.com/comment/82401534
type: QuestionComment
has text: Can you just save that sheet as a `csv` and then try to read it as `df = pd.read_csv(path_to_csv, encoding='utf-16')`?? Wanted to see if that happens to `pd.read_csv` too
comment on: http://stackoverflow.com/q/47719494
score: 0
type: Comment

http://stackoverflow.com/comment/82620199
type: QuestionComment
score: 3
has text: If iterator should return strings, why not use `io.StringIO`? Like this: `string_data = StringIO(base64.decodestring(csv_rec).decode())`
type: Comment
comment on: http://stackoverflow.com/q/47828854

http://stackoverflow.com/comment/82431464
has text: checking with print() i was only able to determine the problem was in the drawBoard function, But the Tile() class itself and the tiles array are ok, since i can print it on console, the problem is when i try to draw.rect on to that grid, i was wondering if it may be because tiles is composed of tile() objects that it gets buggy
score: 0
comment on: http://stackoverflow.com/q/47735269
type: QuestionComment
type: Comment

http://stackoverflow.com/q/47700347
score: 42
has answer: http://stackoverflow.com/a/55099383
has answer: http://stackoverflow.com/a/68608368
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/74646544
possible better answer: http://stackoverflow.com/a/67501637
accepted answer: http://stackoverflow.com/a/47700674
tagged with: mysql-python
has answer: http://stackoverflow.com/a/67501637
has answer: http://stackoverflow.com/a/47700674
has answer: http://stackoverflow.com/a/47700752
has answer: http://stackoverflow.com/a/63220890
favorite count: 0
upvote count: 42
type: Question
has body: I want to connect MySQL database to my django project, but it is throwing an error : "django.core.exceptions.ImproperlyConfigured: Requested setting USE_I18N, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings." Trace: (myenv) LIBINGLADWINs-MacBook-Air:libinrenold$ django-admin dbshell Traceback (most recent call last): File "/Users/libinrenold/Desktop/djangoworks/myenv/bin/django-admin", line 11, in &lt;module&gt; sys.exit(execute_from_command_line()) File "/Users/libinrenold/Desktop/djangoworks/myenv/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/Users/libinrenold/Desktop/djangoworks/myenv/lib/python3.6/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/libinrenold/Desktop/djangoworks/myenv/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/Users/libinrenold/Desktop/djangoworks/myenv/lib/python3.6/site-packages/django/core/management/base.py", line 322, in execute saved_locale = translation.get_language() File "/Users/libinrenold/Desktop/djangoworks/myenv/lib/python3.6/site-packages/django/utils/translation/__init__.py", line 195, in get_language return _trans.get_language() File "/Users/libinrenold/Desktop/djangoworks/myenv/lib/python3.6/site-packages/django/utils/translation/__init__.py", line 59, in __getattr__ if settings.USE_I18N: File "/Users/libinrenold/Desktop/djangoworks/myenv/lib/python3.6/site-packages/django/conf/__init__.py", line 56, in __getattr__ self._setup(name) File "/Users/libinrenold/Desktop/djangoworks/myenv/lib/python3.6/site-packages/django/conf/__init__.py", line 39, in _setup % (desc, ENVIRONMENT_VARIABLE)) django.core.exceptions.ImproperlyConfigured: Requested setting USE_I18N, but set…
answer count: 9
has answer: http://stackoverflow.com/a/47700818
has answer: http://stackoverflow.com/a/67211524
has title: django.core.exceptions.ImproperlyConfigured: Requested setting USE_I18N, but settings are not configured
downvote count: 0
tagged with: django
tagged with: python

http://stackoverflow.com/comment/85727893
has text: @MartijnPieters Great answers, thank you! Just a comment, though - is this not massively frustrating? Very old mindset. If passing data to subprocesses over a network, for example, I understand the issue; but to do so between processes with local upwards of 50GB RAM, shared buses etc.. - who cares. Should be scalable. Issue a warning for Pete's sake. Don't hard break on a struct.error.
type: Comment
comment on: http://stackoverflow.com/a/47776649
score: 9
type: AnswerComment

http://stackoverflow.com/q/47817448
has comment: http://stackoverflow.com/comment/82597193
favorite count: 0
type: Question
tagged with: ipc
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82596556
has comment: http://stackoverflow.com/comment/82696000
linked to: http://stackoverflow.com/q/89228
has comment: http://stackoverflow.com/comment/82641333
has title: How to pass parameters from c++ to an already active python program?
has body: I am integrating a c++ code with a python program. I have a python script that in loop waits for input. The problem is that I have to pass this input from a c++ program and read the result. I cannot use files! For every input I have to return a value to the c++ program without stopping the script. The python program must be running because in its initialization generates a data structure which I cannot build every time (quite expensive). This is the python script prototype: while (true): input_string = input() result = my_function(input_string) return_result(result) I have a simple function my_function which computes a result (string) and I have to return this result to the calling c++ program (through the function return_result). I am looking for a solution specifically to send the input from a c++ program to a running python script for further processing.
has comment: http://stackoverflow.com/comment/82597375
tagged with: python
has comment: http://stackoverflow.com/comment/82598093
has comment: http://stackoverflow.com/comment/82596938
tagged with: c++
has comment: http://stackoverflow.com/comment/82597145
has comment: http://stackoverflow.com/comment/82597983
answer count: 0
has comment: http://stackoverflow.com/comment/82596524
score: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/47819550
type: Question
has title: How to use ManyToManyField of model inside itself?
type: UnansweredQuestion
tagged with: django
tagged with: django-models
tagged with: python
score: 2
linked to: http://stackoverflow.com/q/11721157
answer count: 0
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/82612350
has body: Scenario I have group of users interested in each others' activity. Whenever a user of this group sees a feed (record), or shows some activity (like, comment, star) and continues; then whenever the next user opens the app randomly and sees the feed or shows some activity (like, comment, star), so the app will lead the second user to the first user's footsteps until they ignore at least three feeds (records). The best I could come up with is a ManyToManyField model inside itself. By this method I will be able to classify every record (feed) and add all it's related feeds back to the same model even without adding a new record. Example: Sam saw feed 1 then Sam saw feed 5 then Sam saw feed 10 now it will add feed 5 and 10 as inner_feed to feed 1 and feed 10 to 5 Is something like this model possible in django? class NewsFeed(models.Model): id = models.AutoField(primary_key=True) user = models.ForeignKey(User, models.DO_NOTHING, related_name="feeduser") date_created = models.DateTimeField(default=timezone.now) last_update = models.DateTimeField(default=timezone.now) inner_feed = models.ManyToManyField(NewsFeed)
favorite count: 0

http://stackoverflow.com/a/47724202
has comment: http://stackoverflow.com/comment/82409653
type: Answer
accepted answer of: http://stackoverflow.com/q/47722693
answers question: http://stackoverflow.com/q/47722693
score: 0
type: AcceptedAnswer
has body: I am sure there are more elegant, functional, pythonic ways to do this... and I would love to know what they are. import numpy as np import pandas as pd # define dataframe df = pd.DataFrame(columns = ['bd', 'date']) df.loc[0, 'bd'] = None df.loc[0, 'date'] = '2017-11-01 09:00:00' df.loc[1, 'bd'] = [['Sulphur'], ['Green Tea']] df.loc[1, 'date'] = '2017-11-02 09:00:00' df.loc[2, 'bd'] = [['Green Tea'], ['Jasmine']] df.loc[2, 'date'] = '2017-11-03 09:00:00' print(df) # set the index df.set_index('date', inplace = True) # df['bd'] contains doubly nested lists # for item in column, for list in item, for string in list, add string to list cols = [] for ls2 in df['bd']: for ls1 in ls2: for string in ls1: if string not in cols: cols.append(string) # make a column for every string in df['bd'] for tea in cols: df[tea] = 0 # manual one-hot encoding; couldn't get pd.get_dummies() to work for row in df.iterrows(): for ls in row[1][0]: for el in ls: if el in df.columns: df.loc[row[0], el] = 1 df.drop('bd', axis = 1, inplace = True) df.fillna(0) I spent some time on this; here's some stuff that didn't totally work: I wasn't able to get this recursive function to work for me (blame me, not the function)... Flatten (an irregular) list of lists I tried get_dummies, but it can't hash a list, let alone a doubly nested list... https://pandas.pydata.org/pandas-docs/stable/generated/pandas.get_dummies.html I tried pivoting and pivot_table... https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.pivot.html I tried converting the list into a string, but that ended up being a dead end as well... Converting a Panda DF List into a string

http://stackoverflow.com/q/47735205
has answer: http://stackoverflow.com/a/47738941
score: 2
upvote count: 2
type: AnsweredQuestion
tagged with: deep-learning
downvote count: 0
tagged with: autoencoder
has title: Keras - Autoencoder for Text Analysis
answer count: 1
tagged with: machine-learning
tagged with: keras
has body: So I'm trying to create an autoencoder that will take text reviews and find a lower dimensional representation. I'm using keras and I want my loss function to compare the output of the AE to the output of the embedding layer. Unfortunately, it gives me the following error. I'm pretty sure the problem is with my loss function but I can't seem to resolve the issue. Autoencoder print X_train.shape input_i = Input(shape=(200,)) embedding = Embedding(input_dim=weights.shape[0],output_dim=weights.shape[1], weights=[weights])(input_i) encoded_h1 = Dense(64, activation='tanh')(embedding) encoded_h2 = Dense(32, activation='tanh')(encoded_h1) encoded_h3 = Dense(16, activation='tanh')(encoded_h2) encoded_h4 = Dense(8, activation='tanh')(encoded_h3) encoded_h5 = Dense(4, activation='tanh')(encoded_h4) latent = Dense(2, activation='tanh')(encoded_h5) decoder_h1 = Dense(4, activation='tanh')(latent) decoder_h2 = Dense(8, activation='tanh')(decoder_h1) decoder_h3 = Dense(16, activation='tanh')(decoder_h2) decoder_h4 = Dense(32, activation='tanh')(decoder_h3) decoder_h5 = Dense(64, activation='tanh')(decoder_h4) output = Dense(weights.shape[1], activation='tanh')(decoder_h5) autoencoder = Model(input_i,output) encoder = Model(input_i,latent) print autoencoder.summary() import keras.backend as K import tensorflow as tf def embedded_mse(x_true, e_pred): print output print embedding mse = K.mean(K.square(output - embedding)) print mse return tf.Session().run(mse) autoencoder.compile(optimizer='adadelta', loss=embedded_mse) autoencoder.fit(X_train,X_train,epochs=10, batch_size=256, validation_split=.1) Output (100000, 200) _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= input_47 (InputLayer) (None, 200) 0 _________________________________________________________________ embedding_31 (Embedding) (None, 200, 100) 21833700 __________________________________________________…
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47738941
tagged with: python

http://stackoverflow.com/q/47792242
has answer: http://stackoverflow.com/a/60742959
tagged with: datetime
has comment: http://stackoverflow.com/comment/82551407
linked to: http://stackoverflow.com/q/3463930
has answer: http://stackoverflow.com/a/67048834
has title: Rounding time off to the nearest second - Python
tagged with: python
has answer: http://stackoverflow.com/a/58415097
has answer: http://stackoverflow.com/a/68527017
has comment: http://stackoverflow.com/comment/82545698
has answer: http://stackoverflow.com/a/61225302
possible better answer: http://stackoverflow.com/a/49309848
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47795286
has answer: http://stackoverflow.com/a/47793826
has answer: http://stackoverflow.com/a/47793075
tagged with: python-2.7
has answer: http://stackoverflow.com/a/61319575
has comment: http://stackoverflow.com/comment/82546407
has answer: http://stackoverflow.com/a/72460290
has answer: http://stackoverflow.com/a/62925829
downvote count: 0
tagged with: pandas
has body: I have a large dataset with more than 500 000 date &amp; time stamps that look like this: date time 2017-06-25 00:31:53.993 2017-06-25 00:32:31.224 2017-06-25 00:33:11.223 2017-06-25 00:33:53.876 2017-06-25 00:34:31.219 2017-06-25 00:35:12.634 How do I round these timestamps off to the nearest second? My code looks like this: readcsv = pd.read_csv(filename) log_date = readcsv.date log_time = readcsv.time readcsv['date'] = pd.to_datetime(readcsv['date']).dt.date readcsv['time'] = pd.to_datetime(readcsv['time']).dt.time timestamp = [datetime.datetime.combine(log_date[i],log_time[i]) for i in range(len(log_date))] So now I have combined the dates and times into a list of datetime.datetime objects that looks like this: datetime.datetime(2017,6,25,00,31,53,993000) datetime.datetime(2017,6,25,00,32,31,224000) datetime.datetime(2017,6,25,00,33,11,223000) datetime.datetime(2017,6,25,00,33,53,876000) datetime.datetime(2017,6,25,00,34,31,219000) datetime.datetime(2017,6,25,00,35,12,634000) Where do I go from here? The df.timestamp.dt.round('1s') function doesn't seem to be working? Also when using .split() I was having issues when the seconds and minutes exceeded 59 Many thanks
has comment: http://stackoverflow.com/comment/82545619
has comment: http://stackoverflow.com/comment/82545562
has comment: http://stackoverflow.com/comment/82545553
upvote count: 28
favorite count: 0
has comment: http://stackoverflow.com/comment/82546677
score: 28
type: Question
accepted answer: http://stackoverflow.com/a/47793075
answer count: 12
has comment: http://stackoverflow.com/comment/82545546
has answer: http://stackoverflow.com/a/49309848

http://stackoverflow.com/comment/82612934
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47825180
has text: If there weren't already duplicates telling you how to do that, yes -- but that's been asked and answered many times.
type: Comment

http://stackoverflow.com/comment/82531141
comment on: http://stackoverflow.com/q/47784721
score: 0
has text: use `print()` to display items - and you will see on screen what you have in variables. You can also use full path in `inventoryFile` because it can save in different folder. And run in console/terminal/cmd.exe to see any error message.
type: QuestionComment
type: Comment

http://stackoverflow.com/a/47820097
type: Answer
has comment: http://stackoverflow.com/comment/82602737
has comment: http://stackoverflow.com/comment/82602384
has comment: http://stackoverflow.com/comment/82602450
upvote count: 3
score: 3
has comment: http://stackoverflow.com/comment/82602619
downvote count: 0
has comment: http://stackoverflow.com/comment/82602484
has comment: http://stackoverflow.com/comment/111825938
has body: I think this shows the principle. Note that returning None is not returning a new object because None is a singleton in Python, but of course it is still an object. Note also that __init__ will not be called as None is not an A class object. class A(): def __new__(cls, condition): if condition: obj = super().__new__(cls) return obj a = A(True) print(a) a1 = A(False) print(a1) This outputs: <__main__.A object at 0x7f64e65c62e8> None Edit: I tried to directly address your question, by showing the new behaviour. But I think all the answers and comments here are good contributions. So the proper answer is more about how you should do this kind of thing. I recommend, more or less in this order depending on your taste and context: "do the sane thing" by @Matt Messersmith. Test condition outside the class in client code and create the object only when appropriate. "If the check is complicated and I want to make it easier for the user, it is better placed inside the class." by MrCarnivore. Maybe, maybe not. You can group validation code in functions inside a module that you import and call from the outside, still like in 1) mostly because validation rules can be repetitive or even apply to different kinds of objects. This also hides validation complexity from the client code. raise an exception and use a try block in client code, by @Farhan.K. This is probably the more pythonic way if you test inside the class. You can still invoke an external data validation function inside the class for this. define a classmethod in the class that acts as an alternate constructor by @salparadise. This is a good option. go with a condition inside __new__ but do not pass it as an arg, or you have to use varargs to deal with that calls and __init__ calls. Then if you need varargs for other reasons, does not look a good option. So I end up recommending several answers and options, except my own example. But I was only illustrating the main point of the question anyway.
accepted answer of: http://stackoverflow.com/q/47819741
answers question: http://stackoverflow.com/q/47819741
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82602562

http://stackoverflow.com/q/47725308
score: 1
answer count: 1
has body: As I am beginning to work my way through web-sockets using Python (Django Channels in this case), I am beginning to wonder how companies scale chat applications. Take this specific problem: User A has a list of "group messages" that they are involved in. User A is capable of receiving notifications from each of the groups. Lets suppose User A has 5 different groups he would like real time notifications for. Does User A have 5 separate web socket connections? This is easiest, but the bulkiest and surely wont scale (what if we had 20 chats per user). It is quite easy to make a Django Channels "Group" that listens and sends notifications to one specific group of people. Does User A instead have 1 web socket connection taking all notifications from many different locations? If so, what is User A subscribing to on the backend? In Django Channels, a websocket is made when users subscribe to a "Group". If we wanted one user per "Group', this would seem counter intuitive. In this case, User A is subscribing to their own personal "Group" and other backend services are delivering messages to that specific "Group" based on other logic that is implemented when a message is received from any user using the service. This is very verbose and text heavy, but it diagrams an interesting problem that has scaled for other companies in the past. I appreciate any information or insight! (this is a list of the problems that I thought were basically the same (ignoring language and library use)) 1. Websocket multiple Channels vs. One Channel + Server Side handling [GroupChat]
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: django-channels
tagged with: websocket
has answer: http://stackoverflow.com/a/47725935
tagged with: django
tagged with: python
downvote count: 0
has title: Websockets on production chat apps:
upvote count: 1
linked to: http://stackoverflow.com/q/32943299

http://stackoverflow.com/comment/82666469
score: 0
has text: I talked about the method later on in my post; however it's not what I'd like to do, I'd like to replicate the behaviour of something like `@property`, but I'm starting to think that it's the only proper way to do it without diving into internals.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47851050

http://stackoverflow.com/a/47737599
type: Answer
has comment: http://stackoverflow.com/comment/82435558
has comment: http://stackoverflow.com/comment/82435590
score: 11
accepted answer of: http://stackoverflow.com/q/47737277
has body: Specify the column names you are assigning data to i.e df = pd.DataFrame(columns=["a","b","c","d"]) df.set_index(['a', 'b'], inplace = True) df.loc[('3','4'),['c','d']] = [4,5] df.loc[('4','4'),['c','d']] = [3,1] c d a b 3 4 4.0 5.0 4 4 3.0 1.0 Also if you have a comma separated file then you can use read_csv i.e : import io import pandas as pd st = '''2017-12-08 15:29:58:740657,245.0,426001,248.65,APPL,190342,2075673,249.35,244.2 2017-12-08 16:29:58:740657,245.0,426001,248.65,GOOGL,190342,2075673,249.35,244.2 2017-12-08 18:29:58:740657,245.0,426001,248.65,GOOGL,190342,2075673,249.35,244.2 ''' #instead of `io`, add the source name df = pd.read_csv(io.StringIO(st),header=None) # Now set the index and select what you want df.set_index([0,4])[[1,7]] 1 7 0 4 2017-12-08 15:29:58.740657 APPL 245.0 249.35 2017-12-08 16:29:58.740657 GOOGL 245.0 249.35 2017-12-08 18:29:58.740657 GOOGL 245.0 249.35
upvote count: 11
has comment: http://stackoverflow.com/comment/82435526
answers question: http://stackoverflow.com/q/47737277
has comment: http://stackoverflow.com/comment/82435474
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82435668
downvote count: 0
has comment: http://stackoverflow.com/comment/82435540
has comment: http://stackoverflow.com/comment/82435619
has comment: http://stackoverflow.com/comment/82435464

http://stackoverflow.com/q/47706045
tagged with: python
has body: I am trying to access the sequence on this webpage: https://www.ncbi.nlm.nih.gov/protein/EGW15053.1?report=fasta The sequence is stored under the div class="seq gbff". Each line is stored under &lt;span class='ff_line' id='gi_344258949_1"&gt; *line 1 of sequence* &lt;/span&gt; When I try to search for the spans containing the sequence, beautiful soup returns None. Same problem when I try to look at the children or content of the div above the spans. Here is the code: import requests import re from bs4 import BeautifulSoup # Create a variable with the url url = 'https://www.ncbi.nlm.nih.gov/protein/EGW15053.1?report=fasta' # Use requests to get the contents r = requests.get(url) # Get the text of the contents html_content = r.text # Convert the html content into a beautiful soup object soup = BeautifulSoup(html_content, 'html.parser') div = soup.find_all('div', attrs={'class', 'seq gbff'}) for each in div.children: print(each) soup.find_all('span', aatrs={'class', 'ff_line'}) Neither method works and I'd greatly appreciate any help :D
has title: BeautifulSoup doesn't find all spans or children
score: 0
answer count: 1
tagged with: beautifulsoup
type: Question
has answer: http://stackoverflow.com/a/47706195
type: UnansweredQuestion

http://stackoverflow.com/q/47736326
accepted answer: http://stackoverflow.com/a/47736398
has comment: http://stackoverflow.com/comment/82433076
tagged with: arrays
tagged with: python
tagged with: firebase
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/47736398
has comment: http://stackoverflow.com/comment/82433107
has title: Python TypeError: Object of type 'ndarray' is not JSON serializable
answer count: 1
has comment: http://stackoverflow.com/comment/82433172
type: Question
has body: I was having some problem when trying to extract data out from array in Python. I got this array: [array([ 349.11759027]), array([ 306.51289706]), array([ 387.37637654]), array([ 348.15424288]), array([ 386.3088823]), array([ 356.0820971]), array([ 446.37942998]), array([ 394.73726333]), array([ 434.91548947]), array([ 507.92351186]), array([ 435.48301334]), array([ 652.74389728])] I am trying to extract out the value, and then add to firebase. The expected output as such: Jan: 349.11759027 Feb: 306.51289706 Mar: 387.37637654 ... Dec: 652.74389728 And my code: month = 0 for t in p: month = month + 1 result = firebase.post('/profit', {month : t}) Any ideas? Thanks!

http://stackoverflow.com/q/47773474
favorite count: 0
type: Question
has title: Loading Keras model error: No Opkernel was registered to support Op 'Assign' with these attrs
has comment: http://stackoverflow.com/comment/82509733
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82509478
tagged with: python
has answer: http://stackoverflow.com/a/48029674
has comment: http://stackoverflow.com/comment/82537591
has comment: http://stackoverflow.com/comment/82513219
has comment: http://stackoverflow.com/comment/82508884
tagged with: raspberry-pi
score: 1
answer count: 1
has body: I've used Floyd hub to to train the following model and saved it # Create the model model = Sequential() model.add(Conv2D(32, (3, 3), input_shape=(3, 32, 32), activation='relu', padding='same')) model.add(Dropout(0.2)) model.add(Conv2D(32, (3, 3), activation='relu', padding='same')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Conv2D(64, (3, 3), activation='relu', padding='same')) model.add(Dropout(0.2)) model.add(Conv2D(64, (3, 3), activation='relu', padding='same')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Conv2D(128, (3, 3), activation='relu', padding='same')) model.add(Dropout(0.2)) model.add(Conv2D(128, (3, 3), activation='relu', padding='same')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Flatten()) model.add(Dropout(0.2)) model.add(Dense(1024, activation='relu', kernel_constraint=maxnorm(3))) model.add(Dropout(0.2)) model.add(Dense(512, activation='relu', kernel_constraint=maxnorm(3))) model.add(Dropout(0.2)) model.add(Dense(num_classes, activation='softmax')) # Compile model epochs = 50 adammax = keras.optimizers.Adamax(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=1e-08, decay=0.0) model.compile(loss='categorical_crossentropy', optimizer=adammax, metrics=['accuracy']) print(model.summary()) When I try to load it on my PC, it's working fine. But when I load it on the Raspberry Pi I get the following error. I tried also to save just the weights and load them, but it didn't work and I got the same error. I am using the same version of Tensorflow as Floyd hub on the Raspberry Pi.
downvote count: 0
upvote count: 1
tagged with: keras
tagged with: tensorflow

http://stackoverflow.com/comment/82397803
score: 2
comment on: http://stackoverflow.com/q/47718761
type: Comment
has text: Possible duplicate of [Python replace multiple strings](https://stackoverflow.com/questions/6116978/python-replace-multiple-strings)
type: QuestionComment

http://stackoverflow.com/comment/82772738
has text: Just once more explaining to people why this solves my problem and ikkuh's solution does not: Pavlo's solution also consistently sorts between two dictionaries that have the same keys but different values.
comment on: http://stackoverflow.com/a/47891763
type: Comment
score: 1
type: AnswerComment

asynchronous
tags question: http://stackoverflow.com/q/47739236
tags question: http://stackoverflow.com/q/47759603
tags question: http://stackoverflow.com/q/47806779
tags question: http://stackoverflow.com/q/47765822
type: Tag
tags question: http://stackoverflow.com/q/47798504
tag name: asynchronous
tags question: http://stackoverflow.com/q/47765084
tags question: http://stackoverflow.com/q/47710052
tags question: http://stackoverflow.com/q/47705691

http://stackoverflow.com/q/47835600
has answer: http://stackoverflow.com/a/47847104
favorite count: 0
has comment: http://stackoverflow.com/comment/82634762
has comment: http://stackoverflow.com/comment/82635939
type: Question
has body: My problem is that when I check the python3 version I get 3.6.0 but when I install python3 with HomeBrew it tells me that I have python 3.6.3. installed. How do I get my computer to tell me that I have python 3.6.3 when I use the python3 --version command? As you can see in the image, that is the problem that I have, how do I fix it? python3: stable 3.6.3 (bottled), devel 3.7.0a3, HEAD Interpreted, interactive, object-oriented programming language https://www.python.org/ /usr/local/Cellar/python3/3.5.2_3 (7,720 files, 109.4MB) Built from source on 2016-11-14 at 18:24:57 /usr/local/Cellar/python3/3.6.3 (7,973 files, 111MB) Built from source on 2017-12-15 at 10:26:40 From: https://github.com/Homebrew/homebrew-core/blob/master/Formula/python3.rb After I typed `brew info python3' then I got the output that you see in the above image. wireless-10-105-105-109:~ johnhsu$ echo $PATH /Library/Frameworks/Python.framework/Versions/2.7/bin:/Library/Frameworks/Python.framework/Versions/3.6/bin:/usr/local/bin:/usr/local/sbin:/Library/Frameworks/Python.framework/Versions/3.5/bin:/Library/Frameworks/Python.framework/Versions/2.7/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin ' Also when I checked what path i have, this is what I got. Which looks very different than what it is supposed to look like, maybe? When I enter a command which python3 it does this. Johns-Air:~ johnhsu$ which python3 /Library/Frameworks/Python.framework/Versions/3.6/bin/python3 However, when I use 'brew info python3', it gives me this: /usr/local/Cellar/python3/3.5.2_3 (7,720 files, 109.4MB) Built from source on 2016-11-14 at 18:24:57 /usr/local/Cellar/python3/3.6.3 (7,973 files, 111MB) * Built from source on 2017-12-15 at 10:26:40
has comment: http://stackoverflow.com/comment/82634737
has title: How do I use the python3 version that is installed in Homebrew instead of the one that is installed in the Library?
linked to: http://stackoverflow.com/q/10343834
tagged with: terminal
has comment: http://stackoverflow.com/comment/82635517
has comment: http://stackoverflow.com/comment/82635307
tagged with: homebrew
linked to: http://stackoverflow.com/q/5157678
has comment: http://stackoverflow.com/comment/82635446
has answer: http://stackoverflow.com/a/47836554
accepted answer: http://stackoverflow.com/a/47847104
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/82636418
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82634868
answer count: 2
has comment: http://stackoverflow.com/comment/82634795
possible better answer: http://stackoverflow.com/a/47836554
upvote count: 0
has comment: http://stackoverflow.com/comment/82635336
tagged with: macos
has comment: http://stackoverflow.com/comment/82636682
downvote count: 1

http://stackoverflow.com/comment/82368544
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47702450
has text: When using APSW, the backup API can do this.

http://stackoverflow.com/q/47736282
tagged with: python
has comment: http://stackoverflow.com/comment/82433674
has body: When I try to run this code under Python 3.6: import sys print &gt;&gt;sys.stderr, 'waiting for a connection' I get this TypeError: Traceback (most recent call last): File "D:/Users/Chanhc1997/Desktop/test_c.py", line 8, in &lt;module&gt; print &gt;&gt;sys.stderr, 'waiting for a connection' TypeError: unsupported operand type(s) for &gt;&gt;: 'builtin_function_or_method' and 'PseudoOutputFile'. Did you mean "print(&lt;message&gt;, file=&lt;output_stream&gt;)"? The code works fine in Python 2. What's going on?
tagged with: python-3.6
favorite count: 0
tagged with: printing
score: 3
tagged with: python-2.x
type: Question
has comment: http://stackoverflow.com/comment/82440897
tagged with: python-3.x
upvote count: 3
type: UnansweredQuestion
has title: TypeError: unsupported operand type(s) in "print >> ..." statement
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/47740712

http://stackoverflow.com/comment/82519213
has text: IMHO, an io.TextIOWrapper over the decompressed stream is all you need, but I could not understand how you get your data...
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47778579

http://stackoverflow.com/comment/82368604
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47704156
has text: You will need the OrderedDict type and any handy tutorial on sorting.

http://stackoverflow.com/q/47811757
has answer: http://stackoverflow.com/a/47817957
has title: How to load row major data from text file in numpy
has comment: http://stackoverflow.com/comment/82588609
tagged with: scipy
has comment: http://stackoverflow.com/comment/82585404
favorite count: 0
type: Question
tagged with: numpy
has body: How can row-major text data files be loaded with numpy? The loadtxt(..) function loads column-major, i.e. the data lies in rows below names in the first row, how can I load data where the names are in the 1st column and data in subsequent columns? Row major: field 1: d1, d2, d3, ... field 2: d1, d2, d3, ... field n: ...
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/82589051
has comment: http://stackoverflow.com/comment/82585886
has comment: http://stackoverflow.com/comment/82588663
downvote count: 0
score: 1
upvote count: 1
answer count: 1

http://stackoverflow.com/comment/82428129
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47733419
has text: I don't have the "play triangle" in the top right, so I have to imagine you are using some sort of plugin I don't have. For Python, I use the MS one: https://marketplace.visualstudio.com/items?itemName=ms-python.python . Any indication what that plugin is?
type: Comment

http://stackoverflow.com/q/47828067
has comment: http://stackoverflow.com/comment/82618371
type: Question
has body: Given the following python dataframe: &gt;&gt;&gt; import pandas &gt;&gt;&gt; df1 = pandas.DataFrame({"dish" : ["fish", "chicken", "fish", "chicken", "chicken", "veg","veg"], ... "location" : ["central", "central", "north", "north", "south", "central", "north"], ... "sales" : [1,3,5,2,4,2,2]}) &gt;&gt;&gt; total_sales = df1.groupby(by="dish").sum().reset_index().set_index(["dish"]) &gt;&gt;&gt; df1["proportion_sales"] = df1.apply((lambda row: row["sales"]/total_sales.loc[row["dish"]]), axis=1) &gt;&gt;&gt; df1 dish location sales proportion_sales 0 fish central 1 0.166667 1 chicken central 3 0.333333 2 fish north 5 0.833333 3 chicken north 2 0.222222 4 chicken south 4 0.444444 5 veg central 2 0.500000 6 veg north 2 0.500000 I want to find out the ranked 1 and ranked 2 dish for each location. For example, in central, chicken is ranked 1 and fish is ranked 3. How do I update the dish_rank_in_location df to be like so? This is what I have: dish location sales proportion_sales rank 0 fish central 1 0.166667 1 1 chicken central 3 0.333333 1 2 fish north 5 0.833333 1 3 chicken north 2 0.222222 1 4 chicken south 4 0.444444 1 5 veg central 2 0.500000 1 6 veg north 2 0.500000 1 expected output: dish location sales proportion_sales dish_rank_in_location 0 fish central 1 0.166667 3 1 chicken central 3 0.333333 2 2 fish north 5 0.833333 1 3 chicken north 2 0.222222 3 4 chicken south 4 0.444444 1 5 veg central 2 0.500000 1 6 veg north 2 0.500000 2
has title: Find rank 1 and rank 2 of grouped values in DF
accepted answer: http://stackoverflow.com/a/47828229
downvote count: 0
has answer: http://stackoverflow.com/a/47828229
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/82618469
has comment: http://stackoverflow.com/comment/82618394
type: AnsweredQuestion
tagged with: pandas
score: 1
answer count: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/82618411
has comment: http://stackoverflow.com/comment/82618401
favorite count: 0

http://stackoverflow.com/a/47737939
type: Answer
has comment: http://stackoverflow.com/comment/82436205
has body: You could achieve what you want by storing the names in lists, but it makes the code more cluttered and less efficient, due to the extra layer of indirection. super_hero_names = { 'Superman' : ['Clark Kent'], 'Spiderman' : ['Peter Parker'], } batman = {'Batman' : ['Bruce']} super_hero_names.update(batman) batman['Batman'][0] = 'Bruce Wayne' print(super_hero_names) output {'Superman': ['Clark Kent'], 'Spiderman': ['Peter Parker'], 'Batman': ['Bruce Wayne']} We could also do that update using batman['Batman'][0] += ' Wayne'
downvote count: 0
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/82436263
answers question: http://stackoverflow.com/q/47737470

http://stackoverflow.com/comment/82429268
comment on: http://stackoverflow.com/q/47732621
type: Comment
has text: Where do you define `wait`? Maybe you are missing an import?
type: QuestionComment
score: 0

http://stackoverflow.com/comment/82460574
comment on: http://stackoverflow.com/q/47742592
type: QuestionComment
has text: Have you read the note on the front page of [GeoAlchemy 2](https://geoalchemy-2.readthedocs.io/en/latest/)? "Note: GeoAlchemy 2 doesn’t currently support other dialects than PostgreSQL/PostGIS."
score: 3
type: Comment

http://stackoverflow.com/a/47774584
accepted answer of: http://stackoverflow.com/q/47774510
has comment: http://stackoverflow.com/comment/82510210
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47774510
type: Answer
has comment: http://stackoverflow.com/comment/82511189
score: 0
has body: Something like this, with list comprehension, linktext = "linktext1" [a['href'] for a in soup.find_all('a', href=True) if linktext in a.text.strip()] You may safely replace if condition if you wish exact match. [a['href'] for a in soup.find_all('a', href=True) if linktext == a.text.strip()]

http://stackoverflow.com/q/47854710
downvote count: 0
has answer: http://stackoverflow.com/a/47874070
favorite count: 0
has body: I am doing a script where I want to change the order of some sentences n = 4 l=[] t = [] for i in range(n): line = input() if i%2 == 0: t += line else: l+=line for i in range(len(l)): print(l[i]) for i in range(len(t)): print(t[i]) I input, in order, the following lines: I like Trains I like apples I like pears I like bananas I want it to print: I like apples, I like bananas, I like Trains, I like pears, but it doesn't prints it, it prints separate letters.
type: Question
tagged with: python-3.x
has title: Issue for and lists and separate characters
has answer: http://stackoverflow.com/a/47854745
type: UnansweredQuestion
tagged with: python
score: 2
tagged with: list
answer count: 2
tagged with: for-loop
upvote count: 2

http://stackoverflow.com/q/47723436
has answer: http://stackoverflow.com/a/47762208
tagged with: google-app-engine
score: 1
tagged with: python
tagged with: google-cloud-endpoints
answer count: 2
has title: WSGI error with Google Endpoints Tutorial
has comment: http://stackoverflow.com/comment/85175434
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49602992
downvote count: 0
upvote count: 1
has body: I'm trying to run this Google Endpoints python tutorial. Traceback (most recent call last): File "main.py", line 19, in &lt;module&gt; import endpoints File "/home/mica/.local/lib/python2.7/site-packages/endpoints/__init__.py", line 27, in &lt;module&gt; from .apiserving import * File "/home/mica/.local/lib/python2.7/site-packages/endpoints/apiserving.py", line 81, in &lt;module&gt; from protorpc.wsgi import service as wsgi_service ImportError: No module named wsgi The error clearly comes from a python library. How am I supposed to fix the issue?
favorite count: 0
type: Question

http://stackoverflow.com/a/47731754
type: Answer
has body: I would: def key_space(): # simply spawn a new bullet and put it into your bullets list def advance_bullet(): # call this after paintnig all bullets in frame # iterate over all bullets inside bullets, advance the Y position by 3 def frame(): # add code to paint all bullets inside bullets - and call advance_bullets() In the code that checks for collision with enemies: # remove a bullet from bullets when its outside your screen (or passed all enemies max y coord) - no need to track that bullet anymore if you ned to advance the bullets slower then your main loops intervall, make a "framespassed" counter and see if framespassed % something == 0 and only then advance your bullets. Adapted to what you already have You need to change these parts: def frame(): global bullets pass ship = turtle.Turtle() ship.pu() ship.ht() ship.setpos(userx, -300) ship.pd() ship.circle(5) # debugging all bullets: # print(bullets) # remove this for idx in range(0,len(bullets)): # paint ALL bullets in the bullets list bulletTurtle = turtle.Turtle() b = bullets[idx] # current bullet we are painting bulletTurtle.pu() bulletTurtle.ht() bulletTurtle.setpos(b[0], b[1]) bulletTurtle.pd() bulletTurtle.circle(2) b[1] += 13 # quick and dirty approach, move bulltet after painting # to save another complete bullets-foreach-loop # quick n dirty bullet removal for out of screen bullets # normally I would do this probably in your "check if enemy hit" # method as you are going over bullets there as well and can remove # them as soon as they passed all enemies bullets = [x for x in bullets if x[1] &lt; 500] def key_space(): global x global y global bullets bullets.append([userx,-300]) # start a new bullet at current player position Edit: You might want to take a look at turtle.shape, turtle.size and turtle.stamp - by using a "circle" shape and a size that fits, you might be able to "stamp" this shape down. Advantage: you can simply delete the stamped shape - by its integer-id. I haven*t worked with turtle eve…
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47731543
score: 1

http://stackoverflow.com/q/47698721
has comment: http://stackoverflow.com/comment/82358320
has answer: http://stackoverflow.com/a/47699175
has comment: http://stackoverflow.com/comment/82357532
has title: Is there a way to infuse the input variable in regex?
has comment: http://stackoverflow.com/comment/82358641
score: -3
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/82357550
duplicate of: http://stackoverflow.com/q/34561638
has comment: http://stackoverflow.com/comment/82358519
type: AnsweredQuestion
upvote count: 0
accepted answer: http://stackoverflow.com/a/47699175
answer count: 2
has comment: http://stackoverflow.com/comment/82357752
downvote count: 3
has body: EDIT: So apparently, this is a string interpolation in regex. Thanks for clarifying. I have a input function that is named omj. omj When I run it, it gives me "obik" I then use that output in this regex function re.findall("\w*obik\w*",dataframe) I received EXACTLY what I wanted, which is the answer "Yaobikuni" Notice that "obik" is in the word, and there is only one match for it. Is there a way to put the input omj in the regex function to get Yaobikuni straightforwardly, or is this the only way it would work? EDIT: I don't understand why people are downvoting, but I thought I made it clear that omj can be considered as an input string that gives the answer obik. omj = """obik""" EDIT2: Thank you for the help @Nick Chapman . I tried this on the first time and I thought it might not have been possible to infuse the input omj on an regex function: re.findall("\w*"omj"\w*",dataframe)
linked to: http://stackoverflow.com/q/34561638
possible better answer: http://stackoverflow.com/a/47699220
has comment: http://stackoverflow.com/comment/82357954
has answer: http://stackoverflow.com/a/47699220
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82357372

http://stackoverflow.com/comment/82457644
comment on: http://stackoverflow.com/q/47729898
type: Comment
type: QuestionComment
score: 0
has text: You can extend the DecisionTreeClassifier and modify/add code in the `fit` function. But the better way to estimate the relevance of a particular feature is to look at the `feature_importances` of a trained tree. See an example [here](http://scikit-learn.org/stable/modules/feature_selection.html#tree-based-feature-selection)

http://stackoverflow.com/comment/82664180
has text: Why it does not have mathematical sense? In some sense it may be thought of as analytical continuation of real function into complex plane. Yes, spline is a piecewise polynomial function, it seems pretty easy to insert a complex value in polynomial in each piece...
type: AnswerComment
type: Comment
score: 0
comment on: http://stackoverflow.com/a/47837258

http://stackoverflow.com/comment/82404585
has text: "Other solutions" not suitable, because i planned to extend functional. "Information about webserver" - i need to know capabilities, and after that i request these capabilities from webhoster. Most of hosters offers python.
score: 0
comment on: http://stackoverflow.com/q/47719643
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47741612
accepted answer of: http://stackoverflow.com/q/47741402
score: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47741402
downvote count: 0
upvote count: 1
has body: aggs = {"Price":"mean", "Qty":"sum","Time":"min"} df = df.groupby(["Date","Symb", "Side"])"Price","Qty","Time".agg(aggs) df = df.reset_index()
type: Answer

http://stackoverflow.com/a/47705392
type: Answer
score: 0
has body: As the error suggests, make sure your outer_function() (or whatever initiates it) is called from within an __main__ guard, e.g. if __name__ == "__main__": outer_function() It doesn't have to be the outer_function() but you need to trace it all back to the first step that initializes the chain that ultimately leads to the call to multiprocessing.Process() and put it within the above block. This is because on non-forking systems multiple processes are essentially run as subprocesses so creating new processes from the main script would end up with an infinite recursion/processes spawning. You can read more about it in this answer. Because of that, you have to make sure your multiprocessing initialization code executes only once which is where the __main__ guard comes in.
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47705228
answers question: http://stackoverflow.com/q/47705228

http://stackoverflow.com/q/47831966
answer count: 1
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82627033
tagged with: python
has comment: http://stackoverflow.com/comment/82626881
score: -1
has comment: http://stackoverflow.com/comment/82626914
has title: Python objects sharing information
type: AnsweredQuestion
has body: I have a workflow that parses a url and loadsdata. The flow is controlled through URLProcessor. In this current setup I'm passing the url variable across all classes just to display the process start and completion of process. I feel its redundant information. Is there a way to share the url variable across all objects instead of explicity passing it. class ParseURL(object): def __init__(self, url): self.url = url def parseoperation(self): print 'start operation for url {0}'.format(self.url) pass print 'end operation for url {0}'.format(self.url) return None class LoadData(object): def __init__(self, url, data=None): self.url = url self.data = data def load_operation(self): print 'start operation for url {0}'.format(self.url) pass print 'end operation for url {0}'.format(self.url) class URLProcessor(object): def __init__(self, url, parseurl, loaddata): self.url = url self.parseurl = parseurl self.loaddata = loaddata def run(self): print 'start operation for url {0}'.format(self.url) self.parseurl.parseoperation() self.loaddata.load_operation() print 'end operation for url {0}'.format(self.url) url = 'http://test.com' parseurl = ParseURL(url) loaddata = LoadData(url) urlprocessor = URLProcessor(url, parseurl, loaddata) urlprocessor.run()
accepted answer: http://stackoverflow.com/a/47832583
upvote count: 0
has answer: http://stackoverflow.com/a/47832583
has comment: http://stackoverflow.com/comment/82626778

http://stackoverflow.com/q/47783711
downvote count: 7
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82528996
has comment: http://stackoverflow.com/comment/82528918
tagged with: python
has title: How to convert strings to int and percentage in dataframe
has answer: http://stackoverflow.com/a/47783791
has body: I have imported this CSV file. I am trying to cast the following strings: Avg Spending Hospital to integer, and Percent Spending Hospital to percentage. This is my code: df['Avg Spending Hospital'] = (df['Avg Spending Hospital']).astype(int) My code is throwing an error.
type: UnansweredQuestion
answer count: 1
upvote count: 1
score: -6

http://stackoverflow.com/comment/82570114
type: AnswerComment
comment on: http://stackoverflow.com/a/47804171
has text: Don't use a lambda expression as a one-line `def` statement.
type: Comment
score: 0

http://stackoverflow.com/q/47844977
upvote count: 3
downvote count: 0
answer count: 1
tagged with: django
has comment: http://stackoverflow.com/comment/82654499
favorite count: 0
type: Question
type: UnansweredQuestion
score: 3
tagged with: python
has body: I just began to work with Django and I would like to create a submit form in a html form that communicates with another html page. Page1.html : Submit form, let's suppose I type "Hello world" then I click on submit, I'm redirected to page2.html Page2.html : Thanks to the Get request Page2.html display "Hello World" because the page2 has been loaded from page1 In page1 I use this form : Search In Views.py I have this function : def page2(request): if request.method == 'GET': search_query = request.GET.get('search_box', None) return render(request, 'interface/recherche.html', locals()) But I don't know how to display how the word that has been typed in page1 in page2, thank you very much for your answer :)
has answer: http://stackoverflow.com/a/47845024
has title: How to get value to one html page to another in Django?

http://stackoverflow.com/a/47855569
score: -1
answers question: http://stackoverflow.com/q/47855488
has comment: http://stackoverflow.com/comment/82690565
upvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/82676710
has body: *arg means the method takes variable length of argument based on the positional values. The below example may throw a light on the concept! Hope it helps! &gt;&gt;&gt; def foo(a=1, b=None, unit=1, *arg): ... print(arg) ... print(a+min(arg)) ... &gt;&gt;&gt; foo(*[1,2,3,5,6,7]) (5, 6, 7) 6
downvote count: 1
has comment: http://stackoverflow.com/comment/82675258

http://stackoverflow.com/comment/82397635
comment on: http://stackoverflow.com/q/47718633
has text: Welcome to [SO]! One thing you should know about our editor. When you [edit] a question, highlight a code snippet and click the `{}` button. That will format your code for maximum readability.
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/109804050
comment on: http://stackoverflow.com/a/47762594
type: Comment
score: 0
type: AnswerComment
has text: @DanielV With Python ints being arbitrary precision there is no good way of deciding which bit should be the sign bit, so I guess the `0b...` is always interpreted as positive. You can put an explicit `-` in front of it but have no influence on how it is encoded. `numpy` gets to see in the first case the positive number `2**16-2**8` which is too large for `int16`, so it goes for the smallest size that can accomodate both, this number and a sign. In the other case `-2**8` everything fits an `int16`, so no coercion needed.

http://stackoverflow.com/comment/82802614
comment on: http://stackoverflow.com/a/47763650
type: Comment
score: 0
type: AnswerComment
has text: Just a heads up, this contains the entire json file as one object and stores it in the list, making the list length only 1. But each entry in the list should be a tweet.

http://stackoverflow.com/comment/82499194
type: AnswerComment
comment on: http://stackoverflow.com/a/47760881
has text: It works like a charm ! thanks ! About the groupby, I don't get what you did with the lambda and how it works ?
type: Comment
score: 0

http://stackoverflow.com/comment/84056338
has text: I think the windowing functions on RDDs/DStreams only operate on rows, not on e.g. event time
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47805216
score: 0

http://stackoverflow.com/comment/82481334
has text: Yes , it easier to do it in the same file
type: Comment
comment on: http://stackoverflow.com/q/47759956
score: 1
type: QuestionComment

http://stackoverflow.com/q/47810819
has comment: http://stackoverflow.com/comment/82620852
tagged with: python
has comment: http://stackoverflow.com/comment/82856699
linked to: http://stackoverflow.com/q/47795836
has comment: http://stackoverflow.com/comment/82618658
score: 0
tagged with: performance
has comment: http://stackoverflow.com/comment/82617624
has comment: http://stackoverflow.com/comment/83075565
has comment: http://stackoverflow.com/comment/82584756
tagged with: multiprocessing
type: Question
tagged with: locking
answer count: 0
has title: Performance of my python program goes down while using multiprocessing
linked to: http://stackoverflow.com/q/10154487
has body: I'm trying to make the following program run faster, so I used multiprocessing as suggested in the responses to the last question I asked, also on the related question. So, I've got the following program which runs very slowly than before: import threading from threading import Thread from multiprocessing import Process def sim_QxD_word(query, document, model, alpha, outOfVocab, lock): #word_level sim_w = {} for q in set(query.split()): sim_w[q] = {} qE = [] if q in model.vocab: qE = model[q] elif q in outOfVocab: qE = outOfVocab[q] else: qE = numpy.random.rand(model.layer1_size) # random vector lock.acquire() outOfVocab[q] = qE lock.release() for d in set(document.split()): dE = [] if d in model.vocab: dE = model[d] elif d in outOfVocab: dE = outOfVocab[d] else: dE = numpy.random.rand(model.layer1_size) # random vector lock.acquire() outOfVocab[d] = dE lock.release() sim_w[q][d] = sim(qE,dE,alpha) return (sim_w, outOfVocab) def sim_QxD_sequences(query, document, model, outOfVocab, alpha, lock): #sequence_level # 1. extract document sequences document_sequences = [] for i in range(len(document.split())-len(query.split())): document_sequences.append(" ".join(document.split()[i:i+len(query.split())])) # 2. compute similarities with a query sentence lock.acquire() query_vec, outOfVocab = avg_sequenceToVec(query, model, outOfVocab, lock) lock.release() sim_QxD = {} for s in document_sequences: lock.acquire() s_vec, outOfVocab = avg_sequenceToVec(s, model, outOfVocab, lock) lock.release() sim_QxD[s] = sim(query_vec, s_vec, alpha) return (sim_QxD, outOfVocab) def word_level(q_clean, d_text, model, alpha, outOfVocab, out_w, q, ext_id, lock): print("in word_level") sim_w, outOfVocab = sim_QxD_word(q_clean, d_text, model, alpha, outOfVocab, lock) numpy.save(join(out_w, str(q)+ext_id+"word_interactions.npy"), sim_w) def sequence_level(q_clean, d_text, model, outOfVocab, alpha, out_s, q, ext_id, lock): print("in sequence_level") sim_s, outOfVocab = sim_QxD_sequences(q_clean, d…
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82588291

http://stackoverflow.com/comment/82486754
comment on: http://stackoverflow.com/a/47762454
score: 0
type: Comment
has text: I have been trying to find a solution for about 3 days to this problem, you have no idea how grateful i am to you. Could you just quickly explain where i was mistaking? The code now is working wonderfully, thank you, you really made my day.
type: AnswerComment

http://stackoverflow.com/comment/82571042
type: QuestionComment
has text: For the above query the answer import "SSHClientInteraction" from paramiko_expect. But now the issue is able to get into config mode but unable to send further commands
comment on: http://stackoverflow.com/q/47715816
score: 0
type: Comment

http://stackoverflow.com/a/47833843
type: Answer
has comment: http://stackoverflow.com/comment/85175262
score: 1
downvote count: 0
upvote count: 1
has body: Pure Python Approach Generator comprehension An alternative pure python implementation with generators and list comprehensions. Could be more memory efficient compared to your code but probably will be slower compared to numpy version. This will be faster for sorted arrays. def pywheregen(a, b): l = ((ia,ib) for ia,j in enumerate(a) for ib,k in enumerate(b) if j == k) a_idx,b_idx = zip(*l) return a_idx,b_idx Python for loop considering array sorting Here is an alternative version that uses simple python for loop and takes into consideration that the arrays are sorted so that it only checks the pairs it needs to. def pywhere(a, b): l = [] a.sort() b.sort() match = 0 for ia,j in enumerate(a): ib = match while ib &lt; len(b) and j &gt;= b[ib]: if j == b[ib]: l.append(((ia,ib))) if b[match] &lt; b[ib]: match = ib ib += 1 a_ind,b_ind = zip(*l) return a_ind, b_ind Timings I compared the timings using the mock_data() function of @Paul Panzer and compared it with findwhere() and f_D() the np.outer approach of @Divakar. findwhere() still performs best but pywhere() does not so bad considering it is pure python. pywheregen() fails and surprisingly f_D() takes longer time. They both fail for N = 10^6. I could not run sqlwhere due to an unrelated error in the heapq module. In [2]: a, b = mock_data(10000) In [10]: %timeit -n 10 findwhere(a,b) 10 loops, best of 3: 1.62 ms per loop In [11]: %timeit -n 10 pywhere(a,b) 10 loops, best of 3: 20.6 ms per loop In [12]: %timeit pywheregen(a,b) 1 loop, best of 3: 12.7 s per loop In [13]: %timeit -n 10 f_D(a,b) 10 loops, best of 3: 476 ms per loop In [14]: a, b = mock_data(1000000) In [15]: %timeit -n 10 findwhere(a,b) 10 loops, best of 3: 109 ms per loop In [16]: %timeit -n 10 pywhere(a,b) 10 loops, best of 3: 2.51 s per loop
answers question: http://stackoverflow.com/q/47831287

data-fitting
tags question: http://stackoverflow.com/q/47848096
type: Tag
tags question: http://stackoverflow.com/q/47738471
tag name: data-fitting

http://stackoverflow.com/a/47729847
score: 1
has body: You can do something like this: I suppose that your input file is called test_file.txt and your output file is called new_file.txt: def read_file(name): data = None with open(name, 'r') as f: data = f.readlines() return (k.split() for k in data) if data else data def merge_columns(name, new_file): data = read_file(name) if not data: raise Exception('Cant operate with a None data') with open(new_file, 'a+') as f: for k in data: first, second, third, *_ = k f.write('{0}{1} {2}\n'.format(second, first, third)) merge_columns('test_file.txt', 'new_file.txt') In terminal: &gt;&gt;&gt; python3 test.py &gt;&gt;&gt; cat new_file.txt C0 -0.053959 C1 -0.053862 C2 -0.059245 C3 -0.058925 S4 0.050616 H5 0.040353 H6 0.040480 H7 0.045907 H8 0.045941
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/82420473
type: Answer
answers question: http://stackoverflow.com/q/47729693
has comment: http://stackoverflow.com/comment/82420372

http://stackoverflow.com/comment/82482556
type: Comment
has text: Is your working directory the same as the desired input directory? Do you call the script from within the same root dir?
type: QuestionComment
comment on: http://stackoverflow.com/q/47760496
score: 0

http://stackoverflow.com/comment/82577512
type: QuestionComment
has text: You should fill one histogram (of the protocol) per date (or the other way round), then plot them like [here](https://matplotlib.org/examples/pylab_examples/bar_stacked.html). Currently you fill one histogram with dates and protocols, which doesn't make sense.
score: 0
comment on: http://stackoverflow.com/q/47807693
type: Comment

http://stackoverflow.com/q/47703736
has body: I have this df1: ID Name Alias Nickname 101 Robert Rob Bob 201 Tom 315 Megan Meg 405 Teddy Ted 510 Bill 602 But I want to add in a Result column that take the entries in an order (Name, Alias (if Name is empty), Nickname (if Alias and Name both empty)) ID Name Alias Nickname Result 101 Robert Rob Bob Robert 201 Tom Tom 315 Megan Meg Megan 405 Teddy Ted Teddy 510 Bill Bill 602 NA
type: Question
accepted answer: http://stackoverflow.com/a/47703915
answer count: 1
has answer: http://stackoverflow.com/a/47703915
tagged with: multiple-columns
has title: pandas taking entries in column order
type: AnsweredQuestion
score: 0
tagged with: pandas
tagged with: python

http://stackoverflow.com/q/47812526
has body: I have a pyspark dataframe with a column of numbers. I need to sum that column and then have the result return as an int in a python variable. df = spark.createDataFrame([("A", 20), ("B", 30), ("D", 80)],["Letter", "Number"]) I do the following to sum the column. df.groupBy().sum() But I get a dataframe back. +-----------+ |sum(Number)| +-----------+ | 130| +-----------+ I would 130 returned as an int stored in a variable to be used else where in the program. result = 130
has answer: http://stackoverflow.com/a/67177997
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/69111584
answer count: 9
has answer: http://stackoverflow.com/a/58377616
has title: PySpark - Sum a column in dataframe and return results as int
tagged with: sum
tagged with: pyspark
tagged with: dataframe
tagged with: python
possible better answer: http://stackoverflow.com/a/50467141
has answer: http://stackoverflow.com/a/69469936
type: AnsweredQuestion
score: 69
has answer: http://stackoverflow.com/a/51855775
has answer: http://stackoverflow.com/a/53029235
accepted answer: http://stackoverflow.com/a/51855775
has answer: http://stackoverflow.com/a/50467141
has answer: http://stackoverflow.com/a/56699255
has answer: http://stackoverflow.com/a/47812992
downvote count: 1
upvote count: 70

http://stackoverflow.com/comment/95359490
type: AnswerComment
comment on: http://stackoverflow.com/a/47853847
type: Comment
score: 0
has text: But what if these fields _are_ required? Is there a way to make `required=True` working, with respect to `source` keys?

http://stackoverflow.com/comment/82373974
has text: I think the quote from the link is just wrong (or poorly worded). Properties are the Pythonic way and they need of course a hidden getter (and maybe setter, deleter) function behind it.
score: 0
comment on: http://stackoverflow.com/q/47706820
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47760489
has comment: http://stackoverflow.com/comment/82482982
score: 0
answer count: 1
tagged with: scrapy
type: Question
has answer: http://stackoverflow.com/a/47761077
has body: I try to get the data of a website which has a filter. The website is the following one: https://www.lequipe.fr/Basket/RES_NBA.html I have a simply spider which collect all the information required but only for the date which is displayed. I need to iterate the filter in order to collect the data of all the date available in the filter. If someone can help i'll appreciate a lot. My spider is like this: # -*- coding: utf-8 -*- import scrapy class LequipeBotSpider(scrapy.Spider): name = 'Lequipe_bot' allowed_domains = ['www.lequipe.fr/Basket/RES_NBA.html'] start_urls = ['http://www.lequipe.fr/Basket/RES_NBA.html'] #location of csv file custom_settings = { 'FEED_FORMAT' : "csv", 'FEED_URI' : 'tmp/lequipe2.csv' } def parse(self, response): #Extracting the content using css selectors #recap = response.css(".equipeDom a::text,div.score span.score--chiffre::text,.equipeExt a::text").extract() recap=response.css(".equipeDom a::text,div.score span.score--chiffre::text,.equipeExt a::text,div.equipeDom span.nba--ranking::text,div.equipeExt span.nba--ranking::text").extract() #Give the extracted content row wise for x in range(0,(len(recap))/6): #create a dictionary to store the scraped info scraped_info = { 'equipe_dom' : recap[1+6*x], 'score_dom' : recap[2+6*x], 'score_ext' : recap[3+6*x], 'equipe_ext' : recap[4+6*x], 'classement_dom' : recap[0+6*x], 'classement_ext' : recap[5+6*x], } #yield or give the scraped info to scrapy yield scraped_info So, how can i iterate the scraping of all pages with the solution of @furas Thanks in advance
type: UnansweredQuestion
tagged with: python
has title: How to manage a filter on a website with scrapy

http://stackoverflow.com/comment/82583497
has text: don't use `sleep` in GUI and any framework which use `mainloop` because it blocks `mainloop` which gets events from system, sends events to widgets, redraw widget, eyc. - and all in loop. In `tkinter` use `root.after()` to run function periodically.
type: Comment
comment on: http://stackoverflow.com/q/47811125
score: 1
type: QuestionComment

http://stackoverflow.com/q/47719494
possible better answer: http://stackoverflow.com/a/47719757
favorite count: 0
linked to: http://stackoverflow.com/q/36462852
accepted answer: http://stackoverflow.com/a/47719782
has body: I am importing an excel worksheet that has the following columns name: N° Pedido 1234 6424 4563 The column name ha a special character (°). Because of that, I can´t merge this with another Data Frame or rename the column. I don´t get any error message just the name stays the same. What should I do? This is the code I am using and the result of the Dataframes: import pandas as pd import numpy as np # Importando Planilhas CRM = pd.ExcelFile(r'C:\Users\Michel\Desktop\Relatorio de Vendas\relatorio_vendas_CRM.xlsx', encoding= 'utf-8') protheus = pd.ExcelFile(r'C:\Users\Michel\Desktop\Relatorio de Vendas\relatorio_vendas_protheus.xlsx', encoding= 'utf-8') #transformando em Data Frame df_crm = CRM.parse('190_pedido_export (33)') df_protheus = protheus.parse('Relatorio de Pedido de Venda')] # Transformando Campos em float o protheus def turn_to_float(x): return np.float(x) df_protheus["TES"] = df_protheus["TES"].apply(turn_to_float) df_protheus["Qtde"] = df_protheus["Qtde"].apply(turn_to_float) df_protheus["Valor"] = df_protheus["Valor"].apply(turn_to_float) #Tirando Tes de não venda do protheus # tirando valores com código errado 6 df_protheus_1 = df_protheus[df_protheus.TES != 513.0] df_protheus_2 = df_protheus_1[df_protheus_1.TES != 576.0] **df_crm.columns = df_crm.columns.str.replace('N° Pedido', 'teste') df_crm.columns** Orçamento Origem N° Pedido Nº Pedido ERP Estabelecimento Tipo de Pedido Classificação(Tipo) Aplicação Conta CNPJ/CPF Contato ... Aprovação Parcial Antecipa Entrega Desconto da Tabela de Preço Desconto do Cliente Desconto Informado Observações Observações NF Vl Total Bruto Vl Total Completo 0 20619.0 23125 NaN Optitex 1 - Venda NaN Industrialização/Revenda XAVIER E ARAUJO LTDA ME 7970626000170 NaN ... N N 0 0 0 Note that I used other codes for the bold part with the same result: #renomeando tabela para dar Merge #df_crm['proc'] = df_crm['N\xc2\xb0 Pedido'] #df_crm['N Pedido'] = df_crm['N° Pedido'] #df_crm.drop('N° Pedido',inplace=True,axis=1) #df_crm #d…
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/82399768
tagged with: pandas
has comment: http://stackoverflow.com/comment/82401534
has comment: http://stackoverflow.com/comment/82400565
tagged with: python
linked to: http://stackoverflow.com/q/9623029
has answer: http://stackoverflow.com/a/47719782
type: Question
answer count: 2
linked to: http://stackoverflow.com/q/18084554
upvote count: 3
has title: Dealing with special characters in pandas Data Frame´s column Name
has comment: http://stackoverflow.com/comment/82399906
downvote count: 0
has comment: http://stackoverflow.com/comment/82400383
has answer: http://stackoverflow.com/a/47719757

http://stackoverflow.com/q/47772299
has comment: http://stackoverflow.com/comment/82505621
tagged with: python-2.7
answer count: 2
has body: I have an image, using steganography I want to save the data in border pixels only. In other words, I want to save data only in the least significant bits(LSB) of border pixels of an image. Is there any way to get border pixels to store data( max 15 characters text) in the border pixels? Plz, help me out...
has answer: http://stackoverflow.com/a/47773915
score: -3
tagged with: image-processing
possible better answer: http://stackoverflow.com/a/49094628
has title: How to get border pixels of an image in python?
downvote count: 6
favorite count: 0
tagged with: opencv
type: AnsweredQuestion
upvote count: 3
has comment: http://stackoverflow.com/comment/82505664
accepted answer: http://stackoverflow.com/a/47773915
tagged with: python
has comment: http://stackoverflow.com/comment/82505579
tagged with: image
has answer: http://stackoverflow.com/a/49094628
type: Question

http://stackoverflow.com/comment/82613219
has text: I think he recommend to use line profiler on your original / non-cython code to see which operations are slow. If those are basic numpy-primitives / vectorized parts, you know that cython is not going to help.
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47824229

http://stackoverflow.com/q/47756635
has body: I have a folder of 1000 photos that I'd like to make a timelapse of. The photos are shot every 60 seconds, and I'd like to make a 10 minute interval timelapse. So I need to delete every 2nd to 9th photo and have it loop. For example, given 1000 photos in a folder, I'd like the script to keep photo 1, 10, 20, 30 and so on and so forth. At the end of this script, the folder should only contain 100 photos. The following code removes every "10th" photo, which doesn't do exactly as I want: import os dir_to_clean = '/Users/myname/Desktop/TBD' l = os.listdir(dir_to_clean) for n in l[::10]: os.unlink(dir_to_clean + '/' + n) How do I modify this code so that it deletes every 2nd-9th photo? It should still be able to run if the folder does not have an even number of files (e.g. if it has 1005 files).
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/47756998
has answer: http://stackoverflow.com/a/47756829
accepted answer: http://stackoverflow.com/a/47756829
tagged with: python-os
type: AnsweredQuestion
score: 0
possible better answer: http://stackoverflow.com/a/47756998
has title: Delete the 2nd to 9th file and loop for a timelapse Python
tagged with: python

http://stackoverflow.com/q/47782924
has title: Python3: reading utf8 encoded bytestrings
has comment: http://stackoverflow.com/comment/82559656
has body: My program uses the output from "iwlist scan" to generate a report. It works fine except when the network name (ESSID) contains non-Ascii characters. IEEE802.11 state that ESSID may contain UTF8 characters. However these essid are reported by iwlist as an encoded bytestring. Example: ESSID:"f\xC3\xAAte" \xC3\xAA is effectively the UTF-8 encoding of "ê" I can't find a way to specify to 'open' that these bytestrings should be automatically converted into UTF-8 characters. Question: what is the most pythonic way to solve my problem? PS: as a test case, I put the following line in a file (say xx): ESSID:"f\xC3\xAAte" and I execute: open( 'xx','rb').read().decode('UTF-8') and my result is: 'ESSID:"f\xC3\xAAte"\n'
tagged with: utf-8
has comment: http://stackoverflow.com/comment/82527400
has comment: http://stackoverflow.com/comment/82548787
possible better answer: http://stackoverflow.com/a/47800828
has comment: http://stackoverflow.com/comment/82571596
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82528568
tagged with: encoding
has comment: http://stackoverflow.com/comment/82591179
has comment: http://stackoverflow.com/comment/82559040
accepted answer: http://stackoverflow.com/a/47806014
has comment: http://stackoverflow.com/comment/82528451
tagged with: python
has comment: http://stackoverflow.com/comment/82562241
has answer: http://stackoverflow.com/a/47806014
has comment: http://stackoverflow.com/comment/82549272
has comment: http://stackoverflow.com/comment/82528576
has comment: http://stackoverflow.com/comment/82552045
has comment: http://stackoverflow.com/comment/82591254
has answer: http://stackoverflow.com/a/47804991
has answer: http://stackoverflow.com/a/47800828
has comment: http://stackoverflow.com/comment/82551412
type: AnsweredQuestion
score: 0
answer count: 3

http://stackoverflow.com/q/47760431
favorite count: 0
type: Question
answer count: 0
upvote count: 2
type: UnansweredQuestion
has title: Xlsxwriter scaling images with no scale input
downvote count: 0
tagged with: python
has body: It seems that either xlsxwriter or excel itself is scaling the image I am inserting into excel. This is an issue for me because I would like to align a second image right below the first image using 'y_offset'. Here is my code: file_name = 'Output File.xlsx' img1 = Image.open('Image1.png') imgwidth1, imgheight1 = img1.size workbook = xlsxwriter.Workbook(file_name) worksheet = workbook.add_worksheet('Summary') worksheet.insert_image('A1', 'Image1.png') worksheet.insert_image('A1', 'Image2.png',{'y_offset':imgheight1}) workbook.close() When I look at the output file the first image is in A1 but the next image has about 30 blank rows between it and the first image. I kinda did a rough check of how much it was scaled down and its about 1/3 the size it should be. If it helps both images DPI is at 300. I'm just wondering if this is excel or is it xlsxwriter and how I can fix it so that both images are aligned with each other and there is not space between them.
score: 2
has comment: http://stackoverflow.com/comment/82505868
tagged with: xlsxwriter
has comment: http://stackoverflow.com/comment/82483311
tagged with: image

http://stackoverflow.com/q/47805767
type: AnsweredQuestion
upvote count: 3
score: 3
tagged with: matplotlib
possible better answer: http://stackoverflow.com/a/47812553
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/47805990
type: Question
has answer: http://stackoverflow.com/a/47805990
answer count: 2
has body: I'm creating a simple bar plot from a DataFrame. (The plot method on Series and DataFrame is just a simple wrapper around pyplot.plot) import pandas as pd import matplotlib as mpl df = pd.DataFrame({'City': ['Berlin', 'Munich', 'Hamburg'], 'Population': [3426354, 1260391, 1739117]}) df = df.set_index('City') ax = df.plot(kind='bar') This is the generated plot Now I want to access the individual bars. And what I've noticed is that there is an additional bar (Rectangle) with width=1, height=1 rects = [rect for rect in ax.get_children() if isinstance(rect, mpl.patches.Rectangle)] for r in rects: print(r) output: Rectangle(xy=(-0.25, 0), width=0.5, height=3.42635e+06, angle=0) Rectangle(xy=(0.75, 0), width=0.5, height=1.26039e+06, angle=0) Rectangle(xy=(1.75, 0), width=0.5, height=1.73912e+06, angle=0) Rectangle(xy=(0, 0), width=1, height=1, angle=0) I would expect only three rectangles here. What is the purpose of the fourth?
tagged with: python
has answer: http://stackoverflow.com/a/47812553
tagged with: plot
has title: Why does pyplot.plot() create an additional Rectangle with width=1, height=1?
tagged with: pandas

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

http://stackoverflow.com/q/47850671
tagged with: ubuntu
tagged with: python-3.6
score: 3
accepted answer: http://stackoverflow.com/a/48158942
upvote count: 3
tagged with: pygtk
has body: I was trying to toy around with the pygtk module to make an app indicator in my top bar in Ubuntu 17.10. With a little research, I have successfully made a menu where you can pause the main thread (which just prints "Update" to the console currently.) Now I've stumbled across a problem and couldn't find an answer. I plan to make a radio streamer for the top bar and the menu closing on every click would be very undesirable for navigation when searching. How can I make the menu stay open when clicking an item? Here is my code: import os import signal import time from threading import Thread import gi gi.require_version("Gtk", "3.0") gi.require_version("AppIndicator3", "0.1") from gi.repository import Gtk as gtk from gi.repository import AppIndicator3 as appindicator from gi.repository import GObject as gobject class Indicator: def __init__(self, name=None, icon=None): self.path = os.path.abspath(os.path.dirname(__file__)) signal.signal(signal.SIGINT, signal.SIG_DFL) if name is None: self.name = "MyApp" else: self.name = name if icon is None: self.icon = gtk.STOCK_INFO else: self.icon = icon self.indicator = appindicator.Indicator.new( self.name, self.icon, appindicator.IndicatorCategory.SYSTEM_SERVICES ) self.indicator.set_status(appindicator.IndicatorStatus.ACTIVE) self.indicator.set_menu(self.create_menu()) self.running = True self.paused = False self.thread = Thread(target=self.update) self.thread.setDaemon(True) self.thread.start() def create_menu(self): menu = gtk.Menu() pause_entry = gtk.MenuItem("Pause") pause_entry.connect("activate", self.pause) menu.append(pause_entry) quit_entry = gtk.MenuItem("Quit") quit_entry.connect("activate", self.quit) menu.append(quit_entry) menu.show_all() return menu def update(self): while self.running: time.sleep(1) if not self.paused: print("Update", flush=True) def start(self): gobject.threads_init() gtk.main() def pause(self, menu): self.paused = not self.paused text = "Resume" if self.paused else "Pause" for widget in menu.g…
has answer: http://stackoverflow.com/a/48158942
has title: How to keep PyGTK AppIndicator menu open after click?
type: AnsweredQuestion
favorite count: 0
type: Question
tagged with: appindicator
answer count: 1
downvote count: 0
tagged with: python

http://stackoverflow.com/a/68047452
answers question: http://stackoverflow.com/q/47698756
upvote count: 5
type: Answer
has body: you can try the code below, it works, I tested. But I do have a question, because the Telethon library doesn't extra all the users, it only extra like 90% of the users. I think it somehow skipped some ones... don't know why. from telethon.sync import TelegramClient from telethon.tl.functions.messages import GetDialogsRequest from telethon.tl.types import InputPeerEmpty import csv api_id = 123456 api_hash = 'YOUR_API_HASH' phone = '+111111111111' client = TelegramClient(phone, api_id, api_hash) client.connect() if not client.is_user_authorized(): client.send_code_request(phone) client.sign_in(phone, input('Enter the code: ')) chats = [] last_date = None chunk_size = 200 groups=[] result = client(GetDialogsRequest( offset_date=last_date, offset_id=0, offset_peer=InputPeerEmpty(), limit=chunk_size, hash = 0 )) chats.extend(result.chats) for chat in chats: try: if chat.megagroup== True: groups.append(chat) except: continue print('Choose a group to scrape members from:') i=0 for g in groups: print(str(i) + '- ' + g.title) i+=1 g_index = input("Enter a Number: ") target_group=groups[int(g_index)] print('Fetching Members...') all_participants = [] all_participants = client.get_participants(target_group, aggressive=True) print('Saving In file...') with open("members.csv","w",encoding='UTF-8') as f: writer = csv.writer(f,delimiter=",",lineterminator="\n") writer.writerow(['username','user id', 'access hash','name','group', 'group id']) for user in all_participants: if user.username: username= user.username else: username= "" if user.first_name: first_name= user.first_name else: first_name= "" if user.last_name: last_name= user.last_name else: last_name= "" name= (first_name + ' ' + last_name).strip() writer.writerow([username,user.id,user.access_hash,name,target_group.title, target_group.id]) print('Members scraped successfully.')
has comment: http://stackoverflow.com/comment/138169003
has comment: http://stackoverflow.com/comment/139030882
score: 5
downvote count: 0

http://stackoverflow.com/a/47738871
upvote count: 2
has comment: http://stackoverflow.com/comment/82438417
accepted answer of: http://stackoverflow.com/q/47738835
type: AcceptedAnswer
has body: It depends on who is going to use this code: If it's only you, you could use the eval funciton: &gt;&gt;&gt; eval('6+6') 12 If you're going to let someone else enter numbers, eval is evil. It can format your hard drive if malicious code is entered! (see also How harmful is eval) Consider other possibilities like ast.literal_eval (only for + and -, even * is too hard for it), pyparsing (powerful, but requires writing a program for this) , etc You could also consider numexpr library (installs numpy as a requirement and returns numpy array as a result): &gt;&gt;&gt; import numexpr as ne &gt;&gt;&gt; ne.evaluate('6**2') array(36, dtype=int32) &gt;&gt;&gt; print(ne.evaluate('6**2')) 36
type: Answer
has comment: http://stackoverflow.com/comment/82438157
has comment: http://stackoverflow.com/comment/82438145
has comment: http://stackoverflow.com/comment/82438364
has comment: http://stackoverflow.com/comment/82438055
has comment: http://stackoverflow.com/comment/82438538
has comment: http://stackoverflow.com/comment/82438218
score: 1
downvote count: 1
answers question: http://stackoverflow.com/q/47738835
has comment: http://stackoverflow.com/comment/82438913
has comment: http://stackoverflow.com/comment/82438028

http://stackoverflow.com/a/47765224
has body: From the documentation for dictionaries: It is best to think of a dictionary as an unordered set of key: value pairs, with the requirement that the keys are unique (within one dictionary). A pair of braces creates an empty dictionary: {}. Placing a comma-separated list of key:value pairs within the braces adds initial key:value pairs to the dictionary; this is also the way dictionaries are written on output.
downvote count: 0
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/47765206
score: 1

http://stackoverflow.com/comment/82452897
type: Comment
comment on: http://stackoverflow.com/q/47746361
type: QuestionComment
score: 1
has text: `property_dict_keyorder.get(i[0])` is returning `None`, because `i[0]` isn't present in the dictionary.

http://stackoverflow.com/q/47730671
favorite count: 0
has answer: http://stackoverflow.com/a/47730866
accepted answer: http://stackoverflow.com/a/47730866
type: Question
possible better answer: http://stackoverflow.com/a/47730777
answer count: 2
has body: I am testing using the requests module to get the content of a webpage. But when I look at the content I see that it does not get the full content of the page. Here is my code: import requests from bs4 import BeautifulSoup url = "https://shop.nordstrom.com/c/womens-dresses-shop?origin=topnav&amp;cm_sp=Top%20Navigation-_-Women-_-Dresses&amp;offset=11&amp;page=3&amp;top=72" page = requests.get(url) soup = BeautifulSoup(page.content, 'html.parser') print(soup.prettify()) Also on the chrome web-browser if I look at the page source I do not see the full content. Is there a way to get the full content of the example page that I have provided?
score: 16
upvote count: 17
tagged with: web-scraping
has comment: http://stackoverflow.com/comment/82421847
tagged with: python-requests
has comment: http://stackoverflow.com/comment/82422048
linked to: http://stackoverflow.com/q/45259232
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82421933
has answer: http://stackoverflow.com/a/47730777
downvote count: 1
has comment: http://stackoverflow.com/comment/82422441
tagged with: python
has title: Python 3: using requests does not get the full content of a web page

http://stackoverflow.com/comment/82660282
type: Comment
score: 0
type: QuestionComment
has text: I will attach the relevant code...
comment on: http://stackoverflow.com/q/47847953

http://stackoverflow.com/q/47852518
accepted answer: http://stackoverflow.com/a/47852549
tagged with: python
score: -2
answer count: 1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82670929
has comment: http://stackoverflow.com/comment/82669393
has comment: http://stackoverflow.com/comment/82669459
favorite count: 0
has comment: http://stackoverflow.com/comment/82669361
has title: method object is not subscriptable Python
downvote count: 4
type: Question
upvote count: 2
has body: Running into a TypeError: 'method' object is not subscriptable import csv import requests import json req = requests.get(url="https://www.draftkings.com/lobby/getcontests?sport=NHL") req.raise_for_status() data = req.json() for i, contest in enumerate(data['DraftGroups']): draftgroupid = contest['DraftGroupId'] req2 = requests.get(url="https://api.draftkings.com/draftgroups/v1/draftgroups/" + str(draftgroupid) + "/draftables?format=json") data2 = req2.json for i, player_info in enumerate(data2['draftables'][0]): date = player_info['competition']['startTime'] print(date) The draftgroupid's Output: 16901 16905 16902 16903 I'm wondering if its possibly the second while loop?
has comment: http://stackoverflow.com/comment/82669368
has answer: http://stackoverflow.com/a/47852549

http://stackoverflow.com/comment/82397995
score: 0
comment on: http://stackoverflow.com/a/47701243
type: Comment
type: AnswerComment
has text: i know we are not supposed to use comments to say thanks but "thanks!". this discussion has been very beneficial...i appreciate it.

http://stackoverflow.com/a/47771705
downvote count: 0
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47764359
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/47764359
has comment: http://stackoverflow.com/comment/82522074
has body: It seems the purpose of this code is to switch back and forth between two plots. So instead of recreating the content in a single axes multiple times you probably just want to use two axes. One for the plot, one for the colormesh. Depending on the counter, you set either one invisible and possibly draw some new content to the axes. import matplotlib.pyplot as plt import numpy as np counter = 0 def onClick(event): global counter counter += 1 if counter % 2: # Plot something else ax2.clear() ax2.plot(x1, x2) ax.set_visible(False) ax2.set_visible(True) else: ax.set_visible(True) ax2.set_visible(False) fig.canvas.draw_idle() x1 = np.random.randn(100) x2 = np.random.randn(100) x3 = np.random.randn(100, 100) fig = plt.figure() ax = fig.add_subplot(111, label="1") ax2= fig.add_subplot(111, label="2") ax2.set_visible(False) quadMeshCol = ax.pcolormesh(x1, x2, x3) fig.canvas.mpl_connect("button_press_event", onClick) plt.show() Or even more compact: import matplotlib.pyplot as plt import numpy as np def onClick(event): ax.set_visible(not ax.get_visible()) ax2.set_visible(not ax2.get_visible()) fig.canvas.draw_idle() x1 = np.random.randn(100) x2 = np.random.randn(100) x3 = np.random.randn(100, 100) fig = plt.figure() ax = fig.add_subplot(111, label="1") ax2= fig.add_subplot(111, label="2") ax2.set_visible(False) quadMeshCol = ax.pcolormesh(x1, x2, x3) line, = ax2.plot(x1, x2) fig.canvas.mpl_connect("button_press_event", onClick) plt.show()

http://stackoverflow.com/comment/82488799
type: Comment
type: QuestionComment
has text: Show the stack trace where the error occurs.
comment on: http://stackoverflow.com/q/47763408
score: 0

http://stackoverflow.com/comment/82523353
comment on: http://stackoverflow.com/a/47778502
type: AnswerComment
has text: Even using 10000 chunks (which eats up almost all my RAM) this is still rather slow.
score: 0
type: Comment

http://stackoverflow.com/comment/82549697
type: Comment
type: QuestionComment
has text: `(todo1 if condition else todo 2 for item in dataset)` this is the correct syntax to use comprehension if you want to add `else part`
score: 0
comment on: http://stackoverflow.com/q/47794327

http://stackoverflow.com/a/47882932
answers question: http://stackoverflow.com/q/47828222
score: 0
has body: Twilio developer evangelist here. If you want the full JSON response proxied to your application, then you may find it easier to avoid the Twilio library and just make requests to the JSON API endpoints and send the response straight on. For example, to get the list of calls with Python's Requests library you would do something like this: @app.route('/getCalls', methods=['GET']) def getCalls(): url = 'https://api.twilio.com/2010-04-01/Accounts/YOUR_ACCOUNT_SID/Calls/.json' request = requests.get(url, auth=(YOUR_ACCOUNT_SID, YOUR_AUTH_TOKEN) resp = Response(response=request.text, status=200, mimetype="application/json") return resp Let me know if that helps at all.
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/47828222

http://stackoverflow.com/comment/82638626
type: Comment
type: QuestionComment
has text: @GarbageCollector :I know I could use matplotlib, but I wanted to know if its possible to visualize the whole data set at once to see the trends and patterns. Looks like I need to do it by parts and interpret it.
score: 0
comment on: http://stackoverflow.com/q/47827390

http://stackoverflow.com/comment/82406249
score: 2
type: Comment
type: QuestionComment
has text: NZEC is not a useful error code. I'd recommend loading this up on a local Python installation and doing your debugging there. You'll get much more meaningful errors.
comment on: http://stackoverflow.com/q/47722819

http://stackoverflow.com/comment/82618490
has text: @ Mike Müller oh!, In this case if we are importing whole module, whats the difference between selective import and wild import? I mean difference between "from module import A,B" and "from module import * " ? or its just readability difference
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47827901
score: 0

http://stackoverflow.com/q/47849592
has title: moving circle using tkinter
has comment: http://stackoverflow.com/comment/82664035
tagged with: python
has comment: http://stackoverflow.com/comment/82664022
has comment: http://stackoverflow.com/comment/82664467
type: AnsweredQuestion
has body: i am new to programming and am currently trying to get a chemistry stimulation with beaker which produces bubbles. after a lot of research I have managed to get a circle moving and also created a rectangle representing a beaker. however I would like the circles to be formed at the top of the beaker and move upwards in random and destroy itself when it meets the top which I just cant figure out. I would be very grateful if anyone can help me. thank you in advance. my code is: from tkinter import * x = 10 y = 10 a = 50 b = 50 x_vel = 5 y_vel = 5 def move(): global x global y global x_vel global y_vel if x &lt; 0: x_vel = 5 if x &gt; 350: x_vel = -5 if y &lt; 0: y_vel = 5 if y &gt; 150: y_vel = -5 canvas1.move(circle, x_vel, y_vel) coordinates = canvas1.coords(circle) x = coordinates[0] y = coordinates[1] window.after(33, move) window = Tk() window.geometry("1000x1000") canvas1=Canvas(window, height = 1000, width= 1000) canvas1.grid (row=0, column=0, sticky=W) coord = [x, y, a, b ] circle = canvas1.create_oval(coord, outline="red", fill="red") coord = [230, 270, 270, 310] rect2 = canvas1.create_rectangle(coord, outline="Blue", fill="Blue") move() window.mainloop ()
score: 0
accepted answer: http://stackoverflow.com/a/47849988
has answer: http://stackoverflow.com/a/47849988
answer count: 1
upvote count: 1
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/82663674
type: Question
tagged with: tkinter

http://stackoverflow.com/q/47847238
type: Question
tagged with: opencv
has title: load Video Using OpenCV in python
has answer: http://stackoverflow.com/a/47847365
tagged with: python
type: AnsweredQuestion
has body: Here is my code which is running...but I didnt understood why we used: if cv2.waitKey(1000) &amp; 0xFF == ord('q'): break in the code......under display the resulting frame comment: import numpy as np import cv2 cap = cv2.VideoCapture('C:\\Users\\KRK\\Desktop\\Dec17thVideo.mp4') while(True): # Capture frame-by-frame ret, frame = cap.read() # Our operations on the frame come here gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # Display the resulting frame cv2.imshow('frame',gray) if cv2.waitKey(1000) &amp; 0xFF == ord('q'): break # When everything done, release the capture cap.release() cv2.destroyAllWindows()
score: 0
accepted answer: http://stackoverflow.com/a/47847365
answer count: 1
upvote count: 1
downvote count: 1
favorite count: 0

http://stackoverflow.com/comment/82427681
type: Comment
type: AnswerComment
has text: I have a section of code that is for initializing all the default values. Under this code, the `self.item` dictionary is created, and the initial values for `ItemEnabled` are set. After that point, I need to update `self.treeWidget` so it the checks reflect the current `ItemEnabled` state. In my case, `self.treeWidget` is defined in the layout section of my code. I'm trying to keep things organized as much as possible.
comment on: http://stackoverflow.com/a/47731685
score: 0

http://stackoverflow.com/comment/82603296
score: 0
type: AnswerComment
has text: Edited the code to allow for unique names and gave link to SO answer about how python reduce function works.
comment on: http://stackoverflow.com/a/47820074
type: Comment

http://stackoverflow.com/a/54811138
has comment: http://stackoverflow.com/comment/108606022
type: Answer
has comment: http://stackoverflow.com/comment/98691378
has comment: http://stackoverflow.com/comment/118423280
answers question: http://stackoverflow.com/q/47800794
score: 65
upvote count: 65
has body: Although Conda previously did not support PowerShell, this is now resolved in Conda 4.6. After adding Anaconda3/Scripts/ to your PATH variable, you should be able to initialize Conda for use with powershell with: conda init powershell Afterwards, you can use conda normally: conda activate base
downvote count: 0
has comment: http://stackoverflow.com/comment/99512111
has comment: http://stackoverflow.com/comment/108608162

http://stackoverflow.com/comment/82428587
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47733596
has text: what happens if you 1. `import time` and 2. Add `time.sleep(3)` after you draw the black rect to delay the red one??
type: Comment

http://stackoverflow.com/a/47795329
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47793628
score: 0
type: Answer
has body: Try this count=input('Enter number of machines:') usrip=re.compile("^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}") for i in range(1,int(count)): user=input('Enter the ip_address of machine '+str(i)+':') while not (usrip.match(user)): print("Enter a valid user name and ip address") user=input('Enter the ip_address of machine '+str(i)+':') if (usrip.match(user)): mac_list.append(user)
accepted answer of: http://stackoverflow.com/q/47793628

http://stackoverflow.com/q/47745106
score: 0
has title: For loop in function, While true difficulty to understand
linked to: http://stackoverflow.com/q/47724574
tagged with: python
type: Question
tagged with: for-loop
has answer: http://stackoverflow.com/a/47745261
answer count: 1
tagged with: web-scraping
has body: I put this simple Web Weather Scraping script together, to check a temperature in a given location. The code works perfectly, even though, it may not be the best, or cleanest version. Still learning. But it is scraping: 67 from HERE. #!/usr/bin/python # -*- coding: utf-8 -*- import requests from BeautifulSoup import BeautifulSoup import time degree = u'\N{DEGREE SIGN}' url = 'https://www.wunderground.com/weather/us/ca/san-diego/KCASANDI355' response = requests.get(url) html = response.content soup = BeautifulSoup(html) current_temp = soup.find("div", {"class" : "current-temp"}).find("span", {"class" : "wu-value wu-value-to"}) for i in current_temp: print('San Diego Feels Like ') + i + (degree + 'F') The Output looks like this: San Diego Feels Like 74°F My goal here is to have a function that is looping, and based on the current temperature that is defined in current_temp variable to print for example if the temperature goes bellow 70F It's too cold, or if it goes above 80F It is too hot, etc. However I am having an issue to understand how to tell my code to execute, or in this case print these different tasks or methods you can say?. Excuse my English. There is definitely something wrong with the While (True): loop, but I can't get my head around it. Thanks for any help, and wish you all good Sunday. #!/usr/bin/python import requests from BeautifulSoup import BeautifulSoup import time degree = u'\N{DEGREE SIGN}' url = 'https://www.wunderground.com/weather/us/ca/san-diego/KCASANDI355' response = requests.get(url) html = response.content soup = BeautifulSoup(html) current_temp = soup.find("div", {"class" : "current-temp"}).find("span", {"class" : "wu-value wu-value-to"}) def weather(): while(True): for i in current_temp: print('San Diego Feels Like ') + i + (degree + 'F') #time.sleep(2) if (i <= 70) and (i >= 50): print('It\'s kinda cool') break elif i <= 50: print('It\'s cold af') elif (i >= 80) and (i <= 100): print('It\'s hot af') break else: print('You Dead') brea…
tagged with: beautifulsoup
has comment: http://stackoverflow.com/comment/82450290
accepted answer: http://stackoverflow.com/a/47745261
type: AnsweredQuestion

http://stackoverflow.com/q/47719524
tagged with: python
type: AnsweredQuestion
score: 0
has body: I wish to iterate over a zip of objects and floats together using a parent class function. Sometimes the subclasses have three objects and three floats in a list, this works fine: L = [A,B,C] F = [1,2,3] for f, o in zip(L,F): # do stuff Sometimes the subclass has one object and one float L = A F = 1 for f, o in zip(L,F): # TypeError This throws an exception because F is not iterable. If I try: F = list(F) This works for 2 or more floats but throws an exception for a single float (it's still not iterable :)). If I try: F = [F] This solves the 1 float case but now returns a nested list when there are two or more floats! a = [1,2] [a] = [[1,2]] Is there a simple builtin way to receive either a single float or list of floats and return a single flat list? Or do I need something like itertools.chain?
has answer: http://stackoverflow.com/a/47719628
has answer: http://stackoverflow.com/a/47719653
possible better answer: http://stackoverflow.com/a/47719632
has title: Creating flat list from single float or list of floats
has answer: http://stackoverflow.com/a/47719632
type: Question
has answer: http://stackoverflow.com/a/47719661
has answer: http://stackoverflow.com/a/47726044
answer count: 5
accepted answer: http://stackoverflow.com/a/47719628

http://stackoverflow.com/a/47725614
downvote count: 0
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/82414002
answers question: http://stackoverflow.com/q/47725554
type: Answer
has body: I would recommend you look into Python's dictionaries. urls = {} urls['qa'] = 'https://qa.test.com' test_environment = 'qa' print(urls[test_environment]) // =&gt; https://qa.test.com
has comment: http://stackoverflow.com/comment/82422403
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47725554

http://stackoverflow.com/comment/99753917
comment on: http://stackoverflow.com/a/55048316
type: Comment
score: 0
type: AnswerComment
has text: Whitenoise was the problem also for me, I've copied the settings.py from another projects where I did use whitenoise, had to deleted for this one. ty

http://stackoverflow.com/comment/82440839
comment on: http://stackoverflow.com/q/47740323
type: Comment
type: QuestionComment
has text: I think you're going to need to clarify what you're asking. And please format your code.
score: 4

http://stackoverflow.com/comment/82627766
type: AnswerComment
score: 0
has text: Thank you so much! So simple, I can't believe I didn't think of this!
comment on: http://stackoverflow.com/a/47832386
type: Comment

http://stackoverflow.com/comment/82570201
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47791378
has text: @Olaf I'm not disputing that ^^, I'm merely suggesting what they were trying to comment
score: 0

http://stackoverflow.com/q/47778054
tagged with: http://stackoverflow.com/tag/json
tagged with: python
score: 2
upvote count: 2
answer count: 0
downvote count: 0
tagged with: google-cloud-platform
type: UnansweredQuestion
has title: Passing JSON Values to an API call in Python for GCP
tagged with: google-compute-engine
favorite count: 0
has body: This is my first post here, so I appreciate you bearing with me on this. let me try and step you through what I am trying to do: I have a json file (compute.json) that has the values for creating a compute instance in the google cloud. I am trying to write a python API call to GCP that: - Loads the compute.json file - decodes the json file - serialized the data to be passed to the GCP API I'm currently getting a " is not JSON serializable" - I am having trouble serializing the data for the API call. Here is the code I have thus far: from pprint import pprint import json import requests auth = json.load(open('auth.json')) key = auth["private_key"] compute_json = json.load(open('Compute.json')) contents = json.dumps(compute_json) url = 'https://www.googleapis.com/compute/v1/projects/[PROJECTID]/zones/[ZONE]/instances' headers = {'content-type': 'application/json'} params = {'key': key} requests.port(url, params=params, data=contents, headers=headers) response = request.post(url, params=params, headers=headers) So my questions are: A) How do I 're-serialize' the data to send to the API B) is their an easy way to pass a Formatted JSON file to an API without decoding, recoding, and serializing the data? Thanks everyone!
type: Question

http://stackoverflow.com/q/47735381
duplicate of: http://stackoverflow.com/q/17778372
has body: I am trying to get the hour and mins from the user but when I enter a alphanumeric a number that exceeds the range the user it allowed the user returns a None type value. I am trying to just get the number from the user. I know the solution is obvious but for some reason I cant figure it out. def get_hours(): h = input("Hour:") try: if len(h) == 0: return 0 else: h = int(h) if 0 &lt;= h &lt;= 24: print(h) print(type(h)) return h else: print("Enter Hours between 0 and 24") get_hours() except ValueError: print("Enter Hour example = 16") get_hours() def get_mins(): m = input("Minutes:") try: if len(m) == 0: return 0 else: m = int(m) if 0 &lt;= m &lt;= 60: print(m) print(type(m)) return m else: print("Enter minutes between 0 and 60") get_mins() except ValueError: print("Enter Minutes example = 23") get_mins() def get_activity(): flag = True while flag: ui = input("Enter a brief summary of what you will be doing? \n:") if len(ui) == 0: flag = True else: return ui def main(): data = [] time = [] activity = [] hour = get_hours() print(type(hour)) print("Hours: " +str(hour)) while hour == None: hour = get_hours() mins = get_mins() print(type(mins)) print("Mins: " + str(mins)) while mins == None: mins = get_mins() main() This is what I want: Hours: 10 Minutes: 53 This is what I get when the following inputs are enterd Hour:1a Enter Hour example = 16 Hour:231 Enter Hours between 0 and 24 Hour:2 2 &lt;class 'int'&gt; &lt;class 'NoneType'&gt; Hours: None Hour:2a Enter Hour example = 16 Hour:2 2 &lt;class 'int'&gt; Hour:2a Enter Hour example = 16 Hour:2 2 &lt;class 'int'&gt; Hour:2 2 &lt;class 'int'&gt; Minutes:2a Enter Minutes example = 23 Minutes:222 Enter minutes between 0 and 60 Minutes:2a Enter Minutes example = 23 Minutes:2 2 &lt;class 'int'&gt; &lt;class 'NoneType'&gt; Mins: None Minutes:2 2 &lt;class 'int'&gt;
score: 0
type: Question
tagged with: python-3.x
tagged with: nonetype
type: UnansweredQuestion
answer count: 1
linked to: http://stackoverflow.com/q/17778372
tagged with: python
has title: Why does python return None?
has answer: http://stackoverflow.com/a/47735421

http://stackoverflow.com/comment/82668786
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47851895
score: 0
has text: Why are the `if` and the `assert` checking the exact same condition? If the `if` is true, then the `assert` would also obviously be true. (Unless you're worried about thread race conditions, but that's exactly the thing you're asking for protection against...)

http://stackoverflow.com/comment/82360125
type: QuestionComment
has text: I did run sup apt-get update. And when I used sudo apt-get install python 3, I got this: ****Reading package lists... Done Building dependency tree Reading state information... Done python3 is already the newest version (3.5.3-1). 0 upgraded, 0 newly installed, 0 to remove and 1 not upgraded.**** but Python --version still says it's 2.7.13
type: Comment
comment on: http://stackoverflow.com/q/47700024
score: 0

http://stackoverflow.com/a/47778664
has body: You mix two different technics First: inheriting class OptionMenu(tk.Frame): # &lt;-- with Frame def __init__(self, master, status, *options): super().__init__(master) # &lt;-- with super() Second: including class OptionMenu(): # &lt;-- without Frame def __init__(self, master, status, *options): self.frame = tk.Frame(master) # &lt;-- create inner widget First create real widget which can use menu.pack() or menu.grid() Second doesn't create widget - it create normal class with widget inside and you have to use menu.frame.pack() or menu.frame.grid() Example with real widget import tkinter as tk class OptionMenu(tk.Frame): # &lt;-- with Frame def __init__(self, master, status, *options): super().__init__(master) # &lt;-- with super() self.status = tk.StringVar() self.status.set(status) # use `self` as parent for widgets inside self.dropdown = tk.OptionMenu(self, self.status, *options) self.dropdown.pack() def main(): editionMap = {1:"English", 2:"German", 3:"Russian"} langMap = {1:"English", 2:"German", 3:"Russian"} topicMap = {1:"English", 2:"German", 3:"Russian"} root = tk.Tk() Edition_Filter = OptionMenu(root, "Edition", *editionMap.keys()) Edition_Filter.grid(row=0, column=0) Language_Filter = OptionMenu(root, "Language", *langMap.keys()) Language_Filter.grid(row=0, column=1) Topic_Filter = OptionMenu(root, "Topic", *topicMap.keys()) Topic_Filter.grid(row=0, column=2) root.mainloop() if __name__ == '__main__': main()
has comment: http://stackoverflow.com/comment/82548309
has comment: http://stackoverflow.com/comment/82518648
has comment: http://stackoverflow.com/comment/82519943
has comment: http://stackoverflow.com/comment/82547748
type: Answer
has comment: http://stackoverflow.com/comment/82589476
has comment: http://stackoverflow.com/comment/82548179
has comment: http://stackoverflow.com/comment/82548418
has comment: http://stackoverflow.com/comment/82548006
has comment: http://stackoverflow.com/comment/82519165
upvote count: 2
has comment: http://stackoverflow.com/comment/82548066
downvote count: 0
has comment: http://stackoverflow.com/comment/82548357
answers question: http://stackoverflow.com/q/47778141
has comment: http://stackoverflow.com/comment/82548004
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82548238
has comment: http://stackoverflow.com/comment/82537863
has comment: http://stackoverflow.com/comment/82548057
has comment: http://stackoverflow.com/comment/82547435
accepted answer of: http://stackoverflow.com/q/47778141
score: 2

http://stackoverflow.com/q/47811125
has comment: http://stackoverflow.com/comment/82583483
has title: tkinter How to prevent the main window from freezing in a long running program?
linked to: http://stackoverflow.com/q/29158220
tagged with: python
has comment: http://stackoverflow.com/comment/82583497
has comment: http://stackoverflow.com/comment/82612639
score: 0
has comment: http://stackoverflow.com/comment/82590148
tagged with: tkinter
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82589976
type: Question
has comment: http://stackoverflow.com/comment/82587894
has body: I have a continuously running program that periodically reads an sqlite database. It calls a function to display messages in a tkinter window by checking certain criteria, and then it goes to sleep. My problem is that the window freezes when I try to close it (using the quit() method). It could be that, in this case, root.mainloop() is not the last statement of the program. (I need to display a pop-up window at regular intervals). I believe multithreading is not a solution because tkinter should not be run in a separate thread. What is the right approach to this problem? Following is the code - def display_reminders(task_names): root = Tk() root.title('Reminder') root.geometry('-0-40') root.minsize(width=300,height=100) root.attributes("-topmost", True) root.rowconfigure(0, weight=1) root.columnconfigure(0, weight=1) for key, name, dt in task_names: Label(root, text=name).grid(padx=20, pady=20, sticky=NW) btn = Button(root, text='Ok', command=root.quit) btn.grid(pady=5) btn.bind('&lt;Return&gt;', lambda e: root.quit()) root.mainloop() def check_for_reminders(missed_flag=False): # logic to read database and check if reminder should be displayed display_reminders(task_names) check_for_reminders(True) time.sleep(60 - int(datetime.datetime.now().strftime('%S'))) while True: check_for_reminders() # We subtract the number of seconds from 60 because having only # time.sleep(60) results in the number of seconds past the minute creeping # up. time.sleep(60 - int(datetime.datetime.now().strftime('%S')))
has comment: http://stackoverflow.com/comment/82583743

http://stackoverflow.com/q/47843819
score: 1
tagged with: python
has title: Odoo 11.0 make field unique
has answer: http://stackoverflow.com/a/47862448
has body: Can somebody explain how to make a field unique value? Like the invoice number, order number, ... each value must be unique. I need this for the product internal_reference and contact reference too. I've been checking the parameters for these fields via Odoo Studio app, but I don't see anything how to make them unique. Thanks
tagged with: odoo-11
type: UnansweredQuestion
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
tagged with: field

http://stackoverflow.com/comment/82686524
comment on: http://stackoverflow.com/q/47853468
has text: I am using python. No errors in anaconda python console when i ran the main program there but after freezing one of the widgets is not showing. The one with xgboost.
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47705222
type: AnsweredQuestion
tagged with: java
has comment: http://stackoverflow.com/comment/82375776
favorite count: 0
accepted answer: http://stackoverflow.com/a/47891732
has comment: http://stackoverflow.com/comment/82370674
has answer: http://stackoverflow.com/a/47891732
tagged with: jython
has body: I need to call some Python code from Java. I am aware though that Jython exists or that Java has its own Python interpreter. Thing is, said Python code uses some native (C) compiled code, even runs something on GPU. So I can divide this into two questions: Does Jython or Java's Python interpreter support this? That is, the Python code (when called from Java) would run with all the C and GPU parts, thus will run roughly as fast as it would on its own. If neither of the above mentioned ways support this, is there any other way to do this? P.S. If that helps, although I suppose it's irrelevant, the code I need to run are highly GPU/C optimized neural networks from Keras (with TensorFlow underneath). I absolutely can't afford to run the only-Python interpreted version.
has comment: http://stackoverflow.com/comment/82370558
downvote count: 0
upvote count: 1
tagged with: python
score: 1
has comment: http://stackoverflow.com/comment/82370622
has title: calling python from java
answer count: 1
type: Question

http://stackoverflow.com/comment/82377270
type: AnswerComment
has text: didnt work, the line create carpet call image but not save anyting to database or the image in the path. im thinking im doing wrong something but i dont know what
score: 0
comment on: http://stackoverflow.com/a/47708521
type: Comment

http://stackoverflow.com/a/47743367
downvote count: 0
upvote count: 1
type: Answer
has body: Just write the number out in base |S| (that is, the size if the set of possible letters). Use the elements of the set in (some) order as the "digits". As an example consider the sequence of lists of three elements from list('0123456789'). Observe that it is precisely the numbers from 0 to 999, written with leading zeros if necessary to make them three digits long. Update Here is some Python code that illustrates the idea: def unrank(src, reqlen, pos): size = len(src) # it is easier to fill result from the end, so pre-create an array of the required size res = [src[0]] * reqlen for i in xrange(reqlen - 1, -1, -1): res[i] = src[pos % size] pos /= size if pos &gt; 0: # this means original pos was beyond (size ** reqlen) i.e. more than the max possible index raise IndexError return res res = unrank(list('0123456789ABCDEF'), 3, 2222) print (res) which prints ['8', 'A', 'E'] You can easily check that hex value of 0x8AE is actually 2222.
has comment: http://stackoverflow.com/comment/82490379
answers question: http://stackoverflow.com/q/47740459
score: 1

http://stackoverflow.com/q/47784159
upvote count: 4
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/82529881
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47784836
possible better answer: http://stackoverflow.com/a/47784317
has comment: http://stackoverflow.com/comment/82530021
has body: I have a very large multiline string, and would like to split it into an array, let's say, after each 50th occurrence of the newline character (\n) What is, in your opinion, the most Pythonic and efficient way to do so?
has answer: http://stackoverflow.com/a/47784482
has answer: http://stackoverflow.com/a/47784261
has title: Most pythonic way of splitting a large string after nth occurence of a newline
has comment: http://stackoverflow.com/comment/82533370
tagged with: algorithm
has answer: http://stackoverflow.com/a/47784317
has answer: http://stackoverflow.com/a/47784473
has comment: http://stackoverflow.com/comment/82530032
tagged with: python
answer count: 6
accepted answer: http://stackoverflow.com/a/47784482
has answer: http://stackoverflow.com/a/47784703

http://stackoverflow.com/a/47807860
has body: you could do something like this: files=None # put file extensions into a list fileext=[".txt",".log",".csv"] for ext in fileext: varlogpath = "C:/Users/vveldand/Office/Fetcher/Projects/LOG- PARSER/var/log/*"+ext outputfile = open(wrfilename, "a") files=glob.glob(varlogpath)
upvote count: 1
score: 1
type: Answer
answers question: http://stackoverflow.com/q/47807741
downvote count: 0

http://stackoverflow.com/comment/82551342
type: Comment
type: AnswerComment
has text: Okay this did the trick. 1. Remove `ipaddress = forms.IntegerField(required=False)` 2. leave `exclude = ('ipaddress',)` 3. keep `fields = ('ipaddress',)`
score: 0
comment on: http://stackoverflow.com/a/47759092

http://stackoverflow.com/q/47733419
tagged with: visual-studio-code
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/82428057
has body: Trying to setup Visual-Studio-Code and running into issues configuring virtualEnv properly. Read everything i could find online and tried different solutions: none worked so far. MAYBE i am just not getting the documentation and everyone else gets it. Proof that the virtualEnv as well as the package oauth2client exists. Path of the virtualEnv Setup in Visual Studio Code (yes i restarted after saving the settings). oauth2client can't be found. As you can see in the corner the Python interpreter was rightfully found. I hope that one of you guys can spot my mistake. Update: So thanks to mattmc3 i figured it out. Was using the "Code Runner" Plugin for running the python code. I missed setting up the right Interpreter for this plugin - used still the default one.
favorite count: 0
has comment: http://stackoverflow.com/comment/82427834
type: Question
has answer: http://stackoverflow.com/a/47733862
accepted answer: http://stackoverflow.com/a/47733862
has comment: http://stackoverflow.com/comment/82428297
score: 1
tagged with: python
has answer: http://stackoverflow.com/a/57863179
possible better answer: http://stackoverflow.com/a/57863179
has title: Mistake in setup python virtualEnv in visual-studio-code
has comment: http://stackoverflow.com/comment/82428200
has comment: http://stackoverflow.com/comment/82428129
type: AnsweredQuestion
answer count: 2

http://stackoverflow.com/comment/82490470
type: QuestionComment
comment on: http://stackoverflow.com/q/47764460
type: Comment
has text: I can't reproduce your situation. The code works as expected for me.
score: 0

http://stackoverflow.com/a/47730402
answers question: http://stackoverflow.com/q/47729648
has comment: http://stackoverflow.com/comment/82431621
has body: Use self.env.ref('external_id') instead of the xmlid_to_res_id method. But I think what you want to do is something like this: @api.multi def open_second_class(self): self.ensure_one() ac = self.env.ref('account.invoice_form') invoice = self.env['account.invoice'].create({ 'partner_id': self.name_id.id }) return { 'name': '2nd class', 'type': 'ir.actions.act_window', 'res_model': 'account.invoice', 'res_id': invoice.id, 'view_type': 'form', 'view_mode': 'form', 'target': 'new', 'context': {'default_id_tbl1': self.env.id }, }
accepted answer of: http://stackoverflow.com/q/47729648
type: Answer
has comment: http://stackoverflow.com/comment/82433527
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82433530

http://stackoverflow.com/comment/82380193
type: Comment
comment on: http://stackoverflow.com/q/47709795
score: 0
type: QuestionComment
has text: Have your function return the logical result and not a string. Then you can use it in your test. Do not generate a strong of code and then use `evel` -- pretty much ever...

http://stackoverflow.com/q/47763555
downvote count: 0
has comment: http://stackoverflow.com/comment/82489482
upvote count: 1
has comment: http://stackoverflow.com/comment/82489432
favorite count: 0
has body: I am using ubuntu and currently have code in python that launches a picture through a subprocess: p1 = subprocess.Popen(["display", "Some-Picture.jpg"]) after a user scans in a barcode which goes to input keyboardIN = input("Scan your barcode to launch the picture: ") My problem is that after the picture launches with the subprocess and is displayed, I need the user to be able to scan a different barcode and show a different picture. But I can't do this unless I bring back focus to the python shell (I'm currently launching from IDLE) and have the cursor ready on the input line. The scanner give a string of something like 'XDSO309G89S' and an enter command. Is there a way for python to maybe listen in the background for input, or switch focus to the shell window after the picture is displayed (without having to manually refocus the window and input line)? I've looked online but nothing is working for me right now.
tagged with: linux
has comment: http://stackoverflow.com/comment/82488860
score: 1
has title: Get input from python shell when another window is opened
tagged with: python
tagged with: shell
has comment: http://stackoverflow.com/comment/82489307
type: Question
tagged with: subprocess
answer count: 0
type: UnansweredQuestion
tagged with: window

http://stackoverflow.com/comment/83036397
has text: Context is the third parameter you pass to render(). It's a dict of variables which will be available in the template.
type: Comment
comment on: http://stackoverflow.com/a/47895926
score: 0
type: AnswerComment

http://stackoverflow.com/a/47839137
answers question: http://stackoverflow.com/q/47838998
score: 0
has body: You are iterating using two values: for num, access in... but your testInput is not separated that way. All the numbers are in the first item and all the access msgs are in the second item. what you want is a list of number-access _pairs. EG [(21, 'denied'), (44, 'Try Again'), (99, 'someMessage') ...] try pairs = zip(testInput[0], testInput[1]) this takes the first item in each list (testInput[0] and testInput[1]) and matches them together. So the first number gets put into a tuple with the first access, the second num with second access... and so on. Then run pairs through for loop for number, access in pairs: df = df.append({'Access Message': access, 'Number': number},ignore_index=True) print df
type: Answer

http://stackoverflow.com/a/65614918
downvote count: 0
answers question: http://stackoverflow.com/q/47797507
has body: Use = feature of f-strings since Python 3.8 logger.debug(f"{apple=}") Output apple=green. See Python: Print a variable's name and value?.
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/comment/85488532
score: 0
has text: Are you having a problem with the Reeher API specifically?
comment on: http://stackoverflow.com/q/47803765
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47790262
has comment: http://stackoverflow.com/comment/82541695
has title: How do I install py.test on a new MacBook ? pip fails
has comment: http://stackoverflow.com/comment/82548372
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/82541570
has comment: http://stackoverflow.com/comment/82541668
has comment: http://stackoverflow.com/comment/82541573
tagged with: macos
has comment: http://stackoverflow.com/comment/82541814
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/82541829
type: Question
has comment: http://stackoverflow.com/comment/82541739
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82542070
upvote count: 1
tagged with: python
has body: Trying to use pip install pytest fails as pip has a problem with the package 6. Here with a more detailed dump : Found existing installation: six 1.4.1 DEPRECATION: Uninstalling a distutils installed project (six) has been deprecated and will be removed in a future version. This is due to the fact that uninstalling a distutils project will only partially uninstall the project. Uninstalling six-1.4.1: Exception: ... OSError: [Errno 1] Operation not permitted: '/var/folders/gl/6qz_qqhn52g658r712r1rlnh0000gn/T/pip-XD54Hn-uninstall/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/six-1.4.1-py2.7.egg-info'

http://stackoverflow.com/q/47815193
score: 0
tagged with: list
answer count: 0
linked to: http://stackoverflow.com/q/9457832
has comment: http://stackoverflow.com/comment/82591758
has comment: http://stackoverflow.com/comment/82591873
duplicate of: http://stackoverflow.com/q/9457832
type: Question
has comment: http://stackoverflow.com/comment/82592719
type: UnansweredQuestion
tagged with: python
has title: What is the fastest way to transpose a python list clockwise for a given number of indexes
has body: I have very big lists of more than 500 elements so I will minimise the example to make the visualisation easier, say I have: a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] and I was to have a function to which I give a list and a number of places to switch the elements clockwise of the form: def transpose_by_n(list, n): pass The result of transpose_by_n(a, 1) will be a = [10, 1, 2, 3, 4, 5, 6, 7, 8, 9] and the result of transpose_by_n(a, 5) will be a = [6, 7, 8, 9, 10, 1, 2, 3, 4, 5] Thanks

http://stackoverflow.com/a/47840704
has comment: http://stackoverflow.com/comment/82645653
type: Answer
has comment: http://stackoverflow.com/comment/82645921
has body: Yes, just change the second loop to: for row in df: and then refer to the row with "row", not name. for col in df: #All columns for row in df: ##All rows, except first if row==1: continue #this skips to next loop iteration if pd.isnull(df.loc[row[0],'Album_Name']): ##If this cell is empty all in the same row too. continue elif pd.isnull(df.loc[row[0], col]) and pd.isnull(df.loc[row[0]+1, col]): ##If a cell and next one are empty, take previous value. df.loc[row[0], col] = df.loc[row[0]-1, col]
score: 0
answers question: http://stackoverflow.com/q/47840376

http://stackoverflow.com/comment/82615959
type: Comment
type: QuestionComment
has text: Understood, but I want it for multiple applications on different servers.
score: 0
comment on: http://stackoverflow.com/q/47826658

http://stackoverflow.com/a/47832327
has body: You can use a list comprehension. tup = () tuple([t[1] for t in your_list_of_tuples if t[1] not in tup]) By the way, id is not a good variable name because it is a builtin.
upvote count: 1
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/47832205
type: Answer

http://stackoverflow.com/a/47794638
accepted answer of: http://stackoverflow.com/q/47783409
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47783409
has body: (windows10) Based on zwer his comment I tried and failed with cmdow but could search with additional words like (cmdow, console, etc.) and found a very nice comment on superusers here from Robert. Solution for permanent replacement of server console (conhost.exe): 1 - press Alt + SHIFT and; 2 - go to "properties"; 3 - select tab "layout"; 4 - go to groupbox "window selection"; 5 - uncheck the box "let system set position" Voila... next time this console is started its on the new position. In addition: window size and hscreen buffer can also be addressed there. No apparent need to use cmdow anymore. Above all... on windows10 Ctrl-C no longer works as exit/quite for this type of server console. Use Alt + F4 instead.
type: Answer
score: 0

http://stackoverflow.com/comment/82592815
comment on: http://stackoverflow.com/q/47815650
score: 1
type: Comment
type: QuestionComment
has text: Are you trying to do something like `tuple(sorted(the_dict.values()))` ?

http://stackoverflow.com/comment/82422699
score: 0
comment on: http://stackoverflow.com/q/47730818
type: QuestionComment
has text: @HilbertoSilva your function `trueanomaly` is returning a value that you need to store in a variable then, e.g. `ta = trueanomaly (e, E0)`, and you need to do that for any function that you're using. The variables declared within a function only exist in the function, not outside it, and so you cannot access `ta` outside of your `trueanomaly` function. It's the same for all the other functions that you are calling, btw.
type: Comment

http://stackoverflow.com/comment/82516370
type: QuestionComment
comment on: http://stackoverflow.com/q/47777608
has text: Because `q.split()` _does not modify `q` in-place_.
score: 3
type: Comment

http://stackoverflow.com/q/47770096
has body: Given a Tensor of shape (A, B, C, D, E) and a tensor of shape (A, B, E), I would like to do a batch multiplication with automatic broadcasting of the second tensor, such that: In [1]: X = tf.placeholder(dtype=tf.float32, shape=[A, B, C, D, E]) In [2]: Y = tf.placeholder(dtype=tf.float32, shape=[A, B, E]) In [3]: # DO SOMETHING LIKE tf.matmul(X, Y) Out[3]: &lt;tf.Tensor 'MatMul_1:0' shape=(A, B, C, D) dtype=float64&gt; Is it even possible? Thanks in advance
has answer: http://stackoverflow.com/a/47775093
upvote count: 1
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/47520854
downvote count: 0
answer count: 1
tagged with: tensorflow
favorite count: 0
type: Question
score: 1
tagged with: python
tagged with: linear-algebra
has title: Batch tf.matmul of tensors with different ranks

http://stackoverflow.com/comment/82433789
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47736659
has text: Please show a few lines from `X_train1`.
score: 0

http://stackoverflow.com/q/47773412
tagged with: python
has comment: http://stackoverflow.com/comment/82508603
has comment: http://stackoverflow.com/comment/82508803
has body: At the moment I am trying to make a mastermind-type code, like the game. I am currently stuck on the bit where I am trying to check if the users guess is correct. colours = ["R","O","Y","G","B","I","V"] n = 1 ans = random.choices(colours, k = 4) print(*ans) guess = input("what is your guess? ") [guess[i:i+n] for i in range(0, len(guess), n)] guess = (guess.upper()) def check(): correct = False right = 0 wrong = 0 if guess == ans: correct = True elif guess != ans: correct = False for i in range(0,(len(guess))): for x in range(0,(len(ans))): if guess[i] in ans: wrong += 1 break print(right,"black pegs") print(wrong,"white pegs") return check() If ans = "R O Y Y", and guess = "R G O O" I would want the output to be 1 white pegs 1 black pegs what it actually gives me is 3 white pegs 0 black pegs white pegs means right colour, wrong place, black pegs means right colour, right place How would I go around coding the black pegs?
accepted answer: http://stackoverflow.com/a/47774095
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/47774961
has answer: http://stackoverflow.com/a/47774046
has answer: http://stackoverflow.com/a/47773548
possible better answer: http://stackoverflow.com/a/47773548
has comment: http://stackoverflow.com/comment/82508704
has comment: http://stackoverflow.com/comment/82508952
has comment: http://stackoverflow.com/comment/82508136
answer count: 4
type: Question
has answer: http://stackoverflow.com/a/47774095
has title: Mastermind check result python
has comment: http://stackoverflow.com/comment/82508557
tagged with: algorithm
has comment: http://stackoverflow.com/comment/82507633

http://stackoverflow.com/comment/82472082
type: AnswerComment
score: 0
has text: Great comments, Erfan please leave feedback if it worked as you said. Check his reply with an ANSWER so that the future users may find use in it too.
type: Comment
comment on: http://stackoverflow.com/a/47752018

http://stackoverflow.com/q/47770973
type: AnsweredQuestion
score: 0
answer count: 1
upvote count: 1
downvote count: 1
has body: a = dd.read_csv('huge.csv', blocksize=1e6) g = a.groupby(['col_a', 'col_b']) g.col_c.sum().max().compute() # failed, MemoryError I thought dask.dataframe won't fail on memory issues, but what? BTW, blocksize matters I think, what if I set a very small size, say 1e3, the read_csv takes forever to finish....
favorite count: 0
type: Question
tagged with: dask
accepted answer: http://stackoverflow.com/a/47774376
tagged with: dataframe
tagged with: python
has title: dask dataframe memory issue on large file
has answer: http://stackoverflow.com/a/47774376

http://stackoverflow.com/q/47820002
has comment: http://stackoverflow.com/comment/82608035
has title: pd.read_csv() incorrectly truncating timestamps formatted as scientific notation in Excel
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82607608
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/82602797
has comment: http://stackoverflow.com/comment/82602631
tagged with: python
has comment: http://stackoverflow.com/comment/82602881
has comment: http://stackoverflow.com/comment/82603611
has answer: http://stackoverflow.com/a/47821861
has body: I have a dataset in csv format that automatically downloads from a webservice. The csv file has the following general format: csv file in excel [Timestamp] [Column B] 1.51258E+12 A 1.51242E+12 B 1.51242E+12 C When the ['Timestamp'] formatting is changed in excel from 'General' to 'Number', the full number shows as follows: csv file (formatting changed in excel) [Timestamp] [Column B] 1512584017891 A 1512423886571 B 1512423818970 C I need to automate the processing of the csv file, and so I cannot go into the file in excel every time to switch the format from general to timestamp. What I'm finding is that pd.read_csv() is importing the ['Timestamp'] csv column as scientific notation, leaving a truncated df['Timestamp'] dtype=float64. df (in pandas) [Timestamp] [Column B] 1.512580e+12 A 1.512420e+12 B 1.512420e+12 C Notice how now df['Timestamp'] added a 0 prior to the E+12 when importing. I tried to convert df['Timestamp'].astype('int64'), but this showed what I was worried about: pd.read_csv() substituted the hidden digits for zeros. In[1]: df['Timestamp'].astype('int64').head(3) Out[1]: 1512580000000 1512420000000 1512420000000 Name: Timestamp, dtype: int64 Is there a way to 1) import the right timestamp, and then 2) convert that timestamp to the following format: 12/14/2017 10:32:12 AM?
tagged with: excel
tagged with: timestamp
has comment: http://stackoverflow.com/comment/82606682
has answer: http://stackoverflow.com/a/47823577
score: 2
upvote count: 2
downvote count: 0
answer count: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/47820773
has comment: http://stackoverflow.com/comment/82603058
favorite count: 0
type: Question

http://stackoverflow.com/a/47707256
score: 1
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/82410700
answers question: http://stackoverflow.com/q/47707016
has body: Since the tree structure and also answers to queries are given in terms of indices, not values, you can simply keep your labels in a separate array with the same order. Demo: a = np.random.rand(100, 3) t = cKDTree(a) t.tree.indices # array([13, 12, 18, 19, 20, 47, 54, 55, 83, 88, 82, 40, 31, 10, 45, 22, 15, # 95, 76, 46, 94, 62, 5, 84, 74, 63, 80, 81, 59, 9, 34, 29, 71, 61, # 73, 4, 85, 0, 16, 39, 35, 26, 53, 69, 77, 6, 36, 97, 57, 78, 90, # 32, 38, 68, 65, 96, 3, 24, 66, 11, 86, 89, 91, 30, 67, 42, 28, 33, # 7, 44, 8, 17, 60, 56, 41, 43, 92, 51, 58, 2, 93, 21, 14, 64, 70, # 87, 72, 50, 25, 49, 98, 37, 99, 52, 1, 48, 75, 79, 23, 27]) t.query_pairs(0.1) # {(20, 55), (48, 98), (6, 35), (38, 89), (98, 99), (26, 39), (45, 84), (26, 53), (37, 48), (48, 99), (15, 46), (36, 97), (14, 87), (42, 56), (37, 99), (5, 94), (71, 73), (0, 85), (70, 72), (22, 74), (37, 98)}
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47707016

http://stackoverflow.com/q/47697945
has comment: http://stackoverflow.com/comment/82355876
has comment: http://stackoverflow.com/comment/82363770
has answer: http://stackoverflow.com/a/47698278
tagged with: python
has comment: http://stackoverflow.com/comment/82356286
has comment: http://stackoverflow.com/comment/82355751
linked to: http://stackoverflow.com/q/10506973
score: 3
has comment: http://stackoverflow.com/comment/82355714
answer count: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/82355974
downvote count: 0
has answer: http://stackoverflow.com/a/47698578
favorite count: 0
type: Question
tagged with: python-3.x
has body: (I'm a beginner in Python, just so you know) What I'm trying to do: I want to keep count of how many times a user choose a wrong option and if it exceeds a number of times, he fails. My approach was to store the count in a variable within a function and check with if/else statement if the number of times is exceeded. Part of the code: choice = int(input("&gt; ")) if choice == 1: print("This is the wrong hall.") increment() elif choice == 2: print("This is the wrong hall.") increment() elif choice == 3: hall_passage() else: end("You failed") COUNT = 0 def increment(): global COUNT COUNT += 1 increment() print(COUNT) The increment part is from this thread and read using global scope is not a good practice. The part I don't really understand is how you store count in a variable and it remembers the last value every time the function runs. What is the best way to do this?
has title: Python: how to increment number and store in variable every time function runs
linked to: http://stackoverflow.com/q/23294658
has answer: http://stackoverflow.com/a/47698368
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/47680233

http://stackoverflow.com/comment/82530910
comment on: http://stackoverflow.com/q/47784653
type: Comment
type: QuestionComment
has text: This may be helpful also if it is, in fact, a network-related race condition: https://stackoverflow.com/questions/3764291/checking-network-connection
score: 0

http://stackoverflow.com/comment/82409864
has text: @J.McCraiton, 2-3 rows of dataframe will help
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47724115

http://stackoverflow.com/comment/82520904
score: 0
has text: as I know scrapy can use proxy servers to connect to web page - and this could helps but sometimes it is hard to find good and free proxy servers.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47774713

http://stackoverflow.com/q/47791384
upvote count: 1
downvote count: 1
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/82543967
has comment: http://stackoverflow.com/comment/82545313
has answer: http://stackoverflow.com/a/47791880
favorite count: 0
has comment: http://stackoverflow.com/comment/82544705
type: AnsweredQuestion
has title: Displaying image from ForeignKey in Admin Panel in Django
score: 0
answer count: 3
has comment: http://stackoverflow.com/comment/82543838
possible better answer: http://stackoverflow.com/a/47791880
has answer: http://stackoverflow.com/a/47792049
has body: I have in project two classes - Photo and Prescription inside models.py file which are related each other with foreign key. Here is part of the code: class Photo(models.Model): name = models.CharField(max_length=100,null=False) photo = models.ImageField(upload_to="photos/",null=True) def photo_tag(self): return '&lt;a href="/media/{0}"&gt;&lt;img src="/media/{0}"&gt;&lt;/a&gt;'.format(self.photo) photo_tag.short_description = 'Photo of prescription' photo_tag.allow_tags = True class Prescription(models.Model): description = models.CharField(max_length=100,null=True) photo = models.ForeignKey(Photo, related_name='related_photo',null=True) def __str__(self): return self.description And my Admin.py class PhotoAdmin(admin.ModelAdmin): list_display = ('name', 'photo_tag') fields = ('name','photo','photo_tag') readonly_fields = ('photo_tag',) admin.site.register(Photo,PhotoAdmin) class PrescriptionAdmin(admin.ModelAdmin): list_display = ('get_photo') fields = ('photo','description') model = Prescription def get_photo(self, obj): return obj.photo.photo_tag get_photo.short_description = 'Photo of prescription' admin.site.register(Prescription,PrescriptionAdmin) Question is, when I open prescriptions list instead of photo in the Photo of prescription field shows following message. &lt;bound method Photo.photo_tag of &lt;Photo: Photo object&gt;&gt; How real photo could be described there?
has comment: http://stackoverflow.com/comment/82544245
type: Question
has answer: http://stackoverflow.com/a/47792416
accepted answer: http://stackoverflow.com/a/47792416
tagged with: django-admin

http://stackoverflow.com/comment/82627035
comment on: http://stackoverflow.com/q/47831916
type: Comment
type: QuestionComment
has text: @Daniel Roseman I'm not getting what you are trying to say now. Those two line breaks is it in .html or .py file
score: 0

http://stackoverflow.com/a/47916583
score: 12
downvote count: 0
answers question: http://stackoverflow.com/q/47835726
upvote count: 12
type: Answer
has body: As @ImportanceOfBeingErnest noted in a comment, your code is fine but matplotlib has a 2d engine, so 3d plots easily show weird artifacts. In particular, objects are rendered one at a time, so two 3d objects are typically either fully in front of or fully behind one another, which makes the visualization of interlocking 3d objects near impossible using matplotlib. My personal alternative suggestion would be mayavi (incredible flexibility and visualizations, pretty steep learning curve), however I would like to show a trick with which the problem can often be removed altogether. The idea is to turn your two independent objects into a single one using an invisible bridge between your surfaces. Possible downsides of the approach are that you need to plot both surfaces as surfaces rather than a contour3D, and the output relies heavily on transparency, so you need a backend that can handle that. Disclaimer: I learned this trick from a contributor to the matplotlib topic of the now-defunct Stack Overflow Documentation project, but unfortunately I don't remember who that user was. In order to use this trick for your use case, we essentially have to turn that contour3D call to another plot_surface one. I don't think this is overall that bad; you perhaps need to reconsider the density of your cutting plane if you see that the resulting figure has too many faces for interactive use. We also have to explicitly define a point-by-point colormap, the alpha channel of which contributes the transparent bridge between your two surfaces. Since we need to stitch the two surfaces together, at least one "in-plane" dimension of the surfaces have to match; in this case I made sure that the points along "y" are the same in the two cases. import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D def f(theta1, theta2): return theta1**2 + theta2**2 fig, ax = plt.subplots(figsize=(6, 6), subplot_kw={'projection': '3d'}) # plane data: X, Y, Z, C (first three sha…

http://stackoverflow.com/comment/82472780
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47755807
has text: @ThomasMatthews I am sorry, I compile it as a C++ project in VS.

http://stackoverflow.com/a/47751863
score: 0
answers question: http://stackoverflow.com/q/47751788
type: AcceptedAnswer
has body: (the most important problem here) ip will hold lines from your file. This includes the newline character that you should remove using str.strip/str.rstrip. You could also use with...as when opening files so you don't have to worry about closing them later. with open('ip_host.txt') as fp: for line in fp: res = subprocess.Popen(["ping.exe", line.rstrip()]) ... The only difference between strip and rstrip is that the latter removes only trailing whitespace. If you have leading whitespaces too, use strip.
type: Answer
accepted answer of: http://stackoverflow.com/q/47751788

http://stackoverflow.com/a/47816686
score: 4
upvote count: 4
downvote count: 0
answers question: http://stackoverflow.com/q/47814809
has body: You can save the model weights using the following code. model.save_weights('weights.h5') And you can save the architecture of the model using the following code: model.save('architecure.h5') If space is not a problem then you can store all the models and select the one which has the lowest validation loss. Or you can use callbacks after each epoch to evaluate validation loss and take the model which has the current lowest loss on validation data. This can be done by referring to the following link. In this example just change the data passed to TestCallback and have a variable to store the current minimum validation loss. class TestCallback(Callback): def __init__(self, test_data): self.test_data = test_data def on_epoch_end(self, epoch, logs={}): x, y = self.test_data loss, acc = self.model.evaluate(x, y, verbose=0) print('\nTesting loss: {}, acc: {}\n'.format(loss, acc)) model.fit(X_train, Y_train, validation_data=(X_val, Y_val), callbacks=[TestCallback((X_test, Y_test))]) Using callbacks example
type: Answer

http://stackoverflow.com/comment/82562999
type: Comment
comment on: http://stackoverflow.com/a/47800875
type: AnswerComment
has text: For example, the `td` can have more than two elements nested. In which case, `(i[0],i[1],v)` would no longer work.
score: 0

http://stackoverflow.com/a/50613803
upvote count: 13
has body: I've found that filtering a Dask dataframe, e.g., by date, often results in empty partitions. If you're having trouble using a dataframe with empty partitions, here's a function, based on MRocklin's guidance, to cull them: def cull_empty_partitions(df): ll = list(df.map_partitions(len).compute()) df_delayed = df.to_delayed() df_delayed_new = list() pempty = None for ix, n in enumerate(ll): if 0 == n: pempty = df.get_partition(ix) else: df_delayed_new.append(df_delayed[ix]) if pempty is not None: df = dd.from_delayed(df_delayed_new, meta=pempty) return df
accepted answer of: http://stackoverflow.com/q/47812785
answers question: http://stackoverflow.com/q/47812785
type: Answer
type: AcceptedAnswer
downvote count: 0
score: 13

data-structures
tags question: http://stackoverflow.com/q/47737343
tags question: http://stackoverflow.com/q/47788081
tag name: data-structures
tags question: http://stackoverflow.com/q/47738554
tags question: http://stackoverflow.com/q/47738372
tags question: http://stackoverflow.com/q/47738959
tags question: http://stackoverflow.com/q/47783833
tags question: http://stackoverflow.com/q/47839546
type: Tag
tags question: http://stackoverflow.com/q/47705049
tags question: http://stackoverflow.com/q/47741022
tags question: http://stackoverflow.com/q/47774755
tags question: http://stackoverflow.com/q/47731767
tags question: http://stackoverflow.com/q/47851237

http://stackoverflow.com/q/47703695
linked to: http://stackoverflow.com/q/41892039
answer count: 0
tagged with: pycharm
upvote count: 2
has title: Remote Debugging with Pycharm, Unable plot figure on local machine
downvote count: 0
favorite count: 0
type: Question
has body: My local machine and remote server are both Ubuntu. And I have succeed setting remote debugging in pycharm, all things work well excepting plotting figure. I tried matplotlib but always failed to install pygtk or gtk package in conda py27 environment. I also tried ssh -x and it works well in terminal. I can see figures on my local machine. But it is not convenient to work on both pycharm and terminal.. I didn't find where can set '-x' argument in pycharm, is it possible to do that? The codes always broke by errors no 'DISPLAY' Variable. _tkinter.TclError: no display name and no $DISPLAY environment variable I have checked "ForwardX11 yes". I tried to add 'DISPLAY' in pycharm environment, by setting "DISPLAY my_local_ip:0.0" but the program just suspend at the plotting step. it seems the figure has been plot somewhere? just not my local machine.... Any one know how to deal with such issues? Test code: from __future__ import print_function import os print("Display is: %s" % (os.environ['DISPLAY'])) import matplotlib print("Default backend is: %s",matplotlib.get_backend()) matplotlib.use('TkAgg') print("Backend is now: %s",matplotlib.get_backend()) from matplotlib import pyplot pyplot.ioff() pyplot.plot([1, 2, 3]) pyplot.show()
type: UnansweredQuestion
tagged with: remote-debugging
tagged with: python
tagged with: ubuntu
score: 2
has comment: http://stackoverflow.com/comment/88749491

database
tags question: http://stackoverflow.com/q/47842573
tags question: http://stackoverflow.com/q/47774092
tags question: http://stackoverflow.com/q/47816716
tags question: http://stackoverflow.com/q/47822961
tags question: http://stackoverflow.com/q/47811629
tags question: http://stackoverflow.com/q/47797615
tags question: http://stackoverflow.com/q/47730994
tags question: http://stackoverflow.com/q/47747130
tags question: http://stackoverflow.com/q/47783297
tags question: http://stackoverflow.com/q/47844706
type: Tag
tags question: http://stackoverflow.com/q/47802937
tags question: http://stackoverflow.com/q/47732415
tags question: http://stackoverflow.com/q/47723959
tags question: http://stackoverflow.com/q/47743047
tags question: http://stackoverflow.com/q/47719890
tags question: http://stackoverflow.com/q/47724709
tags question: http://stackoverflow.com/q/47750439
tags question: http://stackoverflow.com/q/47801886
tags question: http://stackoverflow.com/q/47773047
tags question: http://stackoverflow.com/q/47802566
tag name: database

http://stackoverflow.com/comment/82408631
type: AnswerComment
has text: Hi @Omar with regards to your note, so what you're saying is that `.all()` means that every column has to meet the criteria, but `.any()` means that at least one column has to?
comment on: http://stackoverflow.com/a/47723723
type: Comment
score: 0

http://stackoverflow.com/q/47759777
answer count: 1
has title: Tensorflow get indices of values in a tensor
score: 6
tagged with: tensorflow
favorite count: 0
type: Question
tagged with: matrix
has answer: http://stackoverflow.com/a/47760684
tagged with: python
type: UnansweredQuestion
upvote count: 6
downvote count: 0
has body: Given a matrix and vector， I want to find the indices of the values in the corresponding rows of the matrix. m = tf.constant([[0, 2, 1],[2, 0, 1]]) # matrix y = tf.constant([1,2]) # values whose indices should be found the ideal output is [2,0] because the first value of y, 1, is at the index 2 of the first vector of m. The second value of y, 2, is at the index 0 of the second vector of m.

http://stackoverflow.com/a/47834497
answers question: http://stackoverflow.com/q/47833722
score: 0
has body: This code will get what you're looking for, without the need to convert your whole dataframe to a dictionary. However, I did have to convert each Pandas column to a list in order to add the name label to each point, but without the name labels you could have used the dataframe directly. # All the necessary imports import pandas as pd import matplotlib.pyplot as plt from matplotlib import style # There are several style templates in Matplotlib, this one seems to fit your look style.use('fivethirtyeight') # Reduce font size to reduce clutter plt.rcParams['font.size'] = 6.0 fig, ax = plt.subplots() # Create list from each dataframe column x = df['total matches'].tolist() y = df['win rate'].tolist() colors = df['color map'].tolist() names = df['name'].tolist() # Create scatter plot, c property takes list of colors ax.scatter(x, y, c=colors) # Iterate through names to add label to each point for i, txt in enumerate(names): ax.annotate(txt, (x[i],y[i])) # Show the chart, matplotlib can save the chart in several formats as well plt.show()
type: Answer

http://stackoverflow.com/a/47822151
has body: You can't use not or chained comparisons with arrays, since neither not nor chained comparisons can be implemented to broadcast. Split the chained comparison into two comparisons, and use ~ and &amp; instead of not and and, since NumPy uses the bitwise operators for boolean operations on boolean arrays: x[~((6 &lt; res) &amp; (res &lt; 18))] = numpy.nan
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/82606895
answers question: http://stackoverflow.com/q/47822077
has comment: http://stackoverflow.com/comment/82606906
accepted answer of: http://stackoverflow.com/q/47822077
type: Answer

http://stackoverflow.com/a/47836874
score: 2
has body: Given divstack, you can retrieve the full MultiIndex entry with .loc and min(): divstack.loc[divstack.eq(divstack.min())] Division Stack 9-10 F 3/3/03 2.13 Name: Time, dtype: float64
accepted answer of: http://stackoverflow.com/q/47836380
type: Answer
answers question: http://stackoverflow.com/q/47836380
has comment: http://stackoverflow.com/comment/82637735
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82637640

http://stackoverflow.com/q/47767461
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47767591
linked to: http://stackoverflow.com/q/47545052
tagged with: dataframe
tagged with: python
score: 4
has title: Grouping dataframe based on consecutive occurrence of values
upvote count: 4
type: AnsweredQuestion
has body: I have a pandas array which has one column which is either true or false (titled 'condition' in the example below). I would like to group the array by consecutive true or false values. I have tried to use pandas.groupby but haven't succeeded using that method, albeit I think that's down to my lack of understanding. An example of the dataframe can be found below: df = pd.DataFrame(df) print df print df index condition H t 0 1 2 1.1 1 1 7 1.5 2 0 1 0.9 3 0 6.5 1.6 4 1 7 1.1 5 1 9 1.8 6 1 22 2.0 Ideally the output of the program would be something along the lines of what can be found below. I was thinking of using some sort of 'grouping' method to make it easier to call each set of results but not sure if this is the best method. Any help would be greatly appreciated. index condition H t group 0 1 2 1.1 1 1 1 7 1.5 1 2 0 1 0.9 2 3 0 6.5 1.6 2 4 1 7 1.1 3 5 1 9 1.8 3 6 1 22 2.0 3
accepted answer: http://stackoverflow.com/a/47767591
answer count: 2
tagged with: pandas
possible better answer: http://stackoverflow.com/a/47767478
downvote count: 0
has answer: http://stackoverflow.com/a/47767478

http://stackoverflow.com/comment/82409656
type: Comment
has text: Or just `import kivy` then use them like `kivy.X.Y`
type: AnswerComment
comment on: http://stackoverflow.com/a/47724125
score: 1

http://stackoverflow.com/a/65987290
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/47828437
type: Answer
has body: I faced same problem So try from sklearn.base import BaseEstimator
downvote count: 0

http://stackoverflow.com/a/79130647
downvote count: 1
answers question: http://stackoverflow.com/q/47736578
has body: you need to pack the label. That's why is not running. Label.pack()
score: -1
upvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/139535656

http://stackoverflow.com/q/47758806
tagged with: pandas
answer count: 1
has comment: http://stackoverflow.com/comment/82478996
has body: I have two dictionaries like this: dict1 = {'foo': 3.0, 'bar': 2.69, 'baz': 3.0} dict2 = {'foo': {'11-abc1': 0.47}, 'bar': {'11-abc1': 0.30, '12-abc1': 0.0}, 'baz': {'14-abc1': 0.47}} Now I want to merge these two dictionaries while multiplying the values. The output should look like this: dict3 = {'foo': {'11-abc1': 3.0 * 0.47}, 'bar': {'11-abc1': 2.69 * 0.30, '12-abc1': 2.69 * 0.0}, 'baz': {'14-abc1': 3.0 * 0.47}} What would be the most efficient way to do that?
has answer: http://stackoverflow.com/a/47758933
accepted answer: http://stackoverflow.com/a/47758933
type: Question
tagged with: http://stackoverflow.com/tag/zip
has title: How do I merge one nested dictionary and one simple dictionary while changing the value in python?
tagged with: python
tagged with: merge
tagged with: dictionary
type: AnsweredQuestion
score: 0

http://stackoverflow.com/comment/82512339
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47775601
has text: Note: I'm not using 2.0 yet. I see the super call could be less verbose :)
score: 0

http://stackoverflow.com/comment/82675828
type: QuestionComment
score: 0
has text: Your next line is `for s in data`. What type do you believe `data` is?
comment on: http://stackoverflow.com/q/47855766
type: Comment

http://stackoverflow.com/comment/82411725
score: 0
has text: Michael: Yes there is...see updated question. If you want to do it "intelligently"—as in only when one is present—see [my answer](https://stackoverflow.com/a/11350095/355230) to a related question which uses the [`csv.Sniffer`](https://docs.python.org/3/library/csv.html#csv.Sniffer) class which makes it relatively easy to do so.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47723420

http://stackoverflow.com/comment/82372249
comment on: http://stackoverflow.com/q/47705583
type: Comment
has text: you can get elements one-by-one, if it is `Group` then save old list and create new one, if it `Item` then add to list. At start "old list" can be `None`.
score: 0
type: QuestionComment

http://stackoverflow.com/comment/82530906
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47783774
has text: @SagarDeshpande ah, could be, I've added that `time.sleep(1)` there - you can at least give it more time to load but better do it using `WebDriverWait()`.
score: 1

http://stackoverflow.com/comment/126236880
score: 1
type: Comment
comment on: http://stackoverflow.com/a/47769479
type: AnswerComment
has text: @Sca - use `for i, df in dfs.items(): print (df)`

http://stackoverflow.com/comment/82502500
score: 2
type: QuestionComment
has text: "Lac" is a regionalism and is not generally understood outside of the Indian cultural sphere.
comment on: http://stackoverflow.com/q/47769818
type: Comment

http://stackoverflow.com/q/47758404
score: 0
has comment: http://stackoverflow.com/comment/82478394
answer count: 1
has body: Hi, I have made a simple Tkinter program in Python 2.7, I typed up this script on a Linux Distro. When I execute the file on Windows 10 it can’t parse the file properly. Here’s the script: # Demo Program def hi(): print("Hello!") # end of function hi() # call function But the. It ends up like this on Windows: # Demo Programdef hi(): print("Hello")# end of functionhi() # call function I’m not sure if it’s soemthing to do with the encoding, the file that I wrote on my linux distro saved it in the UTF-8 format. When I type a text document on Windows it saves it in the ANSI encoding format. Overall, when I try and read the file it appears in a piece of junk that isn’t understandable. Even when I execute it in python on Windows it can’t read the file. Any help would be appreciated.
has comment: http://stackoverflow.com/comment/82478550
type: Question
tagged with: linux
has comment: http://stackoverflow.com/comment/82478095
has comment: http://stackoverflow.com/comment/82478586
tagged with: windows
has answer: http://stackoverflow.com/a/47758576
accepted answer: http://stackoverflow.com/a/47758576
tagged with: python
tagged with: character-encoding
has title: Windows not reading .py file correctly
type: AnsweredQuestion

http://stackoverflow.com/comment/82510210
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47774584
type: Comment
has text: i want get herf just matching 'linktext'. not all

http://stackoverflow.com/a/47703756
answers question: http://stackoverflow.com/q/47703606
downvote count: 0
has comment: http://stackoverflow.com/comment/82386380
has body: NOTE: This solution works only if each group has at least 3 rows Try the following approach: In [59]: x = (df.groupby(pd.Grouper(freq='H'))['VAL'] .apply(lambda x: x.nlargest(3)) .reset_index(level=1, drop=True) .to_frame('VAL')) In [60]: x Out[60]: VAL TIME 2017-12-08 00:00:00 82 2017-12-08 00:00:00 56 2017-12-08 00:00:00 53 2017-12-08 01:00:00 95 2017-12-08 01:00:00 87 2017-12-08 01:00:00 79 2017-12-08 02:00:00 88 2017-12-08 02:00:00 78 2017-12-08 02:00:00 41 In [61]: x.set_index(np.arange(len(x)) % 3, append=True)['VAL'].unstack().add_prefix('VAL') Out[61]: VAL0 VAL1 VAL2 TIME 2017-12-08 00:00:00 82 56 53 2017-12-08 01:00:00 95 87 79 2017-12-08 02:00:00 88 78 41 Some explanation: In [94]: x.set_index(np.arange(len(x)) % 3, append=True) Out[94]: VAL TIME 2017-12-08 00:00:00 0 82 1 56 2 53 2017-12-08 01:00:00 0 95 1 87 2 79 2017-12-08 02:00:00 0 88 1 78 2 41 In [95]: x.set_index(np.arange(len(x)) % 3, append=True)['VAL'].unstack() Out[95]: 0 1 2 TIME 2017-12-08 00:00:00 82 56 53 2017-12-08 01:00:00 95 87 79 2017-12-08 02:00:00 88 78 41
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82386830
has comment: http://stackoverflow.com/comment/82383592
has comment: http://stackoverflow.com/comment/82368627
accepted answer of: http://stackoverflow.com/q/47703606
upvote count: 5
score: 5
has comment: http://stackoverflow.com/comment/82368458
has comment: http://stackoverflow.com/comment/82377330
type: Answer

http://stackoverflow.com/comment/82620852
has text: I commented the instruction "lock.acquire()" and "lock.release()", now the program is working, that means that I misused the 'lock". However without a lock I will not get all the "outOfVocab" values. Has someone another suggestion?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47810819
score: 0

http://stackoverflow.com/q/47753932
favorite count: 0
has comment: http://stackoverflow.com/comment/82468729
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82468580
has body: I've written a script in python selenium to collect some zip-code against few addresses from a webpage using reverse search. It's doing fine if i put a hardcodeed delay after each click. Although I've created my scraper using Explicit Wait, I could not get rid of this flaw. This happens only because as soon as the page loads, the zip code automatically updates according to the address I'm living and after clicking on a new search it takes 1/2 seconds for the new record to get placed. How can I kick out harcoded delay from my script and still get the flawless results? Here is the link: URL The script I've tried with: import time from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.keys import Keys search_street =[ '43 Rue Caumartin', '14 rue du Théatre', '3 rue de Chevreuse', ] def find_zip(driver, wait): for item in range(len(search_street)): driver.get("use_the_above_url") wait = WebDriverWait(driver, 10) wait.until(EC.presence_of_element_located((By.ID, "address"))).send_keys(search_street[item],Keys.RETURN) time.sleep(2) ##if i take out, the results get messy item_val = wait.until(EC.presence_of_element_located((By.ID,"display_zip"))).text print(item_val) if __name__ == '__main__': driver = webdriver.Chrome() wait = WebDriverWait(driver, 10) try: find_address(driver, wait) finally: driver.quit()
tagged with: python
has answer: http://stackoverflow.com/a/47760713
has title: Can't kick out hardcoded delay from my script to get the accurate result
tagged with: selenium-webdriver
type: AnsweredQuestion
score: 1
accepted answer: http://stackoverflow.com/a/47760713
answer count: 1
downvote count: 0
tagged with: selenium
tagged with: web-scraping
upvote count: 1
has comment: http://stackoverflow.com/comment/82468600

http://stackoverflow.com/comment/82433983
has text: sure, fair enough. Just tested everything and this is most definitely the right answer, thanks!
score: 0
comment on: http://stackoverflow.com/a/47736565
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/96965830
comment on: http://stackoverflow.com/q/47778854
type: QuestionComment
has text: @Andrew Cassidy - did Anuj's answer help?
type: Comment
score: 0

http://stackoverflow.com/comment/82679784
has text: Thanks. I used HEATH3N's solution but this was very informative. I'm still having trouble with the yield statement but will continue to research.
comment on: http://stackoverflow.com/a/47853805
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/82535331
has text: @angelwally I'm also worried that `merge()` may take up too much RAM, but that could be irrational
comment on: http://stackoverflow.com/q/47786968
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47850202
accepted answer: http://stackoverflow.com/a/47850787
has comment: http://stackoverflow.com/comment/82665479
tagged with: matplotlib
possible better answer: http://stackoverflow.com/a/54529366
tagged with: python
has answer: http://stackoverflow.com/a/47850787
has answer: http://stackoverflow.com/a/54529366
has title: plotting a histogram on a Log scale with Matplotlib
tagged with: numpy
has body: I have a Pandas DataFrame that has the following values in a Series x = [2, 1, 76, 140, 286, 267, 60, 271, 5, 13, 9, 76, 77, 6, 2, 27, 22, 1, 12, 7, 19, 81, 11, 173, 13, 7, 16, 19, 23, 197, 167, 1] I was instructed to plot two histograms in a Jupyter notebook with Python 3.6. x.plot.hist(bins=8) plt.show() I chose 8 bins because that looked best to me. I have also been instructed to plot another histogram with the log of x. x.plot.hist(bins=8) plt.xscale('log') plt.show() This histogram looks TERRIBLE. Am I not doing something right? I've tried fiddling around with the plot, but everything I've tried just seems to make the histogram look even worse. Example: x.plot(kind='hist', logx=True) I was not given any instructions other than plot the log of X as a histogram. For the record, I have imported pandas, numpy, and matplotlib and specified that the plot should be inline.
has answer: http://stackoverflow.com/a/47850534
has answer: http://stackoverflow.com/a/76619653
has comment: http://stackoverflow.com/comment/119369898
has answer: http://stackoverflow.com/a/76648316
upvote count: 56
downvote count: 1
favorite count: 0
type: Question
tagged with: statistics
type: AnsweredQuestion
tagged with: pandas
answer count: 5
score: 55

http://stackoverflow.com/q/47723301
accepted answer: http://stackoverflow.com/a/47725872
tagged with: http://stackoverflow.com/tag/html
tagged with: django
tagged with: javascript
tagged with: python
has body: I've got a wee site set up to play some sounds a list of which are passed forward by my view. I'm going to go straight into the code: var sounds = ""; sounds = JSON.parse(sounds); var howls = {}; sounds.forEach(function(sound){ howls[sound] = new Howl({ src: ["{% static 'audio/"+sound+".mp3' %}"] }); $(document).on('click', '#'+sound+'_btn_play', function(){ howls[sound].play(); }); $(document).on('click', '#'+sound+'_btn_stop', function(){ howls[sound].stop(); }); } Not the neatest solution - the html template also creates a bunch of buttons and things for playing the sounds, which my Javascript references in those on click functions. I'm also using the Javascript Howler library to simplify the playing of the sounds. Now, when I was testing this locally it worked perfectly, but after I deployed, a problem arose in the line src: ["{% static 'audio/"+sound+".mp3' %}"]. It seems like this is being executed weirdly, because rather than inserting the sound into the Django tag and executing it as one string, it seems to be executing it as: src: ["{% static 'audio/%22%2Bsound%2B%22.mp3' %}"], i.e. attempting to parse the "+ as part of the string. I'm struggling to figure out why it's doing this when deployed but not locally. Also, any feedback on how to make this process better (perhaps not using template tags in Javascript, that doesn't feel right) would be much appreciated, but really I'm just looking for any way to pass this sound value to the tag in Javascript.
has title: Javascript and the Django 'static' template tag
type: AnsweredQuestion
upvote count: 3
score: 3
downvote count: 0
answer count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47725872

http://stackoverflow.com/comment/82541437
has text: @Szabolcs - `set` is a hash table, so O(1) search complexity on average.
score: 0
comment on: http://stackoverflow.com/a/47789759
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/82570145
comment on: http://stackoverflow.com/a/47804321
has text: That's part of the standard mathematical definition of "combination".
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/82506993
type: QuestionComment
comment on: http://stackoverflow.com/q/47772711
score: 0
has text: @JonClements I have run the same python 3 script in my current environment and it works.
type: Comment

http://stackoverflow.com/a/47736591
score: 2
type: Answer
has comment: http://stackoverflow.com/comment/82442880
has body: I wrote a code myself. # Compute confusion matrix def confusion_matrix(act_labels, pred_labels): uniqueLabels = list(set(act_labels)) clusters = list(set(pred_labels)) cm = [[0 for i in range(len(clusters))] for i in range(len(uniqueLabels))] for i, act_label in enumerate(uniqueLabels): for j, pred_label in enumerate(pred_labels): if act_labels[j] == act_label: cm[i][pred_label] = cm[i][pred_label] + 1 return cm # Example labels=['a','b','c', 'a','b','c', 'a','b','c', 'a','b','c'] pred=[ 1,1,2, 0,1,2, 1,1,1, 0,1,2] cnf_matrix = confusion_matrix(labels, pred) print('\n'.join([''.join(['{:4}'.format(item) for item in row]) for row in cnf_matrix])) Edit: (Dayyyuumm) just found that I could do this easily with Pandas Crosstab :-/. labels=['a','b','c', 'a','b','c', 'a','b','c', 'a','b','c'] pred=[ 1,1,2, 0,1,2, 1,1,1, 0,1,2] # Create a DataFrame with labels and varieties as columns: df df = pd.DataFrame({'Labels': labels, 'Clusters': pred}) # Create crosstab: ct ct = pd.crosstab(df['Labels'], df['Clusters']) # Display ct print(ct)
upvote count: 2
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47708865
accepted answer of: http://stackoverflow.com/q/47708865

http://stackoverflow.com/comment/82624651
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47830035
type: Comment
has text: Hi, the solution works fine. A small concern, i noticed that the date-format has changed in the output file. Any reason why i can't keep it the same as in the input file?

http://stackoverflow.com/comment/82379759
type: Comment
has text: There are many ways to do things. For your example, you should probably learn how to filter out text (applying contrast, using color range, edge detection, etc). After you have done that, look into ERFilter under opencv::text, use it to get the region of interest, then pass the region to tesseract for recognition. Also, doing OCR is a very broad topic. You should experiment things yourself and return with specific question after you have done it. There are a lot of details behind each steps and you should look into them yourself if you want to learn.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47709192

http://stackoverflow.com/comment/82512058
has text: @Icefire we can continue the discussion in the chat: https://chat.stackoverflow.com/rooms/161035/getting-error-when-using-class-in-tkinter-oop
comment on: http://stackoverflow.com/q/47774809
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/q/47747662
tagged with: python
has comment: http://stackoverflow.com/comment/82455629
has comment: http://stackoverflow.com/comment/82489672
answer count: 0
tagged with: h2o
has body: By executing the code h2o.connect() I am getting the error message "raise AttributeError("Attribute %s cannot be set on H2OCluster (= %r)" % (k, v)) AttributeError: Attribute internal_security_enabled cannot be set on H2OCluster (= False)". Can someone help me out with this issue? Thanks in advance.
score: 1
has comment: http://stackoverflow.com/comment/82460911
has title: Error while executing h2o framework python code
upvote count: 1
favorite count: 0
type: Question
type: UnansweredQuestion
downvote count: 0

http://stackoverflow.com/comment/82543555
comment on: http://stackoverflow.com/q/47767596
has text: Try [GLib GIO](https://lazka.github.io/pgi-docs/#Gio-2.0).
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47846629
upvote count: 1
has comment: http://stackoverflow.com/comment/82657460
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/82657423
accepted answer of: http://stackoverflow.com/q/47846569
answers question: http://stackoverflow.com/q/47846569
type: AcceptedAnswer
downvote count: 0
has body: When you ask for the negative of a type uint8 variable, the result overflows, because negative values don't exist for this type: &gt;&gt;&gt; -np.round(10 * 0.3333).astype('uint8') 253 Use a signed integer type and it will work as expected: &gt;&gt;&gt; -np.round(10 * 0.3333).astype('int') -3

http://stackoverflow.com/a/47802133
has body: You can transform one (filename, number) pair using this example program: def f(filename, n): res = filename for i in range(2, n+1): res += ' | ' + filename[:-4] + '_' + str(i) + '.jpg' return res print(f('test.com/img/abc.jpg', 3)) # test.com/img/abc.jpg | test.com/img/abc_2.jpg | test.com/img/abc_3.jpg If your data is a csv, the csv module should help you to both read and write csv files in Python.
answers question: http://stackoverflow.com/q/47801945
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/47801945
score: 0

http://stackoverflow.com/comment/82463839
comment on: http://stackoverflow.com/q/47751278
has text: @zwer So as the purpose of a terminal would be to execute arbitrary input from an external source, from your point of view terminals shoudln't exist ? I think there's some context missing as to how to program is intended to be used to really judge on those kind of question ...
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/q/47708608
answer count: 1
has body: I have a list created in Python, something like a=[1.0,3.7,1.0,3.9]. I need to check a condition with if at least two values in the list have values in the range [3.0,4.0], then do something.
downvote count: 1
favorite count: 0
type: Question
tagged with: if-statement
upvote count: 0
tagged with: python
score: -1
accepted answer: http://stackoverflow.com/a/47708639
has answer: http://stackoverflow.com/a/47708639
type: AnsweredQuestion
has title: Python: Checking at least two values in a list satisfy a condition
tagged with: list
tagged with: multiple-instances

http://stackoverflow.com/q/47713175
has answer: http://stackoverflow.com/a/47713549
has title: AttributeError while unpickling: Can't get attribute 'Location'
upvote count: 3
tagged with: cgi
favorite count: 0
type: Question
downvote count: 0
answer count: 1
has body: I'm writing a Python CGI script for an inventory system. It needs to store through pickle a list (called locations) of objects. Here's the code I'm using: try: with open(".config/autosave.bin", "rb") as dataFile: locations = pickle.load(dataFile) except (FileNotFoundError, PermissionError): dispHTML("p", contents="Error in load: Save file incorrectly configured!") locations = [] However, this results in: /Applications/MAMP/cgi-bin/ic/main.py in () 16 try: 17 with open(".config/autosave.bin", "rb") as dataFile: =&gt; 18 locations = pickle.load(dataFile) 19 except (FileNotFoundError, PermissionError): 20 dispHTML("p", contents="Error in load: Save file incorrectly configured!") AttributeError: Can't get attribute 'Location' on &lt;module '__main__' from '/Applications/MAMP/cgi-bin/ic/main.py'&gt; args = ("Can't get attribute 'Location' on &lt;module '__main__' from '/Applications/MAMP/cgi-bin/ic/main.py'&gt;",) with_traceback = &lt;built-in method with_traceback of AttributeError object&gt; As you can see the save file is stored at .config/autosave.bin. Writing to it seems to work fine but I haven't been able to check. How can I fix this?
tagged with: python
accepted answer: http://stackoverflow.com/a/47713549
type: AnsweredQuestion
score: 3

http://stackoverflow.com/a/47732946
has comment: http://stackoverflow.com/comment/82426624
has body: You can try this: import csv headers = ['name', 'ipadd', 'mac', 'interfaces'] new_data = [{a:b for a, b in zip(headers, i[:3]+[i[3:]])} for i in csv.reader(open('file.csv'))]
downvote count: 0
has comment: http://stackoverflow.com/comment/82426539
has comment: http://stackoverflow.com/comment/82426853
has comment: http://stackoverflow.com/comment/82427350
answers question: http://stackoverflow.com/q/47732878
has comment: http://stackoverflow.com/comment/82426594
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/82426500
type: Answer

http://stackoverflow.com/q/47818706
favorite count: 0
type: Question
answer count: 0
type: UnansweredQuestion
tagged with: android
downvote count: 0
has comment: http://stackoverflow.com/comment/82630001
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/82611036
has comment: http://stackoverflow.com/comment/82634280
has comment: http://stackoverflow.com/comment/82705020
has title: Is it possible to change the icon and the application name in the google developer console?
score: 1
has body: I have created an apk with kivy/buildozer, can I change the icon and the application name in the google Developer Console?
has comment: http://stackoverflow.com/comment/82633778
has comment: http://stackoverflow.com/comment/82624080
tagged with: kivy

http://stackoverflow.com/comment/82642044
has text: $ python -i Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:01:18) [MSC v.1900 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information.
comment on: http://stackoverflow.com/q/47839042
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/comment/82432690
type: QuestionComment
has text: @furas, 0xa8 is a double quote.
comment on: http://stackoverflow.com/q/47735949
score: 0
type: Comment

http://stackoverflow.com/q/47738537
has comment: http://stackoverflow.com/comment/82437398
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82437559
downvote count: 2
has comment: http://stackoverflow.com/comment/82437497
has comment: http://stackoverflow.com/comment/82437277
has comment: http://stackoverflow.com/comment/82437615
has body: I'm trying to use the max function in Python 3,6: print('Maximum is:', max(1, 3, 2, 5, 4)) And the result is File "E:/ProgramyRobione/untitled1.py", line 2, in &lt;module&gt; print('Maximum is:', max(1, 3, 2, 5, 4)) TypeError: 'int' object is not callable I'm using Spyder and that line is all that code should do.
has comment: http://stackoverflow.com/comment/82437360
has comment: http://stackoverflow.com/comment/82437478
has comment: http://stackoverflow.com/comment/82437381
tagged with: spyder
answer count: 1
tagged with: error-handling
has comment: http://stackoverflow.com/comment/82437357
has comment: http://stackoverflow.com/comment/82437598
has comment: http://stackoverflow.com/comment/82437419
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82437507
has comment: http://stackoverflow.com/comment/82437448
has answer: http://stackoverflow.com/a/47738834
accepted answer: http://stackoverflow.com/a/47738834
has comment: http://stackoverflow.com/comment/82437847
tagged with: function
has comment: http://stackoverflow.com/comment/82437345
linked to: http://stackoverflow.com/q/58018003
upvote count: 6
has comment: http://stackoverflow.com/comment/82437526
has comment: http://stackoverflow.com/comment/82437312
tagged with: python
score: 4
has comment: http://stackoverflow.com/comment/82437327
has title: Builtin function not working with Spyder
has comment: http://stackoverflow.com/comment/82437353
has comment: http://stackoverflow.com/comment/82437528

keras
tags question: http://stackoverflow.com/q/47774552
tags question: http://stackoverflow.com/q/47814809
tags question: http://stackoverflow.com/q/47741562
tags question: http://stackoverflow.com/q/47733980
tags question: http://stackoverflow.com/q/47783481
tags question: http://stackoverflow.com/q/47787458
tags question: http://stackoverflow.com/q/47837880
tags question: http://stackoverflow.com/q/47814481
tags question: http://stackoverflow.com/q/47788799
tags question: http://stackoverflow.com/q/47724077
tags question: http://stackoverflow.com/q/47759384
tags question: http://stackoverflow.com/q/47703051
tags question: http://stackoverflow.com/q/47750930
tags question: http://stackoverflow.com/q/47762881
tags question: http://stackoverflow.com/q/47847942
tags question: http://stackoverflow.com/q/47722292
tags question: http://stackoverflow.com/q/47842931
tags question: http://stackoverflow.com/q/47848606
tags question: http://stackoverflow.com/q/47735205
tags question: http://stackoverflow.com/q/47855197
tags question: http://stackoverflow.com/q/47840527
tags question: http://stackoverflow.com/q/47769181
tags question: http://stackoverflow.com/q/47747136
tags question: http://stackoverflow.com/q/47703927
tags question: http://stackoverflow.com/q/47800819
tags question: http://stackoverflow.com/q/47798854
tags question: http://stackoverflow.com/q/47702975
tags question: http://stackoverflow.com/q/47784351
tags question: http://stackoverflow.com/q/47834673
tags question: http://stackoverflow.com/q/47814459
tags question: http://stackoverflow.com/q/47749255
tag name: keras
tags question: http://stackoverflow.com/q/47716395
tags question: http://stackoverflow.com/q/47743202
tags question: http://stackoverflow.com/q/47785317
tags question: http://stackoverflow.com/q/47813824
tags question: http://stackoverflow.com/q/47710566
type: Tag
tags question: http://stackoverflow.com/q/47713596
tags question: http://stackoverflow.com/q/47726870
tags question: http://stackoverflow.com/q/47843265
tags question: http://stackoverflow.com/q/47727679
tags question: http://stackoverflow.com/q/47829428
tags question: http://stackoverflow.com/q/47803066
tags question: http://stackoverflow.com/q/47792376
tags question: http://stackoverflow.com/q/47773474
tags question: http://stackoverflow.com/q/47845448

http://stackoverflow.com/q/47794788
has title: If a number is a Prime Number?
has answer: http://stackoverflow.com/a/47795147
has answer: http://stackoverflow.com/a/47794919
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47795503
answer count: 5
type: UnansweredQuestion
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/47794940
has body: def isPrime(n): if n == 1: return False else: for i in range(2,n): if n%i == 0: return False return True I'd like to know why this code omits two when saying if a number isPrime and how do I fix it if I should make the value of n be 2.
has answer: http://stackoverflow.com/a/47794999
upvote count: 0

http://stackoverflow.com/comment/82557901
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47797909
type: Comment
has text: Can you please print the dictionary (`print(DoL)`)? The output format you use for it is strange.

http://stackoverflow.com/a/47733212
type: AcceptedAnswer
downvote count: 0
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/82426957
has body: I made a work around; I ended up creating an object class router: name = '' ipadd = '' mac = '' interfaces = [] def __init__(self, name, ipadd, mac, interfaces): self.name = name self.ipadd = ipadd self.mac = mac self.interfaces = interfaces with open('file.csv') as f: reader = csv.reader(f) for row in reader: item = row[0] newitem = item.split('\t') mylist.append(router(newitem[0], newitem[1], newitem[2], newitem[3:]))
accepted answer of: http://stackoverflow.com/q/47732878
has comment: http://stackoverflow.com/comment/82428653
answers question: http://stackoverflow.com/q/47732878
score: 1

http://stackoverflow.com/comment/82603623
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47820679
has text: And I'm assuming that on your models folder you have an __init__.py file importing models.py.

http://stackoverflow.com/comment/82619126
type: Comment
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/47828239
has text: I edited the code, try now. You had `print: ()` on the last line, which is the wrong python syntax.

iframe
tags question: http://stackoverflow.com/q/47841851
tags question: http://stackoverflow.com/q/47770144
tag name: iframe
type: Tag
tags question: http://stackoverflow.com/q/47770694
tags question: http://stackoverflow.com/q/47698704
tags question: http://stackoverflow.com/q/47831039
tags question: http://stackoverflow.com/q/47811895

http://stackoverflow.com/q/47761182
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82485971
linked to: http://stackoverflow.com/q/21524830
tagged with: models
has title: Django OneToOneField relation with to_field and db_column been ignored on makemigrations files
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/47775414
type: UnansweredQuestion
score: 1
has body: Even after reading the docs on db_column and Django' recomendations I was not able to accomplish the desired results with this feature. This is part of my code class DefaultBaseModel(models.Model): slug = models.SlugField(primary_key=True, unique=True, null=False, blank=False) class Bill(DefaultBaseModel): class Payment(DefaultBaseModel): bill = models.OneToOneField(Bill, related_name='payments', on_delete=models.CASCADE, to_field='slug', db_column='bill_slug') What I expect to do is the following on Django's shell: from apps.bills.models import Payment p = Payment.objects.first() p.bill_slug However I get the error: Traceback (most recent call last): File "&lt;console&gt;", line 1, in &lt;module&gt; AttributeError: 'Payment' object has no attribute 'bill_slug' Well, p.bill_id gives me the slug value but it is still creating the column with the suffix _id. I tried to delete makemigrations (migrate) files (those initial.py and others) and create it again Moved from Sqlite to Postgres Looked into Django's makemigrations files and db_column='bill_slug' was there. Any ideas?
answer count: 1
has comment: http://stackoverflow.com/comment/82483895
downvote count: 0

http://stackoverflow.com/a/47847391
downvote count: 0
upvote count: 1
score: 1
type: Answer
answers question: http://stackoverflow.com/q/47847283
has body: So we want to first generate a list of all the kid's money (and there kids) using the function you already have. We can do this with a comprehension. Then, we can use all() on a generator to check if all of the kid's money is the same (i.e. it is balanced). All in all, the function comes down to 2 lines: def balanced(person, money): kidsMoney = [amount_of_money(k, money) for k in kids[person]] return all(m == kidsMoney[0] for m in kidsMoney) and it does work: &gt;&gt;&gt; balanced("Adam", money) True
accepted answer of: http://stackoverflow.com/q/47847283
type: AcceptedAnswer

http://stackoverflow.com/a/76619653
type: Answer
has body: According to my experiment, the use of np.histogram might be unnecessary, since the two ends of x are exactly the minimum and the maximum, which needn't np.histogram to calculate: import numpy as np from matplotlib import pyplot as plt def plot_loghist(x, bins): logbins = np.logspace(np.log10(np.min(x)),np.log10(np.max(x)),bins+1) plt.hist(x, bins=logbins) plt.xscale('log') plot_loghist(np.random.rand(200), 10)
answers question: http://stackoverflow.com/q/47850202
score: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/47778543
has comment: http://stackoverflow.com/comment/82518222
has comment: http://stackoverflow.com/comment/82518373
type: Question
possible better answer: http://stackoverflow.com/a/47778719
has title: Using variable to call element of list is returning "List index out of range"
tagged with: python
has comment: http://stackoverflow.com/comment/82518361
has answer: http://stackoverflow.com/a/47778701
accepted answer: http://stackoverflow.com/a/47778701
has comment: http://stackoverflow.com/comment/82518284
type: AnsweredQuestion
score: 0
tagged with: list
answer count: 2
has body: I'm new to coding and have been having this problem for a bit, I've tried looking around and messing with the code but can't seem to find the problem as simple as the solution probably is. My code is: import random import sys import os clear = lambda: os.system('cls') clear() filt = int(raw_input("What number do you want your results to be filtered by?")) clear() gorl = raw_input("Do you want to filter numbers greater or lower than %i?" %(filt)) clear() ammvar = int(raw_input("How many variables do you want to filter?")) clear() y = ammvar var_list_remainder = [] var_list = [] varnum = 1 while ammvar &gt; 0: var_list.append(int(raw_input("Variable %i:"%(varnum)))) varnum = varnum + 1 ammvar = ammvar - 1 clear() print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") if gorl == "greater": x = 0 while y &gt; 0: if var_list[x] &gt; filt: var_list_remainder.append(var_list[x]) x = x + 1 y = y - 1 elif var_list[x] &lt;= filt: x = x + 1 y = y + 1 elif gorl == "lower": x = 0 while y &lt; 0: if var_list[x] &gt; filt: var_list_remainder.append(var_list[x]) x = x + 1 y = y - 1 elif var_list[x] &gt;= filt: x = x + 1 y = y + 1 print(var_list_remainder) print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") If I run this and I get to input my variables then the following error occurs: Traceback (most recent call last): File "c:/Users/D/OneDrive/Documents/Intro To Python/GreaterOrLower.py", line 43, in if var_list[x] > filt: IndexError: list index out of range
has answer: http://stackoverflow.com/a/47778719

http://stackoverflow.com/a/47852066
has body: If you are okay with using a library for this, paver is an option. The documentation here states a way to use paver without changing the way setuptools are used in a project.
score: 0
type: Answer
answers question: http://stackoverflow.com/q/47847370

http://stackoverflow.com/q/47852697
type: AnsweredQuestion
tagged with: pyqt
has body: I have a problem that the layout cannot automatically fill the window when the window changes its size. So how to make this layout to fill the window whenever the windows resizes? from PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(200,40) self.centralwidget = QtWidgets.QWidget(MainWindow) self.horizontalLayoutWidget = QtWidgets.QWidget(self.centralwidget) self.horizontalLayout = QtWidgets.QHBoxLayout(self.horizontalLayoutWidget) self.horizontalLayout.setContentsMargins(0, 0, 0, 0) self.label = QtWidgets.QLabel(self.horizontalLayoutWidget) self.label.setText("LABEL") self.horizontalLayout.addWidget(self.label) self.lineEdit = QtWidgets.QLineEdit(self.horizontalLayoutWidget) self.horizontalLayout.addWidget(self.lineEdit) MainWindow.setCentralWidget(self.centralwidget) QtCore.QMetaObject.connectSlotsByName(MainWindow) if __name__ == "__main__": import sys app = QtWidgets.QApplication(sys.argv) MainWindow = QtWidgets.QMainWindow() ui = Ui_MainWindow() ui.setupUi(MainWindow) MainWindow.show() sys.exit(app.exec_()) I want the line always to fill the width of window.
answer count: 1
downvote count: 0
tagged with: pyqt5
score: 1
upvote count: 1
accepted answer: http://stackoverflow.com/a/47852830
favorite count: 0
tagged with: qlayout
type: Question
has answer: http://stackoverflow.com/a/47852830
has title: How to make layout automatically fill window size
tagged with: python

http://stackoverflow.com/q/47839575
tagged with: odoo
accepted answer: http://stackoverflow.com/a/47840314
tagged with: python
has answer: http://stackoverflow.com/a/47840314
has body: I have 2 model "Book" and "Author". I have Many2many relation between them.If one of the Author is deleted from Author database, I should delete all the book that was written from this author.I have tried many ways but I am new in Odoo. So I couldn't. What will be the solution? Thanks. Book.py # -*- coding: utf-8 -*- from odoo import models, fields,api class Book(models.Model): _name = 'about.book' _description = 'Book Information' _order = 'publication_date desc, name' isbn = fields.Char('ISBN',required=True) name = fields.Char('Title', required=True) publication_date = fields.Date('Publication Date') author_ids = fields.Many2many('about.author', select=True, required=True,string='Authors') _sql_constraints = [('isbn_uniq', 'unique (isbn)','ISBN already exists!')] @api.constrains('publication_date') def _check_publication_date(self): for r in self: if (r.publication_date &gt; fields.Date.today()) and (r.publication_date == False): raise models.ValidationError('Publication date must be in the past !') @api.constrains('author_ids') def has_author(self): for r in self: if r.author_ids == False: raise models.ValidationError('Book must have at least 1 author!') @api.one def unlink(self): rule = self.env['about.book'] if rule.search([('author_ids', '=', False)]): rule.unlink() Author.py from odoo import models, fields,api class Author(models.Model): _name='about.author' _inherits = {'res.partner' : 'partner_id'} partner_id = fields.Many2one('res.partner', string="Author") is_book_author= fields.Boolean('Is Book Author',required=True,default=False)
has title: How to update the Model's database if it has Many2many relation with other Model's database in Odoo?
type: AnsweredQuestion
tagged with: odoo-10
answer count: 1
downvote count: 0
score: 1
upvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/comment/82510330
comment on: http://stackoverflow.com/q/47774660
has text: Did you check the other answer: https://stackoverflow.com/a/30041823/846892?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/47712336
has comment: http://stackoverflow.com/comment/82384744
answers question: http://stackoverflow.com/q/47712024
score: 1
downvote count: 0
upvote count: 1
type: Answer
has body: You may use the statement : if __name__ == '__main__': Which will be executed if you run this file as a script. In your case: def main_function() a=subfunction(b) def subfunction(value) do something return a if __name__ == '__main__': main_function() Note there is no need to import your function. Doing so you can order your fonction the way you want.

http://stackoverflow.com/a/47827561
has comment: http://stackoverflow.com/comment/82618077
upvote count: 1
has comment: http://stackoverflow.com/comment/82618037
has comment: http://stackoverflow.com/comment/82618152
has comment: http://stackoverflow.com/comment/82618466
has comment: http://stackoverflow.com/comment/82618139
has comment: http://stackoverflow.com/comment/82617663
has comment: http://stackoverflow.com/comment/82618314
has comment: http://stackoverflow.com/comment/82617821
has comment: http://stackoverflow.com/comment/82618669
has comment: http://stackoverflow.com/comment/82617937
has comment: http://stackoverflow.com/comment/82618441
score: 1
has comment: http://stackoverflow.com/comment/82617736
has body: I think you need transform with nunique and filter by boolean indexing: df = df[df.groupby(level='ID')['my_source'].transform('nunique') == 1] Or slowier solution with filtration: df = df.groupby(level='ID').filter(lambda d: d.my_source.nunique() == 1) Sample: df = pd.DataFrame({'my_source':list('abcccc'), 'B':[4,5,4,0,0,0], 'C':[7,8,9,4,2,3], 'D':[1,3,5,7,1,0], 'E':[5,3,6,9,2,4]}, index=list('aaabbb')) df.index.name = 'ID' print (df) B C D E my_source ID a 4 7 1 5 a a 5 8 3 3 b a 4 9 5 6 c b 0 4 7 9 c b 0 2 1 2 c b 0 3 0 4 c df1 = df.groupby(level='ID').filter(lambda d: d.my_source.nunique() == 1) df1 = df[df.groupby(level='ID')['my_source'].transform('nunique') == 1] print (df1) B C D E my_source ID b 0 4 7 9 c b 0 2 1 2 c b 0 3 0 4 c EDIT: df = df.reset_index() df = df[df.groupby('ID')['my_source'].transform('nunique') == 1]
type: Answer
has comment: http://stackoverflow.com/comment/82693445
has comment: http://stackoverflow.com/comment/82618218
has comment: http://stackoverflow.com/comment/82618949
answers question: http://stackoverflow.com/q/47827484
has comment: http://stackoverflow.com/comment/82618076
has comment: http://stackoverflow.com/comment/82618106
has comment: http://stackoverflow.com/comment/82618496
has comment: http://stackoverflow.com/comment/82618324
has comment: http://stackoverflow.com/comment/82693371
has comment: http://stackoverflow.com/comment/82617970
has comment: http://stackoverflow.com/comment/82617978
downvote count: 0

http://stackoverflow.com/comment/82600992
score: 1
type: QuestionComment
has text: What? *no* that isn't helpful at all. Again, please read the link. There are many ways to provide reproducible data. That isn't one of them...
type: Comment
comment on: http://stackoverflow.com/q/47818881

http://stackoverflow.com/a/47828870
score: 3
has body: you can keep track of the last line printed, compare the two, then replace identical elements with an equivalent number of spaces. import itertools l = [('name1','species','description','country','n/a'), ('name1','species','description','country','plasmid1'), ('name1','species','description','country','plasmid2')] last_line = [] for ll in l: line = [" "*len(el_l) if el_l == el_last else el_l for el_l, el_last in itertools.zip_longest(ll, last_line, fillvalue=None)] last_line = ll print("\t".join(line))
has comment: http://stackoverflow.com/comment/82620507
type: Answer
upvote count: 3
downvote count: 0
answers question: http://stackoverflow.com/q/47828776
has comment: http://stackoverflow.com/comment/82636561
has comment: http://stackoverflow.com/comment/82636245

http://stackoverflow.com/a/49712365
upvote count: 1
answers question: http://stackoverflow.com/q/47754749
has comment: http://stackoverflow.com/comment/107851546
type: Answer
has body: If @x0s answer gives dependency issues then try updating conda before that. conda update conda conda install -c peterjc123 pytorch_legacy cuda80
score: -1
downvote count: 2

http://stackoverflow.com/comment/82617400
comment on: http://stackoverflow.com/q/47826029
type: Comment
type: QuestionComment
has text: @Eugene S Yes, I did click on the *"See all 71 customer reviews"* and encountered that issue when I made an attempt to sort the reviews.
score: 0

http://stackoverflow.com/a/47840614
accepted answer of: http://stackoverflow.com/q/47834140
score: 9
has body: This implementation follows Matlab's and should give exactly the same results with the following exception: it throws an error if n &lt; 3 rather than return a non-magic square [[1, 3], [4, 2]] when n=2 like Matlab does. As usual, there are three cases: odd, divisible by 4, and even but not divisible by 4, the last one being the most complicated. def magic(n): n = int(n) if n &lt; 3: raise ValueError("Size must be at least 3") if n % 2 == 1: p = np.arange(1, n+1) return n*np.mod(p[:, None] + p - (n+3)//2, n) + np.mod(p[:, None] + 2*p-2, n) + 1 elif n % 4 == 0: J = np.mod(np.arange(1, n+1), 4) // 2 K = J[:, None] == J M = np.arange(1, n*n+1, n)[:, None] + np.arange(n) M[K] = n*n + 1 - M[K] else: p = n//2 M = magic(p) M = np.block([[M, M+2*p*p], [M+3*p*p, M+p*p]]) i = np.arange(p) k = (n-2)//4 j = np.concatenate((np.arange(k), np.arange(n-k+1, n))) M[np.ix_(np.concatenate((i, i+p)), j)] = M[np.ix_(np.concatenate((i+p, i)), j)] M[np.ix_([k, k+p], [0, k])] = M[np.ix_([k+p, k], [0, k])] return M I also wrote a function to test this: def test_magic(ms): n = ms.shape[0] s = n*(n**2+1)//2 columns = np.all(ms.sum(axis=0) == s) rows = np.all(ms.sum(axis=1) == s) diag1 = np.diag(ms).sum() == s diag2 = np.diag(ms[::-1, :]).sum() == s return columns and rows and diag1 and diag2 Try [test_magic(magic(n)) for n in range(3, 20)] to check the correctness.
type: AcceptedAnswer
downvote count: 0
upvote count: 9
answers question: http://stackoverflow.com/q/47834140
type: Answer

http://stackoverflow.com/q/47767259
has comment: http://stackoverflow.com/comment/82499761
tagged with: python-3.x
linked to: http://stackoverflow.com/q/123198
type: UnansweredQuestion
tagged with: python
score: -1
has title: Trying to copy one CSV data to another CSV file
has answer: http://stackoverflow.com/a/47767807
has comment: http://stackoverflow.com/comment/82495515
has body: I have 2 CSV files, say 'a.csv' and 'b.csv'. I want to copy the data of 'a.csv' into 'b.csv'. The whole of 'a.csv' data should be added at the end of the 'b.csv' import csv ifile = open('/Users/avtarsingh/Downloads/StocksProject-master/data/nasdaq.csv', 'w', newline='') read = csv.reader(ifile) writer = csv.writer(ifile) for row in ifile.readlines(): writer.writerow(['Avtar']) print(row) ifile.close() ================================================================= New Code:- with open('/Users/avtarsingh/Downloads/StocksProject-master/data/procter.csv', 'r') as f: # f = list(f) for row in f: print(row) time.sleep(2) with open('/Users/avtarsingh/Downloads/StocksProject-master/data/sp.csv', 'r') as g: for row1 in g: # g.writerow(f) print(row1) with open('/Users/avtarsingh/Downloads/StocksProject-master/data/nasdaq.csv', 'w') as h: writer = csv.writer(h) writer.writerows(f)
upvote count: 0
has comment: http://stackoverflow.com/comment/82766763
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/82496055
favorite count: 0
type: Question

http://stackoverflow.com/a/47767710
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/82497189
score: 1
type: Answer
answers question: http://stackoverflow.com/q/47767162
has body: The error is in your other features that you are treating as non-categorical features. Those columns like 'hedge_value', 'indicator_code' etc contains mixed type data like TRUE, FALSE from the original csv and 2.0 from your fillna() call. The OneHotEncoder is not able to process them. As mentioned in OneHotEncoder fit() documentation: fit(X, y=None) Fit OneHotEncoder to X. Parameters: X : array-like, shape [n_samples, n_feature] Input array of type int. You can see that it requires all X to be of numerical (int, but float will do) type. As a workaround you can do this to encode your categorical features: X_train_categorical = x_train[:, [0,1,2,3,6,8,14]] onehotencoder = OneHotEncoder() X_train_categorical = onehotencoder.fit_transform(X_train_categorical).toarray() And then concatenate this with your non-categorical features.
has comment: http://stackoverflow.com/comment/82501685

http://stackoverflow.com/q/47721618
tagged with: python
type: UnansweredQuestion
has title: FOREIGN KEY constraint failed when in CLI but not with Python script?
linked to: http://stackoverflow.com/q/4477269
has comment: http://stackoverflow.com/comment/82404616
tagged with: sqlite
downvote count: 0
has comment: http://stackoverflow.com/comment/82415794
duplicate of: http://stackoverflow.com/q/4477269
answer count: 0
score: 1
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/82404652
type: Question
has body: I created the MyStudents.db SQLite database with followings commands in sqlite3 CLI: CREATE TABLE workpiecelist ( idnum integer CONSTRAINT pk_workpiecelist PRIMARY KEY AUTOINCREMENT , grade integer NOT NULL , quart integer NOT NULL , workpiecenamehu text NOT NULL COLLATE nocase , workpiecenamesr text NOT NULL COLLATE nocase ); CREATE TABLE student ( id integer CONSTRAINT pk_student PRIMARY KEY AUTOINCREMENT , idnum integer UNIQUE NOT NULL , studentsname text NOT NULL COLLATE nocase , lang text NOT NULL COLLATE nocase , grade integer NOT NULL , class text NOT NULL COLLATE nocase , headteacher text NOT NULL COLLATE nocase ); CREATE TABLE uniqueworkpc (id integer CONSTRAINT pk_uniqueworkpc PRIMARY KEY AUTOINCREMENT, student_who_owns_workpc text NOT NULL REFERENCES student (idnum) ON DELETE CASCADE ON UPDATE CASCADE , numofworkpc_fromthelist integer NOT NULL REFERENCES workpiecelist (idnum) ON DELETE CASCADE ON UPDATE CASCADE , mark integer , reason text); Then I inserted two records into workpiecelist table with: INSERT INTO workpiecelist VALUES(1,5,1,'workpeaceNameHu1','workpeaceNameSr1'); INSERT INTO workpiecelist VALUES(2,5,1,'workpeaceNameHu2','workpeaceNameSr2'); and ten records into student table: INSERT INTO student VALUES(1,29660,'FirstName1 LastName1','Hu',5,'b','HeadTeachers Name'); INSERT INTO student VALUES(2,12037,'FirstName2 LastName2','Hu',5,'b','HeadTeachers Name'); INSERT INTO student VALUES(3,32284,'FirstName3 LastName3','Hu',5,'b','HeadTeachers Name'); INSERT INTO student VALUES(4,20125,'FirstName4 LastName4','Hu',5,'b','HeadTeachers Name'); INSERT INTO student VALUES(5,20624,'FirstName5 LastName5','Hu',5,'b','HeadTeachers Name'); INSERT INTO student VALUES(6,14302,'FirstName6 LastName6','Hu',5,'b','HeadTeachers Name'); INSERT INTO student VALUES(7,28590,'FirstName7 LastName7','Hu',5,'b','HeadTeachers Name'); INSERT INTO student VALUES(8,13040,'FirstName8 LastName8','Hu',5,'b','HeadTeachers Name'); INSERT INTO student VALUES(9,12514,'FirstName9 LastN…

http://stackoverflow.com/q/47733697
tagged with: python-2.7
score: 0
answer count: 2
tagged with: subprocess
linked to: http://stackoverflow.com/q/19130958
has comment: http://stackoverflow.com/comment/82427993
has answer: http://stackoverflow.com/a/47733719
has title: Code regarding game won for lillypad not seem to be working
type: Question
accepted answer: http://stackoverflow.com/a/47735861
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47735861
has body: To be more specific been trying to code a frog and toad game. Most of the code works however can not seem to get python to display when the user has won the game. Feel free to ask for any added information. frogandtoad= ['f','f','f',' ', 't','t','t'] def game_won(): for i in range(0,3): if frogandtoad[i] =='f': frog = True if frogandtoad[i]=='t': toad = True if frog == True and toad == True: return True def playgame(frogandtoad): print("From: ") from_pos = int(input()) - 1 print("To: ") to_pos = int(input())-1 #Bring in valid_move valid = valid_move(frogandtoad, from_pos, to_pos) if valid: value = frogandtoad[from_pos] frogandtoad[to_pos] = value frogandtoad[from_pos] = ' ' print("frogandtoad panel", frogandtoad) else: print("Invalid Move, Look at rules under demonstration!") if game_won(): print("you won") exit_game()
possible better answer: http://stackoverflow.com/a/47733719
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/82405452
type: AnswerComment
comment on: http://stackoverflow.com/a/47718154
has text: e.g. `xytext=(0,(-1)**i*30)`
type: Comment
score: 0

http://stackoverflow.com/q/47766256
favorite count: 0
type: Question
upvote count: 2
downvote count: 2
tagged with: pyspark
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/82494310
has body: For example, the structure of local file data.txt is: 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 ... Reading file as RDD[String]: lines = sc.textFile("data.txt") split into RDD[List[String]]: data_temp = lines.map(lambda line: line.split(" ")) How to convert into RDD[List[Float]]? I know json.loads() can parse the string, how to do in this case?
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47766573
score: 0
tagged with: apache-spark
has title: How to convert RDD[List[String]] to RDD[List[Float]]
has answer: http://stackoverflow.com/a/47766573

http://stackoverflow.com/a/47770928
score: 0
has comment: http://stackoverflow.com/comment/82504039
has comment: http://stackoverflow.com/comment/82504157
has comment: http://stackoverflow.com/comment/82504273
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82503634
has comment: http://stackoverflow.com/comment/82503870
has comment: http://stackoverflow.com/comment/82503580
has comment: http://stackoverflow.com/comment/82503994
has body: Have you tried to run the command as administrator?
has comment: http://stackoverflow.com/comment/82503776
has comment: http://stackoverflow.com/comment/82503945
has comment: http://stackoverflow.com/comment/82503701
has comment: http://stackoverflow.com/comment/82504014
accepted answer of: http://stackoverflow.com/q/47770473
type: Answer
answers question: http://stackoverflow.com/q/47770473

http://stackoverflow.com/q/47803215
has comment: http://stackoverflow.com/comment/82580833
linked to: http://stackoverflow.com/q/19576978
type: AnsweredQuestion
score: 0
has body: My question is how does one get all data in a row (in a printable format, not just the object) where the user can specify the names of the columns of data they want. Here's my current code: #!/usr/bin/python3 from sqlalchemy import create_engine, MetaData, Table, Column, String, Integer from sqlalchemy.orm import mapper, sessionmaker from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker class SQL_Engine: def __init__(self, dbpath, username, password, dbtype='sqlite', tableName='content_blocks', connector=None): self.dbpath = dbpath self.username = username self.password = password self.dbtype = dbtype self.tableName = tableName self.connector = connector def Create_Session(self): if self.connector == None: engine = create_engine(self.dbtype+"://"+self.username+":"+self.password+"@"+self.dbpath) else: engine = create_engine(self.dbtype+"+"+self.connector+"://"+self.username+":"+self.password+"@"+self.dbpath) Base = declarative_base(engine) class ContentBlocks(Base): __tablename__ = self.tableName __table_args__ = {'autoload':True} metadata = Base.metadata Session = sessionmaker(bind=engine) session = Session() return session, ContentBlocks, Base def ViewTable(self): session, ContentBlocks, Base = self.Create_Session() request = session.query(ContentBlocks).all() columns = ContentBlocks.__table__.columns.keys() table = " ".join(columns) for entry in request: for column in columns: #print entry.column; can't do this as of yet My initial attempt, as you can see in Create_Session() was to retrieve all the column names and pass them as a variable into entry object, however this just results in an error: Traceback (most recent call last): File "SQLDeduplication-copy.py", line 131, in &lt;module&gt; no.ViewTable() File "SQLDeduplication-copy.py", line 64, in ViewTable print(entry.column) AttributeError: 'ContentBlocks' object has no attribute 'column' Thus, I need to make python interpret column …
linked to: http://stackoverflow.com/q/2612610
has comment: http://stackoverflow.com/comment/82580927
tagged with: python
has answer: http://stackoverflow.com/a/48065951
accepted answer: http://stackoverflow.com/a/48065951
tagged with: sqlalchemy
type: Question
has title: Getting a whole row's data without knowing the column names in sqlalchemy
answer count: 1
has comment: http://stackoverflow.com/comment/82646587

http://stackoverflow.com/q/47768826
tagged with: windows
has comment: http://stackoverflow.com/comment/82500228
tagged with: ssh
tagged with: python
score: -1
tagged with: paramiko
type: AnsweredQuestion
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/82499629
upvote count: 0
accepted answer: http://stackoverflow.com/a/47828806
answer count: 1
has comment: http://stackoverflow.com/comment/82500595
has answer: http://stackoverflow.com/a/47828806
downvote count: 1
has body: I'm using paramiko to execute commands on a remote windows server. I'm able to execute commands like dir and extract the output, but executing a python script seems to fail. No error message is thrown. Here is my code snippet: def ssh_connect(ip,user,pwd): ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(ip, username=user, password=pwd) return ssh def execute_command(device_details, command): ip = device_details.get('ip') username = device_details.get('username') password = device_details.get('password') ssh_ns_obj = ssh_connect(ip, username, password) ssh_stdin, ssh_stdout, ssh_stderr = ssh_ns_obj.exec_command(command) print ssh_stderr.read() return ssh_stdout.read() device_details = dict() device_details['ip'] = 'a.b.c.d' device_details['username'] = 'Administrator' device_details['password'] = 'pass' command_1 = "cmd /c mkdir asdf" output = execute_command(device_details, command_1) command_2 = 'cmd /c "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\python.exe C:\pythonattempt\try.py"' output = execute_command(device_details, command_2) Here is my try.py mentioned in command_2: import os if __name__ == '__main__': print ("Hey, just starting") os.system(r"mkdir C:\Users\Administrator\Desktop\x") print ("hey, file is up") with open(r"C:\Users\Administrator\Desktop\x.txt", "w") as f: f.write("This is a line of a file") command_1 executes successfully, i'm able to see the directory created on my windows machine. But command_2 does not throw any error, but also doesn't get executed. I know because the x.txt or folder x does not get created. I've installed the freeSSHd service on Windows. I'm able to ssh into my Windows machine and execute the exact same command, and it's working. See image below: How do i proceed?
has comment: http://stackoverflow.com/comment/82500801
favorite count: 0
type: Question
has title: Execute python script on remote windows client
has comment: http://stackoverflow.com/comment/82499445

python-2.x
tags question: http://stackoverflow.com/q/47827858
tags question: http://stackoverflow.com/q/47736282
tags question: http://stackoverflow.com/q/47851320
tag name: python-2.x
tags question: http://stackoverflow.com/q/47706721
type: Tag

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

http://stackoverflow.com/q/47849484
tagged with: qtableview
score: 2
type: AnsweredQuestion
tagged with: contextmenu
upvote count: 2
answer count: 1
downvote count: 0
tagged with: pyqt5
favorite count: 0
has title: How to get the row number from a rigth-click on a QTableView?
type: Question
tagged with: position
accepted answer: http://stackoverflow.com/a/47849694
has body: I'm developing an app with PyQt5, and can't find out how to translate the position of a right click on a QTableView into a row number. The way I implemented it, which is by using the rowAt method on the QPoint cursor position, I get row numbers that look like having an offset with the real row number that was clicked. I've been looking around but couldn't get any clear solution. Sounds like there's something to do with the scrolling area. An example of my code is below. The UI code generated with Qt Designer: from PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.setWindowModality(QtCore.Qt.NonModal) MainWindow.resize(941, 767) MainWindow.setMinimumSize(QtCore.QSize(922, 767)) MainWindow.setMaximumSize(QtCore.QSize(1900, 1200)) MainWindow.setAutoFillBackground(False) MainWindow.setAnimated(False) self.MyWindows = QtWidgets.QWidget(MainWindow) self.MyWindows.setEnabled(True) self.MyWindows.setMinimumSize(QtCore.QSize(921, 726)) self.MyWindows.setMaximumSize(QtCore.QSize(1900, 1200)) self.MyWindows.setObjectName("MyWindows") self.layoutWidget = QtWidgets.QWidget(self.MyWindows) self.layoutWidget.setGeometry(QtCore.QRect(10, 0, 911, 441)) self.layoutWidget.setObjectName("layoutWidget") self.gridLayout = QtWidgets.QGridLayout(self.layoutWidget) self.gridLayout.setContentsMargins(0, 0, 0, 0) self.gridLayout.setObjectName("gridLayout") self.tableView = QtWidgets.QTableView(self.layoutWidget) self.tableView.setEnabled(True) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(1) sizePolicy.setVerticalStretch(1) sizePolicy.setHeightForWidth(self.tableView.sizePolicy().hasHeightForWidth()) self.tableView.setSizePolicy(sizePolicy) self.tableView.setMinimumSize(QtCore.QSize(900, 400)) font = QtGui.QFont() font.setPointSize(10) self.tableView.setFont(font) self.tableView.setSizeAdjustPolicy(QtWidgets.QAbstractS…
has answer: http://stackoverflow.com/a/47849694
tagged with: python

http://stackoverflow.com/comment/82551203
comment on: http://stackoverflow.com/q/47795001
type: Comment
type: QuestionComment
has text: Didn't know I could edit the code into an existing question. New in stackoverflow. I will keep that in mind for my next question. Thxs
score: 0

http://stackoverflow.com/comment/82636229
type: Comment
score: 0
has text: Not exactly. Lets say current index is a(i), then in the new list the index(a(i)) should contain the average(a(i-1), a(i), a(i+1)).
type: QuestionComment
comment on: http://stackoverflow.com/q/47836242

http://stackoverflow.com/q/47705675
tagged with: solr
tagged with: django
tagged with: python
has body: I'm working on a website that's running Django with Solr as it search backend. Haystack functions as Django's interface to Solr. I currently have one Solr collection, Apps. Apps each have multiple releases, but in Solr they manifest as one (most recent) release per app. I've come up against a limitation for that architecture: I need to be able to search all of an app's releases and return the most relevant one. Example data in Django ORM: App Foo Release A - released Nov 2017, compatible with Linux Release B - released April 2017, compatible with Windows Example search in Solr: Give me all the apps with a release that's compatible with Windows Expected: App Foo is returned. Actual: App Foo is not returned because we're only storing Release A's metadata in the App Foo document in Solr. A solution I'm pursuing is to index Solr based on Release rather than App. But when we do that, how do we use Solr/Haystack to return only the most recent release that matches the query? It seems like Result Grouping / Field Collapsing might solve the problem: http://yonik.com/solr-result-grouping-field-collapsing/ Grouping results based on a matching attribute in one field, and returning the top N results sounds about right. But does Haystack support it? If not, is there a way to shoehorn it in? An alternate solution might be to use Solr nested documents: http://yonik.com/solr-nested-objects/ Releases are indeed children of Apps. But again, I'm finding that Haystack doesn't support this feature. Also, the syntax for nested objects is ... crazy. What's the best practice for solving this problem? Result grouping or Nested objects? What's the difference between the two? Why would you use one and not the other? Lastly, am I going to have to rip out Haystack and use a different interface to Solr? Thanks in advance!
has title: Solr nested documents vs. grouping/field collapse (via Django Haystack)
type: UnansweredQuestion
answer count: 1
has answer: http://stackoverflow.com/a/48166117
type: Question
score: 0

http://stackoverflow.com/comment/82407565
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47722671
type: Comment
has text: Fantastic! Exactly as desired. Thanks Wen!

http://stackoverflow.com/comment/82570302
has text: Yes. You are unpacking something which can't be unpacked. Look what's returned by predict before unpacking to debug ```result=model.predict(crop)``` and ```print(result)```. You either misinterpret the docs or opencv's python-wrappers are broken or not following the C++ API. [Maybe relevant A](https://github.com/opencv/opencv_contrib/issues/512) and [B](https://github.com/menpo/conda-opencv3/issues/11) (but i won't do that research for you; maybe someone else will)
comment on: http://stackoverflow.com/q/47804333
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/q/47818459
type: Question
tagged with: python-3.x
tagged with: operator-overloading
has title: Overloading [] operator in python?
has comment: http://stackoverflow.com/comment/82599120
accepted answer: http://stackoverflow.com/a/47818534
tagged with: python
has answer: http://stackoverflow.com/a/47818534
has comment: http://stackoverflow.com/comment/82599001
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82598848
upvote count: 2
score: 1
answer count: 1
has body: Is it possible to overload the [] operator in python? I want to access a method of a class by calling classname[elementname] (like in a dict). This might seem unneccessary but the class encapsulates a database element with children that also have children that also have children that... You get the point. If I know which child from the 3rd inheritance step I want to get I could then instead of: classnname.getChild(childname1).getChild(childname2).getChild(childname3) use the shorter and cleaner: classnname[childname1][childname2][childname3]
has comment: http://stackoverflow.com/comment/82598745
downvote count: 1
favorite count: 0

ms-word
tag name: ms-word
type: Tag
tags question: http://stackoverflow.com/q/47703796
tags question: http://stackoverflow.com/q/47767576

http://stackoverflow.com/a/59788397
downvote count: 0
has body: Ok, i know im late.You can hide console window in pyinstaller by using --noconsole Such as this: python PyInstaller Filename.py --onefile --noconsole This will hide console window and program will execute normally.
type: Answer
answers question: http://stackoverflow.com/q/47840633
upvote count: 2
score: 2

http://stackoverflow.com/comment/82672790
comment on: http://stackoverflow.com/q/47841438
has text: @RayToal Helps to understand something, but how then can I check if log(x, base) gives result without decimal?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/82518057
score: 0
type: Comment
type: QuestionComment
has text: Ng Oon-Ee, what you want to do seems like an anti-pattern to me. I personally pass the `dbsession` to the functions. That `dbsession` is bound to the current transaction and it makes a lot of sense to do it that way instead of trying to rely on some global state in a threaded environment.
comment on: http://stackoverflow.com/q/47712122

http://stackoverflow.com/a/61402349
type: Answer
score: 0
answers question: http://stackoverflow.com/q/47726854
has body: [THIS IS A WINDOWS SPECIFIC GUIDE] I'm pretty late to this issue, but I hope this helps someone. I've added links to an easy to follow guide at the bottom. Here are the essential steps, you'd need to follow: Install CMake &amp; Git (if you haven't already) In a folder git vcpkg (git clone https://github.com/Microsoft/vcpkg.git) Install freetype and harfbuzz using vcpkg commandline bootstrap-vcpkg.bat vcpkg install freetype:x64-windows vcpkg install harfbuzz:x64-windows Locate vcpkg.cmake file and note down its path Ensure C++ build tools are installed in Visual Studio 19 Download and extract OpenCV &amp; OpenCV contrib Create a empty dir called "build" inside the extracted OpenCV (not OpenCV-contrib) Modify CMakeLists.txt inside freetype module folder in opencv-contrib (Link) Modify and run the following command: cmake -G "Visual Studio 16 2019" -B D:\code\downloads\opencv-4.3.0\build -D BUILD_NEW_PYTHON_SUPPORT=ON -D BUILD_PYTHON_SUPPORT=ON -D BUILD_opencv_python3=yes -D PYTHON_DEFAULT_EXECUTABLE=D:\anaconda3\python.exe -D OPENCV_SKIP_PYTHON_LOADER=ON -D PYTHON_LIBRARY=D:\anaconda3\libs\python36.lib -D OPENCV_EXTRA_MODULES_PATH=D:\code\downloads\opencv_contrib-4.3.0\modules -D OPEN_CV_FORCE_PYTHON_LIBS=yes -D CMAKE_TOOLCHAIN_FILE=D:\code\downloads\vcpkg\scripts\buildsystems\vcpkg.cmake Use CMake GUI to make changes referenced at this link (LINK) Once necessary changes are made, click Configure and Generate. Building DEBUG &amp; RELEASE versions using Visual Studio 19 Test the installation by importing cv2.freetype from the environment you setup. There's a comprehensive written guide over here: https://github.com/BabaGodPikin/Build-OpenCv-for-Python-with-Extra-Modules-Windows-10 Also, I've made a video inspired by the same tutorial, which can be found here: https://youtu.be/9YUDx3qzKwY I would recommend watching the video and keeping this guide open on the side. Cheers!

http://stackoverflow.com/q/47745944
accepted answer: http://stackoverflow.com/a/47746306
type: AnsweredQuestion
answer count: 2
has body: I've got a program that needs to take a text file as input and do a few things with each line of code. Before i can do anything with the text file though, i need to ensure that every line matches a specific format which in this case, would be city name (which could be any string, it wouldn't need to be a real city name) followed by a ',' followed by a number. a typical line would look like this: towna,2.43 This is what I have at the moment, it works in terms of making the program function but it doesn't verify that the data is correct, so if its wrong (and it will be from time to time) its going to give me an error. I read some stuff about re.match, but I don't understand how to use it. def read_file(fileName): weatherFile = open(fileName) for line in weatherFile: stripped = line.replace(' ','') pass #add data validation for file town, rain = stripped.split(",") if checkIfExists(town): dataList.append({"city":town, "average_rainfall":float(rain.rstrip())}) else: print("It looks like {0} is on the list twice. Please ensure all towns in {1} only appear once and try again." .format(town, fileName)) break
tagged with: validation
downvote count: 0
possible better answer: http://stackoverflow.com/a/47746150
score: 1
upvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47746306
tagged with: python
has title: Python - confirming string from text file matches format
has answer: http://stackoverflow.com/a/47746150

http://stackoverflow.com/comment/82520593
type: Comment
has text: Hmm, I'll read through that. I see they also have a version on CentOS which is the distro I'm running. Thanks for the lead.
comment on: http://stackoverflow.com/a/47779559
type: AnswerComment
score: 0

http://stackoverflow.com/q/47816876
upvote count: 2
type: UnansweredQuestion
tagged with: python
tagged with: kivy
score: 2
has body: I am using Kivy in an application where several widgets are used to modify/edit a set of data (the model). When some data is changed in one widget others need to be informed that something has changed so they can update their view. To do this I use Kivy Properties to mirror the model data, and this works fine. However the first time the Kivy Properties are set, when reading in the model data, this generates alot of unnecessary updates in the UI. I would like there to be a way to update a Kivy Property without generating update events. I have looked in the documentation (https://kivy.org/docs/api-kivy.properties.html) and in the code (https://github.com/kivy/kivy/blob/master/kivy/properties.pyx) but I have not been able to find anything to do this. How can this be solved? I have done a very simple example app to show how the code is organized and where the problem occurs. #! /usr/bin/env python import kivy from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.uix.listview import ListView from kivy.adapters.listadapter import ListAdapter from kivy.uix.listview import ListItemButton from kivy.properties import StringProperty from kivy.uix.label import Label from kivy.uix.textinput import TextInput from kivy.uix.button import Button model_data = ["Data1","Data2","Data3"] class TestApp(App): def build(self): tl = TestLayout() tl.read_data(model_data) return tl class TestLayout(BoxLayout): def __init__(self, **kwargs): super().__init__(**kwargs) self.test_list = TestList() self.test_edit = TestEdit() self.add_widget(self.test_list) self.add_widget(self.test_edit) self.test_list.adapter = ListAdapter(data=[], cls=ListItemButton, selection_mode='single') self.test_list.adapter.bind(selection=self.select_data) self.test_edit.bind(data=self.update_list) def read_data(self, data_list): self.test_list.init_list(data_list) def select_data(self, list_adapter, selection): if len(selection) &gt; 0: data = selection[0].text self.test_edit.init_data(data) def up…
has title: Prevent unnecessary event from Kivy Properties
downvote count: 0
has comment: http://stackoverflow.com/comment/82677976
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82611023
answer count: 0

http://stackoverflow.com/comment/82641079
has text: You need `if request.method == "POST"` inside your definition, then put your form validation there. At the end it should be `return redirect(url_for('students'))`
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47838575
score: 0

http://stackoverflow.com/q/47719146
tagged with: exception
accepted answer: http://stackoverflow.com/a/47719288
has body: My purpose with this program is to take input from student and make sure that he/she typed 3 digit number. Neither less than 3 or greater than 3 and it shouldnt be string. All this above if something wrong, program should ask again until its become true def studentID(): try: number=int(input("sutedent IDS:")) try: assert len(number)==3 except AssertionError: print("Must be 3 digit number.") studentID() except ValueError: print("Please enter an integer.") studentID() except TypeError: print("What is wrong with you?") studentID()
tagged with: python
type: AnsweredQuestion
score: 0
answer count: 2
tagged with: assertions
has answer: http://stackoverflow.com/a/47719288
has answer: http://stackoverflow.com/a/47719519
has title: Python 3.x A program thats control if some requirments true
possible better answer: http://stackoverflow.com/a/47719519
type: Question
tagged with: try-catch
tagged with: python-3.x

http://stackoverflow.com/a/47721540
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/82403716
type: Answer
has body: Writing a dynamic programming algorithm implies that you are already dealing with the recursive calls, so your current code is not dynamic programming yet. You need to identify what is causing the problem and then provide a solution which take less steps to compute your function in exchange of memory consumption, this is, storing function calls results to avoid a new calculation of the same call. I don't know all the details of your problem but it seems to have an optimal substructure property. You will find a guide on how to tell what kind of problem you are dealing with and how to solve it here
accepted answer of: http://stackoverflow.com/q/47721083
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47721083
downvote count: 0

http://stackoverflow.com/a/47737836
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/47735684
has comment: http://stackoverflow.com/comment/82437654
type: Answer
has body: Short answer: go with subprocess module Any flavor from subprocess should be used depending on what you need (input, output, pipes), but os.system and os.popen are definetly to be replaced and shouldn't be used anymore. subprocess.check_output is a wrapper around subprocess.Popenas the other sibling commands subprocess.call and check_call and only returns the output of the command, but doesn't manage any communication. subprocess.Popen is the base method and it used to do more sophisticated process communication like One-Way/Bidirectional and PIPE redirecting. shell_command is a package that eases shell interaction and it is based on subprocess.Popen. If you are not doing a lot of system admin work, no need to use it. So, how do you choose which subprocess call you need? 1) No need for shell interaction, just Fire and Forget? subprocess.call is the direct replacement of os.system and os.call. You call it and don't care about the output. The command line arguments are passed as a list of strings or a single string (shell=True mode only), which free's you from the burden of escaping quotes or special characters. Example: subprocess.call(['ls', '-l']) The return value is the exit code of the application itself, if you want to know if the external command crashed/succeed or any other exit command, you have to handle it yourself. 1a) You need automatic Error Handling If you want python to deal with the error handling, a convenient function subprocess.check_call is available, which is the same as subprocess.call but it raises a CalledProcessError exception if the process returns any other error value than 0. try: subprocess.check_call(['false']) except subprocess.CalledProcessError as err: print 'Error:', err 2) Interested in the output of the external command? subprocess.call and subprocess.check_call are bound to the output of the parent's programm, so they cannot capture the output of the command. subprocess.check_output is the command that captures the output of the c…

http://stackoverflow.com/comment/82389274
comment on: http://stackoverflow.com/q/47709918
type: Comment
type: QuestionComment
score: 0
has text: What error are you getting in cx_Freeze?

http://stackoverflow.com/comment/82383436
score: 0
comment on: http://stackoverflow.com/q/47699872
type: Comment
type: QuestionComment
has text: There may be many error. eg: header_row = get_headers() should be header_row = test_sheet .get_headers()? Can you give me a paste of your whole code?

http://stackoverflow.com/q/47778162
has comment: http://stackoverflow.com/comment/82518849
type: AnsweredQuestion
upvote count: 3
has title: Python/Numpy have I already written the swiftest code for large array?
has body: GOAL: I have a large 1d array (3000000+) of distances with many duplicate distances. I am trying to write the swiftest function that returns all distances that appear n times in the array. I have written a function in numpy but there is a bottleneck at one line in the code. Swift performance is an issue because the calculations are done in a for loop for 2400 different large distance arrays. import numpy as np for t in range(0, 2400): a=np.random.randint(1000000000, 5000000000, 3000000) b=np.bincount(a,minlength=np.size(a)) c=np.where(b == 3)[0] #SLOW STATEMENT/BOTTLENECK return c EXPECTED RESULTS: Given a 1d array of distances [2000000000,3005670000,2000000000,12345667,4000789000,12345687,12345667,2000000000,12345667] I would expect back an array of [2000000000,12345667] when queried to return an array of all distances that appear 3 times in the main array. What should I do?
score: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/82518877
has comment: http://stackoverflow.com/comment/82517688
accepted answer: http://stackoverflow.com/a/47778457
has comment: http://stackoverflow.com/comment/82517747
has comment: http://stackoverflow.com/comment/82637228
possible better answer: http://stackoverflow.com/a/47778504
linked to: http://stackoverflow.com/q/12897374
favorite count: 0
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/47778504
answer count: 2
has answer: http://stackoverflow.com/a/47778457
tagged with: python
has comment: http://stackoverflow.com/comment/82517559

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

http://stackoverflow.com/q/47812785
upvote count: 10
has comment: http://stackoverflow.com/comment/82594405
tagged with: python
has answer: http://stackoverflow.com/a/65758095
answer count: 4
has answer: http://stackoverflow.com/a/54967005
possible better answer: http://stackoverflow.com/a/54967005
type: AnsweredQuestion
downvote count: 0
has title: Remove empty partitions in Dask
has answer: http://stackoverflow.com/a/50613803
has body: When loading data from CSV some CSVs cannot be loaded, resulting in an empty partition. I would like to remove all empty partitions, as some methods seem to not work well with empty partitions. I have tried to repartition, where (for example) repartition(npartitions=10) works, but a value greater than this can still result in empty partitions. What's the best way of achieving this? Thanks.
accepted answer: http://stackoverflow.com/a/50613803
has answer: http://stackoverflow.com/a/47816564
favorite count: 0
type: Question
tagged with: dask
score: 10

http://stackoverflow.com/comment/82634613
type: Comment
has text: Thank you, I only changed to list() and worked well.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47831614

http://stackoverflow.com/comment/82576717
comment on: http://stackoverflow.com/q/47807738
score: 1
type: QuestionComment
has text: you've typo in your code. `rec_abs` and `rek_abs`. then use `abs(el)` to append.
type: Comment

http://stackoverflow.com/a/60454915
upvote count: 1
has body: @Greg Holst, why so much duplication? Why not: class ZipCodeList(mixins.CreateModelMixin, generics.GenericAPIView): def post(self, request, format=None): serializer = ZipCodeSerializer(data=request.data, many=isinstance(request.data, list)) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Anyway, that only worked for me for creating new objects, didn't work to create-or-update in one sweep (it kept telling me these objects already exist), so this is what I did: class ContributorSyncListAPIView(ListAPIView): permission_classes = (isSuperUserPermission,) allowed_methods = ("GET", "PUT") lookup_field = "airtable_id" serializer_class = ContributorSyncSerializer # Doesn't get used in Put, just in Get. model = Contributor def get_queryset(self): return self.model.objects.all() def put(self, request, format=None): objects = list(request.data) # objects is a list of OrderedDicts try: for o in objects: try: instance = self.model.objects.get( **{self.lookup_field: o.get(self.lookup_field)} ) for key, value in o.items(): setattr(instance, key, value) except self.model.DoesNotExist: instance = self.model(**o) instance.save() return Response(objects, status=status.HTTP_200_OK) except Exception as e: return Response({"detail": str(e)}, status=status.HTTP_400_BAD_REQUEST) Note my code above is very light on validation just because it was for a process of syncing models from one environment to another by a superuser, different environments with an identical codebase; so the assumption was the data had already been validated when the data was entered into the first environment. For any other purpose you'd want to validate more. But this is what I had to do to handle a list of objects that may need to be created or updating, on an object-by-object basis.
type: Answer
answers question: http://stackoverflow.com/q/47809551
score: 1
downvote count: 0

http://stackoverflow.com/a/47774041
has body: Try this: context = { 'question': serializers.serialize('json', Question), 'answers' : serializers.serialize('json', answers) } return JsonResponse(context, safe=False)
answers question: http://stackoverflow.com/q/47773873
score: 0
type: Answer

http://stackoverflow.com/comment/82667283
has text: @Alexander not in Python 2.7 - it throws a SyntaxError - Update: it compiles in Python 3
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47851402
score: 0

http://stackoverflow.com/q/47729370
has comment: http://stackoverflow.com/comment/82419220
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/47729410
upvote count: 0
answer count: 3
tagged with: django
has title: How to convert from unicode list to normal list in python/django
has answer: http://stackoverflow.com/a/47729410
downvote count: 1
accepted answer: http://stackoverflow.com/a/47729480
favorite count: 0
has answer: http://stackoverflow.com/a/47729480
type: Question
has comment: http://stackoverflow.com/comment/82421754
has answer: http://stackoverflow.com/a/47729464
tagged with: python
has body: How can i convert this list: list = [u"[u'book1', u'book2', u'book3']"]into this list: to: [u'book1', u'book2', u'book3'] I tried this : n = ast.literal_eval(list) but i got this error: ValueError: malformed string what else can i do to change this list without "u"?
has comment: http://stackoverflow.com/comment/82419283
score: -1

http://stackoverflow.com/comment/82547777
comment on: http://stackoverflow.com/q/47790088
score: 0
type: Comment
type: QuestionComment
has text: `data['net_booking_value_monthly']` and `data['net_booking_value_monthly'].value_counts(dropna=False)‌​` will have different indexes, the latter not necessarily monotonic. I'm not sure exactly what's causing the error though. If `v = data['net_booking_value_monthly'].value_counts(dropna=False)‌​` what is the output of `len(v)` and `v.index.dtype`?

http://stackoverflow.com/a/47839602
has comment: http://stackoverflow.com/comment/82643354
type: Answer
has body: I was able to solve it without creating a udf , I did refer to a similar post (pyspark substring and aggregation) on stack and it just worked perfectly. from pyspark.sql.functions import * format = 'mmddyy' col = unix_timestamp(df1['DATE_OPENED'], format).cast('timestamp') df1 = df1.withColumn("DATE_OPENED", col) df2 = df.withColumn('open_dt', df['DATE_OPENED'].substr(1, 11))
score: 5
downvote count: 0
answers question: http://stackoverflow.com/q/47801317
upvote count: 5

http://stackoverflow.com/q/47736951
favorite count: 0
type: Question
has body: I am new to tensorflow . I need to load the dataset to train my model . And sample of my dataset looks like TRAINING_FILE.iloc[0:5,0:5] num_var_1 num_var_2 num_var_3 num_var_4 num_var_5 0 -0.010655 0.040182 0.0 1.800000e-07 -0.011319 1 -0.006542 0.157872 0.0 2.105000e-06 -0.010966 2 -0.010626 0.089140 0.0 3.550000e-07 -0.011286 3 -0.010626 0.227239 0.0 1.050000e-06 -0.011159 4 -0.008947 0.160410 0.0 2.105000e-06 -0.010966 I Load this csv file with mentioned code in tensorflow documentation .This is how i loaded my training file train_fn = tf.contrib.learn.datasets.base.load_csv_with_header( filename = TRAINING_FILE, target_dtype = np.int, features_dtype= np.float32) and when i compile the script i got the following error Traceback (most recent call last): File "train.py", line 31, in features_dtype = np.float32) File "/usr/local/lib/python2.7/dist-packages/tensorflow/contrib/learn/python/learn/datasets/base.py", line 48, in load_csv_with_header n_samples = int(header[0]) ValueError: invalid literal for int() with base 10: '-0.0106550312'
upvote count: 2
type: UnansweredQuestion
has title: tensorflow : load csv data file and training the model
tagged with: python
score: 2
has answer: http://stackoverflow.com/a/47761890
downvote count: 0
answer count: 1
tagged with: tensorflow

http://stackoverflow.com/comment/82411159
has text: Hey, @zainy, still having troubles with Stuart's answer? He edited it to address your other problem, too.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47718160

http://stackoverflow.com/comment/82634689
has text: Ok. I did a while statement that does something before breaking, which works for now. I was trying the following before: `clean_list = list(map(lambda s: s.strip(), concept['name']))`, `if any(word == keyword for word in concept['name']):`, `print(True)`, `else:`, `print(False)`.
type: AnswerComment
comment on: http://stackoverflow.com/a/47835175
score: 1
type: Comment

http://stackoverflow.com/comment/139273120
comment on: http://stackoverflow.com/a/47817864
has text: @Llamageddon The reason it's in a separate file is so that it can be saved and loaded as needed, but if you're ok with copying and pasting this code into the interpreter everytime, you can do it that way.
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47746772
score: 0
has comment: http://stackoverflow.com/comment/82463894
answer count: 0
has title: SSD. Image recovering (frame t-1 and t). Python
has comment: http://stackoverflow.com/comment/82461830
tagged with: image-processing
type: Question
type: UnansweredQuestion
tagged with: python
has body: I try to recover an previous frame (t-1) from current (t). This code is working but get bad quality. I can't find the error =( May be someone have any ideas? frames: import random import numpy as np import cv2 def get_ssd(first_block, second_block): return np.sum((first_block[:, :] - second_block[:, :]) ** 2) def get_sad(first_block, second_block): return np.sum(abs((first_block[:, :] - second_block[:, :]))) def sliding_block(image, block_size, step): for w in range(0, image.shape[0], step): if w + block_size[0] &gt; image.shape[0]: w = image.shape[0] - block_size[0] for h in range(0, image.shape[1], step): if h + block_size[1] &gt; image.shape[1]: h = image.shape[1] - block_size[1] yield (w, h, image[w:w + block_size[0], h:h + block_size[1]]) def replace_block(a, b, c, position_x, position_y): a[position_x:position_x + BLOCK_SIZE[0], position_y:position_y + BLOCK_SIZE[1]] += b[0:0 + BLOCK_SIZE[0], 0:0 + BLOCK_SIZE[1]] c[position_x:position_x + BLOCK_SIZE[0], position_y:position_y + BLOCK_SIZE[1]] += 1 def search_window(image, x, y, size): if x - size &lt; 0: width_s = 0 width_e = x + size elif x + size &gt; image.shape[0]: width_s = x - size width_e = image.shape[0] else: width_s = x - size width_e = x + size if y - size &lt; 0: height_s = 0 height_e = y + size elif y + size &gt; image.shape[1]: height_s = y - size height_e = image.shape[1] else: height_s = y - size height_e = y + size return width_s, height_s, image[width_s:width_e, height_s:height_e] t_1 = cv2.imread("frame20.jpg", 0) t = cv2.imread("frame21.jpg", 0) t_rec = t_1.copy() t_acc = t_1.copy() t_vec = t_1.copy() t_rec2 = t_1.copy() t_rec2.fill(0) t_vec.fill(255) t_acc.fill(0) t_rec.fill(0) block_memory = [] BLOCK_SIZE = [10, 10] STEP_SIZE = 10 for (x, y, im_block) in sliding_block(t_1, BLOCK_SIZE, STEP_SIZE): sad = 99999 (x_start, y_start, im_window) = search_window(t, x, y, 30) for width in range(0, im_window.shape[0] - BLOCK_SIZE[0]): for height in range(0, im_window.shape[1] - BLOCK_SIZE[1]): sad_ne…
tagged with: frames
tagged with: opencv

http://stackoverflow.com/comment/82445984
comment on: http://stackoverflow.com/q/47742823
score: 0
type: QuestionComment
type: Comment
has text: Done. Check now

http://stackoverflow.com/comment/82395622
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47716953
has text: You left out the possibility that the largest digit is zero, as in the number `0`.
type: Comment

http://stackoverflow.com/a/47727666
answers question: http://stackoverflow.com/q/47726528
score: 5
upvote count: 5
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/82432229
has body: XLA is still very new : it was released on March 2017. As stated of the Tensorflow XLA page : Note: XLA is experimental and considered alpha. Most use cases will not see improvements in performance (speed or decreased memory usage). We have released XLA early so the Open Source Community can contribute to its development, as well as create a path for integration with hardware accelerators. If it was released, it is because the development team wants the feedback and the contributions of the Open Source community to the project. This is backed up by this statement on the Google Developpers Blog : XLA is still in early stages of development. It is showing very promising results for some use cases, and it is clear that TensorFlow can benefit even more from this technology in the future. We decided to release XLA to TensorFlow Github early to solicit contributions from the community and to provide a convenient surface for optimizing TensorFlow for various computing devices, as well as retargeting the TensorFlow runtime and models to run on new kinds of hardware. So why is it considered experimental ? Simply because there's a lot of use case and hardware that have not been tested. The benchmarks don't always show the expected improvements. It's possible that you encounter some bugs while using it, and you are encouraged to signal them via the github issue page of the project.

http://stackoverflow.com/a/47811558
has comment: http://stackoverflow.com/comment/82584903
answers question: http://stackoverflow.com/q/47810814
type: Answer
has comment: http://stackoverflow.com/comment/83304360
has body: Basically the encryption that you are trying is known as Caesar Cipher You can try: data = "ABCD" shift = 1 encypted_data_array = [] def krypt(): for i in data: new = chr(ord(i) + shift) encypted_data_array.append(new) print "".join(encypted_data_array)
downvote count: 0
has comment: http://stackoverflow.com/comment/82584847
has comment: http://stackoverflow.com/comment/82601795
upvote count: 1
score: 1

http://stackoverflow.com/q/47776622
tagged with: pandas
score: 1
answer count: 1
downvote count: 0
has title: Python,using dataframes how to split the value of a string in a column and then add a new column with the value from the split
favorite count: 0
type: Question
has body: Ok. That title is terrible but let's try with an example. Let us imagine we have soemthing like this: c1 c2 column1-x 2 column1-y 3 column2-x 5 column3 6 And i would want it to end up like this: c1 c2 c3 column1-x 2 column1 column1-y 3 column1 column2-x 5 column2 column3 6 column3 As you probably guessed this is an attempt on rejoining the value importance after one-hot encoding after this I will make the sum of all values with the same value in c3, but for that i need to be able to check the value in c1 before the "-" to add that third column c3.
upvote count: 1
tagged with: dataframe
tagged with: python
accepted answer: http://stackoverflow.com/a/47776661
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47776661

http://stackoverflow.com/comment/82416951
has text: Why are you modifying `x`? Besides, inserting at position zero is relatively expensive, since all subsequent list items have to be moved up to make room, which is an O(n) operation, and although it happens at C speed it's better to avoid it if it's not necessary.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47728202
type: AnswerComment

http://stackoverflow.com/a/47833934
upvote count: 2
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: k - [4, 8] Demo: &gt;&gt;&gt; &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; k = np.array([[13, 29], [17, 18], [19, 27]]) &gt;&gt;&gt; k - [4, 8] array([[ 9, 21], [13, 10], [15, 19]])
score: 2
accepted answer of: http://stackoverflow.com/q/47833749
answers question: http://stackoverflow.com/q/47833749

http://stackoverflow.com/q/47844864
tagged with: z-axis
tagged with: python
has answer: http://stackoverflow.com/a/47845355
has title: Matplotlib append to z axis
accepted answer: http://stackoverflow.com/a/47845355
type: AnsweredQuestion
score: 0
has body: I want to plot in 3D using matplotlib (python), which data is added in real time(x,y,z). In the below code, data appends on x-axis and y-axis successfully, but on z-axis I've encountered problems.although I've searched in matplotlib's docs, I could not find any solutions. what should be added/changed to this code to make it append data in z-axis? what works correctly: return plt.plot(x, y, color='g') problem: return plt.plot(x, y, z, color='g') Code: from mpl_toolkits.mplot3d import axes3d import matplotlib.pyplot as plt import numpy as np import matplotlib.animation as animation import random np.set_printoptions(threshold=np.inf) fig = plt.figure() ax1 = fig.add_subplot(111, projection='3d') x = [] y = [] z = [] def animate(i): x.append(random.randint(0,5)) y.append(random.randint(0,5)) z.append(random.randint(0,5)) return plt.plot(x, y, color='g') #return plt.plot(x, y, z, color='g') =&gt; error ani = animation.FuncAnimation(fig, animate, interval=1000) ax1.set_xlabel('x') ax1.set_ylabel('y') ax1.set_zlabel('z') plt.show() How to get this done correctly?
tagged with: matplotlib
answer count: 1
type: Question
tagged with: 3d

http://stackoverflow.com/q/47845229
has comment: http://stackoverflow.com/comment/82697056
has comment: http://stackoverflow.com/comment/82701841
score: 1
favorite count: 0
type: Question
answer count: 0
type: UnansweredQuestion
downvote count: 0
has title: Yocto Toaster won't build image
has comment: http://stackoverflow.com/comment/82696608
tagged with: yocto
upvote count: 1
tagged with: python
has body: I can't make Yocto Toaster make any image. When I try to build using bitbake, everything work as expected. Toaster als start without any warning or errors, but when I start build I always receive error: Error executing a python function in &lt;code&gt;: The stack trace of python calls that resulted in this exception/failure was: File: '&lt;code&gt;', lineno: 4, function: &lt;module&gt; 0001:__anon_22__home_gpufler_poky__toaster_clones__git___git_yoctoproject_org_poky_master_meta_conf_machine_include_arm_feature_arm_thumb_inc(d) 0002:__anon_25__home_gpufler_poky__toaster_clones__git___git_yoctoproject_org_poky_master_meta_classes_patch_bbclass(d) 0003:__anon_160__home_gpufler_poky__toaster_clones__git___git_yoctoproject_org_poky_master_meta_classes_base_bbclass(d) *** 0004:__anon_686__home_gpufler_poky__toaster_clones__git___git_yoctoproject_org_poky_master_meta_classes_base_bbclass(d) 0005:__anon_1312__home_gpufler_poky__toaster_clones__git___git_yoctoproject_org_poky_master_meta_classes_insane_bbclass(d) 0006:__anon_250__home_gpufler_poky__toaster_clones__git___git_yoctoproject_org_poky_master_meta_classes_package_bbclass(d) 0007:__anon_707__home_gpufler_poky__toaster_clones__git___git_yoctoproject_org_poky_master_meta_classes_package_rpm_bbclass(d) 0008:__anon_25__home_gpufler_poky__toaster_clones__git___git_yoctoproject_org_poky_master_meta_classes_debian_bbclass(d) File: '/home/gpufler/poky/_toaster_clones/_git___git.yoctoproject.org_poky_master/meta/classes/base.bbclass', lineno: 587, function: __anon_686__home_gpufler_poky__toaster_clones__git___git_yoctoproject_org_poky_master_meta_classes_base_bbclass 0583: needsrcrev = False 0584: srcuri = d.getVar('SRC_URI') 0585: for uri in srcuri.split(): 0586: (scheme, _ , path) = bb.fetch.decodeurl(uri)[:3] *** 0587: 0588: # HTTP/FTP use the wget fetcher 0589: if scheme in ("http", "https", "ftp"): 0590: d.appendVarFlag('do_fetch', 'depends', ' wget-native:do_populate_sysroot') 0591: File: '/home/gpufler/poky/_toaster_…
has comment: http://stackoverflow.com/comment/82692399

http://stackoverflow.com/a/47724504
score: 2
upvote count: 2
downvote count: 0
type: AcceptedAnswer
has body: The Python Standard Library itertools already has the functionality you are trying to implement. Also you are using it in your code (funnily). itertools.combinations(a,3) returns all 3-combinations of the a. To convert that to "list of list" you should use .extend() as follows; x = ['a','b','c','d','e'] n = 3 import itertools permutations = [] combinations = [] combinations.extend(itertools.combinations(x,n)) permutations.extend(itertools.permutations(x,n)) print("Permutations;", permutations) print("\n") print("Combinations;", combinations) Additionally, I suggest you to search on "Combination, Permutation Difference". As I understood from your question; permutation is what you want. (If you run the code I shared, you will understand the difference easliy.)
answers question: http://stackoverflow.com/q/47724459
type: Answer
accepted answer of: http://stackoverflow.com/q/47724459

http://stackoverflow.com/comment/82564924
score: 0
type: Comment
has text: I just used `df1.iloc[:,:]/df1.iloc[0,:].sum()` and i think it works
comment on: http://stackoverflow.com/a/47796697
type: AnswerComment

http://stackoverflow.com/comment/82656406
has text: It depends on the input shape and layers you are using in the neural network.
comment on: http://stackoverflow.com/a/47845537
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/47702646
type: Answer
has body: Since you're not using a ModelForm, you need to define the fields. And you can get rid of the model = Status declaration. Try this: from django import forms class CreatePost(forms.Form): title = forms.CharField() username = forms.CharField() class meta: fields = ("title","username" ) Since it's not a ModelForm, the form has no idea what fields there are in the Status model. And it has no way to instantiate the fields (since they are not defined). I think you probably want to use a ModelForm though, unless there's some compelling reason not to.
score: 1
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47702309

http://stackoverflow.com/comment/82376849
has text: @3P3 This is really the only easy way to do this. Do you really have to have `col1`, `col2` and `col3` ordered?
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47708322
type: Comment

http://stackoverflow.com/comment/82453934
type: QuestionComment
comment on: http://stackoverflow.com/q/47736531
type: Comment
score: 0
has text: You could also try e_dist and just leave out the sqrt section towards the bottom. this einsum approach can be used in a variety of situations as a substitute for scipy cdist and pdist etc. https://stackoverflow.com/questions/42660459/how-do-i-find-the-distances-between-two-points-from-different-numpy-arrays/42662151#42662151

http://stackoverflow.com/a/62740970
has body: A bit late, but I recently had this issue, or at least the same error report. When you get something like: turicreate.toolkits._main.ToolkitError: Annotations column must contain lists try annotations.column_types() or data.column_types() you will most likely see something like str, image, str instead of the desired str, image, list and the issue will be a string malformed so that the Python parser barfs. In my case the defect was simply an extra space after the closing square bracket on each line. Fix it, re run column_types to verify list processed correctly, and move forward to the next roadblock!
score: 0
answers question: http://stackoverflow.com/q/47795909
type: Answer

http://stackoverflow.com/a/47778970
score: 27
upvote count: 27
has comment: http://stackoverflow.com/comment/123052265
has comment: http://stackoverflow.com/comment/103795909
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47778889
has comment: http://stackoverflow.com/comment/82523967
accepted answer of: http://stackoverflow.com/q/47778889
has comment: http://stackoverflow.com/comment/123058870
has body: is checks that the left hand argument holds the exact same reference as the right hand argument. This is fine for None which is a singleton, but is usually a bad idea for other types, where multiple instances can have the same logical value. Consider, e.g. the following example: &gt;&gt;&gt; my_string = ''.join([c for c in 'xfje']) &gt;&gt;&gt; print my_string xfje &gt;&gt;&gt; print my_string == 'xfje' True &gt;&gt;&gt; print my_string is 'xfje' False
type: Answer
has comment: http://stackoverflow.com/comment/82521242

http://stackoverflow.com/comment/82869756
comment on: http://stackoverflow.com/a/47949392
type: AnswerComment
score: 0
type: Comment
has text: The code is not counting correctly assuming this is taken out. I may have to re-write it from scratch.

http://stackoverflow.com/a/47881690
answers question: http://stackoverflow.com/q/47854282
has body: There is no multi-table functionality. How implement LEFT or RIGHT JOIN using spark-cassandra-connector You can add relational layers onto Cassandra. How to do a join queries with 2 or more tables in cassandra cql You can fruitlessly search the manual. http://cassandra.apache.org/doc/latest/cql/dml.html Re browsing/googling: Other SQL ways to do what you want are EXCEPTaka MINUS &amp; NOT IN. Algebraic functionality is DIFFERENCE aka MINUS &amp; ANTIJOIN).
type: Answer
score: 2
upvote count: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47854282
type: AcceptedAnswer

http://stackoverflow.com/a/47779267
type: Answer
score: 7
has comment: http://stackoverflow.com/comment/133157569
has body: As it turns out this problem was unrelated to sqlacodegen. All the tables in my database are prefixed with dbname. Passing in --schema dbname works.
answers question: http://stackoverflow.com/q/47775177
type: AcceptedAnswer
downvote count: 0
upvote count: 7
accepted answer of: http://stackoverflow.com/q/47775177

http://stackoverflow.com/comment/82423798
comment on: http://stackoverflow.com/q/47731543
type: Comment
type: QuestionComment
score: 0
has text: use [ontimer()](https://docs.python.org/3.6/library/turtle.html#turtle.ontimer) to execute function in intervals - and you will no need `sleep` (ontimer use time in milliseconds 0.5s = 500ms)

http://stackoverflow.com/a/47722345
answers question: http://stackoverflow.com/q/47722263
has body: I'd pick out just a list of the keys and a list of the values separately by unzipping: keys, vals = zip(*pairs) Then I'd count the number of each unique value with numpy: unique, counts = np.unique(vals, return_counts=True) And the value you want is the one with the smallest counts: myminval = unique[np.argmin(counts)] Then you find this value in your list of keys: keys[vals.index(myminval)]
type: Answer
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/a/47731451
type: Answer
score: 4
upvote count: 4
has body: var arry = [{ "parentId": null, "moduleId": 1 }, { "parentId": 1, "moduleId": 2 }, { "parentId": 1, "moduleId": 3 }, { "parentId": null, "moduleId": 4 }, { "parentId": null, "moduleId": 5 }, { "parentId": 3, "moduleId": 6 } ]; function convert(array){ var map = {}; for(var i = 0; i &lt; array.length; i++){ var obj = array[i]; obj.children= []; map[obj.moduleId] = obj; var parent = obj.parentId || '-'; if(!map[parent]){ map[parent] = { children: [] }; } map[parent].children.push(obj); } return map['-'].children; } var r = convert(arry) console.log('array', r); console.log('result', JSON.stringify(r))
downvote count: 0
answers question: http://stackoverflow.com/q/47728841

routes
type: Tag
tags question: http://stackoverflow.com/q/47763794
tag name: routes

http://stackoverflow.com/comment/82523527
has text: @DiogoDaniel Happy to help :). Hopefully cleared some stuff up for ya there. Good luck on the rest of your project!
comment on: http://stackoverflow.com/a/47780832
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47784467
accepted answer: http://stackoverflow.com/a/47809126
has body: What do h2o checkpoints actually do? Does a model created with say gbm_continued = H2OGradientBoostingEstimator(checkpoint= gbm_orig.model_id, ntrees = 50, seed = 1234) mean that gbm_continued will have the same parameters and prediction performance as gbm_orig if we were to not train it on any new data? The docs, say "This will build a new model as a continuation of a previously generated model", but I am confused as to what a "continuation" actually implies. An explanation would be much appreciated. Thanks
type: AnsweredQuestion
tagged with: h2o
score: 1
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/44341557
has answer: http://stackoverflow.com/a/47809126
has title: What do h2o checkpoints really do?
tagged with: python

http://stackoverflow.com/comment/82533764
score: 0
type: Comment
has text: I think you should post another question, something like "How can I accelerate an object?". And add a short description of your goals and a code example to show us what you've tried.
comment on: http://stackoverflow.com/a/47764753
type: AnswerComment

http://stackoverflow.com/comment/82543835
has text: It is Oracle Linux. yeah it is installed
comment on: http://stackoverflow.com/q/47769191
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47730966
has answer: http://stackoverflow.com/a/47735086
type: AnsweredQuestion
score: 3
has body: I'm using Spyder 3.2.4 (Python 3.6). Spyder doesn't detect changes in imported python files. For example: test2.py: def func(): return 5 test1.py: import test2 a = test2.func() print(a) When I wrote those classes, and saved them (in the same working directory), and ran test1.py the output was 5. BUT when I change the function in test2.py, to like: def func(): return 10 Save it, and then run python1.py, I still get 5. Only when I save, exit the IDE, and return, I will get the changed code (10). This behavior is going on since I started using Spyder (few months by now), and it's super annoying. Help would be appreciated.
accepted answer: http://stackoverflow.com/a/47731570
upvote count: 3
has answer: http://stackoverflow.com/a/47731570
tagged with: spyder
has comment: http://stackoverflow.com/comment/82423422
tagged with: import
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82423183
has comment: http://stackoverflow.com/comment/82423097
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/82422960
tagged with: ide
has title: Spyder doesn't detect changes in imported python files
possible better answer: http://stackoverflow.com/a/47735086
tagged with: python

http://stackoverflow.com/q/47778117
downvote count: 0
linked to: http://stackoverflow.com/q/47755704
possible better answer: http://stackoverflow.com/a/47778502
tagged with: scipy
score: 8
favorite count: 0
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/47778502
upvote count: 8
has answer: http://stackoverflow.com/a/47779290
has comment: http://stackoverflow.com/comment/82517912
tagged with: python
has title: Find minimum distances between groups of points in 2D (fast and not too memory consuming)
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47779290
answer count: 2
has comment: http://stackoverflow.com/comment/82517447
tagged with: euclidean-distance
has body: I have two sets of points in 2D A and B and I need to find the minimum distance for each point in A, to a point in B. So far I've been using SciPy's cdist with the code below import numpy as np from scipy.spatial.distance import cdist def ABdist(A, B): # Distance to all points in B, for each point in A. dist = cdist(A, B, 'euclidean') # Indexes to minimum distances. min_dist_idx = np.argmin(dist, axis=1) # Store only the minimum distances for each point in A, to a point in B. min_dists = [dist[i][md_idx] for i, md_idx in enumerate(min_dist_idx)] return min_dist_idx, min_dists N = 10000 A = np.random.uniform(0., 5000., (N, 2)) B = np.random.uniform(0., 5000., (N, 2)) min_dist_idx, min_dists = ABdist(A, B) which works just fine for smallish values of N. But now the lengths of the sets have increased from N=10000 to N=35000 and I'm running into a dm = np.zeros((mA, mB), dtype=np.double) MemoryError I know I can replace cdist with a for loop that keeps only the minimum distance (and the index) for each point in A to each point in B, as that is all I need. I don't need the full AxB distance matrix. But I've been using cdist precisely because it is fast. Is there a way to replace cdist with an implementation that is (almost?) as fast, but that does not take that much memory?

http://stackoverflow.com/q/47784668
type: Question
type: AnsweredQuestion
score: 0
has body: I'm trying to loop through JSON data to find values for specific keys. My data is coming from a http request and the data looks like: {'1': {'manufacturername': 'SVLJ', 'modelid': 'TCL014', 'name': 'Fling'}, '10': {'manufacturername': 'SONY', 'modelid': 'BLL4554', 'name': 'ACQ'}} My current goal is to loop through each item number (1, 10, etc..) and get the value for light ('fling', 'acq', etc..). My latest attempt is: import requests RESOURCE_URL = 'xxx/xxx/' def get_json(url): raw_response = requests.get(url) data = raw_response.json() return data def get_SMR(): url = "{}SMR/".format(RESOURCE_URL) return get_json(url) smr_json = get_SMR() for SMR in smr_json: print(SMR['name']) When I try running this, I get the error: TypeError: string indices must be integers I've also tried importing the json library, and using json.loads(raw_response.text); however, it's still being recognized as a string, rather than an iterable json object (that can be referenced by key). Any and all insight would be greatly appreciated.
answer count: 3
tagged with: http://stackoverflow.com/tag/json
has answer: http://stackoverflow.com/a/47784826
possible better answer: http://stackoverflow.com/a/47784710
tagged with: python
has title: Unable to iterate through JSON data
has answer: http://stackoverflow.com/a/47784710
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/47784692
has answer: http://stackoverflow.com/a/47784692
tagged with: python-requests

http://stackoverflow.com/q/47800626
has body: Can I get some advice on writing a unit test for the following piece of code? %python import sys import json sys.argv = [] sys.argv.append('{"product1":{"brand":"x","type":"y"}}') sys.argv.append('{"product1":{"brand":"z","type":"a"}}') products = sys.argv yy= {} my_products = [] for n, i in enumerate(products[:]): xx = json.loads(i) for j in xx.keys(): yy["brand"] = xx[j]['brand'] yy["type"] = xx[j]["type"] my_products.append(yy) print my_products
answer count: 1
tagged with: unit-testing
type: Question
has comment: http://stackoverflow.com/comment/82563325
has comment: http://stackoverflow.com/comment/82563520
has comment: http://stackoverflow.com/comment/82565812
accepted answer: http://stackoverflow.com/a/47801249
has comment: http://stackoverflow.com/comment/82563579
tagged with: python
has answer: http://stackoverflow.com/a/47801249
has title: Python unit test advice
type: AnsweredQuestion
score: 0

http://stackoverflow.com/a/47836618
has body: We can using idxmax df.DATE[df.TX.idxmax()] Out[346]: 19010103 For enhance the speed df.values[2,df.TX.values.argmax()]
downvote count: 0
has comment: http://stackoverflow.com/comment/82636894
has comment: http://stackoverflow.com/comment/82638750
has comment: http://stackoverflow.com/comment/82639331
has comment: http://stackoverflow.com/comment/82638712
has comment: http://stackoverflow.com/comment/82637878
score: 5
has comment: http://stackoverflow.com/comment/82637692
has comment: http://stackoverflow.com/comment/82637925
has comment: http://stackoverflow.com/comment/82638765
answers question: http://stackoverflow.com/q/47836499
upvote count: 5
has comment: http://stackoverflow.com/comment/82639412
type: Answer
has comment: http://stackoverflow.com/comment/82637790
has comment: http://stackoverflow.com/comment/82637989
has comment: http://stackoverflow.com/comment/82637668

http://stackoverflow.com/comment/82430248
comment on: http://stackoverflow.com/a/47734798
has text: Heh yep it does. But the `student_data_dict` values are strings and their first index is 0. I have another problem though, answer order is getting mixed up. any thoughts ? or is it just my print that is out of order ?
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/a/47748262
score: 7
type: Answer
has comment: http://stackoverflow.com/comment/95015939
answers question: http://stackoverflow.com/q/47745989
downvote count: 0
has comment: http://stackoverflow.com/comment/82457133
upvote count: 7
type: AcceptedAnswer
has body: Your solution will work, however I see problem with it. async def main(): asyncio.ensure_future(main()) # task finishing As soon as main started it creates new task and it happens immediately (ensure_future creates task immediately) unlike actual finishing of this task that takes time. I guess it can potentially lead to creating enormous amount of tasks which can drain your RAM. Besides that it means that potentially any enormous amount of tasks can be ran concurrently. It can drain your network throughput or amount of sockets that can be opened same time (just imagine you're tying to download 1 000 000 urls parallely - nothing good will happen). In concurrent world this problem usually can be solved by limiting amount of things that can be ran concurrently with some sensible value using something like Semaphore. In your case however I think it's more convenient to track amount of running tasks manually and populate it manually: import asyncio from random import randint async def get_message(): message = randint(0, 1_000) print(f'{message} got') return message async def process_message(message): await asyncio.sleep(randint(1, 5)) print(f'{message} processed') return message async def deal_with_message(message): await asyncio.sleep(randint(1, 5)) print(f'{message} dealt') async def utilize_message(): message = await get_message() message = await process_message(message) await deal_with_message(message) parallel_max = 5 # don't utilize more than 5 msgs parallely parallel_now = 0 def populate_tasks(): global parallel_now for _ in range(parallel_max - parallel_now): parallel_now += 1 task = asyncio.ensure_future(utilize_message()) task.add_done_callback(on_utilized) def on_utilized(_): global parallel_now parallel_now -= 1 populate_tasks() if __name__ == '__main__': loop = asyncio.get_event_loop() try: populate_tasks() loop.run_forever() finally: loop.run_until_complete(loop.shutdown_asyncgens()) loop.close() Output will be like: 939 got 816 got 737 got 257 got 528 got …
accepted answer of: http://stackoverflow.com/q/47745989
has comment: http://stackoverflow.com/comment/82461682

http://stackoverflow.com/q/47826706
upvote count: 3
answer count: 2
downvote count: 0
has body: 2 layers MLP (Relu) + Softmax After 20 iterations, Tensor Flow just gives up and stops updating any weights or biases. I initially thought that my ReLu where dying, so I displayed histograms to make sure none of them where 0. And none of them are ! They just stop changing after few iterations and cross entropy is still high. ReLu, Sigmoid and tanh gives the same results. Tweaking GradientDescentOptimizer from 0.01 to 0.5 also doesn't change much. There has to be a bug somewhere. Like an actual bug in my code. I can't even overfit a small sample set ! Here are my histograms and here's my code, if anyone could check it out, that would be a major help. We have 3000 scalars with 6 values between 0 and 255 to classify in two classes : [1,0] or [0,1] (I made sure to randomise the order) def nn_layer(input_tensor, input_dim, output_dim, layer_name, act=tf.nn.relu): with tf.name_scope(layer_name): weights = tf.Variable(tf.truncated_normal([input_dim, output_dim], stddev=1.0 / math.sqrt(float(6)))) tf.summary.histogram('weights', weights) biases = tf.Variable(tf.constant(0.4, shape=[output_dim])) tf.summary.histogram('biases', biases) preactivate = tf.matmul(input_tensor, weights) + biases tf.summary.histogram('pre_activations', preactivate) #act=tf.nn.relu activations = act(preactivate, name='activation') tf.summary.histogram('activations', activations) return activations #We have 3000 scalars with 6 values between 0 and 255 to classify in two classes x = tf.placeholder(tf.float32, [None, 6]) y = tf.placeholder(tf.float32, [None, 2]) #After normalisation, input is between 0 and 1 normalised = tf.scalar_mul(1/255,x) #Two layers hidden1 = nn_layer(normalised, 6, 4, "hidden1") hidden2 = nn_layer(hidden1, 4, 2, "hidden2") #Finish by a softmax softmax = tf.nn.softmax(hidden2) #Defining loss, accuracy etc.. cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y, logits=softmax)) tf.summary.scalar('cross_entropy', cross_entropy) correct_prediction = tf.equ…
tagged with: machine-learning
tagged with: tensorflow
has answer: http://stackoverflow.com/a/47828078
accepted answer: http://stackoverflow.com/a/47828078
favorite count: 0
possible better answer: http://stackoverflow.com/a/53578792
type: Question
has title: MLP(ReLu) stops learning after few iterations. Tensor Flow
score: 3
has answer: http://stackoverflow.com/a/53578792
tagged with: neural-network
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/a/47846407
has comment: http://stackoverflow.com/comment/82657017
accepted answer of: http://stackoverflow.com/q/47846283
has body: You are recursing, so when it finds astronomy it returns only from that call back into the loop. You need to test the return value from your function and use that. For example: import requests def walk(d = None,val = None): print("val:", val) if val == 'astronomy': return (val,d) else: for k,v in d.items(): if isinstance(v,dict): p = d[k] rtn = walk(d=p,val=k) # Changed if not rtn is None: # Added return rtn # Added r = requests.get('https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22nome%2C%20ak%22)&amp;format=json&amp;env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys',stream = True) n = r.json() b = walk(d=n) print(b)
type: Answer
score: 0
answers question: http://stackoverflow.com/q/47846283
type: AcceptedAnswer

http://stackoverflow.com/a/47778472
type: Answer
has body: This seemed like a hard problem, but in the comments Norrius suggested the very obvious solution of just making dbtable into its own class. class DbTable: def __init__(self): self._db_table = None @property def dbtable(self): if self._db_table is None: print('new assignment') self._db_table = self.get_data_from_db() return self._db_table def get_data_from_db(self): # Placeholder function for database access return 4 class Foo1: db = DbTable() dbtable = db.dbtable class Foo2(Foo1): pass class Foo3(Foo1): pass And it seems to have the functionality that I wanted. print(Foo1.dbtable) print(Foo2.dbtable) print(Foo3.dbtable) &gt; new assignment &gt; 4 &gt; 4 &gt; 4 print(Foo2.dbtable) print(Foo3.dbtable) &gt; new assignment &gt; 4 &gt; 4 So thanks again Norrius for the simple and obvious suggestion that I was somehow overlooking. To everyone else, sorry that I bothered you with a problem that turned out to have a pretty trivial answer.
score: 0
answers question: http://stackoverflow.com/q/47778082

http://stackoverflow.com/q/47786882
upvote count: 9
type: UnansweredQuestion
tagged with: openpyxl
has title: Cannot write to an excel AttributeError: 'Worksheet' object has no attribute 'write'
has answer: http://stackoverflow.com/a/47786977
answer count: 1
tagged with: python
has body: I am trying to write text to an excel I am following this post. This was working earlier but now it is not. I get: Error: line 122, in &lt;module&gt; worksheet.write(0, 11, 'HI') AttributeError: 'Worksheet' object has no attribute 'write' df1 A E c d c D Code: writer = pd.ExcelWriter("C:\\33.xlsx") df1.to_excel(writer, startrow=0, startcol=0, index = False) worksheet = writer.sheets['Sheet1'] worksheet.write(0, 11, 'YO') worksheet.write(1, 11, 'HI') I have tried also: import xlrd import xlwt from xlutils.copy import copy import os.path rb = xlrd.open_workbook('C:\\13.xlsx',formatting_info=True) r_sheet = rb.sheet_by_index(0) wb = copy(rb) sheet = wb.get_sheet(0) sheet.write(5,2,"string") wb.save('C:\\13.xlsx') I get: with open(filename, "rb") as f: OSError: [Errno 22] Invalid argument: 'C:\\13.xlsx"' How do I fix AttributeError: 'Worksheet' object has no attribute 'write'
linked to: http://stackoverflow.com/q/43537598
tagged with: excel
favorite count: 0
tagged with: pandas
tagged with: xlsxwriter
downvote count: 1
score: 8
type: Question

http://stackoverflow.com/comment/82517569
type: Comment
has text: email: furas@tlen.pl
comment on: http://stackoverflow.com/a/47775499
score: 0
type: AnswerComment

http://stackoverflow.com/comment/82637823
comment on: http://stackoverflow.com/q/47810164
score: 0
type: QuestionComment
has text: do you have access to the cluster via a terminal?
type: Comment

matplotlib
tags question: http://stackoverflow.com/q/47846357
tags question: http://stackoverflow.com/q/47838680
tags question: http://stackoverflow.com/q/47837821
tags question: http://stackoverflow.com/q/47833192
tags question: http://stackoverflow.com/q/47801821
tags question: http://stackoverflow.com/q/47825940
tags question: http://stackoverflow.com/q/47782185
tags question: http://stackoverflow.com/q/47806784
tags question: http://stackoverflow.com/q/47833722
tags question: http://stackoverflow.com/q/47830127
tags question: http://stackoverflow.com/q/47754677
tags question: http://stackoverflow.com/q/47805588
tags question: http://stackoverflow.com/q/47852102
tags question: http://stackoverflow.com/q/47840417
tags question: http://stackoverflow.com/q/47778208
tags question: http://stackoverflow.com/q/47810149
tags question: http://stackoverflow.com/q/47775220
tags question: http://stackoverflow.com/q/47705972
tags question: http://stackoverflow.com/q/47755608
tags question: http://stackoverflow.com/q/47793985
tags question: http://stackoverflow.com/q/47800922
tags question: http://stackoverflow.com/q/47813259
tags question: http://stackoverflow.com/q/47774935
tags question: http://stackoverflow.com/q/47709630
tags question: http://stackoverflow.com/q/47708267
tags question: http://stackoverflow.com/q/47808676
tags question: http://stackoverflow.com/q/47832237
tags question: http://stackoverflow.com/q/47767394
tags question: http://stackoverflow.com/q/47853750
tags question: http://stackoverflow.com/q/47842156
tags question: http://stackoverflow.com/q/47764825
tags question: http://stackoverflow.com/q/47821383
tags question: http://stackoverflow.com/q/47736457
tags question: http://stackoverflow.com/q/47770017
tags question: http://stackoverflow.com/q/47725725
tags question: http://stackoverflow.com/q/47773629
tags question: http://stackoverflow.com/q/47726283
tags question: http://stackoverflow.com/q/47807463
tags question: http://stackoverflow.com/q/47777579
tags question: http://stackoverflow.com/q/47776176
tags question: http://stackoverflow.com/q/47850202
tags question: http://stackoverflow.com/q/47764359
tags question: http://stackoverflow.com/q/47819697
tags question: http://stackoverflow.com/q/47852620
tags question: http://stackoverflow.com/q/47828890
tags question: http://stackoverflow.com/q/47770651
tags question: http://stackoverflow.com/q/47796389
tags question: http://stackoverflow.com/q/47756618
tags question: http://stackoverflow.com/q/47778550
tags question: http://stackoverflow.com/q/47711871
tags question: http://stackoverflow.com/q/47781076
tags question: http://stackoverflow.com/q/47834757
tags question: http://stackoverflow.com/q/47801283
tags question: http://stackoverflow.com/q/47775935
tags question: http://stackoverflow.com/q/47820905
tags question: http://stackoverflow.com/q/47833071
tags question: http://stackoverflow.com/q/47772417
tags question: http://stackoverflow.com/q/47699542
tag name: matplotlib
tags question: http://stackoverflow.com/q/47833775
tags question: http://stackoverflow.com/q/47773057
tags question: http://stackoverflow.com/q/47782031
tags question: http://stackoverflow.com/q/47711180
tags question: http://stackoverflow.com/q/47759474
tags question: http://stackoverflow.com/q/47775739
tags question: http://stackoverflow.com/q/47718341
tags question: http://stackoverflow.com/q/47834643
tags question: http://stackoverflow.com/q/47737772
tags question: http://stackoverflow.com/q/47744942
tags question: http://stackoverflow.com/q/47817024
tags question: http://stackoverflow.com/q/47738965
tags question: http://stackoverflow.com/q/47793894
tags question: http://stackoverflow.com/q/47698830
tags question: http://stackoverflow.com/q/47850132
tags question: http://stackoverflow.com/q/47771471
tags question: http://stackoverflow.com/q/47743513
tags question: http://stackoverflow.com/q/47750639
tags question: http://stackoverflow.com/q/47807693
tags question: http://stackoverflow.com/q/47818231
tags question: http://stackoverflow.com/q/47785237

http://stackoverflow.com/comment/82466233
comment on: http://stackoverflow.com/q/47752808
score: 0
type: Comment
type: QuestionComment
has text: I can use a text file too

http://stackoverflow.com/a/47767107
accepted answer of: http://stackoverflow.com/q/47767076
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47767076
score: 5
upvote count: 5
type: Answer
has body: I believe you dont need MultiIndex, only change: data.index = pd.MultiIndex.from_tuples([(file_date)] * len(data)) to: data.index = [file_date] * len(data)

http://stackoverflow.com/a/47777682
upvote count: 4
accepted answer of: http://stackoverflow.com/q/47777419
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47777419
has body: Your problem is not that the tuple is iterable. Making the tuple non-iterable won't help because extending a list with a non-iterable simply doesn't work. &gt;&gt;&gt; l = [] &gt;&gt;&gt; l.extend(1) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: 'int' object is not iterable &gt;&gt;&gt; What you need to do, is wrap your tuples in a list: &gt;&gt;&gt; t1 = (1,2,3) &gt;&gt;&gt; t2 = (4,5,6) &gt;&gt;&gt; l.extend([t1]) &gt;&gt;&gt; l.extend([t2]) &gt;&gt;&gt; l [(1, 2, 3), (4, 5, 6)] &gt;&gt;&gt; You can also extend the list with both tuples at the same time: &gt;&gt;&gt; l.extend([t1,t2]) &gt;&gt;&gt; l [(1, 2, 3), (4, 5, 6), (1, 2, 3), (4, 5, 6)] &gt;&gt;&gt;
type: Answer
score: 4

http://stackoverflow.com/a/47846442
type: Answer
score: 2
answers question: http://stackoverflow.com/q/47846256
downvote count: 0
has body: I believe you need first extract values before position of range, then by range and replace and last all values after range: print (uniprots) uniprot position amino amino_var sequence 0 P11362 3 W A WWWWWWWWWWW 1 P11362 4 E G MEEEEEELFWH 2 P11362 6 N I MWSWKCNNLVH 3 P11362 3 S C MWSWVESFLVH 4 P11362 3 W V MWEQAQPWGAH N = 2 def repl(x): s = x['sequence'] p = x['position'] a1 = x['amino'] a2 = x['amino_var'] return s[:p-N-1] + s[p-N-1:p+N].replace(a1,a2) +s[p+N:] uniprots['sequence'] = uniprots.apply(repl, axis=1) print (uniprots) uniprot position amino amino_var sequence 0 P11362 3 W A AAAAAWWWWWW 1 P11362 4 E G MGGGGGELFWH 2 P11362 6 N I MWSWKCIILVH 3 P11362 3 S C MWCWVESFLVH 4 P11362 3 W V MVEQAQPWGAH EDIT by edited answer: Extract values and join with column amino_var: N = 1 a = uniprots.apply(lambda x: x['sequence'][x['position']-N-1 : x['position']-1] , axis=1) b = uniprots.apply(lambda x: x['sequence'][x['position'] : x['position']+N] , axis=1) uniprots['sequence'] = a + uniprots['amino_var'] + b print (uniprots) position amino_var sequence 0 3 A WAW 1 4 G SGK 2 6 I KIL 3 3 C WCW 4 2 V MVE
upvote count: 2

http://stackoverflow.com/q/47846283
possible better answer: http://stackoverflow.com/a/47846519
score: -3
has comment: http://stackoverflow.com/comment/82656875
has body: I have a code to get a specific value from Yahoo API. The problem is it matched the IF statement but it returns None and also again its going to the else loop for some reason. I am very new to python. I want to get the value of key astronomy as return. import requests def walk(d = None,val = None): if val == 'astronomy': return (val,d) else: for k,v in d.items(): if isinstance(v,dict): p = d[k] walk(d=p,val=k) r = requests.get('https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22nome%2C%20ak%22)&amp;format=json&amp;env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys',stream = True) n = r.json() b = walk(d=n) print(b)
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/47846519
type: AnsweredQuestion
upvote count: 0
downvote count: 3
accepted answer: http://stackoverflow.com/a/47846407
favorite count: 0
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/47846407
has title: Value for Dict in Python

http://stackoverflow.com/a/47743911
score: 0
type: Answer
has body: You can do it like this, getting all the divs in one go, finding enclosing "a" tags for groups of 3 "li" tags containing one set of data. from bs4 import BeautifulSoup import requests import unicodedata from pandas import DataFrame page = requests.get("http://properties.kimcorealty.com/properties/0014/") soup = BeautifulSoup(page.content, 'html.parser') table = [] # Find all the divs we need in one go. divs = soup.find_all('div', {'id':['units_box_1', 'units_box_2', 'units_box_3']}) for div in divs: # find all the enclosing a tags. anchors = div.find_all('a') for anchor in anchors: # Now we have groups of 3 list items (li) tags lis = anchor.find_all('li') # we clean up the text from the group of 3 li tags and add them as a list to our table list. table.append([unicodedata.normalize("NFKD",lis[0].text).strip(), lis[1].text, lis[2].text.strip()]) # We have all the data so we add it to a DataFrame. headers = ['Number', 'Tenant', 'Square Footage'] df = DataFrame(table, columns=headers) print (df) Outputs: Number Tenant Square Footage 0 1 Nordstrom Rack 34,032 1 2 Total Wine &amp; More 29,981 2 3 Thomasville Furniture 10,628 ... 47 49 Jo-Ann Fabrics 45,940 48 50 Available 32,572
accepted answer of: http://stackoverflow.com/q/47734744
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47734744

http://stackoverflow.com/q/47805239
answer count: 1
downvote count: 0
tagged with: authentication
favorite count: 0
type: Question
has body: Let me preface this by saying I'm an engineer at a big company and am NOT a programmer so I'm sorry if I'm way off. This question has really been tough to google the answer which generally means I'm asking the question terribly. So I'll try to respond to users to work towards a solution if you'll let me. I've also tagged multiple languages because I'm not sure if this is a javascript solution or a python solution. I apologize. Basically, when a user fills in a form it runs a python cgi script that stores the information to a database. I want to automate the writing of the username so the user doesn't have to fill it in manually(not for security, just for ease of use) My program is on an apache RedHat server and in /etc/httpd/conf I have put the following in my httpd.conf file: &lt;Directory /var/www/html/program&gt; ##### LDAP Login ####################### AuthType Basic AuthName "ProbeEng Webserver: Enter Your BIGCOMPANY Username and Password" AuthBasicProvider ldap AuthzLDAPAuthoritative off AuthLDAPURL "ldap://ldap.city.bigcompany.com/ou=mtworkers,o=bigcompany.com?uid" ##### Require Authentication Require valid-user Order deny,allow Allow from all &lt;/Directory&gt; When users access my program they are required to put in their BIGCOMPANY username and password. How can I send that username through to my python cgi-script. The program they start the form on is also a python cgi-script that generates the html. I tried the following: try: username = getpass.getuser() But that doesn't seem to work. Is this possible while using a cgi-script, if so how do I access the user's username? Thanks
tagged with: javascript
tagged with: python
has title: How do I get the basic authentication username with a cgi python script?
accepted answer: http://stackoverflow.com/a/47807085
has answer: http://stackoverflow.com/a/47807085
type: AnsweredQuestion
score: 2
upvote count: 2
tagged with: apache

http://stackoverflow.com/a/47721827
accepted answer of: http://stackoverflow.com/q/47721726
type: Answer
has comment: http://stackoverflow.com/comment/82404299
has body: Simple. just pass the kwargs themselves into the sub function and add a kwargs variable to the sub functions def foo(a, print_line="Hello World!", **kwargs): print a, print_line def bar(a, number=2, multiple=4, **kwargs): print a, number * multiple def baz(a, **kwargs): foo(a, **kwargs) bar(a, **kwargs) This works because now the sub functions can receive an arbitrary number of keyword arguments while concretely defining the arguments they are required to have. Thus, a kwarg dict that looks like {'print_line':'test_line', 'number':1,'multiple':2} will function perfectly for both functions. As requested by comment: class SomeoneElsesClass: def someone_elses_function(self, a, foo="bar"): print(foo) class MyClass(SomeoneElsesClass): def someone_elses_function(self, a, foo="bar2", **kwargs): super(MyClass, self).someone_elses_function(a, foo)
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/82404272
answers question: http://stackoverflow.com/q/47721726

http://stackoverflow.com/q/47840374
tagged with: 3d
answer count: 0
downvote count: 0
score: 1
upvote count: 1
favorite count: 0
tagged with: plot
tagged with: colors
type: Question
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/82646789
tagged with: python
type: UnansweredQuestion
has title: how to restart colormap when it gets to the last color? Or how to make the first colors in colormap last longer?
has body: I have this 3d plot, but after a while the only color it puts is yellow, how can I make cmap start again from the first color instead of just plotting with yellow after a while? Or how can I make the colors equally distributed? and prevent them from going very rapidly to yellow. The colormap code line is the following cm_gradient = plt.get_cmap('viridis') This is how I call it if numb_walkers in snapshot or finished_cluster==True: col=np.arange(len(seeds_z_coordinates)) fig=plt.figure() snapshots_taken.append(numb_walkers) ax=fig.add_subplot(111, projection='3d') ax.scatter(seeds_z_coordinates, seeds_y_coordinates, seeds_x_coordinates, s=1, c=col, marker='o', cmap=cm_gradient) # cmap=cmap) label=str(numb_walkers) plt.title("Crystal Growth by DLA") ax.set_xlim3d(0, box_dim) ax.set_ylim3d(0,box_dim) ax.set_zlim3d(0,box_dim) ax.set_xlabel("x") ax.set_ylabel("y") ax.set_zlabel("z") plt.savefig("Gifs and images/{}_walkers.png".format(label), dpi=200) plt.close()

http://stackoverflow.com/comment/82435549
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47737141
type: Comment
has text: I meant how are you returning values from your country finder function? It has been a while since i have done any python but should there be a return statement to your function?

http://stackoverflow.com/q/47748824
tagged with: stashy
tagged with: django
has comment: http://stackoverflow.com/comment/82545479
tagged with: python
has comment: http://stackoverflow.com/comment/82545100
has answer: http://stackoverflow.com/a/47814596
has comment: http://stackoverflow.com/comment/82551670
has answer: http://stackoverflow.com/a/47799154
has comment: http://stackoverflow.com/comment/82545597
has comment: http://stackoverflow.com/comment/82457847
has comment: http://stackoverflow.com/comment/82545712
upvote count: 2
score: 2
has comment: http://stackoverflow.com/comment/82557766
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/82554361
has comment: http://stackoverflow.com/comment/82552563
has comment: http://stackoverflow.com/comment/82459734
has comment: http://stackoverflow.com/comment/82545277
tagged with: virtualenv
has body: I'm hitting a very weird issue. Edit: Adding full details: virtualenv -p python3 testenv cd testenv source bin/activate django-admin startproject blah cd blah mkdir modules vi modules/stash.py pip install django pip install stashy python manage.py shell &lt; modules/stash.py I have a script that sync data to populate a database: $ cat modules/stash.py import stashy class SyncProject: def __init__(self, endpo, user, passw): import stashy self.stash = stashy.connect(endpo, user, passw) access = SyncProject("http://localhost", "test", "test" ) I run my script with: $ python manage.py shell &lt; modules/stash.py The weirdness is that if I don't put the second import stashy, it doesn't work: NameError: name 'stashy' is not defined From the bit of Python I did a long time ago, that seems very unexpected and forces me to add import in every single method... Not sure if there is something wrong in how I import my dependencies or the way I run the script... Edit: more details, the error message: Traceback (most recent call last): File "manage.py", line 15, in &lt;module&gt; execute_from_command_line(sys.argv) File "/[PATH]/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/[PATH]/python3.6/site-packages/django/core/management/__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/[PATH]/python3.6/site-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "/[PATH]/python3.6/site-packages/django/core/management/base.py", line 335, in execute output = self.handle(*args, **options) File "/[PATH]/python3.6/site-packages/django/core/management/commands/shell.py", line 92, in handle exec(sys.stdin.read()) File "&lt;string&gt;", line 6, in &lt;module&gt; File "&lt;string&gt;", line 4, in __init__ NameError: name 'stashy' is not defined
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82544614
has comment: http://stackoverflow.com/comment/82543202
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82542938
has title: Very weird issue with import

http://stackoverflow.com/a/47764180
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/47763678
type: Answer
has body: What about something like this: entries = [ ("parent_id1", "comment1"), ("parent_id2", "comment2"), ("parent_id3", "comment3") ] query = "INSERT INTO p_reply (parent_id, comment) VALUES %s;" % ", ".join(str(entry) for entry in entries) ? That may fit your needs: &gt;&gt;&gt; "INSERT INTO p_reply (parent_id, comment) VALUES %s;" % ", ".join(str(entry) for entry in [("parent_id1", "comment1"), ("parent_id2", "comment2")]) "INSERT INTO p_reply (parent_id, comment) VALUES ('parent_id1', 'comment1'), ('parent_id2', 'comment2');" If you have integers (parent_id values) in your dataset, you may also have to convert it into str or modify the formatted string to add the '.
has comment: http://stackoverflow.com/comment/82512432
accepted answer of: http://stackoverflow.com/q/47763678
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/47780229
downvote count: 0
answer count: 1
has title: python - regex to remove a if it occures after a b
tagged with: string
upvote count: 7
accepted answer: http://stackoverflow.com/a/47780400
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47780400
has body: I want to remove all the dots in a text that appear after a vowel character. how can I do that? Here is the code I wish I had: string = re.sub('[aeuio]\.', '[aeuio]', string) Meaning like keep whatever vowel you have matched and remove the '.' next to it.
tagged with: python
tagged with: regex
type: AnsweredQuestion
score: 7

http://stackoverflow.com/q/47716354
tagged with: python
score: 0
answer count: 0
has body: I have the following minimal working example of code: #!/usr/bin/python # -*- coding: utf-8 -*- import pylab as pl import matplotlib.pyplot as plt v=[2,2.5,3] frec=[5,5.5,6] pl.plot(frec, v, 'ro', markersize=6) pl.xlabel(u'Wave frequency 'r'$\nu$'u' (Hz)', fontsize=17) pl.ylabel(u'Phase velocity'r'$v$'u' (cm/s)', fontsize=17) pl.xlim() pl.xlim(4.8,6.2) pl.ylim(1.8,3.2) pl.show() But when the plot is generated, the LaTeX code included on the labels is too small and does not fit well at all with the rest of the text. Is there any way to make it look better? The result looks like this, where the greek letters are too small: Plot
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/82393167
has comment: http://stackoverflow.com/comment/82392973
linked to: http://stackoverflow.com/q/11367736
has comment: http://stackoverflow.com/comment/82393497
type: Question
duplicate of: http://stackoverflow.com/q/11367736
type: UnansweredQuestion
has title: Size of LaTeX symbols on axes labels of a Python plot

http://stackoverflow.com/q/47793724
downvote count: 2
tagged with: python
has answer: http://stackoverflow.com/a/47795070
has comment: http://stackoverflow.com/comment/82548355
accepted answer: http://stackoverflow.com/a/47793830
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47793830
has comment: http://stackoverflow.com/comment/82548429
answer count: 3
tagged with: file
favorite count: 0
linked to: http://stackoverflow.com/q/29283466
type: Question
has title: how to look through the file in certain folder?
possible better answer: http://stackoverflow.com/a/47793884
has body: Let say I have a folder /home/me/data/picture/ and picture folder include various of picture files. if I want to look through all the file inside and get each file name. while file in fileexist: y,sr = somefunction.load("/home/me/data/picture"+file.name); is it possible how many files in certain folder? and get each file names?
upvote count: 0
has answer: http://stackoverflow.com/a/47793884
score: -2

http://stackoverflow.com/a/47843746
upvote count: 3
type: Answer
has comment: http://stackoverflow.com/comment/82651690
answers question: http://stackoverflow.com/q/47843707
has comment: http://stackoverflow.com/comment/82651497
has comment: http://stackoverflow.com/comment/82651745
has comment: http://stackoverflow.com/comment/82651472
downvote count: 0
has comment: http://stackoverflow.com/comment/82651720
has comment: http://stackoverflow.com/comment/82651598
has body: First method : What about without loop ? print(list(map(lambda x:x[0],b_data)).count('example')) output: 2 Second method : You can calculate using simple dict , without importing any external module or without making it so complex: b_data = [('example', 123), ('example-one', 456), ('example', 987)] dict_1={} for i in b_data: if i[0] not in dict_1: dict_1[i[0]]=1 else: dict_1[i[0]]+=1 print(dict_1) print(list(filter(lambda y:y!=None,(map(lambda x:(x,dict_1.get(x)) if dict_1.get(x)&gt;1 else None,dict_1.keys()))))) output: [('example', 2)] Test_case : b_data = [('example', 123), ('example-one', 456), ('example', 987),('example-one', 456),('example-one', 456),('example-two', 456),('example-two', 456),('example-two', 456),('example-two', 456)] output: [('example-two', 4), ('example-one', 3), ('example', 2)]
score: 3

yahoo-finance
tags question: http://stackoverflow.com/q/47740151
type: Tag
tag name: yahoo-finance

http://stackoverflow.com/a/47798652
has body: Use explode() function: In [30]: explode(df, lst_cols='source') Out[30]: fruits source prices 0 banana brazil 2 1 banana algeria 2 2 banana nigera 2 3 apple brazil 3 4 apple morocco 3 5 apple iran 3 6 apple france 3 7 pear china 7 8 pear india 7 9 pear mexico 7
has comment: http://stackoverflow.com/comment/82558214
answers question: http://stackoverflow.com/q/47798578
downvote count: 0
has comment: http://stackoverflow.com/comment/82558973
upvote count: 7
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82558677
score: 7
type: Answer
accepted answer of: http://stackoverflow.com/q/47798578
has comment: http://stackoverflow.com/comment/82558236
has comment: http://stackoverflow.com/comment/82558182

http://stackoverflow.com/comment/82550095
score: 0
type: Comment
has text: Aren't you missing a closing `)` before the `if` statement? So `a = [pd.read_pickle("my_file"+str(i)+".pkl") if os.path.exists...`?
type: QuestionComment
comment on: http://stackoverflow.com/q/47794327

http://stackoverflow.com/comment/82603410
score: 0
has text: @ShubhamSrivastava does my post answers your question?
type: Comment
comment on: http://stackoverflow.com/q/47820259
type: QuestionComment

http://stackoverflow.com/a/47735086
answers question: http://stackoverflow.com/q/47730966
score: 2
upvote count: 2
downvote count: 0
type: Answer
has body: (Spyder maintainer here) This is a know issue and it'll fixed in our 3.2.5 version, to be released on December/2017.

tkinter
tags question: http://stackoverflow.com/q/47843511
tags question: http://stackoverflow.com/q/47760319
tags question: http://stackoverflow.com/q/47734823
tags question: http://stackoverflow.com/q/47735793
tags question: http://stackoverflow.com/q/47753510
tags question: http://stackoverflow.com/q/47755522
tags question: http://stackoverflow.com/q/47761696
tags question: http://stackoverflow.com/q/47781434
tags question: http://stackoverflow.com/q/47855762
tags question: http://stackoverflow.com/q/47771832
tags question: http://stackoverflow.com/q/47768100
tags question: http://stackoverflow.com/q/47810226
tags question: http://stackoverflow.com/q/47743402
tags question: http://stackoverflow.com/q/47744778
tags question: http://stackoverflow.com/q/47842183
tags question: http://stackoverflow.com/q/47794918
tags question: http://stackoverflow.com/q/47743497
tags question: http://stackoverflow.com/q/47819197
tags question: http://stackoverflow.com/q/47731358
tags question: http://stackoverflow.com/q/47795610
tags question: http://stackoverflow.com/q/47778141
tags question: http://stackoverflow.com/q/47803270
tags question: http://stackoverflow.com/q/47837300
tags question: http://stackoverflow.com/q/47733961
tags question: http://stackoverflow.com/q/47844219
tags question: http://stackoverflow.com/q/47849592
tags question: http://stackoverflow.com/q/47829049
tags question: http://stackoverflow.com/q/47855605
tags question: http://stackoverflow.com/q/47855329
tags question: http://stackoverflow.com/q/47732254
tags question: http://stackoverflow.com/q/47796104
tags question: http://stackoverflow.com/q/47821717
tags question: http://stackoverflow.com/q/47794758
tags question: http://stackoverflow.com/q/47824017
tags question: http://stackoverflow.com/q/47793178
tags question: http://stackoverflow.com/q/47813259
tags question: http://stackoverflow.com/q/47852221
tags question: http://stackoverflow.com/q/47822411
tags question: http://stackoverflow.com/q/47735062
tags question: http://stackoverflow.com/q/47820406
tags question: http://stackoverflow.com/q/47799765
tags question: http://stackoverflow.com/q/47713915
tags question: http://stackoverflow.com/q/47847071
tags question: http://stackoverflow.com/q/47849840
tags question: http://stackoverflow.com/q/47728946
tags question: http://stackoverflow.com/q/47836837
tags question: http://stackoverflow.com/q/47823586
tags question: http://stackoverflow.com/q/47736578
tags question: http://stackoverflow.com/q/47818431
tag name: tkinter
tags question: http://stackoverflow.com/q/47734898
tags question: http://stackoverflow.com/q/47720824
tags question: http://stackoverflow.com/q/47772051
tags question: http://stackoverflow.com/q/47804945
tags question: http://stackoverflow.com/q/47841720
tags question: http://stackoverflow.com/q/47827578
tags question: http://stackoverflow.com/q/47845817
tags question: http://stackoverflow.com/q/47760017
tags question: http://stackoverflow.com/q/47722877
tags question: http://stackoverflow.com/q/47845220
tags question: http://stackoverflow.com/q/47811125
tags question: http://stackoverflow.com/q/47744143
tags question: http://stackoverflow.com/q/47850817
tags question: http://stackoverflow.com/q/47834017
tags question: http://stackoverflow.com/q/47850992
tags question: http://stackoverflow.com/q/47834896
tags question: http://stackoverflow.com/q/47775715
tags question: http://stackoverflow.com/q/47717259
tags question: http://stackoverflow.com/q/47773620
tags question: http://stackoverflow.com/q/47818157
tags question: http://stackoverflow.com/q/47770719
tags question: http://stackoverflow.com/q/47748918
tags question: http://stackoverflow.com/q/47753912
tags question: http://stackoverflow.com/q/47740478
tags question: http://stackoverflow.com/q/47780423
tags question: http://stackoverflow.com/q/47845048
tags question: http://stackoverflow.com/q/47698407
tags question: http://stackoverflow.com/q/47774809
tags question: http://stackoverflow.com/q/47720537
tags question: http://stackoverflow.com/q/47704736

http://stackoverflow.com/q/47705183
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/17261061
linked to: http://stackoverflow.com/q/8898294
has title: How to read a SQL file with python with proper character encoding?
answer count: 1
downvote count: 0
tagged with: psycopg2
favorite count: 0
type: Question
tagged with: postgresql
has body: Based on a few examples (here, here) I can use psycopg2 to read and hopefully run a SQL file from python (the file is 200 lines, and though runs quickly, isn't something I want to maintain in a python file). Here is the script to read and run the file: sql = open("sql/sm_bounds_current.sql", "r").read() curDest.execute(sql) However, when I run the script, the following error is thrown: Error: syntax error at or near "ï»¿drop" LINE 1: ï»¿drop table dpsdata.sm_boundaries_current_dev; As you can see, the first line in the script is to drop a table, but I'm not sure why the extra characters are being read, and can't seem to find a solution that might set the encoding of the file when reading it.
score: 5
has comment: http://stackoverflow.com/comment/82375006
upvote count: 5
accepted answer: http://stackoverflow.com/a/47722635
has comment: http://stackoverflow.com/comment/82403122
tagged with: python
linked to: http://stackoverflow.com/q/36416405
has answer: http://stackoverflow.com/a/47722635

http://stackoverflow.com/q/47766702
has answer: http://stackoverflow.com/a/47766853
has comment: http://stackoverflow.com/comment/82494541
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47766749
tagged with: timestamp
type: Question
answer count: 3
tagged with: datetime
tagged with: python
has body: I'm loading a string value ({str}) from a data base this is the value: 'W/"datetime\\'2017-10-16T20%3A18%3A02.2644265Z\\'"' Now i need to convert it to {Timestamp} format. Tried this: from datetime import datetime datetime.strftime(MyStrValue) And got: {TypeError}descriptor 'strftime' requires a 'datetime.date' object but received a 'str' Tried this: import dateutil.parser dateutil.parser.parse(MyStrValue) And got: {ValueError}Unknown string format I understand it's already in the right format but i'm Python newbie and i guess i'm missing something. Edit: to use datetime.strptime i need a format, since the string is already formatted i wish to parse it without explicitly building the format.
has comment: http://stackoverflow.com/comment/82495440
has answer: http://stackoverflow.com/a/47767469
has title: Python parse a formatted string to {Timestamp}
has comment: http://stackoverflow.com/comment/82494556
tagged with: parsing
linked to: http://stackoverflow.com/q/9637838
score: 0

http://stackoverflow.com/comment/82672485
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47854186
score: 0
has text: You have a file of JSON line data?

http://stackoverflow.com/q/47796218
type: Question
has comment: http://stackoverflow.com/comment/82554211
tagged with: dll
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/82553321
has body: I have read various articles on web to develop some rudimentary understanding of DLL. As I understand DLL's are binary files so if I am able to generate a DLL from Python script using Cython.build package, the DLL is going to give a speed up compared to original Python script. If there is no C++ code optimization, will the DLL using Cython.build give the same speed as a native C++ code with same logic. Or is all my above understanding false?
has title: Python DLL vs C++ DLL
answer count: 0
upvote count: 1
score: 1
tagged with: cythonize
downvote count: 0
favorite count: 0

http://stackoverflow.com/a/47741064
downvote count: 0
has comment: http://stackoverflow.com/comment/82446222
has body: The isinstance function makes a quick check to see if the type of the instance supplied as an argument is the same as that of the class. If so, it returns early and doesn't invoke your custom __instancecheck__. This is an optimization used in order to avoid an expensive call to __instancecheck__ (it's Pythonland code) when it isn't required. You can see the specific test in PyObject_IsInstance, the function that handles the isinstance call in the CPython implementation: /* Quick test for an exact match */ if (Py_TYPE(inst) == (PyTypeObject *)cls) return 1; Of course, your __instancecheck__ fires correctly when that test isn't True: &gt;&gt;&gt; isinstance(2, A) doing instance check &lt;class '__main__.A'&gt; 2 False I am not certain if this is implementation specific, I would of thought so, though, since there's no reference to this in the corresponding PEP section nor in the documentation on isinstance. Interesting aside: issubclass actually doesn't behave this way. Due to its implementation it always calls __subclasscheck__. I had opened an issue on this a while back which is still pending.
accepted answer of: http://stackoverflow.com/q/47740953
has comment: http://stackoverflow.com/comment/82446123
has comment: http://stackoverflow.com/comment/82442252
type: Answer
score: 11
upvote count: 11
answers question: http://stackoverflow.com/q/47740953
type: AcceptedAnswer

http://stackoverflow.com/q/47747960
favorite count: 0
has comment: http://stackoverflow.com/comment/82456090
has answer: http://stackoverflow.com/a/47748028
type: Question
has comment: http://stackoverflow.com/comment/82456897
tagged with: python
type: UnansweredQuestion
score: -2
has comment: http://stackoverflow.com/comment/82456670
has title: python error could not convert string to float
tagged with: slack
has body: We are getting this below error while migrating the data from slack channel to a file, when we execute the script for fetching the data for one day, it executing perfectly. But when we execute the script for 2 months data, it gives 10 days data in separate file but getting throwing an error on particular date. It might be possible that the source data on slack is bit different from expected Traceback (most recent call last): File "C:\Users\Slack SCript\script.py", line 218, in &lt;module&gt; main() File "C:\Users\Slack SCript\script.py", line 201, in main parse(message['text']) File "C:\Users\Slack SCript\script.py", line 114, in parse size = float(elements[1]) ValueError: could not convert string to float: As per the source data we found that some value is 0 maybe the error we got because of this value. is there any way to skip or continue future. from slackclient import SlackClient import time import os import sys import datetime from dateutil.relativedelta import relativedelta servers = ("fd2a", "ff1a", "hh3b", "kw1a", "kw1b", "lo8a", "os5a", "os5b", "sg2a", "sg2b", 'sy1a', 'va1a', 'va1b') types = ("", "nfs", "cluster") currser = "d" currtype = "" used = {} total = {} available = {} ts = 0 dir_name = "data" def savedata(dir_path, filename, data): f = open(dir_path + filename, "w") # opens file with name of "test.txt" print(dir_path + filename) f.write(data) f.close() def reset_data(): print("datareset") for i in range(0, len(servers)): for j in range(0, len(types)): used[servers[i] + types[j]] = 0 total[servers[i] + types[j]] = 0 available[servers[i] + types[j]] = 0 def write_data(ts): datastr = '' global used global total ttotaltotalsum = 0 for j in range(0, len(types)): datastr += types[j] + '\n' datastr += "Name\t" + "Region\t" + "total(TB)\t" + "used(TB)\t" + "available(TB)\t" + "Used(%)\n" for i in range(0, len(servers)): tused = used[servers[i] + types[j]] ttotal = total[servers[i] + types[j]] ttotaltotalsum += ttotal if (ttotal != 0): datastr += ( servers[…
has comment: http://stackoverflow.com/comment/82456761
has comment: http://stackoverflow.com/comment/82456684
has comment: http://stackoverflow.com/comment/82456880
has answer: http://stackoverflow.com/a/47748033
upvote count: 0
has comment: http://stackoverflow.com/comment/82456133
downvote count: 2
answer count: 2

http://stackoverflow.com/q/47847748
type: Question
tagged with: python-3.x
answer count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82659812
has answer: http://stackoverflow.com/a/47847857
has title: Store data for a loop
score: 0
tagged with: python
has body: I'm doing a numerical integration using the Monte Carlo Method. I've managed to make the function work, but now I'm trying to store the results in a matrix, so I can plot everything together. Here's my error: ``Traceback(most recent call last): File "mcmc.py", line 41, in result_array = list(fnArea) TypeError: 'float' object is not iterable And here's my code: from math import * from random import * import numpy as np def f(a): return sin(a) amin = 0.0 amax = 2.0*pi numRep = 100 #quanto maior, mais preciso porem mais devagar bmin = f(amin) bmax = bmin for i in range(numRep): a = amin + (amax - amin) * float(i)/numRep b = f(a) if b &lt; bmin: bmin = b if b &gt; bmax: bmax = b retArea = (amax - amin)*(bmax - bmin) #definicao da integral numPontos = 100 soma = 0 for j in range(numPontos): a = amin + (amax - amin) * random() b = bmin + (bmax - bmin) * random() if fabs(b) &lt;= fabs(f(a)): if f(a) &gt; 0 and b &gt; 0 and b &lt;= f(a): soma += 1 if f(a) &lt; 0 and b &lt; 0 and b &gt;= f(a): soma -= 1 fnArea = retArea * float(soma)/numPontos print (str(fnArea)) result_array = np.empty((0,100)) count = 100 for i in range(count): fnArea = retArea * (soma)/numPontos result_array = list(fnArea) print (result_array)
has answer: http://stackoverflow.com/a/47847820

http://stackoverflow.com/comment/82408201
comment on: http://stackoverflow.com/q/47723305
score: 0
type: Comment
type: QuestionComment
has text: @martineau That could be a solution as well.

http://stackoverflow.com/comment/82409754
type: QuestionComment
comment on: http://stackoverflow.com/q/47722610
score: 1
has text: If you are very new, my best advice is to try things yourself. You actually learn much better that way.
type: Comment

http://stackoverflow.com/a/47829067
answers question: http://stackoverflow.com/q/47828890
type: Answer
has comment: http://stackoverflow.com/comment/82620681
score: 2
upvote count: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82620948
accepted answer of: http://stackoverflow.com/q/47828890
downvote count: 0
has comment: http://stackoverflow.com/comment/82621888
has comment: http://stackoverflow.com/comment/82621306
has body: Something went wrong with your definition of min and max values. Additionally you probably also forgot to transpose your data. It should probably be limXMin = np.min(test_data.T[0]) limXMax = np.max(test_data.T[0]) limYMin = np.min(test_data.T[1]) limYMax = np.max(test_data.T[1]) Using the provided data, set_xlim()/set_ylim and set_xbound()/set_ybound() both produce the same figure:
has comment: http://stackoverflow.com/comment/82621754

http://stackoverflow.com/comment/82642654
comment on: http://stackoverflow.com/q/47839248
type: Comment
type: QuestionComment
has text: Well, your function `convert_to_integer` returns 20060606, which is the number of seconds elapsed since 1970: it gives what you retrieve.
score: 0

http://stackoverflow.com/q/47796932
favorite count: 0
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/82555083
has comment: http://stackoverflow.com/comment/82554896
has comment: http://stackoverflow.com/comment/82556503
downvote count: 0
has comment: http://stackoverflow.com/comment/82554940
has title: Requiring pandas dataframe input has either two column pairs or error thrown
has comment: http://stackoverflow.com/comment/82556412
has comment: http://stackoverflow.com/comment/82556386
has comment: http://stackoverflow.com/comment/82556656
has body: I am writing a short program which takes a user-input *csv file and manipulates this as a pandas DataFrame. Users must input the *csv with required columns A1 and B2 (including/without optional columns) or required columns C3 and D4 (including/without optional columns). If A1 exists as a column, then B2 must exist as a column, or there is an error thrown (and vice versa). Same with C3 and D4. Uses are allowed to choose either pair, but they must chose. Given an example dataframe: import pandas as pd df = pd.DataFrame("example1.csv") I can individual check that the columns pairs must both exist as follows, either with pandas: if df.columns.isin(['A1', 'B2']).any(): raise ValueError("Both A1 and B2 must be included") or with .issubset() as: if not {'A1', 'B2'}.issubset(df.columns): raise ValueError("Both A1 and B2 must be included") My problem is how to combine all of these conditionals together and not create spaghetti code. If neither A nor B nor C nor D is found, throw an error. If one is found, check for the partner; if the required partner is not found, throw an error...(but this will fail if A, B, C exist and D doesn't and I chose C to find the pair...)
type: AnsweredQuestion
tagged with: conditional-statements
tagged with: pandas
upvote count: 1
tagged with: http://stackoverflow.com/tag/csv
score: 1
has answer: http://stackoverflow.com/a/47797978
accepted answer: http://stackoverflow.com/a/47797978
tagged with: python
has answer: http://stackoverflow.com/a/47797417
possible better answer: http://stackoverflow.com/a/47797417

http://stackoverflow.com/comment/82373777
has text: find tag ` `, get all as normal text and use standard string functions or regex to find element in text.
comment on: http://stackoverflow.com/q/47704682
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47804372
has comment: http://stackoverflow.com/comment/82570314
has comment: http://stackoverflow.com/comment/82570326
has comment: http://stackoverflow.com/comment/82571024
type: AnsweredQuestion
answer count: 2
tagged with: django-queryset
accepted answer: http://stackoverflow.com/a/47804505
has answer: http://stackoverflow.com/a/47804505
downvote count: 0
favorite count: 0
type: Question
tagged with: python-3.x
score: 5
has body: I have a system where there is a many to one relationship with a number a model (say 1 a -> many b) and that many model has a one to one relationship with another model (say 1 b -> 1 c). Drawn like so: /--- b1 --- c1 / a ---- b2 --- c2 \ \--- b3 --- c3 I'm determined to create a method in that collects all the c's that correspond to a. Given an model system with the same structure to mine, the best I could come up with is shown in the method: Person.find_important_treats(). Is there a better way that does not involve so many calls to the database? from django.db import models class Person(models.Model): """ The 'a' from my above example """ def find_important_treats(self): return (pet.treat for pet in self.pets) class Pet(models.Model): """ The 'b' from my above example """ owner = models.ForeignKey( to=Person, related_name='pets' ) favourite_treat = models.ForeignKey( to=Treat, ) class Treat(models.Model): """ The 'c' from my above example """ pass
possible better answer: http://stackoverflow.com/a/47804451
upvote count: 5
has title: Django cannot determine queryset for chaining one-to-many with one-to-one relationship
tagged with: django
has answer: http://stackoverflow.com/a/47804451
tagged with: django-models
tagged with: python

http://stackoverflow.com/a/47731346
score: 0
has body: Suppose Span is inside a paragraph. Then you would be trying to replace it with a RawBlock, which is not going to work. Maybe try using RawInline instead?
answers question: http://stackoverflow.com/q/47729207
type: Answer

http://stackoverflow.com/comment/82670402
score: 0
has text: I have not coded yet, before am going to proceed i would like to know the way to do.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47845403

http://stackoverflow.com/comment/116199677
has text: It seems like we have to reset random seed every time to make sure we get the same random number
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47742668
type: Comment

ubuntu
tags question: http://stackoverflow.com/q/47812420
tags question: http://stackoverflow.com/q/47823941
tags question: http://stackoverflow.com/q/47813835
tags question: http://stackoverflow.com/q/47844910
tags question: http://stackoverflow.com/q/47788346
tags question: http://stackoverflow.com/q/47821174
tags question: http://stackoverflow.com/q/47753680
tag name: ubuntu
tags question: http://stackoverflow.com/q/47822740
tags question: http://stackoverflow.com/q/47704818
tags question: http://stackoverflow.com/q/47801775
tags question: http://stackoverflow.com/q/47780442
tags question: http://stackoverflow.com/q/47799480
type: Tag
tags question: http://stackoverflow.com/q/47850671
tags question: http://stackoverflow.com/q/47703695

http://stackoverflow.com/a/47846802
has comment: http://stackoverflow.com/comment/82709377
score: 0
type: Answer
has body: What you are probably looking for are model properties. From anticipating your needs I think you are looking for: You can add properties to you models that calculate a function. For your case it would be sth like: class Butterfly_model(models.Model): a = models.FloatField(verbose_name='a') b = models.FloatField(verbose_name='b') @property def X(self): return [i for i in range(0,self.a)] @property def Y(self): return [i+b for i in range(0,self.a)] That way you can access X and Y for each model instance and do not need to save it in the database (if that is what you want?).
answers question: http://stackoverflow.com/q/47846116

http://stackoverflow.com/q/47752324
tagged with: matrix
upvote count: 5
linked to: http://stackoverflow.com/q/26089893
possible better answer: http://stackoverflow.com/a/47752655
linked to: http://stackoverflow.com/q/34521845
has answer: http://stackoverflow.com/a/47752655
has body: I need to perform matrix multiplication on two 4D arrays (m &amp; n) with dimensions of 2x2x2x2 and 2x3x2x2 for m &amp; n respectively, which should result in a 2x3x2x2 array. After a lot of research (mostly on this site) it seems this can be done efficiently with either np.einsum or np.tensordot, but I am unable to replicate the answer I am getting from Matlab (verified by hand). I understand how these methods (einsum and tensordot) work when performing matrix multiplication on 2D arrays (clearly explained here), but I cannot get the axes indexes correct for the 4D arrays. Clearly I’m missing something! My actual problem deals with two 23x23x3x3 arrays of complex numbers but my test arrays are: a = np.array([[1, 7], [4, 3]]) b = np.array([[2, 9], [4, 5]]) c = np.array([[3, 6], [1, 0]]) d = np.array([[2, 8], [1, 2]]) e = np.array([[0, 0], [1, 2]]) f = np.array([[2, 8], [1, 0]]) m = np.array([[a, b], [c, d]]) # (2,2,2,2) n = np.array([[e, f, a], [b, d, c]]) # (2,3,2,2) I realise the complex numbers may present further issues, but for now, I am just trying to understand how the indexxing works with einsum &amp; tensordot. The answer I’m chasing is this 2x3x2x2 array: +----+-----------+-----------+-----------+ | | 0 | 1 | 2 | +====+===========+===========+===========+ | 0 | [[47 77] | [[22 42] | [[44 40] | | | [31 67]] | [27 74]] | [33 61]] | +----+-----------+-----------+-----------+ | 1 | [[42 70] | [[24 56] | [[41 51] | | | [10 19]] | [ 6 20]] | [ 6 13]] | +----+-----------+-----------+-----------+ and my closest attempt is by using np.tensordot: mn = np.tensordot(m,n, axes=([1,3],[0,2])) which gives me a 2x2x3x2 array with correct numbers but not in the right order: +----+-----------+-----------+ | | 0 | 1 | +====+===========+===========+ | 0 | [[47 77] | [[31 67] | | | [22 42] | [24 74] | | | [44 40]] | [33 61]] | +----+-----------+-----------+ | 1 | [[42 70] | [[10 19] | | | [24 56] | [ 6 20] | | | [41 51]] | [ 6 13]] | +----+-----------+-----------+ I’ve also tr…
accepted answer: http://stackoverflow.com/a/47752766
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/82466025
score: 5
has answer: http://stackoverflow.com/a/47752766
has title: Matrix multiplication on 4D numpy arrays
tagged with: arrays
downvote count: 0
tagged with: python
favorite count: 0
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/41870228
has answer: http://stackoverflow.com/a/47752832
answer count: 3

http://stackoverflow.com/q/47783515
tagged with: list
answer count: 2
possible better answer: http://stackoverflow.com/a/63341077
has comment: http://stackoverflow.com/comment/82528550
has comment: http://stackoverflow.com/comment/82528456
has body: I'm trying to create a dictionary from a list. Some of the information is in specific format so it's straighforward but then I need a catcha;; to put anything else so that key will have multiple values but I can't get it to work. Can anyone explain the best way to do this? dv = 'Not Found' mydict = {'key1': dv, 'key2': dv, 'key3': dv,} for stuff in list6: stringit = str(stuff).strip().replace(' ', '_') descriplst.append(stringit) for x in descriplst: if re.match(regasset, x): mydict['key1'] = x if re.match(regcid, x): mydict['key2'] = x else: mydict['key3'].append(x) The error I am getting is: Traceback (most recent call last): File "fixdes.py", line 73, in mydict['Interconnect'].append(x) AttributeError: 'str' object has no attribute 'append'
has comment: http://stackoverflow.com/comment/82528925
has comment: http://stackoverflow.com/comment/82528511
has answer: http://stackoverflow.com/a/63341077
type: Question
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47785626
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/47785626
has title: Iterate list and add multiple values to python dictionary key
score: 0

http://stackoverflow.com/a/47807586
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/47807446
has body: import datetime data = [('Lebron James', datetime.date(2017, 12, 23), 500), ('Julie Peralta', datetime.date(2017, 12, 13), 1500), ('Reynaldo Pahay', datetime.date(2017, 12, 11), 2500)] print([{'Name': name, 'date': date, 'penalty': penalty} for name, date, penalty in data]) # [{'Name': 'Lebron James', 'date': datetime.date(2017, 12, 23), 'penalty': 500}, {'Name': 'Julie Peralta', 'date': datetime.date(2017, 12, 13), 'penalty': 1500}, {'Name': 'Reynaldo Pahay', 'date': datetime.date(2017, 12, 11), 'penalty': 2500}]
score: 5
upvote count: 5

http://stackoverflow.com/q/47810983
has body: models.py I have created a Model i.e Form_db,now i want to print that information using template thanks.html from django.db import models from django import forms # Create your models here. class Form_db(models.Model): name = models.CharField(max_length=50) email = models.EmailField(max_length=50) number = models.CharField(max_length=15) any_query = models.TextField(blank=True,max_length=100) address = models.TextField(max_length=100,blank=True) def __str__(self): # __unicode__ on Python 2 return self.name forms.py from django import forms from .models import Form_db class Form_db_att(forms.ModelForm): class Meta: model = Form_db fields= ['name','email','address','number','any_query'] views.py from django.http import HttpResponseRedirect, HttpResponse, request from django.shortcuts import redirect ,render from .forms import Form_db_att from django.utils import timezone from .models import Form_db # Create your views here. def home(request): if request.method == 'POST': form = Form_db_att(request.POST) if form.is_valid(): model_instance = form.save(commit=False) model_instance.timestamp = timezone.now() model_instance.save() return HttpResponseRedirect('/home/test') else: form = Form_db_att() return render (request,'mforma/name.html',{'form':form}) def thanks(request): form = Form_db(request.POST) return render(request,'mforma/thanks.html',{'form':form}) thanks.html form.id is returning values with csrf token and presenting the field values in list format. &lt;form action="" method="post"&gt; {{form.id}} &lt;/form&gt; name.html &lt;form action="/home/thanks/" method="post" &gt; {% csrf_token %} {{form.as_p}} &lt;input type="submit" value="submit"&gt; &lt;/form&gt; mformp/urls.py from django.contrib import admin from django.conf.urls import url , include urlpatterns = [ url('admin/', admin.site.urls), url('home/',include('mforma.urls')), ] mformp/urls.py from django.conf.urls import url from . import views urlpatterns =[ url(r'^$',views.home,name='home'), url(r'^thank…
tagged with: python
has comment: http://stackoverflow.com/comment/82583663
has answer: http://stackoverflow.com/a/47811761
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/82584041
answer count: 1
accepted answer: http://stackoverflow.com/a/47811761
has comment: http://stackoverflow.com/comment/82584160
has comment: http://stackoverflow.com/comment/82584390
type: Question
has comment: http://stackoverflow.com/comment/82584591
has comment: http://stackoverflow.com/comment/82584292
has comment: http://stackoverflow.com/comment/82583783
has title: how to print form fields in the next page?
tagged with: django

http://stackoverflow.com/comment/82595086
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47815004
has text: @errantlinguist is the problem resolved? I was editing another question couldn't reply to your comment

http://stackoverflow.com/q/47845783
tagged with: javascript
tagged with: amazon-web-services
has comment: http://stackoverflow.com/comment/82669245
has comment: http://stackoverflow.com/comment/82685256
has title: Serverless CORS preflight request failed - AWS API Stripe
score: 1
has body: I have spent about 2 weeks trying to debug this but no luck. I have created a lambda function using python that creates a charge. This works fine with Stripe Checkout's simple script. It invokes it and returns the response without any issues (Python). try: stripe.api_key = "*******PRIVATE KEY***********" Tokenstring = event.get('body') Stripe_List = Tokenstring.split('=') Token = Stripe_List[1].split('&amp;')[0] Email = Stripe_List[-1] Email = Email.replace('%40', '@') charge = stripe.Charge.create( amount=100, currency="gbp", description="Example charge", source=Token, receipt_email=Email ) print('Full SUCCESSFUL Transaxn Info ==== {}'.format(event)) return { "statusCode": 302, "headers": { "Location": "https://example.com/#success" } } This is invoked very simply in the html body with &lt;form action="https://XXXXXXX.execute-api.eu-central-1.amazonaws.com/beta" method="POST"&gt; Now, when I try to use the custom stripe checkout code, I get: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. My javascript code is: var handler = StripeCheckout.configure({ key: '*****PRIVATE KEY*****', image: 'logo.png', locale: 'auto', token: function(token) { var xhr = new XMLHttpRequest(); xhr.open("POST","https://XXXXXXX.execute-api.eu-central-1.amazonaws.com/beta", true); xhr.setRequestHeader('Content-Type','application/json'); xhr.setRequestHeader('Access-Control-Allow-Origin','*'); xhr.onreadystatechange = handler; xhr.send(JSON.stringify({ body : token })); } }); I have set up OPTIONS in Amazon's API Gateway to respond and have enabled CORS on amazon API gateway. How can I pass the pre-flight request and let lambda execute the function?
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/82685100
has comment: http://stackoverflow.com/comment/82684813
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47854254
has comment: http://stackoverflow.com/comment/82684744
has comment: http://stackoverflow.com/comment/82684837
type: UnansweredQuestion
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/103113504
score: 0
has text: The same tip is also applied for name.of the generated pdf file.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/58382561

http://stackoverflow.com/comment/82601692
has text: what is `__opcall__`?
type: AnswerComment
comment on: http://stackoverflow.com/a/47810912
score: 1
type: Comment

http://stackoverflow.com/q/47729845
has title: Population of a Numpy array
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/82420548
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/82420202
has comment: http://stackoverflow.com/comment/82420922
has comment: http://stackoverflow.com/comment/82420479
answer count: 0
has comment: http://stackoverflow.com/comment/82420414
has comment: http://stackoverflow.com/comment/82420628
has comment: http://stackoverflow.com/comment/82420600
upvote count: 1
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82420335
has body: I am writing a code to populate a Numpy array. It's a 2D array, so I run two For loops with a specified condition. "Coords" array are positions of my particles. However every time I try to run it through the loops "coords" array starts being populated from x=2 position rather than x=1 (so the second position from the array) and then it gives me an error because of the lack of space in the array. Any ideas why is this happening? Thank you for any help! The error I am getting: "IndexError: index 10 is out of bounds for axis 0 with size 10" Here's my code: import random from math import exp, pow import numpy as np #Lattice and sampling parameters: L = 10 #no of sites per one side of the lattice nSites = L*L nPart = 10 #no of particles nSteps = 50000 AddRemFraction = 0.5 #acceptance ratio # create an array of coordinates of particles: coords = np.zeros((nPart,2), dtype=object) # create an LxL array of particle occupancy =&gt; occ(x,y) = 1 if site is occupied occ = np.zeros((L, L), dtype=object) #no of particles that have been placed on the lattice so far nPlace = 0 for x in range (1, L): for y in range (1, L): if (nPlace &lt; nPart): nPlace = nPlace +1 coords[nPlace,:] = [x,y] occ[x,y]=1
has comment: http://stackoverflow.com/comment/82420416
score: 0
downvote count: 1

http://stackoverflow.com/comment/82601467
has text: Hi, from a first reading it seems this might work, but can you explain a couple of things: 1 - what does the list in list(g) refer to? just the fact that g is a list? 2 - what is out= ? is that a variable that stores the results? why not just use results itself..?
comment on: http://stackoverflow.com/a/47819586
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/82603331
type: QuestionComment
score: 0
has text: @unutbu the desired result is to check if a specific row is empty or not. If it is take data from a different column
comment on: http://stackoverflow.com/q/47820360
type: Comment

http://stackoverflow.com/comment/82449902
type: AnswerComment
has text: if you want to use `Enter` with button then `bind` to button. You can also bind to `root` and it can execute even when you doesn't select `Entry` or `Button`
comment on: http://stackoverflow.com/a/47741488
type: Comment
score: 0

http://stackoverflow.com/comment/82438218
comment on: http://stackoverflow.com/a/47738871
score: 0
type: AnswerComment
has text: @Piinthesky `literal_eval` only does **literals** - it doesn't do expressions...
type: Comment

http://stackoverflow.com/a/47895062
type: Answer
score: 1
accepted answer of: http://stackoverflow.com/q/47835123
answers question: http://stackoverflow.com/q/47835123
has comment: http://stackoverflow.com/comment/82781889
has comment: http://stackoverflow.com/comment/82781744
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: I suppose the most straightforward solution would be the Floyd-Warshall algorithm, which computes the shortest distances between all pairs of nodes in a graph. This doesn't necessarily exploit the fact that you happen to have a 2D grid (it could work on other kinds of graphs too), but it should work fine. The fact that you do have a 2D grid may enable you to implement it more efficiently than if you had to write an implementation for any arbitrary graph (e.g. you can just store distances as they're computed in a matrix, instead of some less efficient data structure). The regular version only produces the distances of all shortest paths as output, and doesn't actually store the paths themselves as output. There's additional info on the wikipedia page on how to modify the algorithm to enable you to efficiently reconstruct paths if necessary. Intuitively, I suspect more efficient implementations may be possible which do exploit the fact that you have a 2D grid, probably using ideas from Rectangular Symmetry Reduction and/or Jump Point Search. Both of those ideas are traditionally used with A* for single-pair pathfinding queries though, I'm not aware of any work using them for all-pair shortest path computations. My intuition says they can be exploited there too, but in the time it'll take to figure that out exactly and implement it correctly, you can probably much more easily implement and run Floyd-Warshall.

http://stackoverflow.com/q/47727571
upvote count: 1
has comment: http://stackoverflow.com/comment/82415741
favorite count: 0
type: Question
has title: Have no idea how to get an average from a text file
has body: I am trying to take the average of numbers from a text file and print it. I have gotten as far as getting the numbers to print. I am lost as to how I can assign the values to variables and get the average. The numbers must be formatted like this in the text file: 10 20 30 40 50 60 70 80 90 100 110 120 130 140 150 160 170 180 190 200 def main(): numbersFile = open ('numbers.dat', 'r') for number in numbersFile: print number main() The expected result is: "The average is 105" Any help would be greatly appreciated. I tried to follow posting guidelines but I am new so correct any mistakes I made. Thank you for any help in advance!
type: UnansweredQuestion
score: -2
tagged with: python
has comment: http://stackoverflow.com/comment/82415657
has answer: http://stackoverflow.com/a/47727805
answer count: 2
linked to: http://stackoverflow.com/q/9039961
has answer: http://stackoverflow.com/a/47727648
downvote count: 3

http://stackoverflow.com/q/47853489
score: 1
tagged with: python
tagged with: numpy
type: AnsweredQuestion
has body: I would like to know. How can I add datetime column to np.array. I wrote this code. But it dosn't work and I get a exception 'Cannot convert from specific units to generic units in NumPy datetimes or timedeltas' trade_type = np.dtype( [ ('id', 'U'), ('timestamp', 'u8'), ('datetime', np.dtype('datetime64')) ] ) array = np.zeros(shape=1, dtype=trade_type) array['datetime'] = np.datetime64('1970-01-01 00:00:00')
accepted answer: http://stackoverflow.com/a/47853625
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/47853625
upvote count: 1
favorite count: 0
type: Question
has title: How can I add datetime column to np.array

http://stackoverflow.com/comment/82381487
has text: nothing happening. console prints "connected" but spark cannot print anything. it has to print the data i send
score: 0
comment on: http://stackoverflow.com/q/47709253
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82398319
comment on: http://stackoverflow.com/q/47709918
type: Comment
has text: It may not be error of cx_Freeze. I am not able to find how to package the server.py, cgi-bin/min.py and index.html as one package. On clicking submit the index page is opening again instead of executing cgi-bin/min.py
type: QuestionComment
score: 0

http://stackoverflow.com/q/47713022
has comment: http://stackoverflow.com/comment/82386071
has title: python poplib get headers from emails
has body: this is my actula code : import poplib, sys, re, threading, time, Queue from email import parser Mailbox = poplib.POP3(pop3, '110') Mailbox.user(username) Mailbox.pass_(password) numMessages = len(Mailbox.list()[1]) for i in range(numMessages): fullemail = '' fullemail = '\n'.join([msg for msg in Mailbox.retr(i+1)[1]]) msg = parser.Parser().parsestr(fullemail) for part in msg.walk(): print part.get_payload(decode=True) print part.get_payload(decode=True) print body of email, how i can print header of email ?
tagged with: email
has comment: http://stackoverflow.com/comment/82386036
tagged with: python
has answer: http://stackoverflow.com/a/52566326
linked to: http://stackoverflow.com/q/8424317
score: -1
tagged with: pop3
tagged with: poplib
upvote count: 0
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/82386033
downvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/q/47752379
has body: I'm trying to import variables from another python files. a.py - to be imported text="Hello, world" print("imported") b.py - works, but I cannot have static name a from a import * print(text) c.py - not work import importlib X = "a" try: text = "" i = importlib.import_module(X) print(i) print(text) except ImportError as err: print('Error:', err) try: text = "" i = importlib.__import__(X , globals=True, locals=True, fromlist=[], level=0) print(i) print(text) except ImportError as err: print('Error:', err) try: text = "" i = importlib.__import__(X , globals=True, locals=True, fromlist=[text], level=0) print(i) print(text) except ImportError as err: print('Error:', err) ouptut is: imported &lt;module 'a' from '/tmp/a.py'&gt; &lt;module 'a' from '/tmp/a.py'&gt; &lt;module 'a' from '/tmp/a.py'&gt; but text varible not working. d.py - not work X = "a" from X import * print(text) Is possible to use importlib as from MODULE import *?
has answer: http://stackoverflow.com/a/73897359
tagged with: python
tagged with: module
has title: Importing variables from another file (importlib)?
type: AnsweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/82465709
answer count: 2
possible better answer: http://stackoverflow.com/a/73897359
upvote count: 2
downvote count: 0
tagged with: python-importlib
accepted answer: http://stackoverflow.com/a/47753021
tagged with: import-libraries
favorite count: 0
has answer: http://stackoverflow.com/a/47753021
type: Question

http://stackoverflow.com/comment/82417598
has text: @MagnusEriksson You are right,I haven't pay attention.
comment on: http://stackoverflow.com/a/47728569
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/47757158
has comment: http://stackoverflow.com/comment/82478436
type: UnansweredQuestion
tagged with: python
has title: argparse - Conditional arguments based upon other argument value
has comment: http://stackoverflow.com/comment/82475428
score: 0
answer count: 0
tagged with: argparse
has body: I want to add some arguments based in other argument value. I mean, something like: parser.add_argument("-e", "--example", type=str) args = parser.parse_args() if args.example = "example": parser.add_argument("-j", "--othervalue", type=str) # I know that it is failing. Any idea?
duplicate of: http://stackoverflow.com/q/9505898
type: Question

http://stackoverflow.com/comment/82493628
comment on: http://stackoverflow.com/a/47766095
type: Comment
score: 0
type: AnswerComment
has text: @Kevin - Thanks, Kevin! That's what I get for being in a hurry! I also found a typo where I put 'is' instead of 'if'. All is fixed in the code now.

http://stackoverflow.com/a/47745830
score: 0
accepted answer of: http://stackoverflow.com/q/47744923
has body: You can use the turtle.ontimer function to implement a timer. In the timer function I increment the global time variable and call turtle.ontimer(timer, t=100) which automatically calls timer again after the specified timer t. import turtle turtle.listen() def number(): global shots shots += 1 print('Shots', shots) def timer(): global time time += .1 # Increase the global time variable. print(round(time, 1)) if time &lt; 2: # 2 seconds. # Call `timer` function again after 100 ms. turtle.ontimer(timer, t=100) else: print('Time is up.') # Do something. shots = 0 time = -0.1 # -0.1 because the `timer` adds .1 immediately. timer() turtle.onkey(number, 's') turtle.mainloop()
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47744923
type: Answer

http://stackoverflow.com/comment/82531482
has text: Works perfectly! Thank you very much! :)
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47784898
type: AnswerComment

http://stackoverflow.com/q/47836025
linked to: http://stackoverflow.com/q/29367255
has body: Say I have a script called src.py with several functions defined in it; the functions are all in a class called LDA. These functions need libraries such as numpy, scipy and others, which are imported as standard at the top of the script. Now in a new separate script, called main.py, I import the class LDA: from src import LDA If I now use the LDA class and all its functions in the new main.py script, the functions all work correctly, even though I did not import the dependencies needed in src.py. How does this work? Shouldn't I need to import numpy, scipy and so on in main.py for LDA to work?
upvote count: 2
has title: Does importing a class from another file also import that files dependencies?
tagged with: python
accepted answer: http://stackoverflow.com/a/47838234
has answer: http://stackoverflow.com/a/47838234
type: AnsweredQuestion
score: 2
answer count: 1
downvote count: 0
tagged with: dependencies
tagged with: import
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/710551

http://stackoverflow.com/comment/82507747
comment on: http://stackoverflow.com/q/47773371
has text: Please edit your question and add a real question. It's not clear what you are asking...
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/47840067
has comment: http://stackoverflow.com/comment/82649007
tagged with: network-programming
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/82646345
has title: Specify distance between nodes in Networkx
score: 0
answer count: 0
has body: I need to create a network out of correlation matrix, I would like the nodes that are highly correlated to be closer to each other and vice versa I tried to create my network like following G.add_edge('A', 'B', weight=0.7) G.add_edge('A', 'C', weight=0.5) G.add_edge('A', 'D', weight=0) G.add_edge('A', 'E', weight=0) G.add_edge('A', 'F', weight=0.1) G.add_edge('A', 'G', weight=-0.2) But the network does not seem accurate in the sense that the distance between nodes do not reflect the correlation Is there any easy fix for setting up in advance the distance between the nodes ? Thank you
tagged with: networkx
type: Question

http://stackoverflow.com/q/47826694
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82616242
has body: I type following code z=1+2j z=list(str(z)) I get output as ['(','1','+','2','j',')'] but when I write the following code z=input('') z=list(str(z)) print(z) I get output as ['1','+','2','j'] and not the curve brackets in the list why?
has answer: http://stackoverflow.com/a/47827181
has title: Why Python shows two different lists for list(str(z)) method
has comment: http://stackoverflow.com/comment/82615617
tagged with: python
score: -1
accepted answer: http://stackoverflow.com/a/47826967
has answer: http://stackoverflow.com/a/47827071
type: AnsweredQuestion
tagged with: list
has answer: http://stackoverflow.com/a/47826967
answer count: 3
downvote count: 2
has comment: http://stackoverflow.com/comment/83003496
has comment: http://stackoverflow.com/comment/82615635
upvote count: 1
possible better answer: http://stackoverflow.com/a/47827071
tagged with: string
has comment: http://stackoverflow.com/comment/82615872

http://stackoverflow.com/q/47782595
type: AnsweredQuestion
score: 0
has title: File is replicated without reason (Python, OpenCV)
has comment: http://stackoverflow.com/comment/82527498
has comment: http://stackoverflow.com/comment/82527617
answer count: 1
has comment: http://stackoverflow.com/comment/82539962
tagged with: opencv
type: Question
has comment: http://stackoverflow.com/comment/82538044
has comment: http://stackoverflow.com/comment/82540699
accepted answer: http://stackoverflow.com/a/47790052
has comment: http://stackoverflow.com/comment/82540634
has comment: http://stackoverflow.com/comment/82528185
tagged with: python
has comment: http://stackoverflow.com/comment/82531673
has answer: http://stackoverflow.com/a/47790052
has body: First, it's hard to explain. If someone have a better title, feel free to edit/suggest. So, I am using the next code to delete ROI's from given images. import cv2 import os import numpy as np import shutil src = (os.path.expanduser('~\\Desktop\\output\\')) causali = os.listdir(src) # CREO LISTA CAUSALI-2 causali.sort(key=lambda x: int(x.split('.')[0])) for file in enumerate(causali): # CONTA NUMERO DI FILE CAUSALE #import image image = cv2.imread(os.path.expanduser('~\\Desktop\\output\\{}'.format(file[1]))) cv2.imshow('orig',image) cv2.waitKey(0) #grayscale gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY) #cv2.imshow('gray',gray) #cv2.waitKey(0) #binary ret,thresh = cv2.threshold(gray,127,255,cv2.THRESH_BINARY_INV) #cv2.imshow('second',thresh) #cv2.waitKey(0) #dilation kernel = np.ones((1,80), np.uint8) img_dilation = cv2.dilate(thresh, kernel, iterations=1) #cv2.imshow('dilated',img_dilation) #cv2.waitKey(0) #find contours im2,ctrs, hier = cv2.findContours(img_dilation.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) #sort contours sorted_ctrs = sorted(ctrs, key=lambda ctr: cv2.boundingRect(ctr)[0]) for i, ctr in enumerate(sorted_ctrs): # Get bounding box x, y, w, h = cv2.boundingRect(ctr) # Getting ROI roi = image[y:y+h, x:x+w] if h &lt; 25: clean = cv2.rectangle(image,(x,y),( x + w, y + h ),(255,255,255),-1) cv2.imwrite(os.path.expanduser('~\\Desktop\\output2\\{}.png').format(file[0]), clean) I put a condition if h &lt; 25 to delete the ROI I don't want to be visible in the final image. This is source folder.. and this is the output the program give out.. As you can see, file n°8 came out as the n°7. This because the program don't find any ROI in that image which is ok for the condition. The problem is I don't understand why it replicate the last file he worked (7 ---> 8). How can I fix this ? In case no ROI is found it should just copy the file, not overwrite it with the last one.. Thanks
has comment: http://stackoverflow.com/comment/82539218

http://stackoverflow.com/a/47846425
has comment: http://stackoverflow.com/comment/82656933
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47846357
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/82671214
type: Answer
has comment: http://stackoverflow.com/comment/82657923
has body: Your xerr array is not 2xN, it should be 2x1: xerr=[[xel[i]],[xeu[i]]] You can avoid the loop as well matplotlib usually supports plotting multiple values at once. plt.errorbar(x, y, xerr=[xel,xeu], fmt='.')
accepted answer of: http://stackoverflow.com/q/47846357
has comment: http://stackoverflow.com/comment/82657390
has comment: http://stackoverflow.com/comment/82671201
score: 1

http://stackoverflow.com/q/47841809
answer count: 3
downvote count: 0
linked to: http://stackoverflow.com/q/433162
has answer: http://stackoverflow.com/a/47866684
favorite count: 0
has title: Django celery worker to send real-time status and result messages to front end
type: Question
upvote count: 12
score: 12
has body: In a django app I'm running async tasks and would like to show progress, errors etc to the user. If there are errors, the user should be redirect to a page where additional input or some action is required to fix the problem. What is the best way to communicate from the celery work back to the front end? Here's a basic structure in pseudo code: # views.py from tasks import run_task def view_task(): run_task.delay() return render(request, 'template.html') # tasks.py from compute_module import compute_fct @shared_task def run_task(): result = compute_fct() # how to catch status update messages from compute_module while compute_fct is running?? if result == 'error': handle_error() else: handle_succes() # compute_module import pandas as pd def compute_fct(): # send message: status = loading file df = pd.read_csv('test.csv') # send message: status = computing val = df['col'].mean() if val is None: return {'status':'error'} else: return {'status':'success','val':val} What I would ideally want: compute_module.py module uses python native logger. By separation of duties I want to keep the logging as generic as possible and use the standard python/django loggers. But they don't seem to be designed to send messages to front end. celery task somehow handles the logs and instead of displaying them on stdout redirects them to pusher front-end js shows and handles the messages There might be standard ways of communicating between celery worker and front end that I'm not aware off. this scenario must happen often and I am surprised it's so difficult to implement. in a way the rabbitmq message queue or aws sns should be designed for this. below are resources that I looked at but don't feel either of them work very well but maybe I am just confused. logging: this seems to be more about logging on the server side, not sending messages to user http://docs.celeryproject.org/en/latest/userguide/tasks.html#logging https://docs.djangoproject.com/en/2.0/topics/logging/ http://oddbird.net/2…
has comment: http://stackoverflow.com/comment/82681436
type: UnansweredQuestion
tagged with: pusher
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/48000392
tagged with: logging
tagged with: celery
has answer: http://stackoverflow.com/a/70301706

http://stackoverflow.com/comment/82356605
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47698221
type: Comment
has text: you have written: 1) *skip starting 100 lines first file and retainheader* ; 2) *want to ignore top 3 rows*. So, what are your actual exact conditions?

http://stackoverflow.com/comment/82521121
comment on: http://stackoverflow.com/a/47779957
type: AnswerComment
has text: This works great, thanks. Can you example the inputs within the extract function? Just for learning purposes.
type: Comment
score: 0

http://stackoverflow.com/q/47840467
downvote count: 0
answer count: 1
tagged with: python
favorite count: 0
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82645914
has comment: http://stackoverflow.com/comment/82645844
accepted answer: http://stackoverflow.com/a/47840955
tagged with: toolz
has answer: http://stackoverflow.com/a/47840955
has comment: http://stackoverflow.com/comment/82645361
has body: In the toolz project, is there anyway to treat an objects method similarly to a function, so i can better compose, curry, etc. ? by better i mean readability, and similar performance Heres a trivial example: # given a list strings (names), l = ["Harry" , "Sally " , " bEn " , " feDDy " ] # Lets pretend I want to apply a few simple string methods on each item in the # list (This is just an example), and maybe replace as it's multi-airity. # Traditional python list comprehension: print([x.strip().lower().title().replace('H','T') for x in l ]) ['Tarry', 'Sally', 'Ben', 'Feddy'] # my attempt, at toolz, same question with compose, curry, # functools.partial. from toolz.functoolz import pipe, thread_last thread_last(l, (map , str.strip), (map , str.lower), (map , str.title), (map , lambda x: x.replace('H','T')), # any better way to do this? # I wish i had function/method `str.replace(__init_value__, 'H', 'T')` where the # `__init_value` is what I guess would go to the str constructor? list, print) I don't like all extra lambda... and I couldn't imagine that would be ok for performance. Any tips on how to make this better with toolz? With the operators module i can make most operators less painful and omit lambdas for things like addition, subtraction, etc. Is there anything similar for method calls in recent versions of python?
has title: python toolz - composing methods (in contrast to functions)
type: Question
score: 2
upvote count: 2

http://stackoverflow.com/q/47851543
tagged with: twilio
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48143526
tagged with: python
has title: Proper way to use Twilio Add-ons for "Lookups" in Python
has body: What is the proper way to us a Twilio Add-on that provides intelligence on a phone number for "Lookups" in Python? Currently, I have it working with "Incoming Voice Call" and "Incoming SMS Message" (Note: you can see "lookups", "Incoming Voice Call: and "Incoming SMS Message" in the attached picture). With "Incoming Voice Call" and "Incoming SMS Message", the information is automatically provided with the rest of the information pertaining to the call or SMS when Twilio makes it's initial request to my application. The problem with this is that in practice, I am paying 10 times over for many spam numbers that are constantly dialing in. Instead, I would like to look up the information manually, only when I do not already have the information cached. It looks like I can make a raw HTTPS request from Python to do this. Example: https://lookups.twilio.com/v1/PhoneNumbers/+16505399600/?AddOns=nomorobo_spamscore&amp;AddOns.nomorobo_spamscore.secondary_address=+15108675309 However, it seems like a more "proper" way would be to use the TwilioRestClient that comes with the Twilio python helper library. However, its not clear get this Add-on information through the Twilio python helper library. If I'm being honest, I have a lot of trouble understanding those docs.
downvote count: 0
score: 1
upvote count: 1
favorite count: 0
answer count: 1
type: Question

http://stackoverflow.com/q/47720662
has comment: http://stackoverflow.com/comment/82402033
type: AnsweredQuestion
answer count: 3
has answer: http://stackoverflow.com/a/47720769
possible better answer: http://stackoverflow.com/a/47720754
upvote count: 3
has body: See the following ipython session: $ ipython --no-banner In [1]: class foo(object): ...: def __new__(self, *args, **kwargs): ...: print 'in superclass __new__' ...: return self ...: ...: class bar(foo): ...: def __init__(self, *args, **kwargs): ...: print 'in subclass __init__' ...: self.val = 42 ...: In [2]: b = bar() in superclass __new__ In [3]: b.val --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) &lt;ipython-input-4-c55d38c9d4d9&gt; in &lt;module&gt;() ----&gt; 1 b.val AttributeError: type object 'bar' has no attribute 'val' What is going on here? Why does defining __new__ in foo prevent the __init__ from running in bar?
downvote count: 0
has title: Subclass __init__ is not called if superclass __new__ is defined
favorite count: 0
type: Question
score: 3
has comment: http://stackoverflow.com/comment/82401982
accepted answer: http://stackoverflow.com/a/47720732
has comment: http://stackoverflow.com/comment/82402156
has answer: http://stackoverflow.com/a/47720754
has answer: http://stackoverflow.com/a/47720732
tagged with: python

http://stackoverflow.com/a/47793367
answers question: http://stackoverflow.com/q/47792429
type: Answer
score: 0
has body: The variable x receives all values, but each loop overwrite the last value. Hence, the result is 'g'. To save all values you can do like this: lst = [] with open ('master.sql', 'r') as f: for line in f: lst.append(line.split('.')[0]) x = '\n'.join(lst) with open('databases.sql', 'w') as f: f.write(x)

http://stackoverflow.com/comment/82499629
type: QuestionComment
comment on: http://stackoverflow.com/q/47768826
has text: Thanks @MartinPrikryl, i've made the change. Also, `ssh_stderr` returns a blank string, so i assume no error
score: 0
type: Comment

http://stackoverflow.com/comment/82603187
type: Comment
has text: Because it's about values, not the structure of internal representation of those values. If a and b are numeric NumPy types, exactly one of a < b, a > b, and a == b must evaluate to True because this is how numbers work. One could have designed `equal` method so that it enforced values being the same type, but NumPy developers made a different design decision.
comment on: http://stackoverflow.com/a/47817696
type: AnswerComment
score: 0

http://stackoverflow.com/comment/82620036
has text: @COLDSPEED `dryscape` might be another way, but the support for Windows seems complicated: https://pypi.python.org/pypi/dryscrape/1.0
comment on: http://stackoverflow.com/a/47828663
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/47806527
has body: def get_details(data, name): for i in data: if i['Name'] == name: return i return {} data = [{"Name": "John_Doe", "Age" : 25 },{"Name": "Jane_Roe", "Age" : 26 }] name = "John_Doe" get_details(data, name) output: {'Age': 25, 'Name': 'John_Doe'}
score: 1
type: Answer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47806397

http://stackoverflow.com/comment/82369265
type: Comment
type: QuestionComment
score: 0
has text: You can create a custom stylesheet with classes and [pass them to the method](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_html.html#pandas.DataFrame.to_html)
comment on: http://stackoverflow.com/q/47704441

http://stackoverflow.com/q/47698022
tagged with: scipy
has comment: http://stackoverflow.com/comment/82357188
type: Question
possible better answer: http://stackoverflow.com/a/54958882
answer count: 2
upvote count: 3
has comment: http://stackoverflow.com/comment/82356920
downvote count: 0
has title: Interpreting the amax parameter in scipy's line_search
favorite count: 0
has body: In SciPy 1.0.0, according to its documentation, scipy.optimize.line_search has an optional parameter amax which determines the "Maximum step size". As such, I would expect that the first return value, alpha, would always be less than the given amax, but this is not the case, as the following example illustrates: from scipy.optimize import line_search def f(x): return x[0]**2 + x[1]**2 def df(x): return 2*x x = np.array([4, 5]) line_search(f, df, x, -df(x), amax=0.001) # Returns (0.5, 3, 1, 0.0, 41.0, array([ 0., 0.])) In this, the value of alpha is 0.5 but the value of amax is 0.001, which is less than 0.5. Another interpretation might be that amax limits the distance between the output values x_new and x0, but this is also not the case. Am I misinterpreting the documentation, or is this a bug in SciPy? And, if it is working as intended, what is the correct interpretation of amax, and is there some other way to limit the range of alphas in which to perform the line search?
type: AnsweredQuestion
score: 3
tagged with: mathematical-optimization
has comment: http://stackoverflow.com/comment/82358017
has answer: http://stackoverflow.com/a/54958882
accepted answer: http://stackoverflow.com/a/47702710
tagged with: python
has answer: http://stackoverflow.com/a/47702710

http://stackoverflow.com/q/47726341
has comment: http://stackoverflow.com/comment/82415393
downvote count: 1
answer count: 1
has body: I have an error when running one of my projects, and it is very strange. What happens is this: File "src/run.py", line 4, in &lt;module&gt; from dotenv import load_dotenv, find_dotenv ImportError: No module named dotenv The strange thing is that I have installed python-dotenv. This is the fourth line: from dotenv import load_dotenv, find_dotenv Does anyone know how to fix this? Running High Sierra with python 2.7.
favorite count: 0
tagged with: macos-high-sierra
type: Question
has title: Python error when running project
has answer: http://stackoverflow.com/a/47726673
tagged with: python
score: -1
tagged with: macos
tagged with: python-2.7
upvote count: 0
has comment: http://stackoverflow.com/comment/82413189
type: UnansweredQuestion

http://stackoverflow.com/comment/82560725
type: Comment
has text: Hi, @Hadar I have updated the answer. The function you posted checks divisor less than or equal to. So you need to do an extra -1 internally/externally which is what I have done in the answer.
comment on: http://stackoverflow.com/a/47785629
type: AnswerComment
score: 0

http://stackoverflow.com/a/47819083
answers question: http://stackoverflow.com/q/47818970
has comment: http://stackoverflow.com/comment/82604127
has comment: http://stackoverflow.com/comment/82604330
has comment: http://stackoverflow.com/comment/82600132
type: Answer
has body: Since your result is a set, I would use a set constructor. Since the value of your set depends on an iteration of your input data, I would pass a generator expression to the set constructor. search_term = '4' data = {'h':['123','4'], 'm':['456','4'], 'a':['123','4']} result = set(k for k,v in data.items() if search_term in v) assert result == {'h', 'm', 'a'}
upvote count: 4
score: 4
has comment: http://stackoverflow.com/comment/82600095
downvote count: 0

dbus
type: Tag
tag name: dbus
tags question: http://stackoverflow.com/q/47718378

http://stackoverflow.com/comment/82357030
comment on: http://stackoverflow.com/q/47698547
has text: Your question is tagged as Python 3.x, but the `print` statement is Python 2.0. Use `print(...)` function instead.
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/q/47739336
upvote count: 1
has title: TypeError: array([ 0.]) is not JSON serializable
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47739835
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/json
tagged with: python
tagged with: tornado
score: 1
downvote count: 0
answer count: 1
has body: I have a python file: analyse.py: def svm_analyze_AHE(file_name): # obtain abp file testdata = pd.read_csv(file_name, header=None) #print testdata testdata_to_transpose = testdata.iloc[:,1] #print testdata_to_transpose testdata = np.transpose(testdata_to_transpose) testdata = testdata.reshape(1, -1) #print testdata # extract abp values #print testdata.shape leng = testdata.shape[1]-1 #print leng #T = testdata.iloc[:,leng] T = np.array(testdata[:,0:leng]) #print T testdata = np.array(T) # once model is stored, then retrieve it model = joblib.load('svm-model-0.pkl') # make predictions predicted = model.predict(testdata) return predicted The variable "predicted" returns [0.] which is not JSON serialisable. How do I rectify this?

http://stackoverflow.com/q/47752342
tagged with: python
has comment: http://stackoverflow.com/comment/82465264
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/82466315
has title: Iterative into Recursive
has comment: http://stackoverflow.com/comment/82465764
accepted answer: http://stackoverflow.com/a/47752973
has comment: http://stackoverflow.com/comment/82465167
has body: Hi everyone, I'm stuck on an assignment and i want to ask a question. My aim is finding all possible routes between the starter(start) and target(end) node. I'm working on this code and its graph: Note: Values in dictionary show the neighbours of keys. import sys graph={'x1': ['x1', 'x2', 'x3'], 'x2': ['x2', 'x4', 'x5'], 'x3': ['x3', 'x6', 'x8'], 'x4': ['x4', 'x5', 'x7'], 'x5': ['x5', 'x7'], 'x6': ['x6', 'x7', 'x8'], 'x7': ['x7', 'x9'], 'x8': ['x8'], 'x9': ['x9']} def find_all_paths(graph, start, end, path=[]): path = path + [start] if start == end: return [path] if start not in graph: return None paths = [] for node in graph[start]: if node not in path: try: newpaths = find_all_paths(graph, node, end, path) for newpath in newpaths: paths.append(newpath) except TypeError: print("No road") sys.exit() return paths I want this to be a completely recursive function(there should be no "for" loops).I've tried many things but I failed every time. Do u have any suggestions ?
answer count: 1
has comment: http://stackoverflow.com/comment/82466185
type: Question
has answer: http://stackoverflow.com/a/47752973
has comment: http://stackoverflow.com/comment/82465921
has comment: http://stackoverflow.com/comment/82465509

http://stackoverflow.com/comment/82442140
comment on: http://stackoverflow.com/q/47741022
type: QuestionComment
has text: use ``len(my_list)``?
type: Comment
score: 0

http://stackoverflow.com/comment/82602276
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47819301
type: AnswerComment
has text: I mean, what did you expect when you appended a solution to a list?

http://stackoverflow.com/comment/82607631
comment on: http://stackoverflow.com/q/47822346
has text: Which template engine are you using? According to [docs](http://boto3.readthedocs.io/en/latest/reference/services/s3.html#S3.Bucket.creation_date) `bucket.creation_date` is a `datetime` object. So I think, the display style resp. string format is set by the template engine
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/82543049
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47790687
type: QuestionComment
has text: @COLDSPEED I wasn't aware. That is how Python printed them out :)

http://stackoverflow.com/a/47725576
downvote count: 0
has comment: http://stackoverflow.com/comment/82420588
type: Answer
has comment: http://stackoverflow.com/comment/82423542
has body: You're hitting one of the sandbox restrictions. From The sandbox: An App Engine application cannot: write to the filesystem. Applications must use Cloud Datastore for storing persistent data. Reading from the filesystem is allowed, and all application files uploaded with the application are available. Well, the note about the datastore is actually misleading, there are several storage options, best for your case is IMHO the Cloud Storage (GCS). But you can't write a file to GCS using the regular open(), you nede to use the GCS client library for it. You can find an example here: Write a CSV to store in Google Cloud Storage
score: 2
has comment: http://stackoverflow.com/comment/82443909
has comment: http://stackoverflow.com/comment/82443907
upvote count: 2
answers question: http://stackoverflow.com/q/47721024

http://stackoverflow.com/comment/82422484
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47730967
type: QuestionComment
has text: So use what? @DanielRoseman

http://stackoverflow.com/comment/123281373
type: Comment
type: AnswerComment
score: 1
has text: @FoggyMindedGreenhorn Sure you are using PySide2, try `btn.clicked.connect(lambda *args, text=s : getbuttontext(text))` OR `btn.clicked[bool].connect(lambda checked, text=s : getbuttontext(text))`, See https://stackoverflow.com/questions/65185005/error-lambda-missing-1-required-positional-argument-when-using-with-qpushbutton/65185119#65185119
comment on: http://stackoverflow.com/a/47774969

http://stackoverflow.com/a/47792981
score: 0
has body: You should split your command. Like this: proc = subprocess.Popen("sshpass -p root ssh root@(IP_ADRESS) 'cd /home/pi/reed &amp;&amp; python reed.py'".split(), stdin=subprocess.PIPE, stdout=subprocess.PIPE, )
type: Answer
answers question: http://stackoverflow.com/q/47792922

http://stackoverflow.com/q/47778968
upvote count: 0
downvote count: 2
score: -2
answer count: 1
has body: I have a function that gives me the date in case it's past midnight. def date(hm, date, incr): d=get_day(date) m=get_month(date) y=get_year(date) if add_minutes(hm,incr)=='00:00': d+=1 if (m%2)!=0 and d&gt;31: m+=1 rest=d-31 if m&gt;12: m=1 y+=1 date=lenght_day_month(d, m, y) return date else: date=lenght_day_month(d, m, y) return date elif (m%2)!=0 and d&lt;=31: date=lenght_day_month(d, m, y) return date if (m%2)==0 and d&gt;30: m+=1 rest=d-31 if m&gt;12: m=1 y+=1 date=lenght_day_month(d, m, y) return date else: date=lenght_day_month(d, m, y) return date elif (m%2)==0 and d&lt;=30: date=lenght_day_month(d, m, y) return date Then I execute the same function in an other one like header[1]=str(date(header[3],header[1],5)) print(header[1]) And I get as a result None. What am I doing wrong?
favorite count: 0
has answer: http://stackoverflow.com/a/47779008
has comment: http://stackoverflow.com/comment/82519078
type: AnsweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/82519103
has title: None output, what's the issue?
accepted answer: http://stackoverflow.com/a/47779008
type: Question

http://stackoverflow.com/comment/82656136
type: AnswerComment
has text: Ya, this kind of questions I dont like, because depends of data... :(
comment on: http://stackoverflow.com/a/47845995
type: Comment
score: 1

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

http://stackoverflow.com/q/47799959
answer count: 1
type: Question
type: UnansweredQuestion
tagged with: python
tagged with: bottle
has title: Error trying to use global variable from Bottlepy mounted app
has body: I got a parent_app in a python file (parent.py) that I'm trying to mount in a child_app in another python file (child.py). The mount seems to work but, when I try to call a route from my parent_app trough the mount in my child_app, this route doesn't seems to be able to use global variable in my parent.py file. The parent.py file: from bottle import route import bottle import subprocess as sp global extProc parent_app = bottle.Bottle() @parent_app.route('/start') def start_bazarr(): global extProc extProc = sp.Popen(['python','child.py']) @parent_app.route('/stop') def stop_bazarr(): sp.Popen.terminate(extProc) @parent_app.route('/restart') def restart_bazarr(): stop_bazarr() start_bazarr() if __name__ == '__main__': start_bazarr() The child.py file: from bottle import route, run import bottle from parent import parent_app child_app = bottle.Bottle() @child_app.route('/') def root(): return u'Lorem Ipsum' if __name__ == '__main__': child_app.mount('/power', parent_app) child_app.run(host='127.0.0.1', port=8080) The URL I'm trying to call: http://127.0.0.1:8080/power/restart The error I got: Traceback (most recent call last): File "C:\Python27\lib\site-packages\bottle.py", line 862, in _handle return route.call(**args) File "C:\Python27\lib\site-packages\bottle.py", line 1740, in wrapper rv = callback(*a, **ka) File "C:\Users\morpheus\Desktop\parent.py", line 20, in restart_bazarr stop_bazarr() File "C:\Users\morpheus\Desktop\parent.py", line 16, in stop_bazarr sp.Popen.terminate(extProc) NameError: global name 'extProc' is not defined What am I doing wrong?
tagged with: python-2.7
score: 0
has answer: http://stackoverflow.com/a/47800102

http://stackoverflow.com/a/47741568
has comment: http://stackoverflow.com/comment/133892896
downvote count: 0
has comment: http://stackoverflow.com/comment/133949533
type: Answer
has comment: http://stackoverflow.com/comment/111968257
accepted answer of: http://stackoverflow.com/q/47740935
score: 40
answers question: http://stackoverflow.com/q/47740935
has comment: http://stackoverflow.com/comment/133893031
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/133949497
upvote count: 40
has body: It is perfectly fine and a more flexible approach to leave it in base.py. Also note that the primary use of __init__.py is to initialize Python packages and not to hold content. To avoid having to import the module each time you can write something like # in __init__.py from .base import Base into the __init__.py such that you can directly import Base from my_package: # some script from my_package import Base This is a common approach to make objects available at the package level. For more info about the __init__.py file check out the documentation.

http://stackoverflow.com/q/47741172
has title: random.shuffle does not work in transcrypt
has comment: http://stackoverflow.com/comment/82442450
has answer: http://stackoverflow.com/a/47741521
has answer: http://stackoverflow.com/a/47741417
type: Question
has comment: http://stackoverflow.com/comment/82443385
type: UnansweredQuestion
has body: I want to use transcrypt to convert a python script into javascript. The script uses 'shuffle' in the python 'random' module. I boiled the problem down to this example: l = [ '1', '2' ] from random import shuffle while True: thing = input( 'thing' ) print( 'before: {}'.format( ' '.join( l ))) shuffle( l ) print( 'after: {}'.format( ' '.join( l ))) This fails - if I comment out the 'shuffle( l )' line then it runs fine. Is shuffle not supported? example edited so the python is valid - even the previous invalid python generated javascript which runs &amp; shows the problem with 'random' I can see the incorrect javascript output: var _random_integer = function () { if (_index == 0) { _fill_array (); } var y = _array [_index]; y ^= y &gt;&gt; 11; y ^= y &lt;&lt; 7 &amp; 2636928640; y ^= y &lt;&lt; 15 &amp; 4022730752; y ^= y &gt;&gt; 18; _index = __mod__ (_index + 1, 624); return y; }; ... var random = function () { return _random_integer () / _bitmask3; }; ... (function () { var __name__ = '__main__'; var l = list (['1', '2']); var shuffle = __init__ (__world__.random).shuffle; while (true) { var thing = input ('thing'); print ('before: {}'.format (' '.join (l))); shuffle (l); print ('after: {}'.format (' '.join (l))); } I am no javascript expert, but it seems clear to me that this line: var shuffle = __init__ (__world__.random).shuffle; is going to generate a run-time error when 'random' is found to be a simple function. EDIT I worked around the problem by implementing my own shuffle function (well, I nicked it from the python library and hacked it till it worked): l = [ '1', '2', '3', '4' ] from random import randint def shuffle( l ): n = len( l ) for i in reversed( range( n )): if i == n - 1: continue # pick an element in x[:i+1] with which to exchange x[i] j = randint( i + 1, n - 1 ) l[i], l[j] = l[j], l[i] while True: thing = input( '&gt;' ) shuffle( l ) print( ' '.join( l ))
tagged with: python
score: 0
answer count: 2

http://stackoverflow.com/a/47732195
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47732165
type: Answer
has body: You can loop over the returned result and use re.sub: import re results = ('A, B, C\n ', 'A.ColA = B.ColB AND B.ColB2=C.ColC') new_results = tuple(re.sub('\n\s+$', '', i) for i in results) Output: ('A, B, C', 'A.ColA = B.ColB AND B.ColB2=C.ColC') Or, you can alter your pattern: import re q = """SELECT * FROM A, B, C WHERE A.ColA = B.ColB AND B.ColB2=C.ColC""" new_data = re.findall('(?&lt;=SELECT \* FROM\s)[A-Z\s,]+(?=\n)|(?&lt;=WHERE\s)[\w\W]+', q) Output: ['A, B, C', 'A.ColA = B.ColB AND B.ColB2=C.ColC']
has comment: http://stackoverflow.com/comment/82425164
has comment: http://stackoverflow.com/comment/82425194
score: 1
accepted answer of: http://stackoverflow.com/q/47732165

http://stackoverflow.com/q/47804782
answer count: 0
tagged with: function
has comment: http://stackoverflow.com/comment/82571189
tagged with: variables
tagged with: global-variables
type: Question
has title: Why can't I change a global variable in a function in python
tagged with: python-3.x
has body: I have a global variable let's just call it: foo = "" And I have a bunch of functions, and I called foo in one of those function. I changed it to having a string value. But if I go into another function after that and call it it doesn't still have that string value. Here's an example: foo = "" funct(): global foo foo = "some words" funct2(): global foo if foo == "some words": print ("foo is" + foo) funct() funct2() But in my case, in: funct2() it thinks that foo is empty even though in funct() I changed it to having a value, is it possible that nested functions have an effect on this because my code is very large and I couldn't really accurately depict the function mess in it. So instead I gave you this example, where here it is quite simple. Do nested functions not work well with changing globals or is there another problem. Is there an easier way to get one variable that can be read and edited in any function? Thank you for anyone who could point me in the right direction.
has comment: http://stackoverflow.com/comment/82571095
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82571113
tagged with: python
has comment: http://stackoverflow.com/comment/82571235
has comment: http://stackoverflow.com/comment/82571137
has comment: http://stackoverflow.com/comment/82571251
score: 0

http://stackoverflow.com/q/47806239
type: Question
downvote count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47810865
answer count: 1
has body: I've tried the following code. But I don't find what is not feedable in tensorflow. Could anybody show me what is not feedable? #!/usr/bin/env python # vim: set noexpandtab tabstop=2 shiftwidth=2 softtabstop=-1 fileencoding=utf-8: import tensorflow as tf x = tf.Variable(3) y = tf.constant(3) z = tf.add(1, 2) with tf.Session() as sess: print sess.graph.is_feedable(x) print sess.graph.is_feedable(y) print sess.graph.is_feedable(z)
tagged with: tensorflow
upvote count: 3
score: 3
tagged with: python
has title: What is not feedable in tensorflow?
favorite count: 0

http://stackoverflow.com/q/47722552
has answer: http://stackoverflow.com/a/47724413
has title: Pandas - set datetime / Timestamp value with apply
has answer: http://stackoverflow.com/a/47724609
has comment: http://stackoverflow.com/comment/82405971
has comment: http://stackoverflow.com/comment/82406132
type: Question
has comment: http://stackoverflow.com/comment/82407734
tagged with: python
has body: Lets consider the following dataframe: a=pd.DataFrame(data=list(range(10))) Trying to create a new column from it with apply: The column is supposed to contain Timestamp object def test(x): x["date"]=pd.Timestamp("2017-01-01") return x a.apply(test,axis=1) However this result in a dataframe containing the .value numerical attribute of the timestamp: 0 date 0 0 1483228800000000000 1 1 1483228800000000000 2 2 1483228800000000000 3 3 1483228800000000000 4 4 1483228800000000000 5 5 1483228800000000000 6 6 1483228800000000000 7 7 1483228800000000000 8 8 1483228800000000000 9 9 1483228800000000000 How come it is so? How can I get the correct Timestamp in the DataFrame? Edit: here the full code that is giving me problem: This is for respondant to understand that i am not trying to set a simply formed list of datetimes to a new column: def mae(x): entry=x.name[0] exit=x.name[1] m=d.loc[entry:exit,"close"] if x.dir==-1: r=(m.sub(m[::-1].cummax()[::-1])).abs().max() imax=(m.sub(m[::-1].cummax()[::-1])).idxmin() elif x.dir==1: r=(m.sub(m[::-1].cummin()[::-1])).abs().max() imax=(m.sub(m[::-1].cummin()[::-1])).idxmax() else: r=0 x['mae']=r*gbp['multiplier'] x['peak']=imax return x k=g.head().apply(mae,axis=1) This takes as input another dataframe and some financial prices data stored in a database - so a bit difficult to invent an example that at the same time is simple enough for people to grab it quickly and complicated enough as to justify the use of .apply. I think there is something i dont understand / or a bug in the .apply function - this is what i would like to have input and help on. Thanks guys!
has comment: http://stackoverflow.com/comment/82405815
has comment: http://stackoverflow.com/comment/82407616
has comment: http://stackoverflow.com/comment/82405768
has comment: http://stackoverflow.com/comment/82406827
tagged with: pandas
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82406005
score: 0
answer count: 2
accepted answer: http://stackoverflow.com/a/47724413
possible better answer: http://stackoverflow.com/a/47724609

http://stackoverflow.com/comment/82799593
type: Comment
type: AnswerComment
has text: `axes.facecolor` can be omitted if you are only interested in the saved image. For showing on screen it needs to be there to have the axes background red.
comment on: http://stackoverflow.com/a/47855504
score: 1

beautifulsoup
tags question: http://stackoverflow.com/q/47744697
tags question: http://stackoverflow.com/q/47708331
tags question: http://stackoverflow.com/q/47787289
tags question: http://stackoverflow.com/q/47801267
tags question: http://stackoverflow.com/q/47855373
tags question: http://stackoverflow.com/q/47719165
tags question: http://stackoverflow.com/q/47708122
tags question: http://stackoverflow.com/q/47831495
type: Tag
tags question: http://stackoverflow.com/q/47741815
tags question: http://stackoverflow.com/q/47709024
tags question: http://stackoverflow.com/q/47813718
tags question: http://stackoverflow.com/q/47738285
tags question: http://stackoverflow.com/q/47842958
tags question: http://stackoverflow.com/q/47732835
tags question: http://stackoverflow.com/q/47724574
tags question: http://stackoverflow.com/q/47716519
tags question: http://stackoverflow.com/q/47713819
tags question: http://stackoverflow.com/q/47724241
tags question: http://stackoverflow.com/q/47723790
tags question: http://stackoverflow.com/q/47766200
tags question: http://stackoverflow.com/q/47710379
tags question: http://stackoverflow.com/q/47840138
tags question: http://stackoverflow.com/q/47849191
tags question: http://stackoverflow.com/q/47840270
tags question: http://stackoverflow.com/q/47819266
tags question: http://stackoverflow.com/q/47762060
tags question: http://stackoverflow.com/q/47736600
tags question: http://stackoverflow.com/q/47728631
tags question: http://stackoverflow.com/q/47735771
tag name: beautifulsoup
tags question: http://stackoverflow.com/q/47780198
tags question: http://stackoverflow.com/q/47852373
tags question: http://stackoverflow.com/q/47704190
tags question: http://stackoverflow.com/q/47740151
tags question: http://stackoverflow.com/q/47838519
tags question: http://stackoverflow.com/q/47783841
tags question: http://stackoverflow.com/q/47817800
tags question: http://stackoverflow.com/q/47744018
tags question: http://stackoverflow.com/q/47786886
tags question: http://stackoverflow.com/q/47762717
tags question: http://stackoverflow.com/q/47735331
tags question: http://stackoverflow.com/q/47818858
tags question: http://stackoverflow.com/q/47846306
tags question: http://stackoverflow.com/q/47853248
tags question: http://stackoverflow.com/q/47825938
tags question: http://stackoverflow.com/q/47826934
tags question: http://stackoverflow.com/q/47788605
tags question: http://stackoverflow.com/q/47855539
tags question: http://stackoverflow.com/q/47698796
tags question: http://stackoverflow.com/q/47851832
tags question: http://stackoverflow.com/q/47834912
tags question: http://stackoverflow.com/q/47741106
tags question: http://stackoverflow.com/q/47852063
tags question: http://stackoverflow.com/q/47799742
tags question: http://stackoverflow.com/q/47773179
tags question: http://stackoverflow.com/q/47703639
tags question: http://stackoverflow.com/q/47847891
tags question: http://stackoverflow.com/q/47734744
tags question: http://stackoverflow.com/q/47852596
tags question: http://stackoverflow.com/q/47732816
tags question: http://stackoverflow.com/q/47728692
tags question: http://stackoverflow.com/q/47716699
tags question: http://stackoverflow.com/q/47702053
tags question: http://stackoverflow.com/q/47776762
tags question: http://stackoverflow.com/q/47723751
tags question: http://stackoverflow.com/q/47725804
tags question: http://stackoverflow.com/q/47764276
tags question: http://stackoverflow.com/q/47745106
tags question: http://stackoverflow.com/q/47761481
tags question: http://stackoverflow.com/q/47751002
tags question: http://stackoverflow.com/q/47706045

http://stackoverflow.com/q/47853134
tagged with: os.system
tagged with: python
has answer: http://stackoverflow.com/a/47853184
score: 2
upvote count: 2
has body: I'm trying to call an executable that has parentheses in the name (e.g. 'test(1).exe'). With Python 3.6.2, when I try the following: os.system('test(1).exe') I get: 'test' is not recognized as an internal or external command, operable program or batch file. But if I change the filename to 'test1).exe' by removing '(', then the following works successfully: os.system('test1).exe') Any ideas why the left parenthesis is causing an issue with os.system?
has comment: http://stackoverflow.com/comment/82670565
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/82677741
type: UnansweredQuestion
has title: os.system unable to call file with left parenthesis '(' in filename
has comment: http://stackoverflow.com/comment/82677577
has answer: http://stackoverflow.com/a/47856772
linked to: http://stackoverflow.com/q/35817
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82670632
tagged with: windows

http://stackoverflow.com/comment/82744276
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47853024
type: QuestionComment
has text: if both widgets are the same except for the pushbutton...(confused)... why al this trouble... besides the confusion you should also add positioning information... if you use wdgetB twice... two-buttons.. one spot... hmmm.. you can simply use button.hide() and or button.show().

http://stackoverflow.com/a/68590274
has comment: http://stackoverflow.com/comment/121270684
has body: If you face this issue in PyCharm 2021.2 add the following line -ea to Help | Edit Custom VM Options ... or to &lt;PyCharm_installation_folder&gt;/bin/pycharm.vmoptions (or pycharm64.vmoptions). Restart PyCharm and the parser should work correctly. See the relevant ticket in PyCharm's bug tracker https://youtrack.jetbrains.com/issue/PY-49970 Update: the fix is available in 2021.2.1 RC.
has comment: http://stackoverflow.com/comment/121285096
type: Answer
answers question: http://stackoverflow.com/q/47776315
downvote count: 0
upvote count: 19
score: 19

http://stackoverflow.com/comment/82383352
type: Comment
comment on: http://stackoverflow.com/q/47711595
type: QuestionComment
score: 0
has text: I edited, of course it's ```['hello', 'world', 'foobar']```

http://stackoverflow.com/a/47870277
type: Answer
has comment: http://stackoverflow.com/comment/100367322
score: 54
upvote count: 55
has comment: http://stackoverflow.com/comment/96693741
downvote count: 1
has body: Well, it really gives me pain to see how crappy hacks, like setting PYSPARK_DRIVER_PYTHON=jupyter, have been promoted to "solutions" and tend now to become standard practices, despite the fact that they evidently lead to ugly outcomes, like typing pyspark and ending up with a Jupyter notebook instead of a PySpark shell, plus yet-unseen problems lurking downstream, such as when you try to use spark-submit with the above settings... :( (Don't get me wrong, it is not your fault and I am not blaming you; I have seen dozens of posts here at SO where this "solution" has been proposed, accepted, and upvoted...). At the time of writing (Dec 2017), there is one and only one proper way to customize a Jupyter notebook in order to work with other languages (PySpark here), and this is the use of Jupyter kernels. The first thing to do is run a jupyter kernelspec list command, to get the list of any already available kernels in your machine; here is the result in my case (Ubuntu): $ jupyter kernelspec list Available kernels: python2 /usr/lib/python2.7/site-packages/ipykernel/resources caffe /usr/local/share/jupyter/kernels/caffe ir /usr/local/share/jupyter/kernels/ir pyspark /usr/local/share/jupyter/kernels/pyspark pyspark2 /usr/local/share/jupyter/kernels/pyspark2 tensorflow /usr/local/share/jupyter/kernels/tensorflow The first kernel, python2, is the "default" one coming with IPython (there is a great chance of this being the only one present in your system); as for the rest, I have 2 more Python kernels (caffe &amp; tensorflow), an R one (ir), and two PySpark kernels for use with Spark 1.6 and Spark 2.0 respectively. The entries of the list above are directories, and each one contains one single file, named kernel.json. Let's see the contents of this file for my pyspark2 kernel: { "display_name": "PySpark (Spark 2.0)", "language": "python", "argv": [ "/opt/intel/intelpython27/bin/python2", "-m", "ipykernel", "-f", "{connection_file}" ], "env": { "SPARK_HOME": "/home/ctsats/spar…
has comment: http://stackoverflow.com/comment/82706970
has comment: http://stackoverflow.com/comment/83723623
answers question: http://stackoverflow.com/q/47824131
has comment: http://stackoverflow.com/comment/83722323

http://stackoverflow.com/comment/82493493
type: Comment
type: AnswerComment
has text: The error went away but so did most of my data. The GUI only displays the 'date'. This is a start though, so I'll keep working from this. Thank you!
score: 0
comment on: http://stackoverflow.com/a/47766095

http://stackoverflow.com/comment/82611096
comment on: http://stackoverflow.com/a/47824008
type: Comment
score: 0
type: AnswerComment
has text: Great, it's good to know what happened too, when you give it an http string pandas swaps modes to begin to download a file using urllib and other stuff to get the job done. But there's no need for that if the file's local.

http://stackoverflow.com/q/47718382
upvote count: 1
has body: When I try to submit my form it says "This field is required." for an image even though I provide the image and other details to it. forms.py file from django.forms import ModelForm from .models import Status class CreatePost(ModelForm): class Meta: model=Status fields = ["username","text","privacy","image"] models.py file class Status(models.Model): title=models.CharField(max_length=20,default="updated status") username = models.ForeignKey('User',on_delete=models.CASCADE) #username = models.CharField(max_length=20) text = models.TextField(blank=True, null=True) image = models.ImageField(upload_to="media/image",null=True) time = models.DateTimeField(auto_now=True) privacy = models.CharField(max_length=5, blank=True, null=True) gid = models.IntegerField(blank=True, null=True) dp = models.SmallIntegerField(blank=True, null=True) class Meta: #unique_together = (('username', 'dp'),) #managed = False db_table = 'status' view.py def create_post(request): form=CreatePost(request.POST or None) if request.method=="POST": if form.is_valid(): instance=form.save(commit=False) instance.time=time.time() instance.save() return redirect('post',) return render(request,"uposts/createpost.html",{'form':form}) createpost.html {% extends "friendsbook/structure.html" %} {% block content %} &lt;form action="" method="post"&gt; {%csrf_token %} {{ form.as_p }} &lt;input type="submit" value="Save"&gt; &lt;/form&gt; {% endblock %} What it said after clicking on save button I am only taking 4 fields in form because all other fields can be null. For time field I took care of that in views.py by giving the time there.
has title: Upload image via ModelForm in django
answer count: 1
tagged with: django-forms
favorite count: 0
type: Question
tagged with: django
tagged with: django-models
tagged with: python
has comment: http://stackoverflow.com/comment/82398642
has comment: http://stackoverflow.com/comment/82397522
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47719052
downvote count: 0
tagged with: modelform
accepted answer: http://stackoverflow.com/a/47719052
score: 1

http://stackoverflow.com/q/47731461
has body: Trying to complete a lab for setting up a mobile game. But the lambda function is throwing the following error: expected string or buffer: TypeError Traceback (most recent call last): File "/var/task/lambda_function.py", line 34, in lambda_handler json_data = json.loads(msg) From what I understand it is expecting a string but the variable msg is a dictionary that also contains list. Can someone explain how I can get this working? Should it be a json.dump instead? New to python and coding so please forgive if I'm not framing the question in the correct way. Code is below. Thanks in advance def lambda_handler(event, context): global client print(event) # check the receiver's queue url if client == None: client = boto3.resource('sqs') records = event['Records'][0] sns_data = records['Sns'] msg = sns_data['Message'] print(msg) json_data = json.loads(msg) type_of_msg = json_data['type'] sender = json_data['sender'] receiver = json_data['receiver'] amount = json_data['amount'] # queue_name = get_queue_name_by_account_id(receiver) queue_name = USER_POOL_ID + "_" + receiver # enqueue the message queue = client.get_queue_by_name(QueueName=queue_name) msg = { "type": type_of_msg, "amount": amount } res = queue.send_message(MessageBody=json.dumps(msg)) print(res) return json_data['receiver']
tagged with: lambda
tagged with: amazon-web-services
has comment: http://stackoverflow.com/comment/82423903
score: 0
has title: JSON error expected string or buffer: TypeError lambda function failing
has answer: http://stackoverflow.com/a/47779084
tagged with: http://stackoverflow.com/tag/json
answer count: 1
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82423888
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82423897
tagged with: python

http://stackoverflow.com/comment/82684194
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47856583
has text: It is not resulting the view of that particular {item_name} , instead it is showing all the items, that is itemlist/

http://stackoverflow.com/comment/82443704
type: AnswerComment
has text: @jpmc26: You're totally right. My mistake. (I missed that the `cond_i` were functions, not booleans; the rest is evident.) Thanks.
score: 1
type: Comment
comment on: http://stackoverflow.com/a/47728462

http://stackoverflow.com/a/47721852
answers question: http://stackoverflow.com/q/47709198
downvote count: 1
has comment: http://stackoverflow.com/comment/82454887
has comment: http://stackoverflow.com/comment/82493777
upvote count: 0
type: Answer
score: -1
accepted answer of: http://stackoverflow.com/q/47709198
has body: If you want to run the same command using the different inputs you have for the list variable you created with register, you can itterate using with_items: - name: doing something cool cmd: my_awesome_cmd {{ item }} with_items: names You can take a look at the docs here. https://docs.ansible.com/ansible/devel/plugins/lookup/items.html If you want to do different stuff for each input, you can also rely on the fact that you can use register as a list: - name: doing something cool with carry cmd: my_awesome_cmd {{ names[0] }} - name: doing something cool with barry cmd: my_awesome_cmd {{ names[1] }} - name: doing something cool with harry cmd: my_awesome_cmd {{ names[2] }} ... You can always use debug to print out the output of your variable, that way you can have a better look at the structure and grab exactelly what you're looking for. http://docs.ansible.com/ansible/latest/debug_module.html
has comment: http://stackoverflow.com/comment/82465577
type: AcceptedAnswer

unmanaged
type: Tag
tags question: http://stackoverflow.com/q/47763747
tag name: unmanaged

http://stackoverflow.com/q/47800391
downvote count: 1
has body: I'm trying to run a Python (pandas) script that returns the initial_order_DT as a column and initial_order_value as another column. Input: Order ID Customer ID Value Date 00000001 0001 1500 10/01/2017 00000002 0001 1300 11/15/2017 00000003 0001 1200 12/12/2017 00000004 0002 500 12/13/2017 00000005 0003 1750 09/15/2017 00000006 0003 1800 10/01/2017 00000007 0003 1600 11/01/2017 00000008 0003 1400 12/01/2017 Output: Order ID Customer ID Value Date First_Order_DT First_Value 00000001 0001 1500 // 10/01/2017 1500 00000002 0001 1300 // 10/01/2017 1500 00000003 0001 1200 // 10/01/2017 1500 00000004 0002 500 // 12/13/2017 500 00000005 0003 1750 // 09/15/2017 1750 00000006 0003 1800 // 09/15/2017 1750 00000007 0003 1600 // 09/15/2017 1750 00000008 0003 1400 etc 09/15/2017 1750
type: Question
tagged with: pandas
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/82566497
favorite count: 0
has title: Return first order date and amount per customer
tagged with: numpy
accepted answer: http://stackoverflow.com/a/47800438
has answer: http://stackoverflow.com/a/47800438
has comment: http://stackoverflow.com/comment/82561947
has comment: http://stackoverflow.com/comment/82561909
upvote count: 1
tagged with: python
answer count: 1

http://stackoverflow.com/q/47804045
upvote count: 0
downvote count: 2
has title: What is meant by 'frame' in this for loop?
answer count: 1
linked to: http://stackoverflow.com/q/45255236
favorite count: 0
has body: for group, frame in Top15.groupby(ContinentDict): groups.loc[group] = [len(frame), frame['Estimate Population'].sum(),frame['Estimate Population'].mean(),frame['Estimate Population'].std()] I understand the for-loop acts on each group, but what is a frame? Is that a row? Column? Value? I guess dataFrame, but how is there more than one frame if the loop is only acting on the dataFrame Top15?
has answer: http://stackoverflow.com/a/47804553
has comment: http://stackoverflow.com/comment/82569994
type: Question
duplicate of: http://stackoverflow.com/q/45255236
has comment: http://stackoverflow.com/comment/82570026
tagged with: python
type: UnansweredQuestion
score: -2
tagged with: pandas-groupby
tagged with: pandas

http://stackoverflow.com/comment/82558848
comment on: http://stackoverflow.com/q/47738671
has text: URL: https://anaconda.org/pythonnet/pythonnet
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/82667433
type: QuestionComment
comment on: http://stackoverflow.com/q/47851402
score: 1
type: Comment
has text: It is a *side-effect* of the `print` function. Just like `somelist.append(x)` has a side effect of mutating the list object, the print functions puts some bytes in the standard output buffer. Note, `.append` *also* returns `None`. Most functions that are used for a side effect return `None` in Python. One counter example would be `somelist.pop()` which mutes the list (a side effect) *and it also* returns the popped value

http://stackoverflow.com/q/47832006
downvote count: 2
answer count: 1
has comment: http://stackoverflow.com/comment/82627090
favorite count: 0
type: Question
tagged with: django-views
score: -2
has body: I need to be able to return a JSON file from a view via the django server using python. If however the url HTTP request contains a parameter named callback I have to wrap it in a javascript function call which is named after the 'callback' parameter. I have been able to create the JSON-file and send it to the server and I know how to retrieve the possible callback parameter. However I am confused about the way I have to wrap the JSON-file to the Javascript function call. Can anybody tell me the correct way? def function_json(request, param): function_call = request.GET.get('callback', "") json_stuff = Object.objects.all().filter(param=parameter) if len(json_stuff) == 0: return HttpResponse("page was not found",status=404) data = {} for x in range(0, len(countries)): data[json_stuff[x].code] = json_stuff[x].name my_json_data = json.dumps(data) my_json_data_wrapped_in_a_function_call = ??? return HttpResponse(my_json_data_wrapped_in_a_function_call, content_type="application/json") and the data should show in server as Function_call({json_stuff})
tagged with: python
has answer: http://stackoverflow.com/a/47832828
accepted answer: http://stackoverflow.com/a/47832828
has title: How to wrap JSON to a javascript function call
type: AnsweredQuestion
upvote count: 0

http://stackoverflow.com/a/47707333
type: Answer
score: 2
upvote count: 2
has body: Use a collections.defaultdict or collections.Counter. Any of these three will work: self.pairLength = collections.defaultdict(int) self.pairLength = collections.defaultdict(lambda: 0) self.pairLength = collections.Counter() collections.Counter has the added advantage of giving you self.pairLength.most_common(10), which may be useful for your particular application. If for whatever reason you can't use a new container, just make sure the key exists before doing anything: for target, source ,in zip(self.tCorpus, self.fCorpus): key = (len(target), len(source)) if key not in self.pairLength: self.pairLength[key] = 0 self.pairLength[key] += 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47707321
downvote count: 0
answers question: http://stackoverflow.com/q/47707321

http://stackoverflow.com/q/47813004
has comment: http://stackoverflow.com/comment/82587498
possible better answer: http://stackoverflow.com/a/47813235
has comment: http://stackoverflow.com/comment/82587420
has answer: http://stackoverflow.com/a/47813235
type: AnsweredQuestion
score: 0
answer count: 2
has title: Django redirect with non-URL parameter
has answer: http://stackoverflow.com/a/47813433
accepted answer: http://stackoverflow.com/a/47813433
tagged with: django
type: Question
has body: I have a view class FooDetailView(View): def get(request, *args): foo_id = int(args[0]) foo = Foo.objects.get(pk=foo_id) // do something and render the page And now I would like to add some message into this page. For example class FooFuncView(View): def get(request): // do something return redirect('foo-detail', foo_id, 'call Func successfully') Since my urls.py is simply url(r'^foo-detail/([1-9][0-9]*)/', FooDetailView.as_view(), name='foo-detail'), I get the error message becuase no reverse match Reverse for 'foo-detail' with arguments '(&lt;id&gt;, 'call Func successfully')' not found. 1 pattern(s) tried: ['tournament-detail/contestant/([1-9][0-9]*)/'] But I dont want the message shown in the url because it could be too long. I just want to simply render the page as FooDetailView does, and add extra message after different operation. It there any good way to achieve this? If not, any explantions for that?
tagged with: python

http://stackoverflow.com/a/47872322
type: Answer
accepted answer of: http://stackoverflow.com/q/47722700
has body: It appears as though SQLAlchemy does not configure relationships both ways until after the model has been added and committed to the session. customer.shipments.append(new_shipment) customer.shipments # includes the new shipment new_shipment.customer # None session.add(customer) session.commit() new_shipment.customer # &lt;Customer object&gt; While this is annoying and I'm not sure why SQLAlchemy doesn't populate the two-way relationship when one side is created, it can be resolved by manually setting the relationship on both sides. For example: new_shipment = Shipment(customer=customer) new_shipment.ship_date # 11/01/2017 customer.shipments.append(new_shipment)
type: AcceptedAnswer
score: 0
answers question: http://stackoverflow.com/q/47722700

http://stackoverflow.com/comment/82463084
has text: Welcome back : )
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47751407
score: 1

http://stackoverflow.com/a/47711234
accepted answer of: http://stackoverflow.com/q/47710894
has comment: http://stackoverflow.com/comment/82383374
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/47710894
score: 1
upvote count: 1
downvote count: 0
has body: I suggest you to type : index_id.get_loc("a")
has comment: http://stackoverflow.com/comment/82383170

http://stackoverflow.com/q/47781597
tagged with: python
has title: print udates in telegram via telethon
has body: I am trying to print updates to my telegram acount . This is my code : client = TelegramClient('session_name', api_id, api_hash, update_workers=4) client.connect() from telethon.tl.types import UpdateShortMessage, PeerUser def callback(update): print(1) print('I received', update) client.add_update_handler(callback) whats wrong ? nothing prints .
tagged with: python-3.x
downvote count: 0
tagged with: telegram
upvote count: 1
type: UnansweredQuestion
answer count: 1
has answer: http://stackoverflow.com/a/68920117
favorite count: 0
type: Question
tagged with: telethon
score: 1

http://stackoverflow.com/q/47787725
has body: I would like to know how to find the nth term - (n-1)th term within a list. I know it should be very simple, but I'm just having trouble with application. So given the input of [0, 2, 4, 6, 5], the function should return [0, 2, 2, 2, -1]. My solution (which doesn't work) is as follows: def cost_to_diff (stocks): for i in range(i+1): stock[i] = stock[i] - stock[i-1] print stock Why doesn't this work as intended?
has answer: http://stackoverflow.com/a/47787818
has comment: http://stackoverflow.com/comment/82536614
tagged with: python
linked to: http://stackoverflow.com/q/24614361
has comment: http://stackoverflow.com/comment/82536605
type: Question
score: 0
has comment: http://stackoverflow.com/comment/82537259
type: UnansweredQuestion
has title: How to take the nth - (n-1)th term in Python?
has answer: http://stackoverflow.com/a/47788064
has comment: http://stackoverflow.com/comment/82536580
has answer: http://stackoverflow.com/a/47787839
answer count: 3

http://stackoverflow.com/comment/82647468
has text: This is a really interesting and clever solution to this problem... first time I've seen it. I'm undecided whether I love it or think it might be slightly too magical for my taste.
score: 3
type: Comment
comment on: http://stackoverflow.com/a/47841636
type: AnswerComment

http://stackoverflow.com/q/47837300
tagged with: python
score: -1
tagged with: frame
type: Question
tagged with: python-3.x
tagged with: tkinter
upvote count: 0
accepted answer: http://stackoverflow.com/a/47837536
tagged with: python-3.5
answer count: 1
has comment: http://stackoverflow.com/comment/82639145
has answer: http://stackoverflow.com/a/47837536
downvote count: 1
favorite count: 0
has body: How do I place the username and password label along with the login button inside the f2 box. Because, at the moment the f1 and f2 is covering the labels and button. Here is my code: from tkinter import * import os def adminLogin(): global AnameEL global ApwordEL # More globals :D global ArootA ArootA = Tk() # This now makes a new window. ArootA.geometry('1280x720') ArootA.title('Admin login') # This makes the window title 'login' f1 = Frame(width=200, height=200, background="#D3D3D3") f2 = Frame(width=400, height=200, background="#b4b4b4") f1.pack(fill="both", expand=True, padx=0, pady=0) f2.place(in_=f1, anchor="c", relx=.5, rely=.5) AnameL = Label(ArootA, text='Username: ') # More labels ApwordL = Label(ArootA, text='Password: ') # ^ AnameL.grid(row=1, sticky=W) ApwordL.grid(row=2, sticky=W) AnameEL = Entry(ArootA) # The entry input ApwordEL = Entry(ArootA, show='*') AnameEL.grid(row=1, column=1) ApwordEL.grid(row=2, column=1) AloginB = Button(ArootA, text='Login') AloginB.grid(columnspan=2, sticky=W) adminLogin() I would like this: to be placed in this dark grey smaller box in the middle:
has title: How to place labels and buttons in frame
has comment: http://stackoverflow.com/comment/82639783
type: AnsweredQuestion

http://stackoverflow.com/q/47762728
score: 3
has comment: http://stackoverflow.com/comment/82487674
has title: How to check if a Pandas row contains an empty set
tagged with: python
answer count: 4
has answer: http://stackoverflow.com/a/47762869
favorite count: 0
tagged with: boolean
has comment: http://stackoverflow.com/comment/82487134
has answer: http://stackoverflow.com/a/47763328
has comment: http://stackoverflow.com/comment/82487515
upvote count: 3
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/82487728
has body: I want to check if a Pandas Dataframe row contains an empty set in a specific column, i.e. d = {'col1': [1, 2], 'col2': [3, {}]} df2 = pd.DataFrame(data=d) col1 col2 0 1 3 1 2 {} and then df2['col_2_contains_empty_set'] = ? # how to implement this should give col1 col2 col_2_contains_empty_set 0 1 3 False 1 2 {} True What's the correct way to do this? Can't do bool(df['col2']) or df['col2'].bool() as Series are have ambiguous Boolean values, I think.
linked to: http://stackoverflow.com/q/36674083
has answer: http://stackoverflow.com/a/50265253
type: Question
tagged with: pandas
has answer: http://stackoverflow.com/a/47762792

http://stackoverflow.com/a/47780601
upvote count: 6
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47780567
has body: After looking for a while, I found in the docs that I can use the parameter 'primitivesAsString' df = spark.read.json(r's3://mypath/', primitivesAsString='true') This way I can forbid inference at least for primite types. But, I will not avoid it for arrays and structs. Still, it works to me.
answers question: http://stackoverflow.com/q/47780567
type: AcceptedAnswer
score: 6
type: Answer

http://stackoverflow.com/q/47769641
has answer: http://stackoverflow.com/a/62112462
upvote count: 36
has title: How do I install packages in PyCharm for all projects?
downvote count: 0
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47772901
tagged with: python
has body: I use PyCharm and all the initial settings are okay.Simple package installation is working. Then why do I need to reinstall a package for each project? Is there any way to install the packages for all projects from now on?
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/62112462
has comment: http://stackoverflow.com/comment/82500389
accepted answer: http://stackoverflow.com/a/47772901
score: 36
answer count: 2
tagged with: pycharm

http://stackoverflow.com/a/47787848
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47787405
score: 1
type: Answer
answers question: http://stackoverflow.com/q/47787405
has body: # with added line numbers 1. while i &lt; n: # modified this for simplicity. 2. sum = sum + i 3. i = i+1 # update counter 4. print("The sum is", sum) Here is the execution to wrap your head around it. # L1: i=1 n=4 sum=0 # L2: i=1 n=4 sum=1 # L3: i=2 n=4 sum=1 # L1: check i&lt;n - True, 2 is less than 4 # L2: i=2 n=4 sum=3 # L3: i=3 n=4 sum=3 # L1: check i&lt;n - True, 3 is less than 4 # L2: i=3 n=4 sum=6 # L3: i=4 n=4 sum=6 # L1: check i&lt;n - False, 4 not less than 4 ; its equal. condition fail. # L4: print 6 In case of starting from 0. # L1: i=0 n=4 sum=0 # L2: i=0 n=4 sum=0 # see sum is 0+0 # L3: i=1 n=4 sum=0 # L1: check i&lt;n - True, 1 is less than 4 # L2: i=1 n=4 sum=1 # L3: i=2 n=4 sum=1 # L1: check i&lt;n - True, 2 is less than 4 # L2: i=2 n=4 sum=3 # L3: i=3 n=4 sum=3 # L1: check i&lt;n - True, 3 is less than 4 # L2: i=3 n=4 sum=6 # L3: i=4 n=4 sum=6 # L1: check i&lt;n - False, 4 not less than 4 ; its equal. condition fail. # L4: print 6 When you contrast both; you did an extra iteration of work in the second case. But, that contributes nothing to the sum. Hope this helps

http://stackoverflow.com/comment/82359752
type: QuestionComment
score: 0
has text: The nested dictionary might be nice, either really. I come from JS/Node mainly and am mildly baffled by things like `OrderedDict`, which I've never seen before. Also seemed that `list()` was doing something different to people using py2 and py3.6
comment on: http://stackoverflow.com/q/47699695
type: Comment

http://stackoverflow.com/comment/82601845
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47819457
has text: Thanks Matt, I'd need to loop through 10 CSV's each time to produce 1 combined CSV.. I realize it's just an extension of this concept to do manually, but what would be the best way to pick all CSV's, convert them to DFs, and do this process on them please.

http://stackoverflow.com/q/47828907
has answer: http://stackoverflow.com/a/47830151
possible better answer: http://stackoverflow.com/a/47932523
has comment: http://stackoverflow.com/comment/82660453
has comment: http://stackoverflow.com/comment/82660339
tagged with: pyspark
has body: I'm connected to the cluster using ssh and I send the program to the cluster using spark-submit --master yarn myProgram.py I want to save the result in a text file and I tried using the following lines: counts.write.json("hdfs://home/myDir/text_file.txt") counts.write.csv("hdfs://home/myDir/text_file.csv") However, none of them work. The program finishes and I cannot find the text file in myDir. Do you have any idea how can I do this? Also, is there a way to write directly to my local machine? EDIT: I found out that home directory doesn't exist so now I save the result as: counts.write.json("hdfs:///user/username/text_file.txt") But this creates a directory named text_file.txt and inside I have a lot of files with partial results inside. But I want one file with the final result inside. Any ideas how I can do this ?
tagged with: hdfs
tagged with: python
accepted answer: http://stackoverflow.com/a/47863316
has answer: http://stackoverflow.com/a/47882971
tagged with: spark-submit
answer count: 4
has comment: http://stackoverflow.com/comment/82660425
has title: How to save a file on the cluster
type: AnsweredQuestion
tagged with: apache-spark
has answer: http://stackoverflow.com/a/47932523
score: 10
has comment: http://stackoverflow.com/comment/82660617
downvote count: 1
upvote count: 11
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47863316
has comment: http://stackoverflow.com/comment/82660480
has comment: http://stackoverflow.com/comment/82660358

http://stackoverflow.com/q/47741315
tagged with: nltk
has title: Showing "TypeError: unhashable type: 'list'" while using it in nltk.FreqDist() function
has comment: http://stackoverflow.com/comment/82442744
has comment: http://stackoverflow.com/comment/82442745
has body: I am trying to get the frequency distribution of the word in a phrase according to its degree using nltk. It is showing "TypeError: unhashable type: 'list'" though. Don't understand what the problem is. Please help. P.S: The code has a whole lot of bugs so don't mind that. I am trying to build a keyword extractor using code snippets from many many programs as I am a noob to python. If anyone wants to shed some light on the other bugs are also welcome. Code: from __future__ import division import operator import nltk import string def isPunct(word): return len(word) == 1 and word in string.punctuation def isNumeric(word): try: float(word) if '.' in word else int(word) return True except ValueError: return False class KeyExt: def __init__(self): self.stopwords = set(nltk.corpus.stopwords.words()) self.top_fraction = 1 def _generate_candidate_keywords(self, sentences): phrase_list = [] for sentence in sentences: words = map(lambda x: "|" if x in self.stopwords else x, nltk.word_tokenize(sentence.lower())) phrase = [] for word in words: if word == "|" or isPunct(word): if len(phrase) &gt; 0: phrase_list.append(phrase) phrase = [] else: phrase.append(word) return phrase_list def _calculate_word_scores(self, phrase_list): word_freq = nltk.FreqDist() word_degree = nltk.FreqDist() for phrase in phrase_list: degree = [x for x in phrase if not isNumeric(x)] for word in phrase: word_freq[word]=word_freq[word]+1 word_degree[word, degree]=word_degree[word, degree]+1 for word in word_freq.keys(): word_degree[word] = word_degree[word] + word_freq[word] word_scores = {} for word in word_freq.keys(): word_scores[word] = word_degree[word] / word_freq[word] return word_scores def _calculate_phrase_scores(self, phrase_list, word_scores): phrase_scores = {} for phrase in phrase_list: phrase_score = 0 for word in phrase: phrase_score += word_scores[word] phrase_scores[" ".join(phrase)] = phrase_score return phrase_scores def extract(self, text, incl_scores=False): sentences = nltk.sent_t…
tagged with: python
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/82442806
accepted answer: http://stackoverflow.com/a/47741613
has comment: http://stackoverflow.com/comment/82442855
answer count: 1
has answer: http://stackoverflow.com/a/47741613
has comment: http://stackoverflow.com/comment/82442712
type: Question
tagged with: python-3.x

http://stackoverflow.com/comment/82526196
type: AnswerComment
has text: have you tried [this ppa](https://launchpad.net/~deadsnakes/+archive/ubuntu/ppa)?
comment on: http://stackoverflow.com/a/47781772
type: Comment
score: 0

http://stackoverflow.com/q/47836276
tagged with: web-scraping
upvote count: 7
has comment: http://stackoverflow.com/comment/82637330
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47836504
type: UnansweredQuestion
score: 7
tagged with: http://stackoverflow.com/tag/html
tagged with: javascript
has title: Scraping values on table generate by Javascript to Python
tagged with: python
has comment: http://stackoverflow.com/comment/82637515
has body: I've run with a problem with my web app. Here's my code: @app.route('/addrec',methods = ['POST', 'GET']) def addrec(): if g.user: if request.method == 'POST': #UPPER PANE payor = request.form['payor'] receiptno = request.form['OR'] paymentmethod = request.form['paymentmethod'] naive_dt = time.strftime("%m/%d/%Y") collectiondate = naive_dt = datetime.now() message = request.form['message'] #LOWER PANE url_to_scrape = 'http://localhost:5000/form' r = requests.get(url_to_scrape) soup = BeautifulSoup(r.text) nature = [] for table_row in soup.select("table.inmatesList tr"): cells = table_row.findAll('td') if len(cells) > 0: nature = cells[0].text.strip() natureamt = cells[1].text.strip() nature = {'nature': nature, 'nature': natureamt} nature_list.append(nature) ent = Entry(receiptno, payor,officer, paymentmethod, collectiondate,message, nature_list) add_entry(ent) actions="Applied" return redirect(url_for('form')) return redirect(url_for('home')) As you can see I am getting each of the values from my forms and is scraping the values in my table using beautifulsoup. However after I click the submit button, it loads forever. I am getting the valeus from the upper pane but not in the table. By the way I am generating my cells from a javascript function onClick. Just in case my javascript might be the problem. or maybe there's an easy way to extract these values from the javascrip functions -> python. Here's my javascript code and HTML HTML: Add Item Nature of Collection Amount The data of these scraped values, I expect them to be saved to my database. On a cell. If possible I would like the list to be inserted in a column so I can get them later. Or is there a way I can get the lists on a cleaner and better way to my database? Any help is appreciated. Thank you!
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/82376038
type: AnswerComment
has text: Ah, that all did it! Thank you! Can you explain what ```vmin``` and ```vmax``` do? I can't believe I was so close
comment on: http://stackoverflow.com/a/47707895
type: Comment
score: 0

http://stackoverflow.com/comment/82573154
comment on: http://stackoverflow.com/q/47805789
score: 0
has text: @andrew_reece it should be updated!
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47742823
has title: iterate through a dictionary in django template
has comment: http://stackoverflow.com/comment/82445822
upvote count: 4
has answer: http://stackoverflow.com/a/47743227
tagged with: django-templates
answer count: 3
has answer: http://stackoverflow.com/a/47744094
type: UnansweredQuestion
has body: {'provide a full refund of any money paid ': ['the ', 'dith ', 'with ', 'ande ', 'cor '], 'copyright laws of the place where you ar': ['e ', 'init ', ' or ', 'ate ', 's '], 'person or entity that provided you with ': ['the ', 'of ', 'ande ', ' or ', 'project '], 'michael s. hart is the originator of the': [' the ', '\n ', 's ', 'r ', ', ']} How do i parse this django variable passed through my view to the html file. I want to make this data to be displayed in the html file in form of a table where each keys values are shown return render(request, 'notebook/instant_search.html', output) i tried this in my html file where out put is the variable i am passing through my view {% for key, value in output %} {{ key }} &lt;br&gt; {% for key2 in value %} {{ key2 }} &lt;br&gt; {% endfor %} {% endfor %} also this: {% for k in context %} {{ k }} {% endfor %} But i am not getting any output. Its blank nothing on the screen to display
has comment: http://stackoverflow.com/comment/82445984
downvote count: 1
favorite count: 0
type: Question
score: 3
tagged with: http://stackoverflow.com/tag/html
tagged with: python
has answer: http://stackoverflow.com/a/47742935

decision-tree
type: Tag
tags question: http://stackoverflow.com/q/47820941
tags question: http://stackoverflow.com/q/47719001
tags question: http://stackoverflow.com/q/47801977
tag name: decision-tree

http://stackoverflow.com/q/47810404
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/55867416
score: 0
has comment: http://stackoverflow.com/comment/82593040
has answer: http://stackoverflow.com/a/47856389
has answer: http://stackoverflow.com/a/55867416
accepted answer: http://stackoverflow.com/a/47810553
tagged with: python
has body: need help for this code import timeit mysetup="" mycode=''' def gener(): ...my code here... return x ''' # timeit statement print (timeit.timeit(setup = mysetup, stmt = mycode, number = 1000000)) print("done") As result I got 0.0008606994517737132 As I read this unit is in "seconds" So my funtion executed 1 million time in 0.8 ms ? I think this is not real, too fast. I also tried basic option start = time.time() my code here end = time.time() print(end - start) and got 0.23901081085205078 for one time execution it seems a little slow... So what I'm I doing wrong ? Thanks
answer count: 4
has title: how to measure execution time of python code
has comment: http://stackoverflow.com/comment/82582232
has answer: http://stackoverflow.com/a/47810553
has answer: http://stackoverflow.com/a/47810767
type: Question

http://stackoverflow.com/comment/82594762
type: AnswerComment
comment on: http://stackoverflow.com/a/47816311
has text: One moment, it is server based so I need to check if that changes it
type: Comment
score: 0

http://stackoverflow.com/q/47819230
has title: Unexpected behaviour when calling shell command on a deployed web app
type: Question
accepted answer: http://stackoverflow.com/a/47819323
possible better answer: http://stackoverflow.com/a/47828862
has answer: http://stackoverflow.com/a/47819323
upvote count: 1
tagged with: python
has body: I am deploying a flask app, in which a multiprocessing.Process will be started. Inside this process I call a shell command trough subprocess.call(). The script runs fine when executed on local host, when deployed with nginx and gunicorn, the flask app behaves as expected until the subprocess starts, then I recieve the following error log: DEBUG:root:start to run command DEBUG:root:(&lt;class 'FileNotFoundError'&gt;, FileNotFoundError(2, "No such file or directory: 'java -jar ábsolute/path/to/jar/file') Process( target=decode_upload, args=( path_to_blf, path_to_dbc_folder, path_to_splitted, path_to_decoder, system_layout, dc_doc, dc_id, file_type, ) ).start() Here is the rellevant part of the function. def decode_file( path_to_blf, path_to_dbc_folder, path_to_splitted, path_to_decoder, system_layout=DEFAULT_SYSTEM_LAYOUT): command = "{} {} --blf={}".format( SOFTWARE_COMMAND, path_to_decoder, path_to_blf ) for dbc_file_name in DBC_FILE_NAME_LIST: command += " --dbc={}".format( os.path.join( path_to_dbc_folder, dbc_file_name ) ) command += " --out={}".format(path_to_splitted) logging.debug("start to run command") subprocess.call(command) logging.debug(f) logging.debug("run command end") def decode_upload( path_to_blf, path_to_dbc_folder, path_to_splitted, path_to_decoder, system_layout, dc_doc, dc_id, file_type): logging.basicConfig(filename='flask.log',level=logging.DEBUG) logging.debug('This message should go to the log file') try: decode_file( path_to_blf, path_to_dbc_folder, path_to_splitted, path_to_decoder, system_layout) except: logging.debug(sys.exc_info()) The process fails when it gets to this line. subprocess.call(command) if I try to call the "command" from the command line it works without a problem.
tagged with: flask
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/3172470
answer count: 2
tagged with: subprocess
score: 1
downvote count: 0
has answer: http://stackoverflow.com/a/47828862
tagged with: shell
favorite count: 0
tagged with: multiprocessing

http://stackoverflow.com/comment/82424107
has text: Possible duplicate of [how to use socket fetch webpage use python](https://stackoverflow.com/questions/14140914/how-to-use-socket-fetch-webpage-use-python). That should explain everything you need to do!
score: 1
comment on: http://stackoverflow.com/q/47731485
type: QuestionComment
type: Comment

http://stackoverflow.com/q/47804333
accepted answer: http://stackoverflow.com/a/47804495
has body: I cant seem to find a solution anywhere, I have a script that runs a facial recognition script, but for some reason its telling me this exact error: File "box.py",line 98, in label,confidence = model.predict(crop) TypeError: 'int' object is not iterable My code thats actually important to the problem: import cv2 #Creates model to be the facerecognizer model = cv2.face.createEigenFaceRecognizer() #Defines the model as a training image taken previously model.load(config.TRAINING_FILE) #Initializes the camera as camera camera = config.get_camera() #Takes a picture using the camera image = camera.read() #Converts to grayscale image = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) #Results if it found a face result = face.detect_single(image) #Tells you to keep taking a picture until you have a face recognized if result is None: print 'Could not see face! Retake picture!' continue #gets dimensions of the face x,y,w,h = result #resizes the face crop = face.resize(face.crop(image, x, y, w, h)) #Tests face against the previously taken model label, confidence = model.predict(crop) **&lt;--- This is where the error is** #Im not 100% as to what this does, I got this part on the internet result = cv2.face.MinDistancePredictCollector() model.predict(crop) label = result.getLabel() confidence = result.getDist() Thats basically it (Theres obviously some more code set up inside and between but it isnt important or relevant to the issue, at least I dont think, Im using Python 2.7 with opencv 3.1.0 on a raspbian raspberry pi 3 if you need that information
upvote count: 0
downvote count: 2
answer count: 1
has answer: http://stackoverflow.com/a/47804495
favorite count: 0
type: Question
tagged with: opencv
has comment: http://stackoverflow.com/comment/82570232
has comment: http://stackoverflow.com/comment/82570144
has title: Int object not iterable? (Python)
has comment: http://stackoverflow.com/comment/82570289
score: -2
tagged with: python
has comment: http://stackoverflow.com/comment/82570302
type: AnsweredQuestion

http://stackoverflow.com/comment/82398642
comment on: http://stackoverflow.com/q/47718382
type: Comment
type: QuestionComment
has text: currently i am in 2.0
score: 0

http://stackoverflow.com/q/47727282
score: 1
has title: odoo the following fields are invalid
downvote count: 0
answer count: 1
upvote count: 1
favorite count: 0
type: Question
has body: In order to consolidate many order lines in one line "quantity, total_price", and try to print it using a button. I got this error the following fields are invalid order_line_consolidation, what I did: 1- created a wizard with a One2many field order_line_consolidation class sale_order_consolidation(models.TransientModel): _name = "sale.order.consolidation" _description = 'consolidation wizard' order_line_consolidation = fields.One2many('sale.order.line', 'order_id') 2- function to consolidate lines, list of dictionary consolidation 3- print function def print_quotation(self, cr, uid, ids, context=None): datas = {} if context is None: context = {} data = self.read(cr, uid, ids)[0] datas = { 'ids': [], 'model': 'sale.order', 'form': data } return {'type': 'ir.actions.report.xml', 'report_name': 'sale.report_saleorder', 'datas': datas }
linked to: http://stackoverflow.com/q/47517038
tagged with: odoo
tagged with: odoo-8
tagged with: python
accepted answer: http://stackoverflow.com/a/47798988
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47798988

http://stackoverflow.com/comment/82640699
type: AnswerComment
has text: @ShaoRanHuang did you see this one ? `df.content=df.content.reindex(df.target).values`
comment on: http://stackoverflow.com/a/47823472
score: 0
type: Comment

http://stackoverflow.com/a/66798838
has body: If you are using a spec file - add console=False to your EXE(...) command: exe = EXE(pyz, ... console=False )
downvote count: 0
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/47840633
type: Answer

http://stackoverflow.com/q/47729077
accepted answer: http://stackoverflow.com/a/47729126
type: AnsweredQuestion
has body: SocketServer Program This code is in raspberry: import SocketServer class MyTCPHandler(SocketServer.BaseRequestHandler): """ The request handler class for our server. It is instantiated once per connection to the server, and must override the handle() method to implement communication to the client. """ def handle(self): # self.request is the TCP socket connected to the client self.data = self.request.recv(1024).strip() print "{} wrote:".format(self.client_address[0]) print self.data # just send back the same data, but upper-cased self.request.sendall(self.data) if __name__ == "__main__": HOST, PORT = "localhost", 9999 # Create the server, binding to localhost on port 9999 server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler) # Activate the server; this will keep running until you # interrupt the program with Ctrl-C server.serve_forever() Socket Client Program This code is in my laptop: import socket import sys HOST, PORT = "192.168.1.40", 3360 data='Hello' #data = data.join(sys.argv[1:]) # Create a socket (SOCK_STREAM means a TCP socket) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: # Connect to server and send data sock.connect((HOST, PORT)) sock.sendall(data + "\n") # Receive data from the server and shut down received = sock.recv(1024) finally: sock.close() print "Sent: {}".format(data) print "Received: {}".format(received) Here the data sent should be received to server and sent back to client. This is the error: [Errno 10061] No connection could be made because the target machine actively refused it.
score: 0
tagged with: sockets
tagged with: python
has title: A simple socket server and client program using python
type: Question
tagged with: python-2.7
tagged with: client-server
answer count: 1
has answer: http://stackoverflow.com/a/47729126

http://stackoverflow.com/comment/82458260
type: Comment
score: 0
type: AnswerComment
has text: Thist would only fit the 4 example formats. The OP stated that he would have to deal with many more different formats ...
comment on: http://stackoverflow.com/a/47747807

http://stackoverflow.com/comment/82398037
has text: The issue with the ticks still appearing is with the `width` parameter. If I pass the argument `width=0`, no more ticks (labels still not aligned)
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47718341

http://stackoverflow.com/q/47775652
score: 0
has title: Concatenating multiple dimensionality reduction algorithms in Scikit-Learn
has comment: http://stackoverflow.com/comment/82530430
answer count: 1
has answer: http://stackoverflow.com/a/47792121
has body: The dataset consists of two 2-dimensional matrices X and Y, both with n rows (number of measurements) and mcolumns describing the corresponding features of each measurement. From the first matrix I would like to obtain the kernel PCA components. Additionally, using cross-decomposition I want to obtain the linear relations between both matrices using PLS and CCA. The goal is to use a Pipeline to create for each row n of the first matrix a feature vector consisting of its kernel PCA components and additionally of its projection on the latent spaces found by PLS and CCA, respectively. For each row of the matrix X its feature vector shall be classified by an SVM in a binary classification task, with the labels available as train_labels and test_labels. The Y matrix is thus only used for the computation of the joint latent space on which X is projected. What is the best way of achieving this, considering that Kernel PCA fits only on the X_train data (first matrix), while PLS and CCA fit on both X_train and Y_train (both matrices)? My code until now (not working): n_comp = 3 plsca = PLSCanonical(n_components=n_comp) cca = CCA(n_components=n_comp) kpca = KernelPCA(kernel="rbf", fit_inverse_transform=False, gamma=10, n_components=n_comp) x_tranf_kpca = kpca.fit_transform(X_train) svm = SVC(probability=True, class_weight='balanced', tol=0.0001) comb_feat_bna_sg = FeatureUnion([('pls_canonical', plsca), ('cca', cca)]) x_feats_bna_sg = comb_feat_bna_sg.fit(X_train, Y_train).transform(X_train) pipe_bna = Pipeline([('kpca', kpca)]) pipe_bna_sg = Pipeline([("x_feats_bna_sg", comb_feat_bna_sg)]) combined_features = FeatureUnion([('bna', pipe_bna), ('bna_sg', pipe_bna_sg)]) pipe = Pipeline([("features", combined_features), ('standardscaler', StandardScaler(copy=True, with_mean=True, with_std=True)), ("svm", svm)]) # Parameters of pipelines can be set using ‘__’ separated parameter names: param_pipe = dict(features__bna_sg__x_feats_bna_sg__pls_canonical__n_components=[1, 2], feature…
type: Question
tagged with: pipeline
has comment: http://stackoverflow.com/comment/82538020
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82540897
has comment: http://stackoverflow.com/comment/82534049
tagged with: grid-search
tagged with: scikit-learn
tagged with: python
linked to: http://stackoverflow.com/q/23895240

http://stackoverflow.com/a/47738714
has body: Given that the error occurs at this line self.ui.setupUi(self) and you assigned an Ui_MyDialog instance to self.ui, before self.ui = Ui_MyDialog() the error message should be mentioning class Ui_MyDialog and not MyDialog. So, either you misreported the error message or the error does not occur 'under MyDialog Class'. I also would point out: QWidget and derived classes have no setupUi method, themselves. Such method belongs to Ui_* classes, generated by uic, and is typically called from the constructor of a widget that inherits from a Ui_* class. So, if you want to call setupUi on MyDialog instances, MyDialog must inherit from Ui_MyDialog, in the first place. And you do call it in open_my_dialog: my_dialog.ui = MyDialog() my_dialog.ui.setupUi(my_dialog)
has comment: http://stackoverflow.com/comment/82438652
type: Answer
has comment: http://stackoverflow.com/comment/82437854
answers question: http://stackoverflow.com/q/47738634
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/q/47848641
tagged with: python
score: -1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82722265
upvote count: 0
has comment: http://stackoverflow.com/comment/82662432
has title: Django get_absolute_url in inclusion_tag Issue in Template
tagged with: templatetags
answer count: 1
has body: The error I'm getting is: NoReverseMatch at / Reverse for 'view_page' not found. 'view_page' is not a valid view function or pattern name. Basically I have a template tag for my app to display the navigation menu on each page, which is dynamic so I can't hard-code the links. I've written an inclusion tag and template: from django import template from ..models import Page register = template.Library() @register.inclusion_tag("tags/page_links.html") def page_links(): all_pages = Page.objects.all() return {'pages': all_pages} And the template tag html in the templates/tags directory: {% for page in pages %} {{ page.link_name }} {% endfor %} Each page object has an @permalink get_absolute_url() function to get the link. This works fine in other parts of the site but this inclusion tag does not. I'm using it like so in my base.html file (so I don't have to add it to each page): {% load static %} {% load page_tags %} ... Navigation: {% page_links %} ... But it appears that the pages are having trouble using the view_page view (which otherwise works) in the template tag. What am I missing here? EDIT: Added URLs and Model code urls.py: from django.contrib import admin from django.urls import path, include from django.conf.urls import url from .views import index, view_page urlpatterns = [ path('admin/', admin.site.urls), path('blog/', include('blog.urls')), url(r'^$', index), url(r'^(?P<slug>[^\.]+).html', view_page), ] And the Model: class Page(SortableMixin): title = models.CharField(max_length=80, unique=True) slug = models.SlugField(max_length=80, unique=True) link_name = models.CharField(max_length=40, unique=True) passthrough_page = models.BooleanField(default=False) passthrough_link = models.CharField(max_length=40, default=None, null=True) content = models.TextField(default=None, null=True) class Meta: ordering = ['the_order'] the_order = models.PositiveIntegerField(default=0, editable=False, db_index=True) @permalink def get_absolute_url(self): if not self.passthro…
tagged with: django
has answer: http://stackoverflow.com/a/47878294
has comment: http://stackoverflow.com/comment/82662413
accepted answer: http://stackoverflow.com/a/47878294
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82722506

http://stackoverflow.com/comment/82499183
type: AnswerComment
score: 0
has text: Adding the path I get the following error SyntaxError: <unicode error> 'unicodeescape' codec can't decode bytes in position 2-4: truncated \UXXXXXXXX escape
type: Comment
comment on: http://stackoverflow.com/a/47767556

http://stackoverflow.com/comment/82435885
has text: `If __name__=="__main__":` it has to be exactly like that written
comment on: http://stackoverflow.com/a/47737620
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47808162
tagged with: anaconda
has title: Can I use fitted ML model as a part of a function in scipy.optimize.minimize?
score: 1
answer count: 1
has body: Can I minimize this function using scipy.optimize? def obj(x): Budget = ((df['CPP TA 30'] / 30 * df['TVC']) * x).sum() x = (x - min_train_x) / (max_train_x-min_train_x) x = np.array([x]) return (0.05 * model.predict(x) - (1.7 * (Budget / 10**10)))[0][0] x0 = np.random.uniform(size = 23) x0 = (x0 / np.sum(x0)) * 1800 from scipy.optimize import minimize res = minimize(obj, x0)
upvote count: 1
tagged with: scipy
favorite count: 0
type: Question
tagged with: numpy
type: UnansweredQuestion
downvote count: 0
tagged with: python
has answer: http://stackoverflow.com/a/47808250
tagged with: optimization

http://stackoverflow.com/q/47846672
favorite count: 0
type: Question
tagged with: sympy
has body: I am trying to integrate the function I, which contains the Legendre polynomial leg_f: import math import numpy as np from mpmath import * from sympy import * from scipy.special import legendre n = 3 c = lambda h_c,z,R : (z**2+h_c**2)**0.5 c_supp = lambda h_c,z,R : (z**2+h_c**2)**(-n) x = lambda h_x,z,R : -4*R*(R-h_x)/c(h_x,z,R)**2 leg_f = lambda h_l,z,R : legendre(n-1,(1-0.5*x(h_l,z,R))/(1-x(h_l,z,R))**0.5) f_f_symb = lambda h_v,z,R : hyper((n, 0.5), (1), (-4*R*(R-h_v)/(z**2+h_v**2))) I = lambda h_i,z_i,R_i : c_supp(h_i,z_i,R_i)*(1-x(h_i,z_i,R_i))**(-n/2)*leg_f(h_i,z_i,R_i) h_i,z_i,R_i = symbols('h_i z_i R_i') int_result = integrate(I(h_i,z_i,R_i), (z_i, 0, np.inf)) But I get the error Traceback (most recent call last): File "test.py", line 99, in &lt;module&gt; int_result = integrate(I(h_i,z_i,R_i), (z_i, 0, np.inf)) File "/Users/Library/Python/2.7/lib/python/site-packages/sympy/integrals/integrals.py", line 1276, in integrate integral = Integral(*args, **kwargs) File "/Users/Library/Python/2.7/lib/python/site-packages/sympy/integrals/integrals.py", line 75, in __new__ obj = AddWithLimits.__new__(cls, function, *symbols, **assumptions) File "/Users/Library/Python/2.7/lib/python/site-packages/sympy/concrete/expr_with_limits.py", line 389, in __new__ obj.is_commutative = function.is_commutative # limits already checked AttributeError: 'poly1d' object has no attribute 'is_commutative' What could be the problem? Is it the right way to integrate such function in sympy?
tagged with: python
tagged with: symbolic-integration
has title: AttributeError: 'poly1d' object has no attribute 'is_commutative'
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/47851888
accepted answer: http://stackoverflow.com/a/47851888
answer count: 1
upvote count: 1
tagged with: polynomials
downvote count: 1

http://stackoverflow.com/q/47727042
tagged with: python
type: UnansweredQuestion
has body: I want use pygal to paint random rambled points and stored a svg file in run.py i are try use loop , every loop 1 times make some data, and assignment a variables my code: random_walk.py from random import choice class RandomWalk(): def __init__(self, num_points=10240): self.num_points = num_points self.x_values = [0] self.y_values = [0] def fill_walk(self): while len(self.x_values) &lt; self.num_points: x_direction = choice([1, -1]) x_distance = choice([0, 1, 2, 3, 4]) x_step = x_direction * x_distance y_direction = choice([1, -1]) y_distance = choice([0, 1, 2, 3, 4]) y_step = y_direction * y_distance next_x = self.x_values[-1] + x_step next_y = self.y_values[-1] + y_step self.x_values.append(next_x) self.y_values.append(next_y) run.py import pygal from random_walk import RandomWalk xy_sjmb = pygal.XY(stroke=False) xy_sjmb.title = "random rambled" a, b, c, d = [], [], [], [] all =[a, b, c, d] for i in range(len(all)): rw = RandomWalk() rw.fill_walk() ns =[(j, k) for j, k in (self.x_values, self.y_values) ] all[i-1] = ns xy_sjmb.add('a', a) xy_sjmb.add('b', b) xy_sjmb.add('c', c) xy_sjmb.add('d', d) xy_sjmb.render_to_file('sjmb.svg') but have error : NameError: name 'self' is not defined
tagged with: pygal
score: 0
answer count: 1
has title: ans ns =[(j, k) for j, k in (self.x_values, self.y_values) ] NameError: name 'self' is not defined
type: Question
has answer: http://stackoverflow.com/a/47727062

http://stackoverflow.com/comment/82552974
comment on: http://stackoverflow.com/q/47796004
type: Comment
score: 0
has text: Thanks. That's the way I'm looking for.
type: QuestionComment

http://stackoverflow.com/a/47805473
score: 1
has body: It seems that all I got wrong was that I was using the wrong CSS class. The correct one is suggested-action instead of needs-attention. If I replace that string in my original code I will get the following correct result:
downvote count: 0
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/47804129

http://stackoverflow.com/comment/82399945
comment on: http://stackoverflow.com/q/47719643
type: Comment
score: 0
type: QuestionComment
has text: I want converter *.obj ->*.dae format on my site. User upload obj-model, and my blender script makes dae file. Very simple.

http://stackoverflow.com/q/47778601
linked to: http://stackoverflow.com/q/36571560
type: AnsweredQuestion
tagged with: python-3.x
score: 0
has comment: http://stackoverflow.com/comment/82518441
answer count: 3
has comment: http://stackoverflow.com/comment/82518517
has comment: http://stackoverflow.com/comment/82518479
has body: I have list like this: test_list = ['test1','test2','test3'] I want to create from each element of the array a separate txt file and write content to that like in below: for test in test_list: print (test, outfile=testdir/test + '.txt') Obviously this code doesn't work. I would like to know how can I do this?
has answer: http://stackoverflow.com/a/47778985
has answer: http://stackoverflow.com/a/47778843
has comment: http://stackoverflow.com/comment/82518715
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/82518676
favorite count: 0
type: Question
has title: Create output files from lines of loop?
possible better answer: http://stackoverflow.com/a/47778843
accepted answer: http://stackoverflow.com/a/47778755
tagged with: python
has answer: http://stackoverflow.com/a/47778755
has comment: http://stackoverflow.com/comment/82518374

http://stackoverflow.com/comment/82471466
type: Comment
type: QuestionComment
has text: I actually added this to my code, however it is serialized in a 1dim array - is it possible to know the original dimensions to which it could be reshaped?
score: 0
comment on: http://stackoverflow.com/q/47750639

http://stackoverflow.com/q/47776828
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/82588506
score: 4
has comment: http://stackoverflow.com/comment/82588373
has comment: http://stackoverflow.com/comment/82588030
has comment: http://stackoverflow.com/comment/82588294
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82587981
has body: I've created a custom User model in models.py: class User(AbstractUser): pass Then, I've set AUTH_USER_MODEL to that model, in settings.py: AUTH_USER_MODEL = 'workoutcal.User' workoutcal is included in INSTALLED_APPS: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'workoutcal', 'rest_framework', 'rest_framework_mongoengine', ] And I've included this in admin.py: admin.site.register(User, UserAdmin) Then, I've ran makemigrations and migrate, and on the latter, I get this long error traceback: (workout) sahands-mbp:workout sahandzarrinkoub$ python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions, workoutcal Running migrations: Applying admin.0001_initial...Traceback (most recent call last): File "manage.py", line 22, in &lt;module&gt; execute_from_command_line(sys.argv) File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 204, in handle fake_initial=fake_initial, File "/Users/sahandzarrinkoub/Documents/Programming/We…
answer count: 1
downvote count: 0
has title: Django not finding custom user model in settings when migrating
accepted answer: http://stackoverflow.com/a/47813648
favorite count: 0
type: Question
upvote count: 4
has answer: http://stackoverflow.com/a/47813648
has comment: http://stackoverflow.com/comment/82588012
has comment: http://stackoverflow.com/comment/82587920
has comment: http://stackoverflow.com/comment/82588166

http://stackoverflow.com/comment/82592635
type: Comment
has text: Could you please edit your question and provide me the code you're working with ? I have trouble understanding your statements.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47809165

http://stackoverflow.com/comment/82620731
comment on: http://stackoverflow.com/q/47808093
type: QuestionComment
type: Comment
has text: I will check with the document link that you gave me.
score: 0

http://stackoverflow.com/a/47848699
answers question: http://stackoverflow.com/q/47846013
type: Answer
score: 0
has body: You need any of the maximum positions? To get the first one numpy.unravel_index(numpy.argmax(A), A.shape)) # (4, 0) Your example code however always finds the last occurrence, which can be done using numpy.unravel_index(A.size - 1 - numpy.argmax(A[::-1, ::-1]), A.shape) # (4, 4)

http://stackoverflow.com/q/47710681
has comment: http://stackoverflow.com/comment/82381355
has answer: http://stackoverflow.com/a/47710807
possible better answer: http://stackoverflow.com/a/47710807
downvote count: 1
favorite count: 0
tagged with: indexing
type: AnsweredQuestion
score: 0
tagged with: list
has title: Sum of specific elements of a list based on indexes from another list in python
answer count: 5
tagged with: sum
has body: I am trying to find the durations of all the notes with the same name in a music piece (from .xml), in python. I have 3 lists: scales = ['A', 'B', 'C'] #scales names notesAll = ['B', 'A', 'C', 'A', 'C', 'C'] #note names of the piece durationsAll = [1, 1.5, 1.5, 1, 1, 2] #duration of each note from notesAll list I want to sum all the durations from durationsAll list for all the notes with the same name. For example for all the 'A's from notesAll list, which equals to scales[0], I want something like: durationsAll[1] + durationsAll[3]= 1.5 + 1 = 2.5. I need a better solution than my attempt: for sc in scales: for ntPosition, nt in enumerate(notesAll): dtOfEach = 0 for dtPosition, dt in enumerate(durationsAll): if sc == nt: dtPosotion = ntPosition #I guess here is the problem dtOfEach = dtOfEach + dt The result I want would be: dtOfEach: 2.5 1 4.5
tagged with: python
has answer: http://stackoverflow.com/a/47710964
accepted answer: http://stackoverflow.com/a/47710964
type: Question
tagged with: for-loop
upvote count: 1
has answer: http://stackoverflow.com/a/47710958
has answer: http://stackoverflow.com/a/47710840
has answer: http://stackoverflow.com/a/47711316

http://stackoverflow.com/comment/82402499
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47720386
type: Comment
has text: I posted this as an additional question, I don't know if this would help you with the karma system on this site. https://stackoverflow.com/questions/47720965/how-to-show-the-ten-most-overdue-numbers-in-a-list

http://stackoverflow.com/a/47751976
has body: Just type python3 where you would have typed python. For example open repl type python3 run app.py program with python3.6 type python3 app.py
score: 7
type: Answer
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47751125
upvote count: 7
answers question: http://stackoverflow.com/q/47751125

http://stackoverflow.com/comment/82594928
type: AnswerComment
comment on: http://stackoverflow.com/a/47777017
has text: thanks for the comment - i can rule out scientific notation (as i generate the equation myself), but i get the point of using a parser beforehand - this made the problem much simpler!
type: Comment
score: 0

http://stackoverflow.com/a/47779606
type: Answer
downvote count: 0
upvote count: 1
score: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47779437
has body: First, you need to activate the virtual environment before installing the python package using pip by running: $ source my_virtual/bin/activate After installing your python packages in the virtual environment, you have to deactivate it my running: $ deactivate Try importing into python again. I hope this helps. Update: Run: import dicom Please see Getting Started with pydicom
answers question: http://stackoverflow.com/q/47779437

http://stackoverflow.com/comment/95706317
type: QuestionComment
has text: Yes and no : I found a workaround. I use the embedded template system in version > 0.13 (you can import bokeh elements/widget in different ), and use getbootstrap grid system to divide my sceen in non-equal parts, eventually with collapse function to simulate tab. I will try to upload some lines of code as example
score: 1
comment on: http://stackoverflow.com/q/47732408
type: Comment

http://stackoverflow.com/q/47812006
tagged with: latitude-longitude
linked to: http://stackoverflow.com/q/19412462
type: Question
linked to: http://stackoverflow.com/q/47534715
has comment: http://stackoverflow.com/comment/82590204
has title: Python - Using Lat-long to find the distance of a point to the closest train station (another point)
tagged with: python
tagged with: distance
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/82585347
answer count: 0
has body: I have found the average central point of each LSOA area in London and want to calculate the distance from this point to the nearest tube station (also a lat-long point) I need to do this in Python - any help would be welcome! I am new to Python and am not sure how to approach this CSV called 'Data': LSOA time lat long E01000907 51.5632 -0.1428 E01000908 51.5639 -0.14530 E01000909 51.5623 -0.149880 E01000912 51.5600 -0.155263 CSV called 'Tube': Station Latitude Longitude Abbey Road 51.53195199 0.003723371 Abbey Wood 51.4907841 0.12027197 Acton 51.51688693 -0.267689952 Acton Central 51.50875778 -0.263430199 Acton Town 51.50307144 -0.280302701 Earls Court 51.49135667 -0.194313809 Thanks in advance!
type: UnansweredQuestion
tagged with: euclidean-distance

http://stackoverflow.com/comment/82431621
comment on: http://stackoverflow.com/a/47730402
type: Comment
score: 0
type: AnswerComment
has text: Note that the reason for the error is because `xmlid_to_res_id` returns an integer, which doesn't have the ability to call a function (`create`), thus the error message. On the other hand, `self.env.ref('external_id')` returns the browse record object, which can call functions normally.

http://stackoverflow.com/a/47784370
type: Answer
answers question: http://stackoverflow.com/q/47784197
downvote count: 0
upvote count: 1
score: 1
has body: Not necessarily better, but often you can condense the loop into a use of any or all (for when you only care if a value was found) or next (for when you care about the value found). For example, to find the first item satisfying some test, or None if no such item exists, you can use two-arg next plus a generator expression: needle = next((x for x in haystack if isneedle(x)), None) if needle is not None: ... do stuff with needle ... else: ... no needle ... or roughly equivalently with one-arg next and exception handling: try: needle = next(x for x in haystack if isneedle(x)) except StopIteration: ... no needle ... else: ... do stuff with needle ... A realistic use case might be identifying a prime number via trial division. In that case, you don't care what factor you found, you just care that there was a factor, so you could write a testing function as: num = ... isnumprime = num &gt;= 2 and all(num % f != 0 for f in range(2, int(num ** 0.5) + 1)) for/else is a perfectly adequate way to do this (see other answers), but any/all/next (usually with generator expressions) can be cleaner in specific contexts.

http://stackoverflow.com/comment/82607669
score: 0
has text: please fix the indentation and quoting.
comment on: http://stackoverflow.com/q/47822369
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47862493
type: Answer
downvote count: 0
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47853809
has body: You get 'This operation would block forever' error because there is no greenlet to consume tasks in the queue, queue.join() just blocks until all greenlets have finished, then the exception raised. JoinableQueue is not needed here, use gevent.joinall() to wait for all the greenlets to finish: import gevent def main(): results = [] gs = [] for job_no in range(5): greenlet = .. gs.append(greenlet) gevent.joinall(gs) print 'All workers finished', results
accepted answer of: http://stackoverflow.com/q/47853809
score: 1

http://stackoverflow.com/comment/82681684
comment on: http://stackoverflow.com/a/47848132
type: Comment
has text: That is the kind of specific question which is well-suited for its own thread Stack Overflow, especially if you can't find an answer amongst existing questions. That said, here are a couple which I found with a few seconds of Googling: https://chrisalbon.com/python/pandas_selecting_rows_on_conditions.html https://stackoverflow.com/questions/27275236/pandas-best-way-to-select-all-columns-starting-with-x https://www.reddit.com/r/learnpython/comments/5zn29l/pandas_how_to_best_search_for_a_keyword_within/
score: 0
type: AnswerComment

http://stackoverflow.com/q/47775312
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82511614
has comment: http://stackoverflow.com/comment/82511674
duplicate of: http://stackoverflow.com/q/2960772
tagged with: python
has body: I am very new at coding so sorry if my code bellow annoys you lol but I was wondering if there is any way to include more than 1 argument in the raw_input() function so that I wouldn't have to do print("Do you want to filter numbers greater or lower that ", filt, "?") gorl = raw_input() rather than just gorl = raw_input("Do you want to filter numbers greater or lower than ", filt, "?") my entire code is import random import sys import os filt = int(raw_input("What number do you want your results to be filtered by?")) gorl = raw_input("Do you want to filter numbers greater or lower than ", filt, "?") ammvar = int(raw_input("How many variables do you want to filter?")) var_list = [] varnum = 1 while ammvar &gt; 0: var_list.append(int(raw_input("Variable ", varnum, ":"))) varnum + 1 ammvar - 1 and this is what eclipse returns when I run it ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ What number do you want your results to be filtered by?10 Do you want it to be filtered greater or lower?greater How many variables do you want to filter?7 Traceback (most recent call last): File "C:\Users\D\workspace\Simple\Sorter__init__.py", line 16, in var_list.append(int(raw_input("Variable ", varnum, ":"))) TypeError: raw_input() takes at most 1 argument (3 given) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
score: 0
tagged with: raw-input
has title: How to include more than one argument in raw_input()?
has comment: http://stackoverflow.com/comment/82511608
type: Question
has comment: http://stackoverflow.com/comment/82511716
answer count: 0
has comment: http://stackoverflow.com/comment/82511622

http://stackoverflow.com/a/47711464
score: 2
has body: There is a method for that. So if the data you want to change back is x scaler.inverse_transform(x) For more information you can have a look at the documentation: http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.MinMaxScaler.html
downvote count: 0
answers question: http://stackoverflow.com/q/47711184
upvote count: 2
type: Answer

http://stackoverflow.com/comment/82585860
comment on: http://stackoverflow.com/a/47811896
score: 0
has text: thaknyou you solved it but can you tell me why - how ListView give us object_list .. when i have objects_list above
type: AnswerComment
type: Comment

http://stackoverflow.com/a/47831410
type: Answer
accepted answer of: http://stackoverflow.com/q/47831379
answers question: http://stackoverflow.com/q/47831379
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: I think you can use instead Series: s = pd.Series(finalpred1, name='RF') numpy array: s = np.array(finalpred1) because there are different index values and not match, so output are NaNs But better is filter only RF column and skip first 50 rows: s = pd.read_csv('poly2_decpred_juneRF.csv', header=0, nrows=17, skiprows=range(1, 50), usecols=['RF'])
score: 1

http://stackoverflow.com/comment/82609998
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47823141
has text: What's the total range of ids?
score: 0

http://stackoverflow.com/q/47837891
type: Question
has answer: http://stackoverflow.com/a/47838664
has body: How can I do it with itertools or do it efficiently? The length of that list is 557845 #Generate all combinations of 4 elements and put on list listLol=list(map("".join, itertools.combinations('1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',4))) #This is too slow for a in listLol: for b in listLol: for c in listLol: for d in listLol: for e in listLol: cadena="SomeString-"+a+"-"+b+"-"+c+"-"+d+"-"+e
has comment: http://stackoverflow.com/comment/82640173
has comment: http://stackoverflow.com/comment/82639692
upvote count: 2
tagged with: python-itertools
has comment: http://stackoverflow.com/comment/82639878
has comment: http://stackoverflow.com/comment/82640284
tagged with: python
has comment: http://stackoverflow.com/comment/82639567
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82639762
score: 1
answer count: 1
has title: How can I generate all the combinations with the elements of an array and put in a formatted string with itertools instead of for?
has comment: http://stackoverflow.com/comment/82640028
has comment: http://stackoverflow.com/comment/82639997
accepted answer: http://stackoverflow.com/a/47838664
downvote count: 1
favorite count: 0

http://stackoverflow.com/a/47848619
type: Answer
upvote count: 3
accepted answer of: http://stackoverflow.com/q/47848500
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47848500
score: 3
has body: This doesn't have anything to do with "arrays"; you are being confused by the fact that you're trying to do everything inline when you define get_data. Actually, the problem is your call to md5(); as the error says, you can't pass a unicode string to that, you need to pass bytes. So, just encode the string: hash = md5(('%s-%s-%s-%s' % (ping, up, down, '297aae72')).encode('utf-8')).hexdigest()

http://stackoverflow.com/comment/82551412
has text: I said that because it's unusual to see a string in that form. It's also the form you see when you inspect a string instead of using `print` on it, so many people make that mistake.
comment on: http://stackoverflow.com/q/47782924
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/47853768
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/82671698
has body: No, that isn't possible. plot is first order function that operates on pd.DataFrame objects. Here, df would be the same thing. What you'd need to do is Load your dataframe using pd.read_* (usually, pd.read_csv(file)) and assign to df Now call df.plot So, in summary, you need - df = pd.read_csv(filename) ... # some processing here (if needed) df.plot() As for the question of whether this can be done "without loading data in memory"... you can't plot data that isn't in memory. If you want to, you can limit tha number of rows you read, or you can load it efficiently, by loading it in chunks. You can also write code to aggregate/summarise data, or sample it.
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47853750
has comment: http://stackoverflow.com/comment/82671620

http://stackoverflow.com/q/47708267
score: 0
tagged with: matplotlib
has answer: http://stackoverflow.com/a/47708752
has comment: http://stackoverflow.com/comment/82386504
type: Question
has title: My circles are not matching up with my planets orbits
tagged with: python
type: UnansweredQuestion
has body: My planets orbits are not matching up with my circular paths im plotting of the orbits, I have matched in my for loop the distance for every planet with the distance they are from the center.(image is attached) from pylab import * from matplotlib.animation import * Here is where I am defining the circes I will plot to show the paths of the orbits at the "def circle..." def circle(x0,y0,R,N) : ''' create circle, given center x0,y0, input radius R, and number of points N, then output arrays of x and y coordinates ''' theta = linspace(0.0,2.0*pi,N) x = R * cos(theta) + x0 y = R * sin(theta) + y0 return x,y a= array([.39,.72,1,1.52,5.20,9.54,19.2,30.1]) #astronomical units of #the planets in order of the planets(i.e mercury, venus, earth,mars...) period = a**(3.0/2.0) I am taking the distane of the planets and inputting them in array, to be able to use a for loop to graph the circles. #distance of the planets d= array([390,790,980, 1520,5200,9540,19200,30100])#same order of the #planets as well #attributes of the sun x0 =0 y0 = 0 r_s=70*1.2#actual earth radius is 695e6 #radius of the planets r_Ear = 63.781#e in m {for all the planets} r_Merc= 24 r_Ven = 60 r_Mars= 33.9 r_Jup = 700 r_Sat = 582 r_Ura = 253 r_Nep = 246 the actual distance of the planets #Distance of the planets d_Ear = 1000#152 d_Merc= 390#70 d_Ven = 790#109 d_Mars= 1520#249 d_Jup = 5200#816 d_Sat = 9540#1514 d_Ura = 19200#3003 d_Nep = 30100#4545 fig = plt.figure() ax = plt.axes(xlim=(-1e4-5000, 1e4+5000), ylim=(-1e4-5000, 1e4+5000), aspect=True) This is where I am looping over, to plot 8 circles. Theres a link here to see the plot I have generated. for i in range(8) : x, y = circle(0.0,0.0,d[i],10000) # orbit plot(x,y,':k') [enter image description here][1] The rest are the patches of the planets and the FuncAnimation. Sun = plt.Circle((x0, y0), radius=r_s, ec='yellow', fc='yellow', lw=3) Mercury = plt.Circle((0, 0), radius=r_Merc, ec='brown', fc='brown', lw=3) Venus = plt.Circle((0, 0), radius=r_Ven, ec=…
answer count: 1

http://stackoverflow.com/q/47784002
has body: What is the list comprehension expression that would accomplish the same thing as: seq_len = list(map(len, fasta_file.readlines()))
answer count: 2
downvote count: 4
upvote count: 0
type: UnansweredQuestion
has title: Convert map to list comprehension
has comment: http://stackoverflow.com/comment/82529949
score: -4
has comment: http://stackoverflow.com/comment/82531641
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47784026
has answer: http://stackoverflow.com/a/47786242
tagged with: python
tagged with: list-comprehension

http://stackoverflow.com/q/47778854
answer count: 2
has answer: http://stackoverflow.com/a/55127626
has body: Before seeing: RuntimeError: IOError: [Errno 2] No such file or directory: '/beam-temp-andrew_mini_vocab-..../......andrew_mini_vocab' [while running .....] in my apache beam python dataflow job I see this error logged: A setup error was detected in __. Please refer to the worker-startup log for detailed information. ` I've found the worker startup logs and the Payload error is: Failed to install packages: failed to install SDK: exit status 2 The error is not specific enough for me to debug. Any insight into what SDK isn't getting loaded? My imports for the job are extremely basic: from __future__ import absolute_import from __future__ import division import argparse import logging import re import apache_beam as beam from apache_beam.io import WriteToText from apache_beam.options.pipeline_options import PipelineOptions from apache_beam.options.pipeline_options import SetupOptions from apache_beam.pvalue import AsDict
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82563684
score: 6
upvote count: 6
has title: Python apache beam dataflow worker-startup error: Failed to install packages: failed to install SDK: exit status 2
tagged with: apache-beam
tagged with: python
tagged with: google-cloud-dataflow
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/96965830
has answer: http://stackoverflow.com/a/69071150
downvote count: 0
tagged with: google-cloud-platform
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82588887

http://stackoverflow.com/q/47837571
type: UnansweredQuestion
upvote count: 1
tagged with: python
has body: I wish to programmatically interact with spreadsheets from python/openpyxl. However, I do not want to deal with formulae in openpyxl; in fact, I seek a "frozen" formula-to-value approach. This includes preserving type fidelity, meaning numerics are distinct from strings (and by formatting convention, I can distinguish numerics from dates). So my goal is some sort of script/program, in any language, where I can do this: $ force2value --input original.xlsx --output frozen.xlsx The net effect is exactly as if I had opened original.xlsx in Excel and done the whole select cells, copy, and repaste special as values only, for each sheet, followed by Save As. If the approach is some sort of wild macro-ish thing that can be "fed" from the command line, that's OK too.
tagged with: excel
has title: Convert Excel spreadsheet formulas to values from command line
score: 1
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/47837746
favorite count: 0
type: Question
tagged with: automation

http://stackoverflow.com/comment/82481305
type: Comment
has text: How do you use the models in core?
type: QuestionComment
comment on: http://stackoverflow.com/q/47759895
score: 0

http://stackoverflow.com/a/47771938
answers question: http://stackoverflow.com/q/47771854
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/47771854
has body: A high level solution would involve grouping adjacent elements. There are more than one ways to do this. I've outlined one with pure python using itertools, and another with pandas since that's what you've tagged the question with. Python itertools.groupby from itertools import groupby r = [tuple(g) for _, g in groupby(lst)] r [(1.0, 1.0), (-1.0, -1.0, -1.0, -1.0, -1.0), (1.0,), (-1.0, -1.0, -1.0, -1.0, -1.0), (1.0,), (-1.0, -1.0), (1.0,), (-1.0, -1.0), (1.0,), (-1.0, -1.0, -1.0), (1.0, 1.0, 1.0), (-1.0, -1.0), (1.0,), (-1.0,), (1.0,), (-1.0,), (1.0, 1.0, 1.0, 1.0), (-1.0, -1.0), (1.0, 1.0, 1.0, 1.0, 1.0), (-1.0, -1.0, -1.0, -1.0), (1.0,), (-1.0,), (1.0,), (-1.0,), (1.0,), (-1.0,), (0.0,), (1.0, 1.0), (-1.0,), (1.0,), (-1.0, -1.0, -1.0, -1.0, -1.0, -1.0)] If you want unique values from groupby, make a slight change to groupby call - r = [i for i, _ in groupby(lst)] Pandas groupby + shift + cumsum + apply x = pd.Series(lst) r = x.groupby(x.ne(x.shift()).cumsum()).apply(tuple) r 1 (1.0, 1.0) 2 (-1.0, -1.0, -1.0, -1.0, -1.0) 3 (1.0,) 4 (-1.0, -1.0, -1.0, -1.0, -1.0) 5 (1.0,) 6 (-1.0, -1.0) 7 (1.0,) 8 (-1.0, -1.0) 9 (1.0,) 10 (-1.0, -1.0, -1.0) 11 (1.0, 1.0, 1.0) 12 (-1.0, -1.0) 13 (1.0,) 14 (-1.0,) 15 (1.0,) 16 (-1.0,) 17 (1.0, 1.0, 1.0, 1.0) 18 (-1.0, -1.0) 19 (1.0, 1.0, 1.0, 1.0, 1.0) 20 (-1.0, -1.0, -1.0, -1.0) 21 (1.0,) 22 (-1.0,) 23 (1.0,) 24 (-1.0,) 25 (1.0,) 26 (-1.0,) 27 (0.0,) 28 (1.0, 1.0) 29 (-1.0,) 30 (1.0,) 31 (-1.0, -1.0, -1.0, -1.0, -1.0, -1.0) dtype: object To find unique values, you can use mean or unique. - r = x.groupby(x.ne(x.shift()).cumsum()).mean() I've used mean, but they do the same thing.

http://stackoverflow.com/a/47709059
upvote count: 1
has body: a matter of personal style. you could also do ingredients = ingredients if ingredients else ['ham', 'ham', 'bacon', 'ham'] just depends on who will be reading your code. personally i'm fine with your second ingredients = ingredients or ['ham', 'ham', 'bacon', 'ham']
score: 1
type: Answer
answers question: http://stackoverflow.com/q/47708630
downvote count: 0

http://stackoverflow.com/comment/82429438
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47734437
has text: What happens if there are 10 adjacent `7`s? You need to filter the groups before `max`ing.

http://stackoverflow.com/q/47848525
has comment: http://stackoverflow.com/comment/82676555
has answer: http://stackoverflow.com/a/47849142
tagged with: arrays
downvote count: 0
tagged with: python
tagged with: c++
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47849142
upvote count: 5
answer count: 1
has body: This is my first question on this site. First of all, I need to make a module with one function for python in C++, which must work with numpy, using &lt;numpy/arrayobject.h&gt;. This function takes one numpy array and returns two numpy arrays. All arrays are one-dimensional. The first question is how to get the data from a numpy array? I want to collect the information from array in std::vector, so then I can easily work with it C++. The second: am I right that function should return a tuple of arrays, then user of my module can write like this in python: arr1, arr2 = foo(arr) ? And how to return like this? Thank you very much.
has comment: http://stackoverflow.com/comment/82661472
favorite count: 0
type: Question
tagged with: numpy
tagged with: python-3.x
score: 5
has title: How to get data from np.array to std::vector in c++ using <numpy/arrayobject.h>?

http://stackoverflow.com/q/47782780
type: Question
has comment: http://stackoverflow.com/comment/82527075
has comment: http://stackoverflow.com/comment/82527416
has comment: http://stackoverflow.com/comment/82526965
possible better answer: http://stackoverflow.com/a/78713464
has comment: http://stackoverflow.com/comment/82527284
downvote count: 0
has comment: http://stackoverflow.com/comment/82527231
has answer: http://stackoverflow.com/a/78713464
has answer: http://stackoverflow.com/a/47784383
tagged with: python
score: 11
has answer: http://stackoverflow.com/a/47782913
has body: Below folder structure of my application: rootfolder /subfolder1/ /subfolder2 /subfolder3/test.py my code inside of the subfolder3. But I want to write output of the code to subfolder1. script_dir = os.path.dirname(__file__) full_path = os.path.join(script_dir,'/subfolder1/') I would like to know how can I do this wihout importing full path to directory.
has title: Python access to project root directory
has comment: http://stackoverflow.com/comment/82527186
has comment: http://stackoverflow.com/comment/82527074
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/131362128
has comment: http://stackoverflow.com/comment/82527019
has comment: http://stackoverflow.com/comment/82527080
answer count: 3
has comment: http://stackoverflow.com/comment/82527049
has comment: http://stackoverflow.com/comment/82526951
accepted answer: http://stackoverflow.com/a/47782913
linked to: http://stackoverflow.com/q/25389095
has comment: http://stackoverflow.com/comment/82526931
has comment: http://stackoverflow.com/comment/82527323
has comment: http://stackoverflow.com/comment/82527054
has comment: http://stackoverflow.com/comment/82527053
has comment: http://stackoverflow.com/comment/82526945
upvote count: 11
has comment: http://stackoverflow.com/comment/82527006
favorite count: 0

http://stackoverflow.com/comment/82612079
type: AnswerComment
has text: This is print content: ImmutableMultiDict([])
comment on: http://stackoverflow.com/a/47809949
score: 0
type: Comment

http://stackoverflow.com/q/47784396
tagged with: date
has title: Date format to Day
score: -3
linked to: http://stackoverflow.com/q/8380389
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47784546
upvote count: 0
downvote count: 3
has answer: http://stackoverflow.com/a/47784546
tagged with: days
has body: Currently, I have a list of Date and time (2017-12-13 01:05:44) in my dataframe. Can anyone please help me to create a new column ('Day') in my dataframe, with a list of days corresponding to my date columns. *Can Ignore the time. For example, the output: Date, Day 2017-12-13 01:05:44, Wednesday 2017-12-12 01:02:13, Tuesday 2017-12-11 01:00:55, Monday 2017-12-10 00:59:31, Sunday 2017-12-09 00:58:23, Saturday
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/82530242
type: Question
has comment: http://stackoverflow.com/comment/82649625
has comment: http://stackoverflow.com/comment/82530324
tagged with: python

http://stackoverflow.com/comment/82676439
type: Comment
has text: @babygame0ver I don't think my code will add any input in this case. It is a classic usage of Cmd module. When the script A is activated it expects commands to be given to it. It is comfortable for human users but tricky for activation from other scripts. I will look into os.system() to see how I can use it for my purposes. Thanks
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47854012

http://stackoverflow.com/a/47708755
answers question: http://stackoverflow.com/q/47707608
score: 0
has body: It is possible, but it may cause conflicts with table names, constraint names, sequence names and other names which are depend on ORM naming strategy.
type: Answer

http://stackoverflow.com/a/47721192
has body: Try this: df1= df1[df1['Count1'] &lt; 5 &amp; df1['Count2'] &lt; 5]
downvote count: 0
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/47720990
type: Answer

http://stackoverflow.com/q/47775026
has title: Choose various entries from a list if its key occurs in another list and add strings together
has body: I have a question regarding my dataframe. In one column, for each row, I have a list of relevant persons (personlist) and a list of persons' speeches (speech) (both relevant and irrelevant persons' speeches). Now, I want to choose the speeches of the relevant persons (from personlist), where the info whether they are relevant is given within the list (personlist) in another column and subsequently add all their speeches together while ignoring the irrelevant speeches. So one column provides the list with last names I am looking for and the other column provides a list of all speakers (first and last name) and their speech and I want to create a new column where the speeches of the relevant persons are added (separated by a space) and stored in the respective row. So my initial dataset looks like this: ticker year quarter personlist jobposition speech xx 2009 1 ("Angle", "Barth") CEO [("Mike Angle", "Thank you"), ("Barbara Barth", "It is"), ("Will Cook", "Yes, true")] xx 2009 1 ("Angle", "Barth") CFO [("Mike Angle", "Thank you"), ("Barbara Barth", "It is"), ("Will Cook", "Yes, true")] xx 2009 2 ("Angle", "Barth") CEO [("Mike Angle", "I am surprised"), ("Barbara Barth", "So am I"), ("Will Cook", "Me too")] xx 2009 2 ("Angle", "Barth") CFO [("Mike Angle", "I am surprised"), ("Barbara Barth", "So am I"), ("Will Cook", "Me too")] yy 2008 3 ("Cruz", "Dolm") CEO [("Damien Cruz", "Hello"), ("Lara Dolm", "Nice to meet you"), ("Lara Bel", "You too")] yy 2008 3 ("Cruz", "Dolm") CFO [("Damien Cruz", "Hello"), ("Lara Dolm", "Nice to meet you"), ("Lara Bel", "You too")] For row one for instance, I want to check each key-value pair whether the first list entry ends with one of the last names in personlist, if no continue, if yes, take the speech part (i.e. value to the entry) and store it in new column, repeat it for the others and add the matches together. As such, I want the following dataset (I hid the initial column speech here, but it should still be contained, so I do not wa…
type: Question
tagged with: pandas
tagged with: python
has answer: http://stackoverflow.com/a/47775923
score: 0
tagged with: list
type: UnansweredQuestion
answer count: 1

http://stackoverflow.com/comment/83362288
comment on: http://stackoverflow.com/q/47734969
has text: @evehsu They are actually quite different. Assign `tmp2[0] = 333` and print `tmp1` and `print tmp1_1` again.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47701090
has comment: http://stackoverflow.com/comment/82362765
has comment: http://stackoverflow.com/comment/82362900
has comment: http://stackoverflow.com/comment/82362796
has title: Input to a file in an array and then pulling info from file later in python
score: 0
has comment: http://stackoverflow.com/comment/82362088
has answer: http://stackoverflow.com/a/47701145
answer count: 1
tagged with: python
type: Question
has body: I am trying to get a program built for a class project and just need help understanding a concept and how it should work. I need to do this: At the end of each game, the program asks you to record the scores for each team member. You type in their first name and that person's score for the game on a single line. Should print the lists into columns of name and scores entered, highest score to lowest score and alphabetical order. My issue is that if I go in and write a file and put the information in, I can pull from that file correctly but I can't get a user input into a file and then pull from that. If anyone could help me understand that. Sorry this is kinda long. # Input trying to figure out scoring = [] n = int(input("Enter the amount: ")) print("Write the name followed by a ',' and then the score") with open("scores.txt", 'w') as the_file: for i in range(0, n): name = input("Enter the Name: ") score = input("Enter the Score: ") name = the_file.write(name) score = the_file.write(score) # output scores = [] with open("scores.txt", 'r') as f: for line in f: name, score = line.split(',') score = int(score) scores.append((name, score)) list.sort(scores, reverse=True, key=lambda s: s[1])
type: UnansweredQuestion
tagged with: arrays

http://stackoverflow.com/a/47710935
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47710323
downvote count: 0
answers question: http://stackoverflow.com/q/47710323
type: Answer
has body: You have defined this field as a one to one relationship. class ProductBidPrice(BaseModel): product = models.ForeignKey(Product) bid = models.ForeignKey(Bid) price_income = models.OneToOneField(ProductIncomePriceHistory) So only one ProductBidPrice can have one ProductIncomePriceHistory the error is probably raised because you already have a ProductBidPrice with the ProductIncomePriceHistory.id you are trying to use. I believe you want a many to on relationship, if I am interpreting what you are trying to do correctly.
score: 2
upvote count: 2

http://stackoverflow.com/comment/99437127
score: 0
comment on: http://stackoverflow.com/q/47745541
has text: I notice someone attempting same in python [here](https://github.com/srijan-mishra/Shadow-Removal) But they appeared to stop at similar chromaticity step as you reached above. Two interesting papers from 2012: [Shadow Detection: A Survey and Comparative Evaluation of Recent Methods](https://arxiv.org/pdf/1304.1233.pdf) Covering following methods - **chromacity-based, physical, geometry-based, texture-based.** [Shadow Removal for Aerial Imagery by Information Theoretic Intrinsic Image Analysis](https://static.googleusercontent.com/media/research.google.com/en//pubs/archive/37743.pdf) From 3 goo
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47867891
answers question: http://stackoverflow.com/q/47765716
accepted answer of: http://stackoverflow.com/q/47765716
downvote count: 0
type: Answer
has body: @ags29 Thanks for your suggestion. Here is the Answer : After creating the Dataframe by reading the file as mentioned above, we have to replace Null values with some value, in this case I am replacing it with NA. InfoWoNull = Info.fillna({'Comments':'NA'}) Then, Create UDF to find ASCII value for each character in the string using ORD function. Output will be array of integer. from pyspark.sql import functions as F from pyspark.sql import types as t from pyspark.sql.types import ArrayType, IntegerType russ_ord=F.udf(lambda x: [ord(a) for a in x],t.ArrayType(IntegerType())) Create Filter function to filter out the value based on ASCII character greater than 127. def russian_filter(x): for index in range(len(x)): if x[index] &gt; 127: return True return False filter_udf = F.udf(russian_filter, BooleanType()) Use it in the final step like below. Info_rus = InfoWoNull.filter(filter_udf(russ_ord('SearchParams')) == 'true') Info_rus.show()
score: 1
type: AcceptedAnswer
upvote count: 1

http://stackoverflow.com/q/47800091
has body: I am a real newbie in C++. I teach High School Tech Apps courses but my principal has given me a programming class, mid year. I am doing ok by staying one step ahead of the class but I have a program turned in by a student that does not work and I can't see what is wrong. If I paste this directly into the Python command line, it works fine. If I open it in IDLE it does not work. Here is the script: """ For this program to work as planned use the keys W,A,D, and SPACE W will draw a circle A will draw a triangle D will end the program and Space will move the turtle """ from turtle import * #this draws you a red circle def draw_circle(): # This function draws a red circle color("red") width(10) penup() goto(-200, -200) pendown() circle(20) #this draws a green trinangle def draw_triangle(): # This function draws a green triangle color("green") width(10) penup() goto(0, -200) pendown() right(180) circle(15, steps =3) #this moves the turtle def move_turt(): penup() goto(-200, 100) pendown #this ends the program def end(): bye() draw_circle() draw_triangle() listen() onkey(move_turt, "space") onkey(draw_circle, "w") onkey(draw_triangle, "a") onkey(end, "d")
tagged with: turtle-graphics
score: 0
has title: Script runs in Python but not in Python shell
has comment: http://stackoverflow.com/comment/83230978
tagged with: python
tagged with: python-idle
type: UnansweredQuestion
answer count: 1
type: Question
has comment: http://stackoverflow.com/comment/82666206
has answer: http://stackoverflow.com/a/47802483

http://stackoverflow.com/a/47855058
has body: Well your dictionary is structured quite weird.. But appending to a list within a dictionary is no stranger than appending directly to a list.. myDict = {"Sue": ["Connor"]} myDict["Sue"].append("Barbara") print(myDict) &gt;&gt;&gt; {"Sue": ["Connor", "Barbara"]}
score: -1
upvote count: 0
downvote count: 1
answers question: http://stackoverflow.com/q/47854980
has comment: http://stackoverflow.com/comment/82675107
has comment: http://stackoverflow.com/comment/82674865
has comment: http://stackoverflow.com/comment/82675229
type: Answer

http://stackoverflow.com/q/47705919
type: Question
accepted answer: http://stackoverflow.com/a/47706478
has body: I have a fitted a KMeans with scaled features using StandardScaler. The issue is the cluster centeroids are also scaled. Is it possible to get the original centeroids programmatically ? import pandas as pd import numpy as np from pyspark.ml.feature import VectorAssembler from pyspark.ml.feature import StandardScaler, StandardScalerModel from pyspark.ml.clustering import KMeans from sklearn.datasets import load_iris # iris data set iris = load_iris() iris_data = pd.DataFrame(iris['data'], columns=iris['feature_names']) iris_df = sqlContext.createDataFrame(iris_data) assembler = VectorAssembler( inputCols=[x for x in iris_df.columns],outputCol='features') data = assembler.transform(iris_df) scaler = StandardScaler(inputCol="features", outputCol="scaledFeatures", withStd=True, withMean=False) scalerModel = scaler.fit(data) scaledData = scalerModel.transform(data).drop('features').withColumnRenamed('scaledFeatures', 'features') kmeans = KMeans().setFeaturesCol("features").setPredictionCol("prediction").setK(3) model = kmeans.fit(scaledData) centers = model.clusterCenters() print("Cluster Centers: ") for center in centers: print(center) Here I want to get the centeroids in original scale. The centeroids are scaled. [ 7.04524479 6.17347978 2.50588155 1.88127377] [ 6.0454109 7.88294475 0.82973422 0.31972295] [ 8.22013841 7.19671468 3.13005178 2.59685552]
has title: Spark get the actual cluster centeroids with StandardScaler
tagged with: k-means
tagged with: pyspark
tagged with: python
has answer: http://stackoverflow.com/a/47706478
upvote count: 2
type: AnsweredQuestion
score: 2
downvote count: 0
tagged with: apache-spark
answer count: 1
favorite count: 0

http://stackoverflow.com/a/47731429
score: 2
has comment: http://stackoverflow.com/comment/82676455
has comment: http://stackoverflow.com/comment/82675454
has comment: http://stackoverflow.com/comment/82676311
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82646046
accepted answer of: http://stackoverflow.com/q/47730524
has body: I have taken Generic Human’s answer, slightly modified it to solve your problem. You need to copy these 125k words, sorted by frequency into a text file, name the file words-by-frequency.txt. from math import log # Build a cost dictionary, assuming Zipf's law and cost = -math.log(probability). with open("words-by-frequency.txt") as f: words = [line.strip() for line in f.readlines()] wordcost = dict((k, log((i+1)*log(len(words)))) for i,k in enumerate(words)) maxword = max(len(x) for x in words) def infer_spaces(s): """Uses dynamic programming to infer the location of spaces in a string without spaces.""" # Find the best match for the i first characters, assuming cost has # been built for the i-1 first characters. # Returns a pair (match_cost, match_length). def best_match(i): candidates = enumerate(reversed(cost[max(0, i-maxword):i])) return min((c + wordcost.get(s[i-k-1:i], 9e999), k+1) for k,c in candidates) # Build the cost array. cost = [0] for i in range(1,len(s)+1): c,k = best_match(i) cost.append(c) # Backtrack to recover the minimal-cost string. out = [] i = len(s) while i&gt;0: c,k = best_match(i) assert c == cost[i] out.append(s[i-k:i]) i -= k return " ".join(reversed(out)) Running the function with the input: messy_txt = "T he administrati on is doing bad things, and not fulfilling what it prom ised" print(infer_spaces(messy_txt.lower().replace(' ', '').replace(',', '')).capitalize()) The administration is doing bad things and not fulfilling what it promised &gt;&gt;&gt; Edit: The code below doesn't require the text file and works just for your input i.e., "T he administrati on is doing bad things, and not fulfilling what it prom ised" from math import log # Build a cost dictionary, assuming Zipf's law and cost = -math.log(probability). words = ["the", "administration", "is", "doing", "bad", "things", "and", "not", "fulfilling", "what", "it", "promised"] wordcost = dict((k, log((i+1)*log(len(words)))) for i,k in enumerate(words)) maxword = max(len(x) for …
has comment: http://stackoverflow.com/comment/82646012
has comment: http://stackoverflow.com/comment/82646077
has comment: http://stackoverflow.com/comment/82825819
answers question: http://stackoverflow.com/q/47730524
upvote count: 2
has comment: http://stackoverflow.com/comment/82646262
downvote count: 0
type: Answer

http://stackoverflow.com/q/47780312
tagged with: reduce
type: Question
tagged with: pandas
type: AnsweredQuestion
has title: Pandas dataframe reduce / add rows based on key
tagged with: dataframe
score: 1
possible better answer: http://stackoverflow.com/a/47780563
has answer: http://stackoverflow.com/a/47780563
favorite count: 0
accepted answer: http://stackoverflow.com/a/47780426
has answer: http://stackoverflow.com/a/47780426
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/82521889
upvote count: 1
tagged with: python
has body: I'm struggling a bit with kind of simple problem. Hope there is also a simple solution for it. My Dataframe looks like this. DataFrame: 8 buy 4 7 sell 1 6 buy 1 5 sell 3 4 sell 10 3 buy 100 2 buy 110 1 buy 120 Is there a way to add same orders that come after each other? So transform the df to: DataFrame: 8 buy 4 7 sell 1 6 buy 1 4 sell 3 + 10 1 buy 100 + 110 + 120 My problem is a bit more complicated. I think it can be solved with iterrows but was hoping that there is a more simple solution.

http://stackoverflow.com/comment/82429451
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47732108
score: 0
has text: you could do it but in reality, each feature (column) is scaled based on its max and min values and not based on the dataset's min max. I think that in all cases, you need to scale its column according to its min and max values. So you should be using MinMaxScaler

http://stackoverflow.com/q/47784693
favorite count: 0
has title: Optional Parameters in **kwargs
type: Question
tagged with: python-3.x
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/60030693
tagged with: python
has body: I am not able to handle to pass optional parameters in python **kwargs def ExecuteyourQuery(self, queryStatement, *args, **kwargs): if self.cursorOBJ is not None: resultOBJ = self.cursorOBJ.execute(queryStatement, *args,**kwargs) self.resultsVal = resultOBJ.fetchall() The below statement works fine when I am calling the function ExecuteyourQuery('select * from item_table where x = :x and y:y', x, y) But when I give an extra argument which is not mentioned in the query, like ExecuteyourQuery('select * from item_table where x = :x and y:y', x, y, z) It returns 0 as output
has answer: http://stackoverflow.com/a/47785854
tagged with: python-2.7
answer count: 2
has comment: http://stackoverflow.com/comment/82531252
tagged with: sql
has comment: http://stackoverflow.com/comment/82531396
score: 1
tagged with: cx-oracle
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/47734100
answers question: http://stackoverflow.com/q/47734068
type: Answer
score: 0
has body: You can split the string and check if all characters are uppercase: import re s = """ First Name: MICKEY One to four lines of cruft go here Last Name: MOUSE More cruft goes here """ final_data = ' '.join(i for i in s.split('\n') if re.findall('^[A-Z]+$', i)) Output: 'MICKEY MOUSE' Or, a pure regex solution: new_data = ' '.join(re.findall('(?&lt;=)[A-Z]+(?=\n)', s)) Output: 'MICKEY MOUSE'

http://stackoverflow.com/comment/82414539
type: AnswerComment
comment on: http://stackoverflow.com/a/47725673
type: Comment
has text: I seem to be getting pandas.errors.ParserError: Error tokenizing data. C error: Expected 1 fields in line 4, saw 2
score: 0

http://stackoverflow.com/comment/82471947
comment on: http://stackoverflow.com/a/47743125
has text: Hey, thank you for your contribution. Did you see my edit? Isn't this what I am also doing ? Or is the fact that I am changing the name of the layers according name='conv1_2_1'+str(brh) with brh = 1 for lleft and 2 for right breaks the logic?
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/82522864
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47780631
type: Comment
has text: @juanpa.arrivillaga Explain to me how it is completely irrelevant. All operations on immutable values return a new value, for example `a = 5; x = a; a -= 1`. If `int`s were mutable, then both would be `4`.

http://stackoverflow.com/q/47790854
has comment: http://stackoverflow.com/comment/82545264
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52772493
has comment: http://stackoverflow.com/comment/82543572
score: 2
upvote count: 3
has body: I just started learning machine learning, when practicing one of the task, I am getting value error, but I followed the same steps as the instructor does. I am getting value error, please help. dff Country Name 0 AUS Sri 1 USA Vignesh 2 IND Pechi 3 USA Raj First I performed labelencoding, X=dff.values label_encoder=LabelEncoder() X[:,0]=label_encoder.fit_transform(X[:,0]) out: X array([[0, 'Sri'], [2, 'Vignesh'], [1, 'Pechi'], [2, 'Raj']], dtype=object) then performed One hot encoding for the same X onehotencoder=OneHotEncoder( categorical_features=[0]) X=onehotencoder.fit_transform(X).toarray() I am getting the below error: ValueError Traceback (most recent call last) &lt;ipython-input-472-be8c3472db63&gt; in &lt;module&gt;() ----&gt; 1 X=onehotencoder.fit_transform(X).toarray() C:\ProgramData\Anaconda3\lib\site-packages\sklearn\preprocessing\data.py in fit_transform(self, X, y) 1900 """ 1901 return _transform_selected(X, self._fit_transform, -&gt; 1902 self.categorical_features, copy=True) 1903 1904 def _transform(self, X): C:\ProgramData\Anaconda3\lib\site-packages\sklearn\preprocessing\data.py in _transform_selected(X, transform, selected, copy) 1695 X : array or sparse matrix, shape=(n_samples, n_features_new) 1696 """ -&gt; 1697 X = check_array(X, accept_sparse='csc', copy=copy, dtype=FLOAT_DTYPES) 1698 1699 if isinstance(selected, six.string_types) and selected == "all": C:\ProgramData\Anaconda3\lib\site-packages\sklearn\utils\validation.py in check_array(array, accept_sparse, dtype, order, copy, force_all_finite, ensure_2d, allow_nd, ensure_min_samples, ensure_min_features, warn_on_dtype, estimator) 380 force_all_finite) 381 else: --&gt; 382 array = np.array(array, dtype=dtype, order=order, copy=copy) 383 384 if ensure_2d: ValueError: could not convert string to float: 'Raj' Please edit my question is anything wrong, thanks in advance!
possible better answer: http://stackoverflow.com/a/47791755
has answer: http://stackoverflow.com/a/47792670
has comment: http://stackoverflow.com/comment/82544589
tagged with: scikit-learn
has answer: http://stackoverflow.com/a/47791755
tagged with: preprocessor
downvote count: 1
favorite count: 0
type: Question
has title: How to perform OneHotEncoding in Sklearn, getting value error
tagged with: one-hot-encoding
has comment: http://stackoverflow.com/comment/105067250
has comment: http://stackoverflow.com/comment/82543332
tagged with: python
has comment: http://stackoverflow.com/comment/82544272
has answer: http://stackoverflow.com/a/64719461
accepted answer: http://stackoverflow.com/a/52772493
answer count: 4
tagged with: sklearn-pandas

http://stackoverflow.com/comment/82460889
type: Comment
type: QuestionComment
has text: What version of python interpreter do you use?
comment on: http://stackoverflow.com/q/47740320
score: 0

http://stackoverflow.com/comment/82610874
type: Comment
comment on: http://stackoverflow.com/q/47824092
score: 0
type: QuestionComment
has text: @StuartDines no it is not

http://stackoverflow.com/q/47815650
has body: Suppose I have a list of dictionaries. Each dictionary has the same keys, but potentially different values per key. How do I get a list of unique values that are sorted alphabetically? Assume each value is a string. Is there a better way than looping through each dictionary, adding each value to a list, sorting that list, and then removing non-unique values?
has title: How to Unique and Sort values from a list of dictionaries in python?
tagged with: python
tagged with: sorting
tagged with: dictionary
has comment: http://stackoverflow.com/comment/82592937
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47815849
tagged with: list
has comment: http://stackoverflow.com/comment/82592756
downvote count: 0
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/82593107
answer count: 1
has comment: http://stackoverflow.com/comment/82592916
has comment: http://stackoverflow.com/comment/82592815
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47815849

http://stackoverflow.com/a/47729006
answers question: http://stackoverflow.com/q/47715337
has body: Very similar to @dubbbdan 's answer but maybe simpler using any and the and operator: any_in_range = lambda row, iterable: any( [(row[0] &lt; x) &amp; (x &lt; row[1]) for x in iterable]) df_A['label'] = df_A.apply(any_in_range, iterable=df_B['created_date'], axis=1) print df_A Prints: amin amax label 0 2016-07-16 19:37:03 2016-07-17 11:16:32 True 1 2016-07-04 21:15:54 2016-07-05 10:57:46 True 2 2016-07-24 23:30:41 2016-07-25 15:38:02 False 3 2016-07-12 03:02:38 2016-07-12 22:11:01 True
score: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/82438232
type: Answer

pandas
tags question: http://stackoverflow.com/q/47760035
tags question: http://stackoverflow.com/q/47704441
tags question: http://stackoverflow.com/q/47804865
tags question: http://stackoverflow.com/q/47743483
tags question: http://stackoverflow.com/q/47828481
tags question: http://stackoverflow.com/q/47767076
tags question: http://stackoverflow.com/q/47851540
tags question: http://stackoverflow.com/q/47754131
tags question: http://stackoverflow.com/q/47749321
tags question: http://stackoverflow.com/q/47797955
tags question: http://stackoverflow.com/q/47853615
tags question: http://stackoverflow.com/q/47818314
tags question: http://stackoverflow.com/q/47723629
tags question: http://stackoverflow.com/q/47786822
tags question: http://stackoverflow.com/q/47800625
tags question: http://stackoverflow.com/q/47801604
tags question: http://stackoverflow.com/q/47765243
tags question: http://stackoverflow.com/q/47745139
tags question: http://stackoverflow.com/q/47853750
tags question: http://stackoverflow.com/q/47706422
tags question: http://stackoverflow.com/q/47809646
tags question: http://stackoverflow.com/q/47728771
tags question: http://stackoverflow.com/q/47775664
tags question: http://stackoverflow.com/q/47773504
tags question: http://stackoverflow.com/q/47766453
tags question: http://stackoverflow.com/q/47836226
tags question: http://stackoverflow.com/q/47783833
tags question: http://stackoverflow.com/q/47783106
tags question: http://stackoverflow.com/q/47714251
tags question: http://stackoverflow.com/q/47773629
tags question: http://stackoverflow.com/q/47831508
tags question: http://stackoverflow.com/q/47763831
tags question: http://stackoverflow.com/q/47727276
tags question: http://stackoverflow.com/q/47758127
tags question: http://stackoverflow.com/q/47834230
tags question: http://stackoverflow.com/q/47702855
tags question: http://stackoverflow.com/q/47748388
tags question: http://stackoverflow.com/q/47801056
tags question: http://stackoverflow.com/q/47708081
tags question: http://stackoverflow.com/q/47740196
tags question: http://stackoverflow.com/q/47840620
tags question: http://stackoverflow.com/q/47703736
tags question: http://stackoverflow.com/q/47841159
tags question: http://stackoverflow.com/q/47750718
tags question: http://stackoverflow.com/q/47836380
tags question: http://stackoverflow.com/q/47823537
tags question: http://stackoverflow.com/q/47848182
tags question: http://stackoverflow.com/q/47738043
tags question: http://stackoverflow.com/q/47845064
tags question: http://stackoverflow.com/q/47700711
tags question: http://stackoverflow.com/q/47822300
tags question: http://stackoverflow.com/q/47819255
tags question: http://stackoverflow.com/q/47850868
tags question: http://stackoverflow.com/q/47792979
tags question: http://stackoverflow.com/q/47783597
tags question: http://stackoverflow.com/q/47810051
tags question: http://stackoverflow.com/q/47709010
tags question: http://stackoverflow.com/q/47836499
tags question: http://stackoverflow.com/q/47849342
tags question: http://stackoverflow.com/q/47774664
tags question: http://stackoverflow.com/q/47849011
tags question: http://stackoverflow.com/q/47844719
tags question: http://stackoverflow.com/q/47841502
tags question: http://stackoverflow.com/q/47831863
tags question: http://stackoverflow.com/q/47751504
tags question: http://stackoverflow.com/q/47827484
tags question: http://stackoverflow.com/q/47716682
tags question: http://stackoverflow.com/q/47704798
tags question: http://stackoverflow.com/q/47821464
tags question: http://stackoverflow.com/q/47807426
tags question: http://stackoverflow.com/q/47722703
tags question: http://stackoverflow.com/q/47735862
tags question: http://stackoverflow.com/q/47754867
tags question: http://stackoverflow.com/q/47835731
tags question: http://stackoverflow.com/q/47754388
tags question: http://stackoverflow.com/q/47751179
tags question: http://stackoverflow.com/q/47776577
tags question: http://stackoverflow.com/q/47756050
tags question: http://stackoverflow.com/q/47800895
tags question: http://stackoverflow.com/q/47738203

http://stackoverflow.com/comment/82367770
type: QuestionComment
comment on: http://stackoverflow.com/q/47703793
score: 0
has text: Can't you just read the csv in with the csv module? I think commas withing quotes aren't counted as delimiters
type: Comment

http://stackoverflow.com/q/47852883
tagged with: python
has comment: http://stackoverflow.com/comment/82670141
tagged with: python-3.6
accepted answer: http://stackoverflow.com/a/47852899
linked to: http://stackoverflow.com/q/11520492
has answer: http://stackoverflow.com/a/47852899
has body: I was solving a coding problem on Codefights and I ALMOST solved it but, a problem in my code occured and I can't find a way to solve the problem. my_list = [1, 2, 3, 4, 3, 6] print(my_list.index(3)) Output : 2 print(my_list[4]) Output : 3 But, here's the problem, when I try to remove the 3 which lies on index 4, Python removes the 3 on the 2nd index, and I don't want this to happen. For example: my_list.remove(my_list[4]) print(my_list) Output : [1, 2, 4, 3, 6] I want to get the output as : [1, 2, 3, 4, 6] This is not my actual code, but just an example. Please help me out if you can.
upvote count: 2
type: AnsweredQuestion
score: 0
downvote count: 2
answer count: 1
has title: How to specify the duplicate value to remove in a list python 3
has comment: http://stackoverflow.com/comment/82670106
favorite count: 0
tagged with: python-3.x
type: Question

http://stackoverflow.com/q/47734969
has body: I know Python is working by " pass by reference ". However when I was trapped in a bug with hours I felt like I still didn't understand how things happened. Below is my code, which is using deep first search to implement listing all subset of a set. def subset_of_unique_dfs(mylist): """ :param list: a list of char first assuming the element in the list is unique :return: list of subset of the input list we could treated as tree, with ith level represent the ith element is selected or not (binary tree) when we reach the leafnode of the tree, append the result so we need to track the level of the tree where we currently at """ result_list = [] def helper(thelist, level, curList,result): print("at level ",level, "curResult is ",curList) if level == len(thelist): print type(curList) result.append(curList) return curList.append(thelist[level]) helper(thelist,level + 1,curList,result) curList.pop() helper(thelist,level + 1,curList,result) helper(mylist, 0, [],result_list) return result_list print subset_of_unique_dfs(['a','b','c']) """ [[], [], [], [], [], [], [], []] """ I have been struggling for a while while an empty list was returned. Then I tried to change "result.append(curList)" to "result.append(list(curList))", correct result is returned. May I ask what happened by applying list(curList)? I used to take result.append(curList) as appending the object that binding with curList to result. For example, the below test case actually showed no difference between append(listA) and append(list(listA)) tmp1 = [[1,2],[2,3]] tmp1_1 = [[1,2],[2,3]] tmp2 = [3,4] tmp1.append(tmp2) tmp1_1.append(list(tmp2)) print tmp1 print tmp1_1 """ [[1, 2], [2, 3], [3, 4]] [[1, 2], [2, 3], [3, 4]] """
tagged with: python
tagged with: depth-first-search
tagged with: parameter-passing
has comment: http://stackoverflow.com/comment/82664085
has comment: http://stackoverflow.com/comment/83362288
has comment: http://stackoverflow.com/comment/82430552
score: 0
linked to: http://stackoverflow.com/q/45335809
answer count: 1
has comment: http://stackoverflow.com/comment/82667002
has answer: http://stackoverflow.com/a/47735063
has title: python pass by reference
has comment: http://stackoverflow.com/comment/82430503
type: Question
type: UnansweredQuestion

http://stackoverflow.com/a/47760907
downvote count: 0
answers question: http://stackoverflow.com/q/47760860
has body: You're looking for pandas.DataFrame.dtypes. &gt;&gt;&gt; df.dtypes Col1 object Col2 object Col3 object dtype: object &gt;&gt;&gt; dict(df.dtypes) {'Col1': dtype('O'), 'Col2': dtype('O'), 'Col3': dtype('O')} &gt;&gt;&gt; df['Col1'].dtypes dtype('O') If you do type(df['Col1']), Python will tell you that the type is pandas.core.series.Series which isn't particularly useful. You need to determine the type of data stored in the column, not that the column is implemented as a series.
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82483123
upvote count: 5
type: Answer
accepted answer of: http://stackoverflow.com/q/47760860
score: 5

http://stackoverflow.com/comment/82799722
has text: what I'm asking to get is a way to basically add this to a plt subplot. So using this gridspec documentation how would I do that? https://matplotlib.org/users/gridspec.html because from what I understand you're using gs to add subplots. so then how would I append this function to another subplot with ax?
type: Comment
score: 0
comment on: http://stackoverflow.com/a/47790514
type: AnswerComment

http://stackoverflow.com/comment/82450159
has text: I guess it would work better with the mask one, as suggested at the end of the post.
type: AnswerComment
comment on: http://stackoverflow.com/a/47744937
type: Comment
score: 1

http://stackoverflow.com/a/47817235
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47804129
accepted answer of: http://stackoverflow.com/q/47804129
type: Answer
score: 3
upvote count: 3
has body: GNOME's Adwaita theme has predefined two classes for suggested actions: suggested-action destructive-action You can read it on GNOME Wiki HowDoI/Buttons: While most buttons are gray, it has become more fashionable to emphasize buttons that are the suggested action, by giving them a different color. In the Adwaita theme, the color is blue. ... Recently, another style class for dangerous actions has been added as well: 'destructive-action'. The Adwaita theme uses red for buttons marked as such. On Adwaita they look like this, respectively: The predefined needs-attention class, it's a Gtk.Stack/GtkStack child property and it's rendered in a Gtk.StackSwitcher to call for users attention, as described in the GtkStack API Reference: The “needs-attention” child property “needs-attention” gboolean Sets a flag specifying whether the child requires the user attention. This is used by the GtkStackSwitcher to change the appearance of the corresponding button when a page needs attention and it is not the current one. The resulting visual aid can be seen in gtk3-widget-factory program, as a blue dot on the child needing attention (assuming Adwaita theme):

http://stackoverflow.com/comment/82595885
score: 0
has text: While it might be that this problem is not solved by any of the answers to that duplicate question, you would need to be very clear about the difference and show *in how far* it is not solved by those.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47817024

http://stackoverflow.com/a/47828982
downvote count: 0
type: Answer
upvote count: 2
answers question: http://stackoverflow.com/q/47819350
has body: I created a decent solution by inherit from WordCloud. You can just copy and paste the code below, and then you can use + and - to indicate the color, something like this: words = { 'home+': 2.0, 'home-': 10.0, 'car+': 5.0, } would generate this: Explanation: I added a character after the word in the dictionary that tells me the color (+ or -). I removed the character in the recolor method of the WordCloud that I overwrote, but I did send the entire world (including the character + or -) to the color_fun that I use to select the appropriate color. I commented the important bits in the code below. from wordcloud import WordCloud as WC from multidict import MultiDict class WordCloud(WC): def recolor(self, random_state=None, color_func=None, colormap=None): if isinstance(random_state, int): random_state = Random(random_state) self._check_generated() if color_func is None: if colormap is None: color_func = self.color_func else: color_func = colormap_color_func(colormap) # Here I remove the character so it doesn't get displayed # when the wordcloud image is produced self.layout_ = [((word_freq[0][:-1], word_freq[1]), font_size, position, orientation, # but I send the full word to the color_func color_func(word=word_freq[0], font_size=font_size, position=position, orientation=orientation, random_state=random_state, font_path=self.font_path)) for word_freq, font_size, position, orientation, _ in self.layout_] return self class WordClouder(object): def __init__(self, words, colors): self.words = words self.colors = colors def get_color_func(self, word, **args): return self.colors[word[-1]] def makeImage(self, path): #alice_mask = np.array(Image.open("alice_mask.png")) wc = WordCloud(background_color="white", width=200, height=100) # generate word cloud wc.generate_from_frequencies(self.words) # color the wordclound wc.recolor(color_func=self.get_color_func) image = wc.to_image() image.save(path) if __name__ == '__main__': colors = { '+': '#00ff00', '-': '#ff0000', } words =…
score: 2

http://stackoverflow.com/comment/134066431
has text: Just a rough guess, but I'm guessing the bug might have something to do with DPI, since you mention the other monitor have a different resolution.
type: QuestionComment
comment on: http://stackoverflow.com/q/47743402
type: Comment
score: 0

http://stackoverflow.com/comment/82435290
type: Comment
type: QuestionComment
has text: Thanks! This was indeed my error, but Python hates me so never gives the line where it went wrong :S
score: 0
comment on: http://stackoverflow.com/q/47737042

http://stackoverflow.com/a/62937535
downvote count: 0
has body: Was facing a similar problem, I used df.values[] y = df.values[:, 4] fixed the issue by using df.iloc[].values function. y = dataset.iloc[:, 4].values df.values[] function returns object datatype array([192261.83, 191792.06, 191050.39, 182901.99, 166187.94, 156991.12, 156122.51, 155752.6, 152211.77, 149759.96, 146121.95, 144259.4, 141585.52, 134307.35, 132602.65, 129917.04, 126992.93, 125370.37, 124266.9, 122776.86, 118474.03, 111313.02, 110352.25, 108733.99, 108552.04, 107404.34, 105733.54, 105008.31, 103282.38, 101004.64, 99937.59, 97483.56, 97427.84, 96778.92, 96712.8, 96479.51, 90708.19, 89949.14, 81229.06, 81005.76, 78239.91, 77798.83, 71498.49, 69758.98, 65200.33, 64926.08, 49490.75, 42559.73, 35673.41, 14681.4], dtype=object) but df.iloc[:, 4].values returns floats array which is what regressor_OLS = sm.OLS(endog=y, exog=X_opt).fit() OLS() fun accepts OR you can just change the datatype of y before inserting it into the fun OLS() y = np.array(y, dtype = float)
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/47838306
score: 2

http://stackoverflow.com/a/47754613
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47754440
has comment: http://stackoverflow.com/comment/82470121
type: Answer
accepted answer of: http://stackoverflow.com/q/47754440
downvote count: 0
has body: FPGrowth from pyspark.ml.fpm takes a pyspark dataframe, not a rdd. convert rdd into dataframe and then pass. Check http://spark.apache.org/docs/2.2.0/api/python/pyspark.ml.html#pyspark.ml.fpm.FPGrowth.fit Or import fpgrowth from mllib from pyspark.mllib.fpm import FPGrowth EDIT: There are two ways you can proceed. 1.Using rdd method Taking straight from the docs, from pyspark.mllib.fpm import FPGrowth txt = sc.textFile("step3.basket").map(lambda line: line.split(",")) #your txt is already a rdd #No need to collect it and parallelize again model = FPGrowth.train(txt, minSupport=0.2, numPartitions=10) #change parameters according to need #model is ready 2.Using dataframe (which i would suggest is a better method) from pyspark.ml.fpm import FPGrowth df = sc.textFile("step3.basket").map(lambda line: (line.split(","),)) .toDF('items') fp = FPGrowth(minSupport=0.2, minConfidence=0.7) model = fp.fit(df) #model is ready!
score: 1
upvote count: 1

http://stackoverflow.com/comment/82489070
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47763792
has text: Aha! Have you seen this [here](https://stackoverflow.com/questions/8406242/why-does-pycharms-inspector-complain-about-d) ?
score: 1

http://stackoverflow.com/a/47844536
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/47824723
score: 1
has body: Guess: Twill won't load the page because there is a problem verifying the page's SSL certificate. Trying to fetch the page using urllib2.urlopen fails with this error: &gt;&gt;&gt; urllib2.urlopen('https://auth.nbnco.net.au/okta/login') Traceback (most recent call last): ... urllib2.URLError: &lt;urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:661)&gt; Fetching the page using curl produces this output: $ curl https://auth.nbnco.net.au/okta/login &gt; /dev/null % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0 curl: (60) SSL certificate problem: unable to get local issuer certificate More details here: http://curl.haxx.se/docs/sslcerts.html curl performs SSL certificate verification by default, using a "bundle" of Certificate Authority (CA) public keys (CA certs). If the default bundle file isn't adequate, you can specify an alternate file using the --cacert option. If this HTTPS server uses a certificate signed by a CA represented in the bundle, the certificate verification probably failed due to a problem with the certificate (it might be expired, or the name might not match the domain name in the URL). If you'd like to turn off curl's verification of the certificate, use the -k (or --insecure) option. The page loads without error for me in Firefox and Chromium, so the certificate is treated differently by the browsers' certificate handling. The sites SSL certificate is issued by Symantec. It's possible that this behaviour relates to problems with Symantec certificate issuance in the past which has caused Chrome and Mozilla to announce that they will distrust SSL certificates from Symantec in 2018. I don't think there is anything you can do in Twill to work around this problem.
downvote count: 0

http://stackoverflow.com/q/47746652
has body: I am new to python and programming in general. This bit of code will eventually be used in a larger application. I apologize ahead of time for any mistakes. I am trying to make a simple query from a table in a postgresql database. The only result comes back as None. Even though I know there is data there. Thank you in advance for any assistance. import psycopg2 def connect(): """Connects to the database so you can query the stats you require""" conn= psycopg2.connect("dbname='Nascar_Stats' user='postgres' \ host='localhost' password='xxxxxxxx'") print('Connected to DB') cur = conn.cursor() cur.execute("SELECT 'Track_Length' FROM t_tracks \ WHERE 'Track_ID' = 'Daytona';") length = cur.fetchone() print('Track Length = ', length) conn.close()
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47746702
answer count: 1
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/47746702
score: 1
tagged with: psycopg2
favorite count: 0
has title: psycopg2 query returns None
tagged with: postgresql
type: Question
tagged with: python

http://stackoverflow.com/comment/82527080
score: 0
has text: I have done above. I don't know why it can't find folder in sys.path
comment on: http://stackoverflow.com/q/47782780
type: Comment
type: QuestionComment

texas-instruments
type: Tag
tags question: http://stackoverflow.com/q/47824302
tag name: texas-instruments

http://stackoverflow.com/comment/82400826
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47718125
has text: This makes sense to me. Question to help me learn: Let's say we can some hypothetical function `check_index()` which would check the file "type" at instantiation---given that such a function exists, how would that be implemented above?

http://stackoverflow.com/q/47699465
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48287600
tagged with: scrapinghub
has answer: http://stackoverflow.com/a/48287600
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/82383336
tagged with: scrapy
favorite count: 0
type: Question
has title: Not able Running/deploying custom script with shub-image
tagged with: python
score: 11
has comment: http://stackoverflow.com/comment/82370849
has body: I have problem for Running/deploying custom script with shub-image. setup.py from setuptools import setup, find_packages setup( name = 'EU-Crawler', version = '1.0', packages = find_packages(), scripts = [ 'bin/launcher.py', 'bin/DE_WEB_launcher.py', 'bin/ES_WEB_launcher.py', 'bin/FR_WEB_launcher.py', 'bin/IT_WEB_launcher.py', 'bin/NL_WEB_launcher.py', 'bin/DE_MOBILE_launcher.py', 'bin/FR_MOBILE_launcher.py' ], package_data = { 'Crawling': ['*.ini'], }, entry_points = {'scrapy': ['settings = Crawling.settings']}, install_requires=[ 'scrapy-crawlera&gt;=1.2.2', 'configobj', 'scrapy-fake-useragent', 'xmltodict', 'selenium==2.53.2', 'python-dateutil', 'pyvirtualdisplay', 'beautifulsoup4', 'incapsula-cracker-py3' ], extras_require={'ScrapyElasticSearch': 'ScrapyElasticSearch[extras]'}, zip_safe = False, include_package_data=True ) in this file I have scripts = [ 'bin/launcher.py', 'bin/DE_WEB_launcher.py', 'bin/ES_WEB_launcher.py', 'bin/FR_WEB_launcher.py', 'bin/IT_WEB_launcher.py', 'bin/NL_WEB_launcher.py', 'bin/DE_MOBILE_launcher.py', 'bin/FR_MOBILE_launcher.py' ], who are my differents filse that I want sent I deploy with this command sudo shub image upload --username [USERNAME] --password [PASSWORD] Before I used shub-image version 0.2.5 et shub version 2.5.1 and I it worked well. But now I use shub version 2.7.0 (shub image is now part of shub 2.70+ ) and I'm not able to deploy my scripts. I got no Error, I transfer my spiders well, but not the files in bin folder . any advice and suggestions will be greatly appreciated
upvote count: 11

http://stackoverflow.com/comment/82370895
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47705241
has text: Yes, for '2013-01-01' the average is 1.5 ((1+2)/2) and 5.5 ((5+6)/2), but for 2013-02-01 the average is 2.5 ((2+3)/2) and 6.5 ((6+7)/2), and you use 3.5 ((3+4)/2) and 7.5 ((7+8)/2).
score: 0

http://stackoverflow.com/comment/82469290
score: 0
comment on: http://stackoverflow.com/q/47753510
has text: This is almost identical to [this question](https://stackoverflow.com/questions/43362069/get-missing-1-required-positional-argument-self).
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47854297
has comment: http://stackoverflow.com/comment/82680901
has body: The expected answer R_inf[1,2] = 0.8 and R_inf[6,8] = 0.8 of OP's example a is the result of the algorithm applied to the directed graph a.T, not the undirected. Here is R_2 computed with OP's code (with some minor fixes) and with my code. And R_inf also computed with my code: after 2 iterations with pp_loop: 0.8000 0 0 0 0 0 0 0.8000 0 0 0.8000 0.8000 0 0 0.4000 0.3200 0 0.3200 0 0.8000 0.8000 0 0 0.4000 0.3200 0 0.3200 0 0 0 0.8000 0.4800 0 0 0 0 0 0 0 0.4800 0.8000 0 0 0 0 0 0.4000 0.4000 0 0 0.8000 0.1600 0 0.1600 0 0.3200 0.3200 0 0 0.1600 0.8000 0 0.8000 0.8000 0 0 0 0 0 0 0.8000 0 0 0.3200 0.3200 0 0 0.1600 0.8000 0 0.8000 after 2 iterations with OP: 0.8000 0 0 0 0 0 0 0.8000 0 0 0.8000 0.8000 0 0 0.4000 0.3200 0 0.3200 0 0.8000 0.8000 0 0 0.4000 0.3200 0 0.3200 0 0 0 0.8000 0.4800 0 0 0 0 0 0 0 0.4800 0.8000 0 0 0 0 0 0.4000 0.4000 0 0 0.8000 0.1600 0 0.1600 0 0.3200 0.3200 0 0 0.1600 0.8000 0 0.8000 0.8000 0 0 0 0 0 0 0.8000 0 0 0.3200 0.3200 0 0 0.1600 0.8000 0 0.8000 in fixed point: 0.8000 0 0 0 0 0 0 0.8000 0 0 0.8000 0.8000 0 0 0.4000 0.3200 0 0.3200 0 0.8000 0.8000 0 0 0.4000 0.3200 0 0.3200 0 0 0 0.8000 0.4800 0.0960 0.0256 0 0.0256 0 0 0 0.4800 0.8000 0.1280 0 0 0 0 0.4000 0.4000 0.0960 0.1280 0.8000 0.1600 0 0.1600 0 0.3200 0.3200 0.0256 0 0.1600 0.8000 0 0.8000 0.8000 0 0 0 0 0 0 0.8000 0 0 0.3200 0.3200 0.0256 0 0.1600 0.8000 0 0.8000 My solution is faster and can compute the fixed point for networks up to ~1000 nodes. A bit of explanation: The strategy is to express the recurrence relation by matrix algebra, because then we can leverage the highly optimized blas powered linear algebra that comes with numpy/scipy. For example, the inner sums - all of them in one go - can be done by multiplying the matrix R_k of current values with the transposed adjacency matrix. This may seem wasteful considering all the zeros in the adjacency matrix but blas is just very, very fast. Similarly, we can compute the sizes of the intersections by multiplying the adja…
type: Answer
has comment: http://stackoverflow.com/comment/82704195
upvote count: 6
has comment: http://stackoverflow.com/comment/82703957
accepted answer of: http://stackoverflow.com/q/47823117
has comment: http://stackoverflow.com/comment/82704527
has comment: http://stackoverflow.com/comment/82704301
has comment: http://stackoverflow.com/comment/82704019
type: AcceptedAnswer
downvote count: 0
score: 6
answers question: http://stackoverflow.com/q/47823117
has comment: http://stackoverflow.com/comment/82704517
has comment: http://stackoverflow.com/comment/82704406

http://stackoverflow.com/comment/82529168
has text: Commenting the html doesn't avoid the template tags to be processed. You have to delete the lines or comment them with template comment {# ... #}
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47783812
score: 0

http://stackoverflow.com/a/47852191
type: Answer
has comment: http://stackoverflow.com/comment/135677544
score: 2
downvote count: 3
has comment: http://stackoverflow.com/comment/111984645
has body: Unfortunately, this is not possible. The reason for this is that the else condition by itself would cause an error. You can split the cell using control+shift+subtract but once you try and run the last cell an error occurs. You can see the exact example of this in the picture I have included. Please let me know if you have any further questions/comments! ]1
answers question: http://stackoverflow.com/q/47841361
upvote count: 5

http://stackoverflow.com/a/47769742
accepted answer of: http://stackoverflow.com/q/47769658
downvote count: 1
answers question: http://stackoverflow.com/q/47769658
upvote count: 2
type: Answer
score: 1
type: AcceptedAnswer
has body: You can use inspect.getargspecs(YourClass.__init__): &gt;&gt;&gt; import inspect &gt;&gt;&gt; class Foo(object): ... def __init__(self, a, b, c): ... pass ... &gt;&gt;&gt; inspect.getargspec(Foo.__init__) ArgSpec(args=['self', 'a', 'b', 'c'], varargs=None, keywords=None, defaults=None) BUT this won't tell you much about what a, b and c are supposed to be. I suspect a XY problem here, so you should probably explain the problem you're trying to solve with this.

http://stackoverflow.com/q/47782536
tagged with: command-line-arguments
tagged with: python
has comment: http://stackoverflow.com/comment/82529213
has comment: http://stackoverflow.com/comment/82527468
type: Question
tagged with: command-line
tagged with: pyc
has comment: http://stackoverflow.com/comment/82528259
has comment: http://stackoverflow.com/comment/82529183
has comment: http://stackoverflow.com/comment/82528260
has comment: http://stackoverflow.com/comment/82527511
answer count: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/4042905
has comment: http://stackoverflow.com/comment/82528330
has comment: http://stackoverflow.com/comment/82526506
has comment: http://stackoverflow.com/comment/82526630
has comment: http://stackoverflow.com/comment/82526437
has title: release python project as pyc files and run from command prompt with arguments
score: 0
has body: I have a python project consisting of three files: file1.py, file2.py and main.py. I can start main.py from cmd with some arguments, which imports and uses file.py and file2.py as follow: from file1 import * from file2 import * # some other imports if __name__ == "__main__": arg1 = sys.argv[1] arg2 = sys.argv[2] arg3 = sys.argv[3] RumMyLogic(arg1, arg2, arg3) # a function defined in file1 or so... Now, I want to export all these files in pyc format(seperate pyc files or all in one, no matter) and hence, be able to run it from command line/terminal with some command like follow(supposing that python is installed on target machine): main.pyc "arg1" "arg2" "arg3" I couldn't find any straight forward solution on the internet. Any simple solution would be appreciated. PS: This is not for code protection reasons.

http://stackoverflow.com/a/51029067
type: Answer
has body: I usually receive this error when not specifying python before appcfg.py. For example: python appcfg.py update ~/mycodeproject/app.yaml
score: 0
upvote count: 1
downvote count: 1
answers question: http://stackoverflow.com/q/47767179

http://stackoverflow.com/q/47780060
type: UnansweredQuestion
tagged with: arrays
answer count: 1
upvote count: 1
tagged with: python
score: -2
has answer: http://stackoverflow.com/a/47780151
has body: I want to convert a list of lists to a standard Python array.array. Let's take good ol' [[1.0, 2.0][3.0, 4.0]] as an example. Answers to similar Q seem to all be in terms of NumPy. I am doing something to be used by folks who are very unlikely to import numpy.
has comment: http://stackoverflow.com/comment/82521618
downvote count: 3
favorite count: 0
type: Question
has title: list of lists to standard Python array.array, not NumPy
has comment: http://stackoverflow.com/comment/83031050
has comment: http://stackoverflow.com/comment/82521303

http://stackoverflow.com/comment/135193984
comment on: http://stackoverflow.com/a/47782130
has text: @VarunSharma this is an old answer and I haven't been using django for a long time, but to answer your question it's the html attributes of the widget, so something like `<select class="form-control"...`, but I can't say if this kind of code is still possible in modern versions of django.
type: AnswerComment
score: 1
type: Comment

http://stackoverflow.com/comment/82515029
type: QuestionComment
score: 0
has text: @vmonteco If `nouns` is a list, I can write `Template("${nouns.as_ul}")`; then the output is a big unordered list. Imagine `${nouns.as_ul}` inside an HTML template, I don't need some weird `{% for n in nouns %} {{ n }} {% endfor %}` but the method `as_ul` take care of it, nice and clean.
comment on: http://stackoverflow.com/q/47773473
type: Comment

http://stackoverflow.com/a/47725741
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47699010
type: Answer
score: 8
upvote count: 8
has body: You should set the top value by using: value_axis.maximum_scale = 1 And then set the major unit to 0.1 or 0.2 or whatever suits: value_axis.major_unit = 0.1 This particular example would show 0.0, 0.1, 0.2, ... 1.0 as the tick mark labels. Another look results from setting the major unit as 1 and setting the minor unit to 0.1 (or whatever you like). This would generally show a more prominent tick mark for the major unit and a less prominent one for the minor unit. Note however that tick labels only appear on the major tick marks. The number format is set using the TickLabels object available on Axis.tick_labels: value_axis.tick_labels.number_format = '0.0'
downvote count: 0
answers question: http://stackoverflow.com/q/47699010

http://stackoverflow.com/a/47764025
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47763831
has body: Here's one way to use annotate (see docs for lots of cosmetic configuration options): ax = df.plot(x='date', y=['experiment', 'control']) ax.annotate('Big event happened', xy=(df.date[1], 1), xytext=(3, 15), textcoords='offset points', arrowprops=dict(facecolor='red', shrink=0.05)) Matplotlib is smart enough to handle a datetime format for the x coordinate. You can also use date2num to convert to its internal numeric representation of date values, as shown in this answer.
accepted answer of: http://stackoverflow.com/q/47763831
type: Answer

http://stackoverflow.com/a/47818445
answers question: http://stackoverflow.com/q/47817947
score: 0
has body: def mergeLists(list1,list2): out = [] for item1 in list1: #find match in list 2 which has same host and item match = filter(lambda x:x['host'] == item1['host'] and x['name'] == item1['name'],list2) if len(match) &gt; 0: #if match found use entry from list 2 out.append(match[0]) else: #else use item from list 1 as it is unique out.append(item1) #lastly, add unique entries from list2 return {v['host']+v['name']:v for v in out+list2}.values()
type: Answer

http://stackoverflow.com/comment/82644419
type: Comment
type: QuestionComment
has text: What library? I added a link, but not sure it is the correct link. Are you using [this one](https://github.com/danielfrg/tsne)?
comment on: http://stackoverflow.com/q/47840056
score: 0

http://stackoverflow.com/comment/82854454
score: 0
has text: This is useful for the 'random' part. How about the URLs and routing? How would I implement this?
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47805517

http://stackoverflow.com/comment/85322332
comment on: http://stackoverflow.com/a/47821887
type: Comment
has text: @user9062171, how did you figure out which directory to specify for upx? Also, how did you tell if upx was working? I see: `85 INFO: UPX is available.`, but I don't know how to tell if UPX is actually used...
type: AnswerComment
score: 0

http://stackoverflow.com/comment/82419195
score: 0
type: Comment
type: QuestionComment
has text: sorry, i edited it, i'ved changed it to timestamp.
comment on: http://stackoverflow.com/q/47729325

http://stackoverflow.com/comment/82465826
has text: Thank you verymuch! It is my mistik ,my true is true.Now i know the true is True.
score: 1
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47752590

http://stackoverflow.com/comment/82384288
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47709687
score: 0
has text: What I want to do is actually find Chinese in quotes and make a replacement.

http://stackoverflow.com/q/47769187
score: 16
upvote count: 16
tagged with: fontconfig
has body: I have two Python installations on my Debian Sid notebook, ⑴ the system's Python (v.2.7) with a little bunch of utility packages (including Tkinter) and ⑵ Anaconda's Python 3. It is easy to see which (well, here how many...) fonts are available for the two Python distributions. Python 2 &gt;&gt;&gt; from Tkinter import Tk &gt;&gt;&gt; from tkFont import families &gt;&gt;&gt; Tk(); available = families() ### Tk() is needed to have a running tcl interpreter &lt;Tkinter.Tk instance at 0x7f977bcbfb90&gt; &gt;&gt;&gt; len(available) 3011 Python 3 &gt;&gt;&gt; from tkinter import Tk &gt;&gt;&gt; from tkinter.font import families &gt;&gt;&gt; Tk() ; available = families() &lt;tkinter.Tk object .&gt; &gt;&gt;&gt; len(available) 68 It seems to me that Anaconda's tkinter only looks at the basic X fonts that came with the distribution see edit below. Do you know a procedure to, alternatively let Anaconda's tkinter know of the system fonts (preferred alternative) or install a few fonts in the Anaconda's tree so that tkinter can use them? tia Edit the fonts available to Anaconda are indeed system fonts, but only the fonts that are known to xfontsel, i.e., the fonts in the font path that can be manipulated using xset. I tried the following $ cd ~/.fonts ; mkfontscale ; mkfontdir ; xset fp+ `pwd` and xfontsel showed about 30 more font families. Checking with Python 3 I verified that only two font families were added to the list of available fonts (namely 'go' and 'gomono' — no 'consolas' etc) and producing a label ... r = Tk() ; Label(r, text="Go Mono", font=('gomono', 24)).pack() with Python 2 and Python 3 succeeded in both cases, but Debian's Python showed a nice antialiased text while the other was a (rough) bitmap rendition. So, in a sense, I have partially answered my question, but not every font family, as shown by xfontsel, was taken up by tkinter even for the very few that were recognized, the rendition leaves too much to be desired... and I'd like to read a better, more u…
favorite count: 0
has comment: http://stackoverflow.com/comment/82504016
has comment: http://stackoverflow.com/comment/82506571
tagged with: anaconda
has comment: http://stackoverflow.com/comment/82502481
downvote count: 0
has comment: http://stackoverflow.com/comment/82503969
has answer: http://stackoverflow.com/a/69454134
has title: Make Anaconda's tkinter aware of system fonts or install new fonts for Anaconda
tagged with: python
has answer: http://stackoverflow.com/a/76794871
has answer: http://stackoverflow.com/a/49416725
has answer: http://stackoverflow.com/a/76123515
type: Question
tagged with: tkinter
tagged with: fonts
answer count: 5
linked to: http://stackoverflow.com/q/73020496
has answer: http://stackoverflow.com/a/47787749
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82506219
linked to: http://stackoverflow.com/q/41573573

http://stackoverflow.com/comment/82640783
has text: `if not (1 <= choice <= 3):`.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47838333
score: 0

http://stackoverflow.com/comment/82542408
score: 0
type: Comment
type: QuestionComment
has text: Yes forgot to mention that, thanks
comment on: http://stackoverflow.com/q/47790591

http://stackoverflow.com/a/47725888
score: 4
has body: Simplistic case For the simplistic case as in the posted sample, here's one vectorized way with NumPy - ar = np.zeros(len(data), dtype=int) ar[data.open_signal.values] = 1 ar[data.close_signal.values] = -1 data['out'] = ar.cumsum().astype(bool) Runtime test - Using the sample dataset and scaling it 100000 times along the rows for the testing. In [191]: data = pd.concat([data]*100000,axis=0); data.index = range(len(data)) # @Dark's soln with int output In [192]: %timeit data['new'] = data['open_signal'].cumsum().ne(data['close_signal'].cumsum()).astype(int) 100 loops, best of 3: 13.4 ms per loop # @Dark's soln with bool output In [194]: %timeit data['new'] = data['open_signal'].cumsum().ne(data['close_signal'].cumsum()).astype(bool) 100 loops, best of 3: 10 ms per loop # Proposed in this post In [195]: %%timeit ...: ar = np.zeros(len(data), dtype=int) ...: ar[data.open_signal.values] = 1 ...: ar[data.close_signal.values] = -1 ...: data['out'] = ar.cumsum().astype(bool) 100 loops, best of 3: 7.52 ms per loop Generic case Now, to solve for a generic case with : 1] A closed signal coming after no prior open signal. 2] Multiple open signals coming prior to the next close signal. 3] Multiple close signals coming prior to the next open signal. We would need few more steps. Approach #1 : Here's one based upon searchsorted - s0 = np.flatnonzero(data.open_signal.values) s1 = np.flatnonzero(data.close_signal.values) idx0 = np.searchsorted(s1,s0,'right') s0c = s0[np.r_[True,idx0[1:] &gt; idx0[:-1]]] idx1 = np.searchsorted(s0c,s1,'right') s1c = s1[np.r_[True,idx1[1:] &gt; idx1[:-1]]] ar = np.zeros(len(data), dtype=int) ar[s0c] = 1 ar[s1c] = -1 if s1c[0] &lt; s0c[0]: ar[s1c[0]] = 0 data['out'] = ar.cumsum().astype(bool) Sample output - In [360]: data Out[360]: close_signal open_signal out 0 False False False 1 False False False 2 True False False 3 False False False 4 False False False 5 False True True 6 False False True 7 False True True 8 False False True 9 True False False 10…
upvote count: 4
has comment: http://stackoverflow.com/comment/82414454
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47725838
has comment: http://stackoverflow.com/comment/82414409
type: Answer
answers question: http://stackoverflow.com/q/47725838

http://stackoverflow.com/q/47759808
answer count: 1
score: 0
tagged with: colors
has title: Unexpected difference between 2 colors with colormath in python
tagged with: python
type: Question
tagged with: python-3.x
has body: I have the following python code from colormath.color_objects import sRGBColor, LabColor from colormath.color_conversions import convert_color from colormath.color_diff import delta_e_cie2000 color1_rgb = sRGBColor(0,0,0) color2_rgb = sRGBColor(0,1,0) # Convert from RGB to Lab Color Space color1_lab = convert_color(color1_rgb, LabColor) color2_lab = convert_color(color2_rgb, LabColor) #Finding the difference diff = delta_e_cie2000(color1_lab, color2_lab) According to this link - http://colormine.org/delta-e-calculator/cie2000 I should be getting a difference of nearly 0.6 Whearas running this on my system using the colormath library returns a difference of nearly 82.76 Similar observations is seen for the color (255,255,255) and (255,254,254) Where am I wrong with this ?
has answer: http://stackoverflow.com/a/47759917
type: UnansweredQuestion

http://stackoverflow.com/q/47851265
tagged with: function
accepted answer: http://stackoverflow.com/a/47852143
has body: I'm trying to call a small helper-function defined in 'timex.py' which is called from 'caller.py', which in turn should get called from (PyCharm's) IPython-console through "%run caller.py". This currently results in "NameError: name 'pickle' is not defined". # timex.py from IPython import get_ipython def time_expression(exp: str): print(f"time expression: {exp}", flush=True) return get_ipython().magic(f"timeit {exp}") # caller.py import pickle from timex import time_expression packet = [*range(10**2)] time_expression("pickle.dumps(packet, protocol=-1)") # Then run from IPython-console: &gt;&gt;&gt;%run caller.py time expression: pickle.dumps(packet, protocol=-1) NameError: name 'pickle' is not defined Obviously the namespace of the ipython timeit-magic doesn't contain caller.py-globals. Passing globals() as argument of time_expression and updating globals from within time_expression didn't help, as well as passing get_ipython() as argument did not do the trick. Is there a way to make it work? It works if I define time_expression in caller.py and called from Terminal with "ipython caller.py", but I'd prefer to put it in a library and just import it into where needed. (Python 3.6.3, IPython 6.2.1)
downvote count: 0
tagged with: ipython-magic
tagged with: python
has answer: http://stackoverflow.com/a/47852143
tagged with: namespaces
type: AnsweredQuestion
has title: How to make caller's namespace available to IPython's magic inside imported function?
score: 1
answer count: 1
upvote count: 1
tagged with: ipython
favorite count: 0
type: Question

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

http://stackoverflow.com/comment/82455069
has text: Thanks for your help. I would like to extend my question a bit. How can I get the frequencies of all college names in the 'College/Univ' column? So like: `Texas A&M: 5, UC Berkeley: 4...`, given a dataframe and a column_name.
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47747301

http://stackoverflow.com/comment/82529039
score: 0
comment on: http://stackoverflow.com/q/47782447
type: Comment
type: QuestionComment
has text: @furas, I updated the code as follows 'referring_url.decode('utf-8')' Printed its type, value changed from <class 'byte'> to <class 'str'> But it now throws "TypeError: 'NoneType' object is not iterable"

http://stackoverflow.com/q/47719852
tagged with: python
score: -1
has body: In my Python code I am trying to iterate a Gaussian function. I am defining a variable x0 = 2, then I do maths on it with a For loop and then I am trying to overwrite the value of x0 with the value of x_test. I want to loop it over many times in order to get the shape of the Gaussian function (so I guess like Monte Carlo method). What I cannot do is figure out how to overwrite the value of x0 with the value of x_test after each iteration. Could anyone give me some pointers here please? As I just can't find the answer to that. Any help would be much appreciated! Thank you! My code: from random import random import random from math import exp, pow import math from random import randint amp = 0.85 x0 = 2.0 def overwrite(x): global x0 x0 = x for n in iter(overwrite, 10000): uniform = random.uniform(0, 1) if uniform &lt; 0.5: sigma_int = 1 else: sigma_int = -1 sigma_uni = round(random.uniform(0, 1),5) x_test = foobar(2.0) + sigma_int * amp P = (exp(-pow(x_test, 2))) / (exp(-pow(x0, 2))) if (P &gt; sigma_uni): f = open('pyton.txt', 'a') f.write("%s %s\n" % (float(x_test), float(P))) f.close()
has comment: http://stackoverflow.com/comment/82400168
favorite count: 0
upvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82400181
answer count: 1
has answer: http://stackoverflow.com/a/47720019
downvote count: 1
type: Question
has title: Overwrite a variable within FOR loop

http://stackoverflow.com/a/47750465
score: 0
has body: [RESOLVED] For everyone that tried to help, thank you so much, you all gave me ideas and I finally did it. I used multiprocessing.Manager(). I used it like this: with Manager() as manager: info = manager.list() proc = [] info2 = [] if opcoes[0] == True: (...) Thank you, and I hope this can help someone with the same problem.
answers question: http://stackoverflow.com/q/47735074
type: Answer

julia
tags question: http://stackoverflow.com/q/47740169
tags question: http://stackoverflow.com/q/47841361
type: Tag
tag name: julia
tags question: http://stackoverflow.com/q/47840667

http://stackoverflow.com/comment/82602177
comment on: http://stackoverflow.com/q/47782824
type: QuestionComment
has text: You may want to show your completed solution and accept your own answer.
score: 0
type: Comment

http://stackoverflow.com/comment/82645934
type: Comment
type: QuestionComment
has text: Make sure you include the a path to your `MyExe.exe`.
score: 0
comment on: http://stackoverflow.com/q/47840633

http://stackoverflow.com/comment/82419986
type: AnswerComment
comment on: http://stackoverflow.com/a/47727455
type: Comment
has text: @PythonLearner - you can further unpack values to point to the same key, check the update above. If that doesn't solve your problem you could take some time to actually explain your structure as it's certainly not clear from your question.
score: 0

http://stackoverflow.com/comment/82565618
type: QuestionComment
comment on: http://stackoverflow.com/q/47801945
has text: @Gary02127 I'm sure that in url column shows url of the file.
score: 0
type: Comment

http://stackoverflow.com/comment/82675014
comment on: http://stackoverflow.com/q/47855469
score: 1
type: Comment
type: QuestionComment
has text: No, the `data2`, should be `'null'`, since you `json.loads` it.

http://stackoverflow.com/q/47778817
downvote count: 0
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82519686
type: UnansweredQuestion
upvote count: 1
tagged with: python
has title: Pandas read_sql_query validation
has comment: http://stackoverflow.com/comment/82521210
answer count: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/82521371
tagged with: sql
score: 1
tagged with: sqlite
has body: How does pandas verify the SQL query that is passed to pandas.read_sql_query? For example, the following does not work. $ echo 1 &gt; test.txt $ python &gt;&gt;&gt; from pandas import read_sql_query &gt;&gt;&gt; from sqlalchemy import create_engine &gt;&gt;&gt; db = create_engine("sqlite:///:memory:") &gt;&gt;&gt; read_sql_query(".shell rm test.txt", db) [Traceback omitted] sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) near ".": syntax error [SQL: '.shell rm test.txt'] However, if I run that same query directly in sqlite3, then it runs correctly and test.txt is removed. This implies that pandas.read_sql_query is stricter about what SQL statements it processes, but I cannot locate what restrictions are imposed. I would like to verify that is safe to allow a user to pass in an arbitrary query string to a program and guarantee that only the database will affected.

http://stackoverflow.com/comment/82395332
score: 0
comment on: http://stackoverflow.com/q/47716776
type: QuestionComment
type: Comment
has text: you could put values directly to `Entry`, and `bind()` event to `Entry` which will execute function everytime something change in `Entry`. This function could copy value from `Entry` to `dataframe`. Or you can add `Button` (ie. with text `"Save"`) and copy data from all `Entry` to `dataframe` only when you click button.

http://stackoverflow.com/a/47792781
score: 1
has body: So it seems like Watson doesn't like leading spaces in the data you send. For starters, take a look here - fixed_name = re.sub('ER\d{4,5}-', ' ', name) # ^ Since name begins with ER..., this pattern is going to be replaced with a leading space. What you should've done is to replace with the empty string, ''. However, a better way to do this would've been to just split on the first - using str.split. Here's how - &gt;&gt;&gt; "ER111-Test1".split('-', 1)[-1] 'Test1'
answers question: http://stackoverflow.com/q/47792415
downvote count: 0
type: Answer
upvote count: 1

http://stackoverflow.com/a/47791115
has comment: http://stackoverflow.com/comment/82546277
has comment: http://stackoverflow.com/comment/82544968
type: Answer
answers question: http://stackoverflow.com/q/47790904
score: 0
has comment: http://stackoverflow.com/comment/82545985
has body: #There is no need to copy immutables. For Academic Purpose: from copy import deepcopy #initialising first tuple k k=(1,2) id(k) # checking memory id of k j=deepcopy(k) #deepcopying k to j id(j) # checking memory id of j

http://stackoverflow.com/a/47769552
has comment: http://stackoverflow.com/comment/82501046
has comment: http://stackoverflow.com/comment/82500534
downvote count: 0
upvote count: 7
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47769508
has body: I believe you need mask for add tag- to all columns together: for chunk in pd.read_csv('file1.csv',chunksize=2, header=0, names=['A','B','C','D']): if len(chunk) >=1: m1 = chunk.notna() chunk = chunk.mask(m1, "tag-" + chunk.astype(str)) You need upgrade to last version of pandas, 0.21.0. You can check docs: In order to promote more consistency among the pandas API, we have added additional top-level functions isna() and notna() that are aliases for isnull() and notnull(). The naming scheme is now more consistent with methods like .dropna() and .fillna(). Furthermore in all cases where .isnull() and .notnull() methods are defined, these have additional methods named .isna() and .notna(), these are included for classes Categorical, Index, Series, and DataFrame. (GH15001). The configuration option pd.options.mode.use_inf_as_null is deprecated, and pd.options.mode.use_inf_as_na is added as a replacement.
answers question: http://stackoverflow.com/q/47769508
score: 7
type: Answer

http://stackoverflow.com/comment/82418951
type: QuestionComment
has text: Your `__repr__` function is a bit freakish. Use `self` instead of `john` for example, and only return one string.
comment on: http://stackoverflow.com/q/47729174
score: 1
type: Comment

http://stackoverflow.com/comment/82487607
comment on: http://stackoverflow.com/q/47762994
score: 0
has text: @AntonvBR: The parens around `print` aren't necessary (and often undesirable) on Python 2 when using the `print` statement. On Python 3, or Python 2 with `from __future__ import print_function` in effect, they're necessary, but adding them to the Py2 `print` statement is misleading.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47765260
has body: Dictionary has unique keys. If you need the value of 'a' separately store the zipped data in a list or you can use list in values part of the dict and store the values as: {'a': [1,2],'c': [3], 'd': [4]}
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/47765206
upvote count: 1
type: Answer

http://stackoverflow.com/comment/82515721
has text: For centre do I need to use `"centre"`
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47775499
type: AnswerComment

http://stackoverflow.com/comment/103125024
type: Comment
comment on: http://stackoverflow.com/a/58377616
type: AnswerComment
has text: Returns a list now
score: 0

http://stackoverflow.com/q/47854318
upvote count: 0
downvote count: 2
answer count: 1
tagged with: image-processing
has answer: http://stackoverflow.com/a/47856043
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82675101
has comment: http://stackoverflow.com/comment/82672956
has body: I want to superimpose a given set of images of the same size (the AT&amp;T facial images database). I have written the code to do so, which works as follows: I have assigned the location of the images (for starting I am considering only 4 images). imstack is used to read one image (as a base image) over which the layover (superimposition) will take place. A for loop is run that goes through all the images and adds them to the base image (imstack). This adding is done by using the addWeighted() function with the parameters as the current image (im) and the base image (imstack) with the alpha values as 0.5 respectively. After the loop has run till its completion (all the images are superimposed on the base image) I tried to print the updated imstack as 'compiledimg' by using the imshow(). Further I added the option to save the 'compiledimg' file by pressing 's'. Error: imstack=cv2.resize(imstack,(97,113)) cv2.error: /build/opencv-RI6cfE/opencv-2.4.9.1+dfsg1/modules/imgproc/src/imgwarp.cpp:1834: error: (-215) ssize.area() > 0 in function resize import cv2 import numpy as np import os fnames =['~/Downloads/1.pgm','~/Downloads/2.pgm','~/Downloads/3.pgm'] imstack=cv2.imread('~/Downloads/4.pgm') imstack=cv2.resize(imstack,(97,113)) for path in fnames: im=cv2.imread(os.path.expanduser(path)) imstack=cv2.addWeighted(imstack,0.5,im,0.5,0) imstack=cv2.resize(imstack,(97,113)) cv2.imshow('compiledimg.jpg',imstack) k = cv2.waitKey(0) &amp; 0xFF if k == 27: cv2.destroyAllWindows() elif k == ord('s'): cv2.imwrite('compiledimg.jpg',imstack) cv2.destroyAllWindows()
has title: OpenCV Error in resize() Python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82672904
score: -2
has comment: http://stackoverflow.com/comment/82675136
tagged with: python
tagged with: opencv

http://stackoverflow.com/q/47727199
accepted answer: http://stackoverflow.com/a/47727230
has answer: http://stackoverflow.com/a/47727230
type: AnsweredQuestion
has body: How do I add an array of seconds to a reference datetime in python e.g: ref_time = datetime.datetime(year=2017, month=6, day=5, hour=10, minute=30, second=30) secs = (0,1,2,3,4,5,6,7,8,9,10) The result needs to be something: 2017,6,5,10,30,30 2017,6,5,10,30,31 2017,6,5,10,30,32 2017,6,5,10,30,33 etc etc I have tried this but its not working, what am I doing wrong? d = datetime.timedelta(seconds=np.int(secs)) new_timestamp = timestamp+d Sorry for the simple question, i'm quite new to python
score: 0
tagged with: datetime
has title: Adding an array of seconds to a reference datetime
tagged with: python
type: Question
answer count: 1

http://stackoverflow.com/q/47854622
tagged with: django-select-related
upvote count: 8
favorite count: 0
score: 8
type: Question
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/47854829
accepted answer: http://stackoverflow.com/a/47854829
tagged with: prefetch
type: AnsweredQuestion
has title: How to prefetch a @property with a Django queryset?
downvote count: 0
has body: I would like to prefetch a model property to a queryset in Django. Is there a way do that ? Here are the three models: class Place(models.Model): name = models.CharField(max_length=200, blank=True) @property def bestpicurl(self): try: return self.placebestpic.picture.file.url except: return None class PlaceBestPic(models.Model): place = models.OneToOneField(Place) picture = models.ForeignKey(Picture, on_delete=models.CASCADE) class Picture(models.Model): file = ImageField(max_length=500, upload_to="/images/") I would need something like: qs = Place.objects.all().select_related('bestpicurl') Any clue how to do that ? Thanks!
answer count: 1

http://stackoverflow.com/comment/82641656
type: QuestionComment
has text: Vasily - You're completely right, I swear I checked it multiple times.... hmm. Any idea why I would be getting horrendously slow times for almost any action on my project? There are ~600 controls on the window, is this known to be incredibly slow with UIA3 or with pywin's wrapping?
comment on: http://stackoverflow.com/q/47787979
score: 0
type: Comment

rfid
tag name: rfid
tags question: http://stackoverflow.com/q/47702548
type: Tag

http://stackoverflow.com/a/47710216
accepted answer of: http://stackoverflow.com/q/47710068
type: Answer
answers question: http://stackoverflow.com/q/47710068
score: 3
upvote count: 3
has body: You'll have to work your way down to the nested levels first, then sort the parent levels as the recursive call returns. I'm going to assume you want to return a new list (and not sort in place): def nested_sort(l): def sort_key(e): if isinstance(e, list): return sum(sort_key(inner) for inner in e) return e return sorted( [nested_sort(e) if isinstance(e, list) else e for e in l], key=sort_key) The sort key has to recursively sum nested lists, so this can be kind of expensive if you have many nested levels. In that it may be worth adding a cache based on the identity of the list being summed: def nested_sort(l, _sum_cache=None): if _sum_cache is None: _sum_cache = {} def sort_key(e): if isinstance(e, list): e_id = id(e) if e_id not in _sum_cache: _sum_cache[e_id] = sum(sort_key(inner) for inner in e) return _sum_cache[e_id] return e return sorted( [nested_sort(e, _sum_cache) if isinstance(e, list) else e for e in l], key=sort_key) Demo: &gt;&gt;&gt; nested_sort([[2, 1, 3], 4, [2, 3], 7, 1, [9, [4, 2], 5]]) [1, 4, [2, 3], [1, 2, 3], 7, [5, [2, 4], 9]]
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/82456610
type: QuestionComment
has text: @furas So I need to edit my html file right.
score: 0
comment on: http://stackoverflow.com/q/47747894
type: Comment

http://stackoverflow.com/a/47782486
answers question: http://stackoverflow.com/q/47782404
score: 0
has body: You might be looking for a regex solution: import re rx = re.compile(r'[^A-Za-z]+') # some sample line line = 'fkdjks97#!%&amp;jd' # and then later on line = rx.sub('', line) print(line) Which yields # fkdjksjd Putting this in a with... construct, you might be using with open(textfile1, "r") as fp: line = rx.sub('', fp.readline()) print(line)
type: Answer

http://stackoverflow.com/q/47841510
tagged with: terminal
upvote count: 8
score: 8
type: Question
accepted answer: http://stackoverflow.com/a/47841566
has comment: http://stackoverflow.com/comment/82647377
tagged with: python-interactive
has answer: http://stackoverflow.com/a/47841566
tagged with: python
has comment: http://stackoverflow.com/comment/82647247
has title: Simple if statement on python interpreter
has body: Environment: Fedora 27 (GNU/Linux) terminal python3.6.3 I am having problems running this simple lines of code in the python interpreter, this is an only if statement or alone if statement. n = 5 if n == 4: print('n=4') print('done') This must print the word "done", but what am I doing wrong?
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82647326
downvote count: 0
has comment: http://stackoverflow.com/comment/82647254
has comment: http://stackoverflow.com/comment/82647292
answer count: 1
favorite count: 0
tagged with: pythoninterpreter
tagged with: python-3.x

http://stackoverflow.com/comment/82441883
type: AnswerComment
comment on: http://stackoverflow.com/a/47740721
has text: When I execute the program, if I input the maximum as 30, it should give me back a list of primes but it gives me back 2,3,5,5,10,20 which is of course wrong so I must have logic error
type: Comment
score: 0

http://stackoverflow.com/q/47738165
has title: Need to group sequence of letters while keeping the order in pandas or/and python
tagged with: pandasql
answer count: 1
downvote count: 3
has body: I have a dataframe : row1 col1 col2 1 U 1 2 U 1 3 U 1 4 D 1 5 D 1 6 U 1 7 U 1 When I did groupby sum I got : col1 col2 1 U 5 2 D 2 But what I want is : col1 col2 1 U 3 2 D 2 3 U 2 someone answered a similar question. but using oracle sql. I only have pandas and python available. Group rows Keeping the Order of values done with sql How can I get achieve the output.
upvote count: 1
linked to: http://stackoverflow.com/q/16987174
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47738251
has comment: http://stackoverflow.com/comment/82436872
score: -2
has comment: http://stackoverflow.com/comment/82436598
tagged with: python
has comment: http://stackoverflow.com/comment/82436648
tagged with: pandas-groupby
tagged with: pandas
type: UnansweredQuestion

http://stackoverflow.com/comment/82518491
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47778572
has text: Good lord man. I know you're probably going for efficiency here but I'm an experienced python user and the readability here is so rough it's even taking me a while to figure out what's going on xD.
type: Comment

http://stackoverflow.com/a/47787464
has comment: http://stackoverflow.com/comment/118350444
type: Answer
has comment: http://stackoverflow.com/comment/105853534
accepted answer of: http://stackoverflow.com/q/47756075
score: 7
answers question: http://stackoverflow.com/q/47756075
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/109339099
upvote count: 7
has body: You could use the glib's g_timeout_add_seconds function that registers a callback function to be executed in GMainloop's context. In python, this function is encapsulated in GObject, and you can try the below example code: from gi.repository import GObject def hello(): print("Hello world!\n") return True GObject.timeout_add_seconds(1, hello) loop = GObject.MainLoop() loop.run()

image-processing
tags question: http://stackoverflow.com/q/47835138
tags question: http://stackoverflow.com/q/47846236
tags question: http://stackoverflow.com/q/47745934
type: Tag
tags question: http://stackoverflow.com/q/47772299
tags question: http://stackoverflow.com/q/47725994
tags question: http://stackoverflow.com/q/47703773
tags question: http://stackoverflow.com/q/47717288
tags question: http://stackoverflow.com/q/47782522
tags question: http://stackoverflow.com/q/47848911
tags question: http://stackoverflow.com/q/47746772
tags question: http://stackoverflow.com/q/47820537
tags question: http://stackoverflow.com/q/47827245
tags question: http://stackoverflow.com/q/47713826
tags question: http://stackoverflow.com/q/47842931
tags question: http://stackoverflow.com/q/47743513
tags question: http://stackoverflow.com/q/47759764
tag name: image-processing
tags question: http://stackoverflow.com/q/47851566
tags question: http://stackoverflow.com/q/47855193
tags question: http://stackoverflow.com/q/47854318
tags question: http://stackoverflow.com/q/47777585
tags question: http://stackoverflow.com/q/47709162
tags question: http://stackoverflow.com/q/47852390

http://stackoverflow.com/q/47793569
has comment: http://stackoverflow.com/comment/82548672
downvote count: 0
answer count: 1
has title: Choosing top k models using GridSearchCV in scikit-learn
tagged with: machine-learning
tagged with: scikit-learn
favorite count: 0
type: Question
score: 5
upvote count: 5
has comment: http://stackoverflow.com/comment/82548512
tagged with: python
has comment: http://stackoverflow.com/comment/82548618
type: AnsweredQuestion
has body: Is there an easy/pre-existing way to perform a Grid Search in scikit-learn and then automatically return the top k best performing models or automatically average their outputs? I intend to try and reduce overfitting this way. I have not yet found anything related to this. EDIT: To clarify, I know about sklearn's GridSearch, I am looking for an option to perform a Grid Search and then return the top k best performing models or average over them, rather than just returning the best single model.
accepted answer: http://stackoverflow.com/a/47796237
has answer: http://stackoverflow.com/a/47796237

http://stackoverflow.com/q/47789624
has comment: http://stackoverflow.com/comment/82610170
answer count: 3
tagged with: pdfkit
has comment: http://stackoverflow.com/comment/82616243
has comment: http://stackoverflow.com/comment/82665908
upvote count: 3
score: 3
has comment: http://stackoverflow.com/comment/118946140
downvote count: 0
has title: pdfkit not working when serving flask app with gunicorn and nginx
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/58384616
tagged with: gunicorn
tagged with: nginx
type: UnansweredQuestion
has body: On the development server I can create a pdf and send this through to the end user by using pdfkit My view that returns the pdf @changesBP.route('/pdf', methods=['GET']) def pdfView(): if not 'dataDict' in session: flash('Du skal uploade regneark for at kunne fortsætte på siden') return redirect(url_for('indexBP.indexView')) balanceChangelist = session['balanceGruppeChanges'] balanceGrupper = balanceData(data = session['dataDict']) balanceListe = session['balanceListe'] resultatChangelist = session['resultatGruppeChanges'] resultatGrupper = resultatData(data = session['dataDict']) resultatListe = session['resultatListe'] aendingsLister = [] for bc in balanceChangelist: for c in bc['changes']: if c['list'] not in aendingsLister: aendingsLister.append(c['list']) for rc in resultatChangelist: for c in rc['changes']: if c['list'] not in aendingsLister: aendingsLister.append(c['list']) options = { 'page-size': 'Letter', 'margin-top': '0.75in', 'margin-right': '0.75in', 'margin-bottom': '0.75in', 'margin-left': '0.75in', 'encoding': "UTF-8", 'no-outline': None, 'quiet': '' } html = render_template('pdfTemplate.html', balanceChangelist = balanceChangelist, balanceGrupper = balanceGrupper, balanceListe = balanceListe, resultatChangelist = resultatChangelist, resultatGrupper = resultatGrupper, resultatListe = resultatListe, aendingsLister = aendingsLister) out_File = BytesIO() out_File.write(pdfkit.from_string(html, False, options=options)) out_File.seek(0) return send_file(out_File, attachment_filename='out.pdf', as_attachment=True, mimetype="application/pdf") When serving the app through gunicorn and Nginx following this guide I get a bad gateway error when accessing the pdf view. I could use a bit of help on the error log that states the following 2017/12/13 10:04:39 [error] 28047#28047: *78 upstream prematurely closed connection while reading response header from upstream, client: 10.2.20.180, server: 10.8.0.12, request: "GET /pdf HTTP/1.1", upstream: http://unix:/home/h…
has comment: http://stackoverflow.com/comment/82688468
tagged with: python
has answer: http://stackoverflow.com/a/73434261
has answer: http://stackoverflow.com/a/58382561
tagged with: flask

http://stackoverflow.com/comment/82634669
has text: Sorry, I didn't see that. Why, specifically?
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47835554

http://stackoverflow.com/q/47807770
favorite count: 0
type: Question
answer count: 0
has comment: http://stackoverflow.com/comment/82576772
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82576859
tagged with: python
has comment: http://stackoverflow.com/comment/82577027
tagged with: copy
tagged with: class
has comment: http://stackoverflow.com/comment/82601363
tagged with: oop
downvote count: 0
score: 1
upvote count: 1
has title: apply function to class instance in place and not in place
has comment: http://stackoverflow.com/comment/82576983
has body: I have a class with data attribute dd. This class has a function member my_fun, which modifies the values of the internal dd of an instance using an helper method baz(). I would like to have te possibility of performing that inplace i.e. on the same object and non inplace i.e. returning a new object and leave the original intact. I have tried the following. What is the right way to do that, possibly without having to deepcopy? class myBar: def my_fun(self,params,inplace=True): if inplace: self.dd = baz(self.dd) return None else: copied_self=copy.deepcopy(self) copied_self.dd = baz(self.dd) return copied_self

http://stackoverflow.com/comment/82597436
type: QuestionComment
comment on: http://stackoverflow.com/q/47817579
score: 0
has text: I can't at all understand what you're asking here. The word "order" is used in its plain English meaning: Django goes through the patterns *in order* to find one that matches, and stops when it does. This problem has nothing to do with "order" at all, but with the fact that you simply haven't defined a URL that matches the root path.
type: Comment

http://stackoverflow.com/comment/82396048
has text: You say you are using Python 2.7, but the traceback shows `python3.5`.
type: QuestionComment
comment on: http://stackoverflow.com/q/47717866
score: 3
type: Comment

audio-fingerprinting
tags question: http://stackoverflow.com/q/47710089
type: Tag
tag name: audio-fingerprinting

http://stackoverflow.com/comment/82579542
score: 0
comment on: http://stackoverflow.com/a/47809171
type: Comment
type: AnswerComment
has text: I could not understand why from package.module1 and why not from module1 as I am running test.py which is in same folder that of all other .py files

http://stackoverflow.com/comment/82458617
type: Comment
has text: share the file to review it
type: QuestionComment
comment on: http://stackoverflow.com/q/47748989
score: 1

http://stackoverflow.com/q/47711180
has body: I am trying to plot a specific course (acceleration over time) using matplotlib. The plot works so far and is being shown (see image). J equals 35 and represents the derivative of acceleration over time (which in this case is a constant). import numpy as np import matplotlib.pyplot as plt def limits_acc_course(): limits_acc_course.t1 = 0.14285714285714285 limits_acc_course.t2 = 0.14285714285714285 + 0.10714285714285715 limits_acc_course.t3 = 2*0.14285714285714285 + 0.10714285714285715 limits_acc_course.t4 = 2*0.14285714285714285 + 0.10714285714285715 + 0.5*0.24714285714285716 limits_acc_course() t_end = 2*limits_acc_course.t4 t_1 = np.linspace(0, limits_acc_course.t1) t_2 = np.linspace(limits_acc_course.t1, limits_acc_course.t2) t_3 = np.linspace(limits_acc_course.t2, limits_acc_course.t3) t_4 = np.linspace(limits_acc_course.t3, limits_acc_course.t4) tk1 = np.array([]) tk2 = np.array([]) tk3 = np.array([]) tk4 = np.array([]) for value1 in t_1: tk1 = np.append(tk1, value1*j) for value2 in t_2: tk2 = np.append(tk2, limits_acc_course.t1*j) for value3 in t_3: tk3 = np.append(tk3, (limits_acc_course.t3-value3)*j) for value4 in t_4: tk4 = np.append(tk4, value4*0) if value4 == (2*limits_acc_course.t4-limits_acc_course.t3)*j: break t = np.concatenate((tk1, tk2, tk3, tk4), axis=0) t_neg = (-1)*np.concatenate((tk1, tk2, tk3), axis=0) t_final = np.concatenate((t, t_neg), axis=0) t_range = np.linspace(0, t_end, t_final.size) fig, t = plt.subplots() t.plot(t_range, t_final) t.get_xaxis().get_major_formatter().set_useOffset(False) plt.show() The problem is that the x-coordinates in plot do not match the calculated values. The x-values in the plot (see image)) should be: 0.142857142857 0.25 (Or at least with such an accuracy:0.1429) The x-values in the plot are. 0.144777 0.295348 I have tried to turn off the offset and i have played with range from 100 to 2500 values for each part and I have tried to round the values but it didn't work either. Further I have tried using endpoint=F…
answer count: 1
has comment: http://stackoverflow.com/comment/82382731
favorite count: 0
accepted answer: http://stackoverflow.com/a/47712467
type: Question
has comment: http://stackoverflow.com/comment/82384671
has answer: http://stackoverflow.com/a/47712467
has comment: http://stackoverflow.com/comment/82384457
upvote count: 0
has comment: http://stackoverflow.com/comment/82383845
has title: Inaccurate values of x-axis in plot
score: -2
downvote count: 2
has comment: http://stackoverflow.com/comment/82384188
tagged with: python
has comment: http://stackoverflow.com/comment/82383492
has comment: http://stackoverflow.com/comment/82383712
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82383670
tagged with: matplotlib

http://stackoverflow.com/comment/82364463
score: 0
comment on: http://stackoverflow.com/q/47701555
type: QuestionComment
type: Comment
has text: [Shared Axis Demo](https://matplotlib.org/gallery/subplots_axes_and_figures/shared_axis_demo.html#sphx-glr-gallery-subplots-axes-and-figures-shared-axis-demo-py): Have you worked through any of the tutorials or browsed [the gallery](https://matplotlib.org/gallery/index.html) to see if there was something similar to what you want? - [Creating adjacent subplots](https://matplotlib.org/gallery/subplots_axes_and_figures/ganged_plots.html#sphx-glr-gallery-subplots-axes-and-figures-ganged-plots-py)

http://stackoverflow.com/q/47749674
tagged with: python
has title: Unable to pass the argument value from the conole
has comment: http://stackoverflow.com/comment/82459690
linked to: http://stackoverflow.com/q/1009860
has body: Iam trying with a simple script where i wanted to print the value that parsed via command line. But while running the script, it doesn't produce the expected output the program name is python commadn_line_argu.py import sys def main(): for arg in sys.argv[1:]: print "Given arfument is ", arg if __name__=="_main_": main() please see the attached screen shot for the same Appreciate if anyone can help on it Thanks
score: -1
has comment: http://stackoverflow.com/comment/82459571
answer count: 4
has answer: http://stackoverflow.com/a/47749762
upvote count: 0
downvote count: 1
has answer: http://stackoverflow.com/a/47749759
favorite count: 0
has answer: http://stackoverflow.com/a/47749703
type: Question
has comment: http://stackoverflow.com/comment/82459584
has answer: http://stackoverflow.com/a/47749788
type: UnansweredQuestion

http://stackoverflow.com/a/47768068
has comment: http://stackoverflow.com/comment/82506367
has comment: http://stackoverflow.com/comment/82506481
has comment: http://stackoverflow.com/comment/82500148
has comment: http://stackoverflow.com/comment/82506619
has comment: http://stackoverflow.com/comment/82507015
has comment: http://stackoverflow.com/comment/82507274
has comment: http://stackoverflow.com/comment/82500942
has comment: http://stackoverflow.com/comment/82499338
has body: As the error message shows: progdata is an int. device.eeProgram(0,0xffffffff,2,"FTDI","FT") First argument of eeProgram is progdata and it clearly is an int and not a class that might have a method or attribute Signature. Caveat: The first argument is the 0, since device is the self? argument from the function definition. So you need to change the 0 to a class instance of whatever class eeProgram is a method of.
has comment: http://stackoverflow.com/comment/82504869
has comment: http://stackoverflow.com/comment/82500855
has comment: http://stackoverflow.com/comment/82497747
answers question: http://stackoverflow.com/q/47767973
type: Answer
has comment: http://stackoverflow.com/comment/82504822
has comment: http://stackoverflow.com/comment/82497902
score: 2
has comment: http://stackoverflow.com/comment/82497497
upvote count: 2
has comment: http://stackoverflow.com/comment/82497229
has comment: http://stackoverflow.com/comment/82500404
has comment: http://stackoverflow.com/comment/82500597
downvote count: 0

http://stackoverflow.com/q/47731156
type: Question
tagged with: flask-assets
tagged with: sass
linked to: http://stackoverflow.com/q/14412677
type: UnansweredQuestion
tagged with: python
has title: Setup Flask to use *.scss - with Flask-Assets and PyScss
answer count: 0
has body: I can't get Flask to work with scss. I looked into this Using sass with Flask and jinja2 and Set up Flask with webassets. But I am currently stuck. I setup everything and when running the server with flask run the server starts without errors. When I go to localhost:5000 I get this error: This page isn’t working localhost didn’t send any data. ERR_EMPTY_RESPONSE But the logs of the server are empty and no *.css file got generated. All thats in the console: * Serving Flask app "app" * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) This is my structure: ── app ├── __init__.py ├── assets │ └── scss │ ├── nav.scss │ └── partials │ └── color.scss ├── config.py ├── static ├── templates │ └── layout.html └── views.py __init__.py from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_assets import Environment, Bundle app = Flask(__name__) app.config.from_object('app.config') db = SQLAlchemy(app) assets = Environment(app) assets.url = app.static_url_path scss = Bundle( "assets/scss/nav.scss", filters="pyscss", output="all.css", depends="assets/scss/partials/*.scss" ) assets.register("style", scss) from app import views layout.html &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; {% assets "style" %} &lt;link rel="stylesheet" href="{{ ASSET_URL }}" type="text/css" /&gt; {% endassets %} &lt;/head&gt; &lt;body&gt; Hello World &lt;/body&gt; &lt;/html&gt; config.py DEBUG = True ASSETS_DEBUG = True SQLALCHEMY_DATABASE_URI = 'sqlite:////tmp/test.db' SQLALCHEMY_TRACK_MODIFICATIONS = False views.py from flask import render_template from app import app @app.route('/') @app.route('/index') def index(): return render_template('layout.html', title="Home") nav.scss body{ background: green; } color.scss $primary-accent-color: rgba(33, 150, 243, 1.0); requirements.txt astroid==1.5.3 attrs==17.3.0 autopep8==1.3.3 Babel==2.5.1 click==6.7 Flask==0.12.2 Flask-Assets==0.12 Flask-Babel==0.11.2 Flask-Login==0.4.0 Flask-SQLAlchemy==2.3.2 Flask-WTF==0.14.2 isort==4.2.15 …
score: 3
upvote count: 3
downvote count: 0
favorite count: 0

http://stackoverflow.com/q/47800200
favorite count: 0
has title: Replace first n elements in pandas dataframe column
type: Question
has body: I want to replace the first n elements of a column in my data frame with another pd.series I have saved. So as an example, category price store testscore 0 Cleaning 11.42 Walmart NaN 1 Cleaning 23.50 Dia NaN 2 Entertainment 19.99 Walmart NaN 3 Entertainment 15.95 Fnac NaN 4 Tech 55.75 Dia NaN 5 Tech 111.55 Walmart NaN Here I would want to replace the first three NaNs in testscore with a new set of strings. Imagine I have a variable: cats = pd.Series(df['category'][0:2]) So can I place this in the testscore column... category price store testscore 0 Cleaning 11.42 Walmart Cleaning 1 Cleaning 23.50 Dia Cleaning 2 Entertainment 19.99 Walmart Entertainment 3 Entertainment 15.95 Fnac NaN 4 Tech 55.75 Dia NaN 5 Tech 111.55 Walmart NaN But whenever I try to do this it won't work. Code to create this fake dataset: import pandas as pd import numpy as np df = pd.DataFrame({'category': ['Cleaning', 'Cleaning', 'Entertainment', 'Entertainment', 'Tech', 'Tech'], 'store': ['Walmart', 'Dia', 'Walmart', 'Fnac', 'Dia','Walmart'], 'price':[11.42, 23.50, 19.99, 15.95, 55.75, 111.55], 'testscore': [np.nan, np.nan, np.nan, np.nan, np.nan, np.nan]}) print(df) df2 = pd.DataFrame({'category': ['Cleaning', 'Cleaning', 'Entertainment', 'Entertainment', 'Tech', 'Tech'], 'store': ['Walmart', 'Dia', 'Walmart', 'Fnac', 'Dia','Walmart'], 'price':[11.42, 23.50, 19.99, 15.95, 55.75, 111.55], 'testscore': ['Cleaning', 'Cleaning', 'Entertainment', np.nan, np.nan, np.nan]}) print(df2)
tagged with: python
has comment: http://stackoverflow.com/comment/82561592
upvote count: 6
has answer: http://stackoverflow.com/a/47800442
possible better answer: http://stackoverflow.com/a/47800442
has comment: http://stackoverflow.com/comment/82561729
type: AnsweredQuestion
answer count: 2
tagged with: pandas
score: 6
downvote count: 0
has answer: http://stackoverflow.com/a/47800366
accepted answer: http://stackoverflow.com/a/47800366

http://stackoverflow.com/comment/82660672
comment on: http://stackoverflow.com/q/47848155
score: 0
type: Comment
has text: to use the same platform as other containers.
type: QuestionComment

http://stackoverflow.com/q/47845059
has comment: http://stackoverflow.com/comment/82658133
has comment: http://stackoverflow.com/comment/82656428
has answer: http://stackoverflow.com/a/47952325
tagged with: python
has body: I want to make segmentation masks for some images by coding. There is a tool that can generate xml file with coordinates of boundary points approximately. These coordinates can be obtained by getting tag values. The image size is 800x600 pixels. For example, following points are extracted from this tool. How can I fill the region inside the contour marked with the dotted lines with e.g. white colour? Thanks. points = [(737, 255), (736, 265), (735, 270), (739, 273), (746, 264), (755, 268), (765, 272), (767, 276), (769, 278), (776, 275), (776, 264), (767, 260), (753, 257), (738, 256), (738, 256), (479, 247), (455, 244), (446, 245), (440, 243), (430, 244), (423, 241), (419, 238), (412, 232), (406, 225), (403, 202), (404, 185), (410, 170), (414, 166), (424, 160), (439, 157), (456, 166), (469, 177), (472, 197), (480, 199), (492, 214), (494, 207), (488, 201), (492, 193), (497, 194), (502, 196), (510, 196), (518, 197), (523, 202), (521, 209)] import Image import numpy as np a = Image.new('RGB',(800,600),0) for p in points: a.putpixel(p,(255,255,255)) a.show() a.save('./Original_mask.png') Original_mask: Expected_mask:
tagged with: http://stackoverflow.com/tag/xml
type: Question
score: 2
has comment: http://stackoverflow.com/comment/82655862
tagged with: image-segmentation
answer count: 2
has answer: http://stackoverflow.com/a/47846039
possible better answer: http://stackoverflow.com/a/47846039
upvote count: 2
downvote count: 0
accepted answer: http://stackoverflow.com/a/47952325
favorite count: 0
has comment: http://stackoverflow.com/comment/82657092
tagged with: opencv
type: AnsweredQuestion
has title: how to make segmentation mask given region marked with dotted line in python

http://stackoverflow.com/q/47813835
has body: I've some code like import os import threading class pixels (object): def myfunction(self, param1, param2): fileImage = str(name) + "_" + str(x) + ".jpg" os.system('ffmpeg -i "' + sub + '" -ss 00:00:' + str(timeFrame) + ' -loglevel panic -vframes 1 "' + fileImage + '"') somecode.... os.remove(fileImage) class otherClass (object): def myCallingFunction (): params1 = "example1" params2 = "example2" for i in someArray: task1= threading.Thread(target=pixels.myfunction, args=(params1, params2 )) task1.start() before exit i've: while threading.active_count() &gt; 1: sleep(1) Well, if i change the way to call the pixels.myfunction to without multithreading, it works, but slower. But with multithreading, the console after execution looks locked, you can type but don't see anythng (but it's writed!, yo can press enter after type some command and works, but you can't see what you types), do you have any idea of what could be the problem?
tagged with: python
tagged with: ubuntu
has comment: http://stackoverflow.com/comment/82590687
type: Question
has comment: http://stackoverflow.com/comment/82589522
has comment: http://stackoverflow.com/comment/82589895
tagged with: python-2.7
score: 0
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82589572
tagged with: multithreading
has comment: http://stackoverflow.com/comment/82590637
has title: Python multithread causes console errors (can not type)

http://stackoverflow.com/comment/82432439
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47736016
type: Comment
has text: As OP said he doesn't have problem with nans but empty strings.

http://stackoverflow.com/q/47842573
tagged with: redis
tagged with: database
has answer: http://stackoverflow.com/a/47842668
tagged with: python
type: AnsweredQuestion
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/82649342
accepted answer: http://stackoverflow.com/a/47842668
has title: How to check if the import of data successful or not
possible better answer: http://stackoverflow.com/a/47842659
has comment: http://stackoverflow.com/comment/82649352
has body: I write a query and I want to add the json data into Redis, but after processed(I use pycharm), there shows no results just Process finished with exit code 0. So how can I check if it is successful or not? Here is the code: import json import redis import mysql.connector r = redis.StrictRedis( host='localhost', port=6379, charset="utf-8", decode_responses=True) cnx = mysql.connector.connect(user='root', password='000000', host='127.0.0.1', database='m') player_data= [ {'playID':'aardsda01', 'birthYear':'1981', 'birthMonth':'12', 'birthDay':'27', 'birthCountry':'USA', 'birthState':'CO', 'nameFirst':'David', 'nameLast':'Aardsma'} ] json_store = json.dumps(player_data) r.set('players', json_store) k = json.loads(r.get('players')) player_data == k Thank you very much!
has answer: http://stackoverflow.com/a/47842659
type: Question
has comment: http://stackoverflow.com/comment/82649282

http://stackoverflow.com/q/47835731
score: -1
favorite count: 0
answer count: 2
downvote count: 2
upvote count: 1
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82635686
has answer: http://stackoverflow.com/a/47835792
has comment: http://stackoverflow.com/comment/82635098
has answer: http://stackoverflow.com/a/47835840
type: Question
tagged with: pandas
has body: I have a DataFrame with several columns, I want to sum up two columns with integers and calculate percentage change of the sums. I have tried with lambda but I cant seem to find the right code. Please help.
has title: How can i calculate percentage change of sum of two columns in dataframe pandas
tagged with: dataframe
tagged with: python

http://stackoverflow.com/comment/82614181
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47768570
type: Comment
has text: Well @janscas, manually adding the property by assigning a value to it seems to have sorted the problem out for me, but then what is the purpose of the "default" parameter? Why would you provide the property with a "default" value and then require the developer to manually assign the property a value before it can be used? It makes the "default" parameter worse than useless, it makes it misleading. It also makes Google's own documentation wrong - [this article](https://cloud.google.com/appengine/articles/update_schema), complete with example, is exactly what I'm trying to do.

http://stackoverflow.com/q/47843894
score: -1
has title: Python evaluate math expression with Literal String Interpolation
type: Question
has answer: http://stackoverflow.com/a/47843922
has body: Today stumbled upon Literal String Interpolation, a=4 b=5 f'{a+b}' the above code gives the output 9, I was trying to put the operation in variable too. a=4 b='+' c=5 Now how can Literal String Interpolation generate the expected output, saw the documentation but could not make much out of it.
upvote count: 0
type: UnansweredQuestion
answer count: 1
downvote count: 1
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82672036
linked to: http://stackoverflow.com/q/2371436
tagged with: python

http://stackoverflow.com/comment/82566506
has text: I think is not duplicate. The question is the 2013. Now firefox support multiprocess.
comment on: http://stackoverflow.com/q/47801788
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47765073
upvote count: 3
accepted answer of: http://stackoverflow.com/q/47765021
downvote count: 0
has comment: http://stackoverflow.com/comment/82492107
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47765021
has comment: http://stackoverflow.com/comment/82491685
score: 3
has body: import itertools li = [1, 'a', 'b'] li2 = [2, 3, 4] def combinations_letters(li, li2): li = list(li) indexes = [i for i, x in enumerate(li) if isinstance(x, str)] for comb in itertools.combinations(li2, r=len(indexes)): for index, c in zip(indexes, comb): li[index] = c yield tuple(li) print list(combinations_letters(li, li2)) This outputs: [(1, 2, 3), (1, 2, 4), (1, 3, 4)] What this does is find the indexes of all the strings in li, and replace them with the output of itertools.permutations.
has comment: http://stackoverflow.com/comment/82491719
type: Answer

http://stackoverflow.com/q/47775876
answer count: 3
has answer: http://stackoverflow.com/a/70107617
downvote count: 0
has body: Is there a way to set the default content_type value for the test client in Flask? For example, if I have the following test: import unittest class MyTestCase(unittest.TestCase): def setUp(self): from my_flask_project import app self.client = app.test_client() def test_request_one(self): self.client.post( data='{}' content_type='application/json' ) def test_request_two(self): self.client.post( data='{}' content_type='application/json' ) All of my test cases are going to set content_type='application/json'. I would like to set application/json as the default content type for requests but I couldn't find any documentation on how to do this. Something like this would be ideal: def setUp(self): from my_flask_project import app self.client = app.test_client( default_content_type='application/json' )
tagged with: unit-testing
favorite count: 0
has answer: http://stackoverflow.com/a/68603724
type: Question
possible better answer: http://stackoverflow.com/a/68603724
score: 6
upvote count: 6
tagged with: python
tagged with: flask
has answer: http://stackoverflow.com/a/47776430
accepted answer: http://stackoverflow.com/a/47776430
type: AnsweredQuestion
has title: Set default content_type for Flask test client

http://stackoverflow.com/comment/82402657
has text: Why don't you keep a reference to your process when you call it in `run()` and then just kill it in `shut()`?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47720956
score: 0

http://stackoverflow.com/comment/82441208
type: AnswerComment
comment on: http://stackoverflow.com/a/47738834
score: 0
type: Comment
has text: @CarlosCordoba I downloaded on this laptop after 1st December (I don't know the exact date but _definitely_ after that as I was abroad until then) and by default there is namespace interference. I acknowledge the feature in my answer but I definitely could recreate the OP's issue easily. Script --> console access is _awesome_ but I've had nothing but trouble from console --> script.

http://stackoverflow.com/q/47770144
upvote count: 8
type: Question
tagged with: http://stackoverflow.com/tag/html
tagged with: python
has comment: http://stackoverflow.com/comment/82502290
has comment: http://stackoverflow.com/comment/82502473
tagged with: selenium-webdriver
linked to: http://stackoverflow.com/q/54459701
answer count: 2
possible better answer: http://stackoverflow.com/a/47771229
has comment: http://stackoverflow.com/comment/82502241
type: AnsweredQuestion
tagged with: iframe
has answer: http://stackoverflow.com/a/47771229
downvote count: 0
accepted answer: http://stackoverflow.com/a/47771879
tagged with: selenium
has answer: http://stackoverflow.com/a/47771879
has body: I am trying to select an element which resides inside an iframe and probably in other iframes. Is it somehow possible to select an element within some (sub-)iframe in (python)selenium without selecting the iframes before? Is there a way to 'loop' over every iframe somehow and to check where to find my element...? And how to do that in the case elements and html stuff and iframes might just about being loaded...?
linked to: http://stackoverflow.com/q/53203417
favorite count: 0
has comment: http://stackoverflow.com/comment/82502424
has title: How can I select a html element no matter what frame it is in in selenium?
score: 8

http://stackoverflow.com/q/47706509
score: 1
has comment: http://stackoverflow.com/comment/82373269
answer count: 1
has title: Calculate each row values python
favorite count: 0
tagged with: python-3.x
type: Question
has answer: http://stackoverflow.com/a/47706625
type: UnansweredQuestion
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/82373240
has body: I want to calculate average of each row and result them in another new column at the each of the DataFrame. This is small sample of data that I am having I am not sure how I should write a function that can calculate row by row for it since my actual data will have something like 600K rows.
has comment: http://stackoverflow.com/comment/82374720
has comment: http://stackoverflow.com/comment/82374527
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/47719165
type: AnsweredQuestion
tagged with: python-2.7
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/47720115
has body: While Scraping data using beautifulSoap In this html code there are two tag but I want to extract data from second tag. So how can i do this? and so on if there are multiples of same tag and i want to extract data from any one of the tag how can I do that? Code: Video Instructions For Making Soft Idlis Recipe For Making Soft Idlis I had thought of extracting data using keyword instead of using tag. for example I can use tag and use keyword Recipe to find the data of second tag
tagged with: beautifulsoup
type: Question
has title: Scrape data using beautiful soup
accepted answer: http://stackoverflow.com/a/48959668
possible better answer: http://stackoverflow.com/a/47720115
tagged with: python
has answer: http://stackoverflow.com/a/48959668

http://stackoverflow.com/comment/82484615
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47761127
has text: @A0sXc950 if this answer helped you, please consider accepting it.

http://stackoverflow.com/q/47756176
has comment: http://stackoverflow.com/comment/82473606
has answer: http://stackoverflow.com/a/79305074
has comment: http://stackoverflow.com/comment/82473559
has body: I have built a faster r-cnn model and am in the process of labeling images with a bunch of bounding boxes. My issue is that the python kernel eventually crashes while labeling the first ~3000 out of 70,000 images. I have narrowed down the issue to image = cv2.imread().Regardless of using del image or image = None, the excessive memory usage persists. Is there a none memory leak issue with the CV2 library? I am using version 3.3. Is there anyway to clear memory? Thanks. def SaveFigureAsImage(fileName,fig=None,**kwargs): ''' Save a Matplotlib figure as an image without borders or frames. Args: fileName (str): String that ends in .png etc. fig (Matplotlib figure instance): figure you want to save as the image Keyword Args: orig_size (tuple): width, height of the original image used to maintain aspect ratio. ''' a=fig.gca() a.set_frame_on(False) a.set_xticks([]); a.set_yticks([]) plt.axis('off') fig.savefig(fileName, transparent=True, bbox_inches='tight', \ pad_inches=0) #classes classes = { redacted } #load model image_input = keras.layers.Input((None, None, 3)) model = keras_retinanet.models.ResNet50RetinaNet(image_input, num_classes=len(classes), weights='imagenet') model.load_weights('snapshots/resnet50_model_1_6.h5') test_image_data_generator = keras.preprocessing.image.ImageDataGenerator() #possibely resize the image test_generator = PascalVocIterator( '../', 'test', test_image_data_generator, classes=classes ) #stats frequency = {} ef read_image_bgr(path): image = np.asarray(PIL.Image.open(path).convert('RGB')) return image[:, :, ::-1].copy() def preprocess_image(x): # mostly identical to "https://github.com/fchollet/keras/blob/master/keras/applications/imagenet_utils.py" # except for converting RGB -> BGR since we assume BGR already x = x.astype(keras.backend.floatx()) if keras.backend.image_data_format() == 'channels_first': if x.ndim == 3: x[0, :, :] -= 103.939 x[1, :, :] -= 116.779 x[2, :, :] -= 123.68 else: x[:, 0, :, :] -= 103.939 x[:, 1, :, :] -= 116.779 x…
has comment: http://stackoverflow.com/comment/82473668
has comment: http://stackoverflow.com/comment/82474053
answer count: 2
has comment: http://stackoverflow.com/comment/82473809
has comment: http://stackoverflow.com/comment/82554280
has comment: http://stackoverflow.com/comment/89602509
downvote count: 2
has comment: http://stackoverflow.com/comment/82473896
has answer: http://stackoverflow.com/a/79283275
has comment: http://stackoverflow.com/comment/82473647
favorite count: 0
has comment: http://stackoverflow.com/comment/82474293
has comment: http://stackoverflow.com/comment/82473688
has comment: http://stackoverflow.com/comment/82474626
type: Question
tagged with: opencv
upvote count: 8
has title: Memory Usage Issues with CV2.imread()
type: UnansweredQuestion
score: 6
tagged with: python
has comment: http://stackoverflow.com/comment/82485762
has comment: http://stackoverflow.com/comment/82474477

bigdata
tags question: http://stackoverflow.com/q/47770575
tags question: http://stackoverflow.com/q/47743042
tags question: http://stackoverflow.com/q/47708128
type: Tag
tag name: bigdata

http://stackoverflow.com/q/47723360
score: 1
answer count: 1
downvote count: 0
has title: logger printing same statement random number of times or not at all
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82414519
has body: I have python logger being defined in the global part of a python script like so: import logging import logging.handlers FORMAT = '%(asctime)-15s %(threadName)s %(levelname)s %(message)s' logfile = app.config['CONTROLROOM_WORKER_LOG_PATH'] loghandler = logging.handlers.TimedRotatingFileHandler(logfile, when='midnight', interval=1, backupCount=10, encoding=None, delay=False, utc=False) fmt = logging.Formatter(FORMAT) loghandler.setFormatter(fmt) logger = logging.getLogger('controlroom_worker') logger.setLevel(logging.INFO) logger.addHandler(loghandler) However issues I'm facing are the following: Sometimes a logger statement prior to some logic is ignored (that is, not logged), even though the logic is executed. This behavior is amplified when a lot of stuff needs to be printed. 90% percent of the times, everything that is printed, is printed twice! Although I have seen a few cases where something is printed 3 times. Example logging: 2017-12-08 17:51:10,823 config_notifier INFO Done notifying changes. 2017-12-08 17:51:10,823 config_notifier INFO Done notifying changes. 2017-12-08 17:51:15,829 config_notifier INFO Notifying changes. 2017-12-08 17:51:15,829 config_notifier INFO Notifying changes. 2017-12-08 17:51:15,829 config_notifier INFO Notifying changes. 2017-12-08 17:51:15,943 config_notifier INFO Committed !!! 2017-12-08 17:51:15,943 config_notifier INFO Committed !!! 2017-12-08 17:51:15,943 config_notifier INFO Committed !!! 2017-12-08 17:51:15,943 config_notifier INFO Done notifying changes. 2017-12-08 17:51:15,943 config_notifier INFO Done notifying changes. 2017-12-08 17:51:20,949 config_notifier INFO Notifying changes. 2017-12-08 17:51:20,949 config_notifier INFO Notifying changes. 2017-12-08 17:51:21,052 config_notifier INFO Committed !!! 2017-12-08 17:51:21,052 config_notifier INFO Committed !!! 2017-12-08 17:51:21,052 config_notifier INFO Done notifying changes. 2017-12-08 17:51:21,052 config_notifier INFO Done notifying changes. 2017-12-08 17:51:21,052 …
type: UnansweredQuestion
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/47726608
tagged with: logging

mysql-connector
tags question: http://stackoverflow.com/q/47737044
tags question: http://stackoverflow.com/q/47816703
tags question: http://stackoverflow.com/q/47769088
tag name: mysql-connector
tags question: http://stackoverflow.com/q/47709703
type: Tag

http://stackoverflow.com/comment/82482220
type: Comment
comment on: http://stackoverflow.com/q/47760436
type: QuestionComment
has text: Related: https://stackoverflow.com/q/1732348
score: 1

http://stackoverflow.com/q/47758967
answer count: 3
has comment: http://stackoverflow.com/comment/82479226
has title: Find nearest value for 3 lists
has comment: http://stackoverflow.com/comment/82479455
linked to: http://stackoverflow.com/q/6473679
type: Question
type: AnsweredQuestion
tagged with: list
has answer: http://stackoverflow.com/a/47760224
has answer: http://stackoverflow.com/a/47759088
accepted answer: http://stackoverflow.com/a/47759088
has answer: http://stackoverflow.com/a/47759245
possible better answer: http://stackoverflow.com/a/47759245
has comment: http://stackoverflow.com/comment/82479216
has comment: http://stackoverflow.com/comment/82482227
tagged with: python
has body: Here is my code to get the nearest value to a given number ( Mynumber) from a list (Mylist) Mylist= [ 1, 2, 3] Mynumber=3 takeClosest = lambda num,collection:min(collection,key=lambda x:abs(x- num)) closest= [takeClosest(Mynumber,Mylist)] print closest Now I have 3 lists [ 1, 2, 3] ,[ 4, 7, 8], [ 13, 9, 10] I want to compare first item , second item and 3rd item of them with this list,[2,6,9] ,If I compare 1st item in each list, out if [1,4,13], 1 is the closest to 2 ,If I compare 2nd item in each list, out of [2,7,9], 7 is the closest to 6,If I compare 3rd item in each list, out of [3,8,10], 10 is the closest to 9 Does any one know how to do it? Any suggestion would be greatly appreciated """ Mylist1= [ 1, 2, 3] Mylist2= [ 4, 7, 8] Mylist3= [ 13, 9, 10] Mynumber=[2,6,9] """
score: 0

mysql
tags question: http://stackoverflow.com/q/47711689
tags question: http://stackoverflow.com/q/47806466
tags question: http://stackoverflow.com/q/47750439
tags question: http://stackoverflow.com/q/47761650
tags question: http://stackoverflow.com/q/47714070
tags question: http://stackoverflow.com/q/47808863
tags question: http://stackoverflow.com/q/47755484
tags question: http://stackoverflow.com/q/47828486
tags question: http://stackoverflow.com/q/47789275
tags question: http://stackoverflow.com/q/47842966
type: Tag
tags question: http://stackoverflow.com/q/47783007
tags question: http://stackoverflow.com/q/47816716
tags question: http://stackoverflow.com/q/47747469
tags question: http://stackoverflow.com/q/47779711
tags question: http://stackoverflow.com/q/47709703
tag name: mysql
tags question: http://stackoverflow.com/q/47730055
tags question: http://stackoverflow.com/q/47854442
tags question: http://stackoverflow.com/q/47810893
tags question: http://stackoverflow.com/q/47816703
tags question: http://stackoverflow.com/q/47769088
tags question: http://stackoverflow.com/q/47783328
tags question: http://stackoverflow.com/q/47825384
tags question: http://stackoverflow.com/q/47759986
tags question: http://stackoverflow.com/q/47717840
tags question: http://stackoverflow.com/q/47767969
tags question: http://stackoverflow.com/q/47728923
tags question: http://stackoverflow.com/q/47825335
tags question: http://stackoverflow.com/q/47855792
tags question: http://stackoverflow.com/q/47722523
tags question: http://stackoverflow.com/q/47736056
tags question: http://stackoverflow.com/q/47775715
tags question: http://stackoverflow.com/q/47847903
tags question: http://stackoverflow.com/q/47728705
tags question: http://stackoverflow.com/q/47744324
tags question: http://stackoverflow.com/q/47842930
tags question: http://stackoverflow.com/q/47829903
tags question: http://stackoverflow.com/q/47749622
tags question: http://stackoverflow.com/q/47827850
tags question: http://stackoverflow.com/q/47768212
tags question: http://stackoverflow.com/q/47854396
tags question: http://stackoverflow.com/q/47793727
tags question: http://stackoverflow.com/q/47702458
tags question: http://stackoverflow.com/q/47705215
tags question: http://stackoverflow.com/q/47732415
tags question: http://stackoverflow.com/q/47811629
tags question: http://stackoverflow.com/q/47704358
tags question: http://stackoverflow.com/q/47700467
tags question: http://stackoverflow.com/q/47719657
tags question: http://stackoverflow.com/q/47729665
tags question: http://stackoverflow.com/q/47792466

http://stackoverflow.com/q/47760505
downvote count: 0
has body: I am trying to open a rather large .xlsx file using openpyxl, and the load_workbook function, but for some reason the file I want to open will not open, and instead will error out. wb=openpyxl.load_workbook(laneReport) print(laneReport) I expect the output from this to be the name of the file I want to open, but instead I get an error message. Traceback (most recent call last): File "C:\Users\tamimia\AppData\Local\Programs\Python\Python36\lib\site-packages\openpyxl\descriptors\base.py", line 57, in _convert value = expected_type(value) ValueError: could not convert string to float: '#REF!' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:/Users/tamimia/Documents/Py/jfu/LaneAnalysis.py", line 55, in &lt;module&gt; main() File "C:/Users/tamimia/Documents/Py/jfu/LaneAnalysis.py", line 50, in main x.checkHeader(laneReport) File "C:/Users/tamimia/Documents/Py/jfu/LaneAnalysis.py", line 32, in checkHeader wb=openpyxl.load_workbook(laneReport) File "C:\Users\tamimia\AppData\Local\Programs\Python\Python36\lib\site-packages\openpyxl\reader\excel.py", line 245, in load_workbook ws_parser.parse() File "C:\Users\tamimia\AppData\Local\Programs\Python\Python36\lib\site-packages\openpyxl\reader\worksheet.py", line 127, in parse dispatcher[tag_name](element) File "C:\Users\tamimia\AppData\Local\Programs\Python\Python36\lib\site-packages\openpyxl\reader\worksheet.py", line 286, in parser_conditional_formatting cf = ConditionalFormatting.from_tree(element) File "C:\Users\tamimia\AppData\Local\Programs\Python\Python36\lib\site-packages\openpyxl\descriptors\serialisable.py", line 79, in from_tree obj = desc.expected_type.from_tree(el) File "C:\Users\tamimia\AppData\Local\Programs\Python\Python36\lib\site-packages\openpyxl\descriptors\serialisable.py", line 79, in from_tree obj = desc.expected_type.from_tree(el) File "C:\Users\tamimia\AppData\Local\Programs\Python\Python36\lib\site-packages\openpyxl\descriptors\serialisable.p…
tagged with: excel
has comment: http://stackoverflow.com/comment/82484224
score: 2
tagged with: python
has comment: http://stackoverflow.com/comment/82482433
favorite count: 0
type: Question
has title: Openpyxl won't load my workbook
answer count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: openpyxl

http://stackoverflow.com/comment/82533261
score: 2
comment on: http://stackoverflow.com/q/47785766
has text: create minimal working example so everyone could run it and make modifications.
type: QuestionComment
type: Comment

http://stackoverflow.com/a/52972147
answers question: http://stackoverflow.com/q/47784483
type: Answer
score: -1
has body: I resolved it setting an image from the setting panel of windows, this way windows will reload it from the disk at reboot, then the program will just override the same image with the other that you want to change and re-call ctypes.windll.user32.SystemParametersInfoW(20, 0, filepath, 0) this way windows will reload the latest image the program overrided.
upvote count: 0
downvote count: 1

http://stackoverflow.com/comment/82578526
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47808590
has text: That's your hint to not use `exec` and `eval` ;-)

http://stackoverflow.com/comment/82397630
type: Comment
comment on: http://stackoverflow.com/a/47718661
type: AnswerComment
has text: That still creates a cross-join from the many to many relation.
score: 0

http://stackoverflow.com/a/47773978
type: Answer
answers question: http://stackoverflow.com/q/47773873
has body: You shouldn't be using JsonResponse with a serializer anyway, as this means you serialize to JSON twice. What you should do here is to serialize each of those objects separately, to Python structures, then send that to JsonResponse. context = { 'question': serializers.serialize('python', [fup.question])[0], 'answers' : serializers.serialize('python', answers) } return JsonResponse(context , safe=False) Note that this is not really a good way of doing things, and if you are trying to do complex serialization you should really use Django REST Framework.
upvote count: 2
score: 2
accepted answer of: http://stackoverflow.com/q/47773873
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82509196

http://stackoverflow.com/comment/82559951
type: QuestionComment
has text: it is being read from a file, via filestream over a directory
score: 0
comment on: http://stackoverflow.com/q/47785723
type: Comment

http://stackoverflow.com/q/47769040
tagged with: python-requests
type: Question
has comment: http://stackoverflow.com/comment/82524126
score: 0
tagged with: python
has title: post data to search box using python request
has body: I'm trying to perform a symbol search in "https://www.investing.com", I checked the inspect tool and find out exact post request that used in search. post request So I use the code: url = 'http://www.investing.com/search/service/search' header = { 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36', } form_data = { 'search_text': symbol, 'term': symbol, 'country_id': '0', 'tab_id': 'All' } response = requests.post(url, data = form_data, headers = header) Trying to land on the url: "https://www.investing.com/equities/stamps.com-inc" However, the response always lead me to the mainpage (https://www.investing.com) I tried to include all the headers exacting matching that in the inspect tool but still no luck. Can someone help me with that?
tagged with: post
has comment: http://stackoverflow.com/comment/82499775
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/47837339
tagged with: python
type: AnsweredQuestion
has body: I am very new to python. I took a bioinformatics class this semester and for my final project I want to create an app that we can use in my lab in the future. I have created and tested the actual program in PyCharm, but I want to integrate it with a GUI and create an executable so that it can be used by anyone without having to open an IDE. So far I have a simple frame with a button that gets the pathway for the input file. I want to take this pathway and insert it into my already existing code. From the wxGlade code, nested under class MyFrame(wx.Frame): : def OnOpenFileDialog(self, event): # wxGlade: MyFrame.&lt;event_handler&gt; dlg = wx.FileDialog(self, message="Choose a file") if dlg.ShowModal() ==wx.ID_OK: f = dlg.GetPath() filename_input = re.sub("\\\\", "/", f) dlg.Destroy() I want to take filename_input and put it here: columns = defaultdict(list) # each value in each column is appended to a list with open(filename_input) as file_object: # open the file reader = csv.DictReader(file_object, delimiter='\t') # assign the file reader for row in reader: # read a row as {column1: value1, column2: value2,...} for (k,v) in row.items(): # for each column (position) and value (residue) if v != '': # if the value isn't blank columns[k].append(v) # append the residue to a list for that position But it seems like anything defined within the OnOpenFileDialog block only exists with that block. So how should I go about integrating my code into the GUI? I feel like pasting it all under def OnOpenFileDialog would be very ugly and bad. I really don't know where to start. Sorry if this question is confusing, I will try to clarify if need be. Thanks
answer count: 1
has answer: http://stackoverflow.com/a/48356766
type: Question
accepted answer: http://stackoverflow.com/a/48356766
score: 0
has title: Integrating my code with a wxglade GUI
tagged with: user-interface
tagged with: wxglade

http://stackoverflow.com/a/47851723
has body: Still using groupby + value_counts df.groupby(['Path','Type']).Category.apply(pd.value_counts).unstack().fillna('') Out[121]: A B C Path Type Blue Image 1 Video 1 Green Video 1 Yellow Image 1 2 Video 1 1 Or we using pivot_table pd.pivot_table(df.reset_index(),index=['Path','Type'],columns=['Category'],values='index',aggfunc='count') Out[123]: Category A B C Path Type Blue Image NaN 1.0 NaN Video 1.0 NaN NaN Green Video 1.0 NaN NaN Yellow Image 1.0 NaN 2.0 Video 1.0 1.0 NaN
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47851667
upvote count: 2
accepted answer of: http://stackoverflow.com/q/47851667
type: Answer
score: 2
downvote count: 0

matplotlib-basemap
type: Tag
tags question: http://stackoverflow.com/q/47767394
tag name: matplotlib-basemap

http://stackoverflow.com/q/47808198
has comment: http://stackoverflow.com/comment/82577676
type: Question
has answer: http://stackoverflow.com/a/47808217
score: 0
tagged with: pandas
tagged with: python
has body: I have a defined process as below. def process(df): date = df.loc[0,'month'] for i in df.index: if pd.isnull(df.loc[i, 'month'])==True: df.loc[i, 'month'] = date else: date = df.loc[i, 'month'] I could run it for one excel file, however when I used: for file in os.listdir(directory): process(file) I have the Error message: AttributeError: 'str' object has no attribute 'loc' Any suggestion is much appreciated.
type: UnansweredQuestion
has title: .loc has no attribute error when run a defined process for all files in a directory
answer count: 1

http://stackoverflow.com/q/47730535
score: 0
has comment: http://stackoverflow.com/comment/82421697
has comment: http://stackoverflow.com/comment/82423627
tagged with: python
has title: folder gets created but no files in it
linked to: http://stackoverflow.com/q/44730935
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82421721
tagged with: flask
tagged with: vlc
type: Question
has comment: http://stackoverflow.com/comment/82422266
has body: I have a digital ocean droplet which has a linux os on it. On this vm I have a flask webserver and in the __init__.py script I have these two functions: @app.route('/ds') def ds(): fp = "/home/ds/gabo/" pre = 'das_' req_value = create_vlc_command(pre, fp) os.system(req_value) return req_value def create_vlc_command(pre_fn, full_path): pre_sc_path = '--scene-path=' file_name = pre_fn + get_date_time() vid_settings = ("--rate=1 --video-filter=scene " "--vout=dummy --run-time=3 " "--scene-format=png --scene-ratio=24 " "--scene-prefix=") + file_name scene_path = pre_sc_path + full_path req_value = ("vlc {arg_name} {vid_settings} {scene_path} " "{quit}").format(arg_name="htttp:examplexxx.com", vid_settings=vid_settings, scene_path=scene_path, quit='vlc://quit') return req_value When I hit ctrl + r on the droplet-ip/ds i can see the req_value and the folder gets created on the vm but I don't see any pictures in that folder. But when I run the req_value later in the terminal, the pictures get created. The command on the page: vlc http://exampleamplexxx.com/dsa.m3u8 --video-filter=scene --vout=dummy --run-time=3 --scene-format=png --scene-ratio=24 --scene-prefix=pi_pic_lc_2017_12_09_15_58_30 --scene-path=/home/ds/gabo/ vlc://quit Is something wrong with the os.system or what am I doing wrong?

http://stackoverflow.com/comment/82412176
type: Comment
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/47725773
has text: Better always provide a simple example.

http://stackoverflow.com/q/47781870
score: 2
upvote count: 2
tagged with: while-loop
answer count: 0
downvote count: 0
has title: Output file from python function using tweepy won't stop printing
tagged with: twitter
favorite count: 0
type: Question
tagged with: function
type: UnansweredQuestion
tagged with: python
tagged with: tweepy
has body: I am trying to use this function I found to gather tweets from a specified user, populate a list with the text portion of the json object that the tweet is comprised of, make some modifications to the string, and then print to a text file. Here is my code: import tweepy import re # Twitter API credentials consumer_key = "" consumer_secret = "" access_key = "" access_secret = "" def get_all_tweets(screen_name): # Twitter only allows access to a users most recent 3240 tweets with this method #authorize twitter, initialize tweepy auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_key, access_secret) api = tweepy.API(auth) # initialize a list to hold all the tweets alltweets = [] # make initial request for most recent tweets new_tweets = api.user_timeline(screen_name = screen_name, count = 200, include_rts = False) # save most recent tweets alltweets.extend(new_tweets) # save the id of the oldest tweet minus one oldest = alltweets[-1].id - 1 # keep grabbing tweets until there are no tweets left to grab while len(new_tweets) &gt; 0: print ("getting tweets before %s" % (oldest)) # all subsequent requests use the max_id parameter to prevent duplicates new_tweets = api.user_timeline(screen_name = screen_name, count = 200, max_id = oldest) # save most recent tweets alltweets.extend(new_tweets) # update the ID of the oldest tweet less one oldest = alltweets[-1].id - 1 print ("...%s tweets downloaded so far" % (len(alltweets))) # transform the tweets into a 2D array that will populate the outtweets = [] for tweet in alltweets : outtweets.append(tweet.text.encode("utf-8")) # outtweets = [[tweet.text.encode("utf-8")] for tweet in alltweets] print(outtweets[:1]) outtweets = [w for tweet_text in outtweets for w in tweet_text.split()] # Split each individual word into a string outtweets = [w for w in outtweets if w] # Print only words to the list / Gets rid of blank strings outtweets = [w.lower() for w in outtweets] # Cast all words to lowercase …

http://stackoverflow.com/q/47717760
has title: How to use Sphinx with other template?
type: Question
upvote count: 2
score: 2
downvote count: 0
has answer: http://stackoverflow.com/a/47721103
accepted answer: http://stackoverflow.com/a/47721103
tagged with: python-sphinx
has body: I'm want to write a documentation for my new module, and I was inspired by the docs of sentry.io, and I find out that they are using the Sphinx module, but the interface isn't the default one. Is there a way to change the template, or the sentry team made that for their own purposes?
answer count: 1
favorite count: 0
type: AnsweredQuestion
tagged with: sentry
tagged with: python

http://stackoverflow.com/q/47738043
has comment: http://stackoverflow.com/comment/82436993
has comment: http://stackoverflow.com/comment/82436928
has body: I am trying to extract only noun and noun phrases to address data (a column a inside csv file). I was able to remove the stop words, punctuations and numbers from the data. Also was able POS tag the data, but not able Extract Noun Phrases and attach back to data frame. Let me know what went wrong stopwords=nltk.corpus.stopwords.words('english') user_defined_stop_words=['hong','kong','hk','kowloon','hongkong'] new_stop_words=stopwords+user_defined_stop_words data['Clean_addr'] = data['Adj_Addr'].apply(lambda x: ' '.join([item.lower() for item in x.split()])) data['Clean_addr']=data['Clean_addr'].apply(lambda x:"".join([item.lower() for item in x if not item.isdigit()])) data['Clean_addr']=data['Clean_addr'].apply(lambda x:"".join([item.lower() for item in x if item not in string.punctuation])) data['Clean_addr'] = data['Clean_addr'].apply(lambda x: ' '.join([item.lower() for item in x.split() if item not in (new_stop_words)])) texts = data['Clean_addr'].tolist() tagged_texts = pos_tag_sents(map(word_tokenize, texts)) data['POS']=tagged_texts data['POS']=data['POS'].apply(lambda x:' '.join([item[0] for item in x if (item[0][1]=='NNP' or item[0][1]=='NNS')])) Sample Dump of the File I am using https://www.dropbox.com/s/allhfdxni0kfyn6/Test.csv?dl=0
has comment: http://stackoverflow.com/comment/82436902
type: Question
has comment: http://stackoverflow.com/comment/82436732
has title: Not able to attach extracted POS taged Noun phrases to pandas data frame
accepted answer: http://stackoverflow.com/a/47738396
tagged with: python
tagged with: nlp
has comment: http://stackoverflow.com/comment/82436504
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82436888
score: 0
has answer: http://stackoverflow.com/a/47738396
tagged with: pandas
has comment: http://stackoverflow.com/comment/82436385
answer count: 1

http://stackoverflow.com/a/47762111
score: 1
answers question: http://stackoverflow.com/q/47761983
type: AcceptedAnswer
type: Answer
has body: merge+fillna g=df1.merge(df2,how='outer') g['Zip']=g.set_index('County').Zip.fillna(df3.set_index('County').Zip.to_dict()).values g Out[1014]: Zip County Zipcount Date Countycount 0 111.0 A 3.0 1/1/17 5.0 1 111.0 A 4.0 1/2/17 6.0 2 112.0 B 5.0 1/1/17 1.0 3 113.0 B 3.0 1/2/17 NaN 4 115.0 C NaN 1/1/17 4.0
accepted answer of: http://stackoverflow.com/q/47761983
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/82529713
comment on: http://stackoverflow.com/a/47784164
type: Comment
type: AnswerComment
has text: Exactly what I was looking for. Another nice feature would be to have it accept no parenthesis. Is that breaking pythonic rules though? What is the difference between doing it this way and using a class with `__init__` and `__call__`? I ran across that some places too.
score: 0

http://stackoverflow.com/comment/82526819
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47782681
has text: How do I make this work without rounding (just diaplaying the first i decimal digits)
score: 0

http://stackoverflow.com/a/47761788
answers question: http://stackoverflow.com/q/47761619
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/82485390
has body: What this will often times mean is that your dataframe does not contain a 'Close' column. Trailing whitespaces or wrong upper/lowercase characters can be the source. Make sure that your actual column name is not like ' Close' or 'close' .
upvote count: 1
downvote count: 1

http://stackoverflow.com/q/47844949
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82665432
has comment: http://stackoverflow.com/comment/82654753
has comment: http://stackoverflow.com/comment/82672647
type: UnansweredQuestion
tagged with: windows
has comment: http://stackoverflow.com/comment/82664042
tagged with: stdout
tagged with: python
linked to: http://stackoverflow.com/q/14058453
linked to: http://stackoverflow.com/q/47392423
tagged with: python-multiprocessing
has comment: http://stackoverflow.com/comment/82654446
has comment: http://stackoverflow.com/comment/82654255
linked to: http://stackoverflow.com/q/9226519
has body: I'm trying to stop a script from outputting text to the command line. It uses selenium in combination with chromedriver and chrome. I am using multiprocessing which could be relevant to the problem. I've tried starting from command line in windows with this: python foo.py 1&gt;nul This redirects stdout to nothing and works on my own print statements, but i still get output from chromedriver (or chrome). I have tried redirecting all the numerical handles from 0-9 but that doesn't help. What can i do to silence the modules i am importing? I would prefer being able to remove the clutter while keeping my own ability to print to screen, but right now i'd take anything. Output examples: DevTools listening on ws://127.0.0.1:12818/devtools/browser/089e9b8d-66ce-431c-8486-abf1db2e1bc1 [10752:15088:1216/122840.419:ERROR:shader_disk_cache.cc(238)] Failed to create shader cache entry: -2 [27752:21264:1216/123032.960:ERROR:process_metrics.cc(105)] NOT IMPLEMENTED I have also tried contextlib.redirect_stdout but this doesn't work on subprocesses and i spawn multiple via multiprocessing module.
downvote count: 0
has comment: http://stackoverflow.com/comment/82664183
score: 1
upvote count: 1
answer count: 1
has answer: http://stackoverflow.com/a/66735515
has title: Redirecting stdout not working for all output
has comment: http://stackoverflow.com/comment/82664407
has comment: http://stackoverflow.com/comment/82654896
favorite count: 0
type: Question

http://stackoverflow.com/comment/82579707
comment on: http://stackoverflow.com/q/47794066
has text: Thanks for your answer, I'm installing VTK in debian linux(last version) with the commands in the following website : https://unix.stackexchange.com/questions/306682/how-to-install-vtk-with-python-wrapper-on-red-hat-enterprise-linux-rhel/306683 But at the end and after make test command, it gives me the mentioned error,
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/82550784
comment on: http://stackoverflow.com/q/47794758
score: 0
type: Comment
type: QuestionComment
has text: Look into the `Button` [documentation](http://effbot.org/tkinterbook/button.htm). They give a nice example of the `command` argument

http://stackoverflow.com/comment/82513149
has text: @Divakar same problem...
comment on: http://stackoverflow.com/q/47775896
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/47744474
type: Answer
score: 0
has body: Returns any MarketGroup that has a descendant MarketGroup_Name with text "Partido". //div[@class="MarketGroup" and descendant::div[@class="MarketGroup_Name" and contains(text(),"Partido")]]
answers question: http://stackoverflow.com/q/47744329

http://stackoverflow.com/comment/82606296
comment on: http://stackoverflow.com/q/47821737
has text: By read only - do you mean the readonly file or the protected cells in the report?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47722111
has title: Tensorflow r1.4 estimator save/load
has comment: http://stackoverflow.com/comment/82417413
score: 2
upvote count: 2
answer count: 0
downvote count: 0
type: UnansweredQuestion
tagged with: tensorflow
favorite count: 0
type: Question
has body: I am trying to LOAD a previously saved Tensor DNNRegressor to predict from new data to verify the saving/loading process using the estimator classes API r1.4. The problem could be either in how I am using the loader or how I am saving the model. The data is from a csv for real numbers for training with a future unknown input size so I have not used keys in the feature_columns Training train_inputs =numpy.float32(dftrain.values) train_outputs =numpy.float32(dftest.values) feature_columns=[tf.feature_column.numeric_column("XX", shape=[103])] estimator=tf.estimator.DNNRegressor(feature_columns=feature_columns, hidden_units=[20]) input_fn_train = tf.estimator.inputs.numpy_input_fn( x={"XX": numpy.array(train_inputs)}, y=numpy.array(train_outputs), batch_size=batch_size, num_epochs=None, shuffle=False) estimator.train(input_fn_train, steps=num_steps) Saving feature_spec = tf.feature_column.make_parse_example_spec(feature_columns) export_input_fn = tf.estimator.export.build_parsing_serving_input_receiver_fn(feature_spec) export_dir = estimator.export_savedmodel(output_directory, export_input_fn) Loading and new Prediction predict_fn = predictor.from_saved_model(load_folder) train_X =numpy.float32(dftrain.values) Predict just first row traininput=train_X[0] predict_input_fn_test = tf.estimator.inputs.numpy_input_fn( x={"XX": numpy.array(traininput)}, num_epochs=1, shuffle=False) predictions = predict_fn(predict_input_fn_test) giving error input_keys = set(input_dict.keys()) AttributeError: 'function' object has no attribute 'keys'
tagged with: python

http://stackoverflow.com/a/47833642
has body: Using triple ' with open('data.txt', 'r') as f: textfile_temp = f.read() print(textfile_temp.split('''first ATOMIC CHARGES -----------------------''')[1].split('My charges : -0.0000000')[0])
answers question: http://stackoverflow.com/q/47833097
score: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/82630427
type: Answer

http://stackoverflow.com/q/47781828
upvote count: 1
score: 1
tagged with: datetime
tagged with: python
has title: Suddently I get this error "cannot set a Timestamp with a non-timestamp"
has comment: http://stackoverflow.com/comment/82887321
favorite count: 0
type: Question
answer count: 0
type: UnansweredQuestion
downvote count: 0
has body: Still feeling as a newbie. :-) For some time I have collected stock data from Yahoo both on a Linux Mint 18.2 32-bit and a new Linux Mint 18.2 64-bit. Suddenly today I get an error on my 64-bit system when plotting the data. The 32-bit system is working I get two errors: The first is: The file pandas/_libs/index.pyx could not be opened. Reason: [Errno 2] Ingen sådan fil eller filkatalog: 'pandas/_libs/index.pyx' It is correct that the file is not in _libs but it do not help to get it from Github and on the 32-bit system it is also missing. The 32-bit system has pandas 0.20.3 and the 64-bit system has pandas 0.21.0. I think is was updated when I installed the fix_yahoo_finance on the 64-bit system. My 32-bit system has an old version. The second error is: Exception "unhandled ValueError" cannot set a Timestamp with a non-timestamp File: pandas/_libs/index.pyx, Line: 509 My code is: import pandas as pd import csv import glob import matplotlib.pyplot as plt import pylab import numpy as np from matplotlib.widgets import CheckButtons import datetime startplot = datetime.datetime(2017,1,1) end = datetime.date.today() print(startplot) ferms = glob.glob("DOWJones_stock/*.csv") for ferm in ferms: data = pd.read_csv(ferm, header=0) data['Date'] = pd.to_datetime(data['Date']) data["20d"] = np.round(data["Close"].rolling(window = 20, center = False).mean(), 2) data["70d"] = np.round(data["Close"].rolling(window = 70, center = False).mean(), 2) data['plot'] = (data['Date'] &gt; startplot) &amp; (data['Date'] &lt;= end) plotdata=data[data['plot']] plotdata # print(data) # data.head() pylab.rcParams['figure.figsize'] = (25, 14) plt.rcParams['figure.dpi'] = 80 plt.rcParams['legend.fontsize'] = 'medium' plt.rcParams['figure.titlesize'] = 'large' plt.rcParams['figure.autolayout'] = 'true' plt.rcParams['xtick.minor.visible'] = 'true' plt.rcParams['grid.linestyle'] = '-' plt.rcParams['grid.color'] = 'k' plt.xlabel('Date') plt.ylabel('Close') plt.title(ferm) plt.plot(plotdata.loc[:,'Dat…
tagged with: linux
tagged with: 32bit-64bit
tagged with: pandas

http://stackoverflow.com/q/47803867
downvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/82569365
has comment: http://stackoverflow.com/comment/82569387
favorite count: 0
type: Question
has title: Why doesn't my input work inside an if condition
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82570461
tagged with: python
has answer: http://stackoverflow.com/a/47803899
has body: I don't know why my inputs inside the if condition don't work when I run the code. Any help would be appreciated: V = input("Ingresar A, si quieres calcular el ahorro anual, o M, si quieres calcular el ahorro mensual") def M_o_A(V): if V == "A": P = input("Ingrese el porcentaje que quiere calcular: ") S = input("Ingrese su sueldo mensual: ") T = (P * S / 100) * 12 print "Si usted ahorra el ",P,"% de su sueldo por un año, tendras ",T,"pesos." elif V == "M": PM = input("Ingrese el porcentaje que quiere calcular: ") SM = input("Ingrese su sueldo mensual: ") TM = PM * SM / 100 print "Si usted ahorra el ",PM,"% de su sueldo, tendras ",TM,"pesos."
score: 0
upvote count: 1

http://stackoverflow.com/a/47774037
type: Answer
answers question: http://stackoverflow.com/q/47773848
has comment: http://stackoverflow.com/comment/82512885
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47773848
has body: I would suggest using multiprocessing instead of threading, with the Pool class you can map a function generate_random_number to an iterable range(1,100). Here is an example that does what you want: N.B. 100 threads is a little overkill for such a small iterable. import multiprocessing from random import randint def generate_random_number(n): random_number = randint(0, 99) return f'{n}th random number: {random_number}' if __name__ == '__main__': pool = multiprocessing.Pool(100) generated_numbers = pool.map(generate_random_number, range(100)) print(generated_numbers)

http://stackoverflow.com/comment/82637140
comment on: http://stackoverflow.com/a/47836271
type: Comment
type: AnswerComment
has text: @Vishwas `dfs = ['df1', 'df2', ...]` is a list of strings. `[df1, ds2, ...]` is a list of dataframes. see the difference?
score: 1

http://stackoverflow.com/comment/82412064
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47725684
has text: Please refer to https://stackoverflow.com/a/29418461/5916727
score: 0

http://stackoverflow.com/comment/82416324
comment on: http://stackoverflow.com/a/47727911
type: AnswerComment
has text: so that we can use database with classes? Can you provide a rough example.
score: 0
type: Comment

http://stackoverflow.com/q/47736881
has body: On a sever at work (Apache 2.2.3), I am trying to activate my first ever Hello World in with Flask. I can't find logs for errors in any typical recommended locations. I have made a virtualenv in /home/nrDee/public_html/rrfexpire This is my rrfexpire.wsgi script: activate_this = '/home/nrDee/public_html/rrfexpire/venv/bin/activate_this.py' execfile(activate_this, dict(__file__=activate_this)) from rrfexpire import app as application This was added to Apache httpd.conf: WSGIDaemonProcess rrfexipre user=apache group=apache threads=5 WSGIScriptAlias /blog /home/nrDee/public_html/rrfexpire/rrfexpire.wsgi &lt;Directory /home/nrDee/public_html/rrfexpire&gt; WSGIProcessGroup rrfexpire WSGIApplicationGroup %{GLOBAL} Order allow,deny Allow from all &lt;/Directory&gt; And this is the my Hello World test (rrfexpire.py): from flask import Flask, render_template app = Flask(__name__) @app.route("/") def hello_world(): return "Hello, World!" print hello_world() if __name__ == '__main__': app.run(host='0.0.0.0', port=8082, debug=True) I was hoping to see the results when I use my Chrome browser at http://departmentServer.company.com/rrfexpire/ but I get nothing. The whole nrDee directory is set to 777 permission to eliminate permissions from preventing this from running. And I tried to confirm Python version (2.7.13) and mod_wsgi compatibility with the command #ldd venv/lib/python2.7/site-packages/mod_wsgi/server/mod_wsgi-py27.so One line from that result reads "libpython2.7.so.1.0 => /usr/local/bin/anaconda/lib/libpython2.7.so.1.0", which I interpreted to mean mod_wsgi is correctly compiled for Python2.7 I'm new to this and have been heavily in Flask and mod_wsgi documentation and feel stuck. Can you please provide guidance on what to check next? Thanks! -nrDee
tagged with: python
has answer: http://stackoverflow.com/a/70175710
tagged with: flask
has comment: http://stackoverflow.com/comment/82434229
has comment: http://stackoverflow.com/comment/82437462
score: 0
has comment: http://stackoverflow.com/comment/82436939
has comment: http://stackoverflow.com/comment/82621275
tagged with: mod-wsgi
has comment: http://stackoverflow.com/comment/82434538
tagged with: virtualenv
has comment: http://stackoverflow.com/comment/82445981
has comment: http://stackoverflow.com/comment/82437602
type: Question
has answer: http://stackoverflow.com/a/47829207
has title: Running Flask with mod_Wsgi through virtualenv
has comment: http://stackoverflow.com/comment/82436942
answer count: 2
has comment: http://stackoverflow.com/comment/82436926
has comment: http://stackoverflow.com/comment/82434604
tagged with: server
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82434866
has comment: http://stackoverflow.com/comment/82437597

http://stackoverflow.com/comment/82568090
type: QuestionComment
has text: You don't want to print a comma after each item, you want to *join* the items with commas.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47803263

http://stackoverflow.com/q/47759123
has comment: http://stackoverflow.com/comment/82486537
has comment: http://stackoverflow.com/comment/82503475
has comment: http://stackoverflow.com/comment/82614082
tagged with: tensorflow
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82481304
has comment: http://stackoverflow.com/comment/82486377
has comment: http://stackoverflow.com/comment/82479617
has comment: http://stackoverflow.com/comment/82480287
has comment: http://stackoverflow.com/comment/82481730
has title: How to get higher accuracy with tensorflow CNN.
upvote count: 2
has comment: http://stackoverflow.com/comment/82483935
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82480000
downvote count: 2
has comment: http://stackoverflow.com/comment/82484614
has comment: http://stackoverflow.com/comment/82486495
tagged with: python
has body: I have created a CNN for classifing images of weeds. The images are 128*128 and I am getting horrible accuracy. Between 18-32%, where I have four classes. Three of them are different types of weed and the last is no weed. Total there is around 1000 images. What am I doing so wrong that my accuracy is this horrible (sometimes worse than guessing). Are my images scaled down to much? (Originally 425*425), are my layers wrong? Are there too little images to train on? And is there any way I can with my current setup improve the results? I am currently new to tensorflow so this is not necessarily optimal. The code are partly from tutorials modified to suit my needs. My code looks like this: Helper functions: def parse_function(filename, label): image_string = tf.read_file(filename) image = tf.image.decode_png(image_string, channels=3) #image_resized = tf.image.resize_image_with_crop_or_pad(image, 128, 128) new_image = tf.image.resize_image_with_crop_or_pad(image, 128,128) return new_image, label # INIT weights def init_weights(shape): init_random_dist = tf.truncated_normal(shape, stddev=0.1) return (tf.Variable(init_random_dist)) # INIT Bias def init_bias(shape): init_bias_vals = tf.constant(0.1, shape=shape) return tf.Variable(init_bias_vals) # CONV2D def conv2d(x, W): # x --&gt; input tensor [batch, H, W, Channels] # W --&gt; [filter H, filter W, Channels IN, Channels OUT] return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME') # Pooling def max_pooling_2by2(x): # x --&gt; [batch, h, w, c] return tf.nn.max_pool( x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME') #Convolutional layer def convolutional_layer(input_x, shape): W = init_weights(shape) b = init_bias([shape[3]]) return tf.nn.relu(conv2d(input_x, W) + b) # Normal (FULLY CONNTCTED) def normal_full_layer(input_layer, size): input_size = int(input_layer.get_shape()[1]) W = init_weights([input_size, size]) b = init_bias([size]) return tf.matmul(input_layer, W) + b My main class def main(): one_hot…
has comment: http://stackoverflow.com/comment/82480012
has comment: http://stackoverflow.com/comment/82672140
has comment: http://stackoverflow.com/comment/82486288
has comment: http://stackoverflow.com/comment/82484713
score: 0
tagged with: conv-neural-network
answer count: 0
has comment: http://stackoverflow.com/comment/82486230
has comment: http://stackoverflow.com/comment/82542138
has comment: http://stackoverflow.com/comment/82479705
tagged with: machine-learning
has comment: http://stackoverflow.com/comment/82480202

http://stackoverflow.com/a/47783349
answers question: http://stackoverflow.com/q/47783297
has body: Not sure why you have % in your query string, it's possible you're confusing it with the %s syntax for string formatting. display = "SELECT * FROM company ORDER BY '%" + column + "%' " It seems what you want is more like this: display = "SELECT * FROM company ORDER BY " + column Or, as I prefer: display = 'SELECT * FROM company ORDER BY {column}'.format(column=column) Of course be careful creating queries like this, you're exposed to SQL security vulnerabilities. It's better to use a parametrised query instead of string interpolation/concatenation, but I don't know which database interface you're using, but it's easy to find that by searching the docs.
score: 0
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/47783297

http://stackoverflow.com/comment/82360372
comment on: http://stackoverflow.com/q/47700149
type: QuestionComment
score: 0
has text: Error that occurred is when entering non-int to "guess".
type: Comment

http://stackoverflow.com/comment/82435171
type: Comment
comment on: http://stackoverflow.com/a/47737392
type: AnswerComment
has text: in the output, it shows Alvin, Peter, James instead of `names = ["Alvin", "James", "Peter"]` from the list. Is there a way that I can arrange it in order?
score: 0

http://stackoverflow.com/a/70175710
score: 0
answers question: http://stackoverflow.com/q/47736881
has body: The easiest solution without using “obscure scripts” is to simply refer to the python within your venv at the beginning of your .wsgi file: #!/path/to/your/venv/bin/python Simple. Logical. No magic. Wish I had thought of it earlier than I did.
type: Answer

coinbase-api
tags question: http://stackoverflow.com/q/47824793
type: Tag
tag name: coinbase-api

http://stackoverflow.com/q/47716239
type: UnansweredQuestion
score: -4
answer count: 1
favorite count: 0
has body: Didn't know how to correctly write the title, so i will try to explain it here. I am making a game, similar to tic tac toe. The play field is 4x4 and i am saving it as an array. I want to make changes in the array during the game, but it will not print out the array each time, rather it makes changes statically. Lets say at the beginning i print out the whole field and under it the user is asked to type a position. He gives it and the changes are being done in the first printed playfield, without calling it again in the shell. Kinda sloppy explanation, sorry about that. play_field = [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]] def print_playfield(): for rows in play_field: print(*['{:&lt;4}'.format(each) for each in rows]) This is the function, which will display the playfield.I've done it with tkinter already, wanna try it without.
type: Question
has answer: http://stackoverflow.com/a/47716305
tagged with: python
linked to: http://stackoverflow.com/q/6840420
has comment: http://stackoverflow.com/comment/82392652
has comment: http://stackoverflow.com/comment/82392697
has title: Replace multiple lines of console output with the contents of a Python array
downvote count: 4
upvote count: 0

http://stackoverflow.com/a/47706614
has comment: http://stackoverflow.com/comment/82374388
score: 0
has body: I think what you are looking for is something along the lines of this: import random try: userin = int(input("Enter the number of desired coin flips: ")) except ValueError: print("Invalid Input") coin = ['H', 'T'] userlist =(random.choices((coin), k=userin)) print('You flipped ' + str(userlist.count('H')) + ' Heads and ' + str(userlist.count('T')) + ' Tails.') print(userlist) k="" for x in range(0, len(userlist)): k=str(k) +"" + str(userlist.pop()) print(k) This is assuming you just want to print the results of the coin flips. Added a try loop at the start in case an integer is not entered. Make sure to import random so that it works as well, also added a missing parentheses at the end of your input statement. Used the list.count() function to find the number of T's or H's in userlist. Also just using str() in your print should work. Hopefully this will serve your purposes.
has comment: http://stackoverflow.com/comment/82373651
has comment: http://stackoverflow.com/comment/82373595
has comment: http://stackoverflow.com/comment/82373453
answers question: http://stackoverflow.com/q/47706418
has comment: http://stackoverflow.com/comment/82373794
type: Answer

http://stackoverflow.com/a/47711970
score: 0
answers question: http://stackoverflow.com/q/47711886
type: Answer
has body: Maybe : print '*' * 80 + '\n' + ' ' * 38 + 'hello' + '\n' + '*' *80 OR If it is python3 a = lambda x,c,mess: print(c*x + ('\n' if not mess else mess)) a(80, '*', None) a(38, ' ', 'Hello') a(80, '*', None)

http://stackoverflow.com/a/47819459
has comment: http://stackoverflow.com/comment/82601079
has comment: http://stackoverflow.com/comment/82601003
has body: If your dictionaries always only have a single key then in Python 2.x: print sorted([{23: (1, 5)}, {59: (2, 3)}, {45: (2, 9)}, {28: (3, 6)}]) Would give: [{23: (1, 5)}, {28: (3, 6)}, {45: (2, 9)}, {59: (2, 3)}] By default in Python 2.x using sorted() will result in a correctly sorted list. For Python 3.x: print(sorted([{23: (1, 5)}, {59: (2, 3)}, {45: (2, 9)}, {28: (3, 6)}], key=lambda x: next(iter(x)))) This uses a lambda function to extract the first (and only) key from the dictionary and use that as the sorting key.
score: 2
accepted answer of: http://stackoverflow.com/q/47819417
has comment: http://stackoverflow.com/comment/82601133
upvote count: 3
answers question: http://stackoverflow.com/q/47819417
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82601456
downvote count: 1
has comment: http://stackoverflow.com/comment/82601034
type: Answer

http://stackoverflow.com/q/47706361
has title: Why are the values for both dictionaries being updated, when I only want one updated? (Python OOP)
score: 0
has comment: http://stackoverflow.com/comment/82373522
answer count: 1
has body: Here is the relevant portion of my code: class Document: def __init__(self): self.term_frequency_per_document = {} self.document_frequency = {} self.term_freq_inv_doc_freq = {} self.file = None self.student_list = [] self.index = 0 def calculate_TFIDF(self): for key in self.term_frequency_per_document: for value in self.term_frequency_per_document[key]: self.term_freq_inv_doc_freq[key] = self.term_frequency_per_document.get(key) for value in self.term_freq_inv_doc_freq[key]: self.term_freq_inv_doc_freq[key][value] = \ (self.term_freq_inv_doc_freq[key][value]) * \ (math.log(26 / float(self.document_frequency.get(value)))) print (self.term_freq_inv_doc_freq) print (self.document_frequency) print (self.term_frequency_per_document) When I execute the calculate_TFDIF method, the values of both the self.term_frequency_per_document and self.term_freq_inv_per_doc dictionaries are being updated, when I only want the latter dictionary's values updated. I know that the erroneous update is occurring in the calculate_TFDIF method, but I cannot figure out why. The term_frequency_per_document dictionary should read: {'student_1': {'love': 1, 'play': 2, 'watch': 1}, 'student_2': {'favorite': 2, 'hobby': 1} After executing the calculate_TFDIF method, the term_freq_inv_doc_freq dictionary should read: {'student_1': {'love': 1.6486586255873816, 'play': 2.121743921370525, 'watch': 1.8718021769015913} 'student_2': {'favorite': 1.9110228900548727, 'hobby': 1.1786549963416462} Unfortunately, both dictionaries look like the latter.
has comment: http://stackoverflow.com/comment/82374410
accepted answer: http://stackoverflow.com/a/47707226
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82372919
has answer: http://stackoverflow.com/a/47707226
tagged with: oop
tagged with: python
has comment: http://stackoverflow.com/comment/82373582
type: Question

http://stackoverflow.com/comment/82664347
has text: Independent of the subplots aspect you can of course use a gridspec to position the subplot or change the figure size. For the simple problem from the question there seems to be no relation between aspect and gridspec or figsize. (Apart from the fact that it makes sense to use a figure size which somehow lets the subplot of the desired aspect look good inside the canvas.)
comment on: http://stackoverflow.com/a/47849854
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/47758406
answer count: 3
has title: Provide default argument value for py.test fixture function
tagged with: pytest
has answer: http://stackoverflow.com/a/78989820
has answer: http://stackoverflow.com/a/66482411
type: Question
accepted answer: http://stackoverflow.com/a/47758594
possible better answer: http://stackoverflow.com/a/66482411
upvote count: 3
has answer: http://stackoverflow.com/a/47758594
downvote count: 0
tagged with: python
favorite count: 0
type: AnsweredQuestion
score: 3
has body: Is there a better way for me to provide default value for argument pytest.fixture function? I have a couple of testcases that requires to run fixture_func before testcase and I would like to use default value for argument in fixture if none of them is provided. The only code I can come up with is as follows. Any better way for me to do it? @pytest.fixture(scope="function") def fixture_func(self, request): argA = request.param['argA'] if request.param.get('argA', None) else 'default value for argA' argB = request.param['argB'] if request.param.get('argB', None) else 'default value for argB' # do something with fixture @pytest.mark.parametrize('fixture_func', [dict(argA='argA')], indirect=['fixture_func']) def test_case_1(self, fixture_func): #do something under testcase pass @pytest.mark.parametrize('fixture_func', [dict()], indirect=['fixture_func']) def test_case_2(self, fixture_func): #do something under testcase pass i wna to use as def test_case_3(self, fixture_func): #do something under testcase pass

http://stackoverflow.com/comment/82531300
has text: I have no idea how to get it to write the way I need it. In other functions, things that have been added show but it prints nothing to the text file. I'm not sure why the list changes when they get to the last function.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47784721

http://stackoverflow.com/comment/88502619
comment on: http://stackoverflow.com/a/47722635
type: Comment
has text: Oh wow ... thank you! I had a similar issue, and forcing the encoding to utf-8 seemed to do the trick for me too, even though the file is already utf-8 unicode.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/82399492
comment on: http://stackoverflow.com/q/47719483
score: 0
type: Comment
has text: @Chris_Rands Thanks, if someone writes an answer with this information (and how I point to a modified list instead of the original) I'll accept it when I get time.
type: QuestionComment

http://stackoverflow.com/comment/82441554
has text: One last thought - I think I've made something similar work by using a different function name for Cython and giving the real name in quotes after: e.g. `double plus_func(double x, double y) "operator()":`. If that doesn't work I _really_ don't know though.
comment on: http://stackoverflow.com/q/47718774
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47796427
downvote count: 0
tagged with: pip
upvote count: 1
tagged with: python
tagged with: virtualenv
tagged with: linux
linked to: http://stackoverflow.com/q/1382925
score: 1
favorite count: 0
type: Question
has title: virtualenv setup with --no-site-packages accesses global packages
answer count: 0
type: UnansweredQuestion
has body: I've setup the virtual env (linux) using: python virtualenv/virtualenv.py rootpy_env --no-site-packages but after activating it I can still "see" the global packages. I can't just upset the PYTHONPATH as suggested in some old thread because it will break other packages that are global and that I need. Executing pip install --upgrade setuptools install the new package in the site/package folder of the python in virtualenv, but seems like when executing python scripts the global package is picked up even though I run the script using ./rootpy_env/bin/python - which is a virtualenv one. Is there a way to force python first to "look" into the local site_packeges? Adding the path to the beginning of PYTHONPATH variable didn't help.

http://stackoverflow.com/comment/82546592
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47792503
has text: Your error is in this line in logistic method: S, R, A = x .. As I can see you are passing proposed to x.So, proposed should have a list having 3 elements.
score: 0

http://stackoverflow.com/comment/82528053
has text: Why '%" + column + "%' and not " + column + "... The % is a wildcard character holder most frequently used in LIKE statement.
score: 1
type: Comment
comment on: http://stackoverflow.com/q/47783297
type: QuestionComment

http://stackoverflow.com/a/47847144
has body: that's what i was searching.... thanks anyway from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt import json @csrf_exempt def hello(request): r = json.loads(request.body) mail = (r['billing']['email']) print (mail) return HttpResponse(r)
type: Answer
score: 1
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47793282

http://stackoverflow.com/a/47845264
score: 1
has comment: http://stackoverflow.com/comment/82654765
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47844961
type: Answer
answers question: http://stackoverflow.com/q/47844961
has body: Assuming this is a valid example text you wish to read from, called something like text.txt: Hello world, it's a nice day today! And you wish to write the encoded characters to a new file, let's say newtext.txt. You can do something like this: d = { "a": 1, "b": 3, "c": 5, "d": 7,"e": 9, "f": 11,"g": 13, "h": 15, "i": 17, "j": 19,"k": 21, "l": 23, "m": 25, "n": 27, "o": 29, "p": 31, "q": 33, "r": 35, "s": 37, "t": 39, "u": 41,"v": 43,"w": 45,"x": 47, "y": 49, "z": 51} # open to be read file with open("text.txt", 'r') as file_open: # create file to write to with open("newtext.txt", 'w') as file_write: for line in file_open: # encode characters new_line = "".join(str(d[c.lower()]) if c.lower() in d else c for c in line) # write to file file_write.write(new_line) # open and print contents of file you just wrote to with open("newtext.txt", 'r') as file_print: print(file_print.read()) Which outputs: 159232329 452935237, 1739'37 1 271759 7149 39297149! Note: You probably will have to modify the code to get exactly want you want, but this gives the general idea.

http://stackoverflow.com/comment/82478807
comment on: http://stackoverflow.com/a/47743506
has text: I guess `unary_function` struct, `binder1st` class and `bind1st` should be wrapped in order to use `bind1st` and then [this answer](https://codereview.stackexchange.com/questions/77546/multiply-vector-elements-by-a-scalar-value-using-stl-and-templates). I am not very familiar how to wrap classes and templates in cython so I am struggling to find out how it should be done.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/88385954
has text: Well, I actually tried to use this today, and it didn't work. I believe it's because I'm using a very particular host provider, which doesn't use the virtual env the same way as I do when I call it manually. I haven't found any workaround so far. But I've read a lot of stuff around and your solution looks like the right way to do it.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47773654

http://stackoverflow.com/q/47833499
has title: Adding rows to a Dataframe to unify the length of groups
score: 1
tagged with: group-by
tagged with: dataframe
tagged with: python
accepted answer: http://stackoverflow.com/a/47833554
has answer: http://stackoverflow.com/a/47833554
type: AnsweredQuestion
tagged with: pandas
tagged with: autofill
downvote count: 0
answer count: 1
upvote count: 1
favorite count: 0
type: Question
has body: I would like to add element to specific groups in a Pandas DataFrame in a selective way. In particular, I would like to add zeros so that all groups have the same number of elements. The following is a simple example: import pandas as pd df = pd.DataFrame([[1,1], [2,2], [1,3], [2,4], [2,5]], columns=['key', 'value']) df key value 0 1 1 1 2 2 2 1 3 3 2 4 4 2 5 I would like to have the same number of elements per group (where grouping is by the key column). The group 2 has the most elements: three elements. However, the group 1 has only two elements so a zeros should be added as follows: key value 0 1 1 1 2 2 2 1 3 3 2 4 4 2 5 5 1 0 Note that the index does not matter.

http://stackoverflow.com/a/47780704
type: Answer
score: 2
answers question: http://stackoverflow.com/q/47778550
upvote count: 3
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47778550
downvote count: 1
has body: I got it working now. I removed my Python 3.6.1 installation and installed Python 3.6.3 from here: https://www.python.org/downloads/release/python-363/ I selected the Windows x86-64 executable installer for my Windows 10 computer. While installing, I chose for "custom installation" so I can check which modules I want or don't want. Apparently, tkinter is present by default. Perhaps I had unchecked it on my last installation (a couple of months ago)? Anyway, I got things working now. But it seems still a bit odd to me that I had to do a complete reinstallation for this to work. A simple pip install tkinter should also do the job (in my opinion).

http://stackoverflow.com/comment/82556102
comment on: http://stackoverflow.com/q/47797615
has text: Your terminology is incorrect. It seems like you're taking 6 elements at a time in strides of 2. Am I wrong?
type: QuestionComment
score: 0
type: Comment

hadoop
tags question: http://stackoverflow.com/q/47757464
tag name: hadoop
type: Tag
tags question: http://stackoverflow.com/q/47707207
tags question: http://stackoverflow.com/q/47766722
tags question: http://stackoverflow.com/q/47832817
tags question: http://stackoverflow.com/q/47850043
tags question: http://stackoverflow.com/q/47776000
tags question: http://stackoverflow.com/q/47812551

http://stackoverflow.com/comment/82473171
type: Comment
type: QuestionComment
has text: Do you mean [scalar](https://softwareengineering.stackexchange.com/a/238045) when you write [singleton](https://en.wikipedia.org/wiki/Singleton_pattern)?
score: 3
comment on: http://stackoverflow.com/q/47755723

http://stackoverflow.com/comment/82510723
comment on: http://stackoverflow.com/a/47771184
type: Comment
score: 0
type: AnswerComment
has text: Now I saw your last edit. That command you mention is used to export an environment variable containing the URI to access the DB with SQLAlchemy. You should substitute the items between square brackets with your corresponding properties.

http://stackoverflow.com/q/47775763
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/82512546
tagged with: python
has body: Is there an opposite of numpy.broadcast_to, e.g. numpy.project_to(array, function, axis)? np.project_to( np.array([[1,1,1], [2,1,3], [2,2,2]], dtype=float), lambda x, y: x/y, axis=1) which would return array([ 1., 0.66666667, 0.5])
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/47776225
answer count: 1
has answer: http://stackoverflow.com/a/47776225
has title: Opposite of numpy.broadcast_to
tagged with: scipy

http://stackoverflow.com/q/47803592
answer count: 1
has body: I have already a database that contains 100 tables. Now, I would like to expose it as a REST-API. I've done this before so I am familiar with the procedure. I create a serializer for the model, a ViewSet for the Serialiizer and an a router. I test it on 2 tables and it works. The problem is that I want to expose all my 100 tables. And doing the same prcedure 100 times is no fun. Is there a way to do it only one time?
type: Question
has comment: http://stackoverflow.com/comment/82568659
tagged with: api
accepted answer: http://stackoverflow.com/a/47804041
tagged with: django
tagged with: python
tagged with: django-rest-framework
type: AnsweredQuestion
score: 0
has title: generate a Django-REST-API directly ?
has answer: http://stackoverflow.com/a/47804041
tagged with: models

http://stackoverflow.com/a/47740293
downvote count: 0
answers question: http://stackoverflow.com/q/47737220
type: Answer
has comment: http://stackoverflow.com/comment/112413306
has body: You can use the append_df_to_excel() helper function, which is defined in this answer: Usage examples: filename = r'C:\OCC.xlsx' append_df_to_excel(filename, df) append_df_to_excel(filename, df, header=None, index=False) append_df_to_excel(filename, df, sheet_name='Sheet2', index=False) append_df_to_excel(filename, df, sheet_name='Sheet2', index=False, startrow=25)
score: 11
upvote count: 11

http://stackoverflow.com/a/47735936
accepted answer of: http://stackoverflow.com/q/47735764
score: 1
has body: It's ez but you should read about regex(regular expressions) cause i don't know the whole data structure: import re search = input("Insert keyword") text ="............." if re.search(r'%s(.*?)\n\n'%(search),text,re.DOTALL) == None: print("Sorry did't found") else: news = re.search(r'%s(.*?)\n\n'%(search),text,re.DOTALL).group() print(news)
type: Answer
answers question: http://stackoverflow.com/q/47735764
downvote count: 0
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82432291

http://stackoverflow.com/a/47815507
has body: Try this chrome_options.add_argument('--host-rules="MAP * localhost"')
has comment: http://stackoverflow.com/comment/82594455
has comment: http://stackoverflow.com/comment/82594779
answers question: http://stackoverflow.com/q/47815334
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/82593873

http://stackoverflow.com/a/47782627
answers question: http://stackoverflow.com/q/47780423
has comment: http://stackoverflow.com/comment/82526634
type: Answer
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47780423
has comment: http://stackoverflow.com/comment/82526653
upvote count: 3
has body: As default columns and rows don't change size but you can use this to change it. columnconfigure(col_number, weight=1) rowconfigure(row_number, weight=1) If you have two rows with different weight then row with bigger weight will resize faster. I added background color to frames to see which one still doesn't change size. from tkinter import * root = Tk() root.columnconfigure(0, weight=1) root.rowconfigure(0, weight=1) f1 = Frame(root, bg='red') f1.grid(row=0, column=0, sticky='news') f1.columnconfigure(0 , weight=1) f1.rowconfigure(1, weight=1) #f1.rowconfigure(2, weight=1) enter = Frame(f1, bg='green') enter.grid(row=1, column=0,columnspan=3,padx=20, sticky='nsew') loginframe = Frame(f1) loginframe.grid(row=2,column=0,columnspan=3, sticky='ew') e1 = Entry(enter,font=('Consolas',15),width=25) e1.insert(0,'E-mail') e1.pack(pady=10) e2 = Entry(enter,font=('',15),show='*',width=25) e2.insert(0,'E-mail') e2.pack(pady=20) loginbutton = Button(loginframe,text='Login!',bg='lightblue',height=2,width=39) loginbutton.pack() account = Frame(f1) account.grid(row=3,column=0,columnspan=3) Label(account,text="Don't have an account yet?").pack(side=LEFT) link = Label(account,text="Sign Up!",cursor='hand2',fg='blue', font=('Helvetica',8,'underline')) link.pack(side=BOTTOM) root.mainloop() Before resize: After resize with columnconfigure and rowconfigure : Without columnconfigure and rowconfigure
score: 3

http://stackoverflow.com/q/47762973
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47804858
score: 6
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/52040980
upvote count: 6
tagged with: multiprocessing
has title: Python (Pytorch) Multiprocessing throwing errors: Connection reset by peer and File Not Found
tagged with: pytorch
answer count: 2
downvote count: 0
has body: I'm trying to get something working similarly to keras' "fit_generator" method. Basically, I have a (very) large data file of mini-batches and I want to have my CPU grab mini-batches and populate a queue parallel to my GPU taking mini-batches from the queue and training on them. By having the CPU work in parallel to the GPU (as opposed to having the CPU grab a batch and making the GPU wait for the CPU before it trains on that batch) I should be able to reduce my training time by about half. I have benchmarked how long it takes the CPU to grab a mini-batch, and it's taking a comparable amount of time to how long it takes my GPU to train on one mini-batch, so parallelizing the CPU and GPU should work alright. I haven't found a built-in method in pytorch to do this, if there is one, please let me know. So I have tried to use the torch.multiprocessing module to do what I want, but I'm not able to complete the training as I always get some sort of error right before training is completed. The torch.multiprocessing module should be a wrapper with essentially all the same functionalities as the regular multiprocessing module except it allows pytorch tensors to be shared between processes. Basically, I have set up my code to have 2 functions, a loader function, and a trainer function like so: def data_gen(que,PATH,epochs,steps_per_epoch,batch_size=32): for epoch in range(epochs): for j in range(steps_per_epoch): with h5py.File(PATH,'r') as f: X = f['X'][j*batch_size:(j+1)*batch_size] Y = f['Y'][j*batch_size:(j+1)*batch_size] X = autograd.Variable(torch.Tensor(X).resize_(batch_size,256,25).cpu()) Y = autograd.Variable(torch.Tensor(Y).cpu()) que.put((X,Y)) que.put('stop') que.close() return def train_network(que,net,optimizer,epochs): print('Training for %s epochs...' %epochs) for epoch in range(epochs): while(True): data = que.get() if(data == 'stop'): break net.zero_grad() net.hid = net.init_hid() inp,labels = data inp = inp.cuda() labels = labels.cuda() out,hid = net(inp) …

http://stackoverflow.com/comment/82647636
has text: K nevermind got it to work with Pillow. I'll give you your thumbs up
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47840768

http://stackoverflow.com/q/47784295
type: Question
has title: Anaconda Package issue: An internal module cannot find a data file located in the same directory
score: 2
upvote count: 2
downvote count: 0
tagged with: setup.py
tagged with: package
answer count: 1
has body: I am building a python 3.6 package using the anaconda conda package framework. The package seems to work fine with respect to the source files. There are no build errors, etc. However, I am trying to add a new functionality where I store some small CSV data files in the package. I want to load the data using pandas The problem I am running into is that I cannot seem to reference the relative file path correctly from within the package. So code that would work if I were in say a Jupyter notebook does not work when I am inside of a package. The path issue seems to be the way the problem presents itself, but I suspect it has more to do with how the internal addressing is handled in a package. The error message is: FileNotFoundError: File b'data.csv' does not exist The strange thing about this error is that the data.csv file is in the same directory as the python file that is trying to access it. So I don't get why the python module reader.py below can't seem to find this file. So let me give a minimal example of the package structure and code. /project /docs /packaging /conda_build_files bld.bat build.sh meta.yaml /src /data __init__.py reader.py data.csv #PROBLEM AREA __init__.py module1.py setup.py README.rst So the problem is that the file reader.py uses pandas to read the csv file into a dataframe. Module1 then calls on reader to obtain the data. So the code is setup like: ##reader.py import pandas as pd class Reader(): def read(): return pd.read_csv('data.csv') Then in module1 I have the code as: ##module1.py from .data.reader import Reader import pandas as pd def main(): dat = Reader.read() print(dat.head()) So this is where I am getting the odd error about data.csv does not exist. Now in this case I don't even need a relative import because the Reader class and the data.csv file are in the same folder. Yes for some reason I get this strange error message. The data.csv file is included in the MANIFEST.in file. My setup.py looks like this. try: from setuptools imp…
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47784389
accepted answer: http://stackoverflow.com/a/47784389
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
tagged with: conda
favorite count: 0

http://stackoverflow.com/comment/82513736
comment on: http://stackoverflow.com/a/47776077
type: AnswerComment
has text: @josh - I think it working without transform also because it return Series with same size as groups sizes - data are not aggregate like `mean`
score: 1
type: Comment

http://stackoverflow.com/comment/82522273
comment on: http://stackoverflow.com/q/47780423
type: Comment
type: QuestionComment
has text: The widgets inside f1. I used frame.grid to place them all and my raise_frame function raises the given frame above the others
score: 0

http://stackoverflow.com/comment/82579630
has text: @NiranjRajasekaran sorry, i do not know how to make sure my print statement fits within the box. In anycase, is there a documentation for the login decorator? I have seen it though i am not sure how to use it.
comment on: http://stackoverflow.com/q/47809064
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/82708505
type: AnswerComment
comment on: http://stackoverflow.com/a/47850765
has text: Thanks. This keeps the interface simple, as I wanted. A decorator reads more pythonic to me. I am running on python 3.6 (production) and version 7, 11, 13 on test versions. so I'll need to upgrade first.
type: Comment
score: 0

http://stackoverflow.com/a/47745880
answers question: http://stackoverflow.com/q/47745595
downvote count: 0
type: Answer
upvote count: 1
has body: You do not need groupby to return values for one 'ID'. Use the following with boolean indexing and tolist: df[df.Type == 2].ID.tolist() Output: [100654, 100655]
score: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47745595
has comment: http://stackoverflow.com/comment/82451825

http://stackoverflow.com/a/47842529
answers question: http://stackoverflow.com/q/47842283
score: 1
downvote count: 0
upvote count: 1
has body: The practical solution to this question was answered by Kirkland. Here's a bit of context, should anyone else wind up here. The issue is that csv.DictReader() produces an instance of type DictReader, which, per the docs, "operates like a regular reader." That means that reading values from a DictReader depletes the contents of the instance. After the first round of the inner loop, there's nothing left in secondDataSet. On future iterations, the inner loop doesn't have any elements to iterate over. This can be verified by adding flags to the print statements: def processCommandCenterFile(data): ... for firstDataSetRecord in firstDataSet: ... print("first print:", firstDataSetNumber) for secondDataSetRecord in secondDataSet: print("second print:", firstDataSetNumber) ... processCommandCenterFile(data) Output: ('first print:', '143739629') ('second print:', '143739629') ('second print:', '143739629') ('second print:', '143739629') ('second print:', '143739629') ('second print:', '143739629') ('second print:', '143739629') ('second print:', '143739629') ('second print:', '143739629') ('second print:', '143739629') ('first print:', '143739629') ('first print:', '143750196') ('first print:', '143750196') ('first print:', '143739646') ('first print:', '143739646') ('first print:', '143739661') ('first print:', '143739661') ('first print:', '143739718') The best option, as Kirkland noted, is to convert the DictReader to a list of dicts, e.g., list(csv.DictReader(file, fieldnames=headers)) (Or just use Pandas.)
type: Answer

http://stackoverflow.com/a/47766573
type: AcceptedAnswer
has body: Simply convert all the strings to floats when splitting the lines: data_temp = line.map(lambda line: [float(i) for i in line.split(" ")]) Or you can read the data as a dataframe and infer the types: df = (spark.read .schema(schema) .option("header", "true") .option("inferSchema", "true") .csv("some_input_file.csv")) For more information about different options when reading csv files, see here.
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47766256
answers question: http://stackoverflow.com/q/47766256
type: Answer
score: 1

http://stackoverflow.com/comment/82482726
comment on: http://stackoverflow.com/q/47759895
has text: It’s more of a hint than forcing you. You could move the `from z_misc import general_scripts` inside of the `refresh_from_db` method, but when you find yourself doing that it’s an indication that you might not have the right structure.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/47799382
score: 0
has comment: http://stackoverflow.com/comment/82560366
tagged with: mitmproxy
has comment: http://stackoverflow.com/comment/82560177
has body: I have a in-line python script for mitmdump I would like to output coloured text to a terminal window. I need it to work on all three platforms (Mac, Linux and Windows 7, 8 and 10) and importantly not require the installation of python, python modules or any other third party tool. ANSI escape codes obviously would be the solution were it not for the fact that Windows 7 and 8 do not support them. Since mitmproxy for Windows works without needing to install any form of python, and also prints coloured text to the terminal itself, there has to be a way, I just do not know what it is. I have searched for an answer and not found a solution, my apologies if I missed one.
has comment: http://stackoverflow.com/comment/82560437
type: Question
has comment: http://stackoverflow.com/comment/82560137
accepted answer: http://stackoverflow.com/a/47824858
answer count: 1
has comment: http://stackoverflow.com/comment/82559918
tagged with: python
has answer: http://stackoverflow.com/a/47824858
has title: Coloured Terminal Text for a mitmdump in-line Python script without additional modules
type: AnsweredQuestion

http://stackoverflow.com/comment/82599025
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47817969
has text: Have edited my code to make it more reasonable. And I want to avoid that to reduce space complexity.

http://stackoverflow.com/q/47813635
has answer: http://stackoverflow.com/a/47813788
has body: a Python cgi script receive a POST XMLHttpRequest with content type: application/x-www-form-urlencoded. The values are not encoded. This looks like this: xhr.open("POST", "URL", true); xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xhr.send('RID=123&amp;RName=Bäcker'); in Chromes developer Tools, the Form Data in Datasource looks like this in source: RID=123&amp;RName=Bäcker or like this in parsed view: RID: 123 RName: Bäcker The python3 script get the form in a fieldstorage: #! /usr/bin/env python3 # -*- coding: UTF-8 -*- import cgi myform = cgi.FieldStorage() print(str(myform["RName"].value)) the print output is B\xe4cker? I have tried to use .encode('iso-8859-1') or decode('utf-8') but it is not very successfull. How can i change the encoding or code type that it will be displayed correctly?
has title: special chars in CGI Python \\xe4 not ä
tagged with: python
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/47813788
answer count: 1
tagged with: cgi
tagged with: character-encoding
tagged with: special-characters
type: Question
tagged with: python-3.x

wavelet
tag name: wavelet
type: Tag
tags question: http://stackoverflow.com/q/47843671

http://stackoverflow.com/comment/82395200
comment on: http://stackoverflow.com/q/47717248
score: 0
has text: Little tip: try to be consistent with your use of plural in variable names, otherwise one day you will drive yourself mad.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47740671
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/82441919
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/47741007
upvote count: 1
answer count: 1
downvote count: 1
tagged with: string
has title: Regular expression - Starting/ending with something specific and repeating pattern inbetween
favorite count: 0
type: Question
has body: I would like to write a regular expression that matches names with the following syntax. "Show log 8006, Conan O'Brian talks about Freddy Mercury, Evan.R Wood, Chan Kong-sang and McDonald?, Great People." Group 1: Conan O'Brian Group 2: Freddy Mercury Group 3: Evan.R Wood Group 4: Chan Kong-sang Group 5: McDonald? The consistency is "Show log ????, 'Name' talks about 'Name' and 'Name', 'Topic'". The amount of names can vary, there are a minimum of 3 names and no maximum.
accepted answer: http://stackoverflow.com/a/47741007
has comment: http://stackoverflow.com/comment/82441741

http://stackoverflow.com/comment/111138615
comment on: http://stackoverflow.com/a/47808488
has text: Align the csvFile.close() to loop ending. Got "I/O operation on closed file" because of that
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/82472282
score: 0
type: Comment
has text: I think you did not get my point I want both menu to be in centre whenever you resize the window if I use this `mymenu1.pack(side="left")` `mymenu2.pack(side="right")` One menu goes to extreme left and other to extreme right.
type: AnswerComment
comment on: http://stackoverflow.com/a/47755676

http://stackoverflow.com/a/47737049
type: Answer
downvote count: 0
has body: It looks like X_train1 is actually a Pandas data frame, based on the formatting of your screenshot. The problem is that Description is a column of lists of words (probably of unequal lengths). Something like this: X = np.array([['alpha','beta'],['theta','theta','gamma'],['delta','delta']]) X_train1 = pd.DataFrame(X, columns=["Description"]) X_train1 Description 0 [alpha, beta] 1 [theta, theta, gamma] 2 [delta, delta] X_train1.shape # (3,1) So you have 10,000 rows of lists of words (with shape (nrow, 1)). But CountVectorizer (assuming you're using the sklearn class) takes an array of documents. From the documentation: CountVectorizer: Convert a collection of text documents to a matrix of token counts More specifically, consider the argument definition to fit(): raw_documents: An iterable which yields either str, unicode or file objects. If you just try and pass in X_train1, you're not providing the expected input - you're passing in a data frame containing a column containing list objects of strings. You should expect to get weird output doing that. Assuming each row in X_train1 represents a document, try joining the word list on each row, then pass to CountVectorizer: X = X_train1.Description.apply(lambda row: ' '.join(row)) ctvec = CountVectorizer() ctvec.fit_transform(X) # combine fit(X) and transform(X) Output: &lt;3x5 sparse matrix of type '&lt;class 'numpy.int64'&gt;' with 5 stored elements in Compressed Sparse Row format&gt; This output is more in line with the intended input.
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/47736659

http://stackoverflow.com/q/47785483
tagged with: python
has comment: http://stackoverflow.com/comment/82532686
has answer: http://stackoverflow.com/a/71333638
has comment: http://stackoverflow.com/comment/82532586
tagged with: statsmodels
score: 3
answer count: 2
upvote count: 3
has comment: http://stackoverflow.com/comment/82532473
has comment: http://stackoverflow.com/comment/82532322
has title: Can't import statsmodels in Jupyter even though it is already installed?
has comment: http://stackoverflow.com/comment/82575297
downvote count: 0
has comment: http://stackoverflow.com/comment/82534167
favorite count: 0
tagged with: jupyter-notebook
type: Question
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/61779001
linked to: http://stackoverflow.com/q/31864749
has body: I've installed statsmodels using pip in a terminal. It was successful. But then I couldn't import statsmodels in the notebook. I also tried running !pip install statmodels in the notebook itself. I got: Requirement already satisfied: statsmodels in /Library/Python/2.7/site-packages But am still unable to import it. import statsmodels as sm --------------------------------------------------------------------------- ImportError Traceback (most recent call last) &lt;ipython-input-4-dd062a96f652&gt; in &lt;module&gt;() ----&gt; 1 import statsmodels as sm Am I missing a step?

http://stackoverflow.com/comment/82601176
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47819417
has text: It won't have two keys. complete list follow the above mentioned pattern
score: 0

numpy
tags question: http://stackoverflow.com/q/47713302
tags question: http://stackoverflow.com/q/47793488
tags question: http://stackoverflow.com/q/47762379
tags question: http://stackoverflow.com/q/47791116
tags question: http://stackoverflow.com/q/47744927
tags question: http://stackoverflow.com/q/47727821
tags question: http://stackoverflow.com/q/47847946
tags question: http://stackoverflow.com/q/47721635
tags question: http://stackoverflow.com/q/47704438
tags question: http://stackoverflow.com/q/47737034
tags question: http://stackoverflow.com/q/47739140
tags question: http://stackoverflow.com/q/47752662
tags question: http://stackoverflow.com/q/47833749
tags question: http://stackoverflow.com/q/47775621
tags question: http://stackoverflow.com/q/47733520
tags question: http://stackoverflow.com/q/47746450
tags question: http://stackoverflow.com/q/47760193
tags question: http://stackoverflow.com/q/47848037
tags question: http://stackoverflow.com/q/47846345
tags question: http://stackoverflow.com/q/47822077
tags question: http://stackoverflow.com/q/47844573
tags question: http://stackoverflow.com/q/47720307
tags question: http://stackoverflow.com/q/47736645
tags question: http://stackoverflow.com/q/47735836
tags question: http://stackoverflow.com/q/47712482
tags question: http://stackoverflow.com/q/47853489
tags question: http://stackoverflow.com/q/47721974
tags question: http://stackoverflow.com/q/47804259
tags question: http://stackoverflow.com/q/47850202
tags question: http://stackoverflow.com/q/47785101
tags question: http://stackoverflow.com/q/47815329
tags question: http://stackoverflow.com/q/47844513
tags question: http://stackoverflow.com/q/47719969
tags question: http://stackoverflow.com/q/47841159
tags question: http://stackoverflow.com/q/47796338
tags question: http://stackoverflow.com/q/47722892
tags question: http://stackoverflow.com/q/47841332
tags question: http://stackoverflow.com/q/47771358
tags question: http://stackoverflow.com/q/47742622
tags question: http://stackoverflow.com/q/47783597
tags question: http://stackoverflow.com/q/47761312
tags question: http://stackoverflow.com/q/47749852
tags question: http://stackoverflow.com/q/47705703
tags question: http://stackoverflow.com/q/47711559
tags question: http://stackoverflow.com/q/47719932
tags question: http://stackoverflow.com/q/47699473
tags question: http://stackoverflow.com/q/47711255
tags question: http://stackoverflow.com/q/47837888
tags question: http://stackoverflow.com/q/47819790
tags question: http://stackoverflow.com/q/47841088
tags question: http://stackoverflow.com/q/47811757
tags question: http://stackoverflow.com/q/47725664
tags question: http://stackoverflow.com/q/47707016
tags question: http://stackoverflow.com/q/47823141
tags question: http://stackoverflow.com/q/47726073
tags question: http://stackoverflow.com/q/47727389
tags question: http://stackoverflow.com/q/47702750
tags question: http://stackoverflow.com/q/47740020
tags question: http://stackoverflow.com/q/47710694
tags question: http://stackoverflow.com/q/47757493
tags question: http://stackoverflow.com/q/47835836
tags question: http://stackoverflow.com/q/47850890
tags question: http://stackoverflow.com/q/47723154
tags question: http://stackoverflow.com/q/47738439
tags question: http://stackoverflow.com/q/47775591
tags question: http://stackoverflow.com/q/47788110
tags question: http://stackoverflow.com/q/47838811
tags question: http://stackoverflow.com/q/47703598
tags question: http://stackoverflow.com/q/47700151
tags question: http://stackoverflow.com/q/47836242
tags question: http://stackoverflow.com/q/47800391
tags question: http://stackoverflow.com/q/47848525
tags question: http://stackoverflow.com/q/47765066
tags question: http://stackoverflow.com/q/47785384
tags question: http://stackoverflow.com/q/47710086
tags question: http://stackoverflow.com/q/47828821
tags question: http://stackoverflow.com/q/47706494
tags question: http://stackoverflow.com/q/47737602
tags question: http://stackoverflow.com/q/47850760
tags question: http://stackoverflow.com/q/47813677

http://stackoverflow.com/comment/82420330
type: QuestionComment
comment on: http://stackoverflow.com/q/47727283
type: Comment
score: 0
has text: What is the value of `file1`? Try the 2nd `loadtxt` without `unpack` and make sure you understand the resulting array. Oh, and cleanup the indenting.

http://stackoverflow.com/comment/82439575
has text: it's the parent of this serializer, I forgot to add that
comment on: http://stackoverflow.com/a/47739720
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/47829210
has comment: http://stackoverflow.com/comment/82622177
has body: This is a new feature of Spark2.0. FileSourceStrategy Combines the smaller parquet files to make a larger file so that it can work in optimized way. Ideally each spark executor wants to work on a block size equivalent to the HDFS block size (128MB).
type: Answer
answers question: http://stackoverflow.com/q/47829089
has comment: http://stackoverflow.com/comment/82621824
has comment: http://stackoverflow.com/comment/82621772
score: 1
has comment: http://stackoverflow.com/comment/82733908
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/82624987

http://stackoverflow.com/q/47757167
tagged with: flask
favorite count: 0
has answer: http://stackoverflow.com/a/54351450
accepted answer: http://stackoverflow.com/a/54351450
has comment: http://stackoverflow.com/comment/95385518
type: AnsweredQuestion
tagged with: heroku
has title: Running flask as package in production
has answer: http://stackoverflow.com/a/54319858
possible better answer: http://stackoverflow.com/a/54319858
tagged with: python
type: Question
upvote count: 12
answer count: 2
has body: I am trying to deploy my flask app. Usually I would have an app.py and put all code in it. app.py templates/ | |--index.html for my really small projects. But then I have a slightly larger app and follow the larger app guide by flask. So I have this: setup.py app/ __init__.py views.py models.py forms.py templates/ | ---index.html I now have all my routes and views in views.py and running the app in __init__.py: from flask import Flask app = Flask(__name__) import app.views # Name in setup.py if __name__ == "__main__": app.run() (This is just an example) So now I follow the guide by running it with pip install -e . and running with: &gt;set FLASK_APP=app(name I set in setup.py) flask run and it works. Except I do not know how to run it with one command. Since there is no one file to run I can not use gunicorn or anything like that. I am not sure how to go about executing this app. How would I run pip install . on the cloud server heroku? My problem is because I have to import the app from __init__.py and views using import blog.[insert import] (models, views etc.) Any help is appreciated. Thank you. EDIT: I do not want to use blueprints though. That might be too much. My app is medium, not small but not large either
downvote count: 1
tagged with: pip
score: 11

http://stackoverflow.com/comment/82497092
score: 0
comment on: http://stackoverflow.com/q/47766805
type: Comment
type: QuestionComment
has text: The result of `df.time.dtype` is `dtype('M8[ns]')` which is a datetime as I know. Isn't it?

http://stackoverflow.com/a/47707583
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47707559
downvote count: 0
answers question: http://stackoverflow.com/q/47707559
type: Answer
has comment: http://stackoverflow.com/comment/82375112
has body: Although you are modifying health, you aren't modifying the actual text which is being displayed. Instead, try using the following: if sqrlsrect.center == girlrect.center: print ('Ouch s!') health -= 1 text = font.render("Health: " + str(health),1, RED)
score: 2
upvote count: 2

http://stackoverflow.com/q/47763078
tagged with: azure-iot-sdk
type: Question
tagged with: azure-iot-hub
answer count: 2
has answer: http://stackoverflow.com/a/57144824
upvote count: 2
downvote count: 2
has body: Is there any real documentation for the Python Azure IoTHub SDK? I have found a few code samples but nothing comprehensive. It's also hard to correlate with the documentation for other language SDK's as they all seem slightly different. Even the source code is not good documentation as it's actually a wrapper over C++. I'd like to be able to take advantage of all the features, but I can't. For instance in the code samples we see send_confirmation_callback, receive_message_callback, device_twin_callback, device_method_callback, and blob_upload_conf_callback, and it's not clear to me what these all do, or what other kinds of callbacks there might be. Am I missing it or does it not exist?
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47778554
score: 0
has comment: http://stackoverflow.com/comment/82518541
has answer: http://stackoverflow.com/a/47778554
tagged with: azure
has title: Documentation for Python Azure IoTHub SDK
has comment: http://stackoverflow.com/comment/82490921
tagged with: python
favorite count: 0
possible better answer: http://stackoverflow.com/a/57144824

http://stackoverflow.com/q/47815846
answer count: 2
tagged with: pandas
has comment: http://stackoverflow.com/comment/82593410
has answer: http://stackoverflow.com/a/47816104
downvote count: 0
possible better answer: http://stackoverflow.com/a/47816104
has body: I am trying to compare the three floats in a row of a dataframe that is (500000x3), I expect the three values to be the same or at least 2 of them. I want to select the value that occurs the most under the presumption that they are not all different. My current attempt with a toy example is like thus: mydf a b c 0 1 1 2 1 3 3 3 2 1 3 3 3 4 5 4 3 4 5 5 mydft = mydf.transpose() counts=[] for col in mydft: counts.append(mydft[col].value_counts()) I am then thinking of looping over counts and selecting the top value for each but this is very slow and feels anti pandas. I have also tried this: truth = mydf['a'] == mydf['b'] with the intention of keeping rows which evaluate to true and doing something to those that do not but I have 1000s of NaN values in the real thing and apparently NaN == NaN is False. Any suggestions?
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47816523
accepted answer: http://stackoverflow.com/a/47816523
has title: count occurences in each dataframe row then create column with most frequent
tagged with: python
score: 4
upvote count: 4
tagged with: vectorization
type: AnsweredQuestion

http://stackoverflow.com/comment/82454470
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47747201
has text: You can do this. ```df = pd.DataFrame({'a':list('abssbab')}) df.groupby('a').count()```
type: Comment

http://stackoverflow.com/comment/82488088
type: QuestionComment
has text: You can sort the dict and then do the dict comprehension
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47763138

http://stackoverflow.com/comment/82557425
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47798079
has text: @cᴏʟᴅsᴘᴇᴇᴅ I'll add that to my answer, thanks.
score: 0

http://stackoverflow.com/q/47812367
has answer: http://stackoverflow.com/a/47812958
tagged with: python
linked to: http://stackoverflow.com/q/45450175
has title: Scipy linalg LU decomposition gives different results to my textbook
type: AnsweredQuestion
score: 3
tagged with: matrix
upvote count: 3
tagged with: math
has body: I am working through the 5th ed of Linear Programming by Saul I. Gass. He gives the following text and example: "Given an n x n nonsingular matrix A, then A can be expressed as the product A = LU... ...if we let the diagonal elements of U (or L) be all equal to 1, then the LU decomposition will be unique..." I managed to get a reversible lower-upper decomposition with this code that I found from this SO question: Is there a built-in/easy LDU decomposition method in Numpy? But I still can't tell what is going on and why L and U are so different from my textbook. Can anybody explain this to me? So this code: import numpy as np import scipy.linalg as la a = np.array([[1, 1, -1], [-2, 1, 1], [1, 1, 1]]) (P, L, U) = la.lu(a) print(P) print(L) print(U) D = np.diag(np.diag(U)) # D is just the diagonal of U U /= np.diag(U)[:, None] # Normalize rows of U print(P.dot(L.dot(D.dot(U)))) # Check gives this output: [[ 0. 1. 0.] [ 1. 0. 0.] [ 0. 0. 1.]] [[ 1. 0. 0. ] [-0.5 1. 0. ] [-0.5 1. 1. ]] [[-2. 1. 1. ] [ 0. 1.5 -0.5] [ 0. 0. 2. ]] [[ 1. 1. -1.] [-2. 1. 1.] [ 1. 1. 1.]]
answer count: 1
tagged with: scipy
favorite count: 0
has comment: http://stackoverflow.com/comment/82588898
type: Question
tagged with: numpy
accepted answer: http://stackoverflow.com/a/47812958
downvote count: 0

http://stackoverflow.com/comment/82603810
comment on: http://stackoverflow.com/q/47815669
type: QuestionComment
has text: What is the question, why it happens or if there is any workaround??
score: 0
type: Comment

http://stackoverflow.com/q/47855792
upvote count: 1
tagged with: python
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/82680192
score: 0
has body: (my_project) [yw@yanbox my_project]$ pip install mysqlclient File "/tmp/pip-build-zza957yo/mysqlclient/setup_posix.py", line 44, in get_config libs = mysql_config("libs_r") File "/tmp/pip-build-zza957yo/mysqlclient/setup_posix.py", line 26, in mysql_config raise EnvironmentError("%s not found" % (mysql_config.path,)) OSError: mysql_config not found Any ideas how to fix this problem?
tagged with: mysql
has answer: http://stackoverflow.com/a/47855865
has title: Error installing mysqlclient inside virtualenv
linked to: http://stackoverflow.com/q/5178292
downvote count: 1
favorite count: 0
type: Question
tagged with: pip
tagged with: django

http://stackoverflow.com/a/47844679
score: 0
answers question: http://stackoverflow.com/q/47844529
type: Answer
has body: Try to append and remove duplicates: df3 = pd.drop_duplicates(df1.append(df2))
has comment: http://stackoverflow.com/comment/82653976

http://stackoverflow.com/a/47786316
type: AcceptedAnswer
downvote count: 0
score: 3
accepted answer of: http://stackoverflow.com/q/47786082
type: Answer
has body: One way to do it would be to import the inner classes within the outer. class Backup: from Models.Create import Create from Models.Delete import Delete from Models.Restore import Restore If you do it this way, I would import them all into the 'Models' package's __init__.py, so you could just do this: class Backup: from Models import Create, Delete, Restore Another option if you're importing them elsewhere is just assigning them within the class. class Backup: Create = Models.Create.Create Delete = Models.Delete.Delete Restore = Models.Restore.Restore
has comment: http://stackoverflow.com/comment/82534006
answers question: http://stackoverflow.com/q/47786082
has comment: http://stackoverflow.com/comment/82576333
has comment: http://stackoverflow.com/comment/129126053
upvote count: 3

http://stackoverflow.com/comment/82404037
type: AnswerComment
has text: you're right Charlie and I apologize for not using the right format. I'm a newbie here and I can't see how i can upload the code precisely as you did above
type: Comment
comment on: http://stackoverflow.com/a/47710363
score: 0

http://stackoverflow.com/q/47851688
tagged with: concatenation
has title: How to do arithmetic in Python with SQLite database selections
has answer: http://stackoverflow.com/a/47853021
tagged with: sqlite
answer count: 1
type: Question
has body: I'm trying to add (not concatenate) a single SQLite selection from my database, but it returns the value as a list and tries to concatenate it. I'm looking at the line "total = users + values." I'm developing a web flask app that manages mock stock portfolio transactions. Please help! The 'users' table's 'cash' column is NUMERIC and the 'portfolio' table's 'shares' and 'price' column are INTEGER and NUMERIC users = db.execute("SELECT cash FROM users WHERE id = :id", id=session["user_id"]) portfolio = db.execute("SELECT * FROM portfolio WHERE id = :id", id=session["user_id"]) values = 0 total = users if portfolio: for each in portfolio: values= values + (each.shares * each.price) total = users + values #value = usd( total ) value = users return render_template("index.html", stock=portfolio, user=users, value=value)
tagged with: math
tagged with: python
type: AnsweredQuestion
score: 0
tagged with: list
accepted answer: http://stackoverflow.com/a/47853021
has comment: http://stackoverflow.com/comment/82668555

http://stackoverflow.com/comment/82423849
comment on: http://stackoverflow.com/a/47729416
score: 1
type: Comment
type: AnswerComment
has text: With the delimiter of '_', it seems to be working. Fingers crossed.. Thanks

http://stackoverflow.com/q/47769547
score: -2
tagged with: python
tagged with: discord
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47786315
has answer: http://stackoverflow.com/a/47786315
upvote count: 0
has body: total I'm a total discord/python noob, I don't really have any code to show as I don't even know where to start. All I'm trying to do is remove everyone from a certain discord role. Lets say the role is, "Warrior" and there are 5 people in it, I don't want to delete the role entirely, instead I want to just remove all 5 people from it. I guess in theory I could delete the entire role and then create it again, let me know your thoughts and the best way to go about it.
downvote count: 2
answer count: 1
favorite count: 0
type: Question
has title: How do I / what is the best way to remove all users from a Discord Role in python?

http://stackoverflow.com/comment/82524794
type: Comment
comment on: http://stackoverflow.com/a/47775821
score: 0
type: AnswerComment
has text: I read through the Grouper documentation, and it appears as though the first two rows aren't working as expected because the frequency parameter lumps 12/11 and 11/11 into the same 180 day period, as opposed to those being rolling averages. Any thoughts on how to make the "Avg Qty" column a rolling average as opposed to a timeblock average?

http://stackoverflow.com/a/47733956
score: 0
has body: &gt;&gt;&gt; day = 'Monday' &gt;&gt;&gt; day[0] + ' ' + day[-1] M y
type: Answer
answers question: http://stackoverflow.com/q/47733919

http://stackoverflow.com/comment/82529821
comment on: http://stackoverflow.com/q/47783442
score: 0
type: Comment
has text: @martineau Yes, correct. Also without modifying the original, to restate for assurance.
type: QuestionComment

http://stackoverflow.com/q/47702323
has answer: http://stackoverflow.com/a/47801127
type: Question
has body: How do you capture unknown values when making predictions on h2o data frames? For example, when doing something like: model.predict(frame_in) in the h2o python api, a progress bar loads while the model is making predictions and then a series of lists are outputted detailing the unknown labels seen for each of the enum types of the model predictive features. Eg. /home/mapr/anaconda2/lib/python2.7/site-packages/h2o/job.py:69: UserWarning: Test/Validation dataset column 'feature1' has levels not trained on: [, &lt;values&gt;] Is there any way to get this set of unknown levels as a python object? Thanks. When working with h2o MOJOs, there is a java method called getTotalUnknownCategoricalLevelsSeen(), but I could not find anything like this in the h2o python docs.
tagged with: python
accepted answer: http://stackoverflow.com/a/47801127
has title: How to capture untrained-on values h2o python
type: AnsweredQuestion
score: 3
answer count: 2
possible better answer: http://stackoverflow.com/a/47807826
tagged with: h2o
upvote count: 3
has answer: http://stackoverflow.com/a/47807826
downvote count: 0
linked to: http://stackoverflow.com/q/14197009
favorite count: 0

http://stackoverflow.com/q/47733606
upvote count: 0
type: UnansweredQuestion
has body: This bubble sort algorithm prints an empty list each time it's run, really don't see the problem with it: def bubble_sort(seq): changed = True while changed: changed = False for i in range(len(seq) - 1): if seq[i] &gt; seq[i+1]: seq[i], seq[i+1] = seq[i+1], seq[i] changed = True print(seq) return None if __name__ == '__main__': bubble_sort(list(range(0,10,-1)))
answer count: 1
has answer: http://stackoverflow.com/a/47733655
downvote count: 1
has title: Bubble sort implementation not working
tagged with: algorithm
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/82428044
favorite count: 0
type: Question

http://stackoverflow.com/a/75334301
has body: If one need to perform more operation with integer fields in models class YOURSerializer(serializers.ModelSerializer): age= serializers.IntegerField(required=True) class Meta: model = User fields = '__all__' def validate(self, data): age= data.get('age', None) if age == 18: raise serializers.ValidationError("Age 18 people are given special discount, Congrats!")
has comment: http://stackoverflow.com/comment/133032515
answers question: http://stackoverflow.com/q/47740302
score: 0
has comment: http://stackoverflow.com/comment/132970671
type: Answer

http://stackoverflow.com/q/47745677
duplicate of: http://stackoverflow.com/q/9969698
has comment: http://stackoverflow.com/comment/82451489
has title: In Python 3, what are the differences between (stably) reverse sorting and (stably) sorting, then reversing the result?
favorite count: 0
has comment: http://stackoverflow.com/comment/82451989
type: Question
tagged with: persistent-storage
tagged with: reverse
has comment: http://stackoverflow.com/comment/82451944
has body: For example, how do the overall processes in the last two lines differ: alist = list(range(3)) alist.sort(); alist.reverse(); alist # [2, 1, 0] alist.sort(reverse=True); alist # [2, 1, 0] In particular, is there a possibility of the two methods returning different results, for any other case? If so, what case is that and how might the results differ? I acknowledge that the responses for python Difference between reversed(list) and list.sort(reverse=True) answer this question. However this question itself is talking about stable sorting in particular. I hope that this question is kept for future users to find.
tagged with: python
tagged with: sorting
linked to: http://stackoverflow.com/q/9969698
has comment: http://stackoverflow.com/comment/82452026
score: 0
answer count: 0
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82451934
downvote count: 2
has comment: http://stackoverflow.com/comment/82452071
has comment: http://stackoverflow.com/comment/82452396
has comment: http://stackoverflow.com/comment/82451721

http://stackoverflow.com/comment/82601155
type: QuestionComment
has text: Hi, thank you for such a quick reply. Do I try it in Python or my SQLite database?
score: 0
comment on: http://stackoverflow.com/q/47819386
type: Comment

http://stackoverflow.com/q/47737636
accepted answer: http://stackoverflow.com/a/47738357
has answer: http://stackoverflow.com/a/47738357
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82435530
tagged with: iterator
type: AnsweredQuestion
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/82435750
has answer: http://stackoverflow.com/a/47737717
upvote count: 1
favorite count: 0
tagged with: generator
has comment: http://stackoverflow.com/comment/82435977
has comment: http://stackoverflow.com/comment/82435713
has comment: http://stackoverflow.com/comment/82435802
has comment: http://stackoverflow.com/comment/82435833
type: Question
has title: custom iterator class vs. generator?
possible better answer: http://stackoverflow.com/a/47737717
has comment: http://stackoverflow.com/comment/82435899
tagged with: python
has body: The following is an illustration. I'd like to understand in general whether there is a reason for defining a custom iterator class when a generator function can be defined instead. I need to iterate over a sequence converting every element to int, e.g. # seq is a sequence of strings or in general anything convertible to int def f(seq): # ... g(int_iter(seq)) # iseq is a numeric sequence def g(iseq): it = iter(iseq) # ... I can use either a custom iterator class: # iterator converting elements it iterates over to int class int_iter: def __init__(self, iterable): self.it = iter(iterable) def __iter__(self): return self def __next__(self): return int(next(self.it)) or a generator function: def int_iter(seq): return (int(i) for i in seq) Are these solutions always interchangeable? Are they equivalently efficient (time- and space-wise)? Stylistically, is any of them considered better? Thanks!
score: 1

http://stackoverflow.com/q/47847218
has comment: http://stackoverflow.com/comment/82658607
has body: this is the output of multiple lists and i want to store them in one list or array (array([[ 1.52494154e+11, 1.52811638e+11, 1.52565040e+11, ..., 1.47778892e+11, 1.46781213e+11, 1.46678951e+11], [ 7.69589176e+10, 7.73638333e+10, 7.76935891e+10, ..., 7.48498747e+10, 7.40088248e+10, 7.40343108e+10], [ 6.32683585e+04, 1.58170271e+06, 6.11287648e+06, ..., 5.06690834e+05, 3.31360693e+05, 7.04757400e+05], ..., [ 7.79589127e+05, 8.09843763e+04, 2.52907491e+05, ..., 2.48520301e+05, 2.11734697e+05, 2.50917758e+05], [ 9.41199946e+05, 4.98371406e+05, 1.29328139e+06, ..., 2.56729806e+05, 3.45253951e+05, 3.51932417e+05], [ 4.36846676e+05, 1.24123764e+06, 9.20694394e+05, ..., 8.35807658e+04, 8.36986905e+05, 3.57807267e+04]]), array([ 0. , 3.90625, 7.8125 , 11.71875, 15.625 , 19.53125, 23.4375 , 27.34375, 31.25 , 35.15625, 39.0625 , 42.96875, 46.875 , 50.78125, 54.6875 , 58.59375, 62.5 , 66.40625, 70.3125 , 74.21875, 78.125 , 82.03125, 85.9375 , 89.84375, 93.75 , 97.65625, 101.5625 , 105.46875, 109.375 , 113.28125, 117.1875 , 121.09375, 125. , 128.90625, 132.8125 , 136.71875, 140.625 , 144.53125, 148.4375 , 152.34375, 156.25 , 160.15625, 164.0625 , 167.96875, 171.875 , 175.78125, 179.6875 , 183.59375, 187.5 , 191.40625, 195.3125 , 199.21875, 203.125 , 207.03125, 210.9375 , 214.84375, 218.75 , 222.65625, 226.5625 , 230.46875, 234.375 , 238.28125, 242.1875 , 246.09375, 250. , 253.90625, 257.8125 , 261.71875, 265.625 , 269.53125, 273.4375 , 277.34375, 281.25 , 285.15625, 289.0625 , 292.96875, 296.875 , 300.78125, 304.6875 , 308.59375, 312.5 , 316.40625, 320.3125 , 324.21875, 328.125 , 332.03125, 335.9375 , 339.84375, 343.75 , 347.65625, 351.5625 , 355.46875, 359.375 , 363.28125, 367.1875 , 371.09375, 375. , 378.90625, 382.8125 , 386.71875, 390.625 , 394.53125, 398.4375 , 402.34375, 406.25 , 410.15625, 414.0625 , 417.96875, 421.875 , 425.78125, 429.6875 , 433.59375, 437.5 , 441.40625, 445.3125 , 449.21875, 453.125 , 457.03125, 460.9375 , 464.84375, 468.75 , 472.65625, 476.5625 , 480.4…
score: 0
has comment: http://stackoverflow.com/comment/82659690
has comment: http://stackoverflow.com/comment/82659054
has comment: http://stackoverflow.com/comment/82658736
answer count: 1
tagged with: spectrogram
has answer: http://stackoverflow.com/a/47847478
tagged with: signal-processing
type: Question
tagged with: numpy
tagged with: python-3.x
has title: Python - how to store multiple lists in one list?
has comment: http://stackoverflow.com/comment/82659168
has comment: http://stackoverflow.com/comment/82659022
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82660378
tagged with: python
linked to: http://stackoverflow.com/q/952914

http://stackoverflow.com/q/47722005
has comment: http://stackoverflow.com/comment/82412570
favorite count: 0
type: Question
tagged with: numpy
upvote count: 15
has answer: http://stackoverflow.com/a/47722393
has comment: http://stackoverflow.com/comment/82405664
downvote count: 0
has comment: http://stackoverflow.com/comment/82405703
linked to: http://stackoverflow.com/q/34187130
tagged with: python
has comment: http://stackoverflow.com/comment/82407405
accepted answer: http://stackoverflow.com/a/47722393
score: 15
tagged with: vectorization
type: AnsweredQuestion
tagged with: random
has body: Numpy has the random.choice function, which allows you to sample from a categorical distribution. How would you repeat this over an axis? To illustrate what I mean, here is my current code: categorical_distributions = np.array([ [.1, .3, .6], [.2, .4, .4], ]) _, n = categorical_distributions.shape np.array([np.random.choice(n, p=row) for row in categorical_distributions]) Ideally, I would like to eliminate the for loop.
answer count: 1
has title: Vectorizing `numpy.random.choice` for given 2D array of probabilities along an axis

http://stackoverflow.com/comment/82450556
score: 2
type: QuestionComment
comment on: http://stackoverflow.com/q/47745226
type: Comment
has text: Please post an actual code in text and not as an image.

http://stackoverflow.com/q/47833620
score: 0
has title: Django- Stuck and cannot get data to display on webpage
has body: Here’s my issue. I can display data from one of my other tables (the stats table that I don’t show here) on my stats page and home page. That was the first time I was able to get it to work, (I am new to Django). Then I made another table in my database (the Alstandings table) and I made an app for that was well because I want a standings page. For some reason I cant get the data from my Alstandings table to display on the standings page. As far as I know I thought I replicated the process but maybe I’m missing something I don’t know about. Yes, I have registered the app in my settings. I’m not getting any errors right now. Please, if anybody has valuable input on how to get this to work, please respond. Your help will be greatly appreciated. Thank You. Standings/models from django.db import models class Alstandings(models.Model): id = models.IntegerField(db_column='ID', primary_key=True) # Field name made lowercase. team = models.CharField(db_column='TEAM', max_length=30, blank=True, null=True) # Field name made lowercase. w = models.IntegerField(db_column='W', blank=True, null=True) # Field name made lowercase. l = models.IntegerField(db_column='L', blank=True, null=True) # Field name made lowercase. pct = models.DecimalField(db_column='PCT', max_digits=4, decimal_places=3, blank=True, null=True) # Field name made lowercase. gb = models.DecimalField(db_column='GB', max_digits=4, decimal_places=1, blank=True, null=True) # Field name made lowercase. rs = models.IntegerField(db_column='RS', blank=True, null=True) # Field name made lowercase. ra = models.IntegerField(db_column='RA', blank=True, null=True) # Field name made lowercase. diff = models.IntegerField(db_column='DIFF', blank=True, null=True) # Field name made lowercase. home = models.CharField(db_column='HOME', max_length=7, blank=True, null=True) # Field name made lowercase. road = models.CharField(db_column='ROAD', max_length=7, blank=True, null=True) # Field name made lowercase. east = models.CharField(db_…
has comment: http://stackoverflow.com/comment/82630466
answer count: 0
has comment: http://stackoverflow.com/comment/82631150
type: Question
has comment: http://stackoverflow.com/comment/82630560
type: UnansweredQuestion
tagged with: django
has comment: http://stackoverflow.com/comment/82630360
tagged with: python
has comment: http://stackoverflow.com/comment/82630686
has comment: http://stackoverflow.com/comment/82633200
has comment: http://stackoverflow.com/comment/82630979

http://stackoverflow.com/comment/89602509
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47756176
has text: I have the same problem - discovered via memory_profiler

http://stackoverflow.com/q/47790526
type: UnansweredQuestion
tagged with: virtualenv
type: Question
score: 0
has answer: http://stackoverflow.com/a/47793054
tagged with: python
has title: Subprocess popen interaction with virtualenv
has answer: http://stackoverflow.com/a/47790977
has answer: http://stackoverflow.com/a/47790708
has body: I am using virtualenv to run a script that uses subprocess popen to run another program that requires the system wide python and original environment variables. How do I prevent virtualenv from affecting it?
answer count: 3

http://stackoverflow.com/a/47713042
has comment: http://stackoverflow.com/comment/82386626
has comment: http://stackoverflow.com/comment/82411772
upvote count: 2
has comment: http://stackoverflow.com/comment/82386558
downvote count: 0
has comment: http://stackoverflow.com/comment/82387288
type: Answer
has body: Popen is a default choice when it comes to using subprocess module. It allows you to create a process and then read its stdout and stderr with specified timeout: def ping(ipadd): process = subprocess.Popen(['ping', ipadd]) try: response, stderr_response = process.communicate(timeout=10) return True except subprocess.TimeoutExpired: return False finally: process.kill() Also, beware that ping on a linux or osx may never exit and continue to ping so this is going to return false on these OSes: &gt;&gt;&gt; ping('127.0.0.1') PING 127.0.0.1 (127.0.0.1): 56 data bytes 64 bytes from 127.0.0.1: icmp_seq=0 ttl=64 time=0.058 ms 64 bytes from 127.0.0.1: icmp_seq=1 ttl=64 time=0.033 ms ... 64 bytes from 127.0.0.1: icmp_seq=8 ttl=64 time=0.064 ms 64 bytes from 127.0.0.1: icmp_seq=9 ttl=64 time=0.031 ms False
has comment: http://stackoverflow.com/comment/82386443
answers question: http://stackoverflow.com/q/47712093
score: 2

http://stackoverflow.com/a/47773415
has comment: http://stackoverflow.com/comment/82512832
score: 0
answers question: http://stackoverflow.com/q/47747979
has body: If you saved your file to csv, you can latter use "read_csv" with parameter "memory_map=True". You might also select a subset of columns from the start instead of dropping them later, and read these just in time if you only need them for a few parameters. You might convert textual repeated/categorical data to dummies/integer instead. Maybe you might also want to use Numpy instead if you can obtain an all same data type table. Together with the use of sparse matrices, it might help reduce significantly your in memory size and speed your loading and processing. For operations of fusion, merge is told by Pandas docs to be "high performance", compared to concat and so (append predating these). You might want to use inplace=True parameters to avoid the burden of copy
type: Answer

http://stackoverflow.com/a/47744108
has comment: http://stackoverflow.com/comment/82876610
downvote count: 0
has comment: http://stackoverflow.com/comment/82470637
score: 4
type: Answer
answers question: http://stackoverflow.com/q/47723256
upvote count: 4
has body: Sounds like a fun problem! If your 3 click points are in the same quadrant then one of the angles of the triangle defined by those points must be obtuse. Call that B and the other two vertices A and C. The general equation for an x-y oriented ellipse has 4 parameters in it. Substituting the x and y coordinates of A, B and C into the ellipse equation will give you three equations. You need to come up with a 4th. You have the freedom to pick that 4th point in some way that makes sense in the context of your game. Here's a SymPy code snippet that assigns an x value to the center of the ellipse based on A, B and C and a parameter 'f'. def e3(p1, p2, p3, f): t = Triangle(p1, p2, p3) a = t.angles for p in a: if a[p] &gt; pi/2: break else: return while p != p2: p1, p2, p3 = p2, p3, p1 pts = A, B, C = p1, p2, p3 # perpendicular line to AB passing through A perp = Segment(A, B).perpendicular_line(A) # intersection between that and the perpendicular to that # which passes through C m = perp.perpendicular_line(C).intersection(perp)[0] delta = m - A c = A + delta*f x, y, h, r, y0 = symbols('x y h r y0', cls=Dummy) eq = Ellipse((c.x, y0), h, r).equation(x, y) s = solve([ eq.xreplace(dict(zip((x, y), p))) for p in pts], dict=True)[0] return eq.subs(s) # for desmos graphing: str(eq.subs(s)).replace('**','^').replace('_','')+'=0' Some of the results for f = .125, .25, .5, 1, 2 are shown at desmos. You can see that they all go through the points that you gave as an example. The red circle provides an interesting point of reference. You might want to pick an f so the resulting width of the ellipse is some fraction of the diameter of the circle that would have gone through the points. The points that the ellipses are going through do not lay in the same quadrant of each ellipse, however. To meet that criteria, you have to consider an "off axis" ellipse. It may also be helpful to use the equation of the arbitrary ellipse that I posted here to guide you in making a selection for variabl…
has comment: http://stackoverflow.com/comment/82530810

http://stackoverflow.com/q/47824302
has comment: http://stackoverflow.com/comment/82636178
type: UnansweredQuestion
downvote count: 0
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/82642945
has body: I'm new to ContikiOS and I'm having an issue when trying to send a character to my cc2650-launchpad from my Raspberry Pi using the UART interface. I want to make my Raspberry Pi communicate by serial interface with a cc2650 launchpad. I can read serial output from the launchpad perfectly but I am unable to send something to the launchpad from the RPi through serial. I have configured my Raspberry Pi to enable UART following this tutorial (I'm using Raspbian Jessie) and configured the launchpad running Contiki to receive serial messages according to Contiki documentation. When testing on TeraTerm (Serial monitor for Windows) I am able to recieve the characters on the launchpad by typing on the terminal window and pressing 'CTRL + ENTER', which sends a "\n" character (ASCII = 0x0A). The launchpad works as expected. However, when I try to automate things on my Raspberry Pi using a program written in Python, it appears the character is not received by the launchpad (or the selial line event is not triggered). What I get is the following behavior: Wrong behavior (on Raspberry Pi) And this is what I expected: Expected Behavior (on Windows Machine) As seen on the first image above, even after sending the character 'T' many times (upper window), the launchpad dows not receive anything (bottom window) The behavior is the same when connecting the launchpad by USB (ttyACM0) and by UART pins (ttyAMA0). I don't believe the problem is with the launchpad firmware since it works well when it is interfacing with a Windows machine (image 2). So the problem must be with my Raspberry Pi configuration or my with Python code. Does anybody know what I might be doing wrong? Source code for reference: Raspberry Pi: #Python code running on Raspberry Pi import serial import time uart_port = serial.Serial("/dev/ttyACM0", 115200); while True: uart_port.write("T") uart_port.write("\n"); print("Sent 'T'") time.sleep(1) CC2650 Launchpad: ... #include "dev/serial-line.h" ... PROCESS_THREAD(udp_serv…
has title: How to send bytes through serial from Raspberry Pi to ContikiOS firmware
has comment: http://stackoverflow.com/comment/82629929
tagged with: texas-instruments
tagged with: uart
answer count: 0
score: 1
has comment: http://stackoverflow.com/comment/82626389
has comment: http://stackoverflow.com/comment/82717260
favorite count: 0
has comment: http://stackoverflow.com/comment/82628647
type: Question
has comment: http://stackoverflow.com/comment/82628060
tagged with: raspberry-pi
tagged with: contiki

http://stackoverflow.com/a/47823102
downvote count: 0
upvote count: 1
score: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47822994
accepted answer of: http://stackoverflow.com/q/47822994
type: Answer
has body: The ravel function along with a new axis should do the trick: import numpy as np x = np.array([[0.5, 0.75, 1], [0.75, 1, 1.25], [1, 1.25, 1.5]]) x.T.ravel()[:, np.newaxis] # array([[ 0.5 ], # [ 0.75], # [ 1. ], # [ 0.75], # [ 1. ], # [ 1.25], # [ 1. ], # [ 1.25], # [ 1.5 ]]) Ravel stitches together all the rows, so we first transpose the matrix (with .T). The result is a row-vector, and we change it to a column vector by adding a new axis.

http://stackoverflow.com/q/47727786
accepted answer: http://stackoverflow.com/a/47727819
has title: recursion binary search in a list of names
tagged with: python
has body: I am trying to build a function that gets the index of an item form a list names = [('Daisy','Fox'),('Josh','Belluga'),('Elin','Grosefield'),('Mike','Levinsan')] this is the code def find_name(lst,name,low,high): if low &gt;= high: return None middle = (low + high) / 2 if lst[middle] == name: return middle elif name &lt; lst[middle]: return find_name(lst, name, low, middle) else: return find_name(lst, name, middle + 1, high) it works fine and all but the only problem that im having is when I define the low and high values to be equals for the index I want to get for example print find_name(names,('Josh','Belluga'),0,1) returns none when it should return 1 for some reason
type: AnsweredQuestion
tagged with: recursion
score: 0
has answer: http://stackoverflow.com/a/47727819
answer count: 1
type: Question
tagged with: binary-search-tree

http://stackoverflow.com/q/47809298
type: UnansweredQuestion
score: -2
tagged with: upload
tagged with: python
has title: Flask file upload , The method is not allowed for the requested URL
tagged with: flask
has comment: http://stackoverflow.com/comment/82579728
has body: I am trying to upload file. the abnormal is 'The method is not allowed for the requested URL' after run . However my code is request methods is 'POST' This is my html: input type="submit" value="upload" id="submit"> This is my api code: @api.route('/upload', methods=['POST','GET']) def upload(): if request.method == 'POST': file = request.files['file'] upload_path = os.path.join(APP_STATIC_TXT, secure_filename(file.filename)) file.save(upload_path) return redirect(url_for('/')) This run result: INFO: werkzeug:127.0.0.1 - - [14/Dec/2017 16:26:42] "POST /api/v1.0/upload HTTP/1.1" 400 - INFO:werkzeug:127.0.0.1 - - [14/Dec/2017 16:26:42] "POST / HTTP/1.1" 405 - INFO:werkzeug: * Detected change in '/home/python/Desktop/VCG/vcg/api_1_0/test01.py', reloading This is web html : Method Not Allowed The method is not allowed for the requested URL.
downvote count: 3
upvote count: 1
answer count: 1
tagged with: file
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47809949

http://stackoverflow.com/comment/82412834
comment on: http://stackoverflow.com/q/47723638
has text: Does it mean I have to multiply y by -1 before projecting?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/47909078
has comment: http://stackoverflow.com/comment/83196196
has comment: http://stackoverflow.com/comment/83196127
upvote count: 2
type: Answer
has body: Can you verify your setup.py containing a structure like: import setuptools setuptools.setup( name='My Project', version='1.0', install_requires=[], packages=setuptools.find_packages(), ) Import your modules like from juliaset.juliaset import SomeClass And when you call the Python script, use python -m juliaset_main (without the .py) Not sure if you already tried this, but just to be sure.
score: 2
answers question: http://stackoverflow.com/q/47837443
downvote count: 0

http://stackoverflow.com/comment/82669509
type: QuestionComment
comment on: http://stackoverflow.com/q/47852335
has text: Here is an [explanation of the COO matrix format](http://www.scipy-lectures.org/advanced/scipy_sparse/coo_matrix.html) with some more examples.
score: 0
type: Comment

http://stackoverflow.com/q/47729029
score: 0
tagged with: pandas
has body: I using the following command to use modules in my machine learning work. conda create -n tensorflow python=3.5 activate tensorflow conda install pandas matplotlib jupyter notebook scipy scikit-learn nltk conda install -c conda-forge tensorflow keras When i using import command in my ipython notebook import numpy as np import pandas as pd Following error is coming Traceback (most recent call last): File "C:\Users\sompatha\Anaconda2\envs\Ml\lib\site-packages\IPython\core\interactiveshell.py", line 2862, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "&lt;ipython-input-1-eeff7c4f34af&gt;", line 1, in &lt;module&gt; import numpy as np File "C:\Users\sompatha\Anaconda2\envs\Ml\lib\site-packages\numpy\__init__.py", line 126, in &lt;module&gt; from numpy.__config__ import show as show_config File "C:\Users\sompatha\Anaconda2\envs\Ml\lib\site-packages\numpy\__config__.py", line 5 blas_mkl_info={'library_dirs': ['C:\Users\sompatha\Anaconda2\envs\ML\\Library\\lib'], 'define_macros': [('SCIPY_MKL_H', None), ('HAVE_CBLAS', None)], 'libraries': ['mkl_core_dll', 'mkl_intel_lp64_dll', 'mkl_intel_thread_dll'], 'include_dirs': ['C:\Users\sompatha\Anaconda2\envs\ML\\Library\\include']} ^ SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape How to resolve this one ? Please help
tagged with: python
has answer: http://stackoverflow.com/a/47729440
has title: Creating a Tensorflow and Pandas Environment
type: UnansweredQuestion
answer count: 1
tagged with: unicode
tagged with: tensorflow
type: Question

http://stackoverflow.com/a/47809767
has comment: http://stackoverflow.com/comment/82580706
has comment: http://stackoverflow.com/comment/82581061
has body: IIUC, you can use groupby + count + unstack + plot - plt.style.use('ggplot') dummyData.groupby(['quarter', 'brand'])\ .brand.count().unstack().plot.bar(legend=True) plt.show() For reference, this is what is plotted - brand Apple Google MS quarter 2015Q1 1.0 NaN NaN 2016Q1 NaN 1.0 NaN 2017Q2 1.0 NaN 2.0
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47809646
accepted answer of: http://stackoverflow.com/q/47809646
score: 6
upvote count: 6
type: Answer

http://stackoverflow.com/q/47817688
has title: python error need explanations
has answer: http://stackoverflow.com/a/47817882
accepted answer: http://stackoverflow.com/a/47817882
has answer: http://stackoverflow.com/a/47817956
possible better answer: http://stackoverflow.com/a/47817956
tagged with: operators
type: AnsweredQuestion
answer count: 2
has body: I have this error when running the following program and I don't understand why: Traceback (most recent call last): line 18 main() line 13, in main nombre=condition(nombre) line 3, in condition if (nombre % 2) == 1: TypeError: unsupported operand type(s) for %: 'NoneType' and 'int' Here is my program: def condition(nombre): if (nombre % 2) == 1: nombre=(nombre*3)+1 else: nombre=(nombre/2) def main(): nombre=int(input()) print(nombre) while nombre!=1: nombre=condition(nombre) print(nombre) main()
upvote count: 2
downvote count: 2
has comment: http://stackoverflow.com/comment/82597161
has comment: http://stackoverflow.com/comment/82597180
has comment: http://stackoverflow.com/comment/82597417
favorite count: 0
has comment: http://stackoverflow.com/comment/82597382
type: Question
has comment: http://stackoverflow.com/comment/82597054
score: 0
has comment: http://stackoverflow.com/comment/82597244
tagged with: python

http://stackoverflow.com/q/47774470
tagged with: python
has comment: http://stackoverflow.com/comment/82509882
type: AnsweredQuestion
score: 3
upvote count: 3
accepted answer: http://stackoverflow.com/a/47775601
favorite count: 0
has answer: http://stackoverflow.com/a/47775601
type: Question
has title: Django checking if an individual field has an error and not run clean()?
downvote count: 0
answer count: 1
has body: Is there a way to check if an inidividual field has not passed validation in django's clean() method for a form. I don't want to have to manually be checking if a required field is there: def clean(): cleaned_data = super().clean() half_day = cleaned_data.get('half_day') start_date = cleaned_data.get('start_date') end_date = cleaned_data.get('end_date') if start_date and end_date: if half_day: if start_date != end_date: self.add_error( 'half_day', 'Start and end date must be the same' )
tagged with: django
has comment: http://stackoverflow.com/comment/82512118

http://stackoverflow.com/comment/82561930
has text: @furas host is http://de-tech-challenge-api.herokuapp.com
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47786886

http://stackoverflow.com/q/47810508
tagged with: orm
answer count: 1
has title: Display joined data with Peewee ORM
type: Question
tagged with: peewee
has answer: http://stackoverflow.com/a/47817357
has body: Using PeeWee Orm I have created two tables (I've removed a lot of the fields that are irrelevant to this query) Product Table class Product(BaseModel): fm_price = FloatField(null=True) magento = IntegerField(db_column='magento_id', null=True, index=True) sku = CharField(index=True, null=True, unique=True) # Compare these two fields to on or offline products magento_status_fm = IntegerField(null=True) magento_status_ff = IntegerField(null=True) # Date fields to put error dates in ff_price_error = DateField(index=True, null=True) ff_stock_error = DateField(index=True, null=True) fm_price_error = DateField(index=True, null=True) fm_stock_error = DateField(index=True, null=True) ff_check_date = DateField(null=True, index=True) # When did we get this product from FF class Meta: db_table = 'products' indexes = ( (('fm_price', 'vip_price', 'education_price'), False), ) Prices Table class Price(BaseModel): price_pk = PrimaryKeyField() entity_id = ForeignKeyField(Product, to_field='magento', null=True, on_update='CASCADE', on_delete='CASCADE') customer_group_id = IntegerField(null=True) final_price = FloatField(null=True) min_price = FloatField(null=True) check_date = DateField(null=True) class Meta: indexes = ( (('entity_id', 'customer_group_id'), True), ) Example Content: Products: ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ------------------------------------------------------------------------------ | id | CREATION | MODIFICATION | fm_price | fm_stock | vip_price | education_price | magento_id | omit | sku | url | web_stock | magento_status_fm | magento_status_ff | ff_price_error | ff_stock_error | fm_price_error | fm_stock_error | fm_vip_price_error | ff_vip_price_error | ff_check_date | ------------------------------------------------------------------…
type: UnansweredQuestion
tagged with: python
tagged with: sql
score: 0

http://stackoverflow.com/a/47701016
has comment: http://stackoverflow.com/comment/82365772
has comment: http://stackoverflow.com/comment/82363579
has comment: http://stackoverflow.com/comment/82361905
has body: Django is web framework for the python language; in order to 'serve' your project pages you'll need a web server to take in the requests, and a application server to process your ... python code! When you're developping locally and use the runserver commands, it simulates both server for you to test your project locally. Same goes to your php, it'll need both those components to serve the page. When you want to expose your pages to the world, you don't want to use "runserver". You could use the same web server to serve both Django pages and your Php pages, such as Nginx (example of multi config) or Apache (example with a multi config). You will need to "isolate" or "match" URLs for either running your php application server or the python one.
score: 0
answers question: http://stackoverflow.com/q/47700707
has comment: http://stackoverflow.com/comment/82366223
has comment: http://stackoverflow.com/comment/82365579
has comment: http://stackoverflow.com/comment/82365555
has comment: http://stackoverflow.com/comment/82365598
type: Answer

http://stackoverflow.com/comment/82606478
type: Comment
has text: This is not at all what OP is doing
comment on: http://stackoverflow.com/a/47821445
type: AnswerComment
score: 0

http://stackoverflow.com/comment/82402204
score: 0
type: Comment
type: QuestionComment
has text: You need to use threads in your client code too. Also, it's generally preferable to use `threading.Thread` rather than the low-level `thread` module.
comment on: http://stackoverflow.com/q/47720660

http://stackoverflow.com/comment/82359542
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47699695
type: Comment
has text: What exactly is your code doing wrong?

http://stackoverflow.com/q/47750757
accepted answer: http://stackoverflow.com/a/47750824
linked to: http://stackoverflow.com/q/2612802
answer count: 1
has answer: http://stackoverflow.com/a/47750824
downvote count: 1
linked to: http://stackoverflow.com/q/986006
favorite count: 0
type: Question
score: 8
has comment: http://stackoverflow.com/comment/82464390
upvote count: 9
tagged with: python
has comment: http://stackoverflow.com/comment/82462153
has title: How to shuffle a copied list without shuffling the original list?
has comment: http://stackoverflow.com/comment/82462041
has comment: http://stackoverflow.com/comment/134129681
type: AnsweredQuestion
tagged with: list
has body: I'm using python and want to shuffle a copied list that I write after that into a txt file (see my code below). Why does the shuffle function randomize the original list, too? I only use the copy for the function call. Any ideas? Thank you ! from random import shuffle def shuffleList2txt(myList): shuffle(myList) f = open('randList.txt','w') f.write(str(liste)) f.close() return(myList) liste = [1,2,3,4,5,6,7,8,9,10] copy = liste shuffledList = shuffleList2txt(copy) liste and shuffledList are the same ! Why? liste should be the original one and shuffledList should be the shuffled list.... :)
tagged with: shuffle

http://stackoverflow.com/q/47840395
has title: ImageMath.eval gives different result than manual calculation
type: Question
linked to: http://stackoverflow.com/q/12251896
tagged with: python-2.7
answer count: 0
has comment: http://stackoverflow.com/comment/82664448
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82665372
has comment: http://stackoverflow.com/comment/82712650
has comment: http://stackoverflow.com/comment/82646094
has comment: http://stackoverflow.com/comment/82709959
score: 0
has comment: http://stackoverflow.com/comment/82647646
tagged with: python-imaging-library
has comment: http://stackoverflow.com/comment/82646055
has body: EDIT: While waiting to see what possible solutions can be thought up for using Image.point() I would like to add that I now understand why my expression doesn't work in ImageMath.eval. ImageMath.eval performs individual actions on the whole image, not the entire eval statement pixel by pixel. So when I ask if (a-b) > 255 what I'm really asking is if the image that results from (a-b) is > 255. Which is a ridiculous question. And Pillow auto-clips values with no option to allow for wrapping in the source. If I had a better understanding of C++ and compiling python libraries I'd gladly fork and change that xD. But until I gain that knowledge I'll just have to do it manually outside of the library. ORIGINAL QUESTION: I have this subtraction routine to subtract two channels in an image from each other. (I use a middleman image because I occasionally got weird results if I added the bias in too soon) def subChannels(c1,c2,divisor=1,bias=0): ecpression = "(a/%s)-(b/%s)" % (divisor,divisor) middleman = ImageMath.eval(expression, a=c1, b=c2).convert("L") return Image.Math.eval("a + b", a = middleman, b = bias).convert("L") Exceedingly simple. And it works. Except in cases where I have a bias/offset that pushes the value over 255 or under 0. Then it just clips the results. Now I have tried adding a ridiculous if else evaluation statement that attempts to do the wrapping for me. def subChannels(c1,c2,divisor=1,bias=0): overflow = "((%s) - 256) if (%s) &gt; 255 else (256 + (%s)) if (%s) &lt; 0 else (%s)" sub = "(a/%s)-(b/%s)" % (divisor,divisor) expression = overflow % (sub, sub, sub, sub, sub) middleman = ImageMath.eval(expression, a=c1, b=c2).convert("L") add = "a + b" expression = overlfow % (add, add, add, add, add) return ImageMath.eval(expression, a=middleman, b = bias).convert("L") And that failed spectacularly. The resulting image only got a few of the pixels correct. The rest were blown out, pure white. It was really weird. Then I tried performing the equation manually…
has comment: http://stackoverflow.com/comment/82647953
tagged with: python

http://stackoverflow.com/q/47761039
accepted answer: http://stackoverflow.com/a/47761127
linked to: http://stackoverflow.com/q/47618118
upvote count: 1
downvote count: 1
favorite count: 0
has body: I want to know the correct approach on how to replace numbers in a list of lists with their dictionary counterpart. Currently my code is: #the object list and max weight are supposed to be user input but i have hard coded it in for now to try and get other parts working first. object_list = [(2, 70), (3, 85), (5, 120)] # the first number in the tuple is my weight and the second is my cost max_weight = 17 #this is the number each list in the list of lists add to #seperatng weights and costs into a string then making a dictionary out of it. weight_values = [int(i[0]) for i in object_list] cost_values = [int(i[1]) for i in object_list] dictionary = dict(zip(weight_values, cost_values)) Lets say I have the list (all the possible combinations that add to the max weight): [[3, 2, 2, 2, 2, 2, 2, 2], [3, 3, 3, 2, 2, 2, 2], [3, 3, 3, 3, 3, 2], [5, 2, 2, 2, 2, 2, 2], [5, 3, 3, 2, 2, 2], [5, 3, 3, 3, 3], [5, 5, 3, 2, 2], [5, 5, 5, 2]] and the dictionary I generated is: dictionary = {2: 70, 3: 85, 5: 120} What I want to try and do is replace all the 2's with 70, all the 3's with 85 and all the 5's with 120 (for this case). The dictionary generated is based on user input, so in another scenario all the 2 's may need to be replaced with 35 instead of 70. I need a way of replacing the numbers without specifically saying something like if there is a 2 replace it with 70. This list of lists is generated using this answer (Recursive tree terminates function prematurely)
type: Question
has title: How to replace numbers in a list of lists with its dictionary counterpart?
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/47775187
has answer: http://stackoverflow.com/a/47775187
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/82483434
score: 0
has comment: http://stackoverflow.com/comment/82483550
tagged with: list
answer count: 2
has answer: http://stackoverflow.com/a/47761127

http://stackoverflow.com/comment/82452814
type: Comment
comment on: http://stackoverflow.com/q/47746361
type: QuestionComment
score: 0
has text: It doesn't look like `"n"` is in your ordering.

http://stackoverflow.com/q/47815762
score: 4
upvote count: 4
type: AnsweredQuestion
tagged with: mocking
accepted answer: http://stackoverflow.com/a/47858979
has body: I want to mock out the generation of an SMTP client form smtplib. The following code: from smtplib import SMTP from unittest.mock import patch with patch('smtplib.SMTP') as smtp: print(SMTP, smtp) returns &lt;class 'smtplib.SMTP'&gt; &lt;MagicMock name='SMTP' id='140024329860320'&gt; implying that the patch failed. EDIT: Interestingly Monkey Patching as described here gives the same result. import smtplib from smtplib import SMTP from unittest.mock import MagicMock smtp = MagicMock() smtplib.SMTP = smtp print(SMTP, smtp)
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/47858979
favorite count: 0
tagged with: unit-testing
type: Question
tagged with: python-3.x
linked to: http://stackoverflow.com/q/2461702
has comment: http://stackoverflow.com/comment/82680216
linked to: http://stackoverflow.com/q/37297265
has title: Patch SMTP client in python with unittest.mock
tagged with: python-unittest.mock
tagged with: python

http://stackoverflow.com/q/47782041
accepted answer: http://stackoverflow.com/a/47782354
tagged with: web-scraping
has answer: http://stackoverflow.com/a/47782078
possible better answer: http://stackoverflow.com/a/47782078
has comment: http://stackoverflow.com/comment/82525432
has title: How to improve regular expression to extract phone numbers?
favorite count: 0
has body: I am trying to use regular expression to extract phone number from web links. The problem I am facing is with unwanted id's and other elements of webpage. If anyone can suggest some improvements, it would be really helpful. Below is the code and regular expression I am using in Python, from urllib2 import urlopen as uReq uClient = uReq(url) page_html = uClient.read() print re.findall(r"(\(?\d{3}\D{0,3}\d{3}\D{0,3}\d{4}).*?",page_html) Now, for most of the website, the script getting some page element values and sometimes accurate. Please suggest some modifications in expression re.findall(r"(\(?\d{3}\D{0,3}\d{3}\D{0,3}\d{4}).*?",page_html) My output looks like below for different url's http://www.fraitagengineering.com/index.html ['(877) 424-4752'] http://hunterhawk.com/ ['1481240672', '1481240643', '1479852632', '1478013441', '1481054486', '1481054560', '1481054598', '1481054588', '1476820246', '1481054521', '1481054540', '1476819829', '1481240830', '1479855986', '1479855990', '1479855994', '1479855895', '1476819760', '1476741750', '1476741750', '1476820517', '1479862863', '1476982247', '1481058326', '1481240672', '1481240830', '1513106590', '1481240643', '1479855986', '1479855990', '1479855994', '1479855895', '1479852632', '1478013441', '1715282331', '1041873852', '1736722557', '1525761106', '1481054486', '1476819760', '1481054560', '1476741750', '1481054598', '1476741750', '1481054588', '1476820246', '1481054521', '1476820517', '1479862863', '1481054540', '1476982247', '1476819829', '1481058326', '(925) 798-4950', '2093796260'] http://www.lbjewelrydesign.com/ ['213-629-1823', '213-629-1823'] I want just phone numbers with (000) 000-0000 (not that I have added space after parenthesis),(000)-000-0000or000-000-0000` format. Any suggestions appreciated. Please note that I have already referred to this link : Find phone numbers in python script I need improvement in regex for my specific needs.
type: Question
downvote count: 0
has answer: http://stackoverflow.com/a/47782354
tagged with: python
tagged with: regex
linked to: http://stackoverflow.com/q/3868753
type: AnsweredQuestion
score: 3
upvote count: 3
answer count: 2
tagged with: pandas

http://stackoverflow.com/comment/82428273
comment on: http://stackoverflow.com/a/47719782
score: 0
type: Comment
has text: If I try to replace the character, nothing happens. I know it is not the code I am using because if I rename or replace any other column it is working. Except this one
type: AnswerComment

http://stackoverflow.com/a/47786168
has comment: http://stackoverflow.com/comment/82636972
answers question: http://stackoverflow.com/q/47785950
has comment: http://stackoverflow.com/comment/82604962
type: Answer
has comment: http://stackoverflow.com/comment/82636873
has body: You can use function __import__ or module importlib for with task. For first use should scan directory for python file. After import then with __import__ or importlib. Better use importlib Example import os import sys def import_libs(path): sys.path.append(path) return [__import__(os.path.join(path, module)) for module in filter(lambda x: x and x[-3:] == ".py", os.listdir("./modules/calculate/calculate"))] print(import_libs('exchanges')) Also i have one question? Why you need do this? I think will be better if you look at the factory design pattern.
score: 0

http://stackoverflow.com/comment/82670283
type: QuestionComment
has text: There's no other way. `co.uk` isn't a valid domain, but `co.de` is. Thus, `foo.co.uk` would reduce to `foo.co.uk`, but `foo.co.de` should become just `co.de`. There are a few libraries that handle all of these special cases.
type: Comment
comment on: http://stackoverflow.com/q/47852950
score: 1

http://stackoverflow.com/a/47757322
upvote count: 4
has comment: http://stackoverflow.com/comment/82475940
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47757308
score: 4
has comment: http://stackoverflow.com/comment/82475788
has body: You can iterate over your list k and use dictionary comprehension to get the new keynames from keymap: k = [{'width_min': 0, 'width_max': 300, 'height_min': 0, 'height_max': 65535}, {'width_min': 301, 'width_max': 600, 'height_min': 0, 'height_max': 65535}, {'width_min': 601, 'width_max': 65535, 'height_min': 0, 'height_max': 65535}] keymap = { 'width_min': 'minWidth', 'width_max': 'maxWidth', 'height_min': 'minHeight', 'height_max': 'maxHeight', } k = [{keymap.get(a, a):b for a, b in i.items()} for i in k] Output: [{'minWidth': 0, 'maxHeight': 65535, 'minHeight': 0, 'maxWidth': 300}, {'minWidth': 301, 'maxHeight': 65535, 'minHeight': 0, 'maxWidth': 600}, {'minWidth': 601, 'maxHeight': 65535, 'minHeight': 0, 'maxWidth': 65535}]
accepted answer of: http://stackoverflow.com/q/47757308
type: Answer

storage
tag name: storage
tags question: http://stackoverflow.com/q/47842966
type: Tag

http://stackoverflow.com/q/47779344
has answer: http://stackoverflow.com/a/47779570
has comment: http://stackoverflow.com/comment/82519916
type: UnansweredQuestion
answer count: 1
tagged with: python
tagged with: matlab
has comment: http://stackoverflow.com/comment/82520019
score: 0
has title: Matlab to Python Conversion CO2 Concentration
has body: I'm new to Python and am trying to get my head around it. I have some code from Matlab that I want to convert to Python and I'm struggling with it. I tried using OMPC converter but so far am finding it hard to use without the built in functions compared with Matlab. Some of my code is as follows: start_year=1; % Model Start Date end_year=100000; % End date dt=1; % Incremented time time=start_year:dt:end_year; % Time variable N=length(time); % Number of incrementes E=1; tauC=50; tauC_fat=[30 300 10000]; C=zeros(1,N); % CO2 Concentration C_fat=zeros(1,N); C0=0; C(1)=C0; C_fat(1)=C0; Also I'm using the Spyder version of Python 3.6 which I downloaded from Anaconda, is this a good place to start my python learning?
tagged with: converters
has comment: http://stackoverflow.com/comment/82520306
has comment: http://stackoverflow.com/comment/82522452
type: Question

http://stackoverflow.com/q/47706002
linked to: http://stackoverflow.com/q/417142
tagged with: nginx
score: 1
answer count: 1
upvote count: 1
tagged with: http
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82383022
has answer: http://stackoverflow.com/a/47706947
has comment: http://stackoverflow.com/comment/82372202
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82372313
has title: Is there a maximum length for django request URL?
downvote count: 0
tagged with: django
tagged with: python
has body: I was trying to send a get request to django beackend which encodes a list of ids that I need. I noticed that when this list of id(string) goes too long, the django will not handle this request. I can see the request in the django test server, but it never actually enter any view. In the browser, nginx gives me 404. URL: "/xxx/xxx/xxx?type=xxx&amp;ids=4918230_25808605%2C4996758_49144848%2C5121093_43940616%2C56944804_40780188...." I know I can maybe use post to encode params in the body instead, but I just want to find out the reason behind this.
has comment: http://stackoverflow.com/comment/82372286

http://stackoverflow.com/comment/82504941
type: Comment
type: QuestionComment
has text: nope. I have little knowledge about pygame that's why I was asking. I know what the codes do and mean in the current state.
comment on: http://stackoverflow.com/q/47771351
score: 0

http://stackoverflow.com/comment/83660713
comment on: http://stackoverflow.com/a/47768570
type: Comment
has text: The default parameter does what it says. If you don't set it, it gets set to the default. BUT, that ONLY works in all entities that you save AFTER you change the model.
type: AnswerComment
score: 0

http://stackoverflow.com/q/47805246
type: Question
type: UnansweredQuestion
tagged with: odoo
tagged with: python
has title: How to move data in sale.order.line to delivery order (stock.pack.operation)
has body: I would like to move the description of the product on sale order line to the delivery order line (stock.pack.operation). I added this code in the "action_confirm" of the sale.order order.picking_ids.pack_operation_product_ids.write ({' my_field_in_stock_pack_operation': order_line.order.name}) for a product that is already successful. But if more than 1 will occur error.. is there a way or another solution? i am using odoo 10
downvote count: 0
tagged with: odoo-10
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/47806950
answer count: 1
favorite count: 0

http://stackoverflow.com/a/47743879
answers question: http://stackoverflow.com/q/47743741
downvote count: 0
score: 3
upvote count: 3
type: Answer
has body: You could use openpyxl. Here's a sketch of the code: from openpyxl import load_workbook compiled_wb = load_workbook(filename = 'yourfile1.xlsx') compiled_ws = compiled['Output'] for i in range(1, 30): wb = load_workbook(filename = 'yourfile{}.xlsx'.format(i)) ws = wb['Output'] compiled_ws.append(ws.rows()[1:]) # ignore row 0 compiled_wb.save('compiled.xlsx')

http://stackoverflow.com/comment/82675019
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47855386
score: 0
has text: This is a code snippet. I have used ret, frame = cap.read() in the write function, which is pure openCV, in a while loop, using the same function list. Same result. Example 1 works (using PySide as windowing, not openCV, doesn't need ret, frame). Again WHY does example 1 WORK and example 2 doesn't?

http://stackoverflow.com/a/47828445
score: 5
answers question: http://stackoverflow.com/q/47828176
downvote count: 0
upvote count: 5
type: Answer
has body: As mentioned in the comment, an XML file cannot have multiple roots. Simple as that. If you do receive/store data in this format (and then it's not proper XML). You could consider a hack of surrounding what you have with a fake tag, e.g. import xml.etree.ElementTree as ET with open("0020-syslog_rules.xml", "r") as inputFile: fileContent = inputFile.read() root = ET.fromstring("&lt;fake&gt;" + fileContent +"&lt;/fake&gt;") print(root)

http://stackoverflow.com/q/47788548
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/82539210
score: 0
has body: I'm starting to learn programming and trying to write my first flash game bot, but I think I can't sort things out This game is, player click in 5 areas randomly, if player is lucky, the enemy will get shot and reduce his hp. Enemy's hp is 6, and this game requires player to finish this in no more than 7 shots, which means player has only one chance to miss the guess. So I "cut" the HP bar into 6 jugdement areas, and use PIL in python to judge the pixel's color change in every area, then let pyautogui to do some auto clicks. Main part of this code is: while True: flag = 1 for i in range(6): s = screenGrab() pixels = s.load() pixelJugde_1 = pixels[judgeAreas[i]] # jugde if hp is reduced after this shot if pixelJugde_1 != (0, 0, 0): # if this shot missed randomClick() # try again s = screenGrab() pixels = s.load() pixelJugde_2 = pixels[judgeAreas[i]] # second judge of this shot if (pixelJugde_2 != pixelJugde_1): # hp changed, second try didn't miss flag = 1 # mark this shot has been tried twice randomClick() # continue next shot elif (pixelJugde_2 == pixelJugde_1 and flag == 1): # second try missed resetResult() # restart the game break else: print 'got shot' # success at first try randomClick() # next shot now my problem is, if the first shot has been tried twice and marked, when the next shot begins and misses, it will still try twice, just like the marking flag is not working. So how to fix this?
has comment: http://stackoverflow.com/comment/82563711
has title: can't figure out a loop with some conditions
type: Question
has comment: http://stackoverflow.com/comment/82538149
answer count: 0

http://stackoverflow.com/a/47847970
has body: It is possible to create a coo format matrix from your x: In [22]: x = np.array('a', 'b', 'c', dtype=object) In [23]: M=sparse.coo_matrix(x) In [24]: M Out[24]: &lt;1x3 sparse matrix of type '&lt;class 'numpy.object_'&gt;' with 3 stored elements in COOrdinate format&gt; In [25]: M.data Out[25]: array(['a', 'b', 'c'], dtype=object) coo has just flattened the input array and assigned it to its data attribute. (row and col have the indices). In [31]: M=sparse.coo_matrix(x) In [32]: print(M) (0, 0) a (0, 1) b (0, 2) c But displaying it as an array produces an error. In [26]: M.toarray() ValueError: unsupported data types in input Trying to convert it to other formats produces your typeerror. dok sort of works: In [28]: M=sparse.dok_matrix(x) /usr/local/lib/python3.5/dist-packages/scipy/sparse/sputils.py:114: UserWarning: object dtype is not supported by sparse matrices warnings.warn("object dtype is not supported by sparse matrices") In [29]: M Out[29]: &lt;1x3 sparse matrix of type '&lt;class 'numpy.object_'&gt;' with 3 stored elements in Dictionary Of Keys format&gt; String dtype works a little better, x.astype('U1'), but still has problems with conversion to csr. Sparse matrices were developed for large linear algebra problems. The ability to do matrix multiplication and linear equation solution were most important. Their application to non-numeric tasks is recent, and incomplete.
accepted answer of: http://stackoverflow.com/q/47845327
has comment: http://stackoverflow.com/comment/82660277
type: Answer
upvote count: 4
answers question: http://stackoverflow.com/q/47845327
type: AcceptedAnswer
downvote count: 0
score: 4

http://stackoverflow.com/q/47735944
linked to: http://stackoverflow.com/q/47163486
tagged with: python-3.6
has answer: http://stackoverflow.com/a/47748598
favorite count: 0
has comment: http://stackoverflow.com/comment/82440972
has title: Countermeasure for having the coordinate grid upside down?
score: 2
has body: So I'm using pygame to create a simple top-down shooter game, and I'm doing lots of angle calculations from the top-down perspective. Let's use a simple arrow and a ball as an example, I want the red arrow to keep pointing at the blue ball regardless of where the blue ball moves: And it seemed easy enough, I just needed atan2: angle = math.atan2(blue.y - red.y, blue.x - red.x) But the problem is, atan2 works for a mathematical coordinate grid like this: Where alpha = math.atan2(blue.y - red.y, blue.x - red.x) But the thing with pygame (on Windows at least) is that the coordinate grid doesn't work like a mathematical coordinate grid, it's actually upside down starting from the left top corner of the game window: So while it looks like the blue ball is higher up and thus mathematically blue.y should be larger than red.y, this is actually not the case due to the upside down coordinate grid, which Python's math.atan2() doesn't know of, and the original calculation I had: angle = math.atan2(blue.y - red.y, blue.x - red.x) Actually yields the correct angle's negation. Now the obvious first solution that I came up with was to just flip the sign, and fair enough it worked with this: angle = -math.atan2(blue.y - red.y, blue.x - red.x) But the issues started again once I needed to do further calculations based on the previously calculated angle, which technically is now upside down. What countermeasures could I take to "permanently" get rid of this issue? Here's an actual example of where I need this, I have a "zombie" entity which does nothing but follows the target it has been given: class Zombie(Entity): def __init__(self, *args, target=None, **kwargs): super().__init__(*args, **kwargs) self.target = target def update(self, dt, app): if self.target: # Face towards target dx = self.target.x - self.x dy = self.target.y - self.y self.angle = math.atan2(dy, dx) # Change velocity towards target speed = self.get_max_speed() vel_x = math.cos(angle) * speed vel_y = math.sin(angle)…
tagged with: python
tagged with: pygame
has comment: http://stackoverflow.com/comment/82432782
tagged with: coordinates
linked to: http://stackoverflow.com/q/47644279
type: Question
has comment: http://stackoverflow.com/comment/82440691
tagged with: angle
upvote count: 2
has comment: http://stackoverflow.com/comment/82433240
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82432985
downvote count: 0
answer count: 1

http://stackoverflow.com/q/47703374
tagged with: pandas
downvote count: 0
answer count: 1
upvote count: 1
has title: 2 groupby in the same dataframe, it is possible?
accepted answer: http://stackoverflow.com/a/47703485
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47703485
has body: I want to the following df, to make a df = df.groupby(['id','quarter'])['jobs].mean() but at the same time that dataframe must have the mean of jobs by id and year in another column. id year quarter month jobs 1 2007 1 1 10 1 2007 1 2 12 1 2007 1 3 12 1 2007 2 4 12 1 2007 2 5 12 1 2007 2 6 13 1 2007 3 7 14 1 2007 3 8 9 1 2007 3 9 12 1 2007 4 10 15 1 2007 4 12 18 2 2007 1 1 15 2 2007 1 2 15 2 2007 1 3 16 2 2007 2 4 17 2 2007 2 5 18 2 2007 2 6 10 2 2007 3 7 12 2 2007 3 8 12 2 2007 3 9 12 2 2007 4 10 12 2 2007 4 11 13 2 2007 4 12 14 result should look like this id year quarter jobs jobs_year 1 2007 1 (mean quarter) (mean year) 1 2007 2 (mean quarter) (mean year) 1 2007 3 (mean quarter) (mean year) 1 2007 4 (mean quarter) (mean year) 2 2007 1 (mean quarter) (mean year) 2 2007 2 (mean quarter) (mean year) 2 2007 3 (mean quarter) (mean year) 2 2007 4 (mean quarter) (mean year)
score: 1
tagged with: python
tagged with: numpy
type: AnsweredQuestion

http://stackoverflow.com/comment/82633900
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47798504
has text: @DDeMartini it is Linux xubuntu 17.10 and python is 3.6.3 from anaconda virtual environment.I ll try to follow your advice. How do one inspects a process stack is what I m wondering.
type: Comment

http://stackoverflow.com/a/47817905
type: Answer
has comment: http://stackoverflow.com/comment/82598903
upvote count: 3
has comment: http://stackoverflow.com/comment/82598510
downvote count: 0
has body: You are trying to access http://localhost:8000/, but at the moment there aren't any matching URL patterns for that. You one URL pattern is for the Django admin, which you can access at http://localhost:8000/admin/. When Django doesn't find a matching URL pattern and you have DEBUG = True in your settings, then you get the yellow 'Page Not Found' page. There are a couple of hardcoded exceptions. When the URL config is empty, or it has not been modified yet, then you get the "Congratulations it worked" page (your example A). In your example B, you have modified the urlpatterns by adding static() to it. Therefore you get the regular yellow 'Page Not Found' page. In order for http://localhost:8000/ to work, you need to add a matching URL pattern, for example: from django.http import HttpResponse def home_view(request): return HttpResponse('home') urlpatterns = [ path('admin/', admin.site.urls), path('', home_view), ] Note that putting a view in your urls.py like this is not good practice. I've done it in this case so that you can quickly add a matching pattern for testing.
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47817579
has comment: http://stackoverflow.com/comment/82599465
answers question: http://stackoverflow.com/q/47817579
score: 3
has comment: http://stackoverflow.com/comment/82600276

http://stackoverflow.com/comment/82635682
type: AnswerComment
has text: That's fine; feel free to adapt my solution for your specific data types. `set(array)` works just as well as `set(list)`.
type: Comment
comment on: http://stackoverflow.com/a/47825100
score: 0

http://stackoverflow.com/a/47738909
answers question: http://stackoverflow.com/q/47735638
type: Answer
score: -1
upvote count: 0
has body: Found the problem, even though i had enough CPU memory, I had to clear my gpu memory by killing the processes running under it (thanks to quora https://www.quora.com/How-do-I-kill-all-the-computer-processes-shown-in-nvidia-smi) (tfpy27) ubuntu@ip-10-0-0-9:~/Object-Detector-App/object_detection$ nvidia-smi Sun Dec 10 12:29:04 2017 +-----------------------------------------------------------------------------+ | NVIDIA-SMI 375.66 Driver Version: 375.66 | |-------------------------------+----------------------+----------------------+ | GPU Name Persistence-M| Bus-Id Disp.A | Volatile Uncorr. ECC | | Fan Temp Perf Pwr:Usage/Cap| Memory-Usage | GPU-Util Compute M. | |===============================+======================+======================| | 0 Tesla K80 Off | 0000:00:1E.0 Off | 0 | | N/A 67C P0 60W / 149W | 4483MiB / 11439MiB | 0% Default | +-------------------------------+----------------------+----------------------+ +-----------------------------------------------------------------------------+ | Processes: GPU Memory | | GPU PID Type Process name Usage | |=============================================================================| | 0 8200 C /home/ubuntu/anaconda2/bin/python 4481MiB | +-----------------------------------------------------------------------------+ sudo kill -9 &lt;PID&gt; but still not sure why it was taking up so much memory for running a session on just a single medium sized image
downvote count: 1

http://stackoverflow.com/q/47766722
has comment: http://stackoverflow.com/comment/82494851
tagged with: python
has comment: http://stackoverflow.com/comment/82494984
has title: Unpickle file from HDFS
type: Question
tagged with: hadoop
has comment: http://stackoverflow.com/comment/86894184
downvote count: 0
answer count: 1
has body: I'm currently using Python 3 and would like to load a pickle file out of HDFS. from pywebhdfs.webhdfs import PyWebHdfsClient import pickle hdfs = PyWebHdfsClient(host='...', user_name='...') pickled_model = hdfs.read_file(pickle_path) model = pickle.load(pickled_model) TypeError: file must have 'read' and 'readline' attributes I get a type error at the pickle loading stage. I found an option to open the file using pydoop and then unpickle it. But unfortunately, I can't use Python 2.7. Any similar options?
favorite count: 0
type: AnsweredQuestion
upvote count: 3
score: 3
has answer: http://stackoverflow.com/a/47767022
accepted answer: http://stackoverflow.com/a/47767022

http://stackoverflow.com/comment/82474692
score: 0
comment on: http://stackoverflow.com/q/47756559
type: Comment
type: QuestionComment
has text: @johnashu added the code

http://stackoverflow.com/q/47806068
score: 5
downvote count: 0
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/82573971
accepted answer: http://stackoverflow.com/a/49488547
has comment: http://stackoverflow.com/comment/85952208
has body: I am making a website where I am using Vuejs for front end. For registration, I am using rest_auth.registration. In Vuejs code, I am making the registration post request through axios. axios.post(this.registrationUrl,{ username, email, password1, password2, }).then(res =&gt; { console.log('Registration Successful!') }).catch(err =&gt; { // console.log('There is error!') let errData = err.response.data this.errors.push(errData) for (let errorType in errData) { for (let error of errData[errorType]) { this.errors.push(error) } } }) The problem is that while registering a user, the promise in the code returns an error even if the registration is successful and a new user can be seen in the django admin panel. The returning error: OSError at /rest-auth/registration/ [Errno 99] Cannot assign requested address Request Method: POST Request URL: http://localhost:8000/rest-auth/registration/ Django Version: 1.11.8
has comment: http://stackoverflow.com/comment/85957763
has answer: http://stackoverflow.com/a/49488547
tagged with: rest
has comment: http://stackoverflow.com/comment/82574144
type: AnsweredQuestion
upvote count: 5
tagged with: authentication
has title: Django rest_auth.registration is sending back error even in successful registration
possible better answer: http://stackoverflow.com/a/50011434
favorite count: 0
has answer: http://stackoverflow.com/a/50011434
type: Question
tagged with: vue.js
answer count: 2

http://stackoverflow.com/q/47802139
tagged with: postgresql
tagged with: python
has answer: http://stackoverflow.com/a/47802452
score: 2
has body: I wrote a script in python that connects to a database using psycopg. I'm working with two tables in the same database. First I run a select * from table_1 and after that I check if each row (fetchone) meets some requirements. If they do, a new row in table_2 is created with an INSERT. The code looks similar to this: cursor_1 = conn.cursor() cursor_2 = conn.cursor() cursor_1.execute("SELECT * FROM table_1") for i in range(1,n): a = cursor_1.fetchone() if (condition_in_a): cursor_2.execute("INSERT into table_2 (f1,f2) values (v1,v2)") The script runs in a sequential for loop and I wanted to know if there's a better way to accomplish this task through psycopg2.pool in terms of performance. So my question is: Is it possible to multithread a psycopg cursor? If not, what would be the best approach to achieve a better performance? Thanks in advance.
upvote count: 2
type: UnansweredQuestion
has title: Threading inside a cursor in psycopg2
downvote count: 0
answer count: 1
tagged with: psycopg2
favorite count: 0
type: Question

http://stackoverflow.com/q/47853615
has comment: http://stackoverflow.com/comment/82671392
has body: To create a pandas.Series from a generic object, the following can be used: import datetime class Test(object): def __init__(self): self.creation = datetime.datetime.now() a = Test() c = pandas.Series(a.__dict__) This results in a Series that is described as creation 2017-12-17 09:51:48.157503 dtype: datetime64[ns] This failed to work if the object contains "attributes" created using @property, like so class Test(object): def __init__(self): self.creation = datetime.datetime.now() @property def as_string(self): return 'Test at {}'.format(self.creation) a = Test() c = pandas.Series(a.__dict__) # same as above How can the object's properties be included in the Series? Or is there an easier way to create a Series from a generic object, including its properties?
linked to: http://stackoverflow.com/q/624926
type: AnsweredQuestion
tagged with: pandas
has comment: http://stackoverflow.com/comment/82671422
has comment: http://stackoverflow.com/comment/82671490
score: 1
answer count: 1
downvote count: 0
upvote count: 1
accepted answer: http://stackoverflow.com/a/47856457
has title: Create series from python object, include its @property
favorite count: 0
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/82671503
has answer: http://stackoverflow.com/a/47856457
has comment: http://stackoverflow.com/comment/82671511
has comment: http://stackoverflow.com/comment/82671403

http://stackoverflow.com/q/47805784
possible better answer: http://stackoverflow.com/a/52890366
score: 9
type: Question
upvote count: 9
has answer: http://stackoverflow.com/a/72010283
tagged with: windows
has answer: http://stackoverflow.com/a/52890366
tagged with: powershell
tagged with: python
answer count: 5
has comment: http://stackoverflow.com/comment/136660680
has comment: http://stackoverflow.com/comment/82573146
has title: Why is 'python' not recognized in powershell?
has answer: http://stackoverflow.com/a/78666306
has answer: http://stackoverflow.com/a/75782679
type: AnsweredQuestion
has body: I have installed python 3.6 in my Windows 10 PC. I also use Pycharm to make my scripts. It runs perfectly fine there. But my problem is I can't run python in powershell. I am told to simply type 'python' in powershell and it should automatically start python. But, I get an error saying it's not recognised. Windows PowerShell Copyright (C) Microsoft Corporation. All rights reserved. PS C:\Users\lenovo> python python : The term 'python' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 + python + ~~~~~~ + CategoryInfo : ObjectNotFound: (python:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException Some suggested to type this: [Environment]::SetEnvironmentVariable("Path", "$enc:Path;C:\Users\lenovo\AppData\Local\Programs\Python\Python36") The path given in the above code is correct for my PC. Infact, Python runs after I give the above code. But, that is my problem. Every time I close and open powershell again, I have to type the above code to get python running. I tried typing this in Powershell running as an admin too. But, it doesn't work. I even tried restarting my PC, still the problem refuses to resolve. I am expected to type the above code every time I want to run python in a new powershell window. This is a bit annoying. Any help would be appreciated. Thanks.
has comment: http://stackoverflow.com/comment/82572976
linked to: http://stackoverflow.com/q/714877
downvote count: 0
accepted answer: http://stackoverflow.com/a/47806488
has answer: http://stackoverflow.com/a/47806488
favorite count: 0

http://stackoverflow.com/comment/82450744
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47736056
has text: I read through the linked question and all my foreign keys reference primary keys and are type `Int` Sorry about the formatting, I'm unable to find a way of posting code blocks in the comment section.
score: 0

http://stackoverflow.com/q/47829457
score: 1
has comment: http://stackoverflow.com/comment/82622667
has comment: http://stackoverflow.com/comment/82621742
accepted answer: http://stackoverflow.com/a/47830625
has answer: http://stackoverflow.com/a/47830625
answer count: 4
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/82888150
has answer: http://stackoverflow.com/a/47830173
has comment: http://stackoverflow.com/comment/82621880
linked to: http://stackoverflow.com/q/31389481
has comment: http://stackoverflow.com/comment/82622151
downvote count: 0
has comment: http://stackoverflow.com/comment/82621665
upvote count: 1
tagged with: python
possible better answer: http://stackoverflow.com/a/47829953
has body: I have a list a = np.ones(100) I want to turn 50 random items in that list to 0. Once those elements are 0, I want to turn 25 random elements of the remaining items in the list to 0. Of the remaining 25 ones, I want to turn 13 of the remaining elements to zero at random etc. I will then run this through a simple loop e.g. (pseudocode) "if item == 1, print red particle, else print blue particle" etc. This is basically to simulate exponential decay, but I'm struggling to think of an algorithm to do this. This is not a duplicate of "Numpy: Replace random elements in an array" because once the elements have changed I do not want them to be considered for change again.
favorite count: 0
has comment: http://stackoverflow.com/comment/82621573
has comment: http://stackoverflow.com/comment/82625224
has answer: http://stackoverflow.com/a/47829953
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47831412
has title: numpy irreversibly change items in a list at random
tagged with: random
has comment: http://stackoverflow.com/comment/82622573

http://stackoverflow.com/a/47707715
type: Answer
has body: Although your sample run is flawed, I believe I understand the gist of what you're trying to do. You generate a random password and then represent it with asterisks, so that the length is shown. Then, for each character in characters="abcdefghijklmnopqrstuvwxyz0123456789" you check if it matches any of the chars in the password. By the time you've run through it, you're done. So, you're going to need a double nested loop. I won't write it for you, but i'll give you a hint, in pseudocode: generate a random password make a corresponding 'fake' password of the same length of asterisks for char in charList: for position in actual password: if char matches that position: change the asterisk to that char in the fake password if my fake password is cracked (no more asterisks): print('Whoohoo!') go home, you're done Hope this helps! Getting the logic right is always the hardest part of programming! As a side note, I got the above understanding because I noticed in your example that you are cracking the password in alphabetical order... d-f-k-s-y-z...
answers question: http://stackoverflow.com/q/47707526
score: 0

http://stackoverflow.com/a/47762024
accepted answer of: http://stackoverflow.com/q/47761762
type: AcceptedAnswer
score: 1
answers question: http://stackoverflow.com/q/47761762
downvote count: 0
type: Answer
upvote count: 1
has body: One way to have both your requirements in one go would be: import regex as re rx = re.compile(r'(?V1)(?&lt;=[a-z])(?=\d+)') def splitter(row): (char, number) = rx.split(row['a']) return pd.Series({'a': '{}_{}{}'.format(char, number, number), 'd': number}) df'a', 'd' = df.apply(splitter, axis = 1) Which yields using df.head(): a b c d 0 e_11 21 99 1 1 e_11 21 99 1 2 e_22 22 99 2 3 e_33 23 99 3 4 e_11 23 99 1 The idea here is to set up a splitter function which splits between letters and numbers. The function is applied row-wise and gives back the new columns. You'll need the newer regex module for empty splits to work.

http://stackoverflow.com/a/47772868
upvote count: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47772143
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85899887
answers question: http://stackoverflow.com/q/47772143
type: Answer
has body: As @Andersson posted the fix is quite simple, all that was needed was the dot at the beginning of the expression: for element in results: field1 = element.find_elements_by_xpath(".//*[contains(@class, 'field1')]")
score: 2

http://stackoverflow.com/q/47826527
has answer: http://stackoverflow.com/a/47826692
tagged with: python
has body: What I'm trying to do is get the data from the child element in the below code: ... .... .... I want to get the id of each div inside the expandedList class. I tried using xpath but that not capturing all the expandedList.
score: -1
tagged with: xpath
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82615383
upvote count: 0
answer count: 1
tagged with: selenium
downvote count: 1
accepted answer: http://stackoverflow.com/a/47826692
favorite count: 0
type: Question
has title: How to get child element data using python and selenium?

http://stackoverflow.com/comment/82523426
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47780832
score: 0
has text: The reason you already have access to all the ones declared within the `__init__` function is because the init is the constructor and gets auto called whenever an instance is created.

http://stackoverflow.com/q/47841675
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47841843
has comment: http://stackoverflow.com/comment/82647588
tagged with: python
has title: str.strip() removes number?
has answer: http://stackoverflow.com/a/47841843
type: AnsweredQuestion
score: 0
tagged with: pandas
upvote count: 1
answer count: 1
downvote count: 1
has body: I got the following DataFrame: DATE STG #TIME HRD SZ AREA BEAU PSD EFFORT TYPE NORTHING EASTING SEASON BOAT ASSOC. P/S 0 2016-04-06 1 1025 12 W LANTAU 2 58 ON HKCRP 813713 802792 SPRING NONE S 1 2016-04-06 2 1113 3 W LANTAU 4 27 ON HKCRP 806173 802043 SPRING NONE S 2 2016-04-06 3 1345 2 SW LANTAU 2 ND OFF HKCRP 805606 803300 SPRING NONE NaN when I do #remove space in content df_obj = sighting.select_dtypes(['object']) df_obj sighting[df_obj.columns] = df_obj.apply(lambda x: x.str.strip()) It removes the value in PSD column and made them as NaN. Why is that? and How can I fix it? Thank you!

http://stackoverflow.com/a/47701243
has comment: http://stackoverflow.com/comment/82397995
type: Answer
has comment: http://stackoverflow.com/comment/82409187
has comment: http://stackoverflow.com/comment/82372439
answers question: http://stackoverflow.com/q/47700224
has comment: http://stackoverflow.com/comment/82379555
score: 0
has body: You made the same error as in your original code, where you made the motion atomic -- you can't stop everything while you implement the jump. You need to break the jump into discrete steps. Here's my ontimer() based solution: from turtle import Turtle, Screen import math screen = Screen() screen.screensize(1000, 1000) screen.bgcolor('light green') player = Turtle('circle', visible=False) player.penup() player.color('red', 'yellow') player.setposition(-50, -40) player.showturtle() player.speed('fastest') s = Turtle('square', visible=False) s.penup() s.color('black', 'white') s.setposition(-50, -60) s.showturtle() # first tier s1 = Turtle('square', visible=False) s1.penup() s1.color('black', 'white') s2 = s1.clone() s2.setx(s1.xcor() + 20) s2.showturtle() s3 = s1.clone() s3.setx(s2.xcor() + 20) s3.showturtle() s4 = s1.clone() s4.setx(s3.xcor() + 20) s4.showturtle() s1.showturtle() # second tier s5 = Turtle('square', visible=False) s5.penup() s5.color('black', 'white') s5.setposition(s4.xcor() + 30, 60) s6 = s5.clone() s6.setx(s5.xcor() + 20) s6.showturtle() s7 = s5.clone() s7.setx(s6.xcor() + 20) s7.showturtle() s8 = s5.clone() s8.setx(s7.xcor() + 20) s8.showturtle() s5.showturtle() # third tier s9 = Turtle('square', visible=False) s9.penup() s9.color('black', 'white') s9.setposition(s8.xcor() + 30, 120) s10 = s9.clone() s10.setx(s9.xcor() + 20) s10.showturtle() s11 = s9.clone() s11.setx(s10.xcor() + 20) s11.showturtle() s12 = s9.clone() s12.setx(s11.xcor() + 20) s12.showturtle() s9.showturtle() # moving enemy s13 = Turtle('square', visible=False) s13.penup() s13.color('black', 'red') s13.setposition(s11.xcor() + 5, 140) s13.showturtle() # static turtle s14 = Turtle('turtle', visible=False) s14.penup() s14.color('black', 'red') s14.setposition(s6.xcor() + 20, 80) s14.showturtle() squareList = [s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12] RISING, FALLING = 0, 1 state = None speed = -1 def jump(): global speed, state speed = 2 state = RISING screen.ontimer(jumping…
has comment: http://stackoverflow.com/comment/82371259
has comment: http://stackoverflow.com/comment/82371158
has comment: http://stackoverflow.com/comment/82372350
has comment: http://stackoverflow.com/comment/82413049

http://stackoverflow.com/q/47827871
downvote count: 4
has comment: http://stackoverflow.com/comment/82618447
has answer: http://stackoverflow.com/a/47827952
tagged with: http://stackoverflow.com/tag/pdf
answer count: 1
linked to: http://stackoverflow.com/q/17098675
upvote count: 1
linked to: http://stackoverflow.com/q/11570466
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/34837707
type: UnansweredQuestion
has body: I have hundreds of articles on many topics in pdf files in a directory. I need to point some papers containing the keywords git log or git diff command from those hundreds of articles. Then, I will collect the selected articles in a list. How can we do that using Python?
score: -3
tagged with: python
has title: How to find some pdf files contain some keyword using python
tagged with: logging
tagged with: git
tagged with: diff
has comment: http://stackoverflow.com/comment/82618102

http://stackoverflow.com/a/47835344
type: Answer
has body: You replace a character and also write the line. Instead of the, you do fout.write('\n') which writes a newline with open("test.txt", "r") as fin: with open("result.txt", "w") as fout: for line in fin: if line.startswith('('): fout.write('\n') else: fout.write(line)
downvote count: 0
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/47835269

http://stackoverflow.com/comment/82445765
has text: Thank you so much. Just to assure; 1. the first solution is to change the ajax.js $('#likes').ready(function(){ var comid; comid = $(this).attr("data-comid"); $.get('/home/like/', {comentario_id: comid}, function(data){ $('#like_count').html(data); $('#likes').hide(); }); });
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47742737

http://stackoverflow.com/comment/82430749
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47735137
has text: I think you over overthinking it, just finish some projects first with any tools you have available, there is always the right tool for something, don't need to reinvent the wheel.
score: 2

http://stackoverflow.com/comment/82576547
has text: Set the path in windows for python
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47807709

http://stackoverflow.com/q/47774660
tagged with: python
has comment: http://stackoverflow.com/comment/82510285
duplicate of: http://stackoverflow.com/q/30041286
tagged with: numpy
answer count: 0
type: UnansweredQuestion
tagged with: arrays
has title: Aggregate data in a numpy array
has comment: http://stackoverflow.com/comment/82510330
type: Question
score: 0
linked to: http://stackoverflow.com/q/30041286
has body: Is there a natural way in a numpy array, to aggregate rows that have same 1st column value? i.e. such that: A = numpy.array([[1, 2], [1, 7], [2, 14], [3, -1], [3, 6]]) #[[ 1 2] # [ 1 7] # [ 2 14] # [ 3 -1] # [ 3 6]] would give [[ 1 9] [ 2 14] [ 3 5]

http://stackoverflow.com/q/47760193
tagged with: array-broadcasting
score: 0
has comment: http://stackoverflow.com/comment/82560158
answer count: 0
has body: I want to execute for b, w in zip(self.biases, self.weights): a= sigmoid(np.dot(w, a) + b) where, a is a tuple of length 784, self.biases contains a list of matrices of dimensions (15, 1) and (10, 1), self.weights contains a list of matrices of dimensions (15, 784) and (10, 15). So, I am basically calculating w.a + b in each pass through the loop. Upon doing this calculation with w of size (15, 784), a of length 784 and b of size (15, 1), I should get the resultant matrix of size (15, 1) but I am getting (15, 15). To debug, I tried to analyse by printing the various matrices involved and I found that if I removed + b from the above line of code, I get the dimensions of the resultant matrix as (15,). So, I am guessing that the bug should be because of some inadequate type of matrix broadcasting happening in the code. I tried to remove the bug by adding the following lines of code before the for loop: a= np.array(a) np.reshape(a, (784, 1)) But it failed to improve the result. Please help..
tagged with: neural-network
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82483797
has title: unwanted broadcasting in numpy
type: Question
has comment: http://stackoverflow.com/comment/82560759
tagged with: python
has comment: http://stackoverflow.com/comment/82481832
tagged with: matrix-multiplication
tagged with: numpy

http://stackoverflow.com/a/47773654
has comment: http://stackoverflow.com/comment/88429397
has comment: http://stackoverflow.com/comment/82512130
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/88385954
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/82514021
has body: Why not using env? #!/usr/bin/env python And then run your application from the appropriate environment?
has comment: http://stackoverflow.com/comment/82522337
accepted answer of: http://stackoverflow.com/q/47772766
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/88401759
answers question: http://stackoverflow.com/q/47772766
has comment: http://stackoverflow.com/comment/82514099

http://stackoverflow.com/a/47705621
downvote count: 0
type: Answer
has body: input() returns strings... Convert to integers: varthree = int(varone) * int(vartwo)
answers question: http://stackoverflow.com/q/47705598
score: 2
upvote count: 2

http://stackoverflow.com/q/47821563
tagged with: parsing
score: 4
upvote count: 4
tagged with: python-3.x
answer count: 1
downvote count: 0
has body: I would like to parse this json response: { "count":2, "next":null, "previous":null, "results":[ { "id":123, "type_vname":"Suspicious Remote Desktop", "category":"LATERAL MOVEMENT", "src_ip":"192.168.1.1", "state":"fixed", "description":null, "t_score":70, "c_score":70, "first_timestamp":"2017-12-13T18:51:22Z", "last_timestamp":"2017-12-13T18:51:22Z", "detection_detail_set":[ { "id":1234567, "description":"Suspicious Remote Desktop", "dst_host_id":1234, "dst_ip":"192.168.1.1", "count":null, "count_pos":null, "dst_dns":null, "dst_port":80, "dst_geo":null, "proto":null, "first_timestamp":"2017-12-13T18:51:22Z", "last_timestamp":"2017-12-13T18:51:22Z", "total_bytes_sent":null, "total_bytes_rcvd":null, "url":"https://192.168.1.2/api/detection_details" }, { "id":89123456, "description":"Suspicious Remote Desktop", "dst_host_id":5678, "dst_ip":"192.168.1.1", "count":null, "count_pos":null, "dst_dns":null, "dst_port":80, "dst_geo":null, "proto":null, "first_timestamp":"2017-12-13T18:50:18Z", "last_timestamp":"2017-12-13T18:50:18Z", "total_bytes_sent":null, "total_bytes_rcvd":null, "url":"https://192.168.1.2/api/detection_details" } ], "dns_set":[ ], "relayed_comm_set":[ ], "sensor_luid":"abc1pdj", "summary":{ "internal_targets":1, "anomalous_events":2, "probable_owner":"user" }, "host":"https://192.168.1.2/api/detection_details", "url":"https://192.168.1.2/api/detection_details", "tags":[ ], "targets_key_asset":false, "triage_rule_id":null }, { "id":1235, "type_vname":"Suspicious Remote Desktop", "category":"LATERAL MOVEMENT", "src_ip":"192.168.1.2", "state":"fixed", "description":null, "t_score":70, "c_score":70, "first_timestamp":"2017-12-11T19:11:46Z", "last_timestamp":"2017-12-11T19:11:46Z", "detection_detail_set":[ { "id":123445, "description":"Suspicious Remote Desktop", "dst_host_id":4958, "dst_ip":"192.168.1.2", "count":null, "count_pos":null, "dst_dns":null, "dst_port":80, "dst_geo":null, "proto":null, "first_timestamp":"2017-12-11T19:11:46Z", "last_timestamp":"20…
type: Question
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47827847
has title: Parse Nested JSON with Python/Pandas
tagged with: pandas
has answer: http://stackoverflow.com/a/47827847
tagged with: http://stackoverflow.com/tag/json
tagged with: python
favorite count: 0

http://stackoverflow.com/a/47790514
has comment: http://stackoverflow.com/comment/82797849
has comment: http://stackoverflow.com/comment/82864489
has comment: http://stackoverflow.com/comment/82864170
has comment: http://stackoverflow.com/comment/84298590
has comment: http://stackoverflow.com/comment/82864839
has comment: http://stackoverflow.com/comment/82798032
score: 3
has comment: http://stackoverflow.com/comment/82865135
has comment: http://stackoverflow.com/comment/82553858
has comment: http://stackoverflow.com/comment/82798465
has comment: http://stackoverflow.com/comment/82865035
type: Answer
answers question: http://stackoverflow.com/q/47779560
has comment: http://stackoverflow.com/comment/82799803
has comment: http://stackoverflow.com/comment/82796746
has comment: http://stackoverflow.com/comment/82864344
has comment: http://stackoverflow.com/comment/82864449
accepted answer of: http://stackoverflow.com/q/47779560
has comment: http://stackoverflow.com/comment/84298326
has comment: http://stackoverflow.com/comment/82799722
upvote count: 3
has comment: http://stackoverflow.com/comment/82864904
has body: It is not possible to insert plots into a matplotlib table. However subplot grids allow to create a table-like behaviour. import matplotlib.pyplot as plt import numpy as np data = np.random.rand(100,4) col1 = ["WAR", "ERA", "IP", "WHIP", "Final\nScore"] col2 = [0.23,1.60,0.28,0.02,0.38] col2colors = ["red", "g", "r", "r", "r"] finalsc = "D+" fig, axes = plt.subplots(ncols=3, nrows=5, figsize=(4,2.6), gridspec_kw={"width_ratios":[1,0.5,2]}) fig.subplots_adjust(0.05,0.05,0.95,0.95, wspace=0.05, hspace=0) for ax in axes.flatten(): ax.tick_params(labelbottom=0, labelleft=0, bottom=0, top=0, left=0, right=0) ax.ticklabel_format(useOffset=False, style="plain") for _,s in ax.spines.items(): s.set_visible(False) border = fig.add_subplot(111) border.tick_params(labelbottom=0, labelleft=0, bottom=0, top=0, left=0, right=0) border.set_facecolor("None") text_kw = dict(ha="center", va="bottom", size=13) for i,ax in enumerate(axes[:,0]): ax.text(0.5, 0.05, col1[i], transform=ax.transAxes, **text_kw) for i,ax in enumerate(axes[:,1]): ax.text(0.5, 0.05, "{:.2f}".format(col2[i]),transform=ax.transAxes, **text_kw) ax.set_facecolor(col2colors[i]) ax.patch.set_color(col2colors[i]) axes[-1,-1].text(0.5, 0.05, finalsc,transform=axes[-1,-1].transAxes, **text_kw) for i,ax in enumerate(axes[:-1,2]): ax.plot(data[:,i], color="green", linewidth=1) plt.show() To put several such plots into a figure you would approach this a bit differently and create a gridspec with several subgrids. import matplotlib.pyplot as plt from matplotlib import gridspec import numpy as np def summaryplot2subplot(fig, gs, data, col1, col2, finalsc): col2colors = ["g" if col2[i] &gt; 1 else "r" for i in range(len(col2)) ] sgs = gridspec.GridSpecFromSubplotSpec(5,3, subplot_spec=gs, wspace=0.05, hspace=0, width_ratios=[0.9,0.7,2]) axes = [] for n in range(5): for m in range(3): axes.append(fig.add_subplot(sgs[n,m])) axes = np.array(axes).reshape(5,3) for ax in axes.flatten(): ax.tick_params(labelbottom=0, labelleft=0, b…
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84303290
has comment: http://stackoverflow.com/comment/82864411
downvote count: 0
has comment: http://stackoverflow.com/comment/82760463
has comment: http://stackoverflow.com/comment/82798115

http://stackoverflow.com/q/47755522
has answer: http://stackoverflow.com/a/47757354
score: -6
has comment: http://stackoverflow.com/comment/82475712
favorite count: 0
type: Question
tagged with: python-3.x
has body: my code runs perfectly but when i add in tick intervals onto the hscale the code crashes here is my code: import tkinter def main() : test_window = tkinter.Tk() test_window.wm_title("My Window") test_label = tkinter.Label(test_window, text="please enter bill amount:") test_entry = tkinter.Entry(test_window, width=10) test_label2 = tkinter.Label(test_window, text="tip amount by percent(%):") hscale = tkinter.Scale(test_window, from_=0, to=50, tickintervals=10, orient="horizontal") hscale.set(30) test_label.pack(side="top") test_entry.pack(side="top") test_label2.pack() hscale.pack() tkinter.mainloop() main()
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82475431
has comment: http://stackoverflow.com/comment/82472472
tagged with: python
has comment: http://stackoverflow.com/comment/82475579
has comment: http://stackoverflow.com/comment/82475388
downvote count: 6
has title: why won't my gui scale include tick intervals
tagged with: tkinter
upvote count: 0
has comment: http://stackoverflow.com/comment/82475647
answer count: 1

http://stackoverflow.com/q/47754354
type: UnansweredQuestion
tagged with: python
has body: I am trying to multithread a function that takes a lot of time when executed iteratively. A simplifier version would be: from multiprocessing import Process, Manager def f(my_dict, key, list1, list2): count = [0] * len(list1) for i, val1 in enumerate(list1): count[i] = sum(belongs_to(val1, val2) for val2 in list2) my_dict[key] = (sum(count)) manager = Manager() my_dict = manager.dict() job = [Process(target=f, args=(my_dict, record, value, list2)) for record, value in other_dict.items()] _ = [p.start() for p in job] _ = [p.join() for p in job] my_dict = {key: value for key, value in my_dict.items()} When I run this code, my memory is overrun. Is there any easy way to limit the number of threads at the same time ? Also, I am sharing the dictionary receiving the answers between all the threads thanks to Manager. Is there any way to share the lists given to the function f, as list2 is always the same ?
tagged with: dictionary
has comment: http://stackoverflow.com/comment/82469954
has comment: http://stackoverflow.com/comment/82473308
linked to: http://stackoverflow.com/q/11515944
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/82469675
answer count: 0
downvote count: 0
tagged with: multithreading
has title: python mutlthreading + limited number of process with lists and dictionaries
favorite count: 0
has comment: http://stackoverflow.com/comment/82470779
type: Question

http://stackoverflow.com/q/47774699
tagged with: cython
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/82510737
tagged with: python-3.x
type: Question
tagged with: pyinstaller
has body: I have recently switched to a windows OS but file is not being found with cython. The file seems correct. I run: CD C:\Users\Django\example-of-cython-pyinstaller-and-subzero\1 ACTUAL PROJECT `python setup.py build_ext --inplace` and get `No such file or directory` I get: C:\Users\Django\ee\123&gt;python setup.py build_ext --inplace running build_ext building 'myapp.cython_module' extension C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.12.25827\bin\HostX86\x64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -IC:\Users\Django\AppData\Local\Continuum\miniconda3\include -IC:\Users\Django\AppData\Local\Continuum\miniconda3\include "-IC:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.12.25827\ATLMFC\include" "-IC:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.12.25827\include" "-IC:\Program Files (x86)\Windows Kits\NETFXSDK\4.6.1\include\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.16299.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.16299.0\shared" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.16299.0\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.16299.0\winrt" /Tcmyapp/cython_module.c /Fobuild\temp.win-amd64-3.6\Release\myapp/cython_module.obj cython_module.c c1: fatal error C1083: Cannot open source file: 'myapp/cython_module.c': No such file or directory C:\Users\Django\example-of-cython-pyinstaller-and-subzero\1 ACTUAL PROJECT\myapp setup.py from setuptools import find_packages, Extension from distutils.core import setup from distutils.core import setup from setuptools import find_packages, Extension from setuptools import setup, Extension setup( name='myapp', ext_modules=[ Extension('myapp.cython_module', ['myapp/cython_module.pyx']) ], ) enter image
type: UnansweredQuestion
tagged with: python
has title: Creating a cython file: No such file or directory
upvote count: 4
has comment: http://stackoverflow.com/comment/82510701
has comment: http://stackoverflow.com/comment/82510342
has comment: http://stackoverflow.com/comment/82510816
score: 3
has comment: http://stackoverflow.com/comment/82510438
has comment: http://stackoverflow.com/comment/82510361
answer count: 0

http://stackoverflow.com/q/47764902
has comment: http://stackoverflow.com/comment/82612556
has comment: http://stackoverflow.com/comment/82609754
has comment: http://stackoverflow.com/comment/82609677
has comment: http://stackoverflow.com/comment/82575872
has comment: http://stackoverflow.com/comment/82491151
has title: Why am I not using all of the memory in spark?
has comment: http://stackoverflow.com/comment/82611169
tagged with: apache-spark
has comment: http://stackoverflow.com/comment/82491175
score: 1
linked to: http://stackoverflow.com/q/43152126
has comment: http://stackoverflow.com/comment/82609537
has comment: http://stackoverflow.com/comment/82592401
has comment: http://stackoverflow.com/comment/82633116
has comment: http://stackoverflow.com/comment/82608906
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82509232
has comment: http://stackoverflow.com/comment/82602636
tagged with: apache-spark-sql
answer count: 0
has body: I am wondering why my jobs are running very slowly, and it appears to be because I am not using all of the memory available in PySpark. When I go to the spark UI, and I click on "Executors" I see the following memory used: And when I look at my executors I see the following table: I am wondering why the "Used" memory is so small compared to the "Total memory. What can I do to use as much of the memory as possible? Other information: I have a small broadcasted table, but it is only 1MB in size. It should be replicated once per each executor, so I do not imagine it would affect this that much. I am using spark managed by yarn I am using spark 1.6.1 Config settings are: spark.executor.memory=45g spark.executor.cores=2 spark.executor.instances=4 spark.sql.broadcastTimeout = 9000 spark.memory.fraction = 0.6 The dataset I am processing has 8397 rows, and 80 partitions. I am not doing any shuffle operations aside from the repartitioning initially to 80 partitions. It is the part when I am adding columns that this becomes slow. All of the parts before that seem to be reasonably fast, when when I try to add a column using a custom udf (using withColumn) it seems to be slowing in that part. There is a similar question here: How can I tell if my spark job is progressing? But my question is more pointed - why does the "Memory Used" show a number so low? Thanks.
has comment: http://stackoverflow.com/comment/82576586
type: UnansweredQuestion
downvote count: 0
tagged with: pyspark
has comment: http://stackoverflow.com/comment/82611888
upvote count: 1
tagged with: python

http://stackoverflow.com/comment/82535760
comment on: http://stackoverflow.com/q/47781571
type: QuestionComment
has text: *"pops out a window or a line"* - I do not see how your code can popup a window or a line. Your code does not do anything apart from starting the command.
score: 0
type: Comment

http://stackoverflow.com/q/47806573
upvote count: 1
tagged with: http://stackoverflow.com/tag/pdf
downvote count: 1
has answer: http://stackoverflow.com/a/47807303
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47807595
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47807294
has body: i have a python script that convert pdf file to text file. the system ask the user to the path of the folder that contains the PDF files. the problem is that the script just convert one file , what need is to make the script convert all the PDF files that exist in the specified directory. the script list all the existing files in the specified directory but it convert all the files excluding last file result after increment the i code: import os from os import chdir, getcwd, listdir, path import codecs import pyPdf from time import strftime def check_path(prompt): ''' (str) -&gt; str Verifies if the provided absolute path does exist. ''' abs_path = raw_input(prompt) while path.exists(abs_path) != True: print "\nThe specified path does not exist.\n" abs_path = raw_input(prompt) return abs_path print "\n" folder = check_path("Provide absolute path for the folder: ") list=[] directory=folder for root,dirs,files in os.walk(directory): for filename in files: if filename.endswith('.pdf'): t=os.path.join(directory,filename) list.append(t) m=len(list) i=0 while i&lt;=len(list): path=list[i] head,tail=os.path.split(path) var="\\" tail=tail.replace(".pdf",".txt") name=head+var+tail content = "" # Load PDF into pyPDF pdf = pyPdf.PdfFileReader(file(path, "rb")) # Iterate pages for j in range(0, pdf.getNumPages()): # Extract text from page and add to content content += pdf.getPage(j).extractText() + "\n" print strftime("%H:%M:%S"), " pdf -&gt; txt " f=open(name,'w') f.write(content.encode('UTF-8')) f.close i+=1
tagged with: python
has title: how to convert multiple files from pdf to text files using python
tagged with: list
score: 0
tagged with: while-loop
answer count: 3

http://stackoverflow.com/comment/82624987
type: AnswerComment
has text: Also, an ideal answer would include an explanation of what's going on behind the scenes (what happens in each job, and why there are so many jobs).
score: 1
comment on: http://stackoverflow.com/a/47829210
type: Comment

http://stackoverflow.com/q/47771364
answer count: 0
score: 1
upvote count: 1
tagged with: jupyter-notebook
favorite count: 0
type: Question
tagged with: python-3.x
has title: 2x ModuleNotFoundError Jupyter notebook
type: UnansweredQuestion
downvote count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/82504265
has comment: http://stackoverflow.com/comment/82504218
has body: While attempting to run jupyter notebook in python3.6.3 on my gnome terminal I get the following output, running on UBUNTU: Traceback (most recent call last): File "/home/willem/.local/lib/python3.6/site-packages/notebook/services/sessions/sessionmanager.py", line 10, in &lt;module&gt; import sqlite3 File "/usr/local/lib/python3.6/sqlite3/__init__.py", line 23, in &lt;module&gt; from sqlite3.dbapi2 import * File "/usr/local/lib/python3.6/sqlite3/dbapi2.py", line 27, in &lt;module&gt; from _sqlite3 import * ModuleNotFoundError: No module named '_sqlite3' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/willem/.local/bin/jupyter-notebook", line 7, in &lt;module&gt; from notebook.notebookapp import main File "/home/willem/.local/lib/python3.6/site-packages/notebook/notebookapp.py", line 81, in &lt;module&gt; from .services.sessions.sessionmanager import SessionManager File "/home/willem/.local/lib/python3.6/site-packages/notebook/services/sessions/sessionmanager.py", line 13, in &lt;module&gt; from pysqlite2 import dbapi2 as sqlite3 ModuleNotFoundError: No module named 'pysqlite2' However, the module sqlite3 is present in my python3.6.3 directory. Which makes the problem rather vague. Any suggestions for this problem to be fixed will be greatly appreciated

http://stackoverflow.com/q/47840267
type: AnsweredQuestion
upvote count: 0
has body: I have 6 different data lists a[], b[], c[], d[], e[], f[]. How would I go about encoding this into a JSON format so it reads like this: { "date":a[0] { "value1":b[0] "value2":c[0] "value3":d[0] "value4":e[0] "value5":f[0] } "date":a[1] { "value1":b[1] "value2":c[1] "value3":d[1] "value4":e[1] "value5":f[1] } }
has answer: http://stackoverflow.com/a/47840838
has comment: http://stackoverflow.com/comment/82645798
tagged with: http://stackoverflow.com/tag/json
downvote count: 2
answer count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82644911
has comment: http://stackoverflow.com/comment/82644723
accepted answer: http://stackoverflow.com/a/47840838
tagged with: encoding
score: -2
tagged with: python
has comment: http://stackoverflow.com/comment/82645769
has title: How would I encode this is JSON format (multiple lists)

http://stackoverflow.com/comment/82507692
score: 0
type: Comment
type: QuestionComment
has text: You mean sending `attr1, attr2, attr3` to the super class constructor?
comment on: http://stackoverflow.com/q/47773427

http://stackoverflow.com/a/47838451
accepted answer of: http://stackoverflow.com/q/47837880
upvote count: 3
downvote count: 0
answers question: http://stackoverflow.com/q/47837880
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82644298
has comment: http://stackoverflow.com/comment/107041559
has comment: http://stackoverflow.com/comment/82644414
score: 3
has body: You are training your network on your entire train set, which is too big to fit in memory, and too large for your gpu. The standard in machine learning is to create small batches of your data and train on those. Batch sizes are usually 16, 32, 64 or some other power of two, but it can be anything, you usually have to find the correct batch size through cross validation.
type: Answer

http://stackoverflow.com/q/47806693
answer count: 2
has answer: http://stackoverflow.com/a/47806733
has body: I am trying to identify time instances using Python regex eg "2.30pm", "1.45 am", "3.30" (Provided am/pm is not given). Following is the regex I wrote: '\d{1,2}\.\d{1,2}[\s]?[am,pm]?' Output I am getting: 2.30p Output I need: 2.30pm Also, I would like it to capture string such as "2.30 pmo" as just "2.30" instead of "2.30 pm". Can someone please help me with the same?
upvote count: 0
has answer: http://stackoverflow.com/a/47806938
downvote count: 1
type: AnsweredQuestion
has title: Regex Match in Python for Time Instances
possible better answer: http://stackoverflow.com/a/47806938
tagged with: python
score: -1
tagged with: regex
favorite count: 0
accepted answer: http://stackoverflow.com/a/47806733
type: Question
tagged with: python-3.x

http://stackoverflow.com/comment/82694731
comment on: http://stackoverflow.com/q/47849529
type: QuestionComment
has text: See https://stackoverflow.com/a/36116237/.
type: Comment
score: 2

http://stackoverflow.com/q/47766107
type: Question
answer count: 0
has comment: http://stackoverflow.com/comment/82649569
tagged with: homebrew
type: UnansweredQuestion
tagged with: syntaxnet
score: 0
has body: MacOS High Sierra. After compilation, syntaxnet works properly on this sentence: echo "This took a long time" | syntaxnet/demo.sh But it crashes python on this sentence: echo "This took a long time" | syntaxnet/demo.sh --conll The crash log file shows that one thread was processing the conll converter and died. The most relevant lines from the apple crash report are: Thread 11 Crashed: 0 libsystem_kernel.dylib 0x00007fff7d102fce __pthread_kill + 10 1 libsystem_pthread.dylib 0x00007fff7d240150 pthread_kill + 333 2 libsystem_c.dylib 0x00007fff7d05f30a abort + 127 3 _pywrap_tensorflow_internal.so 0x000000011267edc0 tensorflow::internal::LogMessageFatal::~LogMessageFatal() + 32 4 _pywrap_tensorflow_internal.so 0x000000011267edd0 tensorflow::internal::LogMessageFatal::~LogMessageFatal() + 16 5 parser_ops.so 0x0000000118d87468 syntaxnet::CoNLLSyntaxFormat::ConvertFromString(std::__1::basic_string&lt;char, std::__1::char_traits&lt;char&gt;, std::__1::allocator&lt;char&gt; &gt; const&amp;, std::__1::basic_string&lt;char, std::__1::char_traits&lt;char&gt;, std::__1::allocator&lt;char&gt; &gt; const&amp;, std::__1::vector&lt;syntaxnet::Sentence*, std::__1::allocator&lt;syntaxnet::Sentence*&gt; &gt;*) + 2776 6 parser_ops.so 0x0000000118d7b740 syntaxnet::TextReader::Read() + 400 7 parser_ops.so 0x0000000118da6cfd syntaxnet::SentenceBatch::AdvanceSentence(int) + 61 8 parser_ops.so 0x0000000118d94a0f syntaxnet::BeamState::AdvanceSentence() + 63 9 parser_ops.so 0x0000000118d94876 syntaxnet::BeamState::Reset() + 38 10 parser_ops.so 0x0000000118d93ebd syntaxnet::BatchState::ResetBeams() + 189 11 parser_ops.so 0x0000000118d8fe55 syntaxnet::BeamParseReader::Compute(tensorflow::OpKernelContext*) + 69 12 _pywrap_tensorflow_internal.so 0x00000001123bf83c tensorflow::ThreadPoolDevice::Compute(tensorflow::OpKernel*, tensorflow::OpKernelContext*) + 348 The entire apple crash log file is below. The script used to try to compile syntaxnet in a regular controllable way on Mac is below. The out…
has title: UPDATE syntaxnet -- error in parser re syntaxnet::CoNLLSyntaxFormat::ConvertFromString (originally "Help build actual instructions")
tagged with: python
has comment: http://stackoverflow.com/comment/82647167
tagged with: macos
tagged with: nlp

http://stackoverflow.com/q/47728789
tagged with: debugging
answer count: 2
upvote count: 9
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47943547
downvote count: 0
possible better answer: http://stackoverflow.com/a/48007912
has title: Python debugger pdb not found on macOS High Sierra
has body: The PythonDebuggingTools documentation says that the Python debugger pdb is "part of all Python installations", yet I can't find it under macOS High Sierra: pdb: command not found Is it supposed to be installed as normal part of macOS these days?
has answer: http://stackoverflow.com/a/48007912
accepted answer: http://stackoverflow.com/a/47943547
favorite count: 0
score: 9
tagged with: macos-high-sierra
type: Question

http://stackoverflow.com/comment/82472109
comment on: http://stackoverflow.com/a/47753703
type: Comment
score: 0
has text: i fix it this line but now i got another error: **Traceback (most recent call last): File "C:\Users\test\Downloads\pdf-txt\text maker.py", line 33, in <module> path=list[i] IndexError: list index out of range >>> **
type: AnswerComment

http://stackoverflow.com/comment/82468729
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47753932
has text: The results automatically gets update with the place I live in not with the search I'm after @Bryan Oakley. That Is what i tried to mean.

http://stackoverflow.com/comment/82518670
comment on: http://stackoverflow.com/a/47778590
score: 0
type: Comment
has text: Im trying to get this to work in spacy version 2.0.5. I previously had it working in an earlier version,but now I need it to work in 2.0.5 And I have installed the english vocab with from spacy.lang.en import English -- Thanks so much for helping me by the way!
type: AnswerComment

http://stackoverflow.com/a/49488237
answers question: http://stackoverflow.com/q/47764527
score: 19
has comment: http://stackoverflow.com/comment/98940726
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/140154774
has body: Untick the option to install for all users ... that sorted it for me :)
accepted answer of: http://stackoverflow.com/q/47764527
type: Answer
upvote count: 19

http://stackoverflow.com/a/47797230
answers question: http://stackoverflow.com/q/47797150
type: Answer
score: 0
has body: You can do: import numpy as np Y['b'] = np.nan merged = X.join(Y, lsuffix="_X", rsuffix="_Y") merged['sum_a'] = merged['a_X'] + merged['a_Y'] merged['sum_b'] = merged['b_X'] + merged.fillna(0)['b_Y'] #&gt;&gt;&gt; merged # a_X b_X a_Y b_Y sum_a sum_b #0 1 2 10 NaN 11 2.0 #1 3 4 20 NaN 23 4.0 #2 5 6 30 NaN 35 6.0

http://stackoverflow.com/q/47755025
has comment: http://stackoverflow.com/comment/82470711
has body: I have a function like this: def test_readout(self, nr_triggers=10, dump_data=False, lanes=range(9)): Which is to be called by command line using the fire python module, via a master file called testbench.py. I want to set the parameter lanes to an array with a single value, 8 specifically. The closest I've gotten is this: mypython3 ./testbench.py test_readout 10 False [8,8] This works, but as you can see the array has two duplicate entries for 8 instead of just one. But if I just do: mypython3 ./testbench.py test_readout 10 False [8] Then I get this error: [...] File "./testbench.py", line 323, in test_readout [trig == nr_triggers for trig in event_counters]) TypeError: 'int' object is not iterable Other strategies like leaving the other parameters at default and setting lanes explicitly like: mypython3 ./testbench.py test_readout --lanes [8] Gives this kind of error: [...] File "./testbench.py", line 306, in test_readout for i in range(nr_triggers): TypeError: 'str' object cannot be interpreted as an integer Anyone know the correct way of doing this?
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: python-fire
answer count: 0
upvote count: 2
has title: Passing array with single member with python fire module
type: UnansweredQuestion
tagged with: arrays
downvote count: 0
tagged with: python
score: 2

http://stackoverflow.com/a/47780985
has comment: http://stackoverflow.com/comment/82523364
has body: What you're thinking of there is a while loop. Instead of checking for x = 'A' or x = 'a', you might try testing for whether x isn't 'A' or 'a'. Try this: while (x != 'A' and x != 'a'): print('That is an incorrect response. Please try again.' + '\n' + '\n' + Number_One + '\n') print(answer_1_choices['A'] + '\n' + '\n' + answer_1_choices['B'] + '\n' + '\n' + answer_1_choices['C']) x = input('\n' + 'Is the answer A, B, or C? Type the letter of your choice.') print('Correct!') This way, it will only print "Correct!" once the breaking condition has been satisfied.
has comment: http://stackoverflow.com/comment/82523415
has comment: http://stackoverflow.com/comment/82524840
type: Answer
accepted answer of: http://stackoverflow.com/q/47780918
answers question: http://stackoverflow.com/q/47780918
score: 7
type: AcceptedAnswer
downvote count: 0
upvote count: 7

http://stackoverflow.com/q/47842283
downvote count: 0
tagged with: loops
upvote count: 1
has answer: http://stackoverflow.com/a/47842327
has comment: http://stackoverflow.com/comment/82648883
has comment: http://stackoverflow.com/comment/82648758
has answer: http://stackoverflow.com/a/47842529
favorite count: 0
possible better answer: http://stackoverflow.com/a/47842529
type: Question
has comment: http://stackoverflow.com/comment/82648847
has comment: http://stackoverflow.com/comment/82648818
has comment: http://stackoverflow.com/comment/82648928
has comment: http://stackoverflow.com/comment/82648990
has comment: http://stackoverflow.com/comment/82648740
has title: Cannot access parent for loop from nested for loop
has comment: http://stackoverflow.com/comment/82648743
tagged with: python
has comment: http://stackoverflow.com/comment/82649062
has comment: http://stackoverflow.com/comment/82648781
has comment: http://stackoverflow.com/comment/82648750
tagged with: scope
type: AnsweredQuestion
tagged with: python-2.7
has body: I'm trying to compare the value of an index between two arrays of dictionaries. To accomplish this I'm using a nested for loop. While the loops are iterating properly there is a problem where firstDataSetNumber is not iterating inside of the nested for loop (indicated by the second print statement). The first print statement shows that the for loop is iterating properly. What might be causing the value printed from the second firstDataSetNumberwithin the nested for loop to never change, even though it's value in the first print statement shows that it is indeed iterating properly? def processCommandCenterFile(data): firstDataSet = data["FirstDataSet"] secondDataSet = data["SecondDataSet"] # Go through every First Data Set Record for firstDataSetRecord in firstDataSet: firstDataSetNumber = firstDataSetRecord["KeyOne"].strip() matchingSecondDataSetRecord = None print(firstDataSetNumber) # Always iterates properly throughout the application # Find the Second Data Set record with the KeyTwo number for secondDataSetRecord in secondDataSet: print(firstDataSetNumber) # Never iterates past the first value if secondDataSetRecord["KeyTwo"].strip() == firstDataSetNumber: matchingSecondDataSetRecord = secondDataSetRecord data = { "FirstDataSet": CsvToDictionary("first_data_set.csv"), "SecondDataSet": CsvToDictionary("second_data_set.csv") } processCommandCenterFile(data) I'm expecting the output from both print statements to be the same. However when I run it the first print statement is each item in the index, however the data from the second print statement is stuck on the first item in the list. The FirstDataSet and SecondDataSet keys store the output of the following function, which loads a CSV and converts it to a dictionary with headers from the CSV as keys. import csv def CsvToDictionary(path): file = open(path, 'r') rawCsvArray = csv.reader(file, delimiter=',', quotechar='|') headers = rawCsvArray.next() dataDictionary = csv.DictReader(file, fieldnames=headers) return d…
answer count: 3
has answer: http://stackoverflow.com/a/47842465
score: 1
accepted answer: http://stackoverflow.com/a/47842465

http://stackoverflow.com/q/47797895
tagged with: python
tagged with: magento-rest-api
answer count: 0
has title: Magento 2 Rest API youtube video missing values
has body: I have simple question regarding the Magento V1 media API. I'm trying to add a video to a product but it keeps telling me that is missing values. I'm trying to add the data from Odoo (python) like this: videoFile = { "entry": { 'position': position, 'media_type': 'external-video', 'disabled': False, 'label': 'Holassss', 'types': ['image', 'small-image', 'thumbnail'], 'content': { 'base64_encoded_data': base64.b64encode(urllib.request.urlopen("https://img.youtube.com/vi/axwE9q7llEQ/0.jpg").read()).decode('ascii'), 'type': 'image/jpeg', 'name': '0.jpg' }, 'extension_attributes': { 'video_content': { 'media_type': 'external-video', 'video_provider': 'youtube', 'video_url': 'https://www.youtube.com/watch?v=axwE9q7llEQ', 'video_title': 'Titulo', 'video_description': 'Description', 'video_metadata': None, } } } } cc = json.dumps(videoFile) productUrl = url + "/index.php/rest/V1/products/" + productSku + "/media" Eventually I'll add the content using the https://www.youtube.com/oembed?url=youtubeurl&amp;format=json response. I'm following the API documentation (http://devdocs.magento.com/swagger/index_20.html) for catalogProductAttributeMediaGalleryManagementV1 (/V1/products/{sku}/media) Error: "message": "Option values that are not specified." Please advice me on which values I'm missing and which I can leave NULL. Also let me know if there is a way to let Magento automatically get the description and other data (as on the admin panel) instead of providing it myself. last but not least, I think this documentation is missing some data. This already happened to me before with a different call and a couple of "optional" values were actually required. Is there another documentation web page? Thank you very much.
type: UnansweredQuestion
downvote count: 0
upvote count: 1
tagged with: youtube
has comment: http://stackoverflow.com/comment/138757220
favorite count: 0
type: Question
score: 1
tagged with: magento2

http://stackoverflow.com/a/47736996
has comment: http://stackoverflow.com/comment/82435611
has comment: http://stackoverflow.com/comment/82447964
answers question: http://stackoverflow.com/q/47736932
type: Answer
accepted answer of: http://stackoverflow.com/q/47736932
score: 0
has comment: http://stackoverflow.com/comment/82481468
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82434638
has body: This is the most iconic example of multithreading usage. import threading import urllib2 import time start = time.time() urls = ["http://www.google.com", "http://www.apple.com", "http://www.microsoft.com", "http://www.amazon.com", "http://www.facebook.com"] def fetch_url(url): urlHandler = urllib2.urlopen(url) html = urlHandler.read() print "'%s\' fetched in %ss" % (url, (time.time() - start)) threads = [threading.Thread(target=fetch_url, args=(url,)) for url in urls] for thread in threads: thread.start() for thread in threads: thread.join() But you should be aware that you can easily be banned by the service for big amount of simultaneous requests

http://stackoverflow.com/comment/83033918
comment on: http://stackoverflow.com/a/47952667
type: Comment
score: 0
type: AnswerComment
has text: I didn't publish a precompiled package for libpruw1 yet, so you'll have to go through the "M" labeled steps, in order to compile your binary.

http://stackoverflow.com/q/47772773
type: UnansweredQuestion
downvote count: 0
tagged with: python
tagged with: systemd
has title: Systemd service - Python script inside Screen on boot
score: 1
answer count: 1
tagged with: gnu-screen
upvote count: 1
has answer: http://stackoverflow.com/a/49208802
favorite count: 0
type: Question
tagged with: linux
has body: Im currently running a python script inside a Screen session through this script in rc.local: screen -L -dmS pi python /home/pi/truck/main2.py &amp; But I would like it to run through systemd so I can restart it if the Python script crashes. I tried creating a service in /systemd/system/myscript.service [Unit] Description=myscript After=network.target [Service] Type=simple Restart=on-failure RestartSec=3 ExecStart=/usr/bin/screen -L -dmS pi python /home/pi/truck/main2.py [Install] WantedBy=multi-user.target But it wont run my script inside the Screen session? If I get a list of running screens it shows that the screen session "pi" is dead.

http://stackoverflow.com/comment/82562372
type: QuestionComment
has text: One explanation of the error is _-23101: Unable to load locale categories. — An invalid locale name was supplied for the locale initialization. The environment variable specifying the locale category has a wrong value. — Check the value of the corresponding environment variable, CLIENT_LOCALE or DB_LOCALE._ . It can also mean that INFORMIXDIR is not set correctly — the `$INFORMIXDIR/gls` directory does not contain the right information.
comment on: http://stackoverflow.com/q/47790988
score: 1
type: Comment

http://stackoverflow.com/q/47789326
has comment: http://stackoverflow.com/comment/82541702
has comment: http://stackoverflow.com/comment/82541451
tagged with: symlink
has comment: http://stackoverflow.com/comment/82539822
answer count: 0
has comment: http://stackoverflow.com/comment/82539727
downvote count: 0
upvote count: 1
type: UnansweredQuestion
has body: Once upon a time long long ago I had an epiphany. In the course of my job I create several more or less temporary files per day. Some of them would be useful to store for longer, some not. Because of the amount of these files, I thought that organizing them into folders per day would be a nice thing. So I created a scheduled task that would run a script every night that would create a new folder for each workday and remove old ones if they were empty. That was fine for some time, but then I started wondering that it'd be mighty convenient if I could access todays folder via some shortcut, like C:\today or something like that. And down the rabbit hole we go... So I modified my script to create a NTFS symlink (yes, such a thing exists!) from C:\today to, for example, C:\Users\&lt;me&gt;\Documents\dayfolders\2017-12-01\ Now, when I leave work, I don't meticulously close every file in every program that I happened to use (so that next morning I can pick up where I left off). This interferes with my fancy symlinking, because I cannot delete the symlink when something still uses it. So, I thought, I'd rename the symlink to a temporary thing in the temp dir and create a NEW one with the old name instead. This strategy only works for the first time (or two). Up till now I've just lived with it, however I still feel that there MAY be a way out! If anybody can help me, please do! :) So, the code of my scheduled task (Python 3) : if __name__ == '__main__': # some setup tasks here for logging, loading conf etc basepath = getbasepath(conf) cleanupolddirs(basepath) newdir = createnewdir(basepath) relink(conf, newdir) # post-run cleanup tasks here and from top down, the rest of the relevant functions: def getbasepath(config): basepath_ = config['General']['BasePath'] if (len(basepath_) == 0) or (not os.path.exists(basepath_)): basepathmsg = "Error with base path. Provided path was: %s" % str(basepath_) logging.fatal(basepathmsg) logging.shutdown() sys.exit(basepathmsg) return base…
has comment: http://stackoverflow.com/comment/82541812
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82541669
has comment: http://stackoverflow.com/comment/82541727
tagged with: ntfs
has comment: http://stackoverflow.com/comment/82543546
score: 1
tagged with: windows
has title: Manipulate NTFS symlinks that may be in use
tagged with: python
has comment: http://stackoverflow.com/comment/82647493

http://stackoverflow.com/comment/82527019
has text: Sorry for my silly question. Really my brain stuck now :)
score: 0
comment on: http://stackoverflow.com/q/47782780
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82570815
score: 0
has text: @sascha I want a sparse matrix where the non-zero values follow a -0.5,0.5 uniform distribution.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47804632

http://stackoverflow.com/q/47735326
has title: Python Selenium -- Searching for a link but finding cards
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47737211
tagged with: selenium
has body: Using Python + Selenium to create a web crawler/scraper to notify me when new homework is posted. Managed to log into the main website, but you need to click a link to select your course. After searching through the HTML manually, I found this information about the link I usually click (The blue box is the link). However, no button that seems clickable. So I searched the page for the link I knew it should redirect me to, and I found this: It looks like a card, which is a new data structure/object for me. How can I use an automated web crawler to click this link?
downvote count: 1
favorite count: 0
type: Question
upvote count: 0
accepted answer: http://stackoverflow.com/a/47737211
answer count: 1
tagged with: python
score: -1

http://stackoverflow.com/a/47724011
has body: this worked. from django.db.models.functions import Concat from django.db.models import Value queryset = Employee.objects.annotate(fullname=Concat('first_name', Value(' '), 'last_name')) c = queryset.filter(fullname__icontains='michael jackson')
upvote count: 14
score: 14
downvote count: 0
answers question: http://stackoverflow.com/q/47723859
has comment: http://stackoverflow.com/comment/103884312
type: Answer

http://stackoverflow.com/q/47781434
has title: Label text changing when dictionary is updated
score: 0
tagged with: tkinter
answer count: 2
has answer: http://stackoverflow.com/a/47792996
has body: I'm new to coding and i've been messing around with tkinter. My labels have text, that is supposed to change when the dictionary values are updated. An example of my code: def setit(point, adic,number): adic[point] = adic[point]+number dict={'a':4,'b':8,'c':3} aa=Label(root,text=dict['a']).pack() bb=Label(root,text=dict['b']).pack() cc=Label(root,text=dict['c']).pack() Button(command=setit('a',dict,3)).pack() When the button is pressed i want both the dictionary and the appropriate Label to update. How would you do that? Preferably without OOP. Thanks!
has answer: http://stackoverflow.com/a/47781604
type: Question
tagged with: python-3.x
linked to: http://stackoverflow.com/q/47334885
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/82580735
comment on: http://stackoverflow.com/a/47803899
has text: You need to define a function before be able to call it. You're defining it, and that's ok, it's what the function does, but you're never calling it, so it's useless.
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/82604273
has text: Usually such errors come from a discrepancy between the matplotlib version and some other dependency. E.g. if you install a binary wheel for 64bit system on python 32bit or so. Maybe you can check if you ran into such a situation here.
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47820905

http://stackoverflow.com/comment/82556237
comment on: http://stackoverflow.com/q/47797723
has text: perhaps `data[data["TX"] == data["TX"].max()]["DATE"]`
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47821174
has answer: http://stackoverflow.com/a/47821413
has comment: http://stackoverflow.com/comment/82605513
tagged with: opencv
has comment: http://stackoverflow.com/comment/82607001
has body: I am trying to install OpenCV on my Ubuntu 14.04. I have Python 2.7 in usr/bin/python2.7. I am trying to compile OpenCV to use my miniconda python 3.6 interpreter, but it always installs on my python 2.7 interpreter. I don't know how to fix this. Here is the guide I am following. These are the cmake commands I run: cmake -D CMAKE_BUILD_TYPE=RELEASE \ -D CMAKE_INSTALL_PREFIX=/usr/local \ -D INSTALL_C_EXAMPLES=ON \ -D INSTALL_PYTHON_EXAMPLES=ON \ -D OPENCV_EXTRA_MODULES_PATH=~/opencv_contrib/modules \ -D BUILD_EXAMPLES=ON -D PYTHON_DEFAULT_EXECUTABLE=$(which python3) .. And this is the relevant output I am getting when I run it: -- GUI: -- QT: NO -- GTK+ 3.x: YES (ver 3.10.8) -- GThread : YES (ver 2.40.2) -- GtkGlExt: NO -- OpenGL support: NO -- VTK support: NO -- -- Media I/O: -- ZLib: /usr/lib/x86_64-linux-gnu/libz.so (ver 1.2.8) -- JPEG: /usr/lib/x86_64-linux-gnu/libjpeg.so (ver ) -- WEBP: build (ver 0.3.1) -- PNG: /usr/lib/x86_64-linux-gnu/libpng.so (ver 1.2.50) -- TIFF: build (ver 42 - 4.0.2) -- JPEG 2000: /usr/lib/x86_64-linux-gnu/libjasper.so (ver 1.900.1) -- OpenEXR: /usr/lib/x86_64-linux-gnu/libImath.so /usr/lib/x86_64-linux-gnu/libIlmImf.so /usr/lib/x86_64-linux-gnu/libIex.so /usr/lib/x86_64-linux-gnu/libHalf.so /usr/lib/x86_64-linux-gnu/libIlmThread.so (ver 1.6.1) -- GDAL: NO -- -- Video I/O: -- DC1394 1.x: NO -- DC1394 2.x: YES (ver 2.2.1) -- FFMPEG: YES -- codec: YES (ver 54.35.1) -- format: YES (ver 54.20.4) -- util: YES (ver 52.3.0) -- swscale: YES (ver 2.1.1) -- resample: YES (ver 1.0.1) -- gentoo-style: YES -- GStreamer: -- base: YES (ver 1.2.4) -- video: YES (ver 1.2.4) -- app: YES (ver 1.2.4) -- riff: YES (ver 1.2.4) -- pbutils: YES (ver 1.2.4) -- OpenNI: NO -- OpenNI PrimeSensor Modules: NO -- OpenNI2: NO -- PvAPI: NO -- GigEVisionSDK: NO -- UniCap: NO -- UniCap ucil: NO -- V4L/V4L2: Using libv4l1 (ver 1.0.1) / libv4l2 (ver 1.0.1) -- XIMEA: NO -- Xine: NO -- gPhoto2: NO -- -- Other third-party libraries: -- Use IPP: 8.2.1 [8.2.1] -- at: /home/tex/o…
answer count: 1
upvote count: 1
score: 1
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/29249611
has title: Installing OpenCV with miniconda while Python 2.7 exists
type: UnansweredQuestion
downvote count: 0
tagged with: python
tagged with: ubuntu
duplicate of: http://stackoverflow.com/q/23119413

http://stackoverflow.com/q/47840056
tagged with: machine-learning
tagged with: python
accepted answer: http://stackoverflow.com/a/47841495
has title: choosing random_State parameter in TSNE (python)
has answer: http://stackoverflow.com/a/47841495
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82644419
answer count: 1
downvote count: 0
has body: I have two questions, I am trying to plot my data with bh_sne library, however as the nature of this algorithm is based on random number in each run I have a different result. I would like to get the same result at each run. it seems that random_state is helpful. But I do not know what exactly does it mean, by choosing different integer number for random_state. For example what is the different between random_state=0 and random_state=1 or random_state=42 .. and random_state=None Second, when I applied this parameter in my function and by giving any values except None I got the following error. AttributeError: 'int' object has no attribute 'randint' I do not have any files that named as random in my pycharm. this is my code: data = bh_sne(X, random_state =1 ) X contains my features values.
has comment: http://stackoverflow.com/comment/82644446
favorite count: 0
type: Question
upvote count: 2

http://stackoverflow.com/comment/82654952
type: Comment
comment on: http://stackoverflow.com/q/47842829
type: QuestionComment
score: 0
has text: HPC system is simply a pool of hardware, isn't it? If so, you'd have to talk to the admins if they use something atop that manages the pool of hardware resources, e.g. Mesos, DC/OS, YARN, Kubernetes. Spark supports them. You could also use [Spark Standalone](http://spark.apache.org/docs/latest/spark-standalone.html).

http://stackoverflow.com/q/47739988
tagged with: python
has answer: http://stackoverflow.com/a/47740332
has comment: http://stackoverflow.com/comment/82440226
type: AnsweredQuestion
upvote count: 0
downvote count: 3
has body: sorry, does anyone know why this program doesn't work? I'm very new to python (as you can see from my inefficient programming), and I can't think of any reason why this souldn't work. Please help. Thankyou! #Land Game Calculator game = 1 hamlet = 0 village = 0 town = 0 city = 0 capital = 0 palace = 0 farm = 0 factory = 0 ruins = 0 apolw = 0 apoll = 0 polw = 0 poll = 0 squaresused = hamlet+village+town+city+capital+palace+farm+factory+ruins+apolw+apoll+polw+poll income = hamlet+(village*2)+(town*3)+(city*4)+(capital*5)+(palace*6)+farm+(factory*3) while game == 1: if input("What would you like to do? ") == hamlet: hamlet = hamlet+(int(input("How many would you like to add? "))) print("There are now "+str(hamlet)+" of them") elif input("What would you like to do? ") == village: village = village+(int(input("How many would you like to add? "))) print("There are now "+str(village)+" of them") elif input("What would you like to do? ") == town: town = town+(int(input("How many would you like to add? "))) print("There are now "+str(village)+" of them")
has comment: http://stackoverflow.com/comment/82440359
accepted answer: http://stackoverflow.com/a/47740332
has title: I'm sorry to be so vague, but does anyone know why this doesn't work?
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/47740571
tagged with: python-3.x
answer count: 2
has answer: http://stackoverflow.com/a/47740571
has comment: http://stackoverflow.com/comment/82440251
score: -3

http://stackoverflow.com/q/47836499
accepted answer: http://stackoverflow.com/a/47836555
possible better answer: http://stackoverflow.com/a/47836618
has answer: http://stackoverflow.com/a/47836618
tagged with: jupyter-notebook
favorite count: 0
type: Question
has title: Get value in csv file in same row
answer count: 2
upvote count: 2
tagged with: python
has body: So given a csv file as a dataframe using pandas and python, i'd like to get the value which is in the same row as another value as efficiently as possible. To clarify this, i will give you an example with the following csv: STAID SOUID DATE TX Q_TX 162 100522 19010101 -31 0 162 100522 19010102 -13 0 162 100522 19010103 -5 0 162 100522 19010104 -10 0 162 100522 19010105 -18 0 So lets say im implementing te following code import pandas as pd data = pd.read_csv("foo.csv") max_val = data["TX"].max() Max_val will now get a value of -5. The thing is that I would now like to know the value in 'DATE' which will be in the same row as max_val, or in other words: a value in the column 'DATE' sharing the same index as the found value. The desired value that I'm aiming for is 19010103. What is the most efficient way to do this only using pandas?? UPDATE: Derped a bit with the min_val, it should obviously be max_val instead of min_val.
has answer: http://stackoverflow.com/a/47836555
score: 2
type: AnsweredQuestion
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
downvote count: 0

http://stackoverflow.com/q/47728148
score: 3
tagged with: python-2.7
tagged with: list
has answer: http://stackoverflow.com/a/47728185
answer count: 3
upvote count: 3
has title: Unpacking values from list in Python 2.7
has answer: http://stackoverflow.com/a/47728202
has answer: http://stackoverflow.com/a/47728263
has body: Python Newbie here: Given a list and a value, how can I unpack the list into separate objects and prepend a value. Length of the array isn't known, unlike in code below: x = [1,2,3,4] y = 0,x y Current Output: (0, [1, 2, 3, 4]) Desired Output: (0, 1, 2, 3, 4) I know it can be done easily in Python 3 using y = 0,*x but how can it be done in Python 2.7? Thanks
favorite count: 0
accepted answer: http://stackoverflow.com/a/47728185
type: Question
has comment: http://stackoverflow.com/comment/82416967
possible better answer: http://stackoverflow.com/a/47728202
downvote count: 0
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/82635895
comment on: http://stackoverflow.com/a/47836144
score: 0
type: Comment
has text: Good finding, I wonder why there is this difference between the `diff_for_humans()` and `in_words()`. Thanks!
type: AnswerComment

http://stackoverflow.com/a/60903525
type: Answer
has comment: http://stackoverflow.com/comment/107754797
answers question: http://stackoverflow.com/q/47842368
downvote count: 0
score: 1
upvote count: 1
has body: I encountered the same issue: I got it working by using different email addresses for login and sendmail (i.e. Login with gmail account and app password,then specify the forwarded email as sender in sendmail). For example: smtpObj.login('bob@gmail.com', 'bobsmistress123') smtpObj.sendmail('alias@bob.com', receiver, emailString)

http://stackoverflow.com/comment/82602668
type: QuestionComment
has text: Do you want to cope with all possible digits `0` to `9` and give empty lists for those with no matches?
score: 0
comment on: http://stackoverflow.com/q/47817992
type: Comment

http://stackoverflow.com/q/47702097
answer count: 0
tagged with: classification
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82385200
has comment: http://stackoverflow.com/comment/82414940
has comment: http://stackoverflow.com/comment/82376485
tagged with: scikit-learn
score: 0
tagged with: ensemble-learning
has body: I'm trying to replicate some previous work where an AdaBoost classifier was used for a two-class classification problem. There are 75 input dimensions but each weak learner exists in one dimension only. All of the input values lie in [0,1], and each weak classifier divides this interval into five sub-intervals: [0, 0.2], [0.2, 0.4], ... , [0.8, 1.0]. Within each sub-interval, the weak learner calculates the sum of the weights of all of the samples which have a label "+1", a, and the sum of the weights of all of the samples which have a label "-1", b. When we see a piece of test data, we check what sub-interval it falls into, and the weak learner in each dimension outputs 0.5log((a+epsilon)/(b+epsilon)) where epsilon &lt;&lt; a,b. AdaBoost is an iterative algorithm and for each set of sample weights, the algorithm needs to build a weak classifier as described above in every dimension. For each weak classifier we calculate:- Z = Sum over all sub-intervals of (Total Weight of +1 Labelled Points in this sub-interval * Total Weight of -1 Labelled Points in this sub-interval)^0.5 This value will be small when there is a big difference within each sub-interval of the total weights of each label i.e. when the weak classifier we have designed can discriminate well between +1 labels and -1 labels. The next weak classifier chosen to become part of the strong classifier is the weak classifier with the smallest value of Z for this set of sample weights. We then update the sample weights and choose a new best weak classifier. I think I can implement the basics of the weak classifier using the BaseEstimator: import numpy as np from sklearn.base import BaseEstimator from sklearn.utils.validation import check_X_y, check_array, check_is_fitted from sklearn.utils.multiclass import unique_labels from scipy import stats import matplotlib.pyplot as plt import math class QuantileMajorityClassifier(BaseEstimator): def __init__(self,demo_param='demo'): self.demo_param = demo_param def fit(s…
has comment: http://stackoverflow.com/comment/82401890
tagged with: adaboost
tagged with: python
type: Question
has title: AdaBoost in scikit-learn with 1D Weak Learners

http://stackoverflow.com/a/47734143
answers question: http://stackoverflow.com/q/47721334
has comment: http://stackoverflow.com/comment/82440160
has comment: http://stackoverflow.com/comment/82439327
has comment: http://stackoverflow.com/comment/82430171
type: Answer
accepted answer of: http://stackoverflow.com/q/47721334
has comment: http://stackoverflow.com/comment/82482841
score: 0
has body: Disclaimer: I can't run the question code. Among other things it is not complete, the extension declaration is missing. Also it seems to be Swift 2 code, this needs to be at least updated to Swift 3. encryption: cryptdata &lt;01b9f69b 45deb31d eda46c2d dc9ad9e8 00000000 00> Is completely wrong, it is even the wrong length Encrypted data will be a multiple of the block size. With PKCS#7 padding and CBC mode the encrypted result should be: C99A30D8DA44968418E8B66F42790216. See Cyyptomathic AES CALCULATOR. Note the 0b0b0b0b0b0b0b0b0b0b0b is the PKCS#7 padding. Here is an example in Swift 3, this is not production code, it is missing error handling at a minimum. func SHA256(string:String) -&gt; Data { let data = string.data(using:.utf8)! var hashData = Data(count: Int(CC_SHA256_DIGEST_LENGTH)) _ = hashData.withUnsafeMutableBytes {digestBytes in data.withUnsafeBytes {messageBytes in CC_SHA256(messageBytes, CC_LONG(data.count), digestBytes) } } return hashData } func aesCBCEncrypt(data:Data, keyData:Data, ivData:Data) -&gt; Data { let cryptLength = size_t(kCCBlockSizeAES128 + data.count + kCCBlockSizeAES128) var cryptData = Data(count:cryptLength) var numBytesEncrypted :size_t = 0 let cryptStatus = cryptData.withUnsafeMutableBytes {cryptBytes in data.withUnsafeBytes {dataBytes in keyData.withUnsafeBytes {keyBytes in ivData.withUnsafeBytes {ivBytes in CCCrypt(CCOperation(kCCEncrypt), CCAlgorithm(kCCAlgorithmAES), CCOptions(kCCOptionPKCS7Padding), keyBytes, keyData.count, ivBytes, dataBytes, data.count, cryptBytes, cryptLength, &amp;numBytesEncrypted) }}}} cryptData.count = (cryptStatus == kCCSuccess) ? numBytesEncrypted : 0 return cryptData; } let keyString = "sample_key" let keyData = SHA256(string:keyString) print("keyString: \(keyString)") print("keyData: \(hexEncode(keyData))") let clearData = hexDecode("68656c6c6f") // let keyData = hexDecode("d5a78c66e9b3ed40b3a92480c732527f1a919fdcf68957d2b7e9218f6221085d") let ivData = hexDecode("00000000000000000000000000000000") …
type: AcceptedAnswer

http://stackoverflow.com/comment/82619699
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47828666
has text: What are you trying to do? Return a string? Use `str.format`. `return '{} {}'.format(largest, smallest)`
score: 0

http://stackoverflow.com/comment/82606806
type: Comment
type: QuestionComment
score: 0
has text: What does `resolve1` return when you call `resolve1(doc.catalog)`?
comment on: http://stackoverflow.com/q/47821633

pygobject
type: Tag
tags question: http://stackoverflow.com/q/47761724
tag name: pygobject

http://stackoverflow.com/a/47760881
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47755363
downvote count: 0
answers question: http://stackoverflow.com/q/47755363
score: 1
upvote count: 1
type: Answer
has body: I would approach this by loading your counts into a Counter() object, using the tuple (title, api) as the key. This can then be converted back into an output dictionary, for example: Counter({('Product2', 'api4'): 8, ('Product2', 'api3'): 6, ('Product2', 'api2'): 4, ('Product1', 'api1'): 2, ('Product2', 'api1'): 2, ('Product3', 'api1'): 2}) This can be done as follows: from collections import Counter from itertools import groupby import json api_counts = Counter() def update_counters(json_filename): with open(json_filename) as f_json: for product in json.load(f_json): title = product['productTitle'] api_counts.update({(title, api) : count for api, count in product['api-activity'].items()}) update_counters('testa.json') update_counters('testb.json') output = [] for product, apis in groupby(sorted(api_counts.items()), lambda x: x[0][0]): api_activity = {} total_calls = 0 for (p, api), count in apis: api_activity[api] = count total_calls += count output.append({'productTitle': product, 'api-activity' : api_activity, 'totalCalls' : total_calls}) with open('outputMerge.json', 'w') as f_output: json.dump(output, f_output, indent=4) Giving you the following output: [ { "productTitle": "Product1", "api-activity": { "api1": 2 }, "totalCalls": 2 }, { "productTitle": "Product2", "api-activity": { "api1": 2, "api2": 4, "api3": 6, "api4": 8 }, "totalCalls": 20 }, { "productTitle": "Product3", "api-activity": { "api1": 2 }, "totalCalls": 2 } ]
has comment: http://stackoverflow.com/comment/82500146
has comment: http://stackoverflow.com/comment/82499194

http://stackoverflow.com/q/47822397
answer count: 1
has body: Here is my text: def judgeScoreInput(): if int(input()) in range (11) == [0,1,2,3,4,5,6,7,8,9,10]: A = int(input("Enter Judge A Score: ")) B = int(input("Enter Judge B Score: ")) C = int(input("Enter Judge C Score: ")) D = int(input("Enter Judge D Score: ")) E = int(input("Enter Judge E Score: ")) judgeScoreInput() I want the Judge score to have a range limit upon to 10 so user can't input more than 10, if they do it sends some sort if error message, how do I go about this?
has answer: http://stackoverflow.com/a/47822679
has comment: http://stackoverflow.com/comment/82626811
downvote count: 1
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/23294658
upvote count: 0
type: UnansweredQuestion
tagged with: python
has title: How do I get a range validation?
score: -1
has comment: http://stackoverflow.com/comment/82607577

http://stackoverflow.com/a/47793905
has body: I had the same issue and I found the solution. You have to check if there are hidden fields in the form .. you have to set them
has comment: http://stackoverflow.com/comment/82548754
answers question: http://stackoverflow.com/q/47791972
has comment: http://stackoverflow.com/comment/82552608
type: Answer
score: 0

http://stackoverflow.com/comment/82478164
type: QuestionComment
type: Comment
score: 0
has text: @zwer: It doesn't use `"0123456789qwertyuiopasdfghjklzxc"`, I guess.
comment on: http://stackoverflow.com/q/47758410

http://stackoverflow.com/comment/82461291
comment on: http://stackoverflow.com/q/47749965
has text: my curl commad is: curl -X POST http://serverip/getimg -F file=@/path/to/file/image.jpg what I do is to processing this image and get the new image back
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82585886
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47811757
has text: Is this an actual example of the data with all the `---` and `|` characters?
score: 0

http://stackoverflow.com/comment/88039765
type: AnswerComment
has text: Why do you need to write out as rds and load back in? I am new to rpy2 but in your "python combined" code you could seemingly run it as far as the line `dfList = base.mget(base.ls())`. Then use a `for` loop over the elements of `base.names(dfList)` to populate `df_dict` with the command `df_dict[i] = pandas2ri.ri2py_dataframe(robjects.globalenv[i])`. At least, that seemed to work for me...
score: 1
comment on: http://stackoverflow.com/a/47872674
type: Comment

http://stackoverflow.com/a/47744500
answers question: http://stackoverflow.com/q/47744325
has comment: http://stackoverflow.com/comment/82449137
type: Answer
has comment: http://stackoverflow.com/comment/82449113
score: 0
has body: It would help more if you've posted your code instead of the JSON, but here's a simple way to do it: # parent.py import json import subprocess transfer_dict = {"name": "Bob", "msg": "Hello"} # dict to transfer # start our sub-process calling the child.py proc = subprocess.Popen(["python", "child.py"], stdout=subprocess.PIPE, stdin=subprocess.PIPE, universal_newlines=True) # serialize to JSON, send to the subprocess and wait for a response stdout, _ = proc.communicate(json.dumps(transfer_dict)) print("child.py responded with: " + stdout) # finally, print out the response Then write the child process: # child.py import json data = input() # awaiting input from parent.py, use raw_input() on Python 2.x transfer_dict = json.loads(data) # deserialize back to dict # print out what we've received print("Hey {}, {} to you too!".format(transfer_dict["name"], transfer_dict["msg"])) I'm using JSON because it's less of a hassle than pickle and you've tagged it in your question. Running this will produce: child.py responded with: Hey Bob, Hello to you too! Proving that the transfer_dict dictionary has been transferred successfully.
has comment: http://stackoverflow.com/comment/82449165

http://stackoverflow.com/a/47839310
answers question: http://stackoverflow.com/q/47839224
score: 0
type: Answer
has body: In your parameter example it's a local variable so the value in the calling function doesn't change. If you make the parameter example take a pointer-to-pointer and fix the rest accordingly the calling function's value would then be changed and it would work.
accepted answer of: http://stackoverflow.com/q/47839224
type: AcceptedAnswer

http://stackoverflow.com/a/47779745
type: Answer
has comment: http://stackoverflow.com/comment/82520739
accepted answer of: http://stackoverflow.com/q/47779673
has comment: http://stackoverflow.com/comment/82520937
has comment: http://stackoverflow.com/comment/82520660
has comment: http://stackoverflow.com/comment/82520637
score: 2
has body: Here's my suggestion. Creating a 'major_array' and adding 'part_result' in that array on each iteration of loop. This way if your loop iterates 10 times, you will then have 10 arrays added in your 'major_array'. And finally the array is returned when the for loop finishes. :) def readTXT(): #create a new array major_array = [] part_result = [] '''Reading all data from text file''' with open('dataset/sometext.txt', 'r') as txt: for lines in txt: part = lines.split() part_result = [int(i) for i in part] #sorted([(p[0], p[14]) for p in part_result], key=lambda x: x[1]) print(part_result) major_array.append(part_result) return major_array
upvote count: 2
answers question: http://stackoverflow.com/q/47779673
has comment: http://stackoverflow.com/comment/82520838
has comment: http://stackoverflow.com/comment/82521070
has comment: http://stackoverflow.com/comment/82521033
has comment: http://stackoverflow.com/comment/82520957
has comment: http://stackoverflow.com/comment/82520806
type: AcceptedAnswer
downvote count: 0

optimization
tags question: http://stackoverflow.com/q/47706005
tags question: http://stackoverflow.com/q/47795836
tags question: http://stackoverflow.com/q/47778476
tags question: http://stackoverflow.com/q/47837808
tag name: optimization
tags question: http://stackoverflow.com/q/47742797
tags question: http://stackoverflow.com/q/47751187
tags question: http://stackoverflow.com/q/47754210
tags question: http://stackoverflow.com/q/47773827
tags question: http://stackoverflow.com/q/47784433
tags question: http://stackoverflow.com/q/47818209
tags question: http://stackoverflow.com/q/47785229
tags question: http://stackoverflow.com/q/47791974
tags question: http://stackoverflow.com/q/47808162
tags question: http://stackoverflow.com/q/47746539
tags question: http://stackoverflow.com/q/47769818
tags question: http://stackoverflow.com/q/47737693
tags question: http://stackoverflow.com/q/47826673
tags question: http://stackoverflow.com/q/47721183
type: Tag
tags question: http://stackoverflow.com/q/47834603
tags question: http://stackoverflow.com/q/47795665

http://stackoverflow.com/q/47846834
tagged with: qsplitter
type: AnsweredQuestion
has body: I want to make the button always next to the second tab's label, even when I use splitter to move the edge between two tabs. How to achieve that? I believe it's because I use the absolute position, but how make an widget attached in the gap in QTabWidget? from PyQt5.QtWidgets import (QWidget, QHBoxLayout, QFrame, QSplitter, QStyleFactory, QApplication,QTabWidget,QPushButton) from PyQt5.QtCore import Qt import sys class Example(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): hbox = QHBoxLayout(self) tab1 = QTabWidget(self) tab2 = QTabWidget(self) a=QWidget() a.setGeometry(0,0, 40, 40) tab2.addTab(a,"2") splitter1 = QSplitter(Qt.Vertical) splitter1.addWidget(tab1) splitter1.addWidget(tab2) splitter1.setSizes([100,100]) hbox.addWidget(splitter1) self.setLayout(hbox) z=QPushButton(self) z.setGeometry(100,100,70,20) z.setText("button") self.setGeometry(300, 300, 300, 200) self.show() if __name__ == '__main__': app = QApplication(sys.argv) ex = Example() sys.exit(app.exec_()) This is what I want to achieve all the time. This is what happened when I adjust the edge between two tabs.
tagged with: qtabwidget
has answer: http://stackoverflow.com/a/47847002
tagged with: pyqt
score: 0
answer count: 1
tagged with: pyqt5
has title: How to make a widget attached to QTabWidget's gap and move accordingly with QSplitter in pyqt5
type: Question
tagged with: python
accepted answer: http://stackoverflow.com/a/47847002

http://stackoverflow.com/comment/82390165
type: QuestionComment
comment on: http://stackoverflow.com/q/47714808
has text: When I use driver.find_element_by_xpath(), I can locate the element. But I have to find all the elements with this xpath. So I used driver.find_elements_by_xpath(). But it shows error.
score: 0
type: Comment

http://stackoverflow.com/a/47735899
has body: check whether there is an exe named jupyter in the scripts folder inside python installation folder. if yes, then add the scripts folder into the path. I would suggest you to use anaconda distribution of python. it will take care of everything.
accepted answer of: http://stackoverflow.com/q/47735820
score: 3
answers question: http://stackoverflow.com/q/47735820
type: Answer
has comment: http://stackoverflow.com/comment/82439334
has comment: http://stackoverflow.com/comment/82466437
has comment: http://stackoverflow.com/comment/82450831
upvote count: 3
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/82571350
score: 0
type: AnswerComment
has text: I want to use the values of $var1 and $var2 inside the python file itself. Say if I call get_variables() function like this -> vars = get_variables(?, ?) ... what argumetns should I pass to the function to get the values of $var1 and $var2 ?
type: Comment
comment on: http://stackoverflow.com/a/47797216

http://stackoverflow.com/comment/82648323
type: AnswerComment
has text: My pleasure :) keep in mind that deep/shallow copying objects should always be thought of when giving copies of your objects to external users. Otherwise they can use the pointer you've given them to modify your objects without using your API.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47841958

state
tag name: state
type: Tag
tags question: http://stackoverflow.com/q/47849196

http://stackoverflow.com/a/47801249
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47800626
type: Answer
has body: As it stands there aren't any units to test!!! A test might consist of: packaging your program in a script invoking your program from python unit test as a subprocess piping the output of your command process to a buffer asserting the buffer is what you except it to be While the above would technically allow you to have an automated test on your code it comes with a lot of burden: - multi processing - weak assertions by not having types - coarse interaction (have to invoke a script, can't just assert on the brand/type logic One way to address those issues could be to package your code into smaller units, ie create a method to encapsulate: for j in xx.keys(): yy["brand"] = xx[j]['brand'] yy["type"] = xx[j]["type"] my_products.append(yy) Import it, exercise it and assert on its output. Then there might be something to map the loading and application of xx.keys() loop to an array (which you could also encapsulate as a function). And then there could be the highest level taking in args and composing the product mapper loader transformer. And since your code will be thoroughly unit tested at this point, you may get away with not having a test for your top level script?
accepted answer of: http://stackoverflow.com/q/47800626
score: 1

http://stackoverflow.com/q/47758790
has answer: http://stackoverflow.com/a/47786790
accepted answer: http://stackoverflow.com/a/47786790
type: Question
tagged with: google-sheets-api
has title: Syncing Google Sheets with a database
tagged with: c#
has body: Does anyone know if there is a way to have google sheets run from a database like Oracle, Microsoft SQL, etc.? When the values in the database table(s) are updated, the spreadsheet will show those changes the next time it's opened. Also, possibly writing back to the DB. Is this possible? Any suggestions? Thanks,
tagged with: google-api
tagged with: python
tagged with: node.js
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/58826549
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/58826549

http://stackoverflow.com/a/47850161
has body: For each of those, there is an API-page, like this one. Every API-page at least provides one example (of basic usage)! If you observed errors, it's probably due to import-style. I can't find some doc-page for that at the moment, but the basic examples are all you need. So it's just: from sklearn.naive_bayes import GaussianNB clf = GaussianNB() from sklearn.svm import SVC clf = SVC() from sklearn.svm import SVR clf = SVR() from sklearn.tree import DecisionTreeClassifier clf = DecisionTreeClassifier()
type: Answer
score: 0
answers question: http://stackoverflow.com/q/47850136
has comment: http://stackoverflow.com/comment/82665100

http://stackoverflow.com/comment/83419131
comment on: http://stackoverflow.com/a/47706606
has text: Sorry for late accept! This worked brilliantly. Thank you very much. I was not even aware of that function. It is so powerful :)
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/47777630
tagged with: rest
has title: python script for a REST APi, using json, with curl works
has body: I want to do a python script for a REST API, first authenticate and then do either a get or a put, usually a do it using curl as follows: curl -i -X POST -d username=admin -d password='pass' -c ./cookies.txt http://ip_address:9080/nbapiemswsweb/login curl -v -i -H “Content-Type:application/json” -X GET -b ./cookies.txt 'http://ip_address:9080/nbapiemswsweb/rest/v1/Search/Element' I am trying to get authenticated, but I am getting 401, and then don't know how to do a GET: import requests from requests.auth import HTTPDigestAuth import json url = "http://IP_ADDRESS:9080/nbapiemswsweb/login" myResponse = requests.post(url,auth=HTTPDigestAuth(raw_input("username: "), raw_input("Password: ")), verify=True) print (myResponse.status_code) result python restapi.py username: admin Password: pass 401 I need to get 200 and be able to do a get for the second curl
has answer: http://stackoverflow.com/a/47777804
tagged with: http://stackoverflow.com/tag/json
tagged with: python
tagged with: curl
type: Question
accepted answer: http://stackoverflow.com/a/47777804
answer count: 1
has comment: http://stackoverflow.com/comment/82516666
type: AnsweredQuestion
score: 0

http://stackoverflow.com/comment/82409582
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47724077
has text: I was using 2.1.1 and updated to 2.1.2 and i now works. Thanks for the tip!

http://stackoverflow.com/q/47797383
upvote count: 12
downvote count: 0
tagged with: python
linked to: http://stackoverflow.com/q/27016904
has title: Plotly legend next to each subplot, Python
has comment: http://stackoverflow.com/comment/82559419
favorite count: 0
has answer: http://stackoverflow.com/a/57549717
possible better answer: http://stackoverflow.com/a/57549717
has answer: http://stackoverflow.com/a/79520810
type: AnsweredQuestion
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/82585253
answer count: 3
has body: After noticing that there was no answer to this question at the moment, I would like to know if anyone has an idea how to: Have a legends for each subplot. Group legends by name. (Ex: for different subplots, all have the same two curves but with different values). Here's my Plotly script: from plotly import tools import plotly.plotly as py import plotly.graph_objs as go import plotly nom_plot=[] trace1 = go.Scatter(x=[1, 2, 3], y=[4, 5, 6],name='1',showlegend=True) nom_plot.append('GRAPH 1') trace2 = go.Scatter(x=[20, 30, 40], y=[50, 60, 70],name='2',yaxis='y2') nom_plot.append('GRAPH 2') trace3 = go.Scatter(x=[300, 400, 500], y=[600, 700, 800],showlegend=False) nom_plot.append('GRAPH 3') trace4 = go.Scatter(x=[4000, 5000, 6000], y=[7000, 8000, 9000]) nom_plot.append('GRAPH 4') trace5 = go.Scatter(x=[20, 30, 40], y=[50, 60, 70]) nom_plot.append('GRAPH 5') print(trace1) fig = tools.make_subplots(rows=4, cols=2, subplot_titles=(nom_plot)) fig.append_trace(trace1, 1, 1) fig['layout']['xaxis1'].update(title='xaxis 1 title') fig.append_trace(trace2, 1, 1) fig.append_trace(trace3, 2, 1) fig.append_trace(trace4, 2, 2) fig['layout']['yaxis3'].update(title='yaxis 3 title') fig.append_trace(trace5, 3, 1) fig['layout']['yaxis2'].update( overlaying='y1', side='right', anchor='x1', # domain=[0.15, 1], range=[2, 6], # zeroline=False, showline=True, showgrid=False, title='yaxis 3 title' ) fig['layout'].update(height=1000, width=1000, title='Multiple Subplots' +' with Titles') plotly.offline.plot(fig, filename='multiple-y-subplots6.html') This what I obtain (Using Plotly Script above): And this is what I want (Made by Pygal):
tagged with: plotly
has comment: http://stackoverflow.com/comment/82610037
score: 12
type: Question
has answer: http://stackoverflow.com/a/48264162
accepted answer: http://stackoverflow.com/a/48264162
has comment: http://stackoverflow.com/comment/82555858
tagged with: plotly-dash
linked to: http://stackoverflow.com/q/62678377

http://stackoverflow.com/comment/82408608
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47723790
type: QuestionComment
has text: error says `column "dot_number" of relation "saferdb_question" does not exist` - are you sure you have column `"dot_number"` in table `"saferdb_question"` in your database ?

http://stackoverflow.com/a/47748598
type: Answer
answers question: http://stackoverflow.com/q/47735944
score: 0
has body: Instead of changing to a negative sign, you can calculate the angle your self. I've used your ball and arrow example. It's very simple trigonometry: #Import needed programs import pygame, sys, time, math from pygame.locals import * #Initialize pygame pygame.init() window = pygame.display.set_mode((600, 450)) pygame.display.set_caption('PyCloud') #Define colours aqua = 0,255,255 white = 255,255,255 #Defne an arrow sprite class arrow = pygame.image.load("arrow.png") arrow = pygame.transform.scale(arrow,(50,200)) #Define a function to calculate angle def calcAngle(triangleA,triangleB): sinAngle = triangleA/triangleB angle = math.asin(sinAngle) return math.degrees(angle) #Creat clock lop for stability clock = pygame.time.Clock() #start main loop while True: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() exit() else: pass #Get mouse pos mouse = pygame.mouse.get_pos() x = mouse[0] y = mouse[1] #calculate triangle lengths triangleA = x triangleB = math.hypot(x,(450-y)) angle = calcAngle(triangleA,triangleB) print(angle) #draw screen window.fill(white) pygame.draw.circle(window,aqua,(x,y),10,0) window.blit(arrow,(0,350)) clock.tick(1000) pygame.display.update() The program stores the exact angle that that the arrow should turn in a variable called angle. I will let you decide what you ant to do with the angle itself. The difference between this and what you did is it calculates it based on the pygame axis, not a mathematical one. Here is the arrow image in case you want to test it out. Just save the below image in the same folder as the program:

cad
tags question: http://stackoverflow.com/q/47793442
tag name: cad
tags question: http://stackoverflow.com/q/47797909
tags question: http://stackoverflow.com/q/47782353
tags question: http://stackoverflow.com/q/47743028
type: Tag
tags question: http://stackoverflow.com/q/47802564

http://stackoverflow.com/q/47746590
linked to: http://stackoverflow.com/q/34254103
tagged with: ply
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82453263
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/82453441
has answer: http://stackoverflow.com/a/47747466
has body: if statements and while statement keep throwing syntax errors from p_error(p), and PLY tells me that there's a conflict at runtime. The issues are from the if-else and while statements because it was fine before adding them. Any help would be appreciated. If possible please don't change the implementation much even if it's in bad practice. I just want help understanding it I don't want a complete overhaul (that'd be plagiarism). import ply.lex as lex import ply.yacc as yacc # === Lexical tokens component === # List of possible token namesthat can be produced by the lexer # NAME: variable name, L/RPAREN: Left/Right Parenthesis tokens = ( 'NAME', 'NUMBER', 'PLUS', 'MINUS', 'TIMES', 'DIVIDE', 'MODULO', 'EQUALS', 'LPAREN', 'RPAREN', 'IF', 'ELSE', 'WHILE', 'EQUAL', 'NOTEQ', 'LARGE', 'SMALL', 'LRGEQ', 'SMLEQ', ) # Regular expression rules for tokens format: t_&lt;TOKEN&gt; # Simple tokens: regex for literals +,-,*,/,%,=,(,) and variable names (alphanumeric) t_PLUS = r'\+' t_MINUS = r'-' t_TIMES = r'\*' t_DIVIDE = r'/' t_MODULO = r'%' t_EQUALS = r'=' t_LPAREN = r'\(' t_RPAREN = r'\)' t_NAME = r'[a-zA-Z_][a-zA-Z0-9_]*' t_IF = r'if' t_ELSE = r'else' t_WHILE = r'while' t_EQUAL = r'\=\=' t_NOTEQ = r'\!\=' t_LARGE = r'\&gt;' t_SMALL = r'\&lt;' t_LRGEQ = r'\&gt;\=' t_SMLEQ = r'\&lt;\=' # complex tokens # number token def t_NUMBER(t): r'\d+' # digit special character regex t.value = int(t.value) # convert str -&gt; int return t # Ignored characters t_ignore = " \t" # spaces &amp; tabs regex # newline character def t_newline(t): r'\n+' # newline special character regex t.lexer.lineno += t.value.count("\n") # increase current line number accordingly # error handling for invalid character def t_error(t): print("Illegal character '%s'" % t.value[0]) # print error message with causing character t.lexer.skip(1) # skip invalid character # Build the lexer lex.lex() # === Yacc parsing/grammar component === # Precedence &amp; associative rules for the arithmetic operators # 1. Unary, right…
answer count: 1
has title: Python PLY issue with if-else and while statements
accepted answer: http://stackoverflow.com/a/47747466
favorite count: 0
type: Question
tagged with: python-3.x
score: 3

http://stackoverflow.com/comment/82483628
score: 0
comment on: http://stackoverflow.com/q/47759732
type: QuestionComment
type: Comment
has text: the .bat file contains the command `robot.bat --pythonpath C:/Users/kondalar/apps/conda/envs/robot-cray-ui-test2 --critical Critical --outputdir ..\report --variablefile C:/Users/kondalar/workspace/rafa/cra-ui-qa/config/windows-local-config.py C:/Users/kondalar/workspace/rafa/cra-ui-qa/cases/01*`

http://stackoverflow.com/a/47834350
has comment: http://stackoverflow.com/comment/82648987
score: 0
answers question: http://stackoverflow.com/q/47823600
has body: I think you need to change your qopts to look like this: qopts = {"query": "\"tesla\"", "filter": "language:(english|en),crawl_date&gt;2017-10-14T12:00:00- 0700,crawl_date&lt;2017-12-14T12:00:00-0800", "aggregations": "[term(host).term(enriched_text.sentiment.document.label),term(enriched_text.sentiment.document.label)]" }
has comment: http://stackoverflow.com/comment/82710844
type: Answer

network-programming
tag name: network-programming
tags question: http://stackoverflow.com/q/47726865
tags question: http://stackoverflow.com/q/47840067
tags question: http://stackoverflow.com/q/47829925
tags question: http://stackoverflow.com/q/47831444
tags question: http://stackoverflow.com/q/47752297
tags question: http://stackoverflow.com/q/47745282
type: Tag
tags question: http://stackoverflow.com/q/47765335

http://stackoverflow.com/comment/82547444
comment on: http://stackoverflow.com/q/47791878
has text: It is a simple use case for pyspark. Show us what have you tried??
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82503265
has text: You could start by reading some basic python programing tutorial books, my favorite first book was "think python"(you can find it in google) you could also see some you tube chanales. And by the way if you want to learn by example turtle module comes with example so got to your idle then go to help and you will find some examples of turtle programs
score: 1
comment on: http://stackoverflow.com/q/47770545
type: QuestionComment
type: Comment

colors
tags question: http://stackoverflow.com/q/47851492
tags question: http://stackoverflow.com/q/47805588
tags question: http://stackoverflow.com/q/47840374
tags question: http://stackoverflow.com/q/47733600
tag name: colors
tags question: http://stackoverflow.com/q/47759808
tags question: http://stackoverflow.com/q/47734513
tags question: http://stackoverflow.com/q/47734322
type: Tag
tags question: http://stackoverflow.com/q/47852944

http://stackoverflow.com/a/47814675
type: Answer
has comment: http://stackoverflow.com/comment/89358097
score: 1
has comment: http://stackoverflow.com/comment/82595058
downvote count: 1
has body: This error message... WebDriverException: Message: TypeError: can't access dead object ...implies that there was an error while switching between &lt;iframes&gt;. Some more information in terms of: The relevant HTML Presence of Frameset Presence of Frames Hierarchy of Nested Frames Sequence of Frame Loading Presence of JavaScript and AJAX Calls within the respective &lt;iframe&gt; tags would have helped us to analyze the issue in a better way. However, at this point it is worth to mention that initially Selenium always gets the focus on the default_content. Here are a few approaches to work with nested &lt;frames&gt; and &lt;framesets&gt;: If both frame1 and frame2 are at same level i.e. under the Top Level Browsing Context you need to: self.driver.switch_to.frame(self.driver.find_element_by_id("frame1")) self.driver.switch_to_default_content() self.driver.switch_to.frame(self.driver.find_element_by_id("frame2")) If frame2 is nested within frame1, to switch from frame1 to frame2 you need to: self.driver.switch_to_default_content() self.driver.switch_to.frame(self.driver.find_element_by_id("frame1")) //code self.driver.switch_to.frame(self.driver.find_element_by_id("frame2")) If frame2 and frame3 is within frame1 then, to switch from frame2 to frame3 you need to: self.driver.switch_to.frame(self.driver.find_element_by_id("frame2")) self.driver.switch_to.frame(self.driver.find_element_by_id("frame1")) self.driver.switch_to.frame(self.driver.find_element_by_id("frame3")) If frame2 and frame3 is within a frameset23 which is within frame1 then, to switch from frame2 to frame3 you need to: self.driver.switch_to.frame(self.driver.find_element_by_id("frame2")) #ignore presence of frameset23 self.driver.switch_to.frame(self.driver.find_element_by_id("frame1")) #ignore presence of frameset23 self.driver.switch_to.frame(self.driver.find_element_by_id("frame3")) Better approach with proper WebDriverWait While dealing with iframe and frameset you need to induce WebDriverWait inc…
answers question: http://stackoverflow.com/q/47811895
upvote count: 2

http://stackoverflow.com/q/47852048
type: Question
has body: I am running a python script on a Bluehost remote machine, and my script opens a browser window to ask the user for his permission to access his personal calendar. This is part of the oAuth2 protocol. In fact, this is for me to give access to this script to access my Google Calendar. I am running this script through SSH from my local machine, and need it to display on my local machine. Is there a way to do this? Has someone with a Bluehost account done this? thanks
has comment: http://stackoverflow.com/comment/82669187
has title: How to forward Display of remote server in bluehost to local machine
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82668649
tagged with: ssh
has comment: http://stackoverflow.com/comment/82669108
tagged with: python
tagged with: bluehost
score: 0
tagged with: display
answer count: 0
has comment: http://stackoverflow.com/comment/82669151
has comment: http://stackoverflow.com/comment/82668638

http://stackoverflow.com/comment/82665432
has text: I would suggest you also post the contents of `foo.py` responsible for the undesired output, with related `import`s, etc.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47844949

http://stackoverflow.com/comment/82571479
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47709529
has text: I have clarified the problem and made sure that the shapes of matrix aren't the reason for my error, but it still doesn't work...
score: 0

http://stackoverflow.com/q/47721597
has body: import pygame pygame.init() Display = pygame.display.set_mode((800,600)) pygame.display.set_caption("Blocky") red = (157, 139, 215) black = (0,0,0) Display.fill(red) pygame.draw.rect(Display,black,(400,300,200,80)) pygame.display.update() excape = False while not excape: for dork in pygame.event.get(): print (dork) [ Works correctly But When I copy and paste red to pygame.draw under the update function it doesn't work.. Why doesn't ?
has comment: http://stackoverflow.com/comment/82403862
type: AnsweredQuestion
score: 0
answer count: 2
has title: How does this thing work this way,just explain
has comment: http://stackoverflow.com/comment/82403924
accepted answer: http://stackoverflow.com/a/47722134
has answer: http://stackoverflow.com/a/47721668
has comment: http://stackoverflow.com/comment/82404751
type: Question
has answer: http://stackoverflow.com/a/47722134
tagged with: python
tagged with: pygame
possible better answer: http://stackoverflow.com/a/47721668

http://stackoverflow.com/q/47790603
tagged with: shell
type: Question
answer count: 2
upvote count: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/19735250
score: -3
has answer: http://stackoverflow.com/a/47791054
tagged with: php
favorite count: 0
has title: Running a Python script as library from PHP
has answer: http://stackoverflow.com/a/47791021
has comment: http://stackoverflow.com/comment/82697430
has body: I'm trying to run a Python script from PHP using the following command: $cmd="sudo /var/www/html/test/class.sh /tmp/tib.jpg" exec($cmd,$output,$return) So, i write the command into a shell script "class.sh" cd $my_work_dir /usr/bin/python3 -m src.inference.classify file $1 But, i can run the script in command line "php /var/www/html/test/class.sh", but that can't run in the browser with output. I use the proc_open capture the part of error: array ( 'stdout' =&gt; '', 'stderr' =&gt; 'Traceback (most recent call last): File "/usr/lib/python3.4/runpy.py", line 170, in _run_module_as_main "__main__", mod_spec) File "/usr/lib/python3.4/runpy.py", line 85, in _run_code exec(code, run_globals) File "/home/bmk/1\\udce6\\udc96\\udc87\\udce6\\udca1\\udca3/0\\udce7\\udca0\\udc94\\udce5\\udc8f\\udc91/Dog/Dog-AI/dog-breeds-classification-master/src/inference/classify.py", line 7, in import tensorflow as tf File "/usr/local/lib/python3.4/dist-packages/tensorflow/__init__.py", line 24, in from tensorflow.python import * File "/usr/local/lib/python3.4/dist- I think , because,Python can not locate my python library. I also refered another stackoverflow Running a Python script from PHP , that is not work for me. Can anybody help me?
downvote count: 3
tagged with: python

http://stackoverflow.com/comment/82866897
has text: to classify a single example should I modify the forward pass that takes average of w1 and b1 ? As currently forward pass classifies entire training set.
type: Comment
comment on: http://stackoverflow.com/a/47941930
score: 0
type: AnswerComment

http://stackoverflow.com/a/47821186
downvote count: 0
type: AcceptedAnswer
has body: We can sort by cluster_id and new column'G': df.assign(G=df.groupby('cluster_id').cluster_id.transform('count')).sort_values(['G','cluster_id'],ascending=[False,True]).drop('G',1) Out[248]: cluster_id distance url 4 7 0.10 abc.com 5 7 0.20 def.com 6 7 0.30 xyz.com 0 1 0.15 aaa.com 1 1 0.25 bbb.com 2 2 0.05 ccc.com 3 2 0.10 ccc.com
has comment: http://stackoverflow.com/comment/82604932
score: 3
accepted answer of: http://stackoverflow.com/q/47821077
has comment: http://stackoverflow.com/comment/82604961
has comment: http://stackoverflow.com/comment/82605695
type: Answer
answers question: http://stackoverflow.com/q/47821077
has comment: http://stackoverflow.com/comment/82605704
upvote count: 3

http://stackoverflow.com/a/47847210
upvote count: 1
has comment: http://stackoverflow.com/comment/82658560
has body: It appears that you have multiple lines which go together, separated by a blank line, and then all the changes are done on this whole record. So, you need to break the file into records, first. Once you do that, the rest becomes easy. Also notice the use of functions to handle different tasks, and make each part of the code responsible for one specific task (mostly). # print one multi-line record def output_record(lines): needs_prefix = is_condition_met(lines) for line in lines: if needs_prefix and '*' not in line: print ('*', line) else: print (line) print() # determine if this record meets the condition for special handling def is_condition_met(lines): if len(lines) &gt;= 2: if 'CAR' in lines[0] and 'CAR' in lines[1]: if '*' in lines[0] or '*' in lines[1]: return True return False # because I didn't want to do file IO in this example all_lines = [ '* CAR SDFSG FDSFDFDSF ', ' CAR FDGDSGGF', 'bla bla', 'bla', '', ' CAR SDdsfdfFSG FDSFDFDSF ', ' CAR FdffdsDGDSGGF', 'bla ', 'bla' ] # parse the whole file into multi-line records lines_this_record = [] for line in all_lines: if line: lines_this_record.append(line) else: output_record(lines_this_record) lines_this_record = [] # last record may still need to be printed, # if we look for newlines, but there was no blank line at the end of file if lines_this_record: output_record(lines_this_record)
accepted answer of: http://stackoverflow.com/q/47844760
has comment: http://stackoverflow.com/comment/82669884
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/82658624
answers question: http://stackoverflow.com/q/47844760
score: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82676185
has comment: http://stackoverflow.com/comment/82669911

http://stackoverflow.com/comment/82669242
comment on: http://stackoverflow.com/a/47817882
has text: You’re welcome. You can flag this answer as a answer. it would be good for me
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47738959
accepted answer: http://stackoverflow.com/a/47739099
tagged with: python
tagged with: data-structures
has answer: http://stackoverflow.com/a/47739072
type: AnsweredQuestion
has body: I have the following 4 fruits stored in an list fruits = ["Apple", "Orange", "Pear", "Watermelon"] and I use a random number generator 'numgen' to generate a value of 1 to 5. The output will be something like this Apple Item is available Orange Item is unavailable Pear Item is available Watermelon Item is available If the number generated is 1 or 2, it should fall under else which will be unavailable. Now I want to store the fruits that fall under else which are unavailable into a list using 'unavailablefruits' and also 'availablefruits' to display the available fruits at the end with a count, using something like this print("The following items are unavailable") print(unavailablefruits) print('Number of fruits available = ' + availablefruits) print('Percentage of fruits available = " + percent) I also wish to display the percentage of fruits available with 'percent' to achieve something like this at the end Output: Apple Item is available Orange Item is unavailable Pear Item is available Watermelon Item is available The following items are unavailable: Orange Number of fruits available = 3 Percentage of fruits available = 75.0 I need some help because I don't know how to store them in a list and give it a name. Any suggestions? Revised code v2 import random class Queue: def __init__(self): self.container = [] def __len__(self): return len(self.container) def is_empty(self): return len(self) == 0 def enqueue(self, item): self.container.append(item) def dequeue(self): return self.container.pop(0) def peek(self) : return self.container[0] def __iter__(self): return iter(self.container) fruits = ["Apple", "Orange", "Pear", "Watermelon"] #unavailable_fruits = [f for f in fruits if random.randint(1, 5) in (1, 2)] #available_fruits = list(set(fruits) - set(unavailable_fruits)) #percent_available = (len(available_fruits)/len(fruits)) * 100 q = Queue() temp = fruits.copy() fruits = ["Apple", "Orange", "Pear", "Watermelon"] d = {fruit: random.randint(1, 5) for fruit in fruit…
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/47738999
tagged with: queue
type: Question
has title: Creating an array inside an if else statement in Python
has answer: http://stackoverflow.com/a/47739099
possible better answer: http://stackoverflow.com/a/47738999

http://stackoverflow.com/q/47724589
has body: I'm trying to bind multiple callback functions across multiple properties with code that looks something like: for key in keys: def callback(self, value): #Do stuff... return None doSomething(callback) This works because the calling code (that calls callback) expect exactly two parameters and the callback to return None. The issue is now I want to wrap the callback such that I can also pass the key in something like: for key in keys: def wrappedCallback(self, value): #How do I get key in here??? realCallback(self, key, value) return None doSomething(wrapperCallback) But I have no idea how to get key inside of wrapperCallback. I can't add an extra default parameter like: ... #This throws with "expected a function taking 2 arguments, not 3" def wrappedCallback(self, value, key=key): realCallback(self, key, value) ... because this will throw an error from the caller (it's C code that expects a very strict callback). I've also tried functools.partial but then I get expected a function, not a functools.partial How do I wrap the passed callback function to include the external parameter key (from the for loop) while keeping the exact signature described?
tagged with: python-3.x
tagged with: blender
type: UnansweredQuestion
tagged with: python
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/47724673
has title: Wrap callback function to include extra argument when caller verifies exact callback signature
has answer: http://stackoverflow.com/a/47724623
type: Question

http://stackoverflow.com/comment/82404148
comment on: http://stackoverflow.com/q/47721524
score: 0
has text: @roganjosh right, previously I did try an add function as well. I was trying to serially add an array and then parallelly add it. Making an edit to show exactly what I tried.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82463088
has text: Exception handling is not a conditional so checking if something exists is cleaner. See [here](https://stackoverflow.com/questions/4512557/python-if-key-in-dict-vs-try-except) for more explanation
comment on: http://stackoverflow.com/a/47751385
type: AnswerComment
score: 1
type: Comment

http://stackoverflow.com/q/47774411
score: 0
has body: I have python3 code how to combine two dictionaries 'd','dconn' in one, if they are in different levels indent. I newbie in python3, help me please. code approximately looks like that: for ip in fp.read().splitlines(): d={} if p.poll(): d.update({ip : '1'}) else: d.update({ip : '0'}) for keys, value in d.items(): print(keys, value) dconn = {} if connection.username == 'REPORT': dconn.update({connection.username : '0'}) else: dconn.update({connection.username : '1'}) for keys, value in dconn.items(): print(keys, value)
upvote count: 1
downvote count: 1
answer count: 1
favorite count: 0
tagged with: python-3.x
has title: Combine two dict into one at different levels of indent
type: Question
has comment: http://stackoverflow.com/comment/82509689
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82509691
has answer: http://stackoverflow.com/a/47774517

http://stackoverflow.com/a/47804936
has comment: http://stackoverflow.com/comment/82572283
has comment: http://stackoverflow.com/comment/82571973
score: 0
has comment: http://stackoverflow.com/comment/82571745
has comment: http://stackoverflow.com/comment/82572359
type: Answer
has body: {"$project":{ "bcced_name": {"$map":{ "input":{"$split":["$status.tat",", "]}, "as":"tat", "in":{ "$cond":[ {"$gt":[{"$indexOfCP":["$$tat","&lt;"]},0]}, {"$arrayElemAt" : [{"$split":["$$tat", "&lt;"]}, 0]}, "$$tat" ] } } } } }
has comment: http://stackoverflow.com/comment/82572333
answers question: http://stackoverflow.com/q/47803034
has comment: http://stackoverflow.com/comment/82572468

http://stackoverflow.com/a/47729272
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/47729174
has body: Any return command will simply exit the function, so having multiple return commands at the same level would never work in Python. The issue with your code is that you should be using the key word self within your __repr__ definition, that way you can access it with all four instances that you create with john = Person('John','Lennon','8th','October','1940') paul = Person('Paul','McCartney','18th','June','1942') george = Person('George','Harrison','25th','February','1943') ringo = Person('Ringo','Starr','7th','July','1940') Those creations of instances of the class Person will also automatically store all the information that you enter, so no need to specify by hand values for john._firstname etc. To give a clear answer: class Person: def __init__(self, _firstname, _surname, d, m, y): self._firstname = _firstname self._surname = _surname self.d = d self.m = m self.y = y def __repr__(self): return '{} {} \n{} {} {}'.format(self._firstname, self._surname, self.d, self.m, self..y) john = Person('John','Lennon','8th','October','1940') paul = Person('Paul','McCartney','18th','June','1942') george = Person('George','Harrison','25th','February','1943') ringo = Person('Ringo','Starr','7th','July','1940') print(john) print(paul) print(george) print(ringo)
score: 2
downvote count: 0
upvote count: 2
answers question: http://stackoverflow.com/q/47729174

doctest
type: Tag
tag name: doctest
tags question: http://stackoverflow.com/q/47832893
tags question: http://stackoverflow.com/q/47741840

http://stackoverflow.com/comment/82426219
has text: Good info. Lots of good stuff buried in the functools module.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47732828
type: Comment

http://stackoverflow.com/q/47785237
answer count: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/82531927
has title: Simpson's Rule returning an array in Python
favorite count: 0
type: Question
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47785734
tagged with: matplotlib
has answer: http://stackoverflow.com/a/47785734
tagged with: python
tagged with: scipy
has comment: http://stackoverflow.com/comment/82532297
score: 1
has body: Ok, so my Simpson's Rule is defined as: def simpsonsRule(func, a, b, n, p0, r0): if n%2 == 1: return "Not applicable" else: h = (b - a) / float(n) s = func(a, p0, r0) + sum((4 if i%2 == 1 else 2) * func(a+i*h, p0, r0) for i in range(1,n)) + func(b, p0, r0) return s*h/3.0 Yet, when I do something like: def integrate_NFW(rx,ps,rs): rho = ps/((r/rs)*((1+(r/rs))**2)) function_result = rho * 4.0 * np.pi * rx**2 return function_result def chisqfuncNFW(iter_vars): global v_model #Normalizes p0 (p0 is too large relative to rc) ps = iter_vars[0] * 3.85e+09 rs = iter_vars[1] for index in range(0, am): integral_result = simpsonsRule(integrate_NFW, 0.0, r[index], 200, ps, rs) print(integral_result) When you print out integral_result it returns an array of numbers: [ 1.58771810e+13 3.68633515e+12 1.60346051e+12 8.81279407e+11 5.37962555e+11 3.54826396e+11 2.49107306e+11 1.80747811e+11 1.36318422e+11 1.05440828e+11 8.32851651e+10 6.66410643e+10 5.41730944e+10 4.48302130e+10] So integral_result = simpsonsRule(integrate_NFW, 0.0, r[index], 200, ps, rs) returns an array instead of one number I would like to add that it works fine (it returns one number instead of an array) for another model of mine: def integrate_Burk(rx,p0,r0): rho = (p0 * r0**3) / ( (rx + r0) * (rx**2 + r0**2) ) function_result = rho * 4.0 * np.pi * rx**2 return function_result def chisqfuncBurk(iter_vars): global v_model #Normalizes p0 (p0 is too large relative to rc) p0 = iter_vars[0] * 3.85e+09 r0 = iter_vars[1] v_model = [] for index in range(0, am): integral_result = simpsonsRule(integrate_Burk, 0.0, r[index], 200, p0, r0) Also, r is an array of numbers: 0.22 0.66 1.11 1.55 2.00 2.45 2.89 3.34 3.78 4.22 4.66 5.11 5.56 6.00 and am is the amount of numbers in r (in this case, I believe it is 14) Let me know if I left anything out or if you want additional code EDIT Here is some code that replicates the error from scipy.optimize import* import numpy as np am = 14 r = np.array([0.22, 0.66, 1.11, 1.55, 2.00, 2.45,…
tagged with: arrays

http://stackoverflow.com/comment/82609002
has text: I am getting this error: TypeError: slice indices must be integers or None or have an __index__ method. I may just be doing something wrong though
type: AnswerComment
comment on: http://stackoverflow.com/a/47823072
score: 0
type: Comment

http://stackoverflow.com/q/47835896
upvote count: 3
score: 3
downvote count: 0
has title: Converting unordered list of tuples to pandas DataFrame
possible better answer: http://stackoverflow.com/a/47836184
favorite count: 0
tagged with: python-3.x
tagged with: tuples
has answer: http://stackoverflow.com/a/47836184
has comment: http://stackoverflow.com/comment/84643691
type: Question
answer count: 2
tagged with: python
accepted answer: http://stackoverflow.com/a/47837365
has answer: http://stackoverflow.com/a/47837365
has body: I am using the library usaddress to parse addresses from a set of files I have. I would like my final output to be a data frame where column names represent parts of the address (e.g. street, city, state) and rows represent each individual address I've extracted. For example: Suppose I have a list of addresses: addr = ['123 Pennsylvania Ave NW Washington DC 20008', '652 Polk St San Francisco, CA 94102', '3711 Travis St #800 Houston, TX 77002'] and I extract them using usaddress info = [usaddress.parse(loc) for loc in addr] "info" is a list of a list of tuples that looks like this: [[('123', 'AddressNumber'), ('Pennsylvania', 'StreetName'), ('Ave', 'StreetNamePostType'), ('NW', 'StreetNamePostDirectional'), ('Washington', 'PlaceName'), ('DC', 'StateName'), ('20008', 'ZipCode')], [('652', 'AddressNumber'), ('Polk', 'StreetName'), ('St', 'StreetNamePostType'), ('San', 'PlaceName'), ('Francisco,', 'PlaceName'), ('CA', 'StateName'), ('94102', 'ZipCode')], [('3711', 'AddressNumber'), ('Travis', 'StreetName'), ('St', 'StreetNamePostType'), ('#', 'OccupancyIdentifier'), ('800', 'OccupancyIdentifier'), ('Houston,', 'PlaceName'), I would like each list (there are 3 lists within the object "info") to represent a row, and the 2 value of each tuple pair to denote a column and the 1 value of the tuple pair to be the value. Note: the link of the inner lists will not always be the same as not every address will have every bit of information. Any help would be much appreciated! Thanks
tagged with: concatenation
tagged with: pandas
type: AnsweredQuestion

http://stackoverflow.com/comment/82432878
type: AnswerComment
comment on: http://stackoverflow.com/a/47735963
has text: That's very kind ;-) But no need to make it a matter of belief. Just check for yourself using `np.shares_memory`.
type: Comment
score: 0

http://stackoverflow.com/q/47795391
accepted answer: http://stackoverflow.com/a/48620972
possible better answer: http://stackoverflow.com/a/48338389
has body: I'm working on a seq2seq RNN generating an output sequence of labels given a seed label. During the inference step I'd like to generate sequences containing only unique labels (i.e. skip labels that have already been added to the output sequence). To do this I created a sampler object that tries to remember the labels that have been added to the output and reduce their logit value to -np.inf. Here is the sampler code: class InferenceSampler(object): def __init__(self, out_weights, out_biases): self._out_weights = tf.transpose(out_weights) self._out_biases = out_biases self._n_tracks = out_weights.shape[0] self.ids_mask = tf.zeros([self._n_tracks], name="playlist_mask") def __call__(self, decoder_outputs): _logits = tf.matmul(decoder_outputs, self._out_weights) _logits = tf.nn.bias_add(_logits, self._out_biases) # apply mask _logits = _logits + self.ids_mask _sample_ids = tf.cast(tf.argmax(_logits, axis=-1), tf.int32) # update mask step_ids_mask = tf.sparse_to_dense(_sample_ids, [self._n_tracks], -np.inf) self.ids_mask = self.ids_mask + step_ids_mask return _sample_ids The code of the inference graph looks like this: self._max_playlist_len = tf.placeholder(tf.int32, ()) self._start_tokens = tf.placeholder(tf.int32, [None]) sample_fn = InferenceSampler(out_weights, out_biases) with tf.name_scope("inf_decoder"): def _end_fn(sample_ids): return tf.equal(sample_ids, PAD_ITEM_ID) def _next_inputs_fn(sample_ids): return tf.nn.embedding_lookup( track_embs, sample_ids ) _start_inputs = tf.nn.embedding_lookup( track_embs, self._start_tokens ) helper = tf.contrib.seq2seq.InferenceHelper( sample_fn=sample_fn, sample_shape=[], sample_dtype=tf.int32, start_inputs=_start_inputs, end_fn=_end_fn, next_inputs_fn=_next_inputs_fn ) decoder = tf.contrib.seq2seq.BasicDecoder( rnn_cell, helper, rnn_cell.zero_state(tf.shape(self._start_tokens)[0], tf.float32), output_layer=projection_layer ) outputs, _, _ = tf.contrib.seq2seq.dynamic_decode( decoder, maximum_iterations=self._max_playlist_l…
downvote count: 0
has comment: http://stackoverflow.com/comment/83661438
has answer: http://stackoverflow.com/a/48620972
tagged with: recurrent-neural-network
tagged with: tensorflow
favorite count: 0
has title: Tensorflow RNN: how to infer a sequence without duplicates?
type: Question
has comment: http://stackoverflow.com/comment/83589054
tagged with: sequence-to-sequence
has answer: http://stackoverflow.com/a/48338389
tagged with: python
score: 4
upvote count: 4
has comment: http://stackoverflow.com/comment/83589283
type: AnsweredQuestion
answer count: 2

http://stackoverflow.com/comment/82512546
score: 0
comment on: http://stackoverflow.com/q/47775763
type: Comment
type: QuestionComment
has text: Show through a sample what you are expecting?

http://stackoverflow.com/a/47758569
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47758330
has body: There are multiple options, but here are two rather simple ones: Option 1 Start logging into a temp file. If you were able to parse the config file, copy the temp file content and change the logging file handle. If there was an error, dump the temp file to stdout. Option 2 Create a wrapper class that delays calls to the logger as long as the config file is not available. Something along the lines of class MyLogger(object): def __init__(self, ...) self.logger = ... # temp file def info(self, msg): self.logger.info(msg) def changeLogfile(self, f): self.logger = ... # now writing to f Once config['logfile'] is available, call mylogger.changeLogfile() and continue logging.
answers question: http://stackoverflow.com/q/47758330
type: Answer

http://stackoverflow.com/comment/82651679
score: 0
type: Comment
has text: sorry, i meant 'Dear'. Thank you very much for your engagement. We found a different solution. We specified different for-loops with different ranges and checked whether the first element is same as the third element and so on.
comment on: http://stackoverflow.com/a/47816335
type: AnswerComment

http://stackoverflow.com/q/47708865
tagged with: cluster-analysis
accepted answer: http://stackoverflow.com/a/47736591
tagged with: scikit-learn
has body: I have a set of data with known labels. I want to try clustering and see if I can get the same clusters given by known labels. To measure the accuracy, I need to get something like a confusion matrix. I know I can get a confusion matrix easily for a test set of a classification problem. I already tried that like this. However, it can't be used for clustering as it expected both columns and rows to have the same set of labels, which makes sense for a classification problem. But for a clustering problem what I expect is something like this. Rows - Actual labels Columns - New cluster names (i.e. cluster-1, cluster-2 etc.) Is there a way to do this? Edit: Here are more details. In sklearn.metrics.confusion_matrix, it expects y_test and y_pred to have the same values, and labels to be the labels of those values. That's why it gives a matrix which has the same labels for both rows and columns like this. But in my case (KMeans Clustering), the real values are Strings and estimated values are numbers (i.e. cluster number) Therefore, if I call confusion_matrix(y_true, y_pred) it gives below error. ValueError: Mix of label input types (string and number) This is the real problem. For a classification problem, this makes sense. But for a clustering problem, this restriction shouldn't be there, because real label names and new cluster names don't need to be the same. With this, I understand I'm trying to use a tool, which is supposed to be used for classification problems, for a clustering problem. So, my question is, is there a way I can get such a matrix for may clustered data. Hope the question is now clearer. Please let me know if it isn't.
tagged with: scikits
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/47736591
score: 8
type: Question
has title: Confusion matrix for Clustering in scikit-learn
upvote count: 9
has comment: http://stackoverflow.com/comment/82379629
has comment: http://stackoverflow.com/comment/82379743
has comment: http://stackoverflow.com/comment/82406753
tagged with: python
has comment: http://stackoverflow.com/comment/82378791
has comment: http://stackoverflow.com/comment/82379927
possible better answer: http://stackoverflow.com/a/47731516
has answer: http://stackoverflow.com/a/47731516
type: AnsweredQuestion
answer count: 2
has comment: http://stackoverflow.com/comment/82424423
tagged with: confusion-matrix

mysql-connect
tag name: mysql-connect
tags question: http://stackoverflow.com/q/47709703
type: Tag

http://stackoverflow.com/a/47839229
answers question: http://stackoverflow.com/q/47838811
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47838811
has comment: http://stackoverflow.com/comment/82651110
has comment: http://stackoverflow.com/comment/82743253
type: Answer
has comment: http://stackoverflow.com/comment/82700199
has comment: http://stackoverflow.com/comment/82645608
has comment: http://stackoverflow.com/comment/82650847
score: 2
has body: Suppose you have a ready function, say read_z_from_file(filename), that returns the z-value contained in the file, you could go about it like this: import numpy as np x = np.arange(10,20,1, dtype = np.int) y = np.arange(20,50,1, dtype = np.int) z = np.zeros((x.shape[0],y.shape[0])) for i,x0 in enum(x): for j,y0 in enum(y): filename = '{}_{}.txt'.format(x0,y0) z[i,j] = read_z_from_file(filename) You can then visualise z with imshow or matshow from matplotlib. For instance: from matplotlib import pyplot as plt fix,ax = plt.subplots() ax.imshow(z) plt.show() EDIT: To respond to the questions of the OP, there is a multitude of ways to visualise your data. imshow and matshow do both about the same thing, but differ in the display details. Additionally, you can, among many others, produce contour plots or 3d surfaces. It depends a lot on what you want to see. Anyway, assuming that the code above does what you want, I show below some code that uses four different methods to display the same example data. You can find out more about these different methods with pythons in-built help() function and, of course, the matplotlib and numpy documentation pages. import numpy as np from matplotlib import pyplot as plt from mpl_toolkits.mplot3d import Axes3D ##for the 3d surface plot from matplotlib import cm #non-integer spacing of the coordinates x = np.linspace (10, 20, 15) y = np.linspace (20, 50, 70) #gridding the coordinates xm, ym = np.meshgrid(x,y) #example data z = np.exp(-( 0.1*(xm-12)**2 + 0.05*(ym-40)**2 ) ) #opening a figure fig = plt.figure(figsize=(6,6)) #matshow: ax1 = fig.add_subplot(221) res = ax1.matshow( z, origin = 'lower', aspect = 'auto', extent=[x[0],x[-1],y[0],y[-1]], ) fig.colorbar(res) ax1.set_title('matshow', y=1.1) #imshow ax2 = fig.add_subplot(222) res = ax2.imshow( z, origin = 'lower', aspect = 'auto', extent=[x[0],x[-1],y[0],y[-1]], ) fig.colorbar(res) ax2.set_title('imshow') #contourf ax3 = fig.add_subplot(223) res = ax3.contourf(xm,ym,z) fig.colorbar…
upvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/q/47837934
answer count: 1
has comment: http://stackoverflow.com/comment/82639622
has comment: http://stackoverflow.com/comment/82639670
type: Question
tagged with: steganography
has answer: http://stackoverflow.com/a/47948444
tagged with: python
has comment: http://stackoverflow.com/comment/82639615
has body: I am new to Steganography. Trying to do a test and i get this error: 'hex' is not a text encoding; use codecs.encode() to handle arbitrary codecs I have read about binascii, but how can i make this work? My code is this one: from __future__ import absolute_import, unicode_literals from steganography.steganography import Steganography path = "/Users/cohen/Desktop/Screenshot_030.png" output_path = "/Users/cohen/Desktop/output_steganography.png" text = "/Users/cohen/Desktop/test.txt" Steganography.encode(path, output_path, text) #---here is the line with error Thank you!
score: 0
has title: Steganography Error-- 'hex' is not a text encoding; use codecs.encode() to handle arbitrary codecs
type: UnansweredQuestion

http://stackoverflow.com/q/47749081
has comment: http://stackoverflow.com/comment/82543296
tagged with: facebook
tagged with: python
has title: Pymongo Insert unique data into Mongodb
tagged with: mongodb
answer count: 0
type: UnansweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/82499008
has body: I am new to Python, Facebook Graph API and MongoDB. I have researched for online resources about insertion into MongoDB. I am unsure about how to insert distinct and unique values that I retrieve from Facebook Graph API into my MongoDB database. Below is my code: def getPostReactionCount(reactions_data): reaction_count = {'LIKE' : 0, 'LOVE' : 0, 'HAHA' : 0, 'WOW' : 0, 'SAD' : 0, 'ANGRY' : 0} if 'reactions' in reactions_data: for x in reactions_data['reactions']['data']: if x['type'] == 'LIKE': reaction_count['LIKE'] += 1 elif x['type'] == 'LOVE': reaction_count['LOVE'] += 1 elif x['type'] == 'HAHA': reaction_count['HAHA'] += 1 elif x['type'] == 'WOW': reaction_count['WOW'] += 1 elif x['type'] == 'SAD': reaction_count['SAD'] += 1 elif x['type'] == 'ANGRY': reaction_count['ANGRY'] += 1 print 'reaction_count:' print reaction_count return reaction_count posts_on_page = graph.get_object(page_id, fields = 'posts') posts_data = json.loads(json.dumps(posts_on_page)) for i in posts_data['posts']['data']: dataPost = {} dataPost['post_id'] = i['id'] dataPost['post_message'] = json.dumps(i['message']) comments_in_posts = graph.get_object(post_id, fields = 'comments') dataPost['comments_data'] = json.loads(json.dumps(comments_in_posts)) reactions_in_post = graph.get_object(post_id, fields = 'reactions') dataPost['reactions_data'] = json.loads(json.dumps(reactions_in_post)) getPostReactionCount(reactions_data) print 'post_id:' print post_id print 'post_massage:' print post_massage print 'comments_data:' print comments_data print 'reactions_data:' print reactions_data #insert process collection.insert(dataPost) # close the connection to MongoDB connection.close() As I think, the line about collection.insert(dataPost) should be inserting all values, and I may have duplicates values.
tagged with: pymongo
downvote count: 0
upvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/a/47772828
has comment: http://stackoverflow.com/comment/82509269
has comment: http://stackoverflow.com/comment/82507931
answers question: http://stackoverflow.com/q/47772556
has comment: http://stackoverflow.com/comment/82509075
type: Answer
has comment: http://stackoverflow.com/comment/82507621
has comment: http://stackoverflow.com/comment/82507099
has comment: http://stackoverflow.com/comment/82506416
has comment: http://stackoverflow.com/comment/82506986
score: 0
has body: Since you didn't include your solution, I used this: from __future__ import division A={('A','B',1):1,('A','B',2):4,('A1','B1',2):5,('A1','B1',1):6} B={} C={} for x in A: val= A[x] y,z,n=x if (y,z) in B: B[(y,z)]+=val C[(y,z)]+=1 else: B[(y,z)]=val C[(y,z)]=1 for x in B: B[x]=B[x]/C[x]
has comment: http://stackoverflow.com/comment/82506795
has comment: http://stackoverflow.com/comment/82506705
has comment: http://stackoverflow.com/comment/82506759
has comment: http://stackoverflow.com/comment/82508216

http://stackoverflow.com/q/47778449
type: AnsweredQuestion
score: 2
linked to: http://stackoverflow.com/q/34145950
tagged with: python-2.7
answer count: 1
favorite count: 0
tagged with: jupyter-notebook
type: Question
has comment: http://stackoverflow.com/comment/82539302
has title: How to save errors from Jupyter Notebook cells to a file?
upvote count: 2
has body: I am trying to save all output (stdout and all errors) of a cell to a file. To save stdout, I am using the following: import sys old_stdout = sys.stdout sys.stdout = open('test.txt', 'w') print("Hello World! ") In this case, the output is not displayed and gets saved in the file as expected. To save errors, I used: #Doesn't work sys.stderr = open('error.txt','w') print(a) #Should raise NameError When I run this cell, I get the error in the notebook, and not in the file as expected: --------------------------------------------------------------------------- NameError Traceback (most recent call last) &lt;ipython-input-5-de3efd936845&gt; in &lt;module&gt;() 1 #Doesn't work ----&gt; 2 sys.stderr = open('error.txt','w') 3 print("Test") 4 print(a) NameError: name 'sys' is not defined I would like this saved in a file and not shown in the notebook. What is the correct code for this?
accepted answer: http://stackoverflow.com/a/47796399
downvote count: 0
has answer: http://stackoverflow.com/a/47796399
tagged with: python

http://stackoverflow.com/a/47831821
has comment: http://stackoverflow.com/comment/82627141
type: Answer
has body: Since this is tagged with Django I assume that query set is actually a Django QuerySet object? If so then there is a simple solution using the ORM values_list: queryset.values_list('id', flat=True)
answers question: http://stackoverflow.com/q/47831549
score: 0
has comment: http://stackoverflow.com/comment/82627306
has comment: http://stackoverflow.com/comment/82631399

qemu
tag name: qemu
tags question: http://stackoverflow.com/q/47791879
type: Tag

http://stackoverflow.com/q/47799305
tagged with: matrix
tagged with: python
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/47799377
score: 0
answer count: 2
has title: Python, finding error in near symmetric matrix created by df.pivot
has answer: http://stackoverflow.com/a/47800373
tagged with: scikit-learn
accepted answer: http://stackoverflow.com/a/47800373
type: Question
has answer: http://stackoverflow.com/a/47799377
tagged with: pandas
has body: I have a 16,000x 16,000 symmetric matrix which I am attempting to perform a multi dimensional scaling analysis on using sklearn. I need to use my own matrix because I have created a unique dissimilarity calculation. The calculations were performed before using df.pivot and all calculations were performed using np.float64 types. When I run the analysis, I get a symmetric error shown below: C:\Users\name\AppData\Local\Continuum\Anaconda2\lib\site-packages\sklearn\utils\validation.py in check_symmetric(array=memmap([[ 0. , 0.0364484 , 0.02794817, ... 0.33687222, 1. , 0. ]]), tol=1e-10, raise_warning=True, raise_exception=True) 633 else: 634 symmetric = np.allclose(array, array.T, atol=tol) 635 636 if not symmetric: 637 if raise_exception: --&gt; 638 raise ValueError("Array must be symmetric") 639 if raise_warning: 640 warnings.warn("Array is not symmetric, and will be converted " 641 "to symmetric by average with its transpose.") 642 if sp.issparse(array): ValueError: Array must be symmetric When looking through the data manually it looks perfect, but given so many columns and rows, I would not be surprised if there was an error or two created from the initial pairwise column/row groupings from the initial data I received which got included and caused confusion in the df.pivot command. The question is thus, how do I find the one or two non-symmetric values in a dissimilarity matrix this large so that I can clear the np.allclose error?

http://stackoverflow.com/comment/82620327
has text: Indeed, @9dogs. You should write an answer.
score: 1
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47828854

http://stackoverflow.com/comment/82371089
has text: I know this can be done in `pandas`. But I want to avoid `pandas` for now. My final goal is to create an `exe` from the python file using pyinstaller and there is some issue with `pandas==0.21`. Also with `pandas` the final `exe` file becomes large.
type: AnswerComment
comment on: http://stackoverflow.com/a/47705479
score: 0
type: Comment

http://stackoverflow.com/a/47834289
type: Answer
answers question: http://stackoverflow.com/q/47834070
downvote count: 0
score: 1
upvote count: 1
has body: cap.read() was unsuccessful, so img is None. From the docs: If no frames has been grabbed (camera has been disconnected, or there are no more frames in video file), the methods return false and the functions return NULL pointer.

http://stackoverflow.com/comment/82490576
type: QuestionComment
score: 0
has text: And I did `install -r requirement.txt` but it showed every packages is satisfied except psycopg2==2.6.1.I changed the version of it in 2.7.3 but showed permission error.I tried to delete it but the package is satisfied still couldn't find it.
comment on: http://stackoverflow.com/q/47758292
type: Comment

http://stackoverflow.com/a/47815677
answers question: http://stackoverflow.com/q/47770786
score: 0
type: Answer
has body: Probably error is in function present_stim. This line: initialy = 400 - (stim_list_b[i] / 2) Array index i is out of range due to long spacebar press.

http://stackoverflow.com/a/47790720
answers question: http://stackoverflow.com/q/47785134
type: Answer
has body: You are trying to run Azure CLI command in PowerShell console of Cloud shell, instead You Should run Azure CLI commands in Bash Shell of cloud shell.
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47785134

http://stackoverflow.com/a/50480095
answers question: http://stackoverflow.com/q/47776954
has body: Since I was testing without making a .pyui file (the file where you edit the actual GUI layout) I had to remove ui.loadview(). But this works and should give you a good starting point. The Pythonista UI Module can be tricky, but sticking with it is worth it :) import ui def lightControl(sender): if switch1.value == False: print 'Lights Off' elif switch1.value == True: print 'Lights On' switch1 = ui.Switch() switch1.action = lightControl v = ui.View() v.add_subview(switch1) v.present('sheet') Also @Lukas is right, the Pythonista Forum is a great place to get help when you’re stuck.
type: Answer
score: 2
upvote count: 2
downvote count: 0

http://stackoverflow.com/comment/82543873
type: Comment
type: AnswerComment
has text: Your comment isn't clear. Setting the `setgid` bit means that the effective gid of the running executable is the group that owns the executable. Under normal operations, new files that that process creates will inherit that group, but of course that doesn't apply if the process explicitly uses a different group (e.g. if you use `tar` to unpack files with different ownership) or changes the effective uid (e.g. using `sudo`). I think you need to edit your question to give an example that shows the permissions you're getting and the permissions you actually want.
score: 0
comment on: http://stackoverflow.com/a/47783564

http://stackoverflow.com/a/47821856
score: 1
type: Answer
answers question: http://stackoverflow.com/q/47782668
has body: (Spyder maintainer here) This is a problem with the IPython console, already reported here. It'll be fixed in Spyder 4.
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47782668
type: AcceptedAnswer

http://stackoverflow.com/q/47815774
score: 1
has body: I'm trying to find all cases of money values in a string called webpage. String webpage is the text from this webpage, in my program it's just hardcoded because that's all that is needed, but I won't paste it all here. regex = r'^[$£€]?(([\d]{1,3},([\d]{3},)*[\d]{3}|[0-9]+)(\.[0-9][0-9])?(\s?bn|\s?mil|\s?euro[s]?|\s?dollar[s]?|\s?pound[s]?|p){0,2})' res = re.findall(regex, webpage) print(res) it's returning [], I expected it to return [$131bn, £100bn, $100bn, $17.4bn]
downvote count: 1
has comment: http://stackoverflow.com/comment/82593028
possible better answer: http://stackoverflow.com/a/47816157
linked to: http://stackoverflow.com/q/37567406
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82593448
has comment: http://stackoverflow.com/comment/82592922
has answer: http://stackoverflow.com/a/47816149
has answer: http://stackoverflow.com/a/47816157
has comment: http://stackoverflow.com/comment/82593020
has comment: http://stackoverflow.com/comment/82593654
has title: Python finding regex in a String
has comment: http://stackoverflow.com/comment/82593657
tagged with: python
tagged with: regex
upvote count: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47816149
answer count: 3
has answer: http://stackoverflow.com/a/47816364

http://stackoverflow.com/comment/82650857
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47843453
has text: Thanks. I tried to convert it to raw string but even after that same error shows up. Also, it also asks to disable the developer extension

http://stackoverflow.com/a/47743125
has comment: http://stackoverflow.com/comment/82476451
accepted answer of: http://stackoverflow.com/q/47741562
downvote count: 0
has comment: http://stackoverflow.com/comment/82476956
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/82471947
answers question: http://stackoverflow.com/q/47741562
has comment: http://stackoverflow.com/comment/82474975
has comment: http://stackoverflow.com/comment/82486630
has body: For the model to share weights, you must create it only once. You cannot create two models. shared_model = creat_conv_model((64, 64, 3), left) If rpn is also a model to be shared, you must create it one time only: rpn_model = create_rpn(...) Then you pass the inputs: img_neg_out = shared_model(img_input_left) img_neg_out = rpn_model(img_neg_out) img_pos_out = shared_model(img_input_right) img_pos_out = rpn_model(img_pos_out) About creating the models branch_left and branch_right, that depends on what you want to do and how you want to train.
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/a/47840362
has body: This should give you the result you are looking for, although it's probably not the most elegant solution. There's probably a better (more pandas way) to do it. I parsed your nested dict and built a list of dictionaries (one for each row). # some sample input nested_dict = { 'string1': {69: [1231, 232], 67:[682, 12], 65: [1, 1]}, 'string2' :{28672: [82, 23], 22736:[82, 93, 1102, 102], 19423: [64, 23]}, 'string3' :{28673: [83, 24], 22737:[83, 94, 1103, 103], 19424: [65, 24]} } # new list is what we will use to hold each row new_list = [] for k1 in nested_dict: curr_dict = nested_dict[k1] for k2 in curr_dict: new_dict = {'col1': k1, 'col2': k2} new_dict.update({'col%d'%(i+3): curr_dict[k2][i] for i in range(len(curr_dict[k2]))}) new_list.append(new_dict) # create a DataFrame from new list df = pd.DataFrame(new_list) The output: col1 col2 col3 col4 col5 col6 0 string2 28672 82 23 NaN NaN 1 string2 22736 82 93 1102.0 102.0 2 string2 19423 64 23 NaN NaN 3 string3 19424 65 24 NaN NaN 4 string3 28673 83 24 NaN NaN 5 string3 22737 83 94 1103.0 103.0 6 string1 65 1 1 NaN NaN 7 string1 67 682 12 NaN NaN 8 string1 69 1231 232 NaN NaN There is an assumption that the input will always contain enough data to create a col1 and a col2. I loop through nested_dict. It is assumed that each element of nested_dict is also a dictionary. We loop through that dictionary as well (curr_dict). The keys k1 and k2 are used to populate col1 and col2. For the rest of the keys, we iterate through the list contents and add a column for each element.
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/47840093
answers question: http://stackoverflow.com/q/47840093
score: 1
type: AcceptedAnswer
upvote count: 1

http://stackoverflow.com/comment/82614433
type: QuestionComment
comment on: http://stackoverflow.com/q/47825900
score: 0
has text: you have wrong focus here buddy, your design should revolve around messages and not users. Users should be a foreign key entity of signed-up users! :)
type: Comment

http://stackoverflow.com/comment/82657869
type: Comment
type: QuestionComment
has text: It's not clear to me what you mean by radial color gradient
comment on: http://stackoverflow.com/q/47844325
score: 0

http://stackoverflow.com/q/47821248
has comment: http://stackoverflow.com/comment/82606341
type: UnansweredQuestion
tagged with: python
tagged with: pyodbc
tagged with: macos
score: 2
has title: Can't open lib 'FreeTDS' : file not found (0) (SQLDriverConnect) Unable to connect MSSQL using PyODBC
answer count: 0
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/82606720
has comment: http://stackoverflow.com/comment/82605671
favorite count: 0
has comment: http://stackoverflow.com/comment/82607000
type: Question
has comment: http://stackoverflow.com/comment/84617149
tagged with: sql-server
has comment: http://stackoverflow.com/comment/82608779
has body: I'm trying to connect to a SQL Server using Pypyodbc on Mac and I'm getting the following error: Driver Manager]Can't open lib 'FreeTDS' : file not found (0) (SQLDriverConnect) Below is my code: import pyodbc conn = pyodbc.connect('DRIVER={FreeTDS};DSN=MYMSSQL;UID=&lt;&gt;;PWD=&lt;&gt;') crsr = conn.cursor() rows = crsr.execute("SELECT * FROM transaction_detail_check").fetchall() print(rows) crsr.close() conn.close() odbcinst.ini odbc.ini freetds.conf Can someone please help ? Thanks

http://stackoverflow.com/q/47820259
has body: I have two lists of dictionaries: list_1 = [ {'total': 18, 'lead_status': '2'}, {'total': 18, 'lead_status': '9'}, {'total': 18, 'lead_status': '8'}, {'total': 16, 'lead_status': '15'}, {'total': 17, 'lead_status': '14'} ] list_2 = [ {'total': 18, 'lead_status': '2'}, {'total': 22, 'lead_status': '9'}, {'total': 18, 'lead_status': '8'}, {'total': 16, 'lead_status': '15'}, {'total': 17, 'lead_status': '14'} ] lead_status always have unique value and the order of dictionary in lists might or might not be same. I want to check that for each lead_status the total value is same or not in both lists Example For lead_status : '2' both the lists have same total which is 18 then it returns True For lead_status : '9' both the lists have different total which is 18 in list_1 but 22 in list_2. So it returns False. I have tried the answer in this solution: Comparing 2 lists consisting of dictionaries with unique keys in python Please help to solve this problem. Any help is appreciated.
score: -3
has title: Compare two List of Dictionaries
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/82602900
has comment: http://stackoverflow.com/comment/82602924
has comment: http://stackoverflow.com/comment/82602911
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82602883
tagged with: list
has comment: http://stackoverflow.com/comment/82603410
has comment: http://stackoverflow.com/comment/82603120
has comment: http://stackoverflow.com/comment/82602958
has comment: http://stackoverflow.com/comment/82602893
answer count: 1
downvote count: 3
has answer: http://stackoverflow.com/a/47820519
linked to: http://stackoverflow.com/q/9845369
has comment: http://stackoverflow.com/comment/82603511
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82603067
has comment: http://stackoverflow.com/comment/82602835
accepted answer: http://stackoverflow.com/a/47820519
upvote count: 0

http://stackoverflow.com/a/47714153
has comment: http://stackoverflow.com/comment/82388936
has comment: http://stackoverflow.com/comment/82388435
has body: You can use a list comprehension like this: a_list = '1100' b_list = '0101' # If a value in a_list is '1', remember if the corresponding value in b_list is '1', too [b == '1' for a, b in zip(a_list, b_list) if a == '1'] &gt;&gt; [False, True] and then wrap it in a function whichever way you like: def contains(a_list, b_list): comparison = [b == '1' for a, b in zip(a_list, b_list) if a == '1'] return all(comparison) contains('1100', '0101') &gt;&gt; False contains('0100', '0101') &gt;&gt; True
has comment: http://stackoverflow.com/comment/82388637
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/82388375
answers question: http://stackoverflow.com/q/47713926

http://stackoverflow.com/a/67721225
answers question: http://stackoverflow.com/q/47773178
type: Answer
score: 0
has body: I got the same problem and I came up with a trivial but effective solution, which is basically to use the variance in the gaussian function definition instead of the standard deviation, since the variance is always positive. Then, you get the std_dev by square rooting the variance, obtaining a positive value i.e., the std_dev will always be positive. So, problem solved easily ;) I mean, create the function this way: def gaussian(x, Heigh, Mean, Variance): return Heigh * np.exp(- (x-Mean)**2 / (2 * Variance)) Instead of: def gaussian(x, Heigh, Mean, Std_dev): return Heigh * np.exp(- (x-Mean)**2 / (2 * Std_dev**2)) And then do the fit as usual.

http://stackoverflow.com/comment/82422356
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47723017
type: Comment
has text: I'd like to know (why using bash appeared to fix this for you) too. See https://gist.github.com/charles-dyfis-net/c96e6b4a57c44ced858c414ca4c8c22d for a test case showing your original code (only the paths changed) working correctly (all output-directory files containing content, none of them empty). If you could build a reproducer that worked for others (showcasing the problem), it would certainly help the question make more sense.

http://stackoverflow.com/a/47721117
answers question: http://stackoverflow.com/q/47720421
type: Answer
score: 36
upvote count: 36
downvote count: 0
has comment: http://stackoverflow.com/comment/117475920
has body: Try this: df[df.c.map(len)&gt;1]

http://stackoverflow.com/a/47705262
answers question: http://stackoverflow.com/q/47705172
score: 2
accepted answer of: http://stackoverflow.com/q/47705172
downvote count: 0
has body: Its just like the example below. s="aaawordaaa" if 'word' in s: print('word') else: print("did not find the word") The mistake you were doing is looping through it and which is not required, because you were however looking for continuous appearance of the word "word" In the above example since 'word' is present as a continuous appearance you will get your desired output. Also have a look at basic_tutorial which shall help you understand much more.
upvote count: 2
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/q/47725554
linked to: http://stackoverflow.com/q/16333296
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82414086
tagged with: python
has comment: http://stackoverflow.com/comment/82414189
type: AnsweredQuestion
has body: Is it possible to split variables that have already been assigned values, and re-piece them back together to hold those same previous values? For Example: URLs.QA.Signin = 'https://qa.test.com' TestEnvironment = 'QA' CurrentURL = 'URLs.' + TestEnvironment + '.Signin' print(CurrentURL) Outputs as: 'URLs.QA.Signin' but I would like it to: Output as: 'https://qa.test.com' The purpose is so I can plug in any value to my 'TestEnvironment' variable and thus access any of my massive list of URL's with ease =P I am green with Python. Your time and efforts are greatly appreciated! =) Based upon evanrelf's answer, I tried and loved the following code!: This is exactly what i'm looking for, I might be over complicating it, any suggestions to clean up the code? urls = {} environment = 'qa' district = 'pleasanthill' url = environment + district urls[url] = 'https://' + environment + '.' + district + '.test.com' print(urls[url]) Output is: https://qa.pleasanthill.test.com
score: 0
accepted answer: http://stackoverflow.com/a/47725614
tagged with: variable-variables
answer count: 2
has title: How do I split and reconstruct a variable name while holding its original value
has answer: http://stackoverflow.com/a/47725614
possible better answer: http://stackoverflow.com/a/47725640
linked to: http://stackoverflow.com/q/1373164
has answer: http://stackoverflow.com/a/47725640

http://stackoverflow.com/comment/82531297
has text: I can't access by localhost:8000/index.html but can't access to localhost:8000/report/audiance_overview.html
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47784922
type: Comment

http://stackoverflow.com/comment/82397549
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47718590
has text: You are creating a many to many relationship with that join. Is there a way to relate the bank column in table A to the bank column in table B. Maybe create a column in table A that has those symbols in table B?
type: Comment

http://stackoverflow.com/q/47757437
linked to: http://stackoverflow.com/q/13838405
favorite count: 0
has body: I have a very simple pandas DataFrame with the following format: date P1 P2 day 2015-01-01 190 1132 Thursday 2015-01-01 225 1765 Thursday 2015-01-01 3427 29421 Thursday 2015-01-01 945 7679 Thursday 2015-01-01 1228 9537 Thursday 2015-01-01 870 6903 Thursday 2015-01-02 785 4768 Friday 2015-01-02 1137 7065 Friday 2015-01-02 175 875 Friday where P1 and P2 are different parameters of interest. I would like to create a bar graph that looks like this for each P1 and P2. As shown in the data, I have several values for each day. I would like to average the given values for a given day, then plot against day of week (so that the averaged value for Monday week 1 gets added to Monday week 2, etc.). I'm new to python and my current method is quite nasty, involving several loops. I currently have two dedicated portions of code - one to do the averages and another to go through each day of the week one at a time and tally results for plotting. Is there a cleaner way to do this?
type: Question
accepted answer: http://stackoverflow.com/a/47757461
tagged with: matplotlib
has answer: http://stackoverflow.com/a/47757461
tagged with: python
score: 4
upvote count: 4
type: AnsweredQuestion
tagged with: pandas
downvote count: 0
answer count: 1
has title: Time series data: bin data to each day, then plot by day of week

http://stackoverflow.com/comment/82545264
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47790854
has text: Those are just warnings, so they will not interfere with your results.

http://stackoverflow.com/comment/82376045
has text: Thanks all, I think it is more readable now. The code block really helps.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47707770
score: 0

http://stackoverflow.com/comment/82478332
type: Comment
type: QuestionComment
score: 0
has text: `'stat3': total_stat[info], 'stat2': total_stat[info]`- of course it's the same value
comment on: http://stackoverflow.com/q/47758510

http://stackoverflow.com/comment/82570268
type: Comment
has text: @Olaf I'm not denying that, and I fully understood your comment, I repeat, I was merely suggesting what they were trying to comment, not agreeing with it
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47791378

http://stackoverflow.com/a/47734912
has comment: http://stackoverflow.com/comment/82430448
has comment: http://stackoverflow.com/comment/82430335
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/82430324
accepted answer of: http://stackoverflow.com/q/47734823
answers question: http://stackoverflow.com/q/47734823
has body: You can bind values to arbitrary attributes on the Button object. Then you can retrieve that value using an attribute lookup. Also, it would be better to use the seating plan held in the seats list to create the buttons. You can use enumerate() to help iterate over the values while still having access to the indices that you need for the grid: import tkinter as tk seats= [["A", "a1", "a2", "a3", "a4", "a5"], ["B", "b1", "b2", "b3", "b4", "b5"], ["C", "c1", "c2", "c3", "c4", "c5"], ["D", "d1", "d2", "d3", "d4", "d5"]] def make_buttons(): for r, row in enumerate(seats): for c, seat in enumerate(row[1:]): # N.B. skip first element btn = tk.Button(root, text="Empty") btn.name = seat # arbitrary attribute on Button object btn['command'] = lambda c=c, r=r, b=btn:red_click(c, r, b) btn.grid(row=r,column=c) def red_click(c, r, btn): print(btn.name, "clicked!") btn.configure(bg="red") root = tk.Tk() make_buttons() root.mainloop() For many objects Python lets you create "arbitrary" attributes on the object from outside of the class itself. E.g. class C: pass &gt;&gt;&gt; c = C() &gt;&gt;&gt; c.whatever Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: C instance has no attribute 'whatever' &gt;&gt;&gt; c.whatever = 'hi there' &gt;&gt;&gt; c.whatever 'hi there'
type: Answer
has comment: http://stackoverflow.com/comment/82430490

http://stackoverflow.com/q/47801684
has body: Let me try to improve this question, as it is still valid for me. I have been using Openpyxl to read Excel files for a while. Now I need to extend the capability of my script to handle "legacy" Excel files that are not supported by Openpyxl. For this I use xlrd and xlutils. On issue I have yet to solve is how to get the modified date of an .xls file in the case where I don't have the path. Using Openpyxl, I can get this as Workbook.properties.modified, as a datetime object. With xlrd I am struggling. A workaround would be to figure out the path to the file (which may be input to my function as a file like object) and to use os.path.getmtime, but I am not sure if that is equivalent. Any help is appreciated!
tagged with: python
tagged with: excel
has title: How to get the modified date of an .xls file using xlrd
has comment: http://stackoverflow.com/comment/83340995
tagged with: xlrd
upvote count: 2
score: 1
answer count: 1
has comment: http://stackoverflow.com/comment/83362654
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/83336308
type: Question
has answer: http://stackoverflow.com/a/64975640
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/83363438

http://stackoverflow.com/comment/82591845
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47810186
has text: I understand that in your code you can add `OrderDetail` to `Order`. But I need to update multiple `Order` records.
score: 0

http://stackoverflow.com/comment/82660448
type: QuestionComment
score: 5
has text: Can you fix the indentation?
comment on: http://stackoverflow.com/q/47848114
type: Comment

http://stackoverflow.com/comment/82568290
type: AnswerComment
comment on: http://stackoverflow.com/a/47803387
score: 0
type: Comment
has text: Thanks, I was thinking about using lists except that the practice problem requires an output. The problem can be found here *sigh* https://www.codestepbystep.com/problem/view/python/recursion/count_to_by

http://stackoverflow.com/a/47793107
type: Answer
upvote count: 2
score: 2
accepted answer of: http://stackoverflow.com/q/47792376
has body: You can find any source code at: https://github.com/keras-team/keras Here is the ImageDataGenerator: https://github.com/keras-team/keras/blob/master/keras/preprocessing/image.py/#L374 The keras documentation page also has links that lead you there: https://keras.io/preprocessing/image/ Internally, the ImageDataGenerator will make a series of different data augmentation procedures on images that you provide, and also prepare a python generator for you to use when fitting your models. There are several data augmentation methods to use, you can have an idea of what they are in the help page above. Generators are used to create batches in a loop. In this case, one batch of images at a time. Instead of using model.fit(), you will use model.fit_generator() with either ImageDataGenerator.flow() or ImageDataGenerator.flow_from_directory().
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/105559972
answers question: http://stackoverflow.com/q/47792376
has comment: http://stackoverflow.com/comment/105363083

http://stackoverflow.com/q/47854150
accepted answer: http://stackoverflow.com/a/47854189
has title: How to reuse TCP socket python
type: AnsweredQuestion
score: 2
upvote count: 3
answer count: 2
has comment: http://stackoverflow.com/comment/82672468
tagged with: tcp
tagged with: error-handling
has body: What I want to do I would like to use again sTCP.connect() with a different IP and PORT My problem In the next interaction of while (when I have a different IP and PORT than the last one), I get an Error: "This connection is already in use" What can I do in order to make it work? The socket is declared before the while loop. For clearance I'll only show the while loop: while y != numero_de_lineas: print "Interaccion numero", y if reintentar == 1: print y reintentar = 0 tupla = (str(iplista[y]),int(portlista[y])) sUDP.sendto(mensaje1,tupla) try: if reintentar != 1: #si estoy reintentando no quiero otro timeout sUDP.settimeout(time_out) respuesta1 , address1 = sUDP.recvfrom(BUFFER_SIZE) #si todo va bien tengo respuesta1 #print(respuesta1) #recibo ni ok ni no if (respuesta1 == "ok") or (reintentar != 1): sTCP.connect((iplista[y],int(portlista[y]))) #SE CONECTA N VECES, HAY QUE ACCEPTAR OTRA CONEXION CON .accept() contenido_fichero = fichero.read() #lo que hay dentro de ./fichero.txt sTCP.send(contenido_fichero) try: sTCP.settimeout(time_out_TCP) #esperamos 10 segundos respuesta2 = sTCP.recv(BUFFER_SIZE) #LIBERAMOS LA CONEXION TCP #print(respuesta2) #recibo transferdone #si recibe respuesta1 y respuesta2 paramos #empezamos con el calculo de la huella con el server aceptado iplista[y],portlista[y] huella_md5 = md5.new() #creamos la huella huella_md5.update(contenido_fichero) #actualicamos su contenido (le podemos meter mas strings despues) huella_md5_calculada = huella_md5.hexdigest() #huella en string sUDP.sendto(huella_md5_calculada,tupla) try: sUDP.settimeout(time_out_TCP) #porque son 10 segundos respuesta3 , address3 = sUDP.recvfrom(BUFFER_SIZE) if respuesta3 == "md5sum ok": print "Copia de fichero en servidor",iplista[y],"correcta" if respuesta3 == "md5sum error": print "Error en la copia del fichero en el servidor",iplista[y],"Se vuelve a intentar" #REINTENTAR reintentar = 1 except socket.timeout: print "Error en la copia del fichero en el servidor",iplista[y],". F…
has answer: http://stackoverflow.com/a/47854189
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47854229
possible better answer: http://stackoverflow.com/a/47854229
tagged with: sockets
tagged with: python

http://stackoverflow.com/q/47710698
tagged with: move
has comment: http://stackoverflow.com/comment/82382208
tagged with: zelle-graphics
score: 0
answer count: 1
upvote count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/47763167
favorite count: 0
type: Question
type: UnansweredQuestion
has title: Why object won't stop moving in Zelle graphics?
tagged with: python
has comment: http://stackoverflow.com/comment/82456846
has body: from graphics import * win = GraphWin("Circle Race", 500, 500) #red circle position RcenterX = 50 RcenterY = 100 Rright = RcenterX+25 Rleft = RcenterY # The Red circle cr = Circle(Point(RcenterX,RcenterY), 25) cr.setFill('red') cr.setOutline('black') cr.draw(win) if RcenterX&lt;=400: win.getMouse() cr.move(50 ,0) elif RcenterX&gt;300: win.getMouse() win.close() I'm trying to move the red circle 50 pixels after each click, and stop when the right edge of the circle reaches 400. But it keeps moving after it reaches 400? How can I make it stop at 400?

http://stackoverflow.com/comment/82470178
type: QuestionComment
has text: I agree with Tillmann, it would be easy to help you if you could provide a [mcve](https://stackoverflow.com/help/mcve).
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47754131

openembedded
tag name: openembedded
tags question: http://stackoverflow.com/q/47770891
type: Tag

http://stackoverflow.com/a/47774113
answers question: http://stackoverflow.com/q/47773912
has comment: http://stackoverflow.com/comment/82509282
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/47773912
has body: The problem is that in the first case you are overriding names[report_id] on this line: names[report_id] = {'name': item['_id'].get('name','')} Let's follow the 5a27cda63fff647c33a14b31 item in the names dictionary: On the first iteration of the loop, you are setting the value of names[report_id]: {'5a27cda63fff647c33a14b31': {'name': ''}} Then, since the amount is 3000, the dictionary is updated to: {'5a27cda63fff647c33a14b31': {'name': '', 'amount': 3000}} Then, on the second iteration of the loop, the dictionary is completely overridden leading to losing the amount value altogether: {'5a27cda63fff647c33a14b31': {'name': 'sriram sathyan'}} Use the debugger to follow the execution line by line, watch how the names dictionary changes.
type: AcceptedAnswer
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/47836097
score: 0
has body: I am working on a unstructured data, there are data coming from a tool equipment. There is lot of noise in the data by having extra columns with no information. For example, I am getting the data for the past 7 days in 7 different files, I need to drop same number or set of columns from all these 7 files. I believe there is a better and efficient way to drop columns of these 7 files. I appreciate if you could take a look at my code and suggest me a way to drop or select only the required columns efficiently. This is what I have tried so far, df1.drop(df1.columns[[4,9,10,11,12,13, 14, 15, 16, 17, 18, 19, 20, 21, 22,23, 25, 28, 30,32, 31, 33]], axis=1, inplace=True) df2.drop(df2.columns[[4,9,10,11,12,13, 14, 15, 16, 17, 18, 19, 20, 21, 22,23, 25, 28, 30,32, 31, 33]], axis=1, inplace=True) df3.drop(df3.columns[[4,9,10,11,12,13, 14, 15, 16, 17, 18, 19, 20, 21, 22,23, 25, 28, 30,32, 31, 33]], axis=1, inplace=True) df4.drop(df4.columns[[4,9,10,11,12,13, 14, 15, 16, 17, 18, 19, 20, 21, 22,23, 25, 28, 30,32, 31, 33]], axis=1, inplace=True) df5.drop(df5.columns[[4,9,10,11,12,13, 14, 15, 16, 17, 18, 19, 20, 21, 22,23, 25, 28, 30,32, 31, 33]], axis=1, inplace=True) df6.drop(df6.columns[[4,9,10,11,12,13, 14, 15, 16, 17, 18, 19, 20, 21, 22,23, 25, 28, 30,32, 31, 33]], axis=1, inplace=True) df7.drop(df7.columns[[4,9,10,11,12,13, 14, 15, 16, 17, 18, 19, 20, 21, 22,23, 25, 28, 30,32, 31, 33]], axis=1, inplace=True)
accepted answer: http://stackoverflow.com/a/47836271
type: Question
has answer: http://stackoverflow.com/a/47836271
answer count: 2
possible better answer: http://stackoverflow.com/a/48231147
has answer: http://stackoverflow.com/a/48231147
tagged with: dataframe
tagged with: python
has title: Drop or select columns from multiple pandas dataframe with no headers
type: AnsweredQuestion

http://stackoverflow.com/a/47841162
type: AcceptedAnswer
downvote count: 0
has body: here is a log plot for some dummy values import matplotlib.pyplot as plt import numpy as np j = np.power(10,range(10)) # &lt;--- here use your computed values instead plt.plot(j) plt.yscale('log') plt.show() If you want log-log set the xscale as well.
type: Answer
accepted answer of: http://stackoverflow.com/q/47841088
score: 2
answers question: http://stackoverflow.com/q/47841088
upvote count: 2

http://stackoverflow.com/comment/82710844
type: Comment
comment on: http://stackoverflow.com/a/47834350
type: AnswerComment
score: 0
has text: dear @atambo , thanks for your commend. yes, agreed, the spelling of our qopts are slightly different. But they all generate the same response which seemly not correct. Using the API on IBM Watson discover news demo site, the return is simply like { "sentiment": { "type": "term", "field": "enriched_text.sentiment.document.label", "results": [....}, while using the python SDK as we discussed, the return is quite meaningless. I guess my question should be specified as How to get the "filter" and "aggregation" work correctly? Truly hope someone can show me a correct sample. Thanks.

http://stackoverflow.com/comment/82444694
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47741486
has text: It seems it's better to stick with https://github.com/denisenkom/django-sqlserver today

http://stackoverflow.com/a/47758843
score: 4
upvote count: 4
answers question: http://stackoverflow.com/q/47758810
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47758810
has body: Use a regex. &gt;&gt;&gt; import re &gt;&gt;&gt; re.search(r'\bor\b', 'or') &lt;_sre.SRE_Match object at 0x7f445333a5e0&gt; &gt;&gt;&gt; re.search(r'\bor\b', 'for') &gt;&gt;&gt;
type: Answer

http://stackoverflow.com/a/47772587
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/82507522
has comment: http://stackoverflow.com/comment/82506296
has body: For windows only: from tkinter import * import ctypes hllDll = ctypes.WinDLL ("User32.dll") VK_CAPITAL = 0x14 def get_capslock_state(): return hllDll.GetKeyState(VK_CAPITAL) def on_focus(event): if (get_capslock_state()): print("Caps lock is on") root = Tk() root.geometry("400x400") e1 = Entry(root, width=40) e1.focus() e1.pack() e2 = Entry(root, width=40) e2.place(x=70, y=100) e2.bind("&lt;FocusIn&gt;", on_focus) root.mainloop()
answers question: http://stackoverflow.com/q/47772051

http://stackoverflow.com/q/47722353
accepted answer: http://stackoverflow.com/a/47722405
upvote count: 7
has answer: http://stackoverflow.com/a/47722405
score: 4
possible better answer: http://stackoverflow.com/a/62099736
has comment: http://stackoverflow.com/comment/82405304
has body: I've seen Python programs using import warnings How to install that package? I tried pip install --upgrade warnings and got an error Collecting warnings Could not find a version that satisfies the requirement warnings (from versions: ) No matching distribution found for warnings
type: Question
has answer: http://stackoverflow.com/a/62099736
type: AnsweredQuestion
has title: How to install 'warnings' package in Python?
downvote count: 3
tagged with: python
favorite count: 0
answer count: 2
tagged with: package

http://stackoverflow.com/q/47802680
answer count: 0
upvote count: 3
downvote count: 0
has body: I want to extract a docstring from every function in a python module. Thought, help does the intended action, It would print out a lot of extra stuff which I do not need. I have tried .__ doc__ as well. However, Even that does print out a lot of stuff and also print \n and \t. eg. def Foo(): """ This is a multiline comment """ pass: I want something which will give me only the comment as a single line or in the specified format as is. &gt;&gt;&gt; print (some operation on foo) &gt;&gt;&gt; "This is a multiline comment" &gt;&gt;&gt; How do I remove of all the extra stuff. Greater picture: I have a module with a search function to find all functions and I want to display their descriptions along with functions &gt;&gt;&gt; find('*', maths) # suppose maths is a module &gt;&gt;&gt; shapes.square "This is square" shapes.cube "This is cube" P.S I already have the find function I just need the string to append in the print statement. Thnaks
linked to: http://stackoverflow.com/q/713138
has comment: http://stackoverflow.com/comment/82566806
has comment: http://stackoverflow.com/comment/82567263
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82567128
has title: Extract docstring from a python function
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/82567254
has comment: http://stackoverflow.com/comment/82566963
has comment: http://stackoverflow.com/comment/82566871
score: 3
has comment: http://stackoverflow.com/comment/82567332

http://stackoverflow.com/q/47848405
has body: I need to send 1-byte number to server through socket in server-client architecture. 1) How can I convert integer object to 1-byte number (0..255 or -127..127) 2) This code gives me 14, so that means integer object takes 14 bits? import sys x = 2 print (sys.getsizeof(x)) 3) I would appreciate some website links connected with data conversion in Python
has comment: http://stackoverflow.com/comment/82661162
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/47848465
possible better answer: http://stackoverflow.com/a/47848475
downvote count: 1
has title: Sending 1-byte number to server
has answer: http://stackoverflow.com/a/47848475
favorite count: 0
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/47848465
upvote count: 1
has comment: http://stackoverflow.com/comment/82661222
has comment: http://stackoverflow.com/comment/82661074
tagged with: python

http://stackoverflow.com/comment/82495854
has text: @alvas thank you for reply. I did it in word2vec and using k-means clustering. I will give a try using synset distance to see how results are different from word2vec...
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47757435

http://stackoverflow.com/q/47737029
upvote count: 1
has title: Python : How to make the 'end' keyword argument in print function to stop functioning for this purpose
score: 1
has answer: http://stackoverflow.com/a/47737040
favorite count: 0
has body: I'm a code newbie so my vocabulary might be way off. I'm using python 3.6.3 on OS X 10.10.5 I'm trying to make a function that takes a list like this: grid = [[ '.', '0'], [ '.', '0'], [ '.', '0']] and print out : ... 000 Here's my code: grid = [['.', '0'], ['.', '0'], ['.', '0']] def spam(eggs): for i in range(len(eggs)): print(eggs[i][0], end='') for i in range(len(eggs)): print(eggs[i][1], end='') spam(grid) I thought that the result would be ... 000 because print(eggs[i][0], end='') print ... in line 1 and print(eggs[i][1], end='') print 000 in line 2. But the actual result is ...000 I think its because the keyword argument end='' is still at work when the execution is going for print(eggs[i][1], end='') after printing print(eggs[i][0], end=''). The problem is that I don't know how to make the keyword argument end='' in print(eggs[i][0], end='') effect to dissappear after ... was printed. How do you do that?
type: Question
answer count: 2
downvote count: 0
accepted answer: http://stackoverflow.com/a/47737040
tagged with: python
possible better answer: http://stackoverflow.com/a/47737064
has answer: http://stackoverflow.com/a/47737064
type: AnsweredQuestion

http://stackoverflow.com/comment/82654695
has text: possibly using `string.punctuation` from the `string` module. `string.punctuation[23]` is a backslash.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47844946
score: 0

http://stackoverflow.com/q/47776318
has comment: http://stackoverflow.com/comment/82772692
possible better answer: http://stackoverflow.com/a/47777837
has answer: http://stackoverflow.com/a/47778106
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47778640
has comment: http://stackoverflow.com/comment/82773239
has comment: http://stackoverflow.com/comment/82747466
upvote count: 9
tagged with: matplotlib
tagged with: python
answer count: 4
has answer: http://stackoverflow.com/a/47777837
score: 9
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47781021
has title: Plotting a 2d numpy array with custom colors
has body: I have a 2d numpy array that I want to plot so I can see how each category is positioned on the grid. The matrix (mat) looks something like this: 156 138 156 1300 137 156 138 138 1300 137 137 137 I plotted this as follows: plt.imshow(mat, cmap='tab20', interpolation='none') However, I want to have custom colors. I have a csv where the id's correspond with the values in the matrix: id,R,G,B 156,200,200,200 138,170,255,245 137,208,130,40 1300,63,165,76 Is there a way I can have the values in the matrix correspond with the R, G, B values in the csv file? Edit: someone asked for a clarification but the entire answer was deleted. each row has an ID and a 3 columns, representing the respective R, G, and B values. So the first row has ID 156 (a domain specific code) with R 200, G 200 and B 200 (which is grey). Now I have a 2d matrix that I want to plot, and on each coordinate where the value is 156 I want that pixel to be grey. Same with ID 1300, where the colors 63, 165, and 76 represent a green color that I want to use in the matrix.
has comment: http://stackoverflow.com/comment/82770865
accepted answer: http://stackoverflow.com/a/47778106
downvote count: 0

http://stackoverflow.com/comment/82485421
comment on: http://stackoverflow.com/a/47761993
type: Comment
has text: Fun stuff, we got the same idea xD
score: 0
type: AnswerComment

http://stackoverflow.com/a/47777546
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47775624
downvote count: 0
answers question: http://stackoverflow.com/q/47775624
score: 1
has comment: http://stackoverflow.com/comment/82558683
has comment: http://stackoverflow.com/comment/82535699
type: Answer
has comment: http://stackoverflow.com/comment/82547793
has comment: http://stackoverflow.com/comment/82539180
has body: You could add a 'missing_key' counter and increment it for each missing key. return a tuple of (missing_keys, fields) and they'll get sorted at the end with the most missing keys going last. def sort_func(sort_by, listObj): missing_keys = 0 fields = [] for key in sort_by: if key in listObj: fields.append(listObj[key]) else: missing_keys += 1 return missing_keys, fields edit: request for detailed explanation tuples(and lists) sort as follows: compare first elements. If first elements aren't equal, use that comparison, else compare 2nd elements etc.... an empty tuple/list is always less than one with elements. so: lst = [ (), (10,), (1, []), (2, [10, 11]), (2, [100]), (0, [10, 9, 8]), (0, [11]), (1, [1, 1, 2]) ] print(sorted(lst)) prints: [ (), (0, [10, 9, 8]), (0, [11]), (1, []), (1, [1, 1, 2]), (2, [10, 11]), (2, [100]), (10,) ] This sort_func returns a tuple. If the first element (missing_keys) is equal, it's evaluated by the next element (fields). But it first sorts by the number of missing keys.
upvote count: 1

http://stackoverflow.com/comment/82410695
has text: Your query should be `INSERT INTO saferdb_question( "DOT_Number") VALUES('1234')` Here column name should be exactly same as in the `create table` statement. PS: Do not use double quotes in DDL statement to avoid such problems.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47723790

http://stackoverflow.com/comment/82731045
comment on: http://stackoverflow.com/a/47868651
score: 0
type: Comment
has text: Sorry, there was a mistake in my reply, you should actually use sequence number 101 on the first data frame, not 102 - since ACK packets do not contain payload (I've corrected the mistake). Using that I do get a reply (301 redirect) from the server. So the code works. Of course the server never gets an ACK or connection shutdown so it keeps re-trying to send the response for a while. I hope your question was not an attempt to use SO users to DDoS the site :)
type: AnswerComment

http://stackoverflow.com/a/47770591
has body: I solved it by including following additional code. Though still my code seems to me a bit inefficient. #Additional blocks of code for getting validation set cost. cv_costs_post_train=[] beta = 0.5 (n_x_cv, m_cv) = cv_x.shape n_y_cv = cv_y.shape[0] ............ ............. ........... ........... if print_cost == True and epoch % 100 == 0: print ("Train Cost after epoch %i: %f" % (epoch, epoch_cost)) X_cv, Y_cv,keep_prob_cv= create_placeholders(n_x_cv, n_y_cv) Z_cv = forward_propagation(X_cv, parameters, keep_prob_cv) cv_cost_post_train = compute_cost(Z_cv,Y_cv) cv_cost_post_train = sess.run([cv_cost_post_train ], feed_dict={X_cv: cv_x, Y_cv: cv_y, keep_prob_cv:1}) print (cv_cost_post_train) if print_cost == True and epoch % 5 == 0: costs.append(epoch_cost) cv_costs_post_train.append(cv_cost_post_train) .... .... .... .... The full code for model is as under. def model(X_train, Y_train,cv_x, cv_y, layers_dims,learning_rate = 0.0001, num_epochs = 2000, minibatch_size = 32, print_cost = True): ops.reset_default_graph() tf.set_random_seed(1) seed = 3 (n_x, m) = X_train.shape n_y = Y_train.shape[0] costs = [] cv_costs_post_train=[] beta = 0.5 (n_x_cv, m_cv) = cv_x.shape n_y_cv = cv_y.shape[0] ########################################################################### ############################################################################################### # Create Placeholders of shape (n_x, n_y) ### START CODE HERE ### (1 line) X, Y,keep_prob= create_placeholders(n_x, n_y) ### END CODE HERE ### # Initialize parameters ### START CODE HERE ### (1 line) parameters = initialize_parameters(layers_dims) ### END CODE HERE ### # Forward propagation: Build the forward propagation in the tensorflow graph ### START CODE HERE ### (1 line) Z = forward_propagation(X, parameters, keep_prob) ### END CODE HERE ### # Cost function: Add cost function to tensorflow graph ### START CODE HERE ### (1 line) cost = compute_cost(Z, Y) L3=len(layers_dims) regularizers=tf.constant(0,dtype…
answers question: http://stackoverflow.com/q/47767294
score: 0
type: Answer

terminal-emulator
tag name: terminal-emulator
type: Tag
tags question: http://stackoverflow.com/q/47843644

http://stackoverflow.com/comment/82558382
comment on: http://stackoverflow.com/q/47793192
type: Comment
has text: Yes,it's running now @suit.Thank you
score: 0
type: QuestionComment

http://stackoverflow.com/comment/82390939
has text: What have you tried so far, and where are you stuck?
comment on: http://stackoverflow.com/q/47715428
score: 2
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82451612
has text: It is unclear under what context you are receiving this `Unresolved attribute reference`.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47745704

http://stackoverflow.com/a/47798134
answers question: http://stackoverflow.com/q/47795001
accepted answer of: http://stackoverflow.com/q/47795001
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82557201
downvote count: 0
has body: I'd do it this way: In [24]: idx = pd.MultiIndex.from_product(( example.index.get_level_values(0).unique(), example.index.get_level_values(1).unique())) In [25]: example = example.reindex(idx).ffill() In [26]: example Out[26]: value US 2017-12-10 12.2 2017-12-11 12.5 2017-12-12 12.6 EU 2017-12-10 15.1 2017-12-11 15.1 2017-12-12 15.0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/82557267
type: Answer
has comment: http://stackoverflow.com/comment/82557240

http://stackoverflow.com/comment/82432141
type: Comment
comment on: http://stackoverflow.com/q/47730944
type: QuestionComment
score: 0
has text: @Gary02127 Sorry for late reply Gary.Network in my location was down. I have tried with multiple pdf but same error.However, I have edited the question with sample PDF.

http://stackoverflow.com/a/47800366
has comment: http://stackoverflow.com/comment/82562203
upvote count: 7
answers question: http://stackoverflow.com/q/47800200
has comment: http://stackoverflow.com/comment/82562386
score: 7
type: Answer
has comment: http://stackoverflow.com/comment/137363018
accepted answer of: http://stackoverflow.com/q/47800200
has body: Simply use df.loc: import pandas as pd import numpy as np df = pd.DataFrame({'category': ['Cleaning', 'Cleaning', 'Entertainment', 'Entertainment', 'Tech', 'Tech'], 'store': ['Walmart', 'Dia', 'Walmart', 'Fnac', 'Dia','Walmart'], 'price':[11.42, 23.50, 19.99, 15.95, 55.75, 111.55], 'testscore': [np.nan, np.nan, np.nan, np.nan, np.nan, np.nan]}) cats = pd.Series(df['category'][:3]) # 3 elements df.loc[:3,'testscore'] = cats # Assign first 3 print(df) And you get: category price store testscore 0 Cleaning 11.42 Walmart Cleaning 1 Cleaning 23.50 Dia Cleaning 2 Entertainment 19.99 Walmart Entertainment 3 Entertainment 15.95 Fnac NaN 4 Tech 55.75 Dia NaN 5 Tech 111.55 Walmart NaN
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/47847140
answers question: http://stackoverflow.com/q/47847084
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47847084
type: Answer
has body: You need to include the full path to your executable. E.g., import subprocess subprocess.check_output(['/bin/echo', 'hello']) (Not sure precisely where it is on Windows, though.) Note: Using shell=True will also make it happen to work, but I don't recommend solving it that way because (1) your PATH resolution will effectively be a side-effect (you'll have a hidden dependency on the value of PATH at runtime), and (2) there are security concerns.
upvote count: 11
score: 11
has comment: http://stackoverflow.com/comment/96932713

http://stackoverflow.com/q/47804120
upvote count: 14
has title: AttributeError: __enter__ from "with tf.Session as sess:"
answer count: 1
score: 13
downvote count: 1
tagged with: tensorflow
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47804199
has body: So, this might be a dumb or obvious question but bear with me. I'm a mathematics student, and I'm in my final year and have been learning to work with neural nets for fun. I am no programmer so errors are something I encounter frequently. Usually I can sort them out, today however I received one I just can't figure out. When I attempt to execute my code I get an error saying: "Traceback (most recent call last): File "C:\Python Practice\gan.py", line 93, in &lt;module&gt; n() File "C:\Python Practice\gan.py", line 73, in nn with tf.Session as sess: AttributeError: __enter__ The code from line 72 until the end looks like: def network_run(): with tf.Session as sess: sess.run(tf.global_variables_initializer()) for i in range(200): sess.run(opt_D, feed_dict={x_ten: images[np.random.choice(range(len(images)), batch_size)].reshape(batch_size, x_ten_size), z_ten:z_noise(batch_size)}) sess.run(opt_G, feed_dict={z_ten:z_noise(batch_size)}) sess.run(opt_G, feed_dict={z_ten:z_noise(batch_size)}) gen_cost=sess.run(G_img, feed_dict={z_ten:z_noise(batch_size)}) disc_cost=sess.run(D_img, feed_dict={x_ten: images[np.random.choice(range(len(images)), batch_size)].reshape(batch_size, x_ten_size), z_ten:z_noise(batch_size)}) image=sess.run(G(z_ten), feed_dict={z_ten:z_noise(batch_size)}) df=sess.run(tf.sigmoid(D_img_fake), feed_dict={z_ten:z_noise()}) print (i, gen_cost, disc_cost, image.max(), df[0][0]) image=sess.run(G(z_ten), feed_dict={z_ten:z_noise(batch_size)}) image1 = image[0].reshape([28, 28]) im = Image.fromarray(image1) im.show() network_run() Thanks in advance to anyone who helps this blubbering fool out- Max
type: UnansweredQuestion
tagged with: neural-network
tagged with: python

http://stackoverflow.com/q/47819741
type: Question
upvote count: 4
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82601526
has comment: http://stackoverflow.com/comment/82601708
has comment: http://stackoverflow.com/comment/82601635
possible better answer: http://stackoverflow.com/a/47819975
has comment: http://stackoverflow.com/comment/82601888
has comment: http://stackoverflow.com/comment/82604661
downvote count: 0
tagged with: python
has answer: http://stackoverflow.com/a/47819923
has answer: http://stackoverflow.com/a/47819975
score: 4
has comment: http://stackoverflow.com/comment/82601916
has answer: http://stackoverflow.com/a/47820011
tagged with: class
accepted answer: http://stackoverflow.com/a/47820097
type: AnsweredQuestion
has body: Is it possible to not create an object if certain conditions are not met in the constructor of a class? E.g.: class ABC: def __init__(self, a): if a &gt; 5: self.a = a else: return None a = ABC(3) print(a) This should print None (since it should not create an Object but return None in this case) but currently prints the Object...
has answer: http://stackoverflow.com/a/47820097
has title: Not creating an object when conditions are not met in python?
linked to: http://stackoverflow.com/q/3860469
has comment: http://stackoverflow.com/comment/82606441
has comment: http://stackoverflow.com/comment/82601855
answer count: 4
has comment: http://stackoverflow.com/comment/82601561
favorite count: 0

http://stackoverflow.com/comment/82360794
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47700024
has text: Our duplicates are mostly asked by people on Macs, but they reflect the same misunderstanding.
score: 0

http://stackoverflow.com/a/47792742
answers question: http://stackoverflow.com/q/47792429
type: Answer
score: 0
has body: Using list: x = [] with open('master.sql', 'r') as f: for line in f.readlines(): x.append(line.split('.')[0]) with open('databases.sql', 'w') as f: for word in x: f.write(str(word)+'\n')

http://stackoverflow.com/comment/82519977
type: Comment
has text: It looks like the choices made depend only on the last two digits of the page URLs. Is that correct, and if so what is their range of value (`00` to `99`)?
score: 0
comment on: http://stackoverflow.com/q/47779071
type: QuestionComment

http://stackoverflow.com/q/47802592
has answer: http://stackoverflow.com/a/47803286
type: Question
tagged with: python-3.x
has body: I have a huge csv file of data, it looks like this: STAID, SOUID, DATE, TX, Q_TX 162,100522,19010101, -31, 0 162,100522,19010102, -13, 0 TX is temperature, data goes on for a few thousand more lines to give you an idea. For every year, I want to plot the amount of days with a temperature above 25 degrees. import pandas as pd import matplotlib.pyplot as plt data = pd.read_csv("klimaat.csv") zomers = data.index[data["TX"] &gt; 250].tolist() x_values = [] y_values = [] plt.xlabel("Years") plt.ylabel("Amount of days with TX &gt; 250") plt.title("Zomerse Dagen Per Jaar") plt.plot(x_values, y_values) # save plot plt.savefig("zomerse_dagen.png") X-axis should be the years say 1900-2010 or something, and the y-axis should be the amount of days with a temperature higher than 250 in that year. How do I go about this? >_&lt; I can't quite get a grasp on how to extract the amount of days from the data.... and use it in a plot.
has title: Python plot amount of x values in data
answer count: 2
type: UnansweredQuestion
tagged with: python
score: 0
has answer: http://stackoverflow.com/a/47803321
tagged with: pandas
tagged with: matplotlib

http://stackoverflow.com/q/47833097
has answer: http://stackoverflow.com/a/47833771
type: Question
possible better answer: http://stackoverflow.com/a/47833642
downvote count: 0
has answer: http://stackoverflow.com/a/47833642
tagged with: python
has title: How to remove a certain character after the extraction of a part, using python
has body: I have text file, which looks like this: . . . ----------------------- first ATOMIC CHARGES ----------------------- 0 C : -0.157853 1 C : -0.156875 2 C : -0.143714 3 C : -0.140489 4 S : 0.058926 5 H : 0.128758 6 H : 0.128814 7 H : 0.142420 8 H : 0.140013 My charges : -0.0000000 ------------------------ . .. . I used this script below in order to extract a specific part. with open('FILE.txt', 'rb') as f: textfile_temp = f.read() print textfile_temp.split('first ATOMIC CHARGES')[1].split("My charges : -0.0000000")[0] my output is: ----------------------- 0 C : -0.157853 1 C : -0.156875 2 C : -0.143714 3 C : -0.140489 4 S : 0.058926 5 H : 0.128758 6 H : 0.128814 7 H : 0.142420 8 H : 0.140013 my goal is to remove the "-----------------------" character, and my output will be like this: 0 C : -0.157853 1 C : -0.156875 2 C : -0.143714 3 C : -0.140489 4 S : 0.058926 5 H : 0.128758 6 H : 0.128814 7 H : 0.142420 8 H : 0.140013
type: AnsweredQuestion
upvote count: 3
score: 3
has comment: http://stackoverflow.com/comment/82629226
answer count: 3
accepted answer: http://stackoverflow.com/a/47833157
has answer: http://stackoverflow.com/a/47833157
favorite count: 0

http://stackoverflow.com/a/47838569
score: 1
type: Answer
has body: With keeping the original mylist: mylist = ['A', 'B', 'C', 'D', 'E'] for direction in ['Up', 'Down']: for x in mylist: print x + direction if x in ['A', 'C'] else x
answers question: http://stackoverflow.com/q/47838324
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/82466205
score: 0
type: Comment
has text: I'm not sure how you can measure anything with that script, considering there are at least two syntax errors.
type: QuestionComment
comment on: http://stackoverflow.com/q/47749021

http://stackoverflow.com/comment/82702784
comment on: http://stackoverflow.com/a/47827596
score: 0
type: AnswerComment
has text: Using signal's may not work as i need to redirect the user to a diffrent URL.
type: Comment

http://stackoverflow.com/q/47853907
has answer: http://stackoverflow.com/a/47854009
answer count: 4
score: 0
has comment: http://stackoverflow.com/comment/82671935
has answer: http://stackoverflow.com/a/47854068
has answer: http://stackoverflow.com/a/47854298
type: UnansweredQuestion
type: Question
has body: The program, which assesses password strength, initially checks whether the length of the password is correct (6-12) and whether the password contains extented ASCII characters, i.e. 127-255. The problem I have is that if the user first inputs a password which is too short or too long, the program then doesn't check for extended characters in the next password, inputted by the user and vice-versa, with checking for extended characters first. I implemented a double while loop, if that's the correct way of calling it, however it still didn't bring the desired effect. import re import time #score variable, responsible for later defining if passwords is weak, medium or strong Score = 0 #list for improvements to password printed out with score at the end Improvements = [] Password = "" #defines function for checking for presence of extended characters (i.e. ascii 128-255) def hasExtended(s): return any(ord(i) &gt; 127 for i in s) #inputs password Password = input("Please enter a password:") Password_length = len(Password) Extended_presence = hasExtended(Password) #checks password length (6-12), asks user to re-input until password is within boundaries #checks if password contains extended characters #double while loops to allow for two conditions simultaneously while Password_length &lt; 6 or Password_length &gt; 12: if Password_length &lt; 6: Outputted_length = "too short" Outputted_criteria = "no shorter than 6 characters" else: Outputted_length = "too long" Outputted_criteria = "no longer than 12 characters" print("Your password is", Outputted_length, ". It has to be", Outputted_criteria, ".") Password = input("Please enter a password:") Password_length = len(Password) while Extended_presence: print("Your password contains characters from the extended ASCII list. Please don't use these.") Password = input("Please enter a password:") Extended_presence = hasExtended(Password) while Extended_presence: print("Your password contains characters from the extended ASCII list.…
has title: How to replace a double while loop?
tagged with: while-loop
has answer: http://stackoverflow.com/a/47854031
tagged with: python

http://stackoverflow.com/comment/105406270
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47763402
has text: It is a custom one, I have edited the question to include it if you want to use it

http://stackoverflow.com/q/47845980
favorite count: 0
type: Question
type: UnansweredQuestion
score: -2
answer count: 1
tagged with: python
tagged with: calendar
upvote count: 0
tagged with: list
downvote count: 2
has body: I came across this program and got a part of it fixed here, but I ran into another problem. When it prints out the months, the days are not in the correct position, it's missing a whitespace. I need to get the dates with single digit numbers to be under the last letter of the week. For example number 1 under the "r" letter instead of the "F" letter. Thank you for your help. calendar1 = [('January', range(1, 31 + 1)), ('Feburary', range(1, 28 + 1)), ('March', range(1, 31 + 1)), ('April', range(1, 30 + 1)), ('May', range(1, 31 + 1)), ('June', range(1, 30 + 1)), ('July', range(1, 31 + 1)), ('August', range(1, 31 + 1)), ('September', range(1, 30 + 1)), ('October', range(1, 31 + 1)), ('November', range(1, 30 + 1)), ('December', range(1, 31 + 1))] week = ['Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su'] def make_calendar(year, start_day): # Determine current starting position on calendar start_pos = week.index(start_day) for month, days in calendar1: # Print month title print('{0} {1}'.format(month, year).center(20, ' ')) # Print Day headings print(' '.join(['{0:&lt;2}'.format(w) for w in week])) # Add spacing for non-zero starting position print('{0:&lt;3}'.format('')*start_pos, end='') for day in days: # Print day print('{0:&lt;3}'.format(day), end='') start_pos += 1 if start_pos == 7: # If start_pos == 7 (Sunday) start new line print() start_pos = 0 # Reset counter print('\n') yr=int(input('Enter Year')) strtday=input('Enter start day of the year Mo,Tu,We,Th,Fr,Sa,Su') make_calendar(yr,strtday)
has answer: http://stackoverflow.com/a/47853258
has title: Python calendar date missing a whitespace
tagged with: whitespace

http://stackoverflow.com/comment/82456756
score: 0
has text: @juanpa.arrivillaga how would I go about doing that
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47748155

http://stackoverflow.com/comment/82565199
has text: @Topto it seems these fields are only present when you click on the buttons (left & right) but not when you select the dropdown. If you used those field I guess (not tested) that you would need to parse the view state & event validation data for each request (and pass it to subsequent call). I assume the server kind of invalidates the "view" (composed of view state & validation) when you put the next or prev field whereas when you don't specify it, it considers the initial state each time. But that's only a guess
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47801226

http://stackoverflow.com/comment/82586928
score: 2
type: Comment
comment on: http://stackoverflow.com/q/47812858
type: QuestionComment
has text: a[::2] -> [1, 3, 5, 7, 9]

http://stackoverflow.com/q/47737141
has comment: http://stackoverflow.com/comment/82436145
type: Question
has comment: http://stackoverflow.com/comment/82435732
upvote count: 0
has comment: http://stackoverflow.com/comment/82435083
has title: Extracting numbers preceded by words from a txt. file in python
tagged with: extract
has comment: http://stackoverflow.com/comment/82436115
has comment: http://stackoverflow.com/comment/82436631
has comment: http://stackoverflow.com/comment/82435743
score: -2
has comment: http://stackoverflow.com/comment/82435017
has comment: http://stackoverflow.com/comment/82436293
has comment: http://stackoverflow.com/comment/82435834
has comment: http://stackoverflow.com/comment/82436451
has comment: http://stackoverflow.com/comment/82436124
tagged with: python
has answer: http://stackoverflow.com/a/47738117
has comment: http://stackoverflow.com/comment/82434788
has comment: http://stackoverflow.com/comment/82436131
has comment: http://stackoverflow.com/comment/82435869
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82436771
downvote count: 2
has comment: http://stackoverflow.com/comment/82435613
has comment: http://stackoverflow.com/comment/82435439
has comment: http://stackoverflow.com/comment/82435429
has comment: http://stackoverflow.com/comment/82435549
has comment: http://stackoverflow.com/comment/82435452
has comment: http://stackoverflow.com/comment/82436125
answer count: 1
has comment: http://stackoverflow.com/comment/82435374
tagged with: file
has comment: http://stackoverflow.com/comment/82435266
has comment: http://stackoverflow.com/comment/82436596
has comment: http://stackoverflow.com/comment/82435197
accepted answer: http://stackoverflow.com/a/47738117
has comment: http://stackoverflow.com/comment/82435099
has body: I am trying to extract specific numbers from a seperate file after the name of a country. The code does not seem to show any input and I have almost no clue what I am doing. It shows output but only the else where it says either No life Expectancy data or No Gini Data. Here is an example of the file I am extracting from 1: Lesotho :63.2 2: South Africa :62.5 3: Central African Republic :61.3 4: Micronesia, Federated States of :61.1 5: Haiti :60.8 and here is the code I have so far country = [] info = [] def countryFinder(fileName,info): infile = open(fileName, "r") line = infile.readline() for line in infile: fields = line.split(":") country.append(fields[1].strip()) info.append(fields[2].strip()) return country, info userCountry = input("Please enter a country (\"q to quit\"): ") life = countryFinder("life.txt",info) gini = countryFinder("gini.txt",info) while userCountry != "q": if userCountry in life: print (" Life Expectancy is ",life[info]," years at birth") else: print (" No Life Expectancy Data") if userCountry in gini: print (" Gini Value is ",gini[info]) else: print (" No Gini Data") userCountry = input("Please enter a country (\"q to quit\"): ") Software: spyder with python 3.6
has comment: http://stackoverflow.com/comment/82435087
has comment: http://stackoverflow.com/comment/82434876
favorite count: 0

http://stackoverflow.com/a/47846797
has body: You create a call to peer1.obtain() which runs the peer to accept calls from different peers to download the file. However, you try to call peer1.download() from the same peer while it is already listening for incoming calls. You need to separate peer1.download() to run from different peer. You need to revise how Napster FileSharing System works. We are not here to solve your assignment. You seem to have good knowledge with python, the issue is that you do not understand the task good enough. We can help you with understanding its concept, helping you with syntax errors,..,etc.
answers question: http://stackoverflow.com/q/47845812
type: Answer
has comment: http://stackoverflow.com/comment/82657977
has comment: http://stackoverflow.com/comment/82658653
score: 0

http://stackoverflow.com/comment/82447598
score: 0
has text: Why not have a dict inside of a dict? Then your current code would work fine.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47743719

http://stackoverflow.com/comment/82618698
score: 0
type: Comment
has text: I did that but then it doesn't give the grade or print it
type: AnswerComment
comment on: http://stackoverflow.com/a/47828191

http://stackoverflow.com/comment/82682492
comment on: http://stackoverflow.com/a/47854328
type: Comment
type: AnswerComment
score: 0
has text: Then you have to split your environments into linux- and w32-related and include proper `install_command` substitution in every environment. At least I don't see any way around that.

http://stackoverflow.com/q/47816703
has title: MySQL Connector not working with table aliases
tagged with: mysql-connector
answer count: 1
accepted answer: http://stackoverflow.com/a/47816827
has answer: http://stackoverflow.com/a/47816827
type: Question
tagged with: python
has body: I'm using mysql.connector in python script. When I'm trying to execute script that has aliases for tables - it cannot be executed and gives error "unknown column 'column_name' in 'field_list'". Both tables have fields with the same names, so I can't just not use aliases. Code: query = ("SELECT ti.itemno, ti.active FROM text_item AS ti" "INNER JOIN text_itemmember AS tim ON tim.itemno = ti.itemno;") cursor.execute(query) The same error I get when replace alias "ti" on table name ("text_item"). I can't find any information about connector not working with aliases. How do I fix this?
tagged with: mysql-connector-python
has comment: http://stackoverflow.com/comment/82595178
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82595074
score: 0
tagged with: mysql

http://stackoverflow.com/comment/82427782
has text: results['items'][profile]['pagemap']['person'][0] Producing error, KeyError: 0
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47733532
type: Comment

http://stackoverflow.com/comment/82584208
comment on: http://stackoverflow.com/q/47811446
type: Comment
type: QuestionComment
score: 2
has text: You can't have assignments in comprehensions.

http://stackoverflow.com/q/47844947
linked to: http://stackoverflow.com/q/20126475
favorite count: 0
tagged with: python-3.x
score: 3
tagged with: importerror
has answer: http://stackoverflow.com/a/60751818
tagged with: python
type: Question
duplicate of: http://stackoverflow.com/q/20126475
has title: ImportError: No module named '_sqlite3'
upvote count: 3
type: UnansweredQuestion
tagged with: python-3.5
tagged with: sqlite
answer count: 1
downvote count: 0
has body: Whenever I import sqlite3, it gives an import error. Can anyone tell me how to import sqlite3 for python3> I'm using CentOS 6.5 on my vps. Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/local/lib/python3.5/sqlite3/__init__.py", line 23, in <module> from sqlite3.dbapi2 import * File "/usr/local/lib/python3.5/sqlite3/dbapi2.py", line 27, in <module> from _sqlite3 import * ImportError: No module named '_sqlite3'

deconvolution
type: Tag
tags question: http://stackoverflow.com/q/47821287
tag name: deconvolution

http://stackoverflow.com/q/47738145
has answer: http://stackoverflow.com/a/47738355
has answer: http://stackoverflow.com/a/47738475
has comment: http://stackoverflow.com/comment/82437007
type: Question
has body: I am using python error handling instructions. In my script I have some try blocks were some temporary variables are used, it similarly holds for the except blocks. I would like to use the del statement (or something similar) within a finally block to clean out all the vars created within the try and except ones. The problem is that I don't know exactly a priori which are the created ones since I don't know whether the program will possibly fail. Is there an elegant way to get it? Thanks in advance
has comment: http://stackoverflow.com/comment/82436505
answer count: 2
tagged with: python
has title: using finally: to remove temporary variables defined in try: except: block
possible better answer: http://stackoverflow.com/a/47738475
accepted answer: http://stackoverflow.com/a/47738355
type: AnsweredQuestion
score: 0

multiple-instances
tags question: http://stackoverflow.com/q/47708608
tag name: multiple-instances
type: Tag

http://stackoverflow.com/comment/82431917
comment on: http://stackoverflow.com/q/47735622
has text: @tiao can you please tell me how do I do that?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47767629
tagged with: python
has title: Django add brackets to django models field
downvote count: 6
has answer: http://stackoverflow.com/a/47767685
has comment: http://stackoverflow.com/comment/82496392
has body: I was trying to add brackets to my django fields how to do it Only with brackets there is syntax error models.py class Customer(models.Model): name = models.CharField(max_length=1000) Region =models.CharField(max_length=1000,choices=Region, default='-') Status =models.CharField(max_length=1000,choices=Option, null=True) APP_SERVER\(Prod\)=models.CharField(max_length=1000,blank=True, null=True)
has comment: http://stackoverflow.com/comment/82496909
score: -6
has comment: http://stackoverflow.com/comment/82496364
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82540135
upvote count: 0
type: UnansweredQuestion
answer count: 1
tagged with: django

http://stackoverflow.com/comment/82472115
comment on: http://stackoverflow.com/q/47755312
has text: Is your TIFF image a single frame? Also, you could try using `image.thumbnail((200, 200), Image.ANTIALIAS)`
type: Comment
score: 1
type: QuestionComment

http://stackoverflow.com/a/47724780
accepted answer of: http://stackoverflow.com/q/47724740
score: 5
answers question: http://stackoverflow.com/q/47724740
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82410498
upvote count: 5
type: Answer
has body: Concrete example (in Python 3.4.4 shell): &gt;&gt;&gt; int(99999999999999999/100000000000000000) 1 &gt;&gt;&gt; 99999999999999999//100000000000000000 0 This happens when the result of the (mathematical) float division is very near to an integer so that the numerical float division result is rounded towards this integer.
has comment: http://stackoverflow.com/comment/82410736

http://stackoverflow.com/comment/82525224
type: QuestionComment
has text: See here https://stackoverflow.com/questions/12570859/how-to-show-pil-images-on-the-screen
type: Comment
comment on: http://stackoverflow.com/q/47776176
score: 0

http://stackoverflow.com/comment/82599289
type: QuestionComment
comment on: http://stackoverflow.com/q/47817800
score: 0
has text: @D-Ru yes, use `f.close()` at the end. It is information for Python or system to send on disk all data which can still be in buffer in memory RAM.
type: Comment

http://stackoverflow.com/q/47846345
has comment: http://stackoverflow.com/comment/82658893
has comment: http://stackoverflow.com/comment/82656759
linked to: http://stackoverflow.com/q/24560298
has comment: http://stackoverflow.com/comment/82656730
score: 0
tagged with: matrix
tagged with: math
has body: im trying to solve the task starting on page 9 with method 2 http://www.math.ucla.edu/~baker/149.1.02w/handouts/dd_splines.pdf My code: import numpy as np from numpy.linalg import inv s0=[1,-1] s1=[-1,2] s2=[1,4] s3=[4,3] s4=[7,5] M=inv(np.array([[4,1,0],[1,4,1],[0,1,4]])) C=np.array([(np.dot(6,s1)-s0), np.dot(6,s2),(np.dot(6,s3)-s4) ]) print np.dot(M*C) Traceback (most recent call last): File "C:/Users/john/Desktop/testint.py", line 16, in print np.dot(M*C) ValueError: operands could not be broadcast together with shapes (3,3) (3,2) So my simple question is how is this done in correct way?
has title: Matrix multiplication with Numpy different size
type: Question
tagged with: numpy
answer count: 0
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/47780834
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47864799
has title: Adding CSS style to table in django with django_tables2
has body: I'm very new to Django. I'm trying to add a CSS style to a table when {% render_table table %} is being run. The code looks as following: views.py: def myTable(request): table = myDataTable.objects.all() filter = request.GET.get('q') startDate = request.GET.get('sd') endDate = request.GET.get('ed') if mail: table = table.filter(Q(filter__icontains=filter) &amp; Q(evaluation_date__range=[startDate, endDate])).distinct() else: table = table.filter(Q(evaluation_date__range=[startDate, endDate])).distinct() table = TableView(table) RequestConfig(request).configure(table) return render(request, 'myapp/myTable.html', {'table': table}) tables.py: class TableView(tables.Table): class Meta: model = myDataTable template = 'django_tables2/bootstrap.html' myApp.html {% load staticfiles %} {% load render_table from django_tables2 %} .... &lt;link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" /&gt; &lt;link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css"&gt; .... &lt;body&gt; {% render_table table %} In project/static/css/ I have a custom style file customstyle.css, but there is no way to make the rendered table use that style. Could you please help me?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82646889
tagged with: python
has comment: http://stackoverflow.com/comment/82634863
score: 3
answer count: 2
upvote count: 3
has answer: http://stackoverflow.com/a/67273431
downvote count: 0
tagged with: django
tagged with: django-tables2
favorite count: 0

http://stackoverflow.com/comment/82600290
has text: Your question is very important. It will become clearer if you can provide example code of manipulation of a column of a data.frame so that one can see how best to accomplish the same thing with python pandas dataframe.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47819024

http://stackoverflow.com/comment/82528427
comment on: http://stackoverflow.com/q/47783480
score: 0
type: QuestionComment
has text: python print inserts a new line by default. You can disable it
type: Comment

http://stackoverflow.com/q/47743737
tagged with: sql
tagged with: sqlite
answer count: 1
type: Question
has body: I am trying to iterate through a .json list. I want to create separate entries in SQLite3 for each of these three sub-lists in 'data'. data = {u'symbols':[{u'optionType': None, u'dividendDate': u'2017-12-29T00:00:00.000000-05:00', u'eps': 2.79, u'currency': u'CAD', u'prevDayClosePrice': 32.41, u'averageVol3Months': 579272, u'industrySubgroup': u'InsuranceLife', u'isTradable': True, u'hasOptions': True, u'optionDurationType': None, u'optionExpiryDate': None, u'symbolId': 32304, u'outstandingShares': 415289000, u'tradeUnit': 1, u'optionStrikePrice': None, u'pe': 11.62, u'lowPrice52': 28.4, u'industrySector': u'FinancialServices', u'optionRoot': u'', u'description': u'POWER CORP OF CDA SV', u'symbol': u'POW.TO', u'securityType': u'Stock', u'dividend': 0.3585, u'minTicks': [{u'pivot': 0, u'minTick': 0.005}, {u'pivot': 0.5, u'minTick': 0.01}], u'averageVol20Days': 506545, u'industryGroup': u'InsuranceLife', u'optionContractDeliverables': {u'cashInLieu': 0, u'underlyings': []}, u'highPrice52': 33.69, u'yield': 4.43, u'listingExchange': u'TSX', u'isQuotable': True, u'optionExerciseType': None, u'marketCap': 13459516489, u'exDate': u'2017-12-07T00:00:00.000000-05:00'}, {u'optionType': None, u'dividendDate': u'2018-02-01T00:00:00.000000-05:00', u'eps': 2.95, u'currency': u'CAD', u'prevDayClosePrice': 35.28, u'averageVol3Months': 394431, u'industrySubgroup': u'InsuranceLife', u'isTradable': True, u'hasOptions': True, u'optionDurationType': None, u'optionExpiryDate': None, u'symbolId': 32316, u'outstandingShares': 713871000, u'tradeUnit': 1, u'optionStrikePrice': None, u'pe': 11.96, u'lowPrice52': 31.75, u'industrySector': u'FinancialServices', u'optionRoot': u'', u'description': u'POWER FINANCIAL CP', u'symbol': u'PWF.TO', u'securityType': u'Stock', u'dividend': 0.4125, u'minTicks': [{u'pivot': 0, u'minTick': 0.005}, {u'pivot': 0.5, u'minTick': 0.01}], u'averageVol20Days': 396594, u'industryGroup': u'InsuranceLife', u'optionContractDeliverables': {u'cashInLieu': 0, u'underlyi…
tagged with: python
has answer: http://stackoverflow.com/a/47743823
accepted answer: http://stackoverflow.com/a/47743823
type: AnsweredQuestion
has title: Looping thru .JSON dictionary and inserting items via SQLite3
score: 0
tagged with: for-loop

http://stackoverflow.com/q/47771351
has body: I've finally figured out how to shoot bullets but now I want to rotate the origin of the bullets on the rotation of the players head. Now it's only shooting straight on the x line. The mobs are working fine. I only need to add in collision and the bullet that is rotating on the player's angle. I will do the collision myself although If anyone could hint me it would be appreciated. My main focus right now is to rotate the bullet according to the player's angle and 'kill' the bullet when it flies off screen. import pygame import random import math GRAD = math.pi / 180 black = (0,0,0) class Config(object): fullscreen = True width = 1366 height = 768 fps = 60 class Player(pygame.sprite.Sprite): #player class maxrotate = 180 down = (pygame.K_DOWN) up = (pygame.K_UP) def __init__(self, startpos=(102,579), angle=0): super().__init__() self.pos = list(startpos) self.image = pygame.image.load('BigShagHoofdzzz.gif') self.orig_image = self.image self.rect = self.image.get_rect(center=startpos) self.angle = angle def update(self, seconds): pressedkeys = pygame.key.get_pressed() if pressedkeys[self.down]: self.angle -= 2 self.rotate_image() if pressedkeys[self.up]: self.angle += 2 self.rotate_image() def rotate_image(self):#rotating player image self.image = pygame.transform.rotate(self.orig_image, self.angle) self.rect = self.image.get_rect(center=self.rect.center) class Mob(pygame.sprite.Sprite):#monster sprite def __init__(self): pygame.sprite.Sprite.__init__(self) self.image = pygame.image.load('Monster1re.png') self.rect = self.image.get_rect() self.rect.x = 1400 self.rect.y = random.randrange(500,600) self.speedy = random.randrange(-8, -1) def update(self): self.rect.x += self.speedy if self.rect.x &lt; -100 : self.rect.x = 1400 self.speedy = random.randrange(-8, -1) class Bullet(pygame.sprite.Sprite):#bullet sprite needs to rotate according to player's angle. """ This class represents the bullet . """ def __init__(self): # Call the parent class (Sprite) constructor super(…
answer count: 1
tagged with: bullet
downvote count: 0
has answer: http://stackoverflow.com/a/47772798
accepted answer: http://stackoverflow.com/a/47772798
has title: how to rotate a bullet according to the player's rotation
has comment: http://stackoverflow.com/comment/82504027
has comment: http://stackoverflow.com/comment/82504941
favorite count: 0
type: Question
tagged with: rotation
linked to: http://stackoverflow.com/q/42280234
tagged with: python
tagged with: pygame
has comment: http://stackoverflow.com/comment/82504531
has comment: http://stackoverflow.com/comment/82504702
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/82506530
upvote count: 3

http://stackoverflow.com/a/47802817
answers question: http://stackoverflow.com/q/47802772
downvote count: 0
upvote count: 1
type: AcceptedAnswer
has body: I would define variables ref_y and ref_y and just add them to my current x and y value as in: import tkinter as tk root = tk.Tk() ref_x = 40 ref_y = 56 btn = tk.Button(root, text="Button") lbl = tk.Label(root, text="Label") btn.place(x=ref_x + 45, y=ref_y + 13) lbl.place(x=ref_x + 13, y=ref_y + 44) root.mainloop() In the above example btn and lbl will be placed with referece to ref_x and ref_y. Which means if you want to place the widgets elsewhere keeping their relative position to each other, you just need to modify ref_x and ref_y values.
score: 1
accepted answer of: http://stackoverflow.com/q/47802772
type: Answer

http://stackoverflow.com/a/47757556
has comment: http://stackoverflow.com/comment/103852336
answers question: http://stackoverflow.com/q/47755723
type: Answer
accepted answer of: http://stackoverflow.com/q/47755723
score: 7
upvote count: 7
has body: Singleton isn't quite the right term, but I get what you want. arr = np.array((0.5, 1), dtype=dtype) Creates a 0d, single element array of this dtype. Check its dtype and shape. arr.item() returns a tuple (0.5, 1). Aso test arr[()] and arr.tolist(). np.float64(0.5) creates a float with a numpy wrapper. It is similar to, but not exactly the same as np.array(0.5). Their methods diff some. I don't know anything similar with a compound dtype. In [123]: dt = np.dtype('i,f,U10') In [124]: dt Out[124]: dtype([('f0', '&lt;i4'), ('f1', '&lt;f4'), ('f2', '&lt;U10')]) In [125]: arr = np.array((1,2,3),dtype=dt) In [126]: arr Out[126]: array((1, 2., '3'), dtype=[('f0', '&lt;i4'), ('f1', '&lt;f4'), ('f2', '&lt;U10')]) In [127]: arr.shape Out[127]: () arr is a 0d 1 element array. It can be indexed with: In [128]: arr[()] Out[128]: (1, 2., '3') In [129]: type(_) Out[129]: numpy.void This indexing produces a np.void object. Doing the same thing on a 0d float array would produce a np.float object. But you can't use np.void((1,2,3), dtype=dt) to directly create such an object (in contrast to np.float(12.34)). item is the normal way of extracting a 'scalar' from an array. Here it returns a tuple, the same sort of object that we used as input to create arr: In [131]: arr.item() Out[131]: (1, 2.0, '3') In [132]: type(_) Out[132]: tuple np.asscalar(arr) returns the same tuple. One difference between the np.void object and the tuple, is that it can still be indexed with the field name, arr[()]['f0'], whereas the tuple has to be indexed by number arr.item()[0]. The void still has a dtype, while the tuple doesn't. fromrecords makes a recarray. This is similar to a structured array, but allows us to access fields as attributes. It may actually be an older class, that has been merged to into numpy, hence the np.rec prefix. Mostly we use structured arrays, though np.rec still has some convenience functions. (actually in numpy.lib.recfunctions): In [133]: res = np.rec.fromrecords((1,2,3), dt) In…
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/47744253
type: Answer
score: 4
answers question: http://stackoverflow.com/q/47744109
upvote count: 4
type: AcceptedAnswer
downvote count: 0
has body: Simple list comprehension appears to be the fastest method when working with such strings: In [112]: df['word_overlap'] = [set(x[0].split()) &amp; set(x[1].split()) for x in df.values] In [113]: df['overlap_count'] = df['word_overlap'].str.len() In [114]: df Out[114]: friend_description friend_definition word_overlap overlap_count 0 James is dumb dumb dude {dumb} 1 1 Jacob is smart smart guy {smart} 1 2 Jane is pretty she looks pretty {pretty} 1 3 Susan is rich she is rich {rich, is} 2 single apply(..., axis=1): In [85]: df['word_overlap'] = df.apply(lambda r: set(r['friend_description'].split()) &amp; ...: set(r['friend_definition'].split()), ...: axis=1) ...: In [86]: df['overlap_count'] = df['word_overlap'].str.len() In [87]: df Out[87]: friend_description friend_definition word_overlap overlap_count 0 James is dumb dumb dude {dumb} 1 1 Jacob is smart smart guy {smart} 1 2 Jane is pretty she looks pretty {pretty} 1 3 Susan is rich she is rich {rich, is} 2 apply().apply(..., axis=1) method: In [23]: df['word_overlap'] = (df.apply(lambda x: x.str.split(expand=False)) ...: .apply(lambda r: set(r['friend_description']) &amp; set(r['friend_definition']), ...: axis=1)) ...: In [24]: df['overlap_count'] = df['word_overlap'].str.len() In [25]: df Out[25]: friend_description friend_definition word_overlap overlap_count 0 James is dumb dumb dude {dumb} 1 1 Jacob is smart smart guy {smart} 1 2 Jane is pretty she looks pretty {pretty} 1 3 Susan is rich she is rich {is, rich} 2 Timing against 40.000 rows DF: In [104]: df = pd.concat([df] * 10**4, ignore_index=True) In [105]: df.shape Out[105]: (40000, 2) In [106]: %timeit [set(x[0].split()) &amp; set(x[1].split()) for x in df.values] 223 ms ± 19.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) In [107]: %timeit df.apply(lambda r: set(r['friend_description'].split()) &amp; set(r['friend_definition'].split()), axis=1) 3.65 s ± 46.6 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) In [108]: %timeit df.apply(lambda x:…
accepted answer of: http://stackoverflow.com/q/47744109

http://stackoverflow.com/a/47838817
has body: There's an almost unlimited number of ways that you can use functions. The main driver in your decision is whether or not you can reuse functionality or if it simplifies your code. So in essence, can I build this into a building block is the question you should ask yourself. So in your example, say you have to take input in several different scenarios or you have to maybe evaluate a number of lists and provide print output. You could separate things based on that: def take_input(list): count = 0 while count &lt; 5: inputlist.append(int(input('list a number:'))) count += 1 def print_output(list): outputlist = [] for input in list: if input &lt; 100: outputlist.append(True) else: outputlist.append(False) print(outputlist) inputlist = [] take_input(inputlist) print_output(inputlist)
type: Answer
score: 1
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47838624

http://stackoverflow.com/comment/82548595
comment on: http://stackoverflow.com/q/47787615
score: 0
type: Comment
type: QuestionComment
has text: Actually type(train_step) is <class 'tensorflow.python.framework.ops.Operation'> and as you see in [Operation](https://www.tensorflow.org/api_docs/python/tf/Operation) - _Operation can be executed by passing it to tf.Session.run_

http://stackoverflow.com/q/47711446
downvote count: 0
has body: I am trying to run tasks through the command 'airflow scheduler' when it produced this error, AFTER I tried to run one of the dags. Traceback (most recent call last): File "/usr/local/bin/airflow", line 28, in &lt;module&gt; args.func(args) File "/usr/local/lib/python3.5/dist-packages/airflow/bin/cli.py", line 839, in scheduler job.run() File "/usr/local/lib/python3.5/dist-packages/airflow/jobs.py", line 200, in run self._execute() File "/usr/local/lib/python3.5/dist-packages/airflow/jobs.py", line 1309, in _execute self._execute_helper(processor_manager) File "/usr/local/lib/python3.5/dist-packages/airflow/jobs.py", line 1441, in _execute_helper self.executor.heartbeat() File "/usr/local/lib/python3.5/dist-packages/airflow/executors/base_executor.py", line 132, in heartbeat self.sync() File "/usr/local/lib/python3.5/dist-packages/airflow/executors/celery_executor.py", line 88, in sync state = async.state File "/home/userName/.local/lib/python3.5/site-packages/celery/result.py", line 436, in state return self._get_task_meta()['status'] File "/home/userName/.local/lib/python3.5/site-packages/celery/result.py", line 375, in _get_task_meta return self._maybe_set_cache(self.backend.get_task_meta(self.id)) File "/home/userName/.local/lib/python3.5/site-packages/celery/backends/amqp.py", line 156, in get_task_meta binding.declare() File "/home/userName/.local/lib/python3.5/site-packages/kombu/entity.py", line 605, in declare self._create_queue(nowait=nowait, channel=channel) File "/home/userName/.local/lib/python3.5/site-packages/kombu/entity.py", line 614, in _create_queue self.queue_declare(nowait=nowait, passive=False, channel=channel) File "/home/userName/.local/lib/python3.5/site-packages/kombu/entity.py", line 649, in queue_declare nowait=nowait, File "/home/userName/.local/lib/python3.5/site-packages/amqp/channel.py", line 1147, in queue_declare nowait, arguments), File "/home/userName/.local/lib/python3.5/site-packages/amqp/abstract_channel.py", line 50, in send_m…
tagged with: rabbitmq
has title: Ariflow [Errno 104] Connection reset by peer
tagged with: celery
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/86416382
has answer: http://stackoverflow.com/a/55765489
tagged with: airflow
tagged with: python
tagged with: airflow-scheduler
score: 4
upvote count: 4
has comment: http://stackoverflow.com/comment/98252940
answer count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/69010548

http://stackoverflow.com/q/47855617
has body: The first demo: class B: def __init__(self): self.name = '234' # def __getattribute__(self, name): # print('getattr') def __getattr__(self, name): print('get') def __setattr__(self, name, value): print('set') def __delattr__(self, name): print('del') b = B() print(b.__dict__) b.name b.__dict__ is {}, but the second demo: class B: def __init__(self): self.name = '234' def __getattribute__(self, name): print('getattr') def __getattr__(self, name): print('get') def __setattr__(self, name, value): print('set') def __delattr__(self, name): print('del') b = B() print(b.__dict__) b.name b.__dict__ is None, why? And b.__dict__ invokes __getattribute__, but don't invoke __getattr__, does it mean __getattribute__ will prevent from invoking __getattr__?
favorite count: 0
tagged with: operator-overloading
type: AnsweredQuestion
downvote count: 0
tagged with: overriding
has answer: http://stackoverflow.com/a/47855651
accepted answer: http://stackoverflow.com/a/47855651
tagged with: python
upvote count: 4
tagged with: attributes
type: Question
tagged with: python-3.x
answer count: 1
has title: Some questions about __getattr__ and __getattribute__?
score: 4

python-2.7
tags question: http://stackoverflow.com/q/47798050
tags question: http://stackoverflow.com/q/47845212
tags question: http://stackoverflow.com/q/47716187
tags question: http://stackoverflow.com/q/47737277
tags question: http://stackoverflow.com/q/47810541
tags question: http://stackoverflow.com/q/47753873
tags question: http://stackoverflow.com/q/47833369
tags question: http://stackoverflow.com/q/47700556
tags question: http://stackoverflow.com/q/47834230
tags question: http://stackoverflow.com/q/47832807
tags question: http://stackoverflow.com/q/47820798
tags question: http://stackoverflow.com/q/47761156
tags question: http://stackoverflow.com/q/47840620
tags question: http://stackoverflow.com/q/47836380
tags question: http://stackoverflow.com/q/47728499
tags question: http://stackoverflow.com/q/47778449
tags question: http://stackoverflow.com/q/47728299
tags question: http://stackoverflow.com/q/47842283
tags question: http://stackoverflow.com/q/47751504
tags question: http://stackoverflow.com/q/47794369
tags question: http://stackoverflow.com/q/47797362
tags question: http://stackoverflow.com/q/47802766
tags question: http://stackoverflow.com/q/47732878
tags question: http://stackoverflow.com/q/47783748
tags question: http://stackoverflow.com/q/47735622
tags question: http://stackoverflow.com/q/47766364
tags question: http://stackoverflow.com/q/47765478
tags question: http://stackoverflow.com/q/47703486
tags question: http://stackoverflow.com/q/47721395
tags question: http://stackoverflow.com/q/47853073
tags question: http://stackoverflow.com/q/47747703
tags question: http://stackoverflow.com/q/47747299
tags question: http://stackoverflow.com/q/47835643
tags question: http://stackoverflow.com/q/47801152
tags question: http://stackoverflow.com/q/47854002
tags question: http://stackoverflow.com/q/47719384
type: Tag
tags question: http://stackoverflow.com/q/47705882
tags question: http://stackoverflow.com/q/47828176
tags question: http://stackoverflow.com/q/47716555
tags question: http://stackoverflow.com/q/47792242
tags question: http://stackoverflow.com/q/47744526
tags question: http://stackoverflow.com/q/47754920
tags question: http://stackoverflow.com/q/47768826
tags question: http://stackoverflow.com/q/47740478
tags question: http://stackoverflow.com/q/47831379
tags question: http://stackoverflow.com/q/47719470
tags question: http://stackoverflow.com/q/47833920
tags question: http://stackoverflow.com/q/47704736
tags question: http://stackoverflow.com/q/47855539
tags question: http://stackoverflow.com/q/47766280
tags question: http://stackoverflow.com/q/47749257
tags question: http://stackoverflow.com/q/47735269
tags question: http://stackoverflow.com/q/47802544
tags question: http://stackoverflow.com/q/47765206
tags question: http://stackoverflow.com/q/47731222
tags question: http://stackoverflow.com/q/47797346
tags question: http://stackoverflow.com/q/47704702
tags question: http://stackoverflow.com/q/47737942
tags question: http://stackoverflow.com/q/47823544
tags question: http://stackoverflow.com/q/47759436
tags question: http://stackoverflow.com/q/47772299
tags question: http://stackoverflow.com/q/47837548
tags question: http://stackoverflow.com/q/47843889
tags question: http://stackoverflow.com/q/47738471
tags question: http://stackoverflow.com/q/47775186
tags question: http://stackoverflow.com/q/47746025
tags question: http://stackoverflow.com/q/47733534
tags question: http://stackoverflow.com/q/47761817
tags question: http://stackoverflow.com/q/47701165
tags question: http://stackoverflow.com/q/47767055
tags question: http://stackoverflow.com/q/47785858
tags question: http://stackoverflow.com/q/47840395
tags question: http://stackoverflow.com/q/47704164
tags question: http://stackoverflow.com/q/47808590
tags question: http://stackoverflow.com/q/47853765
tags question: http://stackoverflow.com/q/47828625
tags question: http://stackoverflow.com/q/47799959
tags question: http://stackoverflow.com/q/47747405
tags question: http://stackoverflow.com/q/47799753

http://stackoverflow.com/comment/82486630
score: 0
type: Comment
has text: I have it. Thank you Daniel!
type: AnswerComment
comment on: http://stackoverflow.com/a/47743125

http://stackoverflow.com/comment/83420150
type: AnswerComment
has text: @delrocco yw~ :-)
comment on: http://stackoverflow.com/a/47706606
type: Comment
score: 0

http://stackoverflow.com/q/47751102
linked to: http://stackoverflow.com/q/5254445
has answer: http://stackoverflow.com/a/47751216
tagged with: python
possible better answer: http://stackoverflow.com/a/47751906
accepted answer: http://stackoverflow.com/a/47751214
type: Question
has answer: http://stackoverflow.com/a/47751214
has body: How to add commas at required positions in the given string in Python? In my case, the positions are not fixed. Example: My requirement is to add the commas after 5th, 8th, 11th, 13th in an input string = "hello Python program" My expected output would be: hello, Py,tho,n p,rogram Is there any simplest way to achieve this in Python? Actually I need to apply a comma on 590 positions in my file record and then process it.
has title: How to add commas at required positions in the given string in Python?
tagged with: string
has comment: http://stackoverflow.com/comment/82462640
has answer: http://stackoverflow.com/a/47751906
has comment: http://stackoverflow.com/comment/82462495
type: AnsweredQuestion
score: 0
linked to: http://stackoverflow.com/q/4022827
answer count: 3

http://stackoverflow.com/q/47708905
has body: When I'm trying to click an element i get the error but in reality the element is clicked. driver = webdriver.Chrome() driver.get("some url here") start_button = driver.find_element_by_class_name('start-button') start_button.click()
score: 0
has comment: http://stackoverflow.com/comment/82378080
has title: python selenium throw element is not clickable at point (x,y) even though the element is clicked
type: Question
answer count: 0
linked to: http://stackoverflow.com/q/44912203
has comment: http://stackoverflow.com/comment/82379378
has comment: http://stackoverflow.com/comment/82377688
type: UnansweredQuestion
tagged with: selenium
tagged with: python

http://stackoverflow.com/q/47736645
answer count: 0
score: 1
has comment: http://stackoverflow.com/comment/82437255
has title: got memoryerror creating ODM=np.zeros((n,n)) with iterating
has comment: http://stackoverflow.com/comment/82435385
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82436600
has comment: http://stackoverflow.com/comment/82436708
tagged with: out-of-memory
type: UnansweredQuestion
has body: import networkx as nx import matplotlib import matplotlib.pyplot as plt import matplotlib.cm as cm import gc import numpy as np from mpl_toolkits.basemap import Basemap from math import radians, cos, sin, asin, sqrt import pandas as pd from sklearn import preprocessing #some modules are unused df_raw = pd.read_csv("AllUserTraj.csv", sep='\t') df_raw = df_raw.drop('Unnamed: 0', 1) # You may start from df_raw df = df_raw'Latitude','Longitude','UserID','Domestic','Weekday','WaitingTime','DayHour' df:contain:'Latitude','Longitude','UserID','Domestic' 0 or 1,'Weekday' 0 or 1,'WaitingTime' in minute,'DayHour' from 1 to 24 def haversine(lon1, lat1, lon2, lat2): """ Calculate the great circle distance between two points on the earth (specified in decimal degrees) in km """ # convert decimal degrees to radians lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2]) # haversine formula dlon = lon2 - lon1 dlat = lat2 - lat1 a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2 c = 2 * asin(sqrt(a)) r = 6371 # Radius of earth in kilometers. Use 3956 for miles return c * r def ODM_cal(df_user, ID): aggregate_features = pd.DataFrame() p = df_user.groupby(['Latitude','Longitude'])['UserID'].count() n = len(p) aggregate_features = pd.DataFrame(p) aggregate_features['temp'] = aggregate_features.index lat = list() long = list() for index, row in aggregate_features.iterrows(): lat.append(row['temp'][0]) long.append(row['temp'][1]) aggregate_features['Latitude'] = lat aggregate_features['Longitude'] = long aggregate_features = aggregate_features.drop('temp', 1) aggregate_features = aggregate_features.sort_values('UserID', ascending=False) aggregate_features = aggregate_features.reset_index(drop=True) ODM = np.zeros((n,n)) frequency = dict() count = 0 for index, row in df_user.iterrows(): Latitude = row['Latitude'] Longitude = row['Longitude'] location_index = aggregate_features[(aggregate_features['Latitude'] == Latitude) &amp; (aggregate_features['Longitude'] == Long…
tagged with: python
has comment: http://stackoverflow.com/comment/82434945
has comment: http://stackoverflow.com/comment/82434138
tagged with: numpy
has comment: http://stackoverflow.com/comment/82437282

http://stackoverflow.com/a/47776685
has comment: http://stackoverflow.com/comment/82515086
accepted answer of: http://stackoverflow.com/q/47775317
type: Answer
has comment: http://stackoverflow.com/comment/82516232
answers question: http://stackoverflow.com/q/47775317
score: 2
upvote count: 2
downvote count: 0
type: AcceptedAnswer
has body: MikG, I would say that python did exactly what you requested. You told to convert the bytes to string, and replace bytes with most significant bit set with escape sequence (except for \xFF char). Characters \x04 (ETB) and \x1F (US) are perfectly legal ASCII chars (though non-printable), and they are encoded using their literal value. Characters \xd6 and \xd0 are illegal in ASCII - they are 8-bit long. They are encoded using 4-letter long escape sequence, as you asked: "\" (backslash char) and "xd6" / "xd0" strings I'm not good with DER, but suppose that you expect to have raw 8-bit sequences. Here is how this could be accomplished: result = bytearray.fromhex('380c2fd6172cd06d1f30') with open("Output.der", "wb") as text_file: text_file.write(result) Please note "wb" specifier to open -- it tells python to do binary IO. I also used with statement to ensure that text_file is closed whatever happens with write.
has comment: http://stackoverflow.com/comment/82538616
has comment: http://stackoverflow.com/comment/82521402

http://stackoverflow.com/comment/82552608
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47793905
has text: @pieta you get `loginCsrfParam` from cookies, not from hidden field.

http://stackoverflow.com/comment/82549154
comment on: http://stackoverflow.com/a/47782905
has text: Thanks ,I've tried that but I am receiving this error; AttributeError: 'list' object has no attribute 'replace'
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/82841177
type: AnswerComment
has text: Right, sorry, I forgot to update the question here. I'd say let's keep the question open and update it when the feature will be merged in SimpleITK.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47875773

http://stackoverflow.com/comment/82488366
type: QuestionComment
has text: ok, thanks, will do
score: 0
comment on: http://stackoverflow.com/q/47763342
type: Comment

math
tags question: http://stackoverflow.com/q/47814123
tags question: http://stackoverflow.com/q/47721865
tags question: http://stackoverflow.com/q/47812367
tags question: http://stackoverflow.com/q/47761102
tags question: http://stackoverflow.com/q/47846345
type: Tag
tags question: http://stackoverflow.com/q/47841088
tags question: http://stackoverflow.com/q/47804299
tags question: http://stackoverflow.com/q/47777585
tags question: http://stackoverflow.com/q/47740459
tags question: http://stackoverflow.com/q/47716384
tags question: http://stackoverflow.com/q/47851688
tags question: http://stackoverflow.com/q/47803241
tags question: http://stackoverflow.com/q/47822994
tags question: http://stackoverflow.com/q/47820877
tags question: http://stackoverflow.com/q/47850993
tag name: math
tags question: http://stackoverflow.com/q/47781157
tags question: http://stackoverflow.com/q/47698771

http://stackoverflow.com/a/47889731
type: Answer
has body: SageMath uses SymPy for symbolic math, so there should be a replace() method on your expression. &gt;&gt;&gt; A a0**2 + 2*a0*a1 + a1**2 &gt;&gt;&gt; A.replace(lambda expr: isinstance(expr, sympy.Pow), lambda expr: expr.args[0]) 2*a0*a1 + a0 + a1 This uses the variation with two functions as arguments. The first is a filter which tests for nodes in the expression tree to be substituted and the second calculates the replacement. We are searching for any Pow node and replace it by it's first argument.
answers question: http://stackoverflow.com/q/47756675
score: 0

http://stackoverflow.com/q/47814335
has comment: http://stackoverflow.com/comment/82590592
type: Question
has comment: http://stackoverflow.com/comment/82591125
has comment: http://stackoverflow.com/comment/82590415
has body: I have created Test.py file which has some function in it and using those function names as Keywords in sample.robot file. Ex: - Test.py def Launch_URL(url): driver.get(url) def article(publication): do something here Sample.robot Library Selenium2Library Library Test.py *** Test Cases **** Open app Launch URL "https://stackoverflow.com" article something Click Element xpath=/html/body/div[1]/div/div/button/i Apart from the derived keywords in .py I also want to use built in Keyword Click Element in robot file. When the I run the above script it is throwing me No Browser Open error for Click Element keyword.
tagged with: python
type: UnansweredQuestion
score: -1
has comment: http://stackoverflow.com/comment/82590811
upvote count: 0
linked to: http://stackoverflow.com/q/23703870
answer count: 1
has comment: http://stackoverflow.com/comment/82591573
downvote count: 1
has title: "No Browser is Open" issue is coming when running the Robot framework script
favorite count: 0
has answer: http://stackoverflow.com/a/47815572
tagged with: robotframework

http://stackoverflow.com/q/47810507
tagged with: python
has comment: http://stackoverflow.com/comment/82583516
type: Question
has title: Django ORM, data that does not match the condition even though filtering is acquired
score: 0
type: UnansweredQuestion
answer count: 1
has body: There is a model called Anayltics like the following. The url field of this model contains various values (e.g '/login', '/sports/1234', '/search'). class Analytics(models.Model) url = models.CharField(max_length=255, null=True) value = models.IntegerField(null=True) I attempted to retrieve only records with url containing strings in category_list below. category_list = ['fashion', 'food', 'sports'] filter_q = reduce(operator.or_, (Q(url__contains=c) for c in category_list)) query = Analytics.objects.filter(filter_q) However, records with unexpected urls, such as url '/login', are also retrieved. Please tell me where is wrong.
tagged with: django
has answer: http://stackoverflow.com/a/47811431
has comment: http://stackoverflow.com/comment/82583648

http://stackoverflow.com/comment/82532398
score: 1
type: QuestionComment
has text: @furas: This is [not quite correct](https://docs.python.org/2/faq/design.html#how-are-lists-implemented) (or at least correct only in Python context, due to how it twisted the usual terminology). For some unknown reason, Python co-opted the term "list" to what every other language calls "array" or "vector". Then numpy took the unused term "array" and stole it for itself.
comment on: http://stackoverflow.com/q/47785229
type: Comment

http://stackoverflow.com/comment/82785775
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47774530
has text: Piping `stdout` and `stderr` but not actually reading them may cause the external process to block. If you want the outputs ignored redirect them to the “null device“. Use `os.devnull` for a platform independent name for that device file.

http://stackoverflow.com/q/47847503
downvote count: 0
upvote count: 1
tagged with: python
has title: Avoiding collisions when extending third-party Python packages
answer count: 0
score: 1
has body: I am working on a project that extends an existing and very active Python package - we'll call it packageA. Our package, packageB adds some functionality that is outside the scope of packageA, but relies heavily on a class from packageA. We want the contents of packageA to be readily available to users of packageB with out having to do the following: import packageA as pkgA import packageB as pkgB and then have to keep track of which classes and methods come from which package. Currently, the __init__.py file in packageB's base directory contains the following: import packageA from packageA import * I am concerned about potential collisions with our package. My thought was to give the package a structure like: packageB/ __init__.py packageA/ __init__.py then remove the import from packageB's __init__.py and move it to the packageA __init__.py where I could then import only the classes and methods needed into the packageB namespace. Users could still access packageA through the packageB.packageA namespace. Is there an accepted best practice for doing this sort of thing?
has comment: http://stackoverflow.com/comment/82659368
has comment: http://stackoverflow.com/comment/82659250
favorite count: 0
type: Question
type: UnansweredQuestion

http://stackoverflow.com/q/47788110
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47788301
has answer: http://stackoverflow.com/a/47788452
score: 1
tagged with: python
has answer: http://stackoverflow.com/a/47789278
tagged with: list-comprehension
has body: I am trying to populate a 2D numpy array. In my experience, the following is not going to scale up well with array sizes. x=np.array([2,3,4]) y=np.array([1,3,9,13]) mat=np.zeros((x.size,y.size)) for i in range(nx): for j in range(ny): if x[i] &gt; y[j]: mat[i,j] = 1 else: mat[i,j] = -1 Ideally, I would like to use list comprehension like It would be simple if it was 1D only mat=np.asarray([foo(x_) for x_ in x]) but how to generalize this to 2D np.arrays? Other numpy based solutions are also suitable, but efficiency is the key metric here
has title: filling a 2D numpy array in a pythonic way
answer count: 4
accepted answer: http://stackoverflow.com/a/47788452
tagged with: numpy
has answer: http://stackoverflow.com/a/47788352
has comment: http://stackoverflow.com/comment/82537274
has comment: http://stackoverflow.com/comment/82537204
tagged with: arrays
downvote count: 0
upvote count: 1
favorite count: 0
possible better answer: http://stackoverflow.com/a/47788301

http://stackoverflow.com/comment/82609807
comment on: http://stackoverflow.com/q/47821717
type: Comment
type: QuestionComment
score: 0
has text: BTW: I would rather keep it as `buttons[(x,y)] = tk.Button()` and use `x,y` in `claim_field(x,y)` - this way `claim_field` will know `x,y` and it can disable `button[(x,y)]`. And you can use `random.randint` to select random `x,y` to disable random button.

http://stackoverflow.com/comment/82481860
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47760121
has text: two ways to solve the problem:1) put optional spaces everywhere in the pattern (Neos07 approach) or 2) normalize the line (with `re.sub`) before testing it with a more simple pattern (with `re.match`). I let you choose the most appropriate approach.

http://stackoverflow.com/comment/82548753
type: QuestionComment
score: 0
has text: can you put all the template you are refer on?Also the base.html. I believe /could be you are not inheriting the blocks from the base.html, have a look to this https://stackoverflow.com/questions/1900892/nested-blocks-in-django-templates
comment on: http://stackoverflow.com/q/47791576
type: Comment

http://stackoverflow.com/a/47722267
type: Answer
has body: According the the Apple website you can upgrade for FREE! Upgrading you macOS version should help with this problem. https://www.apple.com/macos/how-to-upgrade/
has comment: http://stackoverflow.com/comment/82426787
score: 0
answers question: http://stackoverflow.com/q/47721998

http://stackoverflow.com/q/47730829
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82424870
score: 0
answer count: 1
tagged with: pygame
has comment: http://stackoverflow.com/comment/82424829
tagged with: sprite
type: Question
has answer: http://stackoverflow.com/a/47733136
has comment: http://stackoverflow.com/comment/82424933
has comment: http://stackoverflow.com/comment/82424795
has title: How do you move a sprite in pygame?
tagged with: animation
has comment: http://stackoverflow.com/comment/82424691
has comment: http://stackoverflow.com/comment/82424743
tagged with: python
accepted answer: http://stackoverflow.com/a/47733136
has comment: http://stackoverflow.com/comment/82424716
has comment: http://stackoverflow.com/comment/82424954
linked to: http://stackoverflow.com/q/47732591
has comment: http://stackoverflow.com/comment/82424641
has body: I know that this question has already been answered in other forms, but I can't seem to make it work for my game. I'm trying to make the sprite move and keep him in the place he moved to. This is part of my code: class player(pygame.sprite.Sprite): def __init__(self, x, y): pygame.sprite.Sprite.__init__(self) def draw(self, x, y): player = pygame.image.load("stand_down.png").convert_alpha() player = pygame.transform.scale(player, (100, 200)) screen.blit(player, (x, y)) pygame.display.update() for event in pygame.event.get(): key = pygame.key.get_pressed() if event.type == KEYDOWN : if key [K_LEFT] : player = pygame.image.load("standleft.png").convert_alpha() player = pygame.transform.scale(player, (100, 200)) x -= 50 screen.blit(player, (x, y)) pygame.display.update() pygame.sprite.Sprite.update(player) if key [K_RIGHT]: player = pygame.image.load("standright.png").convert_alpha() player = pygame.transform.scale(player, (100, 200)) x += 50 screen.blit(player, (x, y)) pygame.display.update() pygame.sprite.Sprite.update(player) def update(self): pygame.sprite.Sprite.update(player) And then this is part of my main function: player.draw(screen, x, y) player.update(screen) I've tried everything I can think of, but the player just keeps flashing at a different point, then returning to the previous position. If you could help, it would be much appreciated!

http://stackoverflow.com/comment/82602022
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47819819
has text: @ThijsvanDien I'm not sure how that's a duplicate - it looks like that question is about adding/subtracting business days, which isn't exactly what I'm looking for.
type: Comment

http://stackoverflow.com/q/47767576
has title: python-docx, access to paragraph font-size
downvote count: 0
has comment: http://stackoverflow.com/comment/120013819
tagged with: ms-word
favorite count: 0
type: Question
tagged with: http://stackoverflow.com/tag/docx
score: 5
possible better answer: http://stackoverflow.com/a/78089307
upvote count: 5
accepted answer: http://stackoverflow.com/a/47767639
tagged with: python
has body: I want to access to a paragraph or run that has a unique font or font-size using python-docx. How i can get texts of runs or paragraphs that has specified font or font-size?
tagged with: python-docx
has answer: http://stackoverflow.com/a/78089307
linked to: http://stackoverflow.com/q/76650844
has answer: http://stackoverflow.com/a/47767639
type: AnsweredQuestion
answer count: 2

http://stackoverflow.com/comment/125518815
type: AnswerComment
comment on: http://stackoverflow.com/a/70995855
score: 1
type: Comment
has text: Ah yes. I just went down a rabbit hole of following github issues around discussing general solutions. I will emphasise that my solution is only relevant to boxplots.

http://stackoverflow.com/comment/82422183
type: QuestionComment
comment on: http://stackoverflow.com/q/47718341
score: 0
type: Comment
has text: @ImportanceOfBeingErnest many thanks for that! I still don't get why different figsize produce different squares. I should have 500x500 squares no matter the resolution, right? From what I saw from documentation, `figsize` is about inches, so shouldn't make a difference in the amount of squares inside, no?

http://stackoverflow.com/q/47791576
has comment: http://stackoverflow.com/comment/82545321
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82556905
tagged with: django
has comment: http://stackoverflow.com/comment/82548753
linked to: http://stackoverflow.com/q/1900892
score: 0
has comment: http://stackoverflow.com/comment/82556635
tagged with: python
has comment: http://stackoverflow.com/comment/82545540
has title: django - csrf protection - markdown2
has body: In some of my blog posts using django and markdown2, I am trying to include a form as follows: views.py: def post_detail(request, slug=None): instance = get_object_or_404(Post, slug=slug) if not instance.published: raise Http404 return render(request, "posts/post_detail.html", {'instance': instance}) My template post_detail.html contains a {{ instance.get_markdown }} variable: {% extends "base.html" %} {% block body_content %} {{ instance.get_markdown }} {% endblock body_content %} base.html: {% block body_content %} {% endblock body_content %} models.py: import markdown2 class Post(models.Model): ... text = models.TextField(verbose_name=_("Text")) ... def get_markdown(self): return mark_safe(markdown2.markdown(self.text)) Example for a saved text in Post: ### Example {% csrf_token %} First name: This way, the page simply shows the string "{% csrf_token %}" within the form. How can I render the post with csrf protection? My temporary solution is: post_detail.html: {% extends "base.html" %} {% block body_content %} {{ instance.get_markdown_text }} {% if instance.form %} {% csrf_token %} {{ instance.get_markdown_form }} {% endif %} {% endblock body_content %} models.py: import markdown2 class Post(models.Model): ... text = models.TextField(verbose_name=_("Text")) form = models.TextField(verbose_name=_("Form"), blank=True, null=True) ... def get_markdown_text(self): return mark_safe(markdown2.markdown(self.text)) def get_markdown_form(self): return mark_safe(markdown2.markdown(self.form)) I'm not very happy with this solution, because of the unnecessary field "form" and method get_markdown_form in Post and post_detail.html.
type: Question
has comment: http://stackoverflow.com/comment/82567865
has comment: http://stackoverflow.com/comment/82546224
has comment: http://stackoverflow.com/comment/82558385
answer count: 0

http://stackoverflow.com/comment/82777859
type: Comment
comment on: http://stackoverflow.com/a/47873708
score: 0
type: AnswerComment
has text: Yes, it is supposed to do that. And if it successfully does it, `frame` should be an image, which can be shown via `imshow`. (This is also what happens when I run the code.) That is why my suspicion is that something goes wrong when opening the videostream, such that it does not return a valid image.

http://stackoverflow.com/comment/82466816
has text: Great solution. Thanks
type: AnswerComment
comment on: http://stackoverflow.com/a/47698960
score: 0
type: Comment

http://stackoverflow.com/comment/82518806
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47778579
has text: What is BZ2FILE, or where do you get it from?

http://stackoverflow.com/a/47736535
type: Answer
has body: You can use numpy for vectorized solution i.e df[df.columns] = (df2.values - df2.values/df.values) X1 X2 X3 X4 index 0 16.666667 18.000000 16.666667 17.142857 1 12.250000 12.444444 12.727273 12.923077 2 15.583333 15.692308 15.866667 15.454545 3 12.250000 12.727273 12.000000 11.666667 4 13.636364 12.857143 12.500000 12.500000 5 18.461538 18.571429 18.181818 18.000000
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47736468
score: 1

http://stackoverflow.com/a/59366249
downvote count: 0
answers question: http://stackoverflow.com/q/47761632
upvote count: 2
type: Answer
score: 2
has body: The following worked for Python 3.7.3: from PIL import Image from cv2 import cvtColor, COLOR_BGR2RGB from numpy import array # get the image path img_path = 'images/test.jpg' img_rgb = cvtColor(array(Image.open(img_path)), COLOR_BGR2RGB)

event-handling
tag name: event-handling
type: Tag
tags question: http://stackoverflow.com/q/47850436

http://stackoverflow.com/q/47745133
score: 3
upvote count: 3
has answer: http://stackoverflow.com/a/47745930
downvote count: 0
favorite count: 0
tagged with: python-requests
type: Question
tagged with: python-3.x
answer count: 2
has title: python requests post to url query parameter requires special character
has answer: http://stackoverflow.com/a/47745322
type: UnansweredQuestion
has body: I am using python requests to submit a post request to a specific url. This url has a query parameter that contains the actual filepath of the file I am uplaoding, with the actual colon (':') and backslashes('\') (it will not accept %3A, or %5C). I have no idea what to do. Here is my code: with requests.Session() as s: payload_10_vo_params = { 'hidInputControlValues': this_hidInputControlValues10, 'hidFormNames': this_hidFormNames10, 'hidToken': this_hidToken10, 'hidFileNm': r"C:\fakepath\{}".format(this_FileName), 'hidFileSourceId': '', 'ReUploadInd': '' } payload10_mpe_vo = MultipartEncoder( [ ('hidLoanTranSaveFlag', 'TRUE'), ('hidUpfrontMIPct', ''), ('radLeadRequestOptBtnImportRetNum', 'LUPL'), ('txtCorrCompId', ''), ('cboLeadRequestFileTypCd', 'DU32'), ('txtLeadRequestSelectFile', (this_FileName, open(this_FileName, 'rb'), 'application/octet-stream')), ('txaLoanTranComments', ''), ], boundary=ct_disp_bndry_10_final_str) headers10 = { "Accept": "application/x-ms-application, image/jpeg, application/xaml+xml, image/gif, image/pjpeg, application/x-ms-xbap, */*", "Accept-Language": "en-US", "User-Agent": "Mozilla/5.0 (compatible; MSIE 7.0; Windows NT 6.1; Win64; x64; Trident/7.0; .NET CLR 2.0.50727; SLCC2; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; Tablet PC 2.0)", "UA-CPU": "AMD64", "Content-Type": "multipart/form-data; boundary={}".format(ct_disp_bndry_10_final_str), "Referer": "referer string", "Host": "host string"} resp10 = s.post(url10, headers=headers10, params=payload_10_vo_params, data=payload10_mpe_vo) Here is the value of the response url from fiddler, please see the final parameter(the value for hidFileNm), everything else is matching fine, (those special characters are for the special character §, which was encoded perfectly by requests). POST /SRVCorrBP/LeadMgmt/Application/Lead/LeadSubmitNew.jsp?hidInputControlValues=�DU32�Y�LUPL�C%3A%5CFAKEPATH%5CMAYRA%20CORTEZ.FNM�&amp;hidFormNames=�frmLoanTran~TRUE~�&amp;hidTok…
has comment: http://stackoverflow.com/comment/82450562
tagged with: python

http://stackoverflow.com/q/47701629
possible better answer: http://stackoverflow.com/a/49674249
tagged with: ipython
favorite count: 0
type: Question
tagged with: visual-studio-code
answer count: 5
has body: Is there a way to run an ipython like debug console in VC Code that would allow tab completion and other sort of things?
has comment: http://stackoverflow.com/comment/103507984
downvote count: 0
accepted answer: http://stackoverflow.com/a/61085420
score: 16
tagged with: python
has answer: http://stackoverflow.com/a/61085420
upvote count: 16
has answer: http://stackoverflow.com/a/49674249
has title: VS Code run ipython in debug console
has answer: http://stackoverflow.com/a/61054880
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/70932685
has answer: http://stackoverflow.com/a/72003595

http://stackoverflow.com/comment/82556387
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47797723
has text: `-31 would be the max or min temperature.` What? How can it be the max OR min? If you meant min, then isn't -78 lower than that?
score: 0

http://stackoverflow.com/comment/82556511
has text: @gbtimmon I'm not sure I agree with that sentiment. I might dump `debug` logging all over my code during testing with any arbitrarily long string output. The fact that interpolation means I can simply remove all of that overhead by changing the logging level means I don't have to go back and hash a load of lines out.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47797507
score: 0

http://stackoverflow.com/comment/82549143
type: Comment
has text: Thank you very much that actually did it. I was hoping for python to provide something ready but maths always work!
type: AnswerComment
comment on: http://stackoverflow.com/a/47783603
score: 0

numpy-ndarray
tag name: numpy-ndarray
tags question: http://stackoverflow.com/q/47819146
type: Tag

http://stackoverflow.com/a/47707580
has comment: http://stackoverflow.com/comment/82375240
has comment: http://stackoverflow.com/comment/82375159
has body: You can use a technique called memoization. For functions which accept hashable arguments, you can use the built-in functools.lru_cache. from functools import lru_cache @lru_cache(maxsize=None) def cached_function(B, C): return (B + C)**2 def formula(x): return cached_function(x.B, x.C) Notice that I had to pass the values through to the cached function for lru_cache to work correctly because Series objects aren't hashable.
score: 6
downvote count: 0
answers question: http://stackoverflow.com/q/47707528
type: Answer
upvote count: 6

http://stackoverflow.com/q/47729534
upvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
score: -2
has body: Here's the code, I just don't know why the error keeps showing up even after reading the past answers about it. import random rand = random.sample(range(10), 1) print(rand) guess = input('Try guessing a number between 0-10! ') for num in str(guess): if rand &gt; guess: print('The number is too low! Try again!') elif rand &lt; guess: print('The number is too high! Try again!') else: print("You got it!")
has title: How do I solve TypeError: '>' not supported between instances of 'int' and 'list'?
tagged with: python
accepted answer: http://stackoverflow.com/a/47729598
possible better answer: http://stackoverflow.com/a/47729571
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82419523
has answer: http://stackoverflow.com/a/47729598
has comment: http://stackoverflow.com/comment/82419558
has answer: http://stackoverflow.com/a/47729571
answer count: 2
downvote count: 3
has comment: http://stackoverflow.com/comment/82421073

http://stackoverflow.com/a/47767340
accepted answer of: http://stackoverflow.com/q/47766364
score: 2
upvote count: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82571597
downvote count: 0
has body: If you are not debugging the python interpreter itself, you don't need any python debugging stuff described in the linked article. You can use the regular interpreter and no extensions. You also don't want to run gdb twice. You only need to make sure you set your breakpoint early enough. $ gdb python --args &lt;your-args&gt; # no -x r (gdb) break &lt;your-breakpoint&gt; No symbol table is loaded. Use the "file" comand. Make breakpoint pending on future shared library load? (y or [n]) Answer "y". (gdb) run That's it.
answers question: http://stackoverflow.com/q/47766364
type: Answer

http://stackoverflow.com/a/47844324
type: Answer
upvote count: 4
downvote count: 0
has body: Using pickle to save the history object threw a whole host of errors. As it turns out you can instead use pickle on H.history instead of H to save your history file! Kind of annoying having to have a model and a history file saved, but whatever
score: 4
answers question: http://stackoverflow.com/q/47843265

http://stackoverflow.com/comment/82527438
comment on: http://stackoverflow.com/q/47782824
type: Comment
type: QuestionComment
has text: That is nice! So delay works. I have to check what scatter does.
score: 0

http://stackoverflow.com/comment/82429405
has text: @JerichoJones could you provide a workable example? In your code `B` and `dydt` are not defined
comment on: http://stackoverflow.com/q/47734122
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47845180
type: Answer
accepted answer of: http://stackoverflow.com/q/47844999
upvote count: 1
type: AcceptedAnswer
has body: Have u tried to use a function that simply return the dict item, and pass it as partiction function? def return_key(x): return your_dict[x] Pass it as partitionFunction.
downvote count: 0
answers question: http://stackoverflow.com/q/47844999
score: 1

http://stackoverflow.com/comment/82403065
comment on: http://stackoverflow.com/q/47719657
type: QuestionComment
score: 0
has text: @univerio: for the matter of fact , Nikhil suggestion seem to work great
type: Comment

qlayout
tags question: http://stackoverflow.com/q/47852697
type: Tag
tag name: qlayout

http://stackoverflow.com/comment/135141776
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47767639
type: Comment
has text: Take a look at [this answer](https://stackoverflow.com/questions/76650844/find-all-the-texts-which-is-normal-style-and-font-size-is-not-11-in-a-docx-fil/76651650#76651650)

http://stackoverflow.com/comment/82536116
score: 0
comment on: http://stackoverflow.com/q/47787405
type: Comment
has text: why i = 0 and not i = 1 if the result is the same after I run the code?
type: QuestionComment

http://stackoverflow.com/comment/82577157
has text: thx sir, BTW, where do I put the code above? whether in action_confirm sale order?
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47806950

http://stackoverflow.com/q/47718774
has title: Using "transform" and a struct in cython to implement operations on vectors
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/47743506
tagged with: matrix
has comment: http://stackoverflow.com/comment/82440649
has comment: http://stackoverflow.com/comment/82440748
tagged with: python
tagged with: cython
has body: I have been trying to write a Matrix class which used a one dimensional vector in order to build up a two-dimensional matrix. My main goal is to be able to add row or column to my Matrix, using this class, in addition of being able to do normal matrix operations. My current issue is how to add/subtract/multiply element by element of two matrices? I'd like to use vector properties in order to solve this problem by applying the idea of this answer. But so far I wasn't successful. How can I use transform and plus/minus for element-wise two vectors operations?? from libcpp.vector cimport vector import cython import numpy as np import ctypes cimport numpy as np cimport cython cdef extern from "&lt;algorithm&gt;" namespace "std" nogil: OutputIter copy[InputIter,OutputIter](InputIter,InputIter,OutputIter) #http://en.cppreference.com/w/cpp/algorithm/transform OutputIter transform[InputIter, OutputIter, UnaryOperation]( InputIter,InputIter,OutputIter, UnaryOperation ) cdef struct plus: T operator[] (T&amp; x, T&amp; y): return x+y cdef class Matrix: cdef vector[double] matrix cdef int _rows cdef int _columns def __cinit__(self, int rows=0, int columns=0, bint Identity=False): self._rows=rows self._columns=columns self.matrix.resize(rows*columns) if Identity: self._IdentityMatrix() property rows: def __get__(self): return self._rows def __set__(self, int x): self._rows = x property columns: def __get__(self): return self._columns def __set__(self, int y): self._columns = y cpdef double getVal(self, int r, int c): return self.matrix[r*self._columns+c] cpdef void setVal(self, int r, int c, double v): self.matrix[r*self._columns+c] = v cpdef void AddRow(self, vector[double] row): cdef int i if (row.size()!=self._columns): raise Exception('The size of appended row is wrong!') else: self._rows+=1 for i from 0 &lt;= i &lt;self._columns: self.matrix.push_back(row[i]) cpdef void AddColumn(self, vector[double] col): cdef int i if (col.size()!=self._rows): raise Exception('The size of …
type: Question
tagged with: struct
has comment: http://stackoverflow.com/comment/82440393
tagged with: vector
has answer: http://stackoverflow.com/a/47743506
has comment: http://stackoverflow.com/comment/82441931
has comment: http://stackoverflow.com/comment/82440881
has comment: http://stackoverflow.com/comment/82441986
answer count: 1
has comment: http://stackoverflow.com/comment/82440574
has comment: http://stackoverflow.com/comment/82441181
has comment: http://stackoverflow.com/comment/82441554

http://stackoverflow.com/comment/82659320
comment on: http://stackoverflow.com/a/47841546
type: AnswerComment
score: 0
type: Comment
has text: Worked perfectly. Thanks!

twilio
tag name: twilio
tags question: http://stackoverflow.com/q/47828222
type: Tag
tags question: http://stackoverflow.com/q/47851543

http://stackoverflow.com/comment/82408955
score: 0
type: QuestionComment
has text: if you have this table then: are you sure you connected with correct database ?
type: Comment
comment on: http://stackoverflow.com/q/47723790

http://stackoverflow.com/comment/82606816
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47821383
score: 0
has text: For the purpose of asking a question on SO, which is a Q&A site about programming it is completely irrelevant whether the data is coming from a CEP measurement or whether it depicts the locations of Yeti sightings. What matters is that the problem in terms of computer language is well defined. If there are unknown variables or functions in the code, one cannot help here.

selenium-chromedriver
tags question: http://stackoverflow.com/q/47768262
tags question: http://stackoverflow.com/q/47813386
tags question: http://stackoverflow.com/q/47772143
tags question: http://stackoverflow.com/q/47815334
tags question: http://stackoverflow.com/q/47854129
tag name: selenium-chromedriver
tags question: http://stackoverflow.com/q/47735375
tags question: http://stackoverflow.com/q/47706295
tags question: http://stackoverflow.com/q/47755571
tags question: http://stackoverflow.com/q/47711009
tags question: http://stackoverflow.com/q/47817665
tags question: http://stackoverflow.com/q/47787289
tags question: http://stackoverflow.com/q/47828773
type: Tag
tags question: http://stackoverflow.com/q/47822507

http://stackoverflow.com/q/47837808
has comment: http://stackoverflow.com/comment/82641227
has answer: http://stackoverflow.com/a/47861778
tagged with: python-imaging-library
accepted answer: http://stackoverflow.com/a/47861778
tagged with: python
tagged with: image
tagged with: optimization
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82640246
score: 1
has comment: http://stackoverflow.com/comment/82640944
answer count: 1
has title: PIL Image compression
downvote count: 0
upvote count: 1
has body: I'm working on a script that resizes and optimizes an image (Iphone pictures in this case) to be used on a website. So far I wrote this simple script that results in about 35% file size reduction, but I was hoping I could get the size down even more. Is there any way to optimize this script more? Any help is much appreciated! from PIL import Image img = Image.open('file location') newImage = img.resize((1024, 768), Image.ANTIALIAS) newImage.save('new file location', optimize=True, quality=95) newImage.show()
favorite count: 0
tagged with: image-compression
has comment: http://stackoverflow.com/comment/82640899
type: Question

http://stackoverflow.com/comment/82393886
type: QuestionComment
comment on: http://stackoverflow.com/q/47716634
score: 1
type: Comment
has text: There's plenty of numbers that floats just CAN NOT store with full precision, even before you get into the realm of serious inaccuracy. Not to mention the fact you're comparing two different calls of `time.time()`, which are already going to have some sub-second differences just due to execution order.

http://stackoverflow.com/q/47761343
has body: In the round() function it is possible to go from a float to i.e. a number rounded to the ten-spot: round(123.2,-1) yields 120 or round(123,2,0) yields 123 Is there a way to do the same thing using format? Like: "{:.-1f}".format(123.2) = "120" or in other notation? format(123.2,.-1f)="120"
tagged with: string
has comment: http://stackoverflow.com/comment/82484092
type: Question
has comment: http://stackoverflow.com/comment/82484122
has comment: http://stackoverflow.com/comment/82484176
tagged with: python
has comment: http://stackoverflow.com/comment/82484119
has title: Format float to decimals (ones, tens, hundreds ...)
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/47761423
accepted answer: http://stackoverflow.com/a/47761423
answer count: 1

http://stackoverflow.com/a/47724327
has comment: http://stackoverflow.com/comment/82409453
score: 1
has comment: http://stackoverflow.com/comment/82409436
has comment: http://stackoverflow.com/comment/82409463
has comment: http://stackoverflow.com/comment/82409483
downvote count: 0
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/47724241
has body: You can try something like this: from bs4 import BeautifulSoup page = """ text 1 text 2 Title text N1 Title text N2. text 3 text 4 """ soup = BeautifulSoup(page, 'html.parser') for i in soup.find_all(): if i.name == 'h4' and i.has_attr('class') and i['class'][0] == 'cat-title' and i.has_attr('id') and i['id'] == '55': if i.find("small") and i.find("small").text.strip()== "Title text N2.": break elif i.name == 'span'and i.has_attr('class') and i['class'][0] == 'myclass': print (i) Outputs: text 1 text 2
has comment: http://stackoverflow.com/comment/82409568

http://stackoverflow.com/a/47703973
downvote count: 0
score: 1
upvote count: 1
has body: Well, I actually think I figured this out. Basically, I created a new dataframe and re-index'd it. value original_index A 44 A 65 A 88 B 69 B 11 B 52 C 56 C 42 C 85 D 66 D 77 D 9 Loop through each index and and copy everything not in that index to a new dataframe. Then concat them all together. l = [] for i in df.index.unique(): d = df[~df.index.isin([i])].copy() d['new_index'] = i d.drop('original_index',axis=0,inplace=True) d.set_index('new_index',inplace=True) l.append(d) df2 = pd.concat(l,axis=0) Ouput: value new_index A 69 A 11 A 52 A 56 A 42 A 85 A 66 A 77 A 9 B 44 B 65 B 88 B 56 B 42 B 85 B 66 B 77 B 9 C 44 C 65 C 88 C 69 C 11 C 52 C 66 C 77 C 9 D 44 D 65 D 88 D 69 D 11 D 52 D 56 D 42 D 85 Now we can apply our groupby function on the new index and it will return results from values that were originally not in the index. group_df = df2.groupby(['new_index']).agg({'value' :[func1,func2]})'value' It works, but I'm sure there must be a better way.
answers question: http://stackoverflow.com/q/47702855
type: Answer
accepted answer of: http://stackoverflow.com/q/47702855
type: AcceptedAnswer

http://stackoverflow.com/a/47726753
answers question: http://stackoverflow.com/q/47726643
type: Answer
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47726643
has body: You shouldn't be looping over the dict to find the matching keys, that's very inefficient. A dict is designed to do fast lookups: you give it the key and it gives you the value. Eg, dataDict["a"] results in "1". Also, as Tim Pietzcker mentions, doing if dataInput == key will only work if dataInput consists of a single letter, because it compares the whole dataInput string to key. Here's a simple way to do the desired conversion. We do the lookups in a list comprehension, which creates a list of the converted values, and then we pass that list to .join to create a string. (I've changed the names of your variables to conform with the PEP-008 style guide). data_dict = { "a": "1", "b": "2", "c": "3", } data_input = "aabbccba" s = ''.join([data_dict[c] for c in data_input]) print(s) output 11223321 However, that's not safe: it will fail with KeyError if data_input contains a char that's not in the dictionary. Here's a better way: it adds an empty string if it gets a bad char. data_input = "aaxbbcycbaz" s = ''.join([data_dict.get(c, '') for c in data_input]) print(s) output 11223321 Alternatively, we could convert bad data to some special value, eg 0. data_input = "aaxbbcycbaz" s = ''.join([data_dict.get(c, '0') for c in data_input]) print(s) output 11022303210 Just for fun, here's a "functional" version. Guido would probably not approve of this one. :) data_input = "aaxbbcycbaz" print(''.join(filter(None, map(data_dict.get, data_input)))) 11223321
has comment: http://stackoverflow.com/comment/82416204
has comment: http://stackoverflow.com/comment/82417274
has comment: http://stackoverflow.com/comment/82416588
has comment: http://stackoverflow.com/comment/82417473

http://stackoverflow.com/q/47799803
tagged with: python
accepted answer: http://stackoverflow.com/a/47815473
type: AnsweredQuestion
has title: "Installing From Source" Within Anaconda Environment
tagged with: anaconda
tagged with: pytorch
score: 7
answer count: 1
downvote count: 0
upvote count: 7
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47815473
has body: What I would like to do: I am using macOS and Anaconda 2. I would like to install a Python package (specifically PyTorch) from source. I would like to install all the dependencies and the package itself within an Anaconda environment. I don't want this Anaconda environment to be the default/ root Anaconda environment, but an environment I particularly created for installing this package and its dependencies from source. What I have done: First, I created the environment as follows conda create --name my_env python=3.5 Now, the instructions for installing PyTorch from source are as follows: export CMAKE_PREFIX_PATH=[anaconda root directory] conda install numpy pyyaml setuptools cmake cffi git clone --recursive https://github.com/pytorch/pytorch MACOSX_DEPLOYMENT_TARGET=10.9 CC=clang CXX=clang++ python setup.py install Now, my questions are: Following this instructions, requires me to specify anaconda root directory for the CMAKE_PREFIX_PATH. What should that directory be given that I want everything set-up in my_env? Is it reasonable to create an extra environment for a package installed from source and its dependencies? Why would one do or not do it? My motivation is mainly fear that one day I may screw my system up big time and hence want things to be cleanly separated. If you can only answer one of the two questions, that is already greatly appreciated. Thanks!

http://stackoverflow.com/q/47805878
type: Question
has answer: http://stackoverflow.com/a/47805922
has comment: http://stackoverflow.com/comment/83957307
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/83955952
tagged with: numpy
has body: How do I change values less than -3 to -3 and more than 1 to 1? randomdata = DataFrame(np.random.randn(400, 4))
tagged with: pandas
has comment: http://stackoverflow.com/comment/82573078
type: UnansweredQuestion
score: 1
answer count: 1
downvote count: 0
upvote count: 1
has title: Restrict values in DataFrame to specified range
favorite count: 0

http://stackoverflow.com/comment/82392954
type: Comment
comment on: http://stackoverflow.com/q/47713302
has text: Thanks for this hint
score: 0
type: QuestionComment

http://stackoverflow.com/comment/82521258
comment on: http://stackoverflow.com/q/47763006
type: Comment
type: QuestionComment
score: 0
has text: FYI. The recommended (and universally l loved) way of reading data is using the Dataset API - https://www.tensorflow.org/programmers_guide/datasets. You might want to try it instead. Otherwise, can you post relevant code to clearly illustrate your approach and issue. Without additional info, I am not sure why something like `print session.run(reader.read())` does not work for you.

http://stackoverflow.com/a/67298072
score: 0
answers question: http://stackoverflow.com/q/47800794
upvote count: 1
downvote count: 1
has body: Open PowerShell. Run conda init (not conda init powershell as the accepted answer suggests). Close and re-open PowerShell. Use conda normally.
has comment: http://stackoverflow.com/comment/133466687
type: Answer

http://stackoverflow.com/comment/82362796
type: QuestionComment
comment on: http://stackoverflow.com/q/47701090
has text: So i would collect the names/scores in a list, and then write the whole list to the file once you are done
type: Comment
score: 0

http://stackoverflow.com/a/47772610
type: Answer
has comment: http://stackoverflow.com/comment/82508958
answers question: http://stackoverflow.com/q/47750850
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47750850
has body: A couple of changes to be made here: In buildings_form.html, render media in head section of your template. {{ form.media }} {% csrf_token %} {{ form.as_p }} When subclassing ModelForm like you have, it is also necessary to set it as the form class in your custom CreateView. class MapCreateView(CreateView): form_class = MapForm template_name = 'buildings_form.html' Also in custom ModelForm, widgets for fields should be specified in widgets class property. class BuildingForm(ModelForm): class Meta: model = Building fields = ('point',) widgets = { 'point': gis_forms.OSMWidget( attrs={ 'map_width': 800, 'map_height': 500, } ) }
score: 8
upvote count: 8

http://stackoverflow.com/comment/82394078
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47716897
has text: You’re comparing `li.index(x) != li.index(max(li))`. `li.index(3)` is the same both times `x == 3`. Use `for i, x in enumerate(li)` instead.

http://stackoverflow.com/comment/82674294
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47854745
has text: @NoCUBes: `\n` is the escape sequence for a newline, the character that tells your terminal or console or text editor that the line has ended and to start a new line for the text that follows. `function(*<expression>)` tells Python to take all values from a sequence (produced by the expression) and apply the values as separate arguments. If `l = ['foo', 'bar']`, then `print(*l)` would be the same thing as `print('foo', 'bar')`. So `print(*l, sep='\n')` prints all values in `l` separately, writing a newline between each.
score: 0

http://stackoverflow.com/a/47814100
score: 2
accepted answer of: http://stackoverflow.com/q/47813718
type: Answer
has comment: http://stackoverflow.com/comment/82590194
has body: I think you should iterate over the "img" or over the "a". You can write something like this: for entry in info_block: try: for a in entry.find_all("a"): title = a.find('img').get('title') url = a.get('href') urlcontent = BeautifulSoup(requests.get(url).content, "lxml") row = [{'Company Name': title, 'Web Page': url}] references = references.append(row, ignore_index=True) except: pass
upvote count: 2
has comment: http://stackoverflow.com/comment/82590751
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82590587
answers question: http://stackoverflow.com/q/47813718

http://stackoverflow.com/a/47759650
has body: You have a TypeError execption. It's raised with message item 352 from tags hasn't type (NoneType), еhis means that in the sent (ntlk.tree.Tree class) has a NoneType object in sequence. This line is the reason for the exception, because str.join can take only str. You need check check each item in the sent iterable to the affiliation of the str type. You can use filter built-in function for this, but the result should be cast to Tree type. filter(bool, sent) # return a iterator with valid items For check which a iterable object has a NoneType item you can do this: if not all(sent): print("NoneType object in \"{}\": {}".format(sent.label(), sent)) sent = cast_to_tree_function(filter(bool, sent)) # update set object to valid items
score: 0
answers question: http://stackoverflow.com/q/47758858
has comment: http://stackoverflow.com/comment/82502890
has comment: http://stackoverflow.com/comment/82503457
type: Answer
has comment: http://stackoverflow.com/comment/82482438
has comment: http://stackoverflow.com/comment/82480654

http://stackoverflow.com/comment/82580400
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47807913
type: Comment
has text: how to use for a user if ernest is a user name means how to mention? like profile.ernest.location....

http://stackoverflow.com/comment/82381526
comment on: http://stackoverflow.com/a/47704213
score: 0
type: AnswerComment
has text: Oh you are correct, they are individual raster shapes, not vectors! Sorry I missed that. I don't know why but I just expected them to be combined into one raster already. I don't suppose there is a quick, inbuilt way to combine all those rasters into one? As it is, the zorder method does that anyway and so is a better solution, I think.
type: Comment

http://stackoverflow.com/q/47763792
has answer: http://stackoverflow.com/a/47764885
has title: How to rewrite this dictionary definition so PyCharm does not warn?
downvote count: 1
duplicate of: http://stackoverflow.com/q/8406242
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47823377
tagged with: pycharm
linked to: http://stackoverflow.com/q/8406242
possible better answer: http://stackoverflow.com/a/47764885
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/82489070
upvote count: 4
has comment: http://stackoverflow.com/comment/82489012
has comment: http://stackoverflow.com/comment/82488981
has answer: http://stackoverflow.com/a/47823377
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/82509805
answer count: 2
has body: How to rewrite this dictionary definition so PyCharm does not warn? My understanding is that the form it is currently in is already dictionary literal. I'm using PyCharm 2017.2.4, but I don't think the version matters.

variables
tags question: http://stackoverflow.com/q/47780550
tags question: http://stackoverflow.com/q/47723816
tag name: variables
tags question: http://stackoverflow.com/q/47743047
tags question: http://stackoverflow.com/q/47738316
tags question: http://stackoverflow.com/q/47848269
tags question: http://stackoverflow.com/q/47722948
tags question: http://stackoverflow.com/q/47777484
tags question: http://stackoverflow.com/q/47724268
tags question: http://stackoverflow.com/q/47715486
tags question: http://stackoverflow.com/q/47787405
tags question: http://stackoverflow.com/q/47804782
tags question: http://stackoverflow.com/q/47736568
tags question: http://stackoverflow.com/q/47707630
tags question: http://stackoverflow.com/q/47790591
tags question: http://stackoverflow.com/q/47746758
type: Tag
tags question: http://stackoverflow.com/q/47821792
tags question: http://stackoverflow.com/q/47710467

http://stackoverflow.com/q/47794835
upvote count: 2
has comment: http://stackoverflow.com/comment/82550616
has comment: http://stackoverflow.com/comment/82550909
answer count: 1
downvote count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/82550610
has comment: http://stackoverflow.com/comment/82550751
has title: Pandas - Groupby - capture first value of a column - Wrong ouput
has comment: http://stackoverflow.com/comment/82551190
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82551082
has comment: http://stackoverflow.com/comment/82550690
has body: I have a pandas dataframe : DOCUMENT_LEDGER_ID ACTUAL_START_DATE 376878 2017-02-01 376880 2017-02-01 16043792 2017-01-05 16043792 2017-02-04 I want to group it on the DOCUMENT_LEDGER_ID and want the first value of ACTUAL_START_DATE That is my expected output : Id ACTUAL_START_DATE 376878 2017-02-01 376880 2017-02-01 16043792 2017-01-05 I have tried the following, but it doesn't seem to work: dictToAgg = {} dictToAgg["ACTUAL_START_DATE"] = "first" cycleTimeFilteringUnique = cycleTimeFiltering.groupby('DOCUMENT_LEDGER_ID', as_index=False).first() The output I am getting is this : Id ACTUAL_START_DATE 376878 2017-02-01 376880 2017-02-01 16043792 2017-02-04 I have seen similar questions, but am unable to understand the mistake I am committing.
tagged with: pandas
tagged with: group-by
tagged with: dataframe
accepted answer: http://stackoverflow.com/a/47795193
has comment: http://stackoverflow.com/comment/82551244
has comment: http://stackoverflow.com/comment/82551172
has answer: http://stackoverflow.com/a/47795193
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82550810
has comment: http://stackoverflow.com/comment/82551109
has comment: http://stackoverflow.com/comment/82550776

http://stackoverflow.com/q/47775470
has body: Looking for some style clarification on Python function design. I understand that Python is "pass reference by value" in its function call semantics, however I still often see code where people have returned a mutable object they've done work on within the function. A simple example: def example(pandasDataframe): pandasDataframe['New Col'] = pandasDataframe['Current Col'] + 'Foo' return pandasDataframe And then the function is used like this df = example(df) To me, this is a waste of time as both the return statement and the assignment in the call are simply not required (for mutable objects). Yet this is a very common idiom (particularly in Pandas code) Is this a recognised/formal convention when coding in Python? I'm wondering if this is regarded as laudable defensive programming, or at least some of the time a lack of understanding by some programmers? Can anyone clarify any formal rules, or if this is left to the developer as a matter of personal taste/opinion?
has answer: http://stackoverflow.com/a/47775779
type: Question
has title: Returning a Mutable Argument From A Python Function
type: UnansweredQuestion
tagged with: python
score: 0
answer count: 2
tagged with: pandas
has answer: http://stackoverflow.com/a/47775755

http://stackoverflow.com/comment/82548475
comment on: http://stackoverflow.com/a/47793757
has text: I would change the relative path to an absolute path, but I plan on possibly publishing my python script, and I don't know where the user of my script would put the folder for my script.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/82600132
type: AnswerComment
comment on: http://stackoverflow.com/a/47819083
has text: I would think so, yes. But the OP's question clearly displays a set as the result.
score: 1
type: Comment

http://stackoverflow.com/q/47802544
type: Question
has comment: http://stackoverflow.com/comment/82566615
has body: Currently, our group is working on building an GUI for our platform. We used pyqt5 so that we make our code python 3.5. However, when we want to add other group's function to our code, it turns out that they are using some packages that only supported in python 2.7. So my question is, how can we import their files into our file, so that both can work properly?
type: UnansweredQuestion
tagged with: python
has title: How to import a python 2.7 file into a python 3.5 file
has comment: http://stackoverflow.com/comment/82566475
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/82566498
tagged with: python-3.5
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/82566476
has comment: http://stackoverflow.com/comment/82566461
has comment: http://stackoverflow.com/comment/82566441
has comment: http://stackoverflow.com/comment/82566565
has comment: http://stackoverflow.com/comment/82566464

http://stackoverflow.com/q/47725258
tagged with: python
upvote count: 3
answer count: 2
tagged with: random
downvote count: 0
has title: builtins.ImportError: cannot import name 'choices'
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82411229
has body: I am trying to import choices from the random library in python but I get an error. from tkinter import * from itertools import accumulate from random import choices from string import ascii_lowercase I get the error that says File "c:\Users\coope\Downloads\hw3.py", line 26, in from random import choices builtins.ImportError: cannot import name 'choices'
favorite count: 0
has answer: http://stackoverflow.com/a/47725276
type: Question
score: 3
has answer: http://stackoverflow.com/a/47725280

http://stackoverflow.com/comment/82680216
type: QuestionComment
comment on: http://stackoverflow.com/q/47815762
score: 0
type: Comment
has text: I would have expected `smtp` and `SMTP` to be the same, since essentially `SMTP`is `smtplib.SMTP` which was supposed to be patched. Patching meaning effectively replaced by a `MagicMock`.

http://stackoverflow.com/comment/82390835
has text: can u show the code where you connecting jquery in template?
comment on: http://stackoverflow.com/a/47713934
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/comment/82642230
comment on: http://stackoverflow.com/a/47838873
score: 0
type: AnswerComment
has text: @Nisa Here you go check live running code here : https://repl.it/@aadi1111/test1
type: Comment

http://stackoverflow.com/q/47736426
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/47736915
score: 0
tagged with: list
answer count: 1
has comment: http://stackoverflow.com/comment/82433288
type: Question
has comment: http://stackoverflow.com/comment/82433276
type: UnansweredQuestion
has title: common_ancestor function for nested tree dictionary in python
has body: I am trying to create a function called "common_ancestor()" that takes two inputs: the first a list of string taxa names, and the second a phylogenetic tree dictionary. It should return a string giving the name of the taxon that is the closest common ancestor of all the species in the input list. Already made a separate function called "list_ancestors" that gives me the general ancestors of the elements in the list. Also, have a dictionary I am working with. tax_dict = { 'Pan troglodytes': 'Hominoidea', 'Pongo abelii': 'Hominoidea', 'Hominoidea': 'Simiiformes', 'Simiiformes': 'Haplorrhini', 'Tarsius tarsier': 'Tarsiiformes', 'Haplorrhini': 'Primates', 'Tarsiiformes': 'Haplorrhini', 'Loris tardigradus':'Lorisidae', 'Lorisidae': 'Strepsirrhini', 'Strepsirrhini': 'Primates', 'Allocebus trichotis': 'Lemuriformes', 'Lemuriformes': 'Strepsirrhini', 'Galago alleni': 'Lorisiformes', 'Lorisiformes': 'Strepsirrhini', 'Galago moholi': 'Lorisiformes' } def halfroot(tree): taxon = random.choice(list(tree)) result = [taxon] for i in range(0,len(tree)): result.append(tree.get(taxon)) taxon = tree.get(taxon) return result def root(tree): rootlist = halfroot(tree) rootlist2 = rootlist[::-1] newlist = [] for e in range(0,len(rootlist)): if rootlist2[e] != None: newlist.append(rootlist2[e]) return newlist[0] def list_ancestors(taxon, tree): result = [taxon] while taxon != root(tree): result.append(tree.get(taxon)) taxon = tree.get(taxon) return result def common_ancestors(inputlist,tree) biglist1 = [] for i in range(0,len(listname)): biglist1.append(list_ancestors(listname[i],tree)) "continue so that I get three separate lists where i can cross reference all elements from the first list to every other list to find a common ancestor " the result should look something like print(common_ancestor([’Hominoidea’, ’Pan troglodytes’,’Lorisiformes’], tax_dict) Output: ’Primates’"

http://stackoverflow.com/comment/82556936
type: Comment
has text: @coldspeed I was just taking the first line as an example, I ment that the variable at that place stands for temperature. I'm sorry for the confusion.
score: 0
comment on: http://stackoverflow.com/q/47797723
type: QuestionComment

http://stackoverflow.com/q/47703965
has answer: http://stackoverflow.com/a/47725348
accepted answer: http://stackoverflow.com/a/47725348
upvote count: 1
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/82368619
has title: Why does cx_Freeze use Win32GUI rather than Win64GUI?
has body: The command line of an application built with cx_Freeze can be hidden with Win32GUI. Why does cx_Freeze choose to reference Win32GUI rather than Win64GUI? This suggests that cx_Freeze has either not been updated to include this feature, or is calling a 32 bit command and yet almost all Windows computers are now 64 bit. Is there a reason why the inplamenters chose to call it this? I have researched for a long time but have not found any answer, any thoughts would be appreciated. Thank you.
favorite count: 0
type: Question
tagged with: python
tagged with: cx-freeze
type: AnsweredQuestion
score: 0

http://stackoverflow.com/comment/82450864
type: Comment
has text: Ummm, why don't you just pass your session to the function call, i.e. `return func(session=session, *args, **kwargs)`. Of course, if you attempt to wrap a function that doesn't have a `session` keyword argument the call will fail but you should know your function signatures before you decorate them.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47745356

http://stackoverflow.com/comment/82505868
comment on: http://stackoverflow.com/q/47760431
type: QuestionComment
score: 0
has text: It is almost certainly an Excel issue since that is how Excel behaves when you insert images. Particularly if the have a high DPI since the default is taken as 96 DPI and images are scaled up or down when displayed in Excel accordingly. (In your case 96/300 = ~1/3 which you are seeing.) XlsxWriter just replicates/implements Excel's image handling.
type: Comment

http://stackoverflow.com/a/47790682
has comment: http://stackoverflow.com/comment/82651224
has comment: http://stackoverflow.com/comment/82758369
has body: first of all you don't really need to check tree for loops, since clojure's data structures don't have circular references (unless you don't use mutable state with atoms referencing to another atoms, which is an obvious code smell). The simple way of traversal could look like this (this way is referenced by lots of lisp (and overall programming) books): user&gt; (defn dfs [goal? data] (if (goal? data) data (loop [data data] (when-let [[x &amp; xs] (seq data)] (cond (goal? x) x (coll? x) (recur (concat x xs)) :else (recur xs)))))) user&gt; (dfs #{10} [1 [3 5 [7 9] [10] 11 12]]) 10 user&gt; (dfs #{100} [1 [3 5 [7 9] [10] 11 12]]) nil in addition there are more concise (and thus idiomatic i guess) ways to do this in clojure. The simplest one is to use tree-seq: user&gt; (defn dfs [goal? tree] (first (filter goal? (tree-seq coll? seq tree)))) #'user/dfs user&gt; (dfs #{10} [1 [3 5 [7 9] [10] 11 12]]) 10 user&gt; (dfs #{100} [1 [3 5 [7 9] [10] 11 12]]) nil user&gt; (dfs (every-pred number? even?) [1 [3 5 [7 9] [10] 11 12]]) 10 tree-seq is lazy, so it only traverses tree until you find the needed value. another way is to use clojure's zippers: user&gt; (require '[clojure.zip :as z]) nil user&gt; (defn dfs [goal? tree] (loop [curr (z/zipper coll? seq identity tree)] (cond (z/end? curr) nil (goal? (z/node curr)) (z/node curr) :else (recur (z/next curr))))) #'user/dfs user&gt; (dfs #{10} [1 [3 5 [7 9] [10] 11 12]]) 10 user&gt; (dfs #{100} [1 [3 5 [7 9] [10] 11 12]]) nil user&gt; (dfs (every-pred number? even?) [1 [3 5 [7 9] [10] 11 12]]) 10
has comment: http://stackoverflow.com/comment/82752546
type: Answer
has comment: http://stackoverflow.com/comment/82643447
has comment: http://stackoverflow.com/comment/82642424
score: 3
upvote count: 3
accepted answer of: http://stackoverflow.com/q/47783359
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82756554
has comment: http://stackoverflow.com/comment/82640988
answers question: http://stackoverflow.com/q/47783359

http://stackoverflow.com/q/47741833
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/82443838
has comment: http://stackoverflow.com/comment/82443788
tagged with: python
score: 4
has title: Designing a Sqrt function in Python
answer count: 3
has answer: http://stackoverflow.com/a/47742256
has answer: http://stackoverflow.com/a/47741932
has comment: http://stackoverflow.com/comment/82443790
has answer: http://stackoverflow.com/a/47741916
has body: This is a bit of an academic exercise. I'm implementing a sqrt function in Python. Here's my code, def mySqrt(x): low, high = 1, x while low &lt; high: mid = low + (high - low)/2 if mid * mid &gt; x: high = mid - 1 elif mid * mid &lt; x: low = mid else: return mid return low The issue is that this doesn't work when the number isn't a perfect square. I want to redesign this function still using the log n complexity which would return the value of the sqrt to a specified number of decimal places. So it's something like, def sqrt(num, param): pass thus sqrt(5, 2) = 2.41 sqrt(5, 3) = 2.414 Can someone help me with this. Thanks.
has comment: http://stackoverflow.com/comment/82444124
favorite count: 0
type: Question
upvote count: 4
tagged with: python-3.x

http://stackoverflow.com/q/47791878
has comment: http://stackoverflow.com/comment/82547444
has comment: http://stackoverflow.com/comment/82574261
type: AnsweredQuestion
score: 0
tagged with: apache-spark
upvote count: 1
answer count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/47806883
has comment: http://stackoverflow.com/comment/82575085
has body: How to merge multiple rows into single cell based on id using PySpark? I have a dataframe with ids and products. First I want to merge the products with the same id together into a list, then I want to count the number of occurrences of each unique list. Input example 1: id,product 1,HOME 1,mobile 2,watch 2,mobile 3,HOME 3,mobile 4,cd 4,music 4,video Output: product,count HOME-mobile,2 mobile-watch,1 cd-music-video,1 Example 2 with sql code: Input example: cloths,brad cloths,edu cloths,keith cloths,stef enter,andr enter,char enter,danny enter,lucas Code: SELECT SS.SEC_NAME, STUFF((SELECT '- ' + US.USR_NAME FROM USRS US WHERE US.SEC_ID = SS.SEC_ID ORDER BY USR_NAME FOR XML PATH('')), 1, 1, '') [SECTORS/USERS] FROM SALES_SECTORS SS GROUP BY SS.SEC_ID, SS.SEC_NAME ORDER BY 1 Output: cloths,brad-edu-keith-stef enter,andr-char-danny-lucas In this example the output does not have the count, but it should be included. I would like to solve this in PySpark instead of sql/pig.
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82574409
tagged with: pyspark
has title: How to merge multiple rows into single cell based on id and then count?
accepted answer: http://stackoverflow.com/a/47806883
tagged with: dataframe
tagged with: python

http://stackoverflow.com/q/47827390
tagged with: python
tagged with: data-science
accepted answer: http://stackoverflow.com/a/47827650
has comment: http://stackoverflow.com/comment/82638660
has title: "How read part of large CSV or read it with any step"
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82750259
score: 0
has answer: http://stackoverflow.com/a/47827650
tagged with: visualization
has body: I have a very large dataset with 125497040 rows and 6 columns. When I try to read the whole CSV file in pandas, my system crashes and hence I read the file in chunks. I wanted to know is there a way to visualize the whole data by reading in chunks?
has comment: http://stackoverflow.com/comment/82617171
type: Question
has comment: http://stackoverflow.com/comment/82638626
has comment: http://stackoverflow.com/comment/82617066
answer count: 1

http://stackoverflow.com/q/47719969
tagged with: python
has answer: http://stackoverflow.com/a/47720083
has title: Function that returns the row in an UNSORTED multidimensional array, A, that sums to the closest number to B?
type: Question
tagged with: numpy
tagged with: python-2.7
linked to: http://stackoverflow.com/q/47718072
answer count: 1
accepted answer: http://stackoverflow.com/a/47720083
type: AnsweredQuestion
score: 0
tagged with: multidimensional-array
has body: Related to my other recent question Function that returns the closest number to B that&#39;s in an UNSORTED multidimensional array, A? What I've made sense of so far: import numpy as np def get_R(A,B): A = np.asanyarray(A) assert A.ndim == 2 sums = A.sum(axis=1) close = sums.argmin(B) return A.flat[close] I'm being returned an error ValueError: axis(=9) out of bounds for get_r([[1,3,6,-8],[2,7,1,0],[4,5,2,8],[2,3,7,10]],9) when I should be getting array([2,7,1,0])

http://stackoverflow.com/q/47767294
tagged with: neural-network
has title: How to access the weights (parameters) of Neural Network after every certain epochs during training process
tagged with: python
has answer: http://stackoverflow.com/a/47770591
score: 0
answer count: 2
type: UnansweredQuestion
tagged with: tensorflow
type: Question
has body: I am training a Neural Network using Tensorflow. I am calculating the training cost after every 100 epochs and printing the cost. I am using the following training code for my model. def model(X_train, Y_train, layers_dims,learning_rate = 0.0001, num_epochs = 100, minibatch_size = 32, print_cost = True): ops.reset_default_graph() tf.set_random_seed(1) seed = 3 (n_x, m) = X_train.shape n_y = Y_train.shape[0] costs = [] beta = 0 X, Y,keep_prob= create_placeholders(n_x, n_y) # Initialize parameters parameters = initialize_parameters(layers_dims) # Forward propagation: Build the forward propagation in the tensorflow graph Z = forward_propagation(X, parameters, keep_prob) cost = compute_cost(Z, Y) L3=len(layers_dims) regularizers=tf.constant(0,dtype=tf.float64) for l3 in range(1,L3): regularizers = regularizers+tf.nn.l2_loss(parameters['W' + str(l3)]) cost = tf.reduce_mean(cost + beta * regularizers) with tf.device('/gpu:0'): optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(cost) init = tf.global_variables_initializer() with tf.Session(config=tf.ConfigProto(log_device_placement=True)) as sess: sess.run(init) for epoch in range(num_epochs): epoch_cost = 0. # Defines a cost related to an epoch num_minibatches = int(m / minibatch_size) # number of minibatches of size minibatch_size in the train set seed = seed + 1 minibatches = random_mini_batches(X_train, Y_train, minibatch_size, seed) for minibatch in minibatches: (minibatch_X, minibatch_Y) = minibatch _ , minibatch_cost = sess.run([optimizer, cost], feed_dict={X: minibatch_X, Y: minibatch_Y,keep_prob:1}) epoch_cost += minibatch_cost / num_minibatches if print_cost == True and epoch % 100 == 0: print ("Cost after epoch %i: %f" % (epoch, epoch_cost)) if print_cost == True and epoch % 5 == 0: costs.append(epoch_cost) plt.plot(np.squeeze(costs)) plt.ylabel('cost') plt.xlabel('iterations (per tens)') plt.title("Learning rate =" + str(learning_rate)) plt.show() parameters = sess.run(parameters) print …
has answer: http://stackoverflow.com/a/47767708

http://stackoverflow.com/comment/82568200
comment on: http://stackoverflow.com/a/47803369
score: 0
type: AnswerComment
has text: I know I didn't ask this, but is there a way to sort the counts within each group? Here they are sorted, but I know I would need to sort them myself in general.
type: Comment

http://stackoverflow.com/q/47707805
answer count: 1
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/47707915
has answer: http://stackoverflow.com/a/47707915
type: Question
has body: I have a QuestionSet that is a manytomany of questions. Each QuestionSet has multiple questions associated with it. I want to get a list of all unique questions that are in two (or more) QuestionSets For example: First QuestionSet = Questions(1,2,3) Second QuestionSet = Questions(1,3,4) Output: List/Queryset/Something of Questions(1,2,3,4) models.py class QuestionSet(models.Model): name = models.CharField(max_length=255) questions = models.ManyToManyField(Question) class Question(models.Model): question_num = models.IntegerField(default=0,blank=False)
has title: Django create queryset or list of unique items in multiple manytomany instances
tagged with: django
tagged with: python

http://stackoverflow.com/comment/88037473
has text: from selenium.webdriver.chrome.options import Options opts = Options() opts.set_headless() driver = webdriver.Chrome(options=opts); you can use this method to scrape data without pops up
type: AnswerComment
comment on: http://stackoverflow.com/a/47743231
score: 0
type: Comment

http://stackoverflow.com/comment/82568053
score: 0
type: Comment
type: QuestionComment
has text: @alfasin Yes how would I remove trailling coma? Oh lol sounded stupid I think I got the fix
comment on: http://stackoverflow.com/q/47803263

http://stackoverflow.com/q/47829089
tagged with: python
tagged with: apache-spark
score: 1
answer count: 1
downvote count: 0
tagged with: hdfs
upvote count: 1
has body: I'm reading in a spark dataframe that's stored in the parquet format on the local cluster's HDFS. The parquet data is split among approx 96,000 individual files. Now I know that ideally the data wouldn't be split into so many small files, but for now I've got to deal with it in this format. I'm using pyspark v2.2.0. When I run spark.read.parquet(data_root), something strange happens: spark sequentially spawns a series of jobs, each with about 2000 tasks. It spawns up 48 of these jobs, each with one stage. Across these 48 jobs it executes just around 96,000 tasks - I assume it runs a task for each parquet file. Each job only takes about 2 seconds to run. The thing I find strange is that this doesn't happen in one job with 96,000 tasks, because that would be faster (no stage boundaries). Where does the number 2000 come from? Is there a parameter I can tune to force more of these tiny tasks into the same job, thereby speeding things up?
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82620742
has answer: http://stackoverflow.com/a/47829210
type: UnansweredQuestion
has title: How to speed up spark's parquet reader with many small files
tagged with: pyspark

http://stackoverflow.com/comment/82490919
comment on: http://stackoverflow.com/q/47764684
score: 0
type: Comment
type: QuestionComment
has text: Why don't you want to create two jobs? What's wrong with it?

http://stackoverflow.com/a/47851415
has comment: http://stackoverflow.com/comment/82667484
answers question: http://stackoverflow.com/q/47850280
type: Answer
score: 10
has comment: http://stackoverflow.com/comment/82667313
has comment: http://stackoverflow.com/comment/95352122
has body: Since this is a numerically heavy task (a lot of iterations around a matrix, or a tensor), I always suggest to use libraries that are good at this: numpy. A properly installed numpy should be able to utilize the underlying BLAS (Basic Linear Algebra Subroutines) routines which are optimized for operating an array of floating points from the memory hierarchy perspective. imread should already give you the numpy array. You can get the reshaped 1d array of the image of the red channel by import numpy as np val = np.reshape(image[:,:,0], -1) the mean of such by np.mean(val) and the standard deviation by np.std(val) In this way, you can get rid of two layers of python loops: count = 0 mean = 0 delta = 0 delta2 = 0 M2 = 0 for i, file in enumerate(tqdm(first)): image = cv2.imread(file) val = np.reshape(image[:,:,0], -1) img_mean = np.mean(val) img_std = np.std(val) ... The rest of the incremental update should be straightforward. Once you have done this, the bottleneck will become the image loading speed, which is limited by disk read operation performance. For that regard, I suspect using multi-thread as others suggested will help much based on my prior experience.
upvote count: 11
type: AcceptedAnswer
downvote count: 1
has comment: http://stackoverflow.com/comment/82667336
accepted answer of: http://stackoverflow.com/q/47850280
has comment: http://stackoverflow.com/comment/82667331
has comment: http://stackoverflow.com/comment/82667348

http://stackoverflow.com/a/50286101
upvote count: 3
downvote count: 0
has body: Answer by Dhanisha works fine, as i am adding explanation on top off it remove import matplotlib.pyplot as plt add import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt The reason behind such behavior is if you are running it on server switch do not have gui support or non interactive mode. If you run same code on jupyter notebook, it would work fine. see below links https://matplotlib.org/faq/howto_faq.html https://github.com/matplotlib/matplotlib/issues/9954
score: 3
type: Answer
answers question: http://stackoverflow.com/q/47710022

http://stackoverflow.com/comment/136248646
type: QuestionComment
score: 0
has text: `math.isqrt()` gives the truncated integer square root of an integer argument, even if the argument is too big to fit in a float. Does that meet your requirements?
comment on: http://stackoverflow.com/q/47854635
type: Comment

http://stackoverflow.com/q/47826246
type: Question
tagged with: python
has title: Python currency converter, float object is not iterable
has body: currency_input = input('Enter GBP values (separated by whitespace): ') currency_list = currency_input.split() # arrays to store currencies and converted currencies GBPvalues = [] convertedEuros = [] convertedDollars = [] convertedYen = [] convertedRupee = [] # stores GBP values in array GBPvalues for x in currency_list: GBPvalues.append(int(x)) # function for converting GBP to euros def euroConversion(): for x in GBPvalues: euros = x * 114 / 100 for e in euros: convertedEuros.append(euros) # function for converting GBP to dollars def dollarConversion(): for x in GBPvalues: dollars = x * 134 / 100 for d in dollars: convertedDollars.append(float(dollars)) # functions for converting GBP to yen def yenConversion(): for x in GBPvalues: yen = x * 15074 / 100 for y in yen: convertedYen.append(float(dollars)) # functions for converting GBP to rupee def rupeeConversion(): for x in GBPvalues: rupee = x * 8614 / 100 for r in rupee: convertedRupee.append(float(rupee)) # function to output the currency and converted currency def conversionOutput(): print('1. Euros') print('2. Dollars') print('3. Yen') print('4. Rupees') print('5. Exit') userInput = input() if userInput == '1': euroConversion() for i in range(10): print(GBPvalues[i] + convertedEuros[i]) # adds up total of GBP and euros totalGBP = sum(GBPvalues) totalEuros = sum(convertedEuros) print(totalGBP) print(totalEuros) if userInput == '2': dollarConversion() for i in range(10): print(GBPvalues[i] + convertedDollars[i]) # adds up total of GBP and dollars totalGBP = sum(GBPvalues) totalDollars = sum(convertedDollars) print(totalGBP) print(totalDollars) if userInput == '3': yenConversion() for i in range(10): print(GBPvalues[i] + convertedYen[i]) # adds up total of GBP and yen totalGBP = sum(GBPvalues) totalYen = sum(convertedYen) print(totalGBP) print(totalYen) if userInput == '4': rupeeConversion() for i in range(10): print(GBPvalues[i] + convertedRupee[i]) # adds up total of GBP rupee totalGBP = sum(GBPvalues) totalRupee …
has answer: http://stackoverflow.com/a/47826609
accepted answer: http://stackoverflow.com/a/47826609
type: AnsweredQuestion
score: 0
answer count: 1
upvote count: 1
downvote count: 1
favorite count: 0

http://stackoverflow.com/comment/82664375
score: 0
has text: I just notice that is for exe files
comment on: http://stackoverflow.com/q/47849798
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82517055
type: QuestionComment
has text: Thanks I've done that and it's returned ; <bound method Response.json of <Response [200]>> How can I see my data in order to put it into a dataframe?
comment on: http://stackoverflow.com/q/47777908
score: 0
type: Comment

http://stackoverflow.com/q/47716768
has comment: http://stackoverflow.com/comment/82393705
has comment: http://stackoverflow.com/comment/82394103
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82394041
score: 0
has title: There is no constant in python so what to do to make variable constant
has comment: http://stackoverflow.com/comment/82393827
linked to: http://stackoverflow.com/q/2682745
tagged with: python
has body: I am C++ programmer and new to python.I found many good things in Python but one thing that was strange to me that there is no way to make variable constant in Python Here is my code: def main(): a = 10 if __name__ == "__main__": main() how can I make a constant. Thanks for your help.
has comment: http://stackoverflow.com/comment/82394166
has comment: http://stackoverflow.com/comment/82394315
has comment: http://stackoverflow.com/comment/82393863
tagged with: constants
has comment: http://stackoverflow.com/comment/82395504
duplicate of: http://stackoverflow.com/q/2682745
answer count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/82393707
type: UnansweredQuestion
downvote count: 2
has comment: http://stackoverflow.com/comment/82393762
has comment: http://stackoverflow.com/comment/82393869
has comment: http://stackoverflow.com/comment/82394510

http://stackoverflow.com/q/47788081
has body: In my app i want to when a user profile is created, another table associated with the user profile id, gets created at the same time. I'm new to Django. I've tried to create the table after user.save() in my models.py and serializers.py, by finding the current user_id and then call create(owner=user_id) on the model object i want to create with user profile but it gives me list index out of range. class UserProfileSerializer(serializers.ModelSerializer): class Meta: model = UserProfile fields = ('id', 'email', 'name', 'password', ) extra_kwargs = {'password' : {'write_only' : True}} def create(self, validated_data): '''Creates and returns new user.''' user = UserProfile( email=validated_data['email'], name=validated_data['name'], ) user.set_password(validated_data['password']) user.save() """here im trying to create the other tabel""" user_id = UserProfile.objects.filter(email='email').values('id')[0]['id'] UserSessions.objects.create(owner_id=user_id) return user In my model.py : class UserProfileManager(BaseUserManager): """Helps Django work with our custom user model.""" def create_user(self, email, name, password): """Create a new user profile object.""" if not email: raise ValueError('Users must have an email address son!') email = self.normalize_email(email) user = self.model(email=email, name=name) user.set_password(password) user.save(using=self.db) return user class UserProfile(AbstractBaseUser, PermissionsMixin, models.Model): """Represent a user profile""" email = models.EmailField(max_length=20, unique=True) name = models.CharField(max_length=20) objects = UserProfileManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name'] In views.py : class UserProfileViewSet(viewsets.ModelViewSet): """Handles CRU.""" serializer_class = UserProfileSerializer queryset = UserProfile.objects.all() authentication_classes = (TokenAuthentication,) permission_classes = (permissions.Update_own_profile,) filter_backends = (filters.SearchFilter,) search_fields = ('name', 'e…
tagged with: django
tagged with: python
tagged with: django-rest-framework
tagged with: data-structures
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47788767
score: 0
has comment: http://stackoverflow.com/comment/82540954
has comment: http://stackoverflow.com/comment/82544169
has answer: http://stackoverflow.com/a/47788767
tagged with: sqlite
answer count: 1
has title: Create another table when user profile table gets created with same ID
type: Question

http://stackoverflow.com/q/47748025
downvote count: 4
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82456502
has answer: http://stackoverflow.com/a/47748366
possible better answer: http://stackoverflow.com/a/47748366
answer count: 2
has comment: http://stackoverflow.com/comment/82456192
score: -3
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47748151
accepted answer: http://stackoverflow.com/a/47748151
upvote count: 1
has body: Given the following list of lists which contain numbers: x = [[1,2],[3,56],[0,1],[[1, 0, 3]]] How would you calculate the total by adding all the numbers in x using a recursive function. I attempted the following: def sum_total(array, start_index): sum = 0 if start_index&gt;= len(array): return sum if type(array[start_index]) is not list: sum = sum + array[start_index] start_index= start_index+ 1; return sum_total(array, start_index) sum_total(x, 0) Example 1: x = [[1,2],[3,56],[0,1],[[1, 0, 3]]] start_index = 0 result = sum_total(x, start_index) result should be = (1 + 2) + (3 + 56) + (0 + 1) + (1 + 0 + 3) Example 2: x = [[1,2],[3,56],[0,1],[[1, 0, 3]]] start_index = 1 result = sum_total(x, start_index) result should be = (3 + 56) + (0 + 1) + (1 + 0 + 3) The method keeps returning 0. It should return the sum.
tagged with: python
has title: How to add numbers in side a complex array using a recurring method in Python?

http://stackoverflow.com/a/47783814
type: Answer
answers question: http://stackoverflow.com/q/47783722
score: 2
has body: IMHO the problem is in bindings.i of the library: serialPuts() is defined as extern void serialPuts (const int fd, const char *s) ; and in C, strings (char*) are terminated by the \0 character. I consider that a bug of the library. It should be extern void serialPuts (const int fd, const char *s, int strlen) ; Try wiringpi.serialPutchar() in a loop.
has comment: http://stackoverflow.com/comment/82529159
has comment: http://stackoverflow.com/comment/82529895
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47783722
upvote count: 2

http://stackoverflow.com/q/47740977
tagged with: python
has answer: http://stackoverflow.com/a/47741245
has title: Code flaw for making 'Encript message' in Python
answer count: 1
has body: I am unable to correct my coding below and for some reason the code is not running. Please help me with the correction, and if possible please suggest better coding practice and help with shorter coding: message = input ('Enter your message') key = int (input('How many Characters should we shift(between 1 - 26)- ')) secret-message = "" for char in message: if char.isalpha(): #Get the character code and add the shift amount char_code = ord(char) chat_code += key #if upper case then compare to uppercase unicode if char.isupper(): #if upper than Z substract 26 if char_code &gt; ord('Z'): char_code -= 26 #if smaller than A add 26 if char_code &lt; ord('A'): char_cod += 26 #Do the same for lower character else: if char_code &gt; ord('z'): char_code -= 26 if char_code &lt; ord('a'): char_cod += 26 #Convert From Code to letter and add to message secret-message = secret-message + chr(char_code) else: secret-message = secret-message + char print (" Encripted :" , secret-message)
favorite count: 0
type: Question
upvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82442209
score: -2
downvote count: 2

http://stackoverflow.com/q/47833192
has comment: http://stackoverflow.com/comment/82629282
answer count: 0
has body: I built a dataframe from uniprot file with the following columns: (index(protein_id),length, organism, sequence,acidic, polar,hydrophobic,color,width) The parameters acidic, hydrophobic and polar are percentages (i.e numbers between 1 to 100), width is between 0-1, and color is set of 4 numbers, e.g.: (0.5, 0.0, 0.0, 1.0) I try to build 3d plot in the following manner: from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import numpy as np fig = plt.figure() ax = fig.add_subplot(111, projection='3d') charge_sum = 0 display(df) for index, record in prot_df.iterrows(): xs=int(record['acidic']) ys=int(record['polar']) zs=int(record['hydrophobic']) cs=record['color'] width=record['width'] ax.bar(xs, ys, zs, zdir='y', color=cs, alpha=width) ax.set_xlabel('X') ax.set_ylabel('Y') ax.set_zlabel('Z') plt.show() But I get the following error: &gt;TypeError Traceback (most recent call last) &gt;&lt;ipython-input-190-13bea2286c05&gt; in &lt;module&gt;() &gt; 18 cs=record['color'] &gt; 19 width=record['width'] &gt;---&gt; 20 ax.bar(xs, ys, zs, zdir='y', color=cs, alpha=width) &gt; 21 &gt; 22 &gt;C:\Users\Owner\Anaconda2\lib\site-packages\mpl_toolkits\mplot3d\axes3d.pyc in &gt;bar(self, left, height, zs, zdir, *args, **kwargs) &gt; 2392 patches = super(Axes3D, self).bar(left, height, *args, **kwargs) &gt; 2393 &gt;-&gt; 2394 zs = _backports.broadcast_to(zs, len(left)) &gt; 2395 &gt; 2396 verts = [] &gt; &gt;TypeError: object of type 'int' has no len() Can someone help me get rid of this error?
has comment: http://stackoverflow.com/comment/82629670
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82629933
has comment: http://stackoverflow.com/comment/82630220
score: 0
tagged with: pandas
tagged with: matplotlib
tagged with: python
tagged with: jupyter
has comment: http://stackoverflow.com/comment/82629589
has title: 3D columns plot using dataFrame and matplotlib
type: Question
tagged with: numpy

http://stackoverflow.com/q/47769236
has comment: http://stackoverflow.com/comment/82500212
type: AnsweredQuestion
tagged with: interpreter
accepted answer: http://stackoverflow.com/a/47935804
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/82500084
favorite count: 0
type: Question
upvote count: 4
has body: Each time if I start the PyCharm after the Laptop restart, the configurations forget the python interpreter. I don't understand how I can save the interpreter for always. p.s.: PyCharm Community Edition 2017.2
has comment: http://stackoverflow.com/comment/82500343
tagged with: pycharm
has title: Pycharm doesn't save the python interpreter in the configurations
tagged with: configuration
has comment: http://stackoverflow.com/comment/82500004
tagged with: python
has answer: http://stackoverflow.com/a/47935804
score: 4
has comment: http://stackoverflow.com/comment/82500393

http://stackoverflow.com/comment/82632189
type: AnswerComment
type: Comment
score: 0
comment on: http://stackoverflow.com/a/47834220
has text: @1ndy123 the built-in `time` module has two functions for precision timers - [`time.clock()`](https://docs.python.org/2/library/time.html#time.clock) and [`time.time()`](https://docs.python.org/2/library/time.html#time.time) (you can read more on different Python timers at [this page](https://www.webucator.com/blog/2015/08/python-clocks-explained/)). Unfortunately, they behave differently on different platforms and for Windows the former one is preferred. That line just stores a reference to the more precise function in dependence of the platform to the `get_timer` variable.

http://stackoverflow.com/a/57549717
has body: I used two side by side Div elements to emulate Plotly subplot. Doing this way, we have independent legends. However, if we want to share an axis, we should do it manually: app.layout = html.Div(children=[ html.Div(['YOUR FIRST GRAPH OBJECT'], style = {'float':'left', 'width':'49%'}) , html.Div(['YOUR SECOND GRAPH OBJECT'], style = {'float':'right', 'width':'49%'}) ])
downvote count: 0
answers question: http://stackoverflow.com/q/47797383
score: 3
type: Answer
upvote count: 3

http://stackoverflow.com/comment/82414050
has text: Start by writing a `Point` class with attributes such as `x_coord`, `y_coord`, `reach_west`, ...
comment on: http://stackoverflow.com/q/47726797
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82366957
type: QuestionComment
score: 3
comment on: http://stackoverflow.com/q/47703347
type: Comment
has text: `file.close()` closes the file.. What is the problem ?

http://stackoverflow.com/comment/82528702
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47783446
type: AnswerComment
has text: So now I edited my post by making some changes with the availableNums. Can you please look at that

http://stackoverflow.com/comment/82673526
comment on: http://stackoverflow.com/q/47854733
type: Comment
type: QuestionComment
has text: You could take the minimum and maximum element, and randomly generate the remaining numbers from that range. Use random.uniform(min,max) to generate float numbers.
score: 0

http://stackoverflow.com/comment/82357372
comment on: http://stackoverflow.com/q/47698721
score: 1
type: Comment
type: QuestionComment
has text: This is very confusing. Can you clarify your input/output/question? What is `omj`: Is it's a function or an input?

http://stackoverflow.com/a/47707265
has comment: http://stackoverflow.com/comment/82386969
answers question: http://stackoverflow.com/q/47707108
score: 0
has comment: http://stackoverflow.com/comment/82387644
has comment: http://stackoverflow.com/comment/82384657
has body: Just use a defaultdict to store the counts of each (code, name): from collections import defaultdict list_dict = [{'code': 'A1', 'name': 'White'}, {'code': 'A2', 'name': 'Black'}, {'code': 'A1', 'name': 'White'}, {'code': 'A3', 'name': 'Red'}, ] d = defaultdict(int) for dic in list_dict: key = dic['code'], dic['name'] d[key] += 1 &gt;&gt;&gt; print(dict(d)) {('A1', 'White'): 2, ('A2', 'Black'): 1, ('A3', 'Red'): 1} Then just create a new list, and insert the new data from the dictionary above: new_dict_list = [{'code':code, 'name':name, 'qty':qty} for (name, code), qty in d.items()] &gt;&gt;&gt; print(new_dict_list) [{'code': 'A1', 'name': 'White', 'qty': 2}, {'code': 'A2', 'name': 'Black', 'qty': 1}, {'code': 'A3', 'name': 'Red', 'qty': 1}]
type: Answer

module
tags question: http://stackoverflow.com/q/47805965
type: Tag
tags question: http://stackoverflow.com/q/47841243
tags question: http://stackoverflow.com/q/47739027
tags question: http://stackoverflow.com/q/47752379
tag name: module
tags question: http://stackoverflow.com/q/47732461
tags question: http://stackoverflow.com/q/47819206
tags question: http://stackoverflow.com/q/47849523
tags question: http://stackoverflow.com/q/47773659
tags question: http://stackoverflow.com/q/47783867
tags question: http://stackoverflow.com/q/47809887
tags question: http://stackoverflow.com/q/47854396
tags question: http://stackoverflow.com/q/47701992
tags question: http://stackoverflow.com/q/47844773

http://stackoverflow.com/comment/82453032
comment on: http://stackoverflow.com/q/47701044
type: QuestionComment
type: Comment
score: 0
has text: I think either AWS doc outdated or `other_policy` not correct

http://stackoverflow.com/comment/82585404
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47811757
has text: Would'nt that be ohk if you just transpose after loading column major?

http://stackoverflow.com/q/47754867
tagged with: python
has body: In my python project, I need to fill a bigquery table with a relational dataframe. I'm having a lot of trouble at creating a new table from scratch and being sure that the first data I upload to it are actually put into the table. I've read the page https://cloud.google.com/bigquery/streaming-data-into-bigquery#dataconsistency and have seen that applying a insertId to the insert query would solve the problem, but since I use pandas's dataframes, the function to_gbq of the pandas-gbq package seems to be perfect for this task. Yet, when using to_gbq function and a new table is created/replaced, sometimes (apparently randomly) the first data chunk is not written into the table. Does anybody know how to ensure the complete insertion of a DataFrame into a bigquery new created table? Thanks
has answer: http://stackoverflow.com/a/47758326
score: 2
type: AnsweredQuestion
downvote count: 0
tagged with: pandas
tagged with: google-cloud-platform
tagged with: dataframe
tagged with: google-bigquery
has title: Bigquery (and pandas) - ensure data-insert consistency
accepted answer: http://stackoverflow.com/a/47758326
favorite count: 0
type: Question
upvote count: 2
answer count: 1

http://stackoverflow.com/comment/82367981
has text: WOW thanks a lot, you're truly an expert haha. I saw your profile you are a data analyst, I want to go on the same career path as well. Thanks a ton!
comment on: http://stackoverflow.com/a/47703309
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/82613852
type: Comment
has text: yap i didn't notice that, i put all the param as a string. Now it works, ty.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47825481

http://stackoverflow.com/q/47849106
tagged with: increment
tagged with: python
has title: Python increment float by smallest step possible predetermined by its number of decimals
linked to: http://stackoverflow.com/q/588004
has body: I've been searching around for hours and I can't find a simple way of accomplishing the following. Value 1 = 0.00531 Value 2 = 0.051959 Value 3 = 0.0067123 I want to increment each value by its smallest decimal point (however, the number must maintain the exact number of decimal points as it started with and the number of decimals varies with each value, hence my trouble). Value 1 should be: 0.00532 Value 2 should be: 0.051960 Value 3 should be: 0.0067124 Does anyone know of a simple way of accomplishing the above in a function that can still handle any number of decimals? Thanks.
has answer: http://stackoverflow.com/a/47849866
accepted answer: http://stackoverflow.com/a/47849866
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82662957
answer count: 3
upvote count: 7
score: 7
has answer: http://stackoverflow.com/a/47849719
possible better answer: http://stackoverflow.com/a/47849719
has comment: http://stackoverflow.com/comment/82662603
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/75854370
has comment: http://stackoverflow.com/comment/82662784
has comment: http://stackoverflow.com/comment/82663122
has comment: http://stackoverflow.com/comment/82662593
downvote count: 0

http://stackoverflow.com/comment/82468662
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47753510
has text: @joe: if that were true, the error would be different.

http://stackoverflow.com/comment/82381432
type: QuestionComment
has text: I have got another question, How Can I call any fucntion, means that only specific function on other script. Means If there are 2 fucntions i.e. Function1 and Function2 in ClassA of ScriptA, I want to access only and only Function2 in ScriptB.
comment on: http://stackoverflow.com/q/47710144
type: Comment
score: 0

http://stackoverflow.com/a/47719596
score: 1
type: Answer
answers question: http://stackoverflow.com/q/47716699
has body: I consider the first sentence in your query first, 'I'm trying to build a python code to check if a string contains HTML code.' BeautifulSoup is most probably not the tool one would use for this because it has been engineered to take almost any string as input, and produce a parsed HTML structure for that string. For instance, here I input a string with no tags and all and BS gives back a complete page, even producing a body element for that page. >>> import bs4 >>> s = 'this represents just about any string' >>> soup = bs4.BeautifulSoup(s, 'lxml') >>> soup this represents just about any string >>> soup.find_all('body') [ this represents just about any string ] Here's an alternative, somewhat crude approach using HTMLParser. HTMLParser is in the standard Python library. >>> from html.parser import HTMLParser >>> class IsItHTML(HTMLParser): ... def __init__(self): ... HTMLParser.__init__(self) ... self.found = False ... def handle_starttag(self, tag, attrs): ... self.found = True ... def __call__(self): ... return self.found ... >>> isitHTML = IsItHTML() >>> s = 'this represents just about any string' >>> isitHTML.feed(s) >>> isitHTML() False >>> s = ' something ' >>> isitHTML.feed(s) >>> isitHTML() True The main criticism I have for this approach is that it involves traversing every tag in an HTML input. Regarding your second principal question: how do I import BS correctly? I think you're doing that. The problem would appear to be with BeautifulSoup(body, "body.parser").find(). I have no idea what that might mean.
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/82417191
type: QuestionComment
comment on: http://stackoverflow.com/q/47728364
score: 23
has text: You should **not** use `assert` to validate data! It's used to validate the logic of your program: you use it to test for conditions which should _never_ happen if your program logic is correct. If a program raises `AssertionError` that means your code is wrong & it needs debugging.
type: Comment

http://stackoverflow.com/a/47735864
upvote count: 1
has comment: http://stackoverflow.com/comment/82438930
answers question: http://stackoverflow.com/q/47735074
type: Answer
has body: This post does not grant a universal one-size-fits-all, but given the above posted pieces of information, this approach does nothing but the requested set of features: Do just what's needed, not more: ( otherwise you will pay way more than receive ) a ) processing must perform a fileIO output ( the compressed file ) b ) processing must report a result / status to the central code c ) processing does not exchange any additional information or synchronisation Let's mock up such processing: &gt;&gt;&gt; def aFunToProcessGivenSTRING( aString2PROCESS = "&lt;aStringNotPassedOnCALL&gt;" ): ... time.sleep( 5 ) # emulate doing compression "efforts" ... # # ( yes, w/o loading a CPU-core ) ... return ( "[pid:{0:}]-&gt;( {1:} )".format( os.getpid(), ... aString2PROCESS ... ) ... ) Let's mock up also a list of "Tasks" for such aFunToProcessGivenSTRING(): aListOfTaskSTRINGs = [ '6554,a,0.109375,2;', '6554,c,0.099609375,2;', '6557,g,0.109375,2;', '6555,b,0.099609375,2;', '6555,f,0.109375,2;', '6556,q,0.109376,2;', '6558,r,0.109375,2;', '6559,s,0.109376,2;', '6553,t,0.109375,2;', '6553,d,0.109375,2;', 'Some more Meat for Dr.Jackson', 'The last but not the least...' ] The most lightweight approach, using an async version of the apply(), a multiprocessing.Pool() builtin, for data-driven parallelism goes as light as this: import multiprocessing, os, time aPool = multiprocessing.Pool( 2 ) # Here, allow 2-Process-streams to take place print( aPool.map( aFunToProcessGivenSTRING, aListOfTaskSTRINGs ) ) ['[pid:12387]-&gt;( 6554,a,0.109375,2; )', '[pid:12388]-&gt;( 6554,c,0.099609375,2; )', '[pid:12387]-&gt;( 6557,g,0.109375,2; )', '[pid:12388]-&gt;( 6555,b,0.099609375,2; )', '[pid:12387]-&gt;( 6555,f,0.109375,2; )', '[pid:12388]-&gt;( 6556,d,0.109375,2; )', ..., '[pid:12387]-&gt;( Some more Meat for Dr.Jackson )' '[pid:12388]-&gt;( The last but not the least... )' ] Check the 2 Process instances via reported "remote"-os.getpid()-#s. Given no other interactions are intended, this ought serv…
has comment: http://stackoverflow.com/comment/82439037
has comment: http://stackoverflow.com/comment/82461002
has comment: http://stackoverflow.com/comment/82462639
score: 1
downvote count: 0

http://stackoverflow.com/q/47831549
accepted answer: http://stackoverflow.com/a/47831614
has comment: http://stackoverflow.com/comment/82627194
has comment: http://stackoverflow.com/comment/82626319
answer count: 5
has comment: http://stackoverflow.com/comment/82626364
has answer: http://stackoverflow.com/a/47831605
upvote count: 1
has answer: http://stackoverflow.com/a/47834452
tagged with: django
downvote count: 5
score: -4
has title: Transform a dictionary in a list in Python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47831821
has answer: http://stackoverflow.com/a/47831614
possible better answer: http://stackoverflow.com/a/47831650
has body: I would like get data from id property and transform in a list queryset = [{"id":1,"name":"John"},{"id":2,"name":"John"}] Expected result ('1','2') ## ID PROPERTY
tagged with: python
has answer: http://stackoverflow.com/a/47831650
favorite count: 0
type: Question

http://stackoverflow.com/a/47853056
has body: You can use a library like colored to change both foreground and background colors, even on the same line. Something like: from colored import stylize, fg offset = 42 # Starting color # ... def pascal_level(n): lists = [] ns = range(n) for n in ns: nlist = [] colors = [] for k in range(n+1): nlist.append(multiplicative(n, k)) color = fg(k + offset) if k + 1 &lt; n//2 else fg(n - k + offset) colors.append(color) nlist = ' '.join(stylize(str(x), color) for x, color in zip(nlist, colors)) lists.append(nlist) return lists
type: Answer
score: 1
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47852944

http://stackoverflow.com/q/47710027
answer count: 2
has comment: http://stackoverflow.com/comment/82381269
downvote count: 0
accepted answer: http://stackoverflow.com/a/47710205
has comment: http://stackoverflow.com/comment/82381411
tagged with: pandas-datareader
has comment: http://stackoverflow.com/comment/82381054
has answer: http://stackoverflow.com/a/47710268
tagged with: machine-learning
possible better answer: http://stackoverflow.com/a/47710268
favorite count: 0
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47710205
tagged with: python
has title: [Python]; Parser error: Too many columns specified
has comment: http://stackoverflow.com/comment/82381155
score: 2
has body: I just want to read a simple .csv file with a header specifying the column types. The following is the code: import pandas as pd url="https://www.dropbox.com/s/n6yt908tgetuq63/LasVegasTripAdvisorReviews-Dataset.csv?dl=0" names=['User country','Nr. reviews','Nr. hotel reviews','Helpful votes','Score','Period of stay','Traveler Type','Pool','Gym','Tennis court','Spa','Casino','Free internet','Hotel name','Hotel stars','Nr. rooms','User continent','Member years','Review month','Review weekday'] data=pd.read_csv(url, names=names, header=0, delimiter=';', error_bad_lines=False) print(data.shape) OUT:- ParserError: Too many columns specified: expected 20 and found 2 P.S:The URL is public and can be accessed
upvote count: 2
has comment: http://stackoverflow.com/comment/82381239

http://stackoverflow.com/a/47781362
has comment: http://stackoverflow.com/comment/82525261
type: AcceptedAnswer
has body: To answer your questions: 1) Like this: matrix = [] Simply put, this just creates an empty list that you can append anything you want into, including more lists. So matrix.append([1,2,3]) gives you a list like this: [[1,2,3]] 2) So you're index out of range error is coming from the fact that you're incrementing test_count to 1 but your matrix is remaining length of 1 (meaning it only has the 0 index) since you never append anything. In order to get the output that you want you're going to need to make a few changes: def get_data(file): example_list = ['one','two','three'] matrix = [] #list of lists test_count = 0 line_count = 0 #keep track of which line we are on for line in file: if line.find('example') != -1: #test for example string temp_a = re.findall(r"\'(.+?)\'",line)[0] new_list = example_list[:] new_list[0] = temp_a matrix.append(new_list) test_count += 1 #go to next "new" list in the matrix line_count += 1 #go to next line print matrix #[['boxes', 'two', 'three'], ['equilateral', 'two', 'three'], ['sphere', 'two', 'three']]
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47780745
has comment: http://stackoverflow.com/comment/82525048
score: 1
answers question: http://stackoverflow.com/q/47780745
type: Answer
has comment: http://stackoverflow.com/comment/82524623
has comment: http://stackoverflow.com/comment/82524557
has comment: http://stackoverflow.com/comment/82524879

http://stackoverflow.com/comment/82697337
has text: Response from Shaido is that you need to create only one file. In any case, Spark will create a folder called text_file.csv with only 1 file inside.
comment on: http://stackoverflow.com/a/47830151
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/comment/82612773
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47825072
has text: No, bash *does not* retrieve stdout from programs it invokes. A program bash runs writes its stdout direct to the same terminal that bash writes its own stdout to.

generator
type: Tag
tags question: http://stackoverflow.com/q/47831240
tags question: http://stackoverflow.com/q/47790212
tags question: http://stackoverflow.com/q/47843707
tag name: generator
tags question: http://stackoverflow.com/q/47737636
tags question: http://stackoverflow.com/q/47784652
tags question: http://stackoverflow.com/q/47772542
tags question: http://stackoverflow.com/q/47699570
tags question: http://stackoverflow.com/q/47851429
tags question: http://stackoverflow.com/q/47844719
tags question: http://stackoverflow.com/q/47747299

http://stackoverflow.com/a/47808250
answers question: http://stackoverflow.com/q/47808162
score: 0
has comment: http://stackoverflow.com/comment/82579227
has comment: http://stackoverflow.com/comment/82578811
type: Answer
has body: Definitely you can. Why not try? If your model is smooth (e.g. linear or neural network), optimization will converge nicely. The only problem is that with nonlinear models there might be multiple local optima, so it would be safe to try different starting points or initialize with some heuristic. If the model is not smooth (e.g. ensembles of trees) there might be problems with convergence, and you should use a gradient-free algorithm like Nelder-Mead.
has comment: http://stackoverflow.com/comment/82577684

http://stackoverflow.com/comment/82585706
has text: I could write a C extension to ensure the utmost flexibility for any string manipulation operations the OP *may* require in the future. Certainly that would not be a good solution, right? Write code for your requirements, not perceived future needs when [you aren't gonna need it](https://en.m.wikipedia.org/wiki/You_aren%27t_gonna_need_it). More complex, less efficient; I saw this in a code review, I would kick it back immediately.
type: Comment
comment on: http://stackoverflow.com/a/47803900
type: AnswerComment
score: 0

http://stackoverflow.com/a/47824154
has comment: http://stackoverflow.com/comment/82611272
has body: Maybe not the answer you are looking for, but using Python with OpenCV on an embedded system is not really a good idea. I have experienced a lot of problems when using python on embedded systems (even with the powerful hardware that the rasp provides you). All the performance problems I experienced vanished when I used C++ instead of Python. OpenCV on C++ is pretty solid and I highly recommend you to give it a try.
type: Answer
has comment: http://stackoverflow.com/comment/82625814
score: 0
answers question: http://stackoverflow.com/q/47823332
has comment: http://stackoverflow.com/comment/82610940

http://stackoverflow.com/comment/82541172
score: 0
type: AnswerComment
has text: Just for curiosity, why do you use a `set` for the lookup instead of a `list` or `tuple`?
comment on: http://stackoverflow.com/a/47789759
type: Comment

http://stackoverflow.com/q/47764984
tagged with: insert
has comment: http://stackoverflow.com/comment/82491266
has answer: http://stackoverflow.com/a/47765030
has title: how to efficiently insert element for a n dimension array
type: Question
tagged with: numpy
has body: There is a simple example. I have a 2d array a=np.arange(4).reshape(2,2)+1 array([[1, 2], [3, 4]]) and I wanna insert 0 (or any other value) in the beginning and end of the array, then it becomes array([[ 0., 0., 0., 0.], [ 0., 1., 2., 0.], [ 0., 3., 4., 0.], [ 0., 0., 0., 0.]]) I'm trying np.insert or np.concatenate, but I failed for >2 dimension. What is the fastest way to handle this kind of problem?
type: UnansweredQuestion
tagged with: arrays
tagged with: python
score: 0
has comment: http://stackoverflow.com/comment/82529109
tagged with: concatenation
answer count: 1

http://stackoverflow.com/a/47861778
upvote count: 5
has comment: http://stackoverflow.com/comment/82745082
type: Answer
has body: You could try Google's Guetzli encoder with pyguetzli, it usually generates smaller jpeg file but takes a substantial amount of time, compare: original: 9.4M pil_1024*768_q95.jpeg: 638K pil_1024*768_q85.jpeg: 404K guetzli_1024*768_q95.jpg: 376K original jpeg file is from wiki common, By Diego Delso, CC BY-SA 4.0.
has comment: http://stackoverflow.com/comment/82748172
has comment: http://stackoverflow.com/comment/82745477
score: 5
has comment: http://stackoverflow.com/comment/82748502
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82928538
downvote count: 0
has comment: http://stackoverflow.com/comment/82746689
answers question: http://stackoverflow.com/q/47837808
has comment: http://stackoverflow.com/comment/82748320
accepted answer of: http://stackoverflow.com/q/47837808
has comment: http://stackoverflow.com/comment/82746739

http://stackoverflow.com/comment/82573799
type: Comment
has text: I tried that. Now I'm using Python 2.7.12 and Django (1, 11, 8, u'final', 0). Yet no change.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47806056

http://stackoverflow.com/comment/83777413
has text: Still no answer for this problem? I read that only simple python code can be use in the server action python code box: How simple? what do I have to change in my syntax? the documentation on this subject is really close to nothing...
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47842818
type: Comment

http://stackoverflow.com/comment/82375483
has text: Is that first section code? It's hard to tell with that formatting. You should use a code block rather than block quote.
comment on: http://stackoverflow.com/q/47707770
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47738124
has body: For a college project, I'm developing a RESTful API. The API has been coded in python and deployed with the Google App Engine (which works fine). I've developped an Angular (5) application as the frontend which makes HTTP requests to that API. The question is - how do I deploy both backend and frontend on the same Google App Engine project? Am I supposed to merge both directories (python and Angular apps) and deploy the whole thing directly?
answer count: 0
tagged with: angular
has comment: http://stackoverflow.com/comment/92243798
downvote count: 0
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/89241317
has title: Deploying app with python backend and Angular frontend on GAE
type: UnansweredQuestion
tagged with: google-app-engine
has comment: http://stackoverflow.com/comment/92269242
tagged with: python
linked to: http://stackoverflow.com/q/39782506
score: 4
upvote count: 4

http://stackoverflow.com/comment/82479349
type: Comment
has text: `print('a-{a}, e-{e}, i-{i}, o-{o}, u-{u}'.format(**cnt))` works for me: I get `a-0, e-0, i-2, o-3, u-1` without setting anything to 0. At least in python 3.4 it works.
comment on: http://stackoverflow.com/a/47759051
score: 2
type: AnswerComment

http://stackoverflow.com/q/47834230
tagged with: python
has title: How to write Huge dataframe in Pandas
answer count: 1
accepted answer: http://stackoverflow.com/a/47834368
tagged with: python-2.7
has answer: http://stackoverflow.com/a/47834368
upvote count: 2
has comment: http://stackoverflow.com/comment/82631512
type: AnsweredQuestion
score: 0
downvote count: 2
favorite count: 0
has body: I have pandas dataframe size of 21909, 20037 (row,column) and I want to convert it to csv by following code. dpF.to_csv("outputFile.csv", encoding='utf-8') after this line of code my computer is getting hang and I am not getting any output. Is there any way to write such a huge dataframe in a optimal way. System configuration OS: ubuntu 16.04 LTS OS type: 64 bit Memory: 7.7 GiB Processor: Intel® Core™ i5-4590 CPU @ 3.30GHz × 4
type: Question
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv

http://stackoverflow.com/comment/82676028
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47855373
has text: every tab may have own `class` or `id`. Page can also use JawaScript to load data. Use DevTool in Chrome/Firefox (tab Network -> XHR) to see JavaSrip/AJAX requests after you click tab. Maybe you find url to data as JSON
score: 0

http://stackoverflow.com/comment/82731111
comment on: http://stackoverflow.com/q/47851091
score: 2
type: Comment
type: QuestionComment
has text: Cannot reproduce with Python 3.6.2 on windows 10. Simply the `2` comes after the cmd prompt.

http://stackoverflow.com/q/47822764
has answer: http://stackoverflow.com/a/47823110
has body: Hello i have been struggling with implementing this selection sort for quite some days now. I feel my code is close to it, but can't figure out why am not getting it. Here is my code with comments def selectionSort(aList): #For each index in the list... for i in range(len(aList)): #Assume first that current item is already correct... minIndex = i #For each index from i to the end... for j in range(i + 1, len(aList)): if aList[j] &gt;= aList[j - 1]: break aList[j], aList[j - 1] = aList[j - 1], aList[j] minIndex = aList.index(aList[j - 1]) #Save the current minimum value since we're about #to delete it minValue = aList[minIndex] #Delete the minimum value from its current index del aList[minIndex] #Insert the minimum value at its new index aList.insert(i, minValue) #Return the resultant list return aList This is the result am getting [4, 2, 1, 3, 5] Instead of this: [1, 2, 3, 4, 5] Thanks for your help in advance
tagged with: python
has comment: http://stackoverflow.com/comment/82608361
score: 0
answer count: 3
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47822851
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47822922
tagged with: selection-sort
has title: Selectionsort not outputing the right result Python
has comment: http://stackoverflow.com/comment/82608294
tagged with: algorithm

http://stackoverflow.com/comment/82590608
comment on: http://stackoverflow.com/a/47800828
has text: @MarkRansom: you're the king mark! That's the kind of statement I was searching for. It's a very convoluted statement but it works fine. If you repost as an answer, I will show my gratitude.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/82675495
has text: `b.name` don't call `__getattr__` either, but `b` don't have attribute `name`, so why don't call `__getattr__`?
comment on: http://stackoverflow.com/a/47855651
score: 0
type: Comment
type: AnswerComment

anaconda
tags question: http://stackoverflow.com/q/47778868
tags question: http://stackoverflow.com/q/47777358
tags question: http://stackoverflow.com/q/47769187
tags question: http://stackoverflow.com/q/47819398
tags question: http://stackoverflow.com/q/47800794
tags question: http://stackoverflow.com/q/47779411
tags question: http://stackoverflow.com/q/47780442
tags question: http://stackoverflow.com/q/47824131
type: Tag
tags question: http://stackoverflow.com/q/47836266
tags question: http://stackoverflow.com/q/47821301
tag name: anaconda
tags question: http://stackoverflow.com/q/47820905
tags question: http://stackoverflow.com/q/47710022
tags question: http://stackoverflow.com/q/47828437
tags question: http://stackoverflow.com/q/47801821
tags question: http://stackoverflow.com/q/47723508
tags question: http://stackoverflow.com/q/47731289
tags question: http://stackoverflow.com/q/47754749
tags question: http://stackoverflow.com/q/47728299
tags question: http://stackoverflow.com/q/47711149
tags question: http://stackoverflow.com/q/47807709
tags question: http://stackoverflow.com/q/47799803
tags question: http://stackoverflow.com/q/47710568
tags question: http://stackoverflow.com/q/47758693
tags question: http://stackoverflow.com/q/47738671
tags question: http://stackoverflow.com/q/47737764
tags question: http://stackoverflow.com/q/47821890
tags question: http://stackoverflow.com/q/47742120
tags question: http://stackoverflow.com/q/47808162
tags question: http://stackoverflow.com/q/47842607

http://stackoverflow.com/a/47806842
score: 8
downvote count: 0
answers question: http://stackoverflow.com/q/47806024
has comment: http://stackoverflow.com/comment/94713341
upvote count: 8
has body: The React Native App consists of two major portions Business Logic which is a NodeJs app. This app controls the other piece Frontend which is written in Javascript, however it gets linked to native interfaces (Java in case of Android and Obj-C in case of iOS) In this framework, best way to integrate Python Code, machine learning or otherwise is to connect NodeJS app with Python interpreter. This also happens to be complex to implement. This will go something like this #include &lt;Python.h&gt; int main(int argc, char *argv[]){ Py_SetProgramName(argv[0]); /* optional but recommended */ Py_Initialize(); PyRun_SimpleString("from time import time,ctime\n" "print 'Today is',ctime(time())\n"); Py_Finalize(); return 0; } As seen at Embedding Tutorial Now this is bit tricky so lets look at secondary options like connecting with the model using C++. Like Tensorflow also has a C++ API which can be used to integrate Models into NodeJS. Final option is ofcourse to use it as a separate child process or server side call.
type: Answer
has comment: http://stackoverflow.com/comment/126566896

http://stackoverflow.com/q/47839895
tagged with: columnspan
downvote count: 0
tagged with: pyqt5
has body: Is possible to set the column span of a QLineEdit box after it has been added to the layout? I have two QLineEdit boxes in a QGridLayout that are right next to each other horizontally. During the execution of some of my code, one of these boxes gets hidden. I would like to increase the column span where the hidden one was to avoid a weird gap at the end, and reduce it when needed. I couldn't really find anything in the Qt documentation for this type of change beyond making the adjustment prior to adding the widget to the layout.
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/47840394
score: 3
tagged with: qgridlayout
tagged with: python
has title: How to reset the column span of a widget in a QGridLayout?
accepted answer: http://stackoverflow.com/a/47840783
has answer: http://stackoverflow.com/a/47840783
type: AnsweredQuestion
answer count: 2
has answer: http://stackoverflow.com/a/47840394
tagged with: pyqt
upvote count: 3

http://stackoverflow.com/q/47709918
has comment: http://stackoverflow.com/comment/82389274
has comment: http://stackoverflow.com/comment/82398319
has comment: http://stackoverflow.com/comment/82397748
tagged with: cx-freeze
score: 0
has title: freezing python program
has comment: http://stackoverflow.com/comment/82398586
tagged with: freeze
tagged with: dependencies
type: Question
has body: I have written a script where user can send mails to multiple addresses. It is an alternative to Mail Merge. The structure of the program is as follows: server.py --- Starts python server and opens index.html which is forms cgi-bin/min.py --- captures the form fields and create email for users with text input Now I wish to freeze and convert it to exe for using on windows without python installation. I used pyinstaller/py2exe/cx_freeze but not getting end result. The script for setup.py for cx_freeze is as follows import sys from cx_Freeze import setup, Executable setup( name = "ravi shankar", version = "3.6", description = "a mail merge tool.", executables = [Executable("server.py", base = "Win32GUI")])
answer count: 0
has comment: http://stackoverflow.com/comment/82397691
tagged with: pyinstaller
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/82654771
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47845362
score: 0
has text: Thanks, thats. a great solution! :)

http://stackoverflow.com/comment/82401474
type: QuestionComment
has text: i typed in python --version into the cmd prompt and i get version 3.6.3. as for the command or line of code python -m pip install flask where am i supposed to put this? in the command prompt? as for the code, i am trying to run it in pycharm. i was able to get the webapp to run in Python however, but not the IDLE. i get a SyntaxError when trying to run it in the IDLE. i really don't know what's going on here.
score: 0
comment on: http://stackoverflow.com/q/47703227
type: Comment

http://stackoverflow.com/comment/82616242
has text: It's kind of strange to want a list of single chars for this anyways; if someone entered `-0.3-1.2j` would you want something like `['-', '0', '.', '3' ...]` or it split up more logically like `['-', '0.3', '-', '1.2', 'j']`?
comment on: http://stackoverflow.com/q/47826694
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/68808573
type: Answer
answers question: http://stackoverflow.com/q/47778277
has body: Per RFC 7662 you need to send your request with Content-Type: x-www-form-urlencoding (so rather than a JSON object you have a set of key=value separated by &amp; having applied encodeURIComponent to each key and value). You also need the Content-Type: x-www-form-urlencoding header in your request. You'll get back JSON. So like below: from urllib.parse import urlencode, quote_plus // using your object from above result = urlencode(payload, quote_via=quote_plus) Then use the result text as the payload of your POST.
score: 0

http://stackoverflow.com/a/47715463
downvote count: 0
answers question: http://stackoverflow.com/q/47715289
score: 1
has comment: http://stackoverflow.com/comment/82390955
upvote count: 1
type: AcceptedAnswer
type: Answer
has body: The error message is clear: This line (line 17) is the problem: if random.random() &lt; reproductionProb random.random() is a float and reproductionProb a function handle. You cannot compare a float with a function. reproductionProb = infection.reproductionProbability is the call where you are passing a function handle instead of a float. Also you need to make sure to encapsulate your main function as: if __name__=='__main__': If you import your file this prevents the main function of the imported file being called.
accepted answer of: http://stackoverflow.com/q/47715289

http://stackoverflow.com/q/47733611
has answer: http://stackoverflow.com/a/47733705
accepted answer: http://stackoverflow.com/a/47733705
type: Question
has title: isinstance: How to manage set classes better
has comment: http://stackoverflow.com/comment/82427745
has comment: http://stackoverflow.com/comment/82427852
has comment: http://stackoverflow.com/comment/82427848
answer count: 1
has comment: http://stackoverflow.com/comment/82427892
has comment: http://stackoverflow.com/comment/82427843
tagged with: isinstance
type: AnsweredQuestion
score: 0
has body: While writing some debugging python, I seem to have created a bit of ugly code that I would like to clean up. Here is the function in its entirety: def debug(message, variable=None): if variable and DEBUG: print("\n" + str(type(variable))) try: if isinstance(variable, (list, dict, 'OrderedDict')): variable = json.dumps( variable, indent=4, sort_keys=True ) except TypeError: if isinstance(variable, (list, dict)): variable = json.dumps( variable, indent=4, sort_keys=True ) if DEBUG: if variable: print(message + str(variable) + "\n") else: print("\n" + message) I specifically despise my try-except statement, because not only am I repeating code, but if I run into another dictionary class (like CaseInsensitiveDict from requests' headers) that I would like to print nicely during debugging output I would have to nest try-except statements. Is there a way that I could check if type(variable) is like *dict* or *list* then add it when creating the tuple for use in isinstance?
tagged with: python
has comment: http://stackoverflow.com/comment/82427918

http://stackoverflow.com/q/47793412
score: 1
accepted answer: http://stackoverflow.com/a/47812863
has body: I have a dataframe (which is created by loading from multiple blobs in azure) where I have a column which is list of IDs. Now, I want a list of unique IDs from this entire column: Here is an example - df - | col1 | col2 | col3 | | "a" | "b" |"[q,r]"| | "c" | "f" |"[s,r]"| Here is my expected response: resp = [q, r, s] Any idea how to get there? My current approach is to convert the strings in col3 to python lists and then maybe flaten them out somehow. But so far I am not able to do so. I tried using user defined functions in pyspark but they only return strings and not lists. FlatMaps only work on RDD not on Dataframes so they are out of picture. Maybe there is way where I can specify this during the conversion from RDD to dataframe. But not sure how to do that.
favorite count: 0
has answer: http://stackoverflow.com/a/47812863
type: Question
has answer: http://stackoverflow.com/a/47794658
tagged with: apache-spark-sql
tagged with: pyspark
tagged with: dataframe
tagged with: python
has title: Pyspark Dataframe get unique elements from column with string as list of elements
tagged with: rdd
possible better answer: http://stackoverflow.com/a/47794658
type: AnsweredQuestion
answer count: 2
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/47796896
has comment: http://stackoverflow.com/comment/82556527
has comment: http://stackoverflow.com/comment/82554691
has answer: http://stackoverflow.com/a/47797076
has title: Python 3: self variable in init can't be changed?
tagged with: python
type: Question
score: 2
upvote count: 2
has body: Im programing a game for school right now. Its going pretty well so far, so Im now trying to implement an undo option after each players turn. My board is a 7x7 matrix and is defined in __ init __ as self.board. The board will be manipulated by each players turn. Besides I have self.saved_states = [] defined in __ init __. This list is supposed to store copies of every state of the game after every players turn. So far I have a method that actually saves state into the list mentioned in 3. def save_state(self): copied_board = copy.copy(self.board) self.saved_states.append(copied_board) I tested this and this seems to work. The problem is somewhere else. So I will get input from user, if he inputs 'u' instead of actual valid game input I want to do the following: if input == 'u': print('Undoing last turn!') self.board = self.saved_states.pop() self.player_2() I just want to change the current state of the game to the previous one and have player 2 take their turn (again). Whats the problem here? Every time each player take its turn Im manipulating elements of the board too. Why can't I just replace the whole board with a previous one? I don't see the difference here. Thanks for any help or idea!
answer count: 1
has comment: http://stackoverflow.com/comment/82554724
downvote count: 0
has comment: http://stackoverflow.com/comment/82555629
favorite count: 0
accepted answer: http://stackoverflow.com/a/47797076
type: AnsweredQuestion

http://stackoverflow.com/comment/82481727
comment on: http://stackoverflow.com/q/47759603
type: QuestionComment
has text: Running a script in the background is less of a problem - [`nohup`](http://linux.101hacks.com/unix/nohup-command/) can deal with that - the bigger issue is did you plan how will you control it once you send it to the background and where do you imagine it should run popups?
type: Comment
score: 0

http://stackoverflow.com/comment/82544028
score: 0
comment on: http://stackoverflow.com/q/47791469
type: Comment
has text: Okay, great. Just wanted to confirm, since this appears to be a duplicate.
type: QuestionComment

http://stackoverflow.com/q/47841981
has comment: http://stackoverflow.com/comment/82648216
has comment: http://stackoverflow.com/comment/82648690
tagged with: udp
has comment: http://stackoverflow.com/comment/82657968
answer count: 0
has comment: http://stackoverflow.com/comment/82664927
upvote count: 3
tagged with: human-readable
downvote count: 0
has body: I am developing a python sniffer which sniff the udp packets. I use this code to receive and get the payload of the received packet in human readable format, but the printed payload is not human readable! I searched about converting this format to human readable, but I got nothing. packet = recv_socket.recvfrom(65565) packet = packet[0] ip_header = packet[0:20] iph = struct.unpack('!BBHHHBBH4s4s', ip_header) data = packet[28:] payload = ":".join("{:02x}".format(ord(c)) for c in data) print payload.decode("utf-8", "ignore") print payload Right now, the out put of print commands are as follow: .*###[ DNS ]### id = 1382 qr = 0L opcode = 12L aa = 0L tc = 0L rd = 1L ra = 0L z = 1L ad = 1L cd = 0L rcode = 12L qdcount = 30062 ancount = 867 nscount = 28525 arcount = 0 qd = '' an = '' ns = '' ar = None ###[ Raw ]### load = '\x01\x00\x01\xc0\x0c\x00\x01\x00\x01\x00\x00\x00&lt;\x00\x04\x80w\xf3\x86' 05:66:61:6c:75:6e:03:63:6f:6d:00:00:01:00:01:c0:0c:00:01:00:01:00:00:00:3c:00:04:80:77:f3:86
has comment: http://stackoverflow.com/comment/82658207
favorite count: 0
has comment: http://stackoverflow.com/comment/82648545
type: Question
score: 3
tagged with: payload
has comment: http://stackoverflow.com/comment/82648591
type: UnansweredQuestion
tagged with: sockets
has title: get the udp packets payload readable in python
tagged with: python
has comment: http://stackoverflow.com/comment/82667765

http://stackoverflow.com/comment/82572353
type: Comment
type: AnswerComment
has text: Your `for i in data:` is still not indented on the same level where you defined `data`
score: 0
comment on: http://stackoverflow.com/a/47805282

http://stackoverflow.com/q/47738384
has title: User Defined numpy 2D array in Python using Numpy
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82437065
score: 0
has body: I am trying to code up for a user defined 2D array in Python using Numpy. I tried the below Code, but it is not working for some reason. import numpy as np x=list() n=int(input()) m=int(input()) for i in range(n*m): z=int(input()) x.append(z) x=np.reshape((n,m)) print(x) In the code I am trying to take a list as an input from user which is containing a total of n*m elements and then using reshape to reshape the array into a dimension of (n,m). Can Someone point out the error I am making in the code also a correct way to implement a user defined 2d array in numpy?
tagged with: python
has comment: http://stackoverflow.com/comment/82439784
type: Question
tagged with: numpy
tagged with: python-3.x

http://stackoverflow.com/comment/82870942
score: 0
type: AnswerComment
has text: @blue-sky Correct, to get an inference result, just do the forward pass for the new data. Result array will contain the probabilities of each label.
type: Comment
comment on: http://stackoverflow.com/a/47941930

http://stackoverflow.com/a/47802563
score: 0
answers question: http://stackoverflow.com/q/47801788
type: Answer
has body: In short, no. In a single Selenium webdriver instance, you can only interact with a single window handle at any given time. This answer has more related details you may find pertinent. With regard to running two different scripts on the same window in different tabs... it is (or at least was at some point in time) technically possible to do in at least Internet Explorer. Selenium maintainers decided that it would not be feasible to implement a general solution for this. While you may find a hack to do this, it almost certainly will be browser-specific and very fragile, therefore not recommended. Your best bet will be to just have two separate instances.

http://stackoverflow.com/comment/82390879
comment on: http://stackoverflow.com/q/47715392
type: QuestionComment
has text: @RoadRunner I tried return True, but if I do so, it only prints the number
type: Comment
score: 0

http://stackoverflow.com/comment/82421435
score: 1
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47730390
has text: You need to know the slope at 0,0... And you can get that using the first two points of the series

http://stackoverflow.com/comment/82434164
score: 0
has text: Yep! That's how you could generate interframe interpolation. Again be cautious of the ordering here, should be `flow[y, x]`. However! And this is an important point: the flow vector will give inter-pixel measurements (i.e. `flow[y, x][0]` might be `3.105`). You'll of course need to round or truncate to integer indices. But what happens if two values get mapped to the same point after rounding? Similarly, what happens if there are some pixels which don't get mapped to? That will happen in a lot of places. You should use `cv2.remap` to do the interpolation for you and it will take care of that.
type: AnswerComment
comment on: http://stackoverflow.com/a/47736465
type: Comment

http://stackoverflow.com/q/47765551
tagged with: array-broadcasting
tagged with: pandas
type: AnsweredQuestion
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/82492496
answer count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/47765724
favorite count: 0
has title: Numpy: conditional np.where replace
type: Question
has comment: http://stackoverflow.com/comment/82494606
possible better answer: http://stackoverflow.com/a/47765724
tagged with: python
has answer: http://stackoverflow.com/a/47766684
accepted answer: http://stackoverflow.com/a/47766753
has comment: http://stackoverflow.com/comment/82492434
tagged with: numpy
has answer: http://stackoverflow.com/a/47766753
has body: I have the following dataframe: 'customer_id','transaction_dt','product','price','units' 1,2004-01-02 00:00:00,thing1,25,47 1,2004-01-17 00:00:00,thing2,150,8 2,2004-01-29 00:00:00,thing2,150,25 3,2017-07-15 00:00:00,thing3,55,17 3,2016-05-12 00:00:00,thing3,55,47 4,2012-02-23 00:00:00,thing2,150,22 4,2009-10-10 00:00:00,thing1,25,12 4,2014-04-04 00:00:00,thing2,150,2 5,2008-07-09 00:00:00,thing2,150,43 5,2004-01-30 00:00:00,thing1,25,40 5,2004-01-31 00:00:00,thing1,25,22 5,2004-02-01 00:00:00,thing1,25,2 I have the following process: start_date_range = pd.date_range('2004-01-01 00:00:00', '12-31-2017 00:00:00', freq='30D') end_date_range = pd.date_range('2004-01-30 23:59:59', '12-31-2017 23:59:59', freq='30D') tra = df['transaction_dt'].values[:, None] idx = np.argmax(end_date_range.values &gt; tra, axis=1) df['window_start_dt'] = np.take(start_date_range, idx) df['window_end_dt'] = end_date_range[idx] However, I need to use np.where to fix an issue with df['window_start_dt'] with the following condition: If 'transaction_dt' &lt;= 'window_start_dt' then select the previous datetime value in start_date_range.

http://stackoverflow.com/a/47727178
type: Answer
answers question: http://stackoverflow.com/q/47726984
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/82415033
has body: Change the file name from random.py to studyrandom.py, filename is same to the module, so it is wrong

http://stackoverflow.com/comment/82460162
type: Comment
has text: it gives me this Cannot assign "'1'": "CompletedTest.test" must be a "Test" instance, do you want to talk in a room?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47749681

http://stackoverflow.com/comment/82449646
type: Comment
score: 0
type: AnswerComment
has text: @AkshanDua There can be no other reason than a data entry error on your part. As you can see, `d_better` has the key `'20MAY17'` in my example.
comment on: http://stackoverflow.com/a/47743753

http://stackoverflow.com/comment/82579146
comment on: http://stackoverflow.com/a/47748033
score: 0
type: AnswerComment
has text: "0" can perfectly be parsed to float. You're looking in the wrong corner. How do you debug this? Why not create a unit test to reproduce the error? I see lots of print statements - you probably benefit from investing some time learning to use the debugger and e.g. `pytest`.
type: Comment

http://stackoverflow.com/a/47730961
score: 0
answers question: http://stackoverflow.com/q/47728559
has body: First, use your full definition of groupreg that assigns both resid and rsquared columns: def groupreg(g): g['residual'] = sm.ols(formula=regmodel, data=g).fit().resid g['rsquared'] = sm.ols(formula=regmodel, data=g).fit().rsquared return g Then, at the very end of your current code (after creating the z_score column), try the following to delete the rsquared entries in rows where -1 &lt; z_score &lt; 1: df.loc[df['z_score'].abs() &lt; 1, 'rsquared'] = np.NaN Output: gp x1 x2 y residual rsquared z_score 10 1 3.17 23 880.37 -43.579309 NaN -0.173726 12 1 4.76 26 716.20 -174.532201 NaN -0.695759 14 1 4.17 73 974.79 318.634921 0.250573 1.270214 16 1 8.70 72 322.80 -287.710952 0.250573 -1.146938 18 1 11.45 16 1054.25 187.187542 NaN 0.746209 20 2 3.17 26 980.37 -67.245089 NaN -0.822329 22 2 4.76 73 816.20 -96.883281 0.912987 -1.184770 24 2 4.17 72 1074.79 104.400010 0.912987 1.276691 26 2 8.70 16 522.80 21.017543 NaN 0.257020 28 2 1.45 25 1254.25 38.710817 NaN 0.473388
type: Answer

http://stackoverflow.com/comment/82480781
type: QuestionComment
score: 3
has text: What _do_ you expect?
comment on: http://stackoverflow.com/q/47759657
type: Comment

http://stackoverflow.com/comment/82490827
score: 0
type: Comment
has text: How do I do achieve the preference score for each record on that data frame . I have used a's rating 4 as an example to show what I meant , I want this to be generalized to a whole data frame .
comment on: http://stackoverflow.com/a/47764454
type: AnswerComment

http://stackoverflow.com/q/47850906
type: AnsweredQuestion
score: 2
duplicate of: http://stackoverflow.com/q/23622922
accepted answer: http://stackoverflow.com/a/47851023
downvote count: 0
has answer: http://stackoverflow.com/a/47851023
linked to: http://stackoverflow.com/q/23622922
answer count: 1
tagged with: sqlalchemy
has body: I have a user class as detailed below: class User(db.Model): __tablename__ = "users" id = db.Column(db.Integer, primary_key=True) email = db.Column(db.Unicode(length=128), unique=True) username = db.Column(db.Unicode(length=128), unique=True) _password = db.Column("password", db.String(length=60)) admin = db.Column(db.Boolean, default=False) joined = db.Column(db.DateTime, default=datetime.utcnow) confirmed = db.Column(db.Boolean, default=False) profile_picture = db.Column(db.Unicode(length=128), unique=True, nullable=True) twitter = db.Column(db.Unicode(length=256), unique=True, nullable=True) github = db.Column(db.Unicode(length=256), unique=True, nullable=True) I would like to add another column to the user class which is a list of users. How can I accomplish this? I think the proper name of what I am looking for is a self-referential one-to-many relationship.
favorite count: 0
has comment: http://stackoverflow.com/comment/82666175
type: Question
has comment: http://stackoverflow.com/comment/82666197
tagged with: python
has title: Using SQLAlchemy, how can I make a field in a class that is a list of other instances of said class?
upvote count: 2

countvectorizer
type: Tag
tags question: http://stackoverflow.com/q/47711515
tag name: countvectorizer
tags question: http://stackoverflow.com/q/47736659

http://stackoverflow.com/a/47847416
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/47798172
has body: I was passing a datetime char type to a timestamp column. In q I would define these as... q)table:([]date:`datetime$(); name:`symbol$()) q)meta table c | t f a ----| ----- date| z name| s q)table:([]date:`timestamp$(); name:`symbol$()) q)meta table c | t f a ----| ----- date| p name| s I was able to work around this by parsing the datetime to a timestamp and casting to K.timestamp([])... Code below... from bittrex.bittrex import Bittrex, API_V2_0 from datetime import datetime import time from pyq import q, K get_bittrex = Bittrex(None, None) starttime = time.time() q.load(':alpha') while True: market_result = get_bittrex.get_market_summaries()['result'] for res in market_result: market_name = res['MarketName'] ask = float(res['Ask']) bid = float(res['Bid']) last = float(res['Last']) volume = float(res['Volume']) dt = res['TimeStamp'] if market_name in ['USDT-BTC', 'USDT-ETH', 'USDT-LTC', 'USDT-XRP', 'USDT-NEO', 'USDT-BCC', 'USDT-ZEC', 'USDT-XMR', 'USDT-DASH']: ts = datetime.strptime(dt, '%Y-%m-%dT%H:%M:%S.%f') data = [market_name[5:], ask, bid, last, volume, ts] q.upsert(':alpha', [data]) q.get(':alpha').show() time.sleep(60.0) Now returns the correct char type in my table... q)meta alpha c | t f a ----| ----- Name| s Ask | f Bid | f Last| f Vol | f Time| p
answers question: http://stackoverflow.com/q/47798172
score: 0

http://stackoverflow.com/comment/82376434
comment on: http://stackoverflow.com/q/47708020
type: Comment
type: QuestionComment
score: 0
has text: Yeah it is, it's defined as a function, but that is not the issue.

http://stackoverflow.com/a/47756716
upvote count: 5
type: Answer
accepted answer of: http://stackoverflow.com/q/47716695
score: 5
type: AcceptedAnswer
downvote count: 0
has body: Ended up performing a stock POST with requests. I'm not sure if the splunk client is even intended to support the HTTP Event Collector. import requests url='https://splunkcollector.hostname.com:443/services/collector/event' authHeader = {'Authorization': 'Splunk {}'.format('ABCDEFG-8A55-4ABB-HIJK-1A7E6637LMNO')} jsonDict = {"index":"cloud_custodian", "event": { 'message' : "Dummy test python client log" } } r = requests.post(url, headers=authHeader, json=jsonDict, verify=False) print r.text
answers question: http://stackoverflow.com/q/47716695
has comment: http://stackoverflow.com/comment/103540610
has comment: http://stackoverflow.com/comment/98673640

http://stackoverflow.com/a/56950883
score: 1
answers question: http://stackoverflow.com/q/47699053
downvote count: 0
upvote count: 1
has body: SamuelNLP's answer is perfect for the case of different calculations on the DataFrame, as is presented in his example! But I had a very similar problem as pookie, a large DataFrame (length>120'000'000), where I needed the std of all but one column over every 5 minute period. And in this specific case, there is a simple but faster alternative: data_std = data.resample('5min').std() data_std.drop('temperature', axis=1) I just calculated the std after the resampling, and drop the columns that I didn't need. &gt;&gt; data.head() x y z temperature time 2018-02-21 11:00:06.354 0.606 0.764 -0.499 21.163203 2018-02-21 11:00:06.364 -0.762 0.127 -0.499 21.163203 2018-02-21 11:00:06.374 -0.793 0.143 -0.482 21.163203 2018-02-21 11:00:06.384 -0.809 0.064 -0.418 21.163203 2018-02-21 11:00:06.394 -0.825 -0.016 -0.401 21.163203 &gt;&gt; data_std = data.resample('5min').std() &gt;&gt; data_std.drop('temperature', axis=1) &gt;&gt; data_std.head() x y z time 2018-02-21 11:00:05 0.260700 0.192227 0.244653 2018-02-21 11:00:10 0.125168 0.164327 0.116562 2018-02-21 11:00:15 0.138330 0.154963 0.126264 2018-02-21 11:00:20 0.182339 0.204350 0.226019 2018-02-21 11:00:25 0.193661 0.107022 0.133125 Speed-up: I tested the two options, over different DataFrame lengths, each 50 times with a simple time.time() measurement. # resample-drop method tmp = data.resample('5s').std() tmp.drop('temperature', axis=1, inplace=True) # aggregate method tmp = data.resample('5s').agg({'x': np.std, 'y':np.std, 'z':np.std}) The resample-drop method is 20%-25% faster than the aggregate method. I assume this runtime difference is due to a more efficient implementation of the simple resample-drop part as compared to the aggregate. But I would be glad for more explanations.
type: Answer

http://stackoverflow.com/comment/82554773
score: 0
type: AnswerComment
type: Comment
has text: Many thanks for the extensive answer as well as the StyleFrame solution itself of course, it is a great help!!!
comment on: http://stackoverflow.com/a/47762136

http://stackoverflow.com/a/67966739
accepted answer of: http://stackoverflow.com/q/47805978
upvote count: 3
has body: Old question but if anyone comes across this, there is a new survival analysis package for python, surpyval, that handles this, and other cases of censoring and truncation. For the example you provide above it would simply be: import surpyval as surv values = np.array([10197.8, 3349.0, 15318.6, 142.6, 6976.5, 2590.7, 11351.7, 10177.0, 3738.4]) # 0 = failed, 1 = right censored censored = np.array([0, 0, 0, 0, 0, 1, 1, 1, 0]) model = surv.Weibull.fit(values, c=censored) print(model.params) (10584.005910580288, 1.038163987652635) You might also be interested in the Weibull plot: model.plot(plot_bounds=False) Weibull plot Full disclosure, I am the creator of surpyval
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47805978
score: 3
type: Answer

spark-structured-streaming
tags question: http://stackoverflow.com/q/47829201
tag name: spark-structured-streaming
type: Tag

http://stackoverflow.com/comment/82699688
score: 0
has text: @kronosjt I added an example with a normal string, and how it could be formatted. It can, of course, also be written up a lot more densely.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47830883

http://stackoverflow.com/comment/82545732
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47776954
has text: You might want to ask this on the [official pythonista forum](https://forum.omz-software.com/)

http://stackoverflow.com/a/47834547
has body: Since Im not sure what sort of Data Structure is file in your example code provided, I'll assume its a string. And in that case you could create a conditional html tag like this {% if ( (".jpg" in status.image.url) or (".png" in status.image.url) ) %} {% else %} {% endif %}
answers question: http://stackoverflow.com/q/47833910
has comment: http://stackoverflow.com/comment/82632368
has comment: http://stackoverflow.com/comment/82633105
has comment: http://stackoverflow.com/comment/82632207
has comment: http://stackoverflow.com/comment/82632591
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/82633021
accepted answer of: http://stackoverflow.com/q/47833910
type: AcceptedAnswer

http://stackoverflow.com/comment/82449087
score: 0
type: AnswerComment
has text: doesn't meet OP's `map` requirement
type: Comment
comment on: http://stackoverflow.com/a/47744473

http://stackoverflow.com/a/47738569
score: 19
accepted answer of: http://stackoverflow.com/q/47738345
has comment: http://stackoverflow.com/comment/126384056
has comment: http://stackoverflow.com/comment/92060092
has body: Remove STATIC_ROOT Add STATICFILES_DIRS to the settings file.(Recommended during development) STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) STATICFILES_DIRS : This setting defines the additional locations the staticfiles app will traverse if the FileSystemFinder finder is enabled, e.g. if you use the collectstatic or findstatic management command or use the static file serving view. This should be set to a list of strings that contain full paths to your additional files directory STATIC_ROOT : The absolute path to the directory where collectstatic will collect static files for deployment. If you want to use STATIC_ROOT, then run the command python manage.py collectstatic which will collect all the static files to the static directory mentioned in STATIC_ROOT. This is used during deployment. Find the detailed documentation here.
type: Answer
upvote count: 19
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47738345
downvote count: 0

http://stackoverflow.com/comment/82458603
comment on: http://stackoverflow.com/q/47749219
type: Comment
has text: That's fine, actually we basically *require* all [tag:regex] questions to also specify the language or platform, ideally with a suitable tag.
type: QuestionComment
score: 0

http://stackoverflow.com/comment/82496891
has text: @EricDuminil: Jupp, this is definitely a Python 2 question, but can be made to work in Python 3 by correcting it your way.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47765846

http://stackoverflow.com/comment/82541357
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47790125
has text: is there a specific reason you want to due this through awkward mel?
score: 0

http://stackoverflow.com/q/47764312
favorite count: 0
has answer: http://stackoverflow.com/a/47764374
type: Question
tagged with: dataframe
tagged with: python
accepted answer: http://stackoverflow.com/a/47764374
type: AnsweredQuestion
has body: I am looking to write a python function that will select a number. So For example, for n=1234567 and k=3, the program has to print the digit 5. So K would define the digit to select from the right side. If the program has less than K digits it will just print 0 instead. So if N = 12 K= 3 it will print 0.
downvote count: 0
has title: Python Selecting a number from the right side
score: 1
upvote count: 1
answer count: 1

http://stackoverflow.com/comment/82458829
type: QuestionComment
comment on: http://stackoverflow.com/q/47749297
score: 2
type: Comment
has text: Post the code here, not a link to it. If the code is too long, reduce it to a [Minimal, Complete, and Verifiable Example](https://stackoverflow.com/help/mcve).

http://stackoverflow.com/comment/82567529
score: 5
type: Comment
comment on: http://stackoverflow.com/q/47803002
has text: "except that it shares mutable state between iterations. Is there any way to do it with a list comprehension" there might be some hacky way, but if it invovles mutating state, then it probably **shouldn't be a list-comprehension**
type: QuestionComment

http://stackoverflow.com/comment/82445030
type: AnswerComment
comment on: http://stackoverflow.com/a/47742362
has text: That's what I did, you can see on my post the `(testenv)` meaning I had sourced it already.
type: Comment
score: 0

http://stackoverflow.com/q/47713028
type: Question
tagged with: python-3.x
tagged with: python
tagged with: sorting
has title: How to sort a nested list by reverse length of the sublists and keep the original order
has answer: http://stackoverflow.com/a/47713174
accepted answer: http://stackoverflow.com/a/47713174
type: AnsweredQuestion
score: 3
upvote count: 3
tagged with: list
downvote count: 0
answer count: 1
has body: Example: a = [ [['test', 21, 28], ['test', 61, 68], ['test', 111, 118], ['test', 118, 125]], [['Columns', 21, 28], ['Columns', 61, 68], ['Columns', 111, 118], ['Columns', 118, 125], ['Columns', 128, 135]], [['Delete', 14, 20], ['Delete', 47, 53], ['Delete', 54, 60], ['Delete', 78, 84], ['Delete', 95, 101]], [['rw', 21, 28], ['rw', 61, 68], ['rw', 111, 118]] ] What I want to do is to sort the nested list by reversed length of the sublists but to keep the original order if the length of sublists is the same. Expected result: [ [['Columns', 21, 28], ['Columns', 61, 68], ['Columns', 111, 118], ['Columns', 118, 125], ['Columns', 128, 135]], [['Delete', 14, 20], ['Delete', 47, 53], ['Delete', 54, 60], ['Delete', 78, 84], ['Delete', 95, 101]], [['test', 21, 28], ['test', 61, 68], ['test', 111, 118], ['test', 118, 125]], [['rw', 21, 28], ['rw', 61, 68], ['rw', 111, 118]] ] I know I can use this to sort the list by reverse length but it will not keep the original order: a = sorted(a, key=len, reverse=True) (it reverses the sublists 'Delete' and 'Columns') How can I sort the list by reverse length of the sublists and keep the original order?
favorite count: 0

http://stackoverflow.com/comment/82399051
type: AnswerComment
score: 0
has text: Yeah but I'm kinda having trouble figuring out how to adapt Stuart's answer into a similar problem of extracting the row in a multidimensional array, that sums to the closest number to B
type: Comment
comment on: http://stackoverflow.com/a/47718160

http://stackoverflow.com/q/47827858
tagged with: python
tagged with: python-2.x
type: Question
answer count: 1
accepted answer: http://stackoverflow.com/a/47827901
has answer: http://stackoverflow.com/a/47827901
has body: One basic question in OOP. test.py file content: class test(object): def __init__(self): print 'INIT of test class' obj = test() Then I opened another file. I just inherited from the above test class: from test import test class test1(test): def __init__(self): pass So when I run this second file, the __init__() from the parent class is executed (the INIT got printed). I read that I can avoid it by using if __name__ == '__main__': # ... I can overcome this, but my question is why the parent class's init is executing as I am just importing this class only in my second file. Why is the object creation code executed?
has title: Parent class init is executing during inheritence
type: AnsweredQuestion
score: 0
tagged with: oop

http://stackoverflow.com/q/47754487
score: 2
tagged with: http://stackoverflow.com/tag/json
has title: How to start a Python server with parameters on another Python server
type: Question
upvote count: 2
answer count: 0
tagged with: server
downvote count: 0
type: UnansweredQuestion
tagged with: javascript
tagged with: python
tagged with: jquery
favorite count: 0
has body: So my problem is that I have a server which returns a JSONobject to the user when the user sends a string to its URL-adress. The problem is that this server needs the parameters: hostname, port (when it is started) from the users pc in order to serve the user with the JSONobjects. So I will first have to start a server manually (we can call it getserver1) and the code of the server is (Don't care about the import-stuff, its just to enable it on both python 2 and 3): #!/usr/bin/env python try: # Python 3 from http.server import HTTPServer, SimpleHTTPRequestHandler, test as test_orig import sys def test (*args): test_orig(*args, port=int(sys.argv[1]) if len(sys.argv) > 1 else 8000) except ImportError: # Python 2 from BaseHTTPServer import HTTPServer, test from SimpleHTTPServer import SimpleHTTPRequestHandler class CORSRequestHandler (SimpleHTTPRequestHandler): def end_headers (self): self.send_header('Access-Control-Allow-Origin', '*') SimpleHTTPRequestHandler.end_headers(self) if __name__ == '__main__': test(CORSRequestHandler, HTTPServer) On this server I have put a html-file with the code: The error I get is the: No "Access-Control-Allow-Origin" when the html file is run. The code of the getserver2.py has the same code as the getserver1 above which should allow the "Access-Control-Allow-Origin". So how can I get this to work. I would like to not involve any new elements as php or something like that into the stew. Also, the next problem when this works is to start the getserver2 with the 2 parameters (So yes getserver2 is a little different from getserver1 but only in the sense that it takes the two parameters). But the test I'm doing right now uses the same code in both servers to start with.

http://stackoverflow.com/comment/82541589
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47790247
has text: Not really. But feel free to append your answer to show how I could rearrange the columns.

indexing
tags question: http://stackoverflow.com/q/47710894
tags question: http://stackoverflow.com/q/47756449
tags question: http://stackoverflow.com/q/47791929
tags question: http://stackoverflow.com/q/47737277
tag name: indexing
type: Tag
tags question: http://stackoverflow.com/q/47699464
tags question: http://stackoverflow.com/q/47750362
tags question: http://stackoverflow.com/q/47812635
tags question: http://stackoverflow.com/q/47726795
tags question: http://stackoverflow.com/q/47841887
tags question: http://stackoverflow.com/q/47740196
tags question: http://stackoverflow.com/q/47751504
tags question: http://stackoverflow.com/q/47777718
tags question: http://stackoverflow.com/q/47823335
tags question: http://stackoverflow.com/q/47710681
tags question: http://stackoverflow.com/q/47802572
tags question: http://stackoverflow.com/q/47804572

http://stackoverflow.com/q/47707793
possible better answer: http://stackoverflow.com/a/47767686
has comment: http://stackoverflow.com/comment/82496633
accepted answer: http://stackoverflow.com/a/47768908
answer count: 2
upvote count: 2
has answer: http://stackoverflow.com/a/47767686
downvote count: 0
tagged with: machine-learning
tagged with: python
has comment: http://stackoverflow.com/comment/82495866
type: AnsweredQuestion
score: 2
tagged with: deep-learning
has answer: http://stackoverflow.com/a/47768908
tagged with: tensorboard
has body: I am training a ResNet50 on Audioset2017 dataset,with tensorflow during training and validating results,my loss function fluctuating,the overall trend is going down,but I am afraid of this. I have run with 100 epochs,with batch size=100. and have decrease and increase the learning rate,but had no effect. want to know is my training correct,can I use this network?or it causes wrong results.Can I remove them with some tricks? these are my train and validation(eval) loss and other metrics pictures(from tensorboard). validation mode: train mode:
has title: tensorflow CNN loss function goes up and down ( oscilating) in tensorboard,How to remove them?
tagged with: tensorflow
favorite count: 0
type: Question

http://stackoverflow.com/q/47722356
type: UnansweredQuestion
favorite count: 0
has body: I am trying to compare 2 lists to see if they fundamentally have the same contents (in whatever order). e.g. x = [1, 2, 2, 3, 4, 4, 5] y = [4, 3, 5, 1, 2, 2, 4] How do I state that these 2 lists each have 1 1, 2 2s, 1 3, 2 4s and 1 5? (python version 3.6)
linked to: http://stackoverflow.com/q/7828867
has title: comparing contents of two lists python
score: 1
tagged with: compare
has comment: http://stackoverflow.com/comment/82405318
duplicate of: http://stackoverflow.com/q/7828867
tagged with: python
has comment: http://stackoverflow.com/comment/82405324
type: Question
tagged with: list
answer count: 0
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/47847347
has comment: http://stackoverflow.com/comment/132122183
type: Answer
has body: This code works as I asked, it shows the interface properly. The key thing is qtbot.waitForWindowShown(window) line. from tests.test import MyApp from time import sleep from PyQt5.QtCore import * def test_myapp(qtbot): window = MyApp() qtbot.addWidget(window) window.show() qtbot.waitForWindowShown(window) sleep(3) qtbot.mouseClick(window.buttonBox.buttons()[0], Qt.LeftButton) assert window.label.text() == 'accept' qtbot.stopForInteraction()
answers question: http://stackoverflow.com/q/47802375
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47802375
upvote count: 9
score: 9

http://stackoverflow.com/a/47836035
has comment: http://stackoverflow.com/comment/82636801
downvote count: 0
type: AcceptedAnswer
has body: json is very fine with single quote, eg: t=# select $${"short_description": "This property's price is..."}$$::jsonb; jsonb ------------------------------------------------------ {"short_description": "This property's price is..."} (1 row) so I assume you could try using dollar sign quotes, to avoid statement structuring exception with single quotes
score: 3
type: Answer
answers question: http://stackoverflow.com/q/47835727
upvote count: 3
accepted answer of: http://stackoverflow.com/q/47835727

http://stackoverflow.com/comment/82487310
type: Comment
type: QuestionComment
has text: My friend got it working with the following: `photo_filename = "/home/pi/motion-uploader/Photos/%s.jpg" % now photo_file = open(photo_filename, "wb") camera.capture(photo_file) photo_file.close() cfg_path = sys.argv[1] vid_path = sys.argv[2] MotionUploader(cfg_path).upload_snapshot(photo_filename)`
comment on: http://stackoverflow.com/q/47748528
score: 0

http://stackoverflow.com/q/47707016
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/47707256
upvote count: 1
tagged with: scipy
favorite count: 0
has answer: http://stackoverflow.com/a/47707256
type: Question
tagged with: python
tagged with: kdtree
has body: I am attempting to build a kd-tree with 3D coordinates that have arbitrary integers assigned to them. For example a tuple ([34534.65424, 10957.00023, -79.154323], 32). However, I cant find out how to use scipy.spatial.cKDTree() with anything but a numpy array. The identifier could even be a fourth field in the numpy array but the tree would have to be build based on the first three coordinates only. Can somebody shed some light on this? The purpose is to reference the kd-tree nodes back to a segment it belongs to for later comparisons. Thank you!
tagged with: numpy
type: AnsweredQuestion
has title: Scipy kd-tree with auxiliary identifier assigned to each point
score: 1

http://stackoverflow.com/a/47809410
type: Answer
score: 6
upvote count: 6
answers question: http://stackoverflow.com/q/47808676
has body: I have solved my problem by changing file "mpld3/_display.py". Please change below part: class NumpyEncoder(json.JSONEncoder): """ Special json encoder for numpy types """ - def default(self, obj): if isinstance(obj, (numpy.int_, numpy.intc, numpy.intp, numpy.int8, numpy.int16, numpy.int32, numpy.int64, numpy.uint8, numpy.uint16,numpy.uint32, numpy.uint64)): return int(obj) elif isinstance(obj, (numpy.float_, numpy.float16, numpy.float32, numpy.float64)): return float(obj) + elif isinstance(obj,(numpy.ndarray,)): #### This is the fix + return obj.tolist() return json.JSONEncoder.default(self, obj) Please refer https://github.com/javadba/mpld3/commit/57ed37dbc4749259b1b46cba8bf28de802972adb for more detail.
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/87570412
accepted answer of: http://stackoverflow.com/q/47808676

http://stackoverflow.com/a/47820627
score: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47820494
downvote count: 0
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/47820494
has body: Say the column name in which the data is stored is called col, try df['name'] = df['col'].str.extract('www.(\w+)\.') 0 nytimes 1 cnn To get them in a list l = df['col'].str.extract('www.(\w+)\.').values.tolist() ['nytimes', 'cnn']

http://stackoverflow.com/q/47726073
answer count: 1
downvote count: 0
favorite count: 0
upvote count: 17
has body: I have a numpy ndarray: array = np.array([[1,2,3],[4,5,6],[7,8,9]]) Whenever I do, np.argmax(array), it doesn't return a tuple of row and column. Why not?
has answer: http://stackoverflow.com/a/47726092
tagged with: python
score: 17
type: Question
tagged with: numpy
has title: How to find the argmax of a two dimensional array in numpy?
type: UnansweredQuestion

http://stackoverflow.com/q/47778176
has title: Extracting python List
upvote count: 0
type: UnansweredQuestion
downvote count: 5
tagged with: python
has body: I have a pandas data frame which has strings in it like this ID value 1 2 2 25,35 3 1,25,3,40 I would like to count the number of times each value occurs. The values are strings not integers or floats
score: -5
tagged with: pandas
has answer: http://stackoverflow.com/a/47778258
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47778235
answer count: 2

http://stackoverflow.com/q/47796196
tagged with: model-fitting
has title: How to make a fittable Ring Gaussian model in python?
tagged with: ring
has body: The purpose of my experiment is to fit a ring gaussian model to image data and find out the parameters of elliptical or ring Gaussian object in an image. I've tried Astropy to make a Ring Gaussian model for simplicity and trial. Unfortunately, it's completely different from my artificial data. from astropy.modeling import Fittable2DModel, Parameter, fitting import matplotlib.pyplot as plt import numpy as np class ringGaussian(Fittable2DModel): background = Parameter(default=5.) amplitude = Parameter(default=1500.) x0 = Parameter(default=15.) y0 = Parameter(default=15.) radius = Parameter(default=2.) width = Parameter(default=1.) @staticmethod def evaluate(x, y, background, amplitude, x0, y0, radius, width): z = background + amplitude * np.exp( -((np.sqrt((x-x0)**2. + (y-y0)**2.) - radius) / width)**2 ) return z Then I made some artificial data (initial parameters) to test the fitting function of ring gaussian class. back = 10 # background amp = 2000 # highest value of the Gaussian x0 = 10 # x coordinate of center y0 = 10 # y coordinate of center radius = 3 width = 1 xx, yy = np.mgrid[:30, :30] z = back + amp * np.exp( -((np.sqrt((xx-x0)**2. + (yy-y0)**2.) - radius) / width)**2 ) I plotted xx, yy and z using contourf: fig = plt.subplots(figsize=(7,7)) plt.contourf(xx,yy,z) plt.show() It is what I got: enter image description here Then I tried to fit the z using my fittable class: p_init = ringGaussian() #bounds={"x0":[0., 20.], "y0":[0., 20.]} fit_p = fitting.LevMarLSQFitter() p = fit_p(p_init, xx, yy, z) # It is the parameter I got: &lt;ringGaussian(background=133.0085329497139, amplitude=-155.53652181827655, x0=25.573499373946227, y0=25.25813520725603, radius=8.184302497405568, width=-7.273935403490675)&gt; I plotted the model: fig = plt.subplots(figsize=(7,7)) plt.contourf(xx,yy,p(xx,yy)) plt.show() It is what I got: enter image description here Originally, I also tried to include the derivative in my class: @staticmethod def fit_deriv(x, y, background, amplitude,…
tagged with: gaussian
tagged with: python
tagged with: astropy
score: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47796623
answer count: 1
type: Question

http://stackoverflow.com/comment/82530004
score: 0
type: AnswerComment
has text: But i don't think it is possible because as tobias_k mentioned there is no way to know if a number returned as 999,999 or 999.999 is supposed to be int(999999) or float(999.999) without knowing the locale, and for the same reason a locale can't be determined from the returned number. I accepted this answer because it illuminated to this fact.
comment on: http://stackoverflow.com/a/47782748
type: Comment

http://stackoverflow.com/a/47744926
has body: A run configuration (not just in PyCharm, for example JetBrains IntelliJ also has them, in fact most IDEs have this concept) is a compilaton of settings to be used when running a program. Let us stay with Python for the sake of simplicity. You might think that when you execute your script by typing in your command prompt... python myscript.py ...that there are no settings or configuration involved. You are just running your script, right? Not quite, you are in fact using what you could call an implicit run configuration, i.e. are whatever defaults and environment settings happen to take effect. Some examples you will also find in PyCharm Python run configurations: Script path is just the script you are calling, in the example myscript.py since we specified that on the command line. Python interpreter is whatever Python interpreter is first in your path. Parameters is empty in our example, as we didn't specify any on the command line. Working directory is the current directory, where we are with our command prompt. Enviromnent variables are those that happen to be set in our shell. All of these and more can be defined in a run configuration (or multiple different run configurations if you need) for your project. You can then select these conveniently from the dropdown menu, and the one currently selected will be used to execute your program when you press the green play button. What is the difference between using a run configuration and just run in PyCharm? If you just run your program, you are telling PyCharm that it should just use the project default configuration for the specific file type. In other words, you are using a run configuration as well there, just the unmodified default configuration.
answers question: http://stackoverflow.com/q/47743660
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47743660
type: Answer

http://stackoverflow.com/q/47772911
has body: I am trying to open any website using Geckodriver and Selenium for Python. However when Firefox is initiated by Selenium, the URL bar remains empty. After 60 seconds or so I receive an error in the kernel stating: WebDriverException: Message: connection refused. This is the stuff I'm using: Linux Raspberry Pi 4.4.38-v7+ #938 SMP Selenium 3.8.0 Geckodriver 0.19.1 Python 2.7.9 Firefox esr 52.5.0 (32-bit) I have seen other posts about this problem: question #18768658 question #725262 Here is my code: import os from selenium import webdriver from selenium.webdriver.support.ui import Select from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC os.environ["DISPLAY"] = ":0.0" fp = webdriver.FirefoxProfile() fp.set_preference("network.proxy.type",2) fp.set_preference("network.proxy.autoconfig_url", "127.0.0.1:4444") browser = webdriver.Firefox(firefox_profile=fp) browser.get("http://www.google.com") I saw another person mentioning setting the proxy type to auto in the code so I tried that as well. However the problem persists. Does anybody know a solution for this problem? I am guessing it has something to do with the versions of Geckodriver and Selenium being incompatible? When I look at the geckodriver.log it says this: 1513080263669 geckodriver INFO geckodriver 0.19.1 1513080263692 geckodriver INFO Listening on 127.0.0.1:56782 1513080265346 mozrunner::runner INFO Running command: "/usr/bin/firefox" "-marionette" "-profile" "/tmp/rust_mozprofile.pBJH12y6ylm0" (firefox-esr:4841): GLib-GObject-CRITICAL **: g_object_ref: assertion 'object-&gt;ref_count &gt; 0' failed (firefox-esr:4841): GLib-GObject-CRITICAL **: g_object_unref: assertion 'object-&gt;ref_count &gt; 0' failed (firefox-esr:4841): GLib-GObject-CRITICAL **: g_object_ref: assertion 'object-&gt;ref_count &gt; 0' failed (firefox-esr:4841): GLib-GObject-CRITICAL **: g_object_unref: assertion 'object-&gt;ref_…
type: UnansweredQuestion
tagged with: firefox
has title: Geckodriver and Selenium with Raspberry Pi using Python gives "connection refused"
downvote count: 0
tagged with: selenium
favorite count: 0
type: Question
score: 3
tagged with: linux
tagged with: python
has comment: http://stackoverflow.com/comment/82837475
tagged with: raspberry-pi
answer count: 0
upvote count: 3

http://stackoverflow.com/q/47732490
tagged with: flask
has title: uWSGI: can't unpickle with a namedtuple - "can't get attribute" error?
has body: I have a Flask service that runs perfectly by itself with the default Flask web server. I'm trying to host it with uWSGI, but in that environment, I'm running into issues where I'm not able to access some required data in a pickle. This is my main WSGI script: from collections import namedtuple from search_service import app SomeNamedTuple = namedtuple('SomeNamedTuple ', 'idx data') if __name__ == "__main__": app.run() And in my Flask service, I'm doing something like this: unpickled_data = None @app.before_first_request def startup(): global unpickled_data with open('data.pickle', 'rb') as handle: unpickled_data = pickle.load(handle) No matter how I try to define the namedtuple (in wsgi.py, in my Flask API, etc...), I end up get this error: [2017-12-09 19:40:57,209] ERROR in app: Exception on / [GET] Traceback (most recent call last): File "/home/ringham/app/appenv/lib/python3.5/site-packages/flask/app.py", line 1982, in wsgi_app response = self.full_dispatch_request() File "/home/ringham/app/appenv/lib/python3.5/site-packages/flask/app.py", line 1607, in full_dispatch_request self.try_trigger_before_first_request_functions() File "/home/ringham/app/appenv/lib/python3.5/site-packages/flask/app.py", line 1654, in try_trigger_before_fi rst_request_functions func() File "./service.py", line 44, in startup min_eval_data = pickle.load(handle) AttributeError: Can't get attribute 'SomeNamedTuple ' on &lt;module '__main__' (built-in)&gt; What might I be missing?
score: 1
has answer: http://stackoverflow.com/a/52649734
answer count: 1
tagged with: uwsgi
favorite count: 0
type: Question
type: UnansweredQuestion
downvote count: 0
upvote count: 1
tagged with: python

http://stackoverflow.com/q/47732102
tagged with: python
tagged with: computer-vision
linked to: http://stackoverflow.com/q/46520123
score: 9
type: AnsweredQuestion
tagged with: python-2.7
has body: I've been wondering what the optical flow matrix, that calcOpticalFlowFarneback function of OpenCV returns, tells. If I compute this Python line: flow = cv2.calcOpticalFlowFarneback(cv2.UMat(prvs),cv2.UMat(next), None, 0.5, 3, 15, 3, 5, 1.2, 0) I will get a matrix, the same size as prvs and next frames, containing, for each position, a vector of two elements (x,y). My question is... That vector is the vector from prvs to next or from next to prvs? Thanks.
tagged with: opticalflow
linked to: http://stackoverflow.com/q/44535091
has comment: http://stackoverflow.com/comment/82428372
has title: Unknown output of OpenCV's calcOpticalFlowFarneback
answer count: 1
accepted answer: http://stackoverflow.com/a/47736465
downvote count: 0
has comment: http://stackoverflow.com/comment/82428277
has answer: http://stackoverflow.com/a/47736465
favorite count: 0
type: Question
tagged with: opencv
has comment: http://stackoverflow.com/comment/82428010
has comment: http://stackoverflow.com/comment/82429959
upvote count: 9

http://stackoverflow.com/comment/82664095
type: Comment
type: QuestionComment
has text: *"seems to not work"* is a profoundly unhelpful description of the problem. Give a [mcve].
comment on: http://stackoverflow.com/q/47849791
score: 1

http://stackoverflow.com/q/47795610
has comment: http://stackoverflow.com/comment/82552108
type: AnsweredQuestion
score: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/47795807
has answer: http://stackoverflow.com/a/47795807
type: Question
tagged with: tkinter
has body: I have a frame, let's say: import Tkinter as tk class Page1(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) label1 = G.tk.Label(self, text="Change me!") label1.pack(pady=10,padx=10) label2 = G.tk.Label(self, text="Change me too!") label2.pack(pady=10,padx=10) Now I would like to be able to change the "Change me!" and "Change me too!" texts both by pressing a button on the page. In my implementation this is for localisation purposes. My current implementation just has separate frames for each language but that is incredibly cumbersome to maintain. I would like to just have one frame for each page of content, and only change the text that is displayed. Is that possible? I've seen StringVar thrown around in documentation but not with a very clear guide on how to use it.
has title: How do I change text on button labels within a frame?
has comment: http://stackoverflow.com/comment/82552152
has comment: http://stackoverflow.com/comment/82553025
tagged with: localization
answer count: 1

http://stackoverflow.com/comment/82616871
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47824532
has text: The \\ is a clue. It suggests double encoding. It means that you have a literal \ in your string, but you're only supposed to have binary, so the \ is used to escape non-ASCII bytes. You've probably inserted a `bytes` object into a `varchar` column. Try doing `SELECT decode(object, 'escape') FROM ...` and see what you get back.
type: Comment

http://stackoverflow.com/comment/82513902
type: AnswerComment
comment on: http://stackoverflow.com/a/47776355
has text: @jlandercy Cheers, I was typing up a solution while you posted :-)
score: 0
type: Comment

http://stackoverflow.com/q/47745027
favorite count: 0
possible better answer: http://stackoverflow.com/a/47801708
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/47801708
accepted answer: http://stackoverflow.com/a/47755630
upvote count: 2
has body: By default, function dynamic_rnn outputs only hidden states (known as m) for each time point which can be obtained as follows: cell = tf.contrib.rnn.LSTMCell(100) rnn_outputs, _ = tf.nn.dynamic_rnn(cell, inputs=inputs, sequence_length=sequence_lengths, dtype=tf.float32) Is there a way get intermediate (not final) cell states (c) in addition? A tensorflow contributor mentions that it can be done with a cell wrapper: class Wrapper(tf.nn.rnn_cell.RNNCell): def __init__(self, inner_cell): super(Wrapper, self).__init__() self._inner_cell = inner_cell @property def state_size(self): return self._inner_cell.state_size @property def output_size(self): return (self._inner_cell.state_size, self._inner_cell.output_size) def call(self, input, state) output, next_state = self._inner_cell(input, state) emit_output = (next_state, output) return emit_output, next_state However, it doesn't seem to work. Any ideas?
has answer: http://stackoverflow.com/a/47755630
downvote count: 0
tagged with: machine-learning
has title: Tensorflow: how to obtain intermediate cell states (c) from LSTMCell using dynamic_rnn?
tagged with: tensorflow
type: AnsweredQuestion
score: 2
tagged with: python
tagged with: recurrent-neural-network
tagged with: lstm

http://stackoverflow.com/comment/82493393
comment on: http://stackoverflow.com/q/47765849
has text: `;` is not allowed after `do`, `then` and `else`.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/47794369
has answer: http://stackoverflow.com/a/47811461
score: 1
answer count: 1
downvote count: 0
has body: I have two models. One model has an One2Many field pointing to the other one. When I save the main record, it only saves one record of the One2many relation. I need it to save 'n' records. Maybe the problem is the structure of the data I planned. Here is the code. I'm sorry for the Spanish names of the variables. Thanks in advance. This is the first class it calls the second class with One2Many relation. class EmpleadosProductos(models.Model): _name = "employee.as.product" #the One2Many relation of the trouble employee_line = fields.One2many( 'employee.line', 'id', string='Employee Lines', store=True ) companyias = fields.Many2one('res.partner', 'Compañia', domain=[('is_company', '=', True)]) amount_total = fields.Monetary(string='Total', store=True, readonly=True, compute='_calcularTotal') journal_entry = fields.Many2one('account.move') currency_id = fields.Many2one('res.currency', 'Currency', required=True, default=lambda self: self.env.user.company_id.currency_id.id) fecha = fields.Date('Fecha') referencia = fields.Char(string='Ref', required=True) _sql_constraints = [ ('refererecia_constraint', 'unique(referencia)', 'La referencia debe de ser única!'), ] @api.one @api.depends('employee_line.total') def _calcularTotal(self): for empleado_obra in self: acumulador = 0.0 for linea in empleado_obra.employee_line: acumulador += linea.total empleado_obra.update({ 'amount_total': acumulador }) This is the second class called in the One2Many relation. class EmployeLine(models.Model): _name = 'employee.line' descripcion = fields.Text(string='Descripción', required=False) employee_id = fields.Many2one( 'hr.employee', string="Empleado", requiered=True, change_default=True ) currency_id = fields.Many2one('res.currency', 'Currency', required=True, default=lambda self: self.env.user.company_id.currency_id.id) apodo = fields.Char('apodo', readonly=False) precio_por_hora = fields.Float('Sueldo/hora', store=True) numero_de_horas = fields.Integer('Número de horas', store=True) tot…
upvote count: 1
favorite count: 0
type: Question
has title: Why my One2Many field does not save more than one record?
tagged with: odoo-10
tagged with: odoo
tagged with: odoo-8
tagged with: python
accepted answer: http://stackoverflow.com/a/47811461
type: AnsweredQuestion
tagged with: python-2.7

http://stackoverflow.com/q/47773765
downvote count: 0
upvote count: 1
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47773935
has title: i've just finished this script it connects to the main script but the doesnt print a csv
tagged with: http://stackoverflow.com/tag/csv
score: 1
has body: i've just finished this script it connects to the main script and the website runs but it doesnt print a csv like i want it to have i done something wrong in my script when i try the /dan route it says it cant find the csv import psutil import sys import os import inspect import socket from gevent.pywsgi import WSGIServer from time import gmtime, strftime from threading import Thread from flask import Flask, render_template, session, app, request, redirect, url_for, send_file, send_from_directory from flask_cors import CORS, cross_origin from time import sleep import requests import data import tank import csv APP_ROOT = os.path.dirname(os.path.abspath('__file__')) def funcScript(): from data import tankOBJ as tank with open(os.path.join('F:\csvtester', '\motherwell.csv'),'w',newline='') as output_file: writer = csv.writer(output_file) writer.writerow(tank) return 'Hello World!' here is the function above to output the csv and below is the output for the webapp @app.route('/dan') def downloadDocument(): try: return csvmotherwell.funcScript() except Exception as error: return event.Error(str(inspect.stack()[1][3]), str(sys.exc_info()[-1].tb_lineno), str(type(error)), str(error))
answer count: 1
has comment: http://stackoverflow.com/comment/82508612
accepted answer: http://stackoverflow.com/a/47773935
tagged with: import
favorite count: 0
type: Question

http://stackoverflow.com/a/47763934
downvote count: 0
score: 1
upvote count: 1
has body: First use set_index() with DatetimeIndex. Then you can use the indexing approach you wanted. df.set_index(pd.DatetimeIndex(df.date), inplace=True) df.sort_index().loc['2017-10':'2017-11'] cost date item date 2017-10-01 9 2017-10-01 Chipotle 2017-11-01 5 2017-11-01 Pasta With respect to your second question, you can also access the month property once you have a DatetimeIndex. df.loc[df.index.month.isin([10,12])] cost date item date 2017-12-01 10 2017-12-01 Subway 2017-10-01 9 2017-10-01 Chipotle (For the second part, to index by year as well, add &amp; df.index.year == 2017)
answers question: http://stackoverflow.com/q/47763590
type: Answer

http://stackoverflow.com/comment/82356818
type: AnswerComment
comment on: http://stackoverflow.com/a/47698374
has text: I've tried to save this file back as : outfilename = "img.jpg" output= open(outfilename,"wb") output.write(image) But it does not work. Can you help with this?
type: Comment
score: 0

http://stackoverflow.com/comment/82417894
type: Comment
score: 0
type: AnswerComment
has text: I've responded in the answer above
comment on: http://stackoverflow.com/a/47728700

http://stackoverflow.com/a/47783791
answers question: http://stackoverflow.com/q/47783711
has comment: http://stackoverflow.com/comment/82529235
type: Answer
has comment: http://stackoverflow.com/comment/82530510
has comment: http://stackoverflow.com/comment/82531981
has comment: http://stackoverflow.com/comment/82529192
upvote count: 2
score: 2
downvote count: 0
has body: You need to remove the dollar signs df['Avg Spending Hospital'] = df['Avg Spending Hospital'].str[1:].astype(int) df['Avg Spending State'] = df['Avg Spending Hospital'].str[1:].astype(int) df['Avg Spending Nation'] = df['Avg Spending Hospital'].str[1:].astype(int) and the percent signs (the indexes here are [:-1]): df['Percent Spending Hospital'] = df['Percent Spending Hospital'].str[:-1].astype(float) df['Percent Spending State'] = df['Percent Spending State'].str[:-1].astype(float)

http://stackoverflow.com/comment/82421953
comment on: http://stackoverflow.com/a/47730710
type: AnswerComment
has text: Now try looping over the same stack in two nested `for` loops. :)
score: 0
type: Comment

http://stackoverflow.com/q/47847724
has answer: http://stackoverflow.com/a/48886218
has answer: http://stackoverflow.com/a/47847859
has answer: http://stackoverflow.com/a/49223209
answer count: 4
tagged with: class
tagged with: attributes
has comment: http://stackoverflow.com/comment/82659597
type: AnsweredQuestion
has body: When I define a class, I often want to set a collection of attributes for that class upon object creation. Until now, I have done so by passing the attributes as arguments to the init method. However, I have been unhappy with the repetitive nature of such code: class Repository(OrderedDict,UserOwnedObject,Describable): def __init__(self,user,name,gitOriginURI=None,gitCommitHash=None,temporary=False,sourceDir=None): self.name = name self.gitOriginURI = gitOriginURI self.gitCommitHash = gitCommitHash self.temporary = temporary self.sourceDir = sourceDir ... In this example, I have to type name three times, gitOriginURI three times, gitCommitHash three times, temporary three times, and sourceDir three times. Just to set these attributes. This is extremely boring code to write. I've considered changing classes like this to be along the lines of: class Foo(): def __init__(self): self.a = None self.b = None self.c = None And initializing their objects like: f = Foo() f.a = whatever f.b = something_else f.c = cheese But from a documentation standpoint, this seems worse, because the user of the class then needs to know which attributes need to be set, rather than simply looking at the autogenerated help() string for the class's initializer. Are there any better ways to do this? One thing that I think might be an interesting solution, would be if there was a store_args_to_self() method which would store every argument passed to init as an attribute to self. Does such a method exist? One thing that makes me pessimistic about this quest for a better way, is that looking at the source code for the date object in cPython's source, for example, I see this same repetitive code: def __new__(cls, year, month=None, day=None): ... self._year = year self._month = month self._day = day https://github.com/python/cpython/blob/master/Lib/datetime.py#L705 And urwid, though slightly obfuscated by the use of setters, also has such "take an argument and set it as an attribute to self" hot-pota…
possible better answer: http://stackoverflow.com/a/47847851
downvote count: 0
has answer: http://stackoverflow.com/a/47847851
upvote count: 1
favorite count: 0
type: Question
score: 1
accepted answer: http://stackoverflow.com/a/47847859
tagged with: python
has title: What is the best way to set the attributes of a class at object creation time in Python?

http://stackoverflow.com/q/47782789
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/82528324
has comment: http://stackoverflow.com/comment/82528114
has title: Where is my log?
has body: I'm running a Flask project. I was trying to logging all logs from debug level to console. Here is my code: #!flask/bin/python import logging from app import app logging.basicConfig(level=logging.DEBUG, format = '%(asctime)s [%(process)d %(name)s] %(levelname)s %(message)s') logging.debug('test') log = logging.getLogger('werkzeug') log.setLevel(logging.DEBUG) log.debug('test') if __name__ == '__main__': print 'crazy' log.debug('test') app.run(host = '0.0.0.0', port = 8100, debug = True, processes = 8) Here is the result (one of the weird thing is there are two 'crazy' printed): (flask) [felixc@diamond flask]$ ./run.py crazy crazy I cannot find anything on console. There is even no 'test' displayed on the console. So where is my logs? My Python is v2.7.13 on CentOS 6.9. Update the logging with basicConfig: (flask) [felixc@diamond flask]$ ipython Python 2.7.13 (default, Jun 22 2017, 13:33:06) Type "copyright", "credits" or "license" for more information. IPython 5.5.0 -- An enhanced Interactive Python. ? -&gt; Introduction and overview of IPython's features. %quickref -&gt; Quick reference. help -&gt; Python's own help system. object? -&gt; Details about 'object', use 'object??' for extra details. In [1]: edit IPython will make a temporary file named: /tmp/ipython_edit_pUodOs/ipython_edit_WWATn8.py Editing... done. Executing edited code... Out[1]: "import logging\nlogging.basicConfig(level=logging.DEBUG, format = '%(asctime)s [%(process)d %(name)s] %(levelname)s %(message)s')\n" In [2]: logging.debug('test') 2017-12-12 14:51:06,042 [14863 root] DEBUG test
has comment: http://stackoverflow.com/comment/82527306
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82527029
answer count: 1
has comment: http://stackoverflow.com/comment/82527141
has comment: http://stackoverflow.com/comment/82527174
has comment: http://stackoverflow.com/comment/82526989
has comment: http://stackoverflow.com/comment/82527122
tagged with: python
has comment: http://stackoverflow.com/comment/82527096
has comment: http://stackoverflow.com/comment/82527418
has answer: http://stackoverflow.com/a/47785643
has comment: http://stackoverflow.com/comment/82527900
type: Question

machine-learning
tags question: http://stackoverflow.com/q/47710027
tags question: http://stackoverflow.com/q/47710566
type: Tag
tags question: http://stackoverflow.com/q/47759123
tags question: http://stackoverflow.com/q/47770361
tags question: http://stackoverflow.com/q/47709854
tags question: http://stackoverflow.com/q/47713596
tags question: http://stackoverflow.com/q/47715748
tags question: http://stackoverflow.com/q/47778403
tags question: http://stackoverflow.com/q/47788981
tags question: http://stackoverflow.com/q/47747532
tags question: http://stackoverflow.com/q/47787615
tags question: http://stackoverflow.com/q/47845448
tags question: http://stackoverflow.com/q/47725994
tags question: http://stackoverflow.com/q/47795309
tags question: http://stackoverflow.com/q/47825940
tags question: http://stackoverflow.com/q/47717818
tags question: http://stackoverflow.com/q/47838306
tags question: http://stackoverflow.com/q/47703196
tags question: http://stackoverflow.com/q/47697880
tags question: http://stackoverflow.com/q/47777318
tags question: http://stackoverflow.com/q/47733980
tags question: http://stackoverflow.com/q/47725046
tags question: http://stackoverflow.com/q/47796453
tags question: http://stackoverflow.com/q/47807463
tags question: http://stackoverflow.com/q/47697988
tags question: http://stackoverflow.com/q/47709629
tags question: http://stackoverflow.com/q/47793569
tags question: http://stackoverflow.com/q/47840228
tags question: http://stackoverflow.com/q/47758223
tags question: http://stackoverflow.com/q/47724077
tags question: http://stackoverflow.com/q/47826706
tags question: http://stackoverflow.com/q/47759384
tags question: http://stackoverflow.com/q/47738016
tags question: http://stackoverflow.com/q/47707793
tags question: http://stackoverflow.com/q/47712374
tags question: http://stackoverflow.com/q/47744964
tags question: http://stackoverflow.com/q/47699506
tags question: http://stackoverflow.com/q/47745027
tags question: http://stackoverflow.com/q/47750930
tags question: http://stackoverflow.com/q/47698121
tags question: http://stackoverflow.com/q/47852014
tags question: http://stackoverflow.com/q/47704467
tags question: http://stackoverflow.com/q/47708375
tags question: http://stackoverflow.com/q/47719001
tags question: http://stackoverflow.com/q/47786637
tags question: http://stackoverflow.com/q/47795918
tags question: http://stackoverflow.com/q/47842931
tags question: http://stackoverflow.com/q/47836295
tags question: http://stackoverflow.com/q/47835350
tags question: http://stackoverflow.com/q/47721792
tags question: http://stackoverflow.com/q/47767162
tags question: http://stackoverflow.com/q/47844093
tags question: http://stackoverflow.com/q/47764474
tags question: http://stackoverflow.com/q/47765595
tags question: http://stackoverflow.com/q/47781159
tags question: http://stackoverflow.com/q/47775771
tags question: http://stackoverflow.com/q/47735205
tag name: machine-learning
tags question: http://stackoverflow.com/q/47750291
tags question: http://stackoverflow.com/q/47769181
tags question: http://stackoverflow.com/q/47707990
tags question: http://stackoverflow.com/q/47767620
tags question: http://stackoverflow.com/q/47723547
tags question: http://stackoverflow.com/q/47793584
tags question: http://stackoverflow.com/q/47840056
tags question: http://stackoverflow.com/q/47803089
tags question: http://stackoverflow.com/q/47723873
tags question: http://stackoverflow.com/q/47819790
tags question: http://stackoverflow.com/q/47743202
tags question: http://stackoverflow.com/q/47823060

http://stackoverflow.com/comment/82433177
type: Comment
score: 0
has text: You're welcome! And please always try to narrow down your code in the future, so that only the problematic sections are left, but make sure that we can still run the program. That can save us lots of time and you could also find the bugs on your own in the process.
type: AnswerComment
comment on: http://stackoverflow.com/a/47736272

http://stackoverflow.com/comment/82528157
has text: @BryanOakley, good point. I just mindlessly copied that part of OP's code because it wasn't directly related to his question about changing label values.
comment on: http://stackoverflow.com/a/47781604
type: Comment
type: AnswerComment
score: 1

http://stackoverflow.com/a/47783341
type: Answer
answers question: http://stackoverflow.com/q/47783106
score: 2
upvote count: 2
has body: you can use PeriodIndex: In [36]: df['Date'] = pd.PeriodIndex(df['Date'].astype(str), freq='M').strftime('%m/%d/%Y') In [37]: df Out[37]: Id Name Date Number 0 1 A 01/31/2016 5 1 2 B 02/29/2016 6 2 3 C 03/31/2016 4
downvote count: 0

http://stackoverflow.com/q/47704291
possible better answer: http://stackoverflow.com/a/47704373
upvote count: 1
has answer: http://stackoverflow.com/a/47704373
tagged with: global-variables
downvote count: 1
favorite count: 0
type: Question
answer count: 2
tagged with: python
accepted answer: http://stackoverflow.com/a/47704341
has answer: http://stackoverflow.com/a/47704341
type: AnsweredQuestion
has body: In the main program I have import medallia_utils from collections import defaultdict Opers = defaultdict(int) Later on in this program, I will be calling a function in medallia_utils called word_checker. I want to manipulate the dictionary variable Opers in a function word_checker defined inside medallia_utils so I want to declare it as Global. When I do this inside of medallia_utils: def word_checker(name, comment): import re from collections import defaultdict global Opers The system says NameError: global name 'Opers' is not defined I also tried to define this variable globally in medallia_utils outside of the function word_checker by doing global Opers or global __Opers__ but nothing working so far. I get the same error. What is the syntax fix to get this to work?
has comment: http://stackoverflow.com/comment/82368910
score: 0
has title: How to declare a global variable in a module

http://stackoverflow.com/comment/82376407
type: QuestionComment
comment on: http://stackoverflow.com/q/47707526
has text: This is a rather poor example of how passwords actually work. I notice this is basically the game of Hangman so maybe just think of it as that instead.
score: 0
type: Comment

http://stackoverflow.com/a/47777715
has body: You can use append feature of a list e.g.:- &gt;&gt;&gt; t1 = tuple([1,2,3]) &gt;&gt;&gt; t2 = tuple([4,5,6]) &gt;&gt;&gt; l = list() &gt;&gt;&gt; l.append(t1) &gt;&gt;&gt; l.append(t2) &gt;&gt;&gt; l # [(1,2,3), (4,5,6)]
has comment: http://stackoverflow.com/comment/82516805
type: Answer
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/47777419

http://stackoverflow.com/comment/82560146
has text: The placeholders are still missing. Try `graph.get_tensor_by_name("X:0")` and `graph.get_tensor_by_name("prediction:2")`
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47796453

http://stackoverflow.com/tag/xml
tags question: http://stackoverflow.com/q/47799742
tags question: http://stackoverflow.com/q/47800256
tags question: http://stackoverflow.com/q/47845059
tags question: http://stackoverflow.com/q/47828262
tags question: http://stackoverflow.com/q/47733563
tags question: http://stackoverflow.com/q/47790068
tag name: xml
tags question: http://stackoverflow.com/q/47704190
type: Tag
tags question: http://stackoverflow.com/q/47828176
tags question: http://stackoverflow.com/q/47764666
tags question: http://stackoverflow.com/q/47741889
tags question: http://stackoverflow.com/q/47818177
tags question: http://stackoverflow.com/q/47724433
tags question: http://stackoverflow.com/q/47719240
tags question: http://stackoverflow.com/q/47831096
tags question: http://stackoverflow.com/q/47794678
tags question: http://stackoverflow.com/q/47719601
tags question: http://stackoverflow.com/q/47734132
tags question: http://stackoverflow.com/q/47848199

http://stackoverflow.com/comment/82396175
score: 1
comment on: http://stackoverflow.com/q/47717288
type: QuestionComment
has text: What image processing library are you using? What's `imcrop` and why don't you want to use it?
type: Comment

http://stackoverflow.com/a/47836043
type: Answer
has comment: http://stackoverflow.com/comment/82636623
score: -1
has comment: http://stackoverflow.com/comment/82635911
upvote count: 0
downvote count: 1
answers question: http://stackoverflow.com/q/47835573
has body: I believe you are looking for pandas.DataFrame.mean(). Example use: import pandas as pd data = ["Beijing","PM2.5","2017-01-01","2017","1",df["Value"].mean(), 'ug/m_', '1 Day', 'Valid'] averages = pd.DataFrame(data, columns=["Site", "Parameter", "Date", "Year", "Month", "Day", "Value", "Unit", "Duration", "QC Name"]) Keep in mind that I hardcoded the values, based on how you get your information there may be better ways of importing the headers, and values. But this should show how to use df.mean()

http://stackoverflow.com/comment/82648545
score: 0
type: Comment
type: QuestionComment
has text: Thank you Galen, I will check the link. I also edited my question again.
comment on: http://stackoverflow.com/q/47841981

http://stackoverflow.com/comment/82656948
comment on: http://stackoverflow.com/q/47846465
type: Comment
has text: have you tried User.objects.get(email=request.POST.get("email")) ?
type: QuestionComment
score: 0

http://stackoverflow.com/q/47731485
linked to: http://stackoverflow.com/q/4086435
has comment: http://stackoverflow.com/comment/82423942
has comment: http://stackoverflow.com/comment/82424259
tagged with: sockets
accepted answer: http://stackoverflow.com/a/47731763
tagged with: javascript
tagged with: python
has body: I've got a working HTTP node.js server. I then created a program on python that uses the socket module to connect to the above server Please for the time being do not mind the try and except statements. The code's connectTO() function simply connects to a server like any other code, with the exception that it handles some errors. Then the program send the message "hello". Next in the while loop it repeatedly waits for an answer and when it receives one, it prints it. When I connect to the Node.js http server from python, I do get the message: "You have just succesfully connected to the node.js server" Which if you look at my code means that the s.connect(()) command was successful. My problem is that when a request is send to the server, it's supposed to output a message back, but it doesn't. I also tried sending a message to the server, in which case the server sends back the following message: HTTP/1.1 400 Bad Request So why is the server not responding to the requests? Why is it rejecting them? Python Client: from socket import AF_INET, SOCK_STREAM, SOL_SOCKET, SO_REUSEADDR import threading, socket, time, sys s = socket.socket(AF_INET,SOCK_STREAM) def connectTO(host,port): connect = False count = 0 totalCount = 0 while connect!= True: try: s.connect((host,port)) connect = True print("You have just succesfully connected to the node.js server") except OSError: count += 1 totalCount += 1 if totalCount == 40 and count == 4: print("Error: 404. Connection failed repeatedly") sys.exit(0) elif count == 4: print("Connection failed, retrying...") count = 0 else: pass connectTO("IP_OF_NODE.jS_SERVER_GOES_HERE",777) message = "hello" s.send(message.encode("utf-8")) while True: try: data, addr = s.recvfrom(1024) if data == "": pass else: print(data.decode()) except ConnectionResetError: print("it seems like we can't reach the server anymore..") print("This could be due to a change in your internet connection or the server.") s.close() Node.js HTTP server: function onRequest(r…
linked to: http://stackoverflow.com/q/38858352
has answer: http://stackoverflow.com/a/47731763
linked to: http://stackoverflow.com/q/32264359
tagged with: node.js
linked to: http://stackoverflow.com/q/40035567
has comment: http://stackoverflow.com/comment/82424107
type: AnsweredQuestion
score: 2
has title: Why does Node.js HTTP server not respond to a request from Python?
upvote count: 2
linked to: http://stackoverflow.com/q/14140914
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/82424028
has comment: http://stackoverflow.com/comment/82424530
favorite count: 0
type: Question

http://stackoverflow.com/a/47851165
type: Answer
has comment: http://stackoverflow.com/comment/82666994
answers question: http://stackoverflow.com/q/47850868
has comment: http://stackoverflow.com/comment/82667049
type: AcceptedAnswer
downvote count: 0
upvote count: 1
score: 1
has body: Axis zero is the index. Axis one are the columns. That’s it. The interpretation of why the different axis choices behave the way they do is confusing. It is my belief that it is consistent though. For dropna it refers to the axis from which keys will be dropped. For any, sum, mean, and many more, it refers to the axis over which we will evaluate the reduction function. For apply it refers to the axis that is used in each of the series objects that get passed to the function being applied. For add, mul, etc. it refers to the axis that is used as a reference when adding a series to a dataframe. You can make arguments why you may have made different choices. But I think the developers made good choices. If something specific confuses you, ask a question.
accepted answer of: http://stackoverflow.com/q/47850868

http://stackoverflow.com/q/47854859
has comment: http://stackoverflow.com/comment/82679206
type: AnsweredQuestion
tagged with: django-views
has title: How to generate download link?
has comment: http://stackoverflow.com/comment/82674133
score: 1
accepted answer: http://stackoverflow.com/a/47857647
has comment: http://stackoverflow.com/comment/82713866
answer count: 1
upvote count: 1
has answer: http://stackoverflow.com/a/47857647
tagged with: file-upload
has body: I'm triying to create a link to download file which has been uploaded. models.py class Comentario (models.Model): archivo = models.FileField(upload_to='media', null=True, blank=True) settings.py MEDIA_ROOT=os.path.join(BASE_DIR, 'media') MEDIA_URL='/media/' template.html Descargar views.py def ComentarioListar(request): form2 = ComentarioForm(request.POST or None, request.FILES or None) if request.method == 'POST' and form2.is_valid(): form2.instance.autor = request.user form2.save() return HttpResponseRedirect('http://127.0.0.1:8000/home/listar') objects= Comentario.objects.filter(tag__in=bb).exclude(autor__id=request.user.id)[:5] return render(request, 'home/comentario_listar.html', {'objects': objects, 'form2':form2}) urls.py urlpatterns = [ url(r'^download/(?P<filename>.+)$', login_required(views.download), name='download')] When I click the download link it does not download the .jpg saved in 'media' folder. Is the path incorrectly specified? It is necessary to create a special view for that?
favorite count: 0
type: Question
tagged with: django-templates
downvote count: 0
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/82681173

http://stackoverflow.com/comment/82555805
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47797316
has text: are your strings actually like `'2 5 8 9 6 3'` or `'258963'`? Because that changes the game quite a lot..
type: Comment

http://stackoverflow.com/comment/82407789
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47723377
score: 0
has text: went and looked at the exercise, no they do not open twice. They also note that `truncate` is not necessary. (So why introduce a method that superfluous and rarely ever used??)

http://stackoverflow.com/q/47818993
possible better answer: http://stackoverflow.com/a/47819518
tagged with: project-structure
tagged with: python
has title: Project structure leads to redundant dot notation
has answer: http://stackoverflow.com/a/47819518
has comment: http://stackoverflow.com/comment/82600133
accepted answer: http://stackoverflow.com/a/47819839
upvote count: 4
tagged with: python-2.7
type: AnsweredQuestion
score: 3
answer count: 2
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/47819839
type: Question
has body: I have created a Python package which builds on the structure indicated in Kenneth Reitz' "Repository Structure and Python" (1). The main package path is: /projects-folder (not site-packages) /package /package __init__.py Datasets.py Draw.py Gmaps.py ShapeSVG.py project.py __init__.py setup.py With the current structure, I must use the following module import syntax: import package.package.Datasets I would prefer to type the following: import package.Datasets I am capable of typing the same word twice, of course, but it feels wrong in a deeper sense, i.e., I am structuring my package incorrectly or misunderstanding how Python interprets that structure. The outer __init__.py is required for Python to detect this package at all, per the docs (2). But that sets up /package/ as the top level of the package and /package/package/ as a sub-package, forcing me into the unwieldy import syntax above. To avoid this, it seems that my options are to: Create a package in which the outer folder contains the top level of package modules. Add the inner folder to my PYTHONPATH environment variable. Yet both of these seem like suboptimal workarounds for something that shouldn't be an issue in the first place. What should I do?

http://stackoverflow.com/q/47790068
tagged with: python
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/xml
has comment: http://stackoverflow.com/comment/82541215
has comment: http://stackoverflow.com/comment/82541825
score: 0
answer count: 0
tagged with: heroku
has title: Python parsing xml file correctly in heroku but not locally
has body: Im having a weird problem. I have a python projekt, which uses an XML File to store data. This file has special characters from the german language and gets parsed by ElementTree. When testing it locally, the special characters are not parsed correctly, but then testing it on heroku those characters are parsed correctly. What could be the problem here? This is how I read and parse the file: # Get the root of the XML File # @return the root and tree def get_root(): try: with open(filename, 'r') as xml_file: tree = ET.parse(xml_file) return tree.getroot(), tree except Exception: return None
type: Question

http://stackoverflow.com/a/47847365
type: AcceptedAnswer
has body: waitkey displays the image for the specified number of milliseconds. Without it, you actually wouldn't be able to see anything. Then 0xFF == ord('q') detects when the keystroke q is pressed on the keyboard. Think of waitkey as a pause function. After the code has been executed; at lightning speed :), waitkey says, pause for 1000 milliseconds to display the frame. Within this, detect if the user pressed q. If q is pressed, then get outside of my infinite while loop. When this happens, then the window won't be shown anymore. Their documentation is a good resource as well.
score: 2
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/47847238
accepted answer of: http://stackoverflow.com/q/47847238
upvote count: 2

http://stackoverflow.com/a/47720634
accepted answer of: http://stackoverflow.com/q/47720160
score: 0
answers question: http://stackoverflow.com/q/47720160
type: AcceptedAnswer
has body: As suggested by @wpercy you have figure out which user is executing the file. Usually that user is called www-data ! To find out which user is calling the service use ps aux | grep -E '[a]pache|[h]ttpd|[_]www|[w]ww-data|[n]ginx' | grep -v root | head -1 | cut -d\ -f1 After you figured out the user you have to change the permission for the folder. That command schould be something like chown -R www-data:www-data /var/www/html/Projectfolder Special thanks to wpercy!
type: Answer

http://stackoverflow.com/comment/107384518
has text: @ravimalhotra: not thread safe means that things can break because multiple threads are altering the same data structures unless you take threading into account. The asyncio event loop implementation is not thread safe apart from a few [explicitly documented functions](https://docs.python.org/3/library/asyncio-dev.html#asyncio-multithreading). The code here *doesn't* create a new event loop per thread, nor does it pass coroutines to the single thread correctly. Note that I also posted an answer to this question that addresses these issues better.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/50177664
score: 4

http://stackoverflow.com/comment/82658894
comment on: http://stackoverflow.com/q/47837081
score: 0
type: Comment
type: QuestionComment
has text: @Evan Alright I'll look that up. The database is PostgreSQL with django models. Does the db have am impact on how I would implement the functionality?

http://stackoverflow.com/q/47780483
has body: I have this script below that takes crypto data (price) and sends it to a small led sign, the problem is the script will run for a bit but then I get the key error: 'price' which stops the script, weird thing is 'price' works for awhile every time. I am using a cron job to run the script every minute for now but I feel like there is a simpler way of doing this. Is there a way to run/reset the script again if it I get an error? This is on a raspberry pi so there is no physical way for me to restart it without plugging it back into the TV, which I don't want obviously. Many thanks for the help! #!/usr/bin/python import time, json, requests from pyledsign.minisign import MiniSign def btc(): btcTick= requests.get('https://api.gdax.com/products/BTC- usd/ticker') # replace buy with spot_rate, sell etc return btcTick.json()['price'] # replace amount with currency etc def ltc(): ltcTick= requests.get('https://api.gdax.com/products/LTC- usd/ticker') # replace buy with spot_rate, sell etc return ltcTick.json()['price'] while True: btcUSD = float(btc()) ltcUSD = float(ltc()) print btcUSD print ltcUSD mysign = MiniSign(devicetype='sign') mysign.queuemsg(data='B: ' + '$' + str(btcUSD) + ' L: ' + '$' + str(ltcUSD) , effect="snow", speed=5) mysign.sendqueue(device='/dev/ttyUSB0', packetdelay=5.0); time.sleep(60)
answer count: 1
type: Question
accepted answer: http://stackoverflow.com/a/47780578
has answer: http://stackoverflow.com/a/47780578
tagged with: http://stackoverflow.com/tag/json
tagged with: python
type: AnsweredQuestion
has title: Key error after running python json for set amount of time
score: 0

http://stackoverflow.com/comment/82429416
has text: BTW: you assign all buttons to the same variable so you have access only to last button. You have to keep buttons on list. Or send it to `redClick` as parameter.
comment on: http://stackoverflow.com/q/47733961
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47731160
accepted answer: http://stackoverflow.com/a/47731223
tagged with: authentication
favorite count: 0
type: Question
has body: I am using Django authentication. Whenever a user logs in, I want to redirect him to /profile/user_id, being user_id a number. I can get the value of user_id by request.user.profile.id. In settings.py I have LOGIN_REDIRECT_URL = 'app_1:index' app_1/urls.py: url(r'^profile/$', views.index, name='index'), # ex: /profile/5/ url(r'^profile/(?P&lt;user_id&gt;[0-9]+)/$', views.profile, name='profile'), app_1/views.py (things I've also tried are commented): def index(request): userid = request.user.profile.id #return render(request, 'app_1/index.html', context) #return profile(request, request.user.profile.id) #return render(request, 'app_1/user_prof.html', {'user': request.user.profile.id}) #return redirect(profile, user_id= request.user.profile.id) return redirect('profile', user_id=userid) def profile(request, user_id): user = get_object_or_404(Profile, pk=user_id) return render(request, 'app_1/user_prof.html', {'user': user}) I must be missing something because this should be easy but I'm stuck on it. Thanks in advance. EDIT: The error I'm getting is Reverse for 'profile' not found. 'profile' is not a valid view function or pattern name.: http://dpaste.com/270YRJ9
upvote count: 2
downvote count: 0
answer count: 1
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/47731223
score: 2
has title: Django: redirect to view with parameters
type: AnsweredQuestion

http://stackoverflow.com/comment/82510129
score: 2
comment on: http://stackoverflow.com/q/47774601
has text: Spark has a builtin CSV reader and SparkSQL can interact with Hive (not magic, it's well documented) . Please show what you've tried
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82578622
comment on: http://stackoverflow.com/a/47806384
type: Comment
score: 0
type: AnswerComment
has text: Thank you for your reply. But value (except last) can have new line. In Example, 'AA' value should have new line and blah blah

automation
tags question: http://stackoverflow.com/q/47785882
tags question: http://stackoverflow.com/q/47732891
tag name: automation
tags question: http://stackoverflow.com/q/47749627
tags question: http://stackoverflow.com/q/47699811
tags question: http://stackoverflow.com/q/47763342
tags question: http://stackoverflow.com/q/47826029
tags question: http://stackoverflow.com/q/47837571
type: Tag
tags question: http://stackoverflow.com/q/47698691

http://stackoverflow.com/comment/82564753
comment on: http://stackoverflow.com/a/47796697
has text: Thank you, that helps a lot! i have another question similar to this one if u can help me. What if i want to sum all the values for the differents rows and then make the proportion of the first/second/third/etc values of row "n" over the sum of the row. It is possible?
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/82608032
comment on: http://stackoverflow.com/q/47822600
score: 0
has text: Are you sure you have python installed on your system? If so what where do you have it installed ?
type: QuestionComment
type: Comment

http://stackoverflow.com/q/47787204
has answer: http://stackoverflow.com/a/47787353
downvote count: 1
has answer: http://stackoverflow.com/a/47787360
tagged with: sorting
has body: So there are two tasks that are to be performed simultaneously on a dictionary. Sort the dictionary and extract the top 10 keys along with their values Ignore keys which have a certain value while reporting top 10 For e.g. my_dict = { 'abc': 10, 'def':20, 'ghi':100, 'jkl':30, 'mno':101} So, if I want top 3 while ignoring keys with value 100 and 101 is result_top3 = [ ('jkl',30), ('def',20), ('abc',10)] Right now I am using the following : my_result = dict(Counter(my_dict).most_common()[:3]) but it has two problems: I don't know how to add a filter in my expression to ignore certain values It returns a dictionary, in which the keys may be unsorted although they would be top 10 values. I was hoping if there was a way to do it in one go, or a more Pythonic and efficient way instead of doing it in 2 steps, like removing the keys I don't want and then sorting. EDIT : It is not necessary to sort the complete dictionary. I just need to extract the top 10 results along with their values.
favorite count: 0
has answer: http://stackoverflow.com/a/47787359
type: AnsweredQuestion
answer count: 5
score: 1
has comment: http://stackoverflow.com/comment/82535443
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/47787541
type: Question
upvote count: 2
possible better answer: http://stackoverflow.com/a/47787359
has answer: http://stackoverflow.com/a/47787308
accepted answer: http://stackoverflow.com/a/47787308
has title: Sort dictionary by value and ignore some values

http://stackoverflow.com/comment/82615343
type: AnswerComment
comment on: http://stackoverflow.com/a/47825757
has text: In my opinion: you should swap the order of `unstack()` and `['sales']` to `['sales'].unstack()`
type: Comment
score: 2

http://stackoverflow.com/comment/82713369
score: 0
has text: Added the error after working out how to print it to a log file.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47840619

http://stackoverflow.com/a/47724674
downvote count: 0
upvote count: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/47724574
has body: Try this: import requests from BeautifulSoup import BeautifulSoup url = 'https://coinmarketcap.com/currencies/bitcoin/' response = requests.get(url) html = response.content soup = BeautifulSoup(html) div = soup.find("div", {"class" : "col-xs-6 col-sm-8 col-md-4 text-left" }).find("span", {"class" : "text-large2"}) for i in div: print i This prints 16051.20 for me. Later Edit: and if you put the above code in a function and loop it it will constantly update. I get different values now.
answers question: http://stackoverflow.com/q/47724574
score: 1
type: AcceptedAnswer

http://stackoverflow.com/a/47746291
has comment: http://stackoverflow.com/comment/82478594
answers question: http://stackoverflow.com/q/47745989
downvote count: 0
has comment: http://stackoverflow.com/comment/82452771
upvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/82489220
score: 2
has body: The easiest solution is asyncio.ensure_future. async def main(): tasks = [] while running: message = await get_message() message = await process_message(message) coroutine = deal_with_message(message) task = asyncio.ensure_future(coroutine) # starts running coroutine tasks.append(task) await asyncio.wait(tasks) Keeping track of the tasks yourself is optional if all your tasks can be awaited at the end. async def main(): while running: message = await get_message() message = await process_message(message) coroutine = deal_with_message(message) asyncio.ensure_future(coroutine) tasks = asyncio.Task.all_tasks() await asyncio.wait(tasks)

http://stackoverflow.com/a/47777742
has comment: http://stackoverflow.com/comment/105603820
answers question: http://stackoverflow.com/q/47773713
type: Answer
upvote count: 2
score: 1
downvote count: 1
has body: The error doesn't match the code you've posted. The error implies that you are using mqtt.client() not mqtt.Client()

http://stackoverflow.com/q/47745288
tagged with: scikit-learn
score: 11
has title: how to featureUnion numerical and text features in python sklearn properly
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47750133
has comment: http://stackoverflow.com/comment/82451194
has answer: http://stackoverflow.com/a/47750133
tagged with: python
favorite count: 0
upvote count: 11
type: Question
answer count: 2
has body: I'm trying to use featureunion for the 1st time in sklearn pipeline to combine numerical (2 columns) and text features (1 column) for multi-class classification. from sklearn.preprocessing import FunctionTransformer from sklearn.pipeline import Pipeline from sklearn.multiclass import OneVsRestClassifier from sklearn.linear_model import LogisticRegression from sklearn.pipeline import FeatureUnion get_text_data = FunctionTransformer(lambda x: x['text'], validate=False) get_numeric_data = FunctionTransformer(lambda x: x'num1','num2', validate=False) process_and_join_features = FeatureUnion( [ ('numeric_features', Pipeline([ ('selector', get_numeric_data), ('clf', OneVsRestClassifier(LogisticRegression())) ])), ('text_features', Pipeline([ ('selector', get_text_data), ('vec', CountVectorizer()), ('clf', OneVsRestClassifier(LogisticRegression())) ])) ] ) In this code 'text' is the text columns and 'num1','num2' are 2 numeric column. The error message is TypeError: All estimators should implement fit and transform. 'Pipeline(memory=None, steps=[('selector', FunctionTransformer(accept_sparse=False, func=&lt;function &lt;lambda&gt; at 0x7fefa8efd840&gt;, inv_kw_args=None, inverse_func=None, kw_args=None, pass_y='deprecated', validate=False)), ('clf', OneVsRestClassifier(estimator=LogisticRegression(C=1.0, class_weigh...=None, solver='liblinear', tol=0.0001, verbose=0, warm_start=False), n_jobs=1))])' (type &lt;class 'sklearn.pipeline.Pipeline'&gt;) doesn't Any step I missed?
possible better answer: http://stackoverflow.com/a/47751122
has comment: http://stackoverflow.com/comment/82469110
has answer: http://stackoverflow.com/a/47751122
downvote count: 0

http://stackoverflow.com/comment/82731584
comment on: http://stackoverflow.com/a/47836852
score: 0
type: Comment
has text: At the "unfair" test with removing all columns your solution is now ~27.5 times faster Than the one provided by Adam Brown. Doing the test with removing every second column your solution still is ~1.5 times faster. Thank you very much. Didn't want to challenge you :)
type: AnswerComment

http://stackoverflow.com/a/47717639
score: 4
has comment: http://stackoverflow.com/comment/82400065
answers question: http://stackoverflow.com/q/47716776
type: AcceptedAnswer
downvote count: 0
has body: I think pandas can't use StringVar as dtype. You would have to get every element in dataframe and create separated var = StringVar(value=df[row,col]) (or var = StringVar() ; var.set(df[row,col]))) and keep them in standard list. But you could put values directly to Entry, and bind() event to Entry which will execute function everytime something change in Entry or you press Enter. This function could copy value from Entry to dataframe. EDIT: example code It changes value in dataframe when you click Enter (or Enter on keypad) in any Entry. import pandas as pd import tkinter as tk df = pd.DataFrame([[1,2,3], [5,6,7], [101,102,103]]) # --- functions --- def change(event, row, col): # get value from Entry value = event.widget.get() # set value in dataframe df.iloc[row,col] = value print(df) # --- main -- root = tk.Tk() # create entry for every element in dataframe rows, cols = df.shape for r in range(rows): for c in range(cols): e = tk.Entry(root) e.insert(0, df.iloc[r,c]) e.grid(row=r, column=c) # ENTER e.bind('&lt;Return&gt;', lambda event, y=r, x=c: change(event,y,x)) # ENTER on keypad e.bind('&lt;KP_Enter&gt;', lambda event, y=r, x=c: change(event,y,x)) # start program root.mainloop() To change value in dataframe with every key press use &lt;KeyRelease&gt; (it works when you press Ctrl+V too, so you can paste data from clipboard) for r in range(rows): for c in range(cols): e = tk.Entry(root) e.insert(0, df.iloc[r,c]) e.grid(row=r, column=c) e.bind('&lt;KeyRelease&gt;', lambda event, y=r, x=c: changed(event, y,x)) EDIT: example as class DataFrameEdit(tk.Frame)
upvote count: 4
type: Answer
accepted answer of: http://stackoverflow.com/q/47716776

http://stackoverflow.com/comment/82415231
has text: Can you turn on debug, or otherwise post the Exception?
comment on: http://stackoverflow.com/q/47727306
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47803977
type: UnansweredQuestion
tagged with: python
tagged with: date
tagged with: rows
has body: UPDATE: Error --> "cannot handle a non-unique multi-index!" After running the code below, I get the following output dataframe in Python: df = df_EVENT5_18'FLEET', 'SUBFLEET', 'AIRCRAFT', 'DTIN' df = df.sort_values(['FLEET', 'SUBFLEET', 'AIRCRAFT', 'DTIN']) df.set_index(['FLEET', 'SUBFLEET', 'AIRCRAFT'], inplace=True) # df = df.reset_index() df['DTIN'] = pd.to_datetime(df['DTIN']) But it errors out at the very last line of code: df_EVENT5_19 = df.assign(output = df.groupby(['FLEET', 'SUBFLEET', 'AIRCRAFT']).DTIN.apply(lambda x: x.diff())) This is the error: "cannot handle a non-unique multi-index!" Below is a sample table that I am working with: The columns UI_A, UI_B, and UI_C taken together form a unique identifier. I want to calculate for each row and for each unique identifier the number of days it has been since the last date. Essentially, if your unique identifier is the same then you need to reference the date one row above you. This logic is a little difficult to explain in words so I'm including my desired output table below. I want to create the column "Days Since Previous Date"
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/47804290
tagged with: loops
type: Question
has title: Python Dataframe: Calculate Number of Days Since Last Date In Previous Row and Place in New Column

apache-spark-sql
tags question: http://stackoverflow.com/q/47793412
tags question: http://stackoverflow.com/q/47764902
tag name: apache-spark-sql
tags question: http://stackoverflow.com/q/47847285
tags question: http://stackoverflow.com/q/47722936
tags question: http://stackoverflow.com/q/47765716
tags question: http://stackoverflow.com/q/47784223
tags question: http://stackoverflow.com/q/47807845
type: Tag
tags question: http://stackoverflow.com/q/47751542
tags question: http://stackoverflow.com/q/47801317

http://stackoverflow.com/comment/82460961
type: Comment
has text: # Functions defined \n \n def test_A(param):\n print(param)\n \n def test_B(param):\n print(param + ' again')\n \n def test_C(param):\n print('and ' + param + ' again')\n \n \n # Dictionary defined\n \n d = dict({\n 'test_A': test_A,\n 'test_B': test_B,\n 'test_C': test_C\n })\n \n \n # Your code\n \n x = "test_A;test_B;test_C"\n \n sequence = x.split(';')\n \n print(sequence)\n \n for func_name in sequence:\n d[func_name]('hi')\n \n # Prints this\n # hi\n # hi again\n # and hi again\n
type: QuestionComment
comment on: http://stackoverflow.com/q/47749744
score: 0

adaboost
tag name: adaboost
tags question: http://stackoverflow.com/q/47702097
type: Tag

http://stackoverflow.com/comment/82641315
type: QuestionComment
has text: Does `cmd` have a newline and/or carriage return?
score: 0
comment on: http://stackoverflow.com/q/47838706
type: Comment

http://stackoverflow.com/a/47800158
upvote count: 11
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47800065
accepted answer of: http://stackoverflow.com/q/47800065
type: Answer
score: 11
has body: You can pass the raw connection object from a streaming GET request, as a file to a POST request: r = requests.get(get_url, stream=True) if r.status_code == 200: r.raw.decode_content = True # decompress as you read files = { 'fieldname': ('filename', r.raw, r.headers['Content-Type']) } requests.post(post_url, files=files) To use the response.raw file-like object will not, by default, decode compressed responses (with GZIP or deflate), but you can force it to decompress for you anyway by setting the decode_content attribute to True (requests sets it to False to control decoding itself). I assumed that the file was to be POSTed as part of a multipart/form-data request. If you need to post the data directly, use data=r.raw instead.

http://stackoverflow.com/comment/82584296
comment on: http://stackoverflow.com/a/47810622
has text: Can you post an actual excerpt of mcqs.txt?
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/101320603
comment on: http://stackoverflow.com/a/52772493
has text: @michael, I am just now seeing your question here - sorry. You'd need a combo of numpy and sklearn, but much more numpy. Let me know if that still doesn't help.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/82486515
comment on: http://stackoverflow.com/a/47762446
type: Comment
type: AnswerComment
has text: interesting. how?
score: 0

http://stackoverflow.com/comment/82584033
type: QuestionComment
has text: @furas and in Python2 as well only slightly less convenient with `super( MyClassName, self ).__init__()`
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47810514

http://stackoverflow.com/a/48197422
upvote count: 1
answers question: http://stackoverflow.com/q/47768206
type: Answer
score: 1
has body: This should do it. from collections import Counter file = open(r"C:/Users/rschuell/Desktop/test.txt", "r", encoding="utf-8-sig") wordcount = Counter(file.read().split()) for word in file.read().split(): if word not in wordcount: wordcount[word] = 1 else: wordcount[word] += 1 print (word,wordcount) file.close(); for item in wordcount.items(): print("{}\t{}".format(*item))
downvote count: 0

http://stackoverflow.com/a/47840117
score: 0
has body: Try ujson, it's quite a bit faster. "Decoding takes most of the time" can be seen as "building the Python objects takes all the time". Do you really need all these things as Python objects in RAM all the time? It must be quite a lot. I'd consider using a proper database for e.g. querying data of such size. If you need mass processing of a different kind, e.g. stats or matrix processing, I'd take a look at pandas.
type: Answer
answers question: http://stackoverflow.com/q/47839776

http://stackoverflow.com/comment/82735220
has text: Just curious, are you using Python 3.6, too? I've heard that PyCharm uses a different [debugging infrastructure for 3.6](https://blog.jetbrains.com/pycharm/2017/03/pycharm-2017-1/), maybe the test runner has been rewritten, too?
type: AnswerComment
comment on: http://stackoverflow.com/a/47883947
score: 1
type: Comment

http://stackoverflow.com/comment/82525304
comment on: http://stackoverflow.com/q/47780828
type: Comment
type: QuestionComment
has text: don't do `self.rect = self.image.get_rect()` in `move_position` because your remove car position. `image.get_rect()` always has position `(0,0)`
score: 0

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

http://stackoverflow.com/q/47819785
has comment: http://stackoverflow.com/comment/82602019
favorite count: 0
type: Question
tagged with: numpy
tagged with: ctypes
has body: I'm trying to use a very large numpy array using numpy memmap, accessing each element as a ctypes Structure. class My_Structure(Structure): _fields_ = [('field1', c_uint32, 3), ('field2', c_uint32, 2), ('field3', c_uint32, 2), ('field4', c_uint32, 9), ('field5', c_uint32, 12), ('field6', c_uint32, 2), ('field7', c_uint32, 2)] def __str__(self): return f'MyStruct -- f1{self.field1} f2{self.field2} f3{self.field3} f3{self.field4} f5{self.field5} f6{self.field6} f7{self.field7}' def __eq__(self, other): for field in self._fields_: if getattr(self, field[0]) != getattr(other, field[0]): return False return True _big_array = np.memmap(filename = 'big_file.data', dtype = 'uint32', mode = 'w+', shape = 1000000 ) big_array = _big_array.ctypes.data_as(ctypes.POINTER(My_Structure)) big_array[0].field1 = 5 ... And it seems to work correctly, but I'm getting an fault on a 64bit Windows machine where python.exe simply stops. In Event Viewer, I see that the faulting module name is _ctypes.pyd and the exception code is 0xc0000005 which I believe is an access exception. I don't seem to be getting the same error on Linux, though my testing has not been thorough. My questions are: Does my access look correct; ie. am I using numpy.memmap.ctypes.data_as correctly? Does the fact that I have functions (__str__ and __eq__) defined on My_Structure change its size? ie. can it still be used in the array as a uint32? Is there anything that you think might cause this behavior? Particularly considering the differences between Windows and Linux? EDIT: Using ctypes.addressof and ctypes.sizeof on big_array elements, it looks like the __str__ and __eq__ do not impact the size of My_Structure I added some asserts before my access to big_array and found that I was attempting to access big_array[-1], which explains the access error and crash. Which leaves question 1 open: It looks like my code is technically correct, but I'm wondering if there is a better way to access the numpy array than using a cty…
tagged with: python
score: 4
has comment: http://stackoverflow.com/comment/82602478
upvote count: 4
type: AnsweredQuestion
has title: Numpy Memmap Ctypes Access
accepted answer: http://stackoverflow.com/a/53370589
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/53370589
tagged with: numpy-memmap

http://stackoverflow.com/comment/82511608
type: QuestionComment
has text: `raw_input("Do you want to filter numbers greater or lower than {} ?".format(filt))`
score: 0
comment on: http://stackoverflow.com/q/47775312
type: Comment

http://stackoverflow.com/comment/84723619
comment on: http://stackoverflow.com/q/47780994
score: 0
has text: Which version of windows are you using? I have this working perfectly on Windows 7 but running the exact same code on Windows server 2008 causes this exact issue.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82567444
type: QuestionComment
score: 4
has text: why are you defining a function in a loop?
type: Comment
comment on: http://stackoverflow.com/q/47803005

http://stackoverflow.com/comment/82491184
type: Comment
has text: I would but... its about 728 lines currently and (like I said) its missing the collision and powerups components currently. You can still access it through the link I suppose. Let me update it real quick...
comment on: http://stackoverflow.com/a/47726711
type: AnswerComment
score: 0

http://stackoverflow.com/comment/82660982
type: Comment
type: AnswerComment
has text: Thanks this really helps
comment on: http://stackoverflow.com/a/47848289
score: 0

http://stackoverflow.com/comment/82386793
score: 1
type: Comment
type: AnswerComment
has text: adding a little more explanation would make a good answer. code-only answers are less useful.
comment on: http://stackoverflow.com/a/47712888

http://stackoverflow.com/q/47723011
has comment: http://stackoverflow.com/comment/82406717
has comment: http://stackoverflow.com/comment/82406874
answer count: 1
has comment: http://stackoverflow.com/comment/82406769
has title: Convert CSV import to a string
type: Question
tagged with: python-3.x
has body: I have a script: import csv with open('2017020397.csv', newline='') as f: reader = csv.reader(f) for row in reader: print(' '.join(row)) Output looks like this: LastName StartTime EndTime Duration Period TeamAbbrev Pos Bouwmeester 0:00 0:37 0:37 1 STL D Schwartz 0:00 0:40 0:40 1 STL W Foligno 0:00 0:40 0:40 1 MIN W Pietrangelo 0:00 0:48 0:48 1 STL D Suter 0:00 0:40 0:40 1 MIN D Instead of printing the rows, I would like the rows to equal data. Then I can just say print(data). New to python and writing scripts.
has comment: http://stackoverflow.com/comment/82406885
accepted answer: http://stackoverflow.com/a/47723420
has comment: http://stackoverflow.com/comment/82406707
has answer: http://stackoverflow.com/a/47723420
tagged with: python
linked to: http://stackoverflow.com/q/11349333
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/82407316
has comment: http://stackoverflow.com/comment/82406664
tagged with: http://stackoverflow.com/tag/csv

backspace
tags question: http://stackoverflow.com/q/47732236
tag name: backspace
type: Tag

http://stackoverflow.com/a/47739173
has comment: http://stackoverflow.com/comment/82439210
accepted answer of: http://stackoverflow.com/q/47738634
has comment: http://stackoverflow.com/comment/82439677
has comment: http://stackoverflow.com/comment/82438845
score: 1
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82438791
upvote count: 1
has comment: http://stackoverflow.com/comment/82439069
has comment: http://stackoverflow.com/comment/82438724
has comment: http://stackoverflow.com/comment/82439408
has comment: http://stackoverflow.com/comment/82438762
has comment: http://stackoverflow.com/comment/82439511
has comment: http://stackoverflow.com/comment/82438997
type: Answer
has comment: http://stackoverflow.com/comment/82438874
has comment: http://stackoverflow.com/comment/82438659
answers question: http://stackoverflow.com/q/47738634
has comment: http://stackoverflow.com/comment/82439446
has body: Finally I got it to work. But before I provide the answer, I would like to thank @p-a-o-l-o and @LoïcG.. the latter helping me out all the way. Thanks! The code worked when I changed it to the following: class MainForm(QMainWindow): def __init__(self, parent=None): super(MainForm, self).__init__(parent) self.ui = Ui_MainForm() self.ui.setupUi(self) self.ui.actionMenu1.triggered.connect(self.open_my_dialog) def open_my_dialog(self): my_dialog = MyDialog() # my_dialog.show() &lt;-- seems this line is not necessary either my_dialog.exec_() # this alone was enough for the code to work class MyDialog(QDialog): def __init__(self, parent=None): super(MyDialog, self).__init__(parent) self.ui = Ui_MyDialog() self.ui.setupUi(self) self.ui.pushButton_cancel.clicked.connect(self.cancel_dialog) def cancel_dialog(self): print("Closing Dialog Window...") self.close() # not important but corrected this also. I hope this helps! Edit: I corrected some lines and made the answer more simple thanks to @LoïcG. !

http://stackoverflow.com/comment/82974746
score: 0
has text: I reproduced the error: "argument to reversed() must be a sequence".
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47795909

http://stackoverflow.com/a/47816827
has body: You need a space after the table alias, e.g: query = ("SELECT ti.itemno, ti.active FROM text_item AS ti " "INNER JOIN text_itemmember AS tim ON tim.itemno = ti.itemno") cursor.execute(query) Python combines adjacent string literals into one, so you actually have 'tiINNER' as the alias name.
answers question: http://stackoverflow.com/q/47816703
type: Answer
has comment: http://stackoverflow.com/comment/82595303
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47816703
score: 0

http://stackoverflow.com/comment/82392981
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47716130
has text: why the "#form-change'' id is not a valid id? It entered inside the if(quantity && rate) block but did not update the basic_amount value. quantity field is integer field, rate field and basic_amount is decimalfield
type: Comment

http://stackoverflow.com/q/47821717
has comment: http://stackoverflow.com/comment/82607898
score: 0
tagged with: random
has title: Python Tkinter - Dictionary with Buttons - how do you disable them?
has body: I created a 7x7 field of buttons with a dictionary. Problem 1: I need to disable a User-Input amount of buttons randomly. The user writes a number x and x buttons will be blocked, but my program has to choose them randomly... Problem 2: The Rest of the buttons are usable. But if you click one, they will change the color and get state = tk.DISABLED. How do I do all that with a dictionary full of buttons? buttons = {} for x in range(0, 7): for y in range(0, 7): buttons[tk.Button(frame_2, height=5, width=10, bg="yellow",command=self.claim_field)] = (x, y) for b in buttons: x, y = buttons[b] b.grid(row=x, column=y) def claim_field(): #changing Color of button and blocking the same button Thank you for your answers, sorry for my bad english :)
answer count: 1
tagged with: button
type: Question
has comment: http://stackoverflow.com/comment/82609705
tagged with: tkinter
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47823624
has comment: http://stackoverflow.com/comment/82609671
has comment: http://stackoverflow.com/comment/82609807
tagged with: python
tagged with: dictionary

http://stackoverflow.com/q/47752659
has title: Map numeric matplotlib axes into "string" variables in surface plot
tagged with: surface
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/47753151
answer count: 1
has body: my issues is this: I have a table from which I want to obtain a 3d surface plot such as the one shown below in the code but the ticks on the x and y units need some "remapping", that is [0, 1, ...] must become ["apple", "orange", etc]. This is very important for me for visualization purposes (I can't switch to a categorical kind of chart because I would lose the "surface" feature). In the code below, the table is a pandas Dataframe that is the "SQL like" representation of a 2D array plus the output values (as shown in almost all the matplolib case studies). #################################################### position time_digitized value 0 0 0 0.636 1 0 3 0.323 2 0 1 0.783 3 0 2 0.494 4 0 4 0.452 5 0 7 0.212 6 0 5 0.465 7 0 6 0.334 8 0 8 0.182 9 0 11 0.256 10 0 9 0.244 #################################################### from mpl_toolkits.mplot3d.axes3d import Axes3D import matplotlib.pyplot as plt from matplotlib import cm fig = plt.figure() ax = Axes3D(fig) surf = ax.plot_trisurf( table.loc[:, 'position'], table.loc[:, 'time_digitized'], table.loc[:, 'value'], cmap=cm.ocean, linewidth=0.1) fig.colorbar(surf, shrink=0.5, aspect=5) plt.show()
tagged with: plot
type: Question
accepted answer: http://stackoverflow.com/a/47753151
tagged with: matplotlib
tagged with: python

http://stackoverflow.com/comment/82537000
score: 0
has text: I don't get an error with select_item. It's just selection_index
comment on: http://stackoverflow.com/q/47787764
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82534421
score: 0
type: QuestionComment
has text: @GarbageCollector I have added the info in the question.
comment on: http://stackoverflow.com/q/47786463
type: Comment

http://stackoverflow.com/a/47832800
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/47829588
has body: First you will merge both csv file in pandas dataframe. Then drop duplicate data from dataframe. import pandas as pd df1=pd.read_csv('first.csv') df2=pd.read_csv('second.csv') frames = [df1, df2] result=pd.concat(frames) df5 = pd.DataFrame(result) df5.drop_duplicates() print(df5)
accepted answer of: http://stackoverflow.com/q/47829588

http://stackoverflow.com/a/47834761
score: -2
has body: You just have to install python. You can do that using Homebrew. In a terminal run: sudo brew install python
type: Answer
upvote count: 0
downvote count: 2
has comment: http://stackoverflow.com/comment/82638332
answers question: http://stackoverflow.com/q/47834643

http://stackoverflow.com/comment/82420302
comment on: http://stackoverflow.com/q/47727236
type: QuestionComment
has text: You don't explain what the actions are in "retrieving data from database & processing the data" - it sounds like you should look if what you're trying to do here would be better moved into your DB extract or the immediately following stage... For instance, you might be able to get the DB to output the key and value, ordered by the key, you could then group by accordingly DB side or if needed during processing side using `itertools.groupby` depending on what you want... (or heck, maybe even just shove it into a key/value store depending what it's needed for)
score: 0
type: Comment

http://stackoverflow.com/comment/82457373
comment on: http://stackoverflow.com/q/47748556
score: 1
type: QuestionComment
has text: create a diagrammatic stack to understand. After you get the first "It got here", the flow will proceed with value of `n = 2` into the last call of `empty(n-1)` and when that finishes, the flow will proceed with `n=3`
type: Comment

http://stackoverflow.com/q/47733520
linked to: http://stackoverflow.com/q/41870228
upvote count: 3
possible better answer: http://stackoverflow.com/a/47734746
downvote count: 0
has answer: http://stackoverflow.com/a/47734746
favorite count: 0
type: Question
tagged with: numpy
has title: Compute weighted sum of 3D and 2D NumPy arrays
has body: Let's say I have a 2D NumPy array A of shape (n, 3) and a 3D array B of shape (x, y, n). I want to create a 3D array Y of shape (x, y, 3) - which is an RGB image. The 3rd dimension of B contains probabilities [0, 1] which sum up to 1. Array A is a list of RGB colors (one color for each probability). For each element C in the 3rd dimension of B I want to compute the sum of A * C so that I get a RGB color vector. Example: Given a colormap A as A = [(255 0 0), ( 0 255 0), ( 0 0 255)] and an element C in the 3rd dimension of B at point (x, y) as C = [0.2, 0.6, 0.20] I want to compute C' = sum(A * C) as (255 0 0) * 0.2 + ( 0 255 0) * 0.6 + ( 0 0 255) * 0.2 --------------------- ( 51 153 51) and assign Y[x, y, :] = C' I know I could just iterate over x and y with a for loop and compute each element at a time but I wonder if this can be done in a vectorized manner that I don't have to iterate over the array myself (mainly for performance reasons).
tagged with: python
accepted answer: http://stackoverflow.com/a/47737721
has answer: http://stackoverflow.com/a/47737721
type: AnsweredQuestion
score: 3
answer count: 2

http://stackoverflow.com/comment/82649452
has text: There are other folders but the conda.exe should be inside the scripts folder according to some how to's in installing Anaconda.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47842607
type: QuestionComment

http://stackoverflow.com/a/47782748
has comment: http://stackoverflow.com/comment/82529593
answers question: http://stackoverflow.com/q/47782580
has comment: http://stackoverflow.com/comment/82527102
has comment: http://stackoverflow.com/comment/82527163
has comment: http://stackoverflow.com/comment/82526875
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82526837
upvote count: 1
has comment: http://stackoverflow.com/comment/82529950
accepted answer of: http://stackoverflow.com/q/47782580
score: 1
has comment: http://stackoverflow.com/comment/82530004
has comment: http://stackoverflow.com/comment/82527430
type: Answer
has body: The tricky part seems to be differentiating decimal points and thousands separators, as some of the numbers seem to use a . for both. But it seems like numbers have either zero, or two decimal places, so we can use this strip away the decimal part (which is not needed for int anyway). &gt;&gt;&gt; nums = ["100000","100,000","100.000","100 000","100000.00","100,000.00","100.000.00","100 000.00"] &gt;&gt;&gt; [re.sub(r"[.,]\d{2}$", "", n) for n in nums] ['100000', '100,000', '100.000', '100 000', '100000', '100,000', '100.000', '100 000'] Afterwards, just remove any non-digit-characters and convert to int. &gt;&gt;&gt; [int(re.sub(r"[ ,.]", "", n)) for n in _] [100000, 100000, 100000, 100000, 100000, 100000, 100000, 100000] Just wrap those to re.sub operations into a function, together with the if check for N/A. If you know the locale of those numbers, you could also try the locale or babel modules: &gt;&gt;&gt; import babel.numbers &gt;&gt;&gt; babel.numbers.parse_decimal("100,000.000", "en") Decimal('100000.000') &gt;&gt;&gt; babel.numbers.parse_decimal("100,000.000", "de") Decimal('100.000000') Those return Decimal numbers, which can easily be converted to int. If you don't know the locale, and can't guarantee a fixed/maximum number of decimal places, I don't see how you could ever decide whether e.g. 100.000 is supposed to be 100 or 100000.

http://stackoverflow.com/q/47792991
linked to: http://stackoverflow.com/q/40388503
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82547055
has comment: http://stackoverflow.com/comment/82546979
has answer: http://stackoverflow.com/a/47840162
tagged with: selenium-webdriver
has body: File "helloselenium.py", line 2, in &lt;module&gt; driver = webdriver.Firefox(executable_path=r'\usr\local\bin\geckodriver') File "/Library/Python/2.7/site-packages/selenium/webdriver/firefox/webdriver.py", line 144, in __init__ self.service.start() File "/Library/Python/2.7/site-packages/selenium/webdriver/common/service.py", line 81, in start os.path.basename(self.path), self.start_error_message) selenium.common.exceptions.WebDriverException: Message: '\usr\local\bin\geckodriver' executable needs to be in PATH.
linked to: http://stackoverflow.com/q/47412303
score: 0
answer count: 3
has title: Selenium using python in mac getting error
has answer: http://stackoverflow.com/a/47793199
has comment: http://stackoverflow.com/comment/82547005
type: Question
has answer: http://stackoverflow.com/a/47793115

http://stackoverflow.com/comment/82525291
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47763720
type: Comment
has text: do you mind explaining a bit? Is it specific to python language or the package or more generally any OOP/functional language? When can I assume similar operations to happen in place and when can I not? Thanks a lot!

http://stackoverflow.com/q/47796445
tagged with: google-cloud-pubsub
has body: As I work on pubsub and Google App Engine, I'm running into some issues with psutil when I try to import pubsub_v1. Pubsub is doing nice work when I run it separately but when I use dev_appserver for app engine, I got this traceback : Traceback (most recent call last): File "/Users/soussa77/google-cloud-sdk/platform/google_appengine/google/appengine/runtime/wsgi.py", line 240, in Handle handler = _config_handle.add_wsgi_middleware(self._LoadHandler()) File "/Users/soussa77/google-cloud-sdk/platform/google_appengine/google/appengine/runtime/wsgi.py", line 299, in _LoadHandler handler, path, err = LoadObject(self._handler) File "/Users/soussa77/google-cloud-sdk/platform/google_appengine/google/appengine/runtime/wsgi.py", line 96, in LoadObject __import__(cumulative_path) File "/Users/soussa77/PycharmProjects/my-project/apps/app1/src/main.py", line 4, in &lt;module&gt; from src.apis.app1 import App1Api File "/Users/soussa77/PycharmProjects/my-project/apps/app1/src/apis/app1.py", line 11, in &lt;module&gt; from google.cloud import pubsub_v1 File "/Users/soussa77/PycharmProjects/my-project/apps/app1/lib/google/cloud/pubsub_v1/__init__.py", line 17, in &lt;module&gt; from google.cloud.pubsub_v1 import types File "/Users/soussa77/PycharmProjects/my-project/app/waterp/lib/google/cloud/pubsub_v1/types.py", line 17, in &lt;module&gt; import psutil File "/Users/soussa77/PycharmProjects/my-project/apps/app1/lib/psutil/__init__.py", line 156, in &lt;module&gt; from . import _psosx as _psplatform File "/Users/soussa77/PycharmProjects/my-project/apps/app1/lib/psutil/_psosx.py", line 16, in &lt;module&gt; from . import _psutil_osx as cext File "/Users/soussa77/google-cloud-sdk/platform/google_appengine/google/appengine/tools/devappserver2/python/runtime/sandbox.py", line 1091, in load_module raise ImportError('No module named %s' % fullname) **ImportError: No module named psutil._psutil_osx** It looks like it fails at psutil when pubsub try to monitor cpu activity.
has title: can't import pubsub for python SDK appengine / psutil
type: Question
has answer: http://stackoverflow.com/a/49019848
type: UnansweredQuestion
tagged with: google-app-engine
tagged with: python
tagged with: python-2.7
score: 0
answer count: 1

http://stackoverflow.com/q/47792530
tagged with: hazelcast
upvote count: 1
has answer: http://stackoverflow.com/a/47854406
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47792756
has comment: http://stackoverflow.com/comment/82546145
has answer: http://stackoverflow.com/a/47794925
type: UnansweredQuestion
tagged with: java
tagged with: python
downvote count: 5
score: -4
has title: Sharing collections between Python and Java using Hazelcast
answer count: 4
has answer: http://stackoverflow.com/a/47921021
has comment: http://stackoverflow.com/comment/82546359
has body: I have two programs, one in Java other in Python. On Java I need to store in a Hazelcast IMap a HashMap, and get it on Python as a dictionary, is it possible?

http://stackoverflow.com/q/47783391
tagged with: python
has body: I have successfully (I hope) trained and evaluated a model using the tf.Estimator where I reach a train/eval accuracy of around 83-85%. So now, I would like to test my model on a separate dataset using the predict() function call in the Estimator class. Preferably I would like to do this in a separate script. I've at this which says that I need to export as a SavedModel, but is this really necessary? Looking at the documentation for the Estimator class, it seems like I can just pass the path to my checkpoint and graph files via the model_dir parameter. Has anyone any experience with this? When I run my model on the same dataset I used for validation, I do not obtain the same performance as during the validation phase... :-(
type: Question
tagged with: tensorflow-estimator
has title: Tensorflow Estimator: using predict() function in separate script
linked to: http://stackoverflow.com/q/46098863
tagged with: deep-learning
score: 0
tagged with: validation
answer count: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/82545676
downvote count: 1
tagged with: tensorflow
favorite count: 0
accepted answer: http://stackoverflow.com/a/47796559
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47796559

http://stackoverflow.com/q/47835403
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82634939
has body: Let's say I have below hierarchy (pretty much simplified) class Ancestor: def __init__(self, *args, **kwargs): super(Ancestor, self).__init__(*args, **kwargs) self.a = 1 I don't want its Child to have access to a attribute class Child(Ancestor): def __init__(self, *args, **kwargs): super(Ancestor, self).__init__(*args, **kwargs) self.b = 2 But I want its Descendant to have access both to a and b class Descendant(Child): def __init__(self, *args, **kwargs): super(Descendant, self).__init__(*args, **kwargs) Is there any way to get desired behavior and avoid multiple inheritance, e.g. class Descendant(Ancestor, Child)?
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/82634274
tagged with: inheritance
upvote count: 0
tagged with: oop
has title: How to get access to ancestors' attribute skipped for parent
type: UnansweredQuestion
answer count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/47835554

http://stackoverflow.com/comment/82465783
score: 1
type: Comment
comment on: http://stackoverflow.com/q/47752711
type: QuestionComment
has text: Why not `fillna`? `df.fillna(0).add(ts.fillna(0), axis=0)`

http://stackoverflow.com/q/47805772
has answer: http://stackoverflow.com/a/47810361
has comment: http://stackoverflow.com/comment/107083044
score: 1
has comment: http://stackoverflow.com/comment/107087998
tagged with: python
has comment: http://stackoverflow.com/comment/82613748
linked to: http://stackoverflow.com/q/27043670
favorite count: 0
type: Question
answer count: 2
tagged with: robotframework
type: UnansweredQuestion
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/82589539
has comment: http://stackoverflow.com/comment/107082836
has answer: http://stackoverflow.com/a/60531043
has body: I have some robot keywords written in FlowKeywords.txt and it is been used in my Robot Test cases. Can I call these keywords from a Python script? I have checked this link but it includes importing the Python file in the robot test case and then call it from robot side. I need to use these keywords in the Python script. This is test.robot file *** Settings *** *** Test Cases *** Test Example keyword *** Keywords *** Example keyword log hello, world Below is Python file runkw.py: from robot.libraries.BuiltIn import BuiltIn def call_keyword(keyword): return BuiltIn().run_keyword(keyword) How can I call KW 'Example keyword' from the Python file itself?
has comment: http://stackoverflow.com/comment/82575353
has comment: http://stackoverflow.com/comment/107083833
has title: Call Robot Keyword from Python script

http://stackoverflow.com/comment/82423411
has text: I just want to be able to get arithmetic operations on multiple columns using agg.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47730071
type: QuestionComment

http://stackoverflow.com/comment/82449460
score: 1
has text: `print` in question with tag `PyGame` ???
comment on: http://stackoverflow.com/a/47744672
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47763534
has body: I am a bit confused about the differences/similarities between the query_pairs and query_ball_tree methods of Scipy's cKDTree. Reading the docs we can see that they have the same description: query_ball_tree(self, other, r[, p, eps]) - Find all pairs of points whose distance is at most r query_pairs(self, r[, p, eps]) - Find all pairs of points whose distance is at most r. They even require the same obligatory parameters, except for query_ball_tree that asks for other which is (from docs): "The tree containing points to search against.". So, is there a practical difference between these two methods? Is it preferred to use one over the other? I currently use query_pairs for my purposes, but I am considering alternatives to it. I have seen people use the former something like tree1.query_ball_tree(tree2, ...), which suggests that you can query between different trees... but I guess that it would be equivalent to query_pairs if we did something like tree1.query_ball_tree(tree1, ...). Any guidance is greatly appreciated.
has comment: http://stackoverflow.com/comment/82490279
upvote count: 2
accepted answer: http://stackoverflow.com/a/62407029
has title: Scipy cKDTree query_pairs versus query_ball_tree
tagged with: python
has answer: http://stackoverflow.com/a/62407029
has comment: http://stackoverflow.com/comment/82490226
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82488988
answer count: 1
downvote count: 0
tagged with: scipy
tagged with: kdtree
favorite count: 0
has comment: http://stackoverflow.com/comment/82490358
type: Question
has comment: http://stackoverflow.com/comment/82490356

http://stackoverflow.com/a/47824008
has body: If you're trying to serve the file locally through some web api route then you'll have to provide more information about your app and what constructions you have laid out. When I try the following off the link you provided and copying the link for their export options for the csv format I get the data downloaded (eventually after several minutes), albeit with a warning... &gt;&gt;&gt; df = pandas.read_csv( 'https://data.cityofnewyork.us/api/views/xx67-kt59/rows.csv' ) sys:1: DtypeWarning: Columns (6) have mixed types. Specify dtype option on import or set low_memory=False. &gt;&gt;&gt; df CAMIS DBA BORO BUILDING \ 0 41471806 THE HEN HOUSE BROOKLYN 7302 1 50060020 CURRY EXPRESS NY MANHATTAN 130 2 50060627 RED HOUSE ASIAN FUSION QUEENS 19203 3 50040866 FUEL GRILL MANHATTAN 112 4 41710571 BLACKTHORN 51 QUEENS 8012 5 50015486 THE IZAKAYA MANHATTAN 326 6 50015250 PETITE BLUE DOG CAFE MANHATTAN 119 7 40388091 MASAWA MANHATTAN 1239 8 41456998 A.I.G.CHARTIS MANHATTAN 175 9 50006741 GRACE CAFE MANHATTAN 572 10 41377069 CATALDO'S RESTAURANT BROOKLYN 554 11 41145911 WA LUNG KITCHEN MANHATTAN 557 12 41547536 MINT'S THAI KITCHEN QUEENS 7015 13 41066771 DUNKIN' DONUTS BROOKLYN 5702 14 40365472 SPAIN RESTAURANT &amp; BAR MANHATTAN 113 15 50072117 NaN MANHATTAN 307 16 50042671 EDGAR'S CAFE MANHATTAN 650 17 41490991 LIPS RESTAURANT MANHATTAN 227 18 41713624 BIENVENIDOS AL CALLAO RESTAURANT QUEENS 11122 19 40923012 DOMINO'S MANHATTAN 200 20 41477406 CIBAO RESTAURANT QUEENS 10422 21 50013522 BREWKLYN GRIND COFFEE BROOKLYN 557 22 41212364 BECKETT'S MANHATTAN 81 23 50066646 TOKOYO EXPRESS QUEENS 7057 24 41575815 BLACKOUT LOUNGE QUEENS 13316 ...
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47823180
has comment: http://stackoverflow.com/comment/82611096
has comment: http://stackoverflow.com/comment/82610712
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/47823180
has comment: http://stackoverflow.com/comment/82610753
upvote count: 2

http://stackoverflow.com/q/47727896
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47727911
has title: If I can use SQLite 3 to organize data in python, why should I use classes?
has comment: http://stackoverflow.com/comment/82416472
tagged with: python
has body: I am going to create a project for my university called Criminal Record System in which I will manage criminal's data and history. Now I stumbled upon the term class. Going through some videos and articles I realized that it is used to save data. So I am confused that if we can use sqlite 3 then why are using classes to organize data.
type: AnsweredQuestion
score: 0
tagged with: sqlite
answer count: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/82416411
downvote count: 1
accepted answer: http://stackoverflow.com/a/47727911

http://stackoverflow.com/q/47764392
score: 0
linked to: http://stackoverflow.com/q/265960
answer count: 0
duplicate of: http://stackoverflow.com/q/265960
has body: This is my current code in Python. From here, I need to strip the gutenberg.txt of its punctuation. How would I go about this? import bs4 import urllib.request #make a string to record location loc = 'http://www.gutenberg.org/files/1155/1155-h/1155-h.htm' #create page object page = urllib.request.urlopen(loc).read() #create the soup object soup = bs4.BeautifulSoup(page,'html.parser') #save into text file print(soup.prettify()) print(soup.get_text()) string = str(soup.get_text()) f = open("gutenberg.txt","w") f.write(string); f.close()
has comment: http://stackoverflow.com/comment/82490284
type: Question
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/82490408
has title: How do I strip the punctuation from this?

http://stackoverflow.com/q/47810891
score: 0
has answer: http://stackoverflow.com/a/47820153
answer count: 1
type: Question
accepted answer: http://stackoverflow.com/a/47820153
tagged with: numba
tagged with: python
has title: Passing functions to CUDA blocks with numba
has body: I am working in python with the numba library and wondered if there is a solution to write a parallel version of a previous work. I have a function f(X, S, F) where X and S are scalar arrays, and F is a list of functions. I am almost sure that passing an array of functions is not possible with numba (and cuda in general?). What would be an alternative solution to this? If there is one. Thanks in advance for your help
tagged with: cuda
type: AnsweredQuestion

http://stackoverflow.com/q/47789436
has comment: http://stackoverflow.com/comment/82570553
has title: How to access --variablefile arguments in python
downvote count: 0
answer count: 3
has body: In a shell script I have: /usr/local/bin/pybot --variablefile variables.py:$var1:$var2 test_cases.tsv inside variables.py how can I access var1 and var2 arguments? I have tried: import sys var1 = sys.argv[1] var1 = sys.argv[2] it seems like this doesn't work.
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/82573383
tagged with: selenium
favorite count: 0
type: Question
tagged with: robotframework
has answer: http://stackoverflow.com/a/47789627
has answer: http://stackoverflow.com/a/47797216
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/82543029
has answer: http://stackoverflow.com/a/47789996

http://stackoverflow.com/comment/82554221
score: 0
type: Comment
has text: Hi Christoph, Thank you for your prompt reply. In reality, the ring in an image may appear anywhere (i.e. I could not guess where it is). Is there anyway to improve my current algorithm so that I don't need to guess? Thanks!
comment on: http://stackoverflow.com/a/47796623
type: AnswerComment

http://stackoverflow.com/comment/82528181
score: 0
comment on: http://stackoverflow.com/q/47779513
type: QuestionComment
has text: In one of your comments, you asked about finding max. There's a `max` function that works on lists. Just use that instead of sum.
type: Comment

http://stackoverflow.com/a/47759407
type: Answer
answers question: http://stackoverflow.com/q/47757493
downvote count: 0
score: 1
upvote count: 1
has body: The formatting of your header has to match the formatting of the columns For example, with a 3 columns and a %10.5f format, the perline format is: In [185]: fmt = '\t'.join(['%10.5f']*3) In [186]: fmt Out[186]: '%10.5f\t%10.5f\t%10.5f' So a numeric line will be written as: In [187]: fmt%tuple(np.random.random(3)) Out[187]: ' 0.83330\t 0.90960\t 0.07613' The corresponding header would be: In [188]: '%10s\t%10s\t%10s'%('A','B','C') Out[188]: ' A\t B\t C' In [189]: header = '%10s\t%10s\t%10s'%('A','B','C') In [193]: np.savetxt('test.txt', np.random.random((2,3)), delimiter='\t', heade ...: r=header, fmt='%10.5f') In [194]: cat test.txt # A B C 0.55919 0.55277 0.47236 0.93945 0.50398 0.56320 The default fmt is given in the signature line np.savetxt(fname, X, fmt='%.18e', delimiter=' ', newline='\n', header='', footer='', comments='# ') That's harder to match since it only specifies the number of decimal pts, not the total width.
has comment: http://stackoverflow.com/comment/96583048

http://stackoverflow.com/comment/82488588
has text: @guillermochamorro i'm not using virtualenv INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'agenda.apps.AgendaConfig', 'rest_framework', ] REST_FRAMEWORK = { # Use Django's standard `django.contrib.auth` permissions, # or allow read-only access for unauthenticated users. 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly' ] }
comment on: http://stackoverflow.com/q/47763408
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47728841
has title: Create Parent-Child tree JSON
tagged with: javascript
tagged with: python
has comment: http://stackoverflow.com/comment/82462202
score: -1
tagged with: php
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/82418797
type: UnansweredQuestion
tagged with: java
answer count: 1
favorite count: 0
has body: I have a JSON data containing moduleId and parentId, I want a new JSON with a map structure of module's parent-child. **parentId can be null which means that module has no parent. Current JSON- [{ "moduleId": 1, "parentId": null }, { "moduleId": 2, "parentId": 1 }, { "moduleId": 3, "parentId": 1 }, { "moduleId": 4, "parentId": null }, { "moduleId": 5, "parentId": null }, { "moduleId": 6, "parentId": 3 } ] Required JSON- [{ "moduleId": 1, "child": [{ "moduleId": 2, "child": [] }, { "moduleId": 3, "child":[{ "moduleId": 6, "child": [] }] }] }, { "moduleId": 4, "child": [] }, { "moduleId": 5, "child": [] } ] Current Code Problem - children inside children are not getting mapped function tree($list) { $map = new stdClass(); $roots = [];$node = []; for($i=0; $i&lt;sizeof($list); $i++) { $c=$list[$i]["moduleId"]; $map-&gt;$c = $i; $list[$i]["children"] = []; // initialize the children } for($i=0; $i&lt;sizeof($list); $i++) { $node = $list[$i]; if( $node["parentId"] !== "" ) { $m = $node["parentId"]; $val = $map-&gt;$m; $child = new StdClass; $child-&gt;moduleId = $node["moduleId"]; $child-&gt;parentId = $node["parentId"]; $child-&gt;children = []; array_push($list[$val]["children"],$node); } } for($i = 0;$i&lt;sizeof($list);$i++) { if($list[$i]["parentId"] == "") { array_push($roots, $list[$i]); } } return json_encode($roots); } I cant figure it out. All the answers here give different kinds of result. Can use any language(java,C,php,js,python,etc). Thankyou.
downvote count: 3
tagged with: http://stackoverflow.com/tag/json
has answer: http://stackoverflow.com/a/47731451

http://stackoverflow.com/comment/82480000
comment on: http://stackoverflow.com/q/47759123
score: 0
has text: The very first question to ask yourself: are you underfitting or overfitting?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82551328
type: Comment
type: QuestionComment
has text: Are all tables going to be unmanaged? Are the tables from both DB imported into a single app? Did you set up both database connections in your `settings.py`?
comment on: http://stackoverflow.com/q/47750439
score: 0

http://stackoverflow.com/q/47855500
tagged with: django
tagged with: python
score: 0
has title: iOS not playing html5 videos
answer count: 1
has comment: http://stackoverflow.com/comment/82675072
type: Question
has body: I built a lan video server using Django. I use the video tag to play videos, so no extra players need to be installed. The videos play quite well in other platforms like windows or android, but it doesn’t work on my iPhone, no matter the size or format of the video file. Moreover, when I use wireshark to analyze the data packages, I found out that the data is transferred correctly at the beginning, but the client closed the socket connection immediately. It’s quite bizarre. Can anyone help me figure out what’s going wrong here. Any suggestions will be helpful. Ps: I edited it on my phone, so sorry for the terrible format. the code for the html page {{file_name}} the log of django: the data package from wireshark
has comment: http://stackoverflow.com/comment/82675262
has answer: http://stackoverflow.com/a/47855582
type: UnansweredQuestion
tagged with: ios
tagged with: http://stackoverflow.com/tag/html

http://stackoverflow.com/a/47791254
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47787458
answers question: http://stackoverflow.com/q/47787458
upvote count: 9
type: Answer
score: 9
has body: set_model is a method defined in keras.callbacks.Callback. To write a custom callback, you'll have to subclass keras.callbacks.Callback. Otherwise, your callback will lack some necessary methods used by Keras internally. Changing the first line into the following line should work. class TimingCallback(keras.callbacks.Callback):

http://stackoverflow.com/q/47826190
type: Question
has comment: http://stackoverflow.com/comment/82614913
has answer: http://stackoverflow.com/a/47826356
has title: Python regex number by looking behind
downvote count: 0
has comment: http://stackoverflow.com/comment/82614762
upvote count: 1
tagged with: python
possible better answer: http://stackoverflow.com/a/47826356
accepted answer: http://stackoverflow.com/a/47826301
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47826301
has body: I am extracting numbers in such format string. AB1234 AC1234 AD1234 As you see, A is always there and the second char excludes ". I write below code to extract number. re.search(r'(?&lt;=A[^"])\d*',input) But I encountered an error. look-behind requires fixed-width pattern So is there any convenient way to extract numbers? Now I know how to search twice to get them.Thanks in advance. Note A is a pattern , in fact A is a world in a long string.
score: 1
answer count: 2
tagged with: regex
has comment: http://stackoverflow.com/comment/82614748
favorite count: 0
has comment: http://stackoverflow.com/comment/82614804

http://stackoverflow.com/a/47736988
upvote count: 1
has body: You should use % to check if a number is even or odd, not //. Another approach is to split your problem into two functions. Below their is one main calling function positive_even(), and one function that adds numbers to an accumulated list, rec_positive(): def positive_even(start, end): if start &lt; 0 or end &lt; 0: raise ValueError("Must be positive numbers") # if start is even, add it to the accumulated list if start % 2 == 0: return rec_positve(start, end, [start]) # otherwise, dont add start to accumulated list, because its odd return rec_positve(start, end, []) def rec_positve(start, end, acc): # base case if start == end: return acc # copy start variable temp = start # If start is even, increment it by 2 for next number if temp % 2 == 0: temp += 2 # otherwise, the next number with be even else: temp += 1 # add to the resulting list acc += [temp] # recurse again, until base case is reached return rec_positve(temp, end, acc) Which works as follows: &gt;&gt;&gt; print(positive_even(0, 10)) [0, 2, 4, 6, 8, 10] &gt;&gt;&gt; print(positive_even(1, 10)) [2, 4, 6, 8, 10] &gt;&gt;&gt; print(positive_even(5, 10)) [6, 8, 10] &gt;&gt;&gt; print(positive_even(10, 10)) [10] Note: I inserted the numbers in a list instead, can be easily printed out from here.
type: Answer
answers question: http://stackoverflow.com/q/47736752
score: 1
downvote count: 0

http://stackoverflow.com/a/47816763
accepted answer of: http://stackoverflow.com/q/47813259
has comment: http://stackoverflow.com/comment/82598778
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47813259
has body: To shift the gridlines, you can simply change the ticks position: ax.set_xticks(np.arange(-0.5, arr.shape[1], 5)) will put one major tick each 5 pixels starting from the border of the first pixel. ax.set_xticks(np.arange(-0.5, arr.shape[1], 1), minor=True) does the same thing but every pixel for minor ticks. And then do the same for y but with arr.shape[0]. To add text, you can simply use ax.text(x, y, 'text'). I used a dictionary to match the colors (in hex format because rgb lists cannot be dictionary keys) to the texts. What you need to pay attention to is that (i, j) matrix indexes correspond to (y, x) coordinates. Here is the full code: from scipy import misc import matplotlib.pyplot as plt import numpy as np import matplotlib.ticker as plticker from matplotlib.colors import to_hex arr = misc.imread('image.png', mode= 'RGB') # array # adapt figure size to the image size. fig = plt.figure(figsize=(0.2*arr.shape[1], 0.2*arr.shape[0])) imgplot = plt.imshow(arr) # RGB ax = plt.gca() ax.grid(True) ax.grid(b=True, which='major', color='b', linestyle='-') plt.minorticks_on() ax.grid(b=True, which='minor', color='k', linestyle='-',linewidth=.3) # put a major gridline every 5 pixels ax.set_xticks(np.arange(-0.5, arr.shape[1], 5)) ax.set_yticks(np.arange(-0.5, arr.shape[0], 5)) # set ticks label ax.set_xticklabels(np.arange(0, arr.shape[1], 5)) ax.set_yticklabels(np.arange(0, arr.shape[0], 5)) # put a minor gridline every pixel ax.set_xticks(np.arange(-0.5, arr.shape[1], 1), minor=True) ax.set_yticks(np.arange(-0.5, arr.shape[0], 1), minor=True) fig.tight_layout(pad=0) # reduce space around image # display text colors_to_text = {'#000000': 'B', '#ffffff': 'W', '#f58a35': 'O', '#bcbbbb': 'G'} for i in range(arr.shape[0]): for j in range(arr.shape[1]): # get the text corresponding to the pixel color txt = colors_to_text.get(to_hex(arr[i,j]/255), '') # display text (x, y are inverted compared to the i, j indexes of the matrix) ax.text(j, i, txt, color='#888888', horizontala…
score: 1
type: Answer

http://stackoverflow.com/q/47708128
has title: how to load json file greater than 10gb in pandas/python of a particular pattern
accepted answer: http://stackoverflow.com/a/47799460
tagged with: bigdata
linked to: http://stackoverflow.com/q/15278375
score: 6
has answer: http://stackoverflow.com/a/47799460
has comment: http://stackoverflow.com/comment/82377775
has answer: http://stackoverflow.com/a/47753696
tagged with: python
has body: I have a json file of 11gb and I'm unable to load it in pandas. (Source: http://jmcauley.ucsd.edu/data/amazon/) Metadata within the above link is the file that I'm using. Metadata: Metadata includes descriptions, price, sales-rank, brand info, and co-purchasing links: It has the following pattern - { "asin": "0000031852", "title": "Girls Ballet Tutu Zebra Hot Pink", "price": 3.17, "imUrl": "http://ecx.images-amazon.com/images/I/51fAmVkTbyL._SY300_.jpg", "related": { "also_bought": ["B00JHONN1S", "B002BZX8Z6", "B00D2K1M3O", "0000031909", "B00613WDTQ", "B00D0WDS9A", "B00D0GCI8S", "0000031895", "B003AVKOP2", "B003AVEU6G", "B003IEDM9Q", "B002R0FA24", "B00D23MC6W", "B00D2K0PA0", "B00538F5OK", "B00CEV86I6", "B002R0FABA", "B00D10CLVW", "B003AVNY6I", "B002GZGI4E", "B001T9NUFS", "B002R0F7FE", "B00E1YRI4C", "B008UBQZKU", "B00D103F8U", "B007R2RM8W"], "also_viewed": ["B002BZX8Z6", "B00JHONN1S", "B008F0SU0Y", "B00D23MC6W", "B00AFDOPDA", "B00E1YRI4C", "B002GZGI4E", "B003AVKOP2", "B00D9C1WBM", "B00CEV8366", "B00CEUX0D8", "B0079ME3KU", "B00CEUWY8K", "B004FOEEHC", "0000031895", "B00BC4GY9Y", "B003XRKA7A", "B00K18LKX2", "B00EM7KAG6", "B00AMQ17JA", "B00D9C32NI", "B002C3Y6WG", "B00JLL4L5Y", "B003AVNY6I", "B008UBQZKU", "B00D0WDS9A", "B00613WDTQ", "B00538F5OK", "B005C4Y4F6", "B004LHZ1NY", "B00CPHX76U", "B00CEUWUZC", "B00IJVASUE", "B00GOR07RE", "B00J2GTM0W", "B00JHNSNSM", "B003IEDM9Q", "B00CYBU84G", "B008VV8NSQ", "B00CYBULSO", "B00I2UHSZA", "B005F50FXC", "B007LCQI3S", "B00DP68AVW", "B009RXWNSI", "B003AVEU6G", "B00HSOJB9M", "B00EHAGZNA", "B0046W9T8C", "B00E79VW6Q", "B00D10CLVW", "B00B0AVO54", "B00E95LC8Q", "B00GOR92SO", "B007ZN5Y56", "B00AL2569W", "B00B608000", "B008F0SMUC", "B00BFXLZ8M"], "bought_together": ["B002BZX8Z6"] }, "salesRank": {"Toys &amp; Games": 211836}, "brand": "Coxlures", "categories": "Sports &amp; Outdoors", "Other Sports", "Dance" } On the other hand the 1st 10 rows have the following data: ["{'asin': '0001048791', 'salesRank': {'Books': 6334800}, 'imUrl': 'http://e…
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47852983
has comment: http://stackoverflow.com/comment/82453122
answer count: 3
tagged with: pandas
possible better answer: http://stackoverflow.com/a/47753696
has comment: http://stackoverflow.com/comment/82566094
has comment: http://stackoverflow.com/comment/82455845
linked to: http://stackoverflow.com/q/14262433
upvote count: 7
has comment: http://stackoverflow.com/comment/82445573
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82377355

http://stackoverflow.com/q/47768372
type: UnansweredQuestion
tagged with: cpython
has comment: http://stackoverflow.com/comment/82501483
has comment: http://stackoverflow.com/comment/82499193
has comment: http://stackoverflow.com/comment/82500827
score: 0
has comment: http://stackoverflow.com/comment/82499873
has title: CPython: how to link an external library (C or C++) to an extension
tagged with: python
tagged with: http://stackoverflow.com/tag/c
has comment: http://stackoverflow.com/comment/82499899
tagged with: c++
type: Question
has comment: http://stackoverflow.com/comment/82498208
tagged with: python-3.x
has body: I'm trying to implement an extension that requires use of external libraries. How can I configure include files, libraries and the path where dynamic libraries should be found? I've tried not adding these parameters and it seems compiling without any error but then, if I try to import the module, I obtain a segmentation fault error probably due to something lacking in configuration settings or setup.py.
answer count: 0
linked to: http://stackoverflow.com/q/6578484

http://stackoverflow.com/a/47766180
has body: You can try something like this : book1 = { "author" :"A A", "book" : { "series" : "19 A, 19 B, 19 C", "year" : "1990, 1991, 1992" }} book2 = { "author" :"B B", "book" : { "series" : "20 A, 20 B, 19 C", "year" : "1995, 1995, 1992" } } book3 = { "author" :"C C", "book" : { "series" : "19 A, 19 B, 19 C", "year" : "1990, 1991, 1992" } } book_list=[book1,book2,book3] for i in book_list: series_book = [] b_list={} for key,value in i['book'].items(): series_book.append([kk.strip() for kk in value.split(',')]) for i in range(0,len(series_book),2): zipped_stuff=list(zip(*series_book[i:i+2])) for i in zipped_stuff: b_list["year"] = i[1] b_list["_id"]={'series': i[0]} print(b_list) output: {'_id': {'series': '19 A'}, 'year': '1990'} {'_id': {'series': '19 B'}, 'year': '1991'} {'_id': {'series': '19 C'}, 'year': '1992'} {'_id': {'series': '20 A'}, 'year': '1995'} {'_id': {'series': '20 B'}, 'year': '1995'} {'_id': {'series': '19 C'}, 'year': '1992'} {'_id': {'series': '19 A'}, 'year': '1990'} {'_id': {'series': '19 B'}, 'year': '1991'} {'_id': {'series': '19 C'}, 'year': '1992'}
score: 0
answers question: http://stackoverflow.com/q/47763958
type: Answer
has comment: http://stackoverflow.com/comment/82504892

http://stackoverflow.com/comment/84794908
has text: See `http://dev.evernote.com/doc/reference/NoteStore.html#Fn_NoteStore_getNoteWithResultSpec`. If you need note title and content, you can set true to NoteResultspec.includeContent (http://dev.evernote.com/doc/reference/NoteStore.html#Struct_NoteResultSpec).
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47837817
score: 0

http://stackoverflow.com/comment/82539224
type: AnswerComment
comment on: http://stackoverflow.com/a/47788896
score: 0
type: Comment
has text: Thanks for your reply. now, it's giving this error `{'type':'paragraph', 'value': 'My Paragraph'}, TypeError: 'function' object has no attribute '__getitem__'`

http://stackoverflow.com/comment/82449518
type: Comment
has text: @roelofs Not at all. I'm sorry if that's the way it came across. I've just never heard of urllib.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47744558

http://stackoverflow.com/q/47726633
answer count: 1
tagged with: file
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/47845402
type: Question
score: 3
has answer: http://stackoverflow.com/a/47845402
tagged with: glob
tagged with: operating-system
tagged with: python
has title: How do I hide all excluding a file type
type: AnsweredQuestion
upvote count: 3
has comment: http://stackoverflow.com/comment/82416841
tagged with: hide
has body: I'm trying to hide all my files excluding .exe. Below hides: files, exe Does not hide: folders I want: Hide folders, files Does not hide: .exe import os, shutil import ctypes folder = 'C:\\Users\\TestingAZ1' for the_file in os.listdir(folder): file_path = os.path.join(folder, the_file) try: if os.path.isfile(file_path): ctypes.windll.kernel32.SetFileAttributesW(file_path, 2) except Exception as e: print(e) I cannot use -onefile due to large size for each exe.

http://stackoverflow.com/comment/114379237
has text: SAME here! Wow, I must've read over 75 webpages before coming across this...
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/53462171
type: Comment

http://stackoverflow.com/comment/82515846
comment on: http://stackoverflow.com/a/47768591
score: 0
type: AnswerComment
has text: Thank you, that makes perfect sense and works like a charm!
type: Comment

http://stackoverflow.com/comment/82391687
type: Comment
has text: @user3046660 Furthermore, my update to convert the row to a row of `float` from `str` assumes each element in the row **can** be converted to `float`.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47714270

http://stackoverflow.com/comment/101175783
score: 1
type: Comment
has text: This was a while ago and I slightly forgot what I meant but I guess what I meant could have been something like 1. use TFIDF on a large corpus that is similar to your domain to get a basic language model like ngram and then 2. only use those ngrams when searching your corpus.
comment on: http://stackoverflow.com/a/47742651
type: AnswerComment

http://stackoverflow.com/comment/111373776
type: Comment
score: 0
has text: Thanks this did the trick for me. No need for route annotation though, a simple call to pythoncom.CoInitialize() seems sufficient
type: AnswerComment
comment on: http://stackoverflow.com/a/57805512

http://stackoverflow.com/a/47834707
score: 1
has comment: http://stackoverflow.com/comment/82643806
type: Answer
has comment: http://stackoverflow.com/comment/137735296
has comment: http://stackoverflow.com/comment/82646808
has comment: http://stackoverflow.com/comment/82640400
has comment: http://stackoverflow.com/comment/82647211
answers question: http://stackoverflow.com/q/47834025
downvote count: 0
upvote count: 1
has body: Using conditional: import pandas as pd df_excel = pd.ExcelFile('Sales.xlsx') df = df_excel.parse('Info') for col in list(df): # All columns pprow = 0 prow = 1 for row in df[1:].iterrows(): # All rows, except first if pd.isnull(df.loc[prow, 'Album Name']): # If this cell is empty all in the same row too. continue elif pd.isnull(df.loc[prow, col]) and pd.isnull(df.loc[row[0], col]): # If a cell and next one are empty, take previous valor. df.loc[prow, col] = df.loc[pprow, col] pprow = prow prow = row[0] Output (I use different names): Order_ID Customer_name Album Name 0 NaN NaN Radio 1 1.0 John a 2 1.0 John b 3 1.0 John c 4 1.0 John d 5 1.0 John e 6 1.0 John f 7 NaN NaN GE 8 2.0 Harry We are Born 9 3.0 Lizzy Relapse 10 4.0 Abe Smoke 11 4.0 Abe Tell me 12 NaN NaN NaN 13 NaN NaN Best Buy 14 5.0 Kristy The wall 15 6.0 Sammy Kind of blue
has comment: http://stackoverflow.com/comment/82641169
has comment: http://stackoverflow.com/comment/82645105

http://stackoverflow.com/comment/82621122
type: Comment
comment on: http://stackoverflow.com/a/47828678
type: AnswerComment
has text: `from rest_framework.compat import is_authenticated`
score: 1

curve-fitting
tags question: http://stackoverflow.com/q/47706487
tags question: http://stackoverflow.com/q/47752210
tags question: http://stackoverflow.com/q/47841933
tag name: curve-fitting
tags question: http://stackoverflow.com/q/47773178
tags question: http://stackoverflow.com/q/47733367
type: Tag

http://stackoverflow.com/a/47815253
answers question: http://stackoverflow.com/q/47814661
upvote count: 3
score: 3
type: AcceptedAnswer
downvote count: 0
has body: A solution that would work with variable digit representations: &gt;&gt;&gt; import re &gt;&gt;&gt; e = 'U+270DU+1F3FF' &gt;&gt;&gt; def emojize(match): ... return chr(int(match.group(0)[2:], 16)) &gt;&gt;&gt; re.sub(r"U\+[0-9A-F]+", emojize, e) '✍'
type: Answer
accepted answer of: http://stackoverflow.com/q/47814661

http://stackoverflow.com/comment/82404644
type: QuestionComment
has text: Can you not update your operating systems to a newer version of macOS?
score: 0
comment on: http://stackoverflow.com/q/47721998
type: Comment

http://stackoverflow.com/q/47854631
type: Question
has body: I'm new to Python/pandas, and I have an issue with decimals and can't figure out for a few hours already how to solve it. Basically I want to read CSV file into pandas and keep the decimals exactly as they are stored in text, for future comparisons and simple math operations. Example: is_string_dtype(report['item_weight_kg']) Out[12]: True l = report.loc[report['item'] == 'B0WY'] num1 = l['item_weight_kg'][8210] num1 Out[14]: '22.000370049504' then I try to convert them to float, which gives me a value ending in ...3999 instead of ...4 report['item_weight_kg'] = report.apply(lambda x: float(x['item_weight_kg']), axis = 1 ) l = report.loc[report['item'] == 'B0WY'] num1 = l['item_weight_kg'][8210] num1 Out[17]: 22.000370049503999 right after importing the dataset, I've tried to convert it to float, and in console it works properly, returns me the desired value, but when I am trying to apply it to the whole dataset, it doesn't float(decimal.Decimal(l['item_weight_kg'][8210])) Out[23]: 22.000370049504 report['item_weight_kg'] = report.apply(lambda x: float(decimal.Decimal(x['item_weight_kg'])), axis = 1 ) l = report.loc[report['item'] == 'B0WY'] num1 = l['item_weight_kg'][8210] num1 Out[25]: 22.000370049503999 How can this be solved?
has comment: http://stackoverflow.com/comment/82682910
has comment: http://stackoverflow.com/comment/82673336
has title: python/pandas keeping decimal places exactly as in string
has comment: http://stackoverflow.com/comment/82682845
tagged with: python
tagged with: type-conversion
possible better answer: http://stackoverflow.com/a/47854769
tagged with: decimal
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82673595
score: 0
has answer: http://stackoverflow.com/a/47854769
answer count: 2
tagged with: pandas
accepted answer: http://stackoverflow.com/a/47874166
has answer: http://stackoverflow.com/a/47874166
tagged with: floating-point

http://stackoverflow.com/q/47805802
answer count: 1
tagged with: python
has answer: http://stackoverflow.com/a/47805949
score: 2
has title: How to read a newline from config file using Python ConfigParser
downvote count: 0
has body: I have a config File "Email_Properties.cfg" as below [email_Properties] Subject=Security keywords Scan Info Body=securityDetails\n Note : This is an auto generated mail I am using ConfigParser to read file and print the content, Not able to get newLine using \n config = ConfigParser.ConfigParser() config.readfp(open(r'Email_Properties.cfg')) body=config.get('email_Properties', 'Body') print body output: securityDetails\n Note : This is an auto generated mail How i can get NewLine present in the string of Config file ? Expected output as below, securityDetails Note : This is an auto generated mail
tagged with: configparser
favorite count: 0
type: Question
upvote count: 2
type: UnansweredQuestion

http://stackoverflow.com/q/47742075
type: Question
has title: Running Python Mathplotlib through Java Interface
type: UnansweredQuestion
downvote count: 0
tagged with: python
answer count: 0
score: 1
has body: I am trying to run a python mathplotlib through a JAVA GUI interface. The plot input i.e. the list is user give. Therefore the runtime and exec commands aren't working as they need an already written code. Is there anyway I can take user input from Java GUI and use it to plot in python(mathplotlib) and display the pic (It is fine if the image is not displayed on the GUI but occurs as in separate window)
tagged with: java
upvote count: 1
favorite count: 0

http://stackoverflow.com/q/47744366
type: Question
has comment: http://stackoverflow.com/comment/82448937
has title: Using map and filter function on a sublist in python
has answer: http://stackoverflow.com/a/47744473
possible better answer: http://stackoverflow.com/a/47744449
downvote count: 0
score: 1
upvote count: 1
accepted answer: http://stackoverflow.com/a/47744386
tagged with: lambda
has answer: http://stackoverflow.com/a/47744386
has answer: http://stackoverflow.com/a/47744480
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47744449
tagged with: python
answer count: 4
has body: L = [[5, 0, 6], [7, 22], [0, 4, 2], [9, 0, 45, 17]] I do have this list and my task is to remove the 0's. I have to use both map() and filter() function. The hint is that this task is solvable with a single expression using map, filter and lambda expressions. I have been trying to figure this out for quite a while but I just don't get it. You don't have to solve it completely, but help would be appreciated. I assume I use map() to iterate over the outer lists, but how do I call filter() with the sublist? L2 = map(lambda x: filter(lambda x: x&lt;&gt;0 ,L),L)
favorite count: 0

http://stackoverflow.com/comment/82543332
type: Comment
type: QuestionComment
has text: Why are you not changing the `'Name'` column to numericals as you did for `'Country'`. OneHotEncoder only handles numerical X. So either remove that from the X before sending to OneHotEncoder or convert to numerical.
score: 0
comment on: http://stackoverflow.com/q/47790854

http://stackoverflow.com/q/47740002
has answer: http://stackoverflow.com/a/47747013
tagged with: opencv3.0
answer count: 1
has title: opencv error cascadedetect.cpp:1639: error: (-215) !empty() in function detectMultiScale
tagged with: face-recognition
type: Question
has body: I am following a tutorial for face recognition using python. so this is the code im using import cv2,os import numpy as np from PIL import Image recognizer = cv2.face.createLBPHFaceRecognizer() detector= cv2.CascadeClassifier("haarcascade_frontalface_default.xml"); def getImagesAndLabels(path): #get the path of all the files in the folder imagePaths=[os.path.join(path,f) for f in os.listdir(path)] #create empth face list faceSamples=[] #create empty ID list Ids=[] #now looping through all the image paths and loading the Ids and the images for imagePath in imagePaths: #loading the image and converting it to gray scale pilImage=Image.open(imagePath).convert('L') #Now we are converting the PIL image into numpy array imageNp=np.array(pilImage,'uint8') #getting the Id from the image Id=int(os.path.split(imagePath)[-1].split(".")[1]) # extract the face from the training image sample faces=detector.detectMultiScale(imageNp) #If a face is there then append that in the list as well as Id of it for (x,y,w,h) in faces: faceSamples.append(imageNp[y:y+h,x:x+w]) Ids.append(Id) return faceSamples,Ids faces,Ids = getImagesAndLabels('trainingImage') recognizer.train(faces, np.array(Ids)) recognizer.save('trainer/trainer.yml') and this is the error message im getting Traceback (most recent call last): File "/home/pi/pythonpy/videofacedet/craft/codacus/trainer.py", line 32, in faces,Ids = getImagesAndLabels('trainingImage') File "/home/pi/pythonpy/videofacedet/craft/codacus/trainer.py", line 24, in getImagesAndLabels faces=detector.detectMultiScale(imageNp) error: /home/pi/opencv-3.1.0/modules/objdetect/src/cascadedetect.cpp:1639: error: (-215) !empty() in function detectMultiScale I read somewhere said that the folder I am pointing to (trainingImage) is empty, but it is not. I put my face training images there with the same filename format used by the tutorial author. I wish some one would help me with this problem.
type: UnansweredQuestion
tagged with: raspberry-pi3
tagged with: python
score: 0

http://stackoverflow.com/comment/82706246
comment on: http://stackoverflow.com/a/47820438
score: 1
type: Comment
has text: Thank you. This works. But I think I will not implement it on the `psycopg` layer. The amount of added SLOC is not worth the trouble. But your first tip, casting to the custom type works like a charm. I tested both solutions though, and they both work. I will just edit the post, making it Python 3 compatible and adding the required `psycopg2` imports if someone else comes across this. Thanks a bunch!
type: AnswerComment

http://stackoverflow.com/comment/82470846
comment on: http://stackoverflow.com/a/47754887
type: AnswerComment
score: 0
type: Comment
has text: Thanks, weirdly I seems to break if I add more than one condition: mask = (img_array == 0 or img_array == 1) Do you know why?

http://stackoverflow.com/a/47826011
has comment: http://stackoverflow.com/comment/82618789
type: Answer
answers question: http://stackoverflow.com/q/47825647
has body: When I run python on command prompt, it shows python 2.7, so I changed tkinter to Tkinter and the program worked by importing the .py file Using cmd: Pyinstaller works(through canopy cmd prompt): the first line is what I put into my IDLE's cmd prompt Which populates the folder when executed: And inside dist, I run test.exe which shows the window NOTE: my system command prompt is using python 2.7 while the canopy(python environment) command prompt uses 3.5 with pyinstaller
score: 0

http://stackoverflow.com/q/47723790
has comment: http://stackoverflow.com/comment/82408987
upvote count: 3
has comment: http://stackoverflow.com/comment/82411145
answer count: 1
has comment: http://stackoverflow.com/comment/82408931
has comment: http://stackoverflow.com/comment/82421692
has comment: http://stackoverflow.com/comment/82409017
has comment: http://stackoverflow.com/comment/82409340
downvote count: 1
has comment: http://stackoverflow.com/comment/82409170
favorite count: 0
tagged with: beautifulsoup
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/48218120
has body: Trying to insert data into PostgreSQL database. Python code: myFields = ((DOT_Number,),(Entity_Type,),(Operating_Status,),(Legal_Name,), (Phone,),(Address,) ) query = """ INSERT INTO saferdb_question( DOT_Number, Entity_Type, Operating_Status, Legal_Name, Phone, Address)VALUES ( %s, %s, %s, %s, %s, %s);""" cur.execute( query, myFields) Getting error: Traceback (most recent call last): File "scraper.py", line 189, in &lt;module&gt; cur.execute( query, myFields) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/psycopg2/extras.py", line 144, in execute return super(DictCursor, self).execute(query, vars) psycopg2.ProgrammingError: column "dot_number" of relation "saferdb_question" does not exist LINE 1: INSERT INTO saferdb_question( DOT_Number, Entity_Type, Oper... SQL from PostgreSQL that created the table: CREATE TABLE public.saferdb_question ( id integer NOT NULL DEFAULT nextval('saferdb_question_id_seq'::regclass), "DOT_Number" character varying(10) COLLATE pg_catalog."default" NOT NULL, ... "Phone" character varying(15) COLLATE pg_catalog."default" NOT NULL, "Address" character varying(200) COLLATE pg_catalog."default" NOT NULL, ) WITH ( OIDS = FALSE ) TABLESPACE pg_default; ALTER TABLE public.saferdb_question OWNER to postgres;
has comment: http://stackoverflow.com/comment/82409795
has comment: http://stackoverflow.com/comment/82408608
has answer: http://stackoverflow.com/a/48218120
has comment: http://stackoverflow.com/comment/82410695
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/82408955
has title: psycopg2.ProgrammingError: column of relation does not exist
has comment: http://stackoverflow.com/comment/82409627
has comment: http://stackoverflow.com/comment/82409269
score: 2
tagged with: postgresql
type: AnsweredQuestion

http://stackoverflow.com/q/47727651
tagged with: postgresql
tagged with: distinct
tagged with: django
tagged with: python
has title: Django Queryset get list for the day of a particular type, unique foreignkey id using Postgres database
has body: I am trying to find a query to get a list of latest attendance for a particular day, with unique employee that has checked in (CHECKIN = 1) Below is my model, records and what I am trying to accomplish. My model has 2 models: class Employee(models.Model): fullname = models.CharField(max_length=30, blank=False) class Attendance(models.Model): CHECKIN = 1 CHECKOUT = 2 ATTENDANCE_TYPE_CHOICES = ( (CHECKIN, "Check In"), (CHECKOUT, "Check Out"), ) employee = models.ForeignKey(Employee) activity_type = models.IntegerField(choices = ATTENDANCE_TYPE_CHOICES, default=CHECKIN) timestamp = models.DateTimeField(auto_now_add=True) Assuming I have the records below: Employee {"id":1, "employee":"michael jackson", "id":2, "fullname":"mariah carey", "id":3, "fullname":"taylor swift"} Attendance {"id":1, "employee": 1,"activity_type": 1, timestamp: "2017-12-05 09:08", -interested in this for the activity type (1 for CHECKIN) and the date 2017-12-05, last of that employee id for that day "id":2, "employee": 2,"activity_type": 1, timestamp: "2017-12-05 10:13", "id":3, "employee": 3,"activity_type": 1, timestamp: "2017-12-05 11:30", "id":4, "employee": 2,"activity_type": 2, timestamp: "2017-12-05 15:13", "id":5, "employee": 3,"activity_type": 2, timestamp: "2017-12-05 18:30", "id":6, "employee": 2,"activity_type": 1, timestamp: "2017-12-05 19:13", -interested in this for the activity type (1 for CHECKIN) and the date 2017-12-05, last of that employee id for that day "id":7, "employee": 3,"activity_type": 1, timestamp: "2017-12-05 20:30", -interested in this for the activity type (1 for CHECKIN) and the date 2017-12-05, last of that employee id for that day "id":8, "employee": 1,"activity_type": 2, timestamp: "2017-12-06 08:08"} I am interest so that it output this 2 record only based on the activity type 1 for CHECKIN and for the date 2017-12-05 and that employee id must be unique and latest: {"id":1, "employee": 1,"activity_type": 1, timestamp: "2017-12-05 09:08", "id":6, "employee": …
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47727961
score: 0
accepted answer: http://stackoverflow.com/a/47727961
tagged with: django-queryset
answer count: 1
type: Question

http://stackoverflow.com/a/47716019
answers question: http://stackoverflow.com/q/47714772
score: 1
type: Answer
has body: paginator=Paginator('test',10)# show 10 results per page here you pass a 'test' string to Paginator, instead pass test object so it will be paginator=Paginator(test,10)# show 10 results per page hope it will work
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47714772

http://stackoverflow.com/comment/82602235
score: 0
comment on: http://stackoverflow.com/a/47818902
type: Comment
type: AnswerComment
has text: Thank you! That improved performance by magnitudes. I tested on a 5000 row sample set, and your "in place" code was ten times faster.

http://stackoverflow.com/q/47757009
accepted answer: http://stackoverflow.com/a/47757379
type: AnsweredQuestion
score: 1
tagged with: spyder
has body: I'm running Spyder 3.2.4 in Windows 10 Despite my best efforts, my code is getting too wide to view in Spyder's default layout. I have therefore tried undocking the editor window. However, the undocked editor does not show up in the taskbar. Which leads me to the question, is there a way of switching between the main Spyder window and the undocked editor window?
tagged with: python
has answer: http://stackoverflow.com/a/47757379
favorite count: 0
type: Question
has title: Python: Spyder switching between undocked editor window and spyder console
answer count: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/47769763
linked to: http://stackoverflow.com/q/1196074
favorite count: 0
has answer: http://stackoverflow.com/a/47769894
type: Question
accepted answer: http://stackoverflow.com/a/47769894
type: AnsweredQuestion
tagged with: python
has body: After executing the first exe, it would do few validation and later I will execute the next exe. os.system ("C:/Python27/python.exe") --Few VALIDATION-- os.system ("C:\notepad.exe") But while execution, I am struck with first exe, after executing os.system ("C:/Python27/python.exe), python doesn't execute the next line.
score: 2
upvote count: 2
has title: How to execute next line after system command in python
tagged with: python-3.x
downvote count: 0
answer count: 1

http://stackoverflow.com/q/47729870
has answer: http://stackoverflow.com/a/47729967
favorite count: 0
accepted answer: http://stackoverflow.com/a/47730836
has answer: http://stackoverflow.com/a/47730836
type: Question
upvote count: 2
score: 2
possible better answer: http://stackoverflow.com/a/47729967
answer count: 2
downvote count: 0
tagged with: file
tagged with: django
tagged with: python
has body: I have an image stored in my media/logo/ folder and I'd like to save it to my model's FileField from my view. Here's what I tried but I'm getting an encoding error &amp; the file becomes corrupted after I'm trying to save it. UnicodeDecodeError: 'charmap' codec can't decode byte ... views.py: def save_records(request): new_path = os.path.join(settings.MEDIA_ROOT, 'logo', filename) same_file = File(new_path, filename) Company.objects.create(logo=same_file) I have some trouble understanding how I can save the file in new_path to the FileField, any idea ?
has title: How to save an image to FileField from its path?
tagged with: django-views
type: AnsweredQuestion

http://stackoverflow.com/comment/82572179
type: Comment
type: AnswerComment
has text: @ikom I think I found a way that when I ask which way the person wants to look, they type that direction. Then a variable gets set either 1, 2, 3, or 4 depending on which way they want to look. Then, still, in the main loop, there is 4 more if statements that ask if | direction == "go there" and variable == (a number) | then it calls a function to the next room.
comment on: http://stackoverflow.com/a/47739059
score: 0

http://stackoverflow.com/comment/82606539
score: 0
type: Comment
type: AnswerComment
has text: @coldspeed Thank you. You are right, the example is just an example here. However, my question is why can't I access the in-memory variable anymore, is it flushed in garbage collection?
comment on: http://stackoverflow.com/a/47806857

monkeypatching
tag name: monkeypatching
tags question: http://stackoverflow.com/q/47721213
type: Tag

http://stackoverflow.com/comment/82565293
comment on: http://stackoverflow.com/q/47801851
type: Comment
has text: It's close, but it's ultimately not the same question. Though, had I seen it before I posted I might have been able to figure it out. However, because the problem is sufficiently different from my question, I feel like my question is valid and not duplicative.
type: QuestionComment
score: 0

http://stackoverflow.com/q/47761398
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47763460
has comment: http://stackoverflow.com/comment/82484355
has body: I have a csv file with the following information: id name age height weight 1 x 12 11 124 2 y 13 23 432 3 z 14 43 1435 It's stored in a file called Workbook2.csv I use the following code: ipFile = csv.DictReader(open('Workbook2.csv', 'rU')) dict = {} # Tring to update the rows to this dictionary. for row in ipFile: print row I get the following result: {'weight': '124', '\xef\xbb\xbfid': '1', 'height ': '11', 'age ': '12', 'name ': 'x'} {'weight': '432', '\xef\xbb\xbfid': '2', 'height ': '23', 'age ': '13', 'name ': 'y'} {'weight': '1435', '\xef\xbb\xbfid': '3', 'height ': '43', 'age ': '14', 'name ': 'z'} I would like to know how I can update this output to a dictionary. I would also like to know how I can ignore the unicode characters that are encoded usig UTF-8, if there is a filter I can use to eliminate them.
has comment: http://stackoverflow.com/comment/82484250
type: UnansweredQuestion
tagged with: byte-order-mark
downvote count: 0
has comment: http://stackoverflow.com/comment/82484236
upvote count: 1
has answer: http://stackoverflow.com/a/47761757
has comment: http://stackoverflow.com/comment/82484381
tagged with: python
has title: How to ignore Unicode whitespace characters encoded in UTF-8?
has comment: http://stackoverflow.com/comment/82484284
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/82484222
answer count: 3
tagged with: http://stackoverflow.com/tag/csv
score: 1
tagged with: utf-8
has answer: http://stackoverflow.com/a/47761748
has comment: http://stackoverflow.com/comment/82484235

http://stackoverflow.com/comment/82627396
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47831551
has text: Let me know about views on concat option

http://stackoverflow.com/comment/82559502
type: Comment
score: 0
type: AnswerComment
has text: In Django 1.11 there is no problem. I opened a new issue on the repository.
comment on: http://stackoverflow.com/a/47773938

http://stackoverflow.com/q/47714943
type: Question
has answer: http://stackoverflow.com/a/47720225
tagged with: python
tagged with: restructuredtext
has body: Here is the snippet of list-table in reStrutureText. .. list-table:: Frozen Delights! :widths: 15 10 30 :header-rows: 1 * - Treat - Quantity - Description * - Albatross - 2.99 - On a stick! * - Crunchy Frog - 1.49 - If we took the bones out, it wouldn't be crunchy, now would it? * - Gannet Ripple - 1.99 - On a stick! The display effect. How to insert two blank lines between title Frozen Delights! and header line Treat Quantity Description ? To test \n in online tool http://rst.ninjs.org/, \n doesn't work.
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/82390778
has title: How to insert two blank lines between title and header in list-table of reStrutureText?
answer count: 1
accepted answer: http://stackoverflow.com/a/47720225

http://stackoverflow.com/comment/82671773
type: Comment
type: QuestionComment
has text: @fuglede good point, but then *only* the months need to be converted, the OP's current code doesn't gain any benefit.
score: 0
comment on: http://stackoverflow.com/q/47853828

http://stackoverflow.com/a/47804495
score: 1
answers question: http://stackoverflow.com/q/47804333
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82570691
has comment: http://stackoverflow.com/comment/82570621
type: Answer
has body: The error you're getting is telling you that model.predict(crop) only returns one thing, and you're telling Python to expect it to return two things. However, unless you omitted some important stuff, it looks like you overwrite the variables label and confidence in the next code block, so you could ostensibly just remove that line of code. If you can't remove that line, then make a hotfix by setting one of those variables to zero: label, confidence = model.predict(crop), 0
accepted answer of: http://stackoverflow.com/q/47804333
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/47715594
score: 0
has body: import networkx as nx author = """Ben Reilly (benwreilly@gmail.com)""" all = ['read_shp', 'write_shp'] [docs]def read_shp(path, simplify=True): """Generates a networkx.DiGraph from shapefiles. Point geometries are translated into nodes, lines into edges. Coordinate tuples are used as keys. Attributes are preserved, line geometries are simplified into start and end coordinates. Accepts a single shapefile or directory of many shapefiles. "The Esri Shapefile or simply a shapefile is a popular geospatial vector data format for geographic information systems software [1]_." Parameters ---------- path : file or string File, directory, or filename to read. simplify: bool If ``True``, simplify line geometries to start and end coordinates. If ``False``, and line feature geometry has multiple segments, the non-geometric attributes for that feature will be repeated for each edge comprising that feature. Returns ------- G : NetworkX graph Examples -------- &gt;&gt;&gt; G=nx.read_shp('test.shp') # doctest: +SKIP References ---------- .. [1] http://en.wikipedia.org/wiki/Shapefile """ try: from osgeo import ogr except ImportError: raise ImportError("read_shp requires OGR: http://www.gdal.org/") if not isinstance(path, str): return net = nx.DiGraph() shp = ogr.Open(path) for lyr in shp: fields = [x.GetName() for x in lyr.schema] for f in lyr: flddata = [f.GetField(f.GetFieldIndex(x)) for x in fields] g = f.geometry() attributes = dict(zip(fields, flddata)) attributes["ShpName"] = lyr.GetName() if g.GetGeometryType() == 1: # point net.add_node((g.GetPoint_2D(0)), attributes) if g.GetGeometryType() == 2: # linestring last = g.GetPointCount() - 1 if simplify: attributes["Wkb"] = g.ExportToWkb() attributes["Wkt"] = g.ExportToWkt() attributes["Json"] = g.ExportToJson() net.add_edge(g.GetPoint_2D(0), g.GetPoint_2D(last), attributes) else: # separate out each segment as individual edge for i in range(last): pt1 = g.GetPoint_2D(i) pt2 = g.GetPoint_2D(i + 1) segment = ogr.Geometry(ogr.wkbLi…
has comment: http://stackoverflow.com/comment/82392231
type: Answer
answers question: http://stackoverflow.com/q/47715318

http://stackoverflow.com/a/47700337
score: 1
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47700271
type: Answer
has body: Generally if you're using a for loop you're probably doing it wrong! What you probably want is a groupby and count? unGrouped.groupBy('borough').size()

http://stackoverflow.com/comment/82399972
has text: `"key"\s*:\s*"([^"]*)"`?
comment on: http://stackoverflow.com/q/47719580
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82414216
type: Comment
has text: @digitalsentinel I was wrong regarding the StopIteration. It is now deemed incorrect by PEP479.
comment on: http://stackoverflow.com/a/47726522
type: AnswerComment
score: 0

http://stackoverflow.com/comment/82606994
score: 0
comment on: http://stackoverflow.com/a/47821920
type: Comment
has text: @MartijnPieters correct, where you originally referring to how the OP wants them sorted?
type: AnswerComment

http://stackoverflow.com/a/47837260
score: 0
answers question: http://stackoverflow.com/q/47837093
has comment: http://stackoverflow.com/comment/82638349
has comment: http://stackoverflow.com/comment/82638251
type: Answer
has body: Just take out the comma in keypoints_lst = lst[:, 0]. When you include the comma, Python thinks you're giving a tuple, which you can't. Now, that will get rid of the error, but keypoints_lst = lst[:0] will just return an empty list, which I don't think you want. Python list slicing follows the format of mylist[start:stop:step]. When the start is not provided, it defaults to 0. So with the stop also being 0, you're going to get an empty list. Change the stop index to being the index of the last element you want to look at, plus one.

http://stackoverflow.com/comment/82423596
type: QuestionComment
comment on: http://stackoverflow.com/q/47731358
has text: The first thing I notice is you have 3 calls to Tk() in that program ... you should only ever have one. Are you trying to make a modal notification? Use Toplevel() for that, not Tk().
type: Comment
score: 1

http://stackoverflow.com/comment/82380829
has text: @Heena And also post a proper JSON string which you are using
comment on: http://stackoverflow.com/q/47710393
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/q/47812858
downvote count: 1
has title: How to get multiple elements of a list
favorite count: 0
score: 0
has comment: http://stackoverflow.com/comment/82586928
has answer: http://stackoverflow.com/a/47817659
has comment: http://stackoverflow.com/comment/82587129
has comment: http://stackoverflow.com/comment/82587200
has comment: http://stackoverflow.com/comment/82587071
tagged with: python
tagged with: slice
type: Question
has comment: http://stackoverflow.com/comment/82587051
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82587064
has body: Is any way to get multiple elements of a list in a single statement? I did the following: import random import sys import os import time clear = lambda: os.system('cls') clear() a = [1,2,3,4,5,6,7,8,9,10] print(a[1,3,5,7,9]) Which returned: Traceback (most recent call last): File "c:/Users/D/OneDrive/Documents/Sorter/Test.py", line 10, in &lt;module&gt; print(a[1,3,5,7,9]) TypeError: list indices must be integers, not tuple Ultimately I was trying to make a while loop using this by doing: while element[0] &lt; element[1, 2, 3, 4, 5, 6, 7, 8, 9]: I know I can probably take a long way and type each scenario out but there has to be a easier way.
answer count: 1
upvote count: 1

http://stackoverflow.com/comment/82402933
score: 0
has text: Here is the link to the pdf online:
type: QuestionComment
comment on: http://stackoverflow.com/q/47703704
type: Comment

http://stackoverflow.com/comment/82531156
has text: @chepner: True, though plain `sum(gen)` would be even prettier. :-) Or if you must use `reduce`, use it with `functools.partial` to make a named special purpose reducer, e.g. `mysum = functools.partial(reduce, operator.add)`, `myproduct = functools.partial(reduce, operator.mul)`, etc., so when you use it, it's more self-documenting (`mysum(gen)` or `myproduct(gen)` is much more obvious).
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47784741

http://stackoverflow.com/comment/82362432
score: 0
comment on: http://stackoverflow.com/a/47701143
type: Comment
has text: @pankajmishra, ...and the other point is that a list of strings is actually the native format for an argv list at the operating system level -- the way other programs are started on UNIX is with the `execve` syscall, and it takes a list of C strings. Anything you do with a *single* string instead of a list is going to need to be broken down / transformed into that list before it can actually be used; passing a list yourself means you have absolutely control, instead of relying on whatever does that transformation to do it the way you intend.
type: AnswerComment

http://stackoverflow.com/q/47716682
score: 1
has title: Python / Pandas: Eliminate for Loop using 2 DataFrames
has body: First time asking a question here so hopefully I will make my issue clear. I am trying to understand how to better apply a list of scenarios (via for loop) to the same dataset and summarize results. *Note that once a scenario is applied, and I pull the relevant statistical data from dataframe and put into the summary table, I do not need to retain the information. Iterrows is painfully slow as I have tens of thousands of scenarios I want to run. Thank you for taking the time to review. I have two Pandas dataframes: df_analysts and df_results: 1) df_analysts contains a specific list of factors (e.g. TB,JK,SF,PWR) scenarios of weights (e.g. 50,50,50,50) TB JK SF PWR 0 50 50 50 50 1 50 50 50 100 2 50 50 50 150 3 50 50 50 200 4 50 50 50 250 2) df_results holds results by date and group and entrant an then ranking by each factor, finally it has the final finish result. Date GR Ent TB-R JK-R SF-R PWR-R Fin W1 W2 W2 W4 SUM(W) 0 11182017 1 1 2 1 2 1 2 1 11182017 1 2 3 2 3 2 1 2 11182017 1 3 1 3 1 3 3 3 11182017 2 1 1 2 2 1 1 4 11182017 2 2 2 1 1 2 1 3) I am using iterrows to loop through each scenario in the df_analysts dataframe apply weight scenario to each factor rank (if rank = 1, then 1.0*weight, rank = 2, then 0.68*weight, rank = 3, then 0.32*weight). Those results go into the W1-W4 columns. Sum the W1-W4 columns. Rank the SUM(W) column. Result sample below for a single scenario (e.g. 50,50,50,50) Date GR Ent TB-R JK-R SF-R PWR-R Fin W1 W2 W2 W4 SUM(W) Rank 0 11182017 1 1 2 1 2 1 1 34 50 34 50 168 1 1 11182017 1 2 3 2 3 2 3 16 34 16 34 100 3 2 11182017 1 3 1 3 1 3 2 50 16 50 16 132 2 3 11182017 2 1 2 2 2 1 1 34 34 34 50 152 2 4 11182017 2 2 1 1 1 2 1 50 50 50 34 184 1 4) Finally, for each scenario, I am creating a new dataframe for the summary results (df_summary) which logs the factor / weight scenario used (from df_analysts) and compares the RANK result to the Finish by date and group and keeps a tally where they land. Sample below (only the 50,50,50,50 scenario is …
has comment: http://stackoverflow.com/comment/82393785
has answer: http://stackoverflow.com/a/47717830
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/82393813
tagged with: loops
linked to: http://stackoverflow.com/q/47718865
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47717830
upvote count: 1
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/82393780
type: AnsweredQuestion
tagged with: pandas

http://stackoverflow.com/comment/82488303
type: QuestionComment
has text: A suggestion rather than a solution : use a dictionnary a list or some other object of your liking to store the information about users and only periodically dump the data to a file. Having your program constantly parsing through a file doesnt sound optimal.
comment on: http://stackoverflow.com/q/47763341
score: 0
type: Comment

http://stackoverflow.com/comment/82671444
score: 0
has text: Using iterator - https://stackoverflow.com/questions/46251494/best-way-to-keep-track-of-windows-with-selenium-in-ie11/46346324#46346324
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47853073

http://stackoverflow.com/comment/82528450
type: Comment
type: QuestionComment
has text: which lines makes problem ? it shows problem with bytes data - maybe you have to convert url from bytes to string.
score: 0
comment on: http://stackoverflow.com/q/47782447

http://stackoverflow.com/comment/82571189
type: QuestionComment
comment on: http://stackoverflow.com/q/47804782
has text: I can't reproduce. Your code worked fine for me on Python 3.6.1 on Linux. (That is, of course, after fixing the syntax related errors).
score: 1
type: Comment

http://stackoverflow.com/q/47716016
has body: I want to do regression with around 500 data points. For that I would like to use epsilon-SVM (sklearn.svm.SVR) with a RBF kernel. The true labels I would like to predict are discrete value from 1 to 9. The epsilon-SVM has the parameter epsilon which I would like to optimize using random search. What range of values should I try for epsilon? For example for the parameter C I'm using scipy.stats.expon(scale=100) and for the gamma parameter scipy.stats.expon(scale=.1). Second, I would also like to use elastic net (sklearn.linear_model.ElasticNet). What range (or distribution) should I choose for the alpha parameter?
tagged with: svm
answer count: 0
score: 1
tagged with: regression
upvote count: 1
tagged with: scikit-learn
favorite count: 0
type: Question
has title: Range of epsilon and alpha parameter in SVM and elastic net for hyperparameter optimization
type: UnansweredQuestion
downvote count: 0
tagged with: python

http://stackoverflow.com/q/47740302
has answer: http://stackoverflow.com/a/47740495
possible better answer: http://stackoverflow.com/a/47740495
has answer: http://stackoverflow.com/a/47740990
favorite count: 0
type: Question
upvote count: 5
score: 5
tagged with: django
tagged with: python
tagged with: django-rest-framework
has comment: http://stackoverflow.com/comment/82441756
has title: Why doesn't DRF's serializer validate PositiveSmallIntegerField?
accepted answer: http://stackoverflow.com/a/47740990
has comment: http://stackoverflow.com/comment/82440868
has comment: http://stackoverflow.com/comment/82440895
type: AnsweredQuestion
answer count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/75334301
has comment: http://stackoverflow.com/comment/82442023
tagged with: validation
has comment: http://stackoverflow.com/comment/82441913
has body: Using Django 1.11 and Django Rest Framework 3.7, I have a Person model class Person(models.Model): name = models.CharField(max_length=100) email = models.EmailField() age = models.PositiveSmallIntegerField() with a PersonSerializer class PersonSerializer(serializers.ModelSerializer): class Meta: model = Person fields = ('id', 'name', 'age', 'email') and a ListCreate view class PersonList(generics.ListCreateAPIView): queryset = Person.objects.all() serializer_class = PersonSerializer Using HTTPie, I can create a Person like this: $ http POST http://127.0.0.1:8000/api/people/ name=Alice age=26 email=alice@example.com HTTP/1.0 201 Created Allow: GET, POST, HEAD, OPTIONS Content-Length: 60 Content-Type: application/json Date: Sun, 10 Dec 2017 15:00:28 GMT Server: WSGIServer/0.1 Python/2.7.11 Vary: Accept, Cookie X-Frame-Options: SAMEORIGIN { "age": 26, "email": "alice@example.com", "id": 1, "name": "Alice" } When I create a Person with a bad email address, I get an error: $ http POST http://127.0.0.1:8000/api/people/ name=Bob age=33 email=oops HTTP/1.0 400 Bad Request Allow: GET, POST, HEAD, OPTIONS Content-Length: 42 Content-Type: application/json Date: Sun, 10 Dec 2017 15:01:08 GMT Server: WSGIServer/0.1 Python/2.7.11 Vary: Accept, Cookie X-Frame-Options: SAMEORIGIN { "email": [ "Enter a valid email address." ] } DRF knows it's an EmailField and automatically applies validation, so far so good. However, when I create a Person with a bad age (negative number), I get no error: $ http POST http://127.0.0.1:8000/api/people/ name=Charlie age=-10 email=charlie@example .com HTTP/1.0 201 Created Allow: GET, POST, HEAD, OPTIONS Content-Length: 65 Content-Type: application/json Date: Sun, 10 Dec 2017 15:03:25 GMT Server: WSGIServer/0.1 Python/2.7.11 Vary: Accept, Cookie X-Frame-Options: SAMEORIGIN { "age": -10, "email": "charlie@example.com", "id": 3, "name": "Charlie" } Now my database has been polluted with bad data. I have no problem doing the work to validate my inputs, but…

http://stackoverflow.com/a/47737040
accepted answer of: http://stackoverflow.com/q/47737029
downvote count: 0
has body: Just print nothing. for ...: print(..., end='') print() for ...: print(..., end='')
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47737029
score: 2
type: Answer
upvote count: 2

http://stackoverflow.com/q/47834225
tagged with: pandas
score: 1
answer count: 1
downvote count: 0
has body: I'm trying to count the amount of times a value in a Pandas dataframe occurs along with another value and count the amount of times for each row. This is what I mean: a t 0 a 2 1 b 4 2 c 2 3 g 2 4 b 3 5 a 2 6 b 3 Say I want to count the amount of times a occurs along with the number 2, I'd like the result to be: a t freq 0 a 2 2 1 b 4 1 2 c 2 1 3 g 2 1 4 b 3 2 5 a 2 2 6 b 3 2 The freq (frequency) column here indicates the amount of times a value in column a appears along with a value in column t. Please note that a solution that e.g. only counts the amount of times a occurs will result in a wrong frequency considering the size of my dataframe. Is there a way to achieve this in Python?
upvote count: 1
has title: Count the amount of times value A occurs with value B
accepted answer: http://stackoverflow.com/a/47834248
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47834248
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/a/47849033
score: 1
upvote count: 1
has body: The problem that you're experiencing is due to malformed HTML due to a reserved character (the less-than symbol &lt;) in place of a &amp;lt;. One workaround to use BeautifulSoup with the html5lib parser backend on your response like this (as suggested in this answer). By overwriting your response's body with the parsed content you should be able to use your current code: from bs4 import BeautifulSoup from scrapy.http import TextResponse # parse response body with BeautifulSoup soup = BeautifulSoup(response.body, "html5lib") # overwrite response body response = TextResponse(url="my HTML string", body=str(soup)) # from here on use your code event = response.xpath('//title//text()').extract() ... Hope this helps!
answers question: http://stackoverflow.com/q/47840862
type: Answer
downvote count: 0

http://stackoverflow.com/a/47737047
accepted answer of: http://stackoverflow.com/q/47737034
downvote count: 0
has body: This is completely idiomatic in Python (and a lot of other languages really), it works exactly as you'd want: &gt;&gt;&gt; def f(x): ... return x+5 ... &gt;&gt;&gt; def g(x): ... return x*3 ... &gt;&gt;&gt; f(g(5)) # (5*3) + 5 20 &gt;&gt;&gt; f(g(4)) # (4*3) + 5 17 &gt;&gt;&gt; x = np.array([1, 2, 3, 4]) &gt;&gt;&gt; f(g(x)) # ([1, 2, 3, 4]*3) + 5 array([ 8, 11, 14, 17]) As long as the return values of the function g can be used as input to f, you're fine to do it just as you'd write it: f(g(input)).
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47737034
upvote count: 2
type: Answer
score: 2

http://stackoverflow.com/comment/82413806
has text: Good idea if these functions will be reused.... I would not 1) Create a generator for a file, it already is one. 2) fpairs() may raise an unhandled StopIteration.
type: Comment
comment on: http://stackoverflow.com/a/47726522
score: 0
type: AnswerComment

http://stackoverflow.com/q/47810702
has title: Why can't I convert floats in an array into integers?
has answer: http://stackoverflow.com/a/47810939
has comment: http://stackoverflow.com/comment/82582541
has answer: http://stackoverflow.com/a/47810996
has comment: http://stackoverflow.com/comment/82583135
has comment: http://stackoverflow.com/comment/82582594
has comment: http://stackoverflow.com/comment/82582652
tagged with: python
has comment: http://stackoverflow.com/comment/82582778
has body: I want to convert the elements(float) into integer, but it seems not working. #get an array from a matrix pre_dataY = data[:, -1] print(pre_dataY) # float to integer for i in range(len(pre_dataY): pre_dataY[i]=int(pre_dataY[i]) print(pre_dataY) however, the output is : [ 3. 2. 9. ..., 7. 5. 5.] [ 3. 2. 9. ..., 7. 5. 5.] I don't see why that is?
type: Question
tagged with: integer
tagged with: numpy
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/82582633
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/4389517

http://stackoverflow.com/q/47804627
tagged with: python
has title: pylint disabling a single line of code just produces another pylint error
type: AnsweredQuestion
answer count: 3
has answer: http://stackoverflow.com/a/54052876
accepted answer: http://stackoverflow.com/a/54052876
has comment: http://stackoverflow.com/comment/82570823
has answer: http://stackoverflow.com/a/61621561
downvote count: 1
has comment: http://stackoverflow.com/comment/82570802
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47804666
possible better answer: http://stackoverflow.com/a/47804666
score: 5
upvote count: 6
tagged with: pylint
has body: The documentation in section 4.1 clearly states: https://pylint.readthedocs.io/en/latest/faq.html#message-control 4.1 Is it possible to locally disable a particular message? Yes, this feature has been added in Pylint 0.11. This may be done by adding “#pylint: disable=some-message,another-one” at the desired block level or at the end of the desired line of code Great! but it doesn't work. Boo. I get the the following pylint error for the following line of code W: 26, 2: Redefining built-in 'zip' (redefined-builtin) &nbsp; try: from itertools import izip as zip # pylint: disable=bad-builtin except ImportError: pass But pylint just complains even louder about my attempt to shut it up: E: 26, 0: Bad option value 'bad-builtin' (bad-option-value) I've also tried the error code # pylint: disable=W0141, that also produces a similar error. Any idea what I'm doing wrong?

http://stackoverflow.com/comment/82536701
type: AnswerComment
has text: Deceptively elegant, assuming you do not need the previous `stock` values afterward
type: Comment
comment on: http://stackoverflow.com/a/47787839
score: 0

http://stackoverflow.com/q/47845448
tagged with: keras
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/91774571
has comment: http://stackoverflow.com/comment/82655052
has answer: http://stackoverflow.com/a/53826668
has body: For a school project, I'm trying to predict data using the keras framework, but it's returning 'nan' loss and values when I try to get predicted data. Source code : X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=5) # create model model = Sequential() model.add(Dense(950, input_shape=(425,), activation='relu')) model.add(Dense(425, activation='relu')) model.add(Dense(200, activation='relu')) model.add(Dense(50, activation='relu')) model.add(Dense(1, activation='sigmoid')) # Compile model sgd = optimizers.SGD(lr=0.1, decay=1e-6, momentum=0.9, nesterov=True) model.compile(loss='mean_squared_error', optimizer='sgd') # Fit the model model.fit(X_train, y_train, epochs=20, batch_size=1, verbose=1) #evaluate the model y_pred = model.predict(X_test) score = model.evaluate(X_test, y_test,verbose=1) print(score) # calculate predictions predictions = model.predict(X_pred) Data : X_train and X_test are (panda)dataframes of 5000 rows(nber of samples) * 425 columns (number of dimensions). y_train and y_test look like : array([ 1.17899644, 1.46080518, 0.9662137 , ..., 2.40157461, 0.53870386, 1.3192718 ]) Can you help me with that ? Thank you for you help!
has answer: http://stackoverflow.com/a/50887725
score: 5
tagged with: python
upvote count: 6
answer count: 4
has answer: http://stackoverflow.com/a/52900555
type: Question
has title: python - returning nan when trying to predict with Keras
has answer: http://stackoverflow.com/a/47846727
type: UnansweredQuestion
tagged with: machine-learning

http://stackoverflow.com/a/47823104
upvote count: 1
has body: import numpy as np # create sample matrix `m` m = np.matrix([[0.5, 0.75, 1], [0.75, 1, 1.25], [1, 1.25, 1.5]]) # convert matrix `m` to a 'flat' matrix m_flat = m.flatten() print(m_flat) # `m_flat` is still a matrix, in case you need an array: m_flat_arr = np.squeeze(np.asarray(m_flat)) print(m_flat_arr) The snippet uses .flatten(), .asarray() and .squeeze() to convert the original matrix m being matrix([[ 0.5 , 0.75, 1. ], [ 0.75, 1. , 1.25], [ 1. , 1.25, 1.5 ]]) into an array m_flat_arr of: array([ 0.5 , 0.75, 1. , 0.75, 1. , 1.25, 1. , 1.25, 1.5 ])
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/47822994
type: Answer

http://stackoverflow.com/a/47819435
has comment: http://stackoverflow.com/comment/82601381
has comment: http://stackoverflow.com/comment/82603743
upvote count: 1
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/82601469
answers question: http://stackoverflow.com/q/47819398
has comment: http://stackoverflow.com/comment/135780330
downvote count: 0
has body: Try this import sys sys.path.append('/absolute/path/to/modified/matplotlib') import matplotlib # modified
has comment: http://stackoverflow.com/comment/82601653

http://stackoverflow.com/comment/82431398
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47735434
has text: You never use `res_up`, by the way. Do you need it?
score: 0

http://stackoverflow.com/q/47716776
score: 1
answer count: 1
tagged with: user-interface
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
type: AnsweredQuestion
has title: Converting Pandas DataFrame to tkinter object
tagged with: python
has comment: http://stackoverflow.com/comment/82395166
has body: I am trying to create a Pandas' DataFrame GUI in tkinter that would update the moment the user changes the value of the cell (each cell is an Entry). I thought that converting the DataFrame into tkinter variables (tk.StringVar, tk.IntVar...) would be the best way to achieve that. My problem: I am not sure how to convert dataframe into those objects. I tried using the astype function, but it doesn't seem to convert the type. My questions: 1) how to convert dataframe into tkinter variables? 2) is converting dataframe into ttkinter variables the best way to make the dataframe update instantly?
accepted answer: http://stackoverflow.com/a/47717639
tagged with: tkinter
tagged with: pandas
has answer: http://stackoverflow.com/a/47717639
has comment: http://stackoverflow.com/comment/82395332

http://stackoverflow.com/comment/82495439
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47767194
has text: These filetypes aren't natively supported on python. If you try opening those filetypes in a notepad you will see that they are random blurbs

http://stackoverflow.com/comment/88071873
comment on: http://stackoverflow.com/a/50529025
has text: @LonelyNeuron looks like an alternative to the other answer
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/47813994
tagged with: dataframe
has answer: http://stackoverflow.com/a/47814086
has title: Python Pandas, How to replace values that have a count smaller than X
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47814083
answer count: 2
downvote count: 0
tagged with: python
possible better answer: http://stackoverflow.com/a/47814086
has answer: http://stackoverflow.com/a/47814083
type: AnsweredQuestion
score: 3
has body: Here's an example: A 0 V1 1 V1 2 V2 3 v4 4 v4 5 v7 And I would want to end up with something like this: A 0 V1 1 V1 2 np.NaN 3 v4 4 v4 5 np.NaN Basically it would be something like this: df.A[df.A.value_counts() &lt; 2] = np.NaN
tagged with: pandas
upvote count: 3

http://stackoverflow.com/a/48059894
score: 15
upvote count: 15
downvote count: 0
has body: First of all, you need to decide whether you want to maintain a persistent connection to MySQL. The latter performs better, but need a little maintenance. Default wait_timeout in MySQL is 8 hours. Whenever a connection is idle longer than wait_timeout it's closed. When MySQL server is restarted, it also closes all established connections. Thus if you use a persistent connection, you need to check before using a connection if it's alive (and if not, reconnect). If you use per request connection, you don't need to maintain the state of connection, because connection are always fresh. Per request connection A non-persistent database connection has evident overhead of opening connection, handshaking, and so on (for both database server and client) per each incoming HTTP request. Here's a quote from Flask's official tutorial regarding database connections: Creating and closing database connections all the time is very inefficient, so you will need to keep it around for longer. Because database connections encapsulate a transaction, you will need to make sure that only one request at a time uses the connection. An elegant way to do this is by utilizing the application context. Note, however, that application context is initialised per request (which is kind of veiled by efficiency concerns and Flask's lingo). And thus, it's still very inefficient. However it should solve your issue. Here's stripped snippet of what it suggests as applied to pymysql: import pymysql from flask import Flask, g, request app = Flask(__name__) def connect_db(): return pymysql.connect( user = 'guest', password = '', database = 'sakila', autocommit = True, charset = 'utf8mb4', cursorclass = pymysql.cursors.DictCursor) def get_db(): '''Opens a new database connection per request.''' if not hasattr(g, 'db'): g.db = connect_db() return g.db @app.teardown_appcontext def close_db(error): '''Closes the database connection at the end of request.''' if hasattr(g, 'db'): g.db.close() @app.route('/') def he…
answers question: http://stackoverflow.com/q/47711689
type: Answer

http://stackoverflow.com/q/47724696
type: UnansweredQuestion
score: 10
tagged with: python
upvote count: 11
has body: I would like to make variables displayed with colours. This is how it looks: This is how I want it to be: Looking through here, I cannot find any settings that allow me to change this.
has answer: http://stackoverflow.com/a/47724866
has title: Make VSCode Variables have Colour
has answer: http://stackoverflow.com/a/57318412
has answer: http://stackoverflow.com/a/77741070
has answer: http://stackoverflow.com/a/69553692
has answer: http://stackoverflow.com/a/47724784
tagged with: syntax-highlighting
downvote count: 1
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/47272835
tagged with: visual-studio-code
answer count: 5

gmail
type: Tag
tag name: gmail
tags question: http://stackoverflow.com/q/47842368
tags question: http://stackoverflow.com/q/47847471

http://stackoverflow.com/comment/82610351
score: 0
has text: Can each key have multiple values? Or only one value? As an extension, in your CSV file, will each column have only one row? Or will it have multiple rows?
type: Comment
comment on: http://stackoverflow.com/q/47823477
type: QuestionComment

http://stackoverflow.com/comment/82567045
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47802722
type: Comment
has text: I assume that n is a kind of delimiter which he can have as a variable instead of hardcoding. Keeping `n` so as to keep the answer short.

http://stackoverflow.com/a/50177664
has comment: http://stackoverflow.com/comment/103537039
has comment: http://stackoverflow.com/comment/107380793
has comment: http://stackoverflow.com/comment/121583792
has comment: http://stackoverflow.com/comment/97737817
answers question: http://stackoverflow.com/q/47841985
has comment: http://stackoverflow.com/comment/95066909
has comment: http://stackoverflow.com/comment/107384518
has body: You can incorporate some async functionality into Flask apps without having to completely convert them to asyncio. import asyncio from flask import Flask async def abar(a): print(a) loop = asyncio.get_event_loop() app = Flask(__name__) @app.route("/") def notify(): loop.run_until_complete(abar("abar")) return "OK" if __name__ == "__main__": app.run(debug=False, use_reloader=False) This will block the Flask response until the async function returns, but it still allows you to do some clever things. I've used this pattern to perform many external requests in parallel using aiohttp, and then when they are complete, I'm back into traditional flask for data processing and template rendering. import aiohttp import asyncio import async_timeout from flask import Flask loop = asyncio.get_event_loop() app = Flask(__name__) async def fetch(url): async with aiohttp.ClientSession() as session, async_timeout.timeout(10): async with session.get(url) as response: return await response.text() def fight(responses): return "Why can't we all just get along?" @app.route("/") def index(): # perform multiple async requests concurrently responses = loop.run_until_complete(asyncio.gather( fetch("https://google.com/"), fetch("https://bing.com/"), fetch("https://duckduckgo.com"), fetch("http://www.dogpile.com"), )) # do something with the results return fight(responses) if __name__ == "__main__": app.run(debug=False, use_reloader=False)
type: Answer
has comment: http://stackoverflow.com/comment/97998671
score: 53
downvote count: 4
has comment: http://stackoverflow.com/comment/120436661
upvote count: 57

http://stackoverflow.com/comment/82667330
has text: @AK47 It's been almost 10 years. It's about time our discourse shifts its default assumption of version to be 3, not 2.
comment on: http://stackoverflow.com/q/47851402
score: 3
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47731763
type: Answer
has comment: http://stackoverflow.com/comment/82424168
has body: You will need to construct an HTTP request. Example: GET / HTTP/1.1\n\n Try this: from socket import AF_INET, SOCK_STREAM, SOL_SOCKET, SO_REUSEADDR import threading, socket, time, sys s = socket.socket(AF_INET,SOCK_STREAM) def connectTO(host,port): connect = False count = 0 totalCount = 0 while connect!= True: try: s.connect((host,port)) connect = True print("You have just succesfully connected to the node.js server") except OSError: count += 1 totalCount += 1 if totalCount == 40 and count == 4: print("Error: 404. Connection failed repeatedly") sys.exit(0) elif count == 4: print("Connection failed, retrying...") count = 0 else: pass connectTO("IP_OF_NODE.jS_SERVER_GOES_HERE",777) message = "GET / HTTP/1.1\n\n" s.send(message.encode("utf-8")) while True: try: data, addr = s.recvfrom(1024) if data == "": pass else: print(data.decode()) except ConnectionResetError: print("it seems like we can't reach the server anymore..") print("This could be due to a change in your internet connection or the server.") s.close() Read this to learn more about HTTP. Now, I would recommend using this python lib to do what you're trying to do. It makes things much easier. However, if you are 100% set on using raw sockets, then you should make the node server use raw sockets as well. (Assuming you will only be connecting via python). Here is an excellent tutorial
score: 2
upvote count: 2
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47731485
answers question: http://stackoverflow.com/q/47731485

http://stackoverflow.com/a/47746373
score: 3
type: Answer
has comment: http://stackoverflow.com/comment/82453143
answers question: http://stackoverflow.com/q/47746286
has comment: http://stackoverflow.com/comment/82452939
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47746286
type: AcceptedAnswer
has body: The problem is that str.replace() doesn't allow you to specify that you only want to match whole words (or phrases). The re module allows you to use regular expressions (regex) for pattern matching. With regex, you can specify word boundaries using the \b escape. Place the \b escape before and after your phrases to cause the match to only occur at word boundaries. The re.sub() function works like the str.replace() method and you can use it in your code like: import re mylist = ['and rock', 'shake well', 'the'] mystring = "the sand rock need to be mixed and shake well" for item in mylist: mystring = re.sub(r"\b{}\b".format(item), "", mystring) print(mystring) Out[6]: ' sand rock need to be mixed and '
has comment: http://stackoverflow.com/comment/82453036
upvote count: 3

http://stackoverflow.com/a/47733701
type: Answer
score: 1
has body: names = [('a', '1\n'), ('b', '2\n'), ('c', '3\n'), ('d', '4\n')] archive_out = open("output.txt", 'w') for line in names: archive_out.write(str(", ".join(line))) archive_out.close()
answers question: http://stackoverflow.com/q/47733599
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/82388906
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47713150
has text: 573 columns will always be painful. You''ll have to invent 573 names for them. And 573 data types. And 573 meanings.
type: Comment

http://stackoverflow.com/comment/82498650
type: Comment
type: AnswerComment
has text: @creative_sh That's a big question. What I will say is, there is confidence in the system, when the model is not overfitting on the learned examples. What this simply means is that the learned model should have a good predictive accuracy on the validation set. The fluctuation in the loss is a very normal observation when training the model. The important thing here is the trend, and in this case, it is downward, which is a good thing.
score: 0
comment on: http://stackoverflow.com/a/47767686

http://stackoverflow.com/comment/119247380
comment on: http://stackoverflow.com/q/47725161
has text: Also can you add result image you are getting from existing code and results you are expecting.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82502138
has text: are the images by any chance jpgs?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47770575
score: 0

http://stackoverflow.com/comment/82562535
type: QuestionComment
comment on: http://stackoverflow.com/q/47800252
score: 1
has text: Although, again I ask, did you *mean* to skip the last elements in your lists on ever loop? i.e. the effect of doing `for i in range(len(x) - 1)` will iterate over all but the *last* index in some list `x`... But I think you are getting repetition because you are looping over the *product* of your two lists, where I think you want every distinct pair instead...
type: Comment

http://stackoverflow.com/a/47764201
accepted answer of: http://stackoverflow.com/q/47763958
type: Answer
has body: You can try below aggregation in 3.4 mongo version. The idea is to $zip together series and year array with $map to create a array of document with series and year key value pair followed by $unwind &amp; $group to create unique combination. $replaceRoot to promote the id to the top level db.collection_name.aggregate([ { "$project": { "series_and_year_list": { "$map": { "input": { "$zip": { "inputs": [ { "$split": [ "$book.series", ", " ] }, { "$split": [ "$book.year", ", " ] } ] } }, "as": "zipped", "in": { "series": { "$arrayElemAt": [ "$$zipped", 0 ] }, "year": { "$arrayElemAt": [ "$$zipped", 1 ] } } } } } }, { "$unwind": "$series_and_year_list" }, { "$group": { "_id": { "series": "$series_and_year_list.series", "year": "$series_and_year_list.year" } } }, { "$replaceRoot": { "newRoot": "$_id" } } ])
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47763958

http://stackoverflow.com/q/47736253
tagged with: python
tagged with: sqlalchemy
type: AnsweredQuestion
score: 0
tagged with: primary-key
accepted answer: http://stackoverflow.com/a/47737592
has title: add a bunch of rows from csv, then keep counting primary key where that left off (postgres, flask-sqlalchemy)
has answer: http://stackoverflow.com/a/47737592
answer count: 1
has body: I have a postgres database that I'm mainly interacting with in python using sqlalchemy (via flask-sqlalchemy). I'd like to be able to add the initial data for my tables directly in psql from a CSV, and then be able to programmatically add new rows later. But I'm having problems with my primary key. Specifically, if I include it in the csv file for the initial data, then when I try to add new rows programmatically, the new rows try to start the primary key at 1, and promptly fail because that key already exists. Details and code The relevant part of my sqlalchemy code: class Contracts(db.Model): __tablename__ = "contracts" id = db.Column(db.Integer, primary_key=True) contract = db.Column(db.Text()) # a bunch of other columns that are irrelevant follow here def __init__(self, contract, url, firstadded, firstaddedby): self.contract = contract # and all the other irrelevant columns. # not ID, because that's to be auto-incremented. I then create the tables from the python shell with: &gt;&gt;&gt; from app import db &gt;&gt;&gt; db.create_all() Confirming that this produced what I expected, the relevant parts of the first two rows of \d+ contracts in psql: id | integer | not null default nextval('contracts_id_seq'::regclass) contract| text | So then, I have a csv file as follows: 1,this is a word,http://foo.bar,never,test,f,,,,, 2,this is a word or t20,http://foo.baz,never,test,f,,,,, which I add to the contracts table from psql as follows: \copy contracts from 'path/to/csv/file' with (format csv); and, as expected, selecting from the table reveals two rows, with ids 1 and 2. But then suppose I open up a shell and try to enter some data with the sqlalchemy code: &gt;&gt;&gt;from database import Contracts &gt;&gt;&gt; k = Contracts("here's some text", "url column", "firstadded column", "firstaddedby column") &gt;&gt;&gt; db.session.add(k) &gt;&gt;&gt; db.session.commit() but it fails with the expected error (in relevant part) (psycopg2.IntegrityError) duplicate key value v…
tagged with: flask-sqlalchemy
tagged with: postgresql
type: Question

python-3.6
tags question: http://stackoverflow.com/q/47822740
tags question: http://stackoverflow.com/q/47736282
tags question: http://stackoverflow.com/q/47729512
tags question: http://stackoverflow.com/q/47850786
tags question: http://stackoverflow.com/q/47825647
tags question: http://stackoverflow.com/q/47852883
tags question: http://stackoverflow.com/q/47831444
tags question: http://stackoverflow.com/q/47848852
tags question: http://stackoverflow.com/q/47702785
tags question: http://stackoverflow.com/q/47746239
tags question: http://stackoverflow.com/q/47710334
tags question: http://stackoverflow.com/q/47735944
tags question: http://stackoverflow.com/q/47728713
tags question: http://stackoverflow.com/q/47816949
tags question: http://stackoverflow.com/q/47739764
tags question: http://stackoverflow.com/q/47699695
tags question: http://stackoverflow.com/q/47833578
tags question: http://stackoverflow.com/q/47792905
tags question: http://stackoverflow.com/q/47808890
tags question: http://stackoverflow.com/q/47731301
tags question: http://stackoverflow.com/q/47854507
type: Tag
tags question: http://stackoverflow.com/q/47738690
tags question: http://stackoverflow.com/q/47718184
tag name: python-3.6
tags question: http://stackoverflow.com/q/47740953
tags question: http://stackoverflow.com/q/47840138
tags question: http://stackoverflow.com/q/47824532
tags question: http://stackoverflow.com/q/47776339
tags question: http://stackoverflow.com/q/47843535
tags question: http://stackoverflow.com/q/47836837
tags question: http://stackoverflow.com/q/47827666
tags question: http://stackoverflow.com/q/47774664
tags question: http://stackoverflow.com/q/47738532
tags question: http://stackoverflow.com/q/47744596
tags question: http://stackoverflow.com/q/47850671
tags question: http://stackoverflow.com/q/47845048

http://stackoverflow.com/a/47852899
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47852883
answers question: http://stackoverflow.com/q/47852883
type: Answer
has body: This is actually the expected output. You should use del instead. del my_list[4] The reason it was not working is that using this line: my_list.remove(my_list[4]) translates in this line: my_list.remove(3) since my_list[4] return 3, which will then delete first occurence of 3 in the list.
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/comment/82637740
comment on: http://stackoverflow.com/q/47834140
has text: Have you looked at the MATLAB code. I suspect it is a `.m` file (readable MATLAB). The Octave version is readable (which I could post if needed). My memory is that this was put into MATLAB way back, more as a show piece, rather than anything sophisticated or useful.
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82578315
score: 0
has text: I checked and it worked, can you give me your command when execute file test.py
comment on: http://stackoverflow.com/q/47807902
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82642636
type: Comment
comment on: http://stackoverflow.com/a/47826432
has text: It should never happen. The customer will use a credit card (which is where we get the zipcode data from) and generally speaking, no one has 2 different cards with 2 different locations. I haven't seen it happen yet, out of millions of transactions.
score: 0
type: AnswerComment

selenium-webdriver
tags question: http://stackoverflow.com/q/47832693
tags question: http://stackoverflow.com/q/47707586
tags question: http://stackoverflow.com/q/47754827
tags question: http://stackoverflow.com/q/47828773
tags question: http://stackoverflow.com/q/47710581
tags question: http://stackoverflow.com/q/47753932
tags question: http://stackoverflow.com/q/47749117
tags question: http://stackoverflow.com/q/47710452
tags question: http://stackoverflow.com/q/47792991
tags question: http://stackoverflow.com/q/47807790
tags question: http://stackoverflow.com/q/47841851
tags question: http://stackoverflow.com/q/47710144
tags question: http://stackoverflow.com/q/47768262
tags question: http://stackoverflow.com/q/47782650
tags question: http://stackoverflow.com/q/47728687
tags question: http://stackoverflow.com/q/47722143
tags question: http://stackoverflow.com/q/47772143
tags question: http://stackoverflow.com/q/47765195
tags question: http://stackoverflow.com/q/47803587
tags question: http://stackoverflow.com/q/47712425
tags question: http://stackoverflow.com/q/47812933
tags question: http://stackoverflow.com/q/47745226
type: Tag
tags question: http://stackoverflow.com/q/47720832
tags question: http://stackoverflow.com/q/47854832
tags question: http://stackoverflow.com/q/47772083
tags question: http://stackoverflow.com/q/47821926
tags question: http://stackoverflow.com/q/47770144
tags question: http://stackoverflow.com/q/47784644
tags question: http://stackoverflow.com/q/47735375
tags question: http://stackoverflow.com/q/47835771
tag name: selenium-webdriver
tags question: http://stackoverflow.com/q/47783834

http://stackoverflow.com/comment/82552504
has text: I'm setting it to True
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47784351
type: Comment

http://stackoverflow.com/q/47720207
tagged with: graph
has comment: http://stackoverflow.com/comment/82400978
tagged with: graph-theory
score: 3
linked to: http://stackoverflow.com/q/8176298
has comment: http://stackoverflow.com/comment/82401250
has title: Are two graphs isomorphic in python, no imports
has comment: http://stackoverflow.com/comment/82401313
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82401408
has comment: http://stackoverflow.com/comment/82401354
tagged with: python
has comment: http://stackoverflow.com/comment/82401570
has comment: http://stackoverflow.com/comment/82401373
has comment: http://stackoverflow.com/comment/82402706
has comment: http://stackoverflow.com/comment/82402226
upvote count: 3
has comment: http://stackoverflow.com/comment/82401885
has answer: http://stackoverflow.com/a/47814378
answer count: 1
downvote count: 0
tagged with: isomorphism
has body: I am writing a function is_iso(graph1, graph2) that takes in two graphs as its input, and then determines whether or not the two graphs are isomorphic. I can assume that the two graphs will have the same number of vertices and that the names used on the vertices will be the same. is_iso({“A” : [“B”, “C”], “B” : [“A”], “C” : [“A”]}, {“A” : [“B”], “B” : [“A”, “C”], “C” : [“B”]}) should return True is_iso({“A” : [“B”, “C”], “B” : [“A”, “C”], “C” : [“A”, “B”]}, {“A” : [“B”, “C”], “B” : [“A”], “C” :[“A”]}) should return False def is_iso(graph1,graph2): for vertex in graph1:#loops through every vertex in graph1 seq1 += [len(graph1[vertex])]#adds the degree of each vertex to the list for vertex in graph2: #loops through every vertex in graph2 seq2 += [len(graph2[vertex])]#adds the degree of each vertex to the list return sorted(seq1) == sorted(seq2) All my method currently checks if the degree sequence is the same but graphs can have the same degree sequence and not be isomorphic. I am not sure how to finish checking from here. I am not allowed to import any libraries. Any help is greatly appreciated!
favorite count: 0
has comment: http://stackoverflow.com/comment/82401434
type: Question

http://stackoverflow.com/comment/82449555
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47730630
has text: Please post something like a [MCVE]. Hard to tell what is going wrong there, or even what kind of data you are talking about.

http://stackoverflow.com/comment/82409521
comment on: http://stackoverflow.com/a/47723651
has text: It is not working and I am getting some error.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/82631827
comment on: http://stackoverflow.com/q/47834112
type: Comment
type: QuestionComment
has text: Yes, but from what i've learnt, you can't really divide by a 'timedelta', hence why it wasn't working when I tried.
score: 0

excel
tags question: http://stackoverflow.com/q/47735845
tags question: http://stackoverflow.com/q/47700554
tags question: http://stackoverflow.com/q/47851698
tags question: http://stackoverflow.com/q/47829726
tags question: http://stackoverflow.com/q/47705416
tags question: http://stackoverflow.com/q/47837571
tags question: http://stackoverflow.com/q/47848037
tag name: excel
tags question: http://stackoverflow.com/q/47703314
tags question: http://stackoverflow.com/q/47801684
tags question: http://stackoverflow.com/q/47698751
tags question: http://stackoverflow.com/q/47761063
tags question: http://stackoverflow.com/q/47775000
tags question: http://stackoverflow.com/q/47801945
tags question: http://stackoverflow.com/q/47732129
type: Tag
tags question: http://stackoverflow.com/q/47834025
tags question: http://stackoverflow.com/q/47743741
tags question: http://stackoverflow.com/q/47788664
tags question: http://stackoverflow.com/q/47786882
tags question: http://stackoverflow.com/q/47840376
tags question: http://stackoverflow.com/q/47728022
tags question: http://stackoverflow.com/q/47760505
tags question: http://stackoverflow.com/q/47737220
tags question: http://stackoverflow.com/q/47843681
tags question: http://stackoverflow.com/q/47782501
tags question: http://stackoverflow.com/q/47747532
tags question: http://stackoverflow.com/q/47738451
tags question: http://stackoverflow.com/q/47719585
tags question: http://stackoverflow.com/q/47701992
tags question: http://stackoverflow.com/q/47760035
tags question: http://stackoverflow.com/q/47767076
tags question: http://stackoverflow.com/q/47760138
tags question: http://stackoverflow.com/q/47776745
tags question: http://stackoverflow.com/q/47743714
tags question: http://stackoverflow.com/q/47802995
tags question: http://stackoverflow.com/q/47837469
tags question: http://stackoverflow.com/q/47820002
tags question: http://stackoverflow.com/q/47810367
tags question: http://stackoverflow.com/q/47782402

http://stackoverflow.com/comment/82608388
type: Comment
score: 0
type: AnswerComment
has text: @Gary02127 Okay, that makes sense. I was thinking it would probably come up empty without a third argument in range(), but wanted to make sure I got the semantics right for my exam. Thank you!
comment on: http://stackoverflow.com/a/47822757

http://stackoverflow.com/q/47786568
favorite count: 0
upvote count: 17
type: Question
answer count: 9
has comment: http://stackoverflow.com/comment/82546786
has answer: http://stackoverflow.com/a/47786737
has answer: http://stackoverflow.com/a/47786969
type: UnansweredQuestion
has title: Triple nested lists Python
has answer: http://stackoverflow.com/a/47805047
has answer: http://stackoverflow.com/a/47794611
has answer: http://stackoverflow.com/a/47795452
downvote count: 5
tagged with: python
has answer: http://stackoverflow.com/a/47786626
score: 12
has answer: http://stackoverflow.com/a/47786607
has comment: http://stackoverflow.com/comment/82574281
tagged with: list
has body: I have a block of code that gives me a list that has some triple nested lists within it: my_list = ['item1','item2', 'item3', 'item4'] And I would like to make it: my_list = [['item1','item2'], ['item3', 'item4']] Any suggestions?
has answer: http://stackoverflow.com/a/47786942
has answer: http://stackoverflow.com/a/47786644
has comment: http://stackoverflow.com/comment/82534198
has comment: http://stackoverflow.com/comment/82568108

http://stackoverflow.com/q/47777585
has answer: http://stackoverflow.com/a/47779829
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47785030
tagged with: math
downvote count: 0
has comment: http://stackoverflow.com/comment/82519238
tagged with: image-processing
has answer: http://stackoverflow.com/a/47834583
possible better answer: http://stackoverflow.com/a/47834583
score: 8
upvote count: 8
favorite count: 0
has answer: http://stackoverflow.com/a/47820911
has answer: http://stackoverflow.com/a/47777866
type: Question
has answer: http://stackoverflow.com/a/47779255
tagged with: angle
has body: I'm working on a project that can calculate the angle of an elbow joint by image. The part I'm struggling on is the image processing. Currently doing this in Python using an Intel RealSense R200 (although it can be taken that I'm using an image input). I'm attempting to detect the edges of the left image, such that I can get the center image, aiming to extract the outer contour (right image): Knowing that the sides of the two pipes coming out of the angle will be parallel (two orange sides and two green sides are parallel to the same colour)... ... I'm trying to construct 2 loci of points equidistant from the two pairs of colours and then 'extrapolate to the middle' in order to calculate the angle: I've got as far as the second image and, unreliably, as far as the third image. I'm very open to suggestions and would be hugely grateful of any assistance.
has title: Detecting outer most-edge of image and plotting based on it
tagged with: python
answer count: 6
accepted answer: http://stackoverflow.com/a/47820911
tagged with: opencv

http://stackoverflow.com/q/47781034
score: 0
tagged with: reddit
answer count: 1
has title: Praw 4.4/5.2 "'Reddit' object has no attribute 'subreddit'"
has comment: http://stackoverflow.com/comment/82962462
has answer: http://stackoverflow.com/a/62383052
type: Question
has comment: http://stackoverflow.com/comment/82523528
type: UnansweredQuestion
has body: I've tried everything and am at my wits end. I keep getting an error that reads "AttributeError: 'Reddit' object has no attribute 'subreddit'" I had praw 5.2 installed, then I uninstalled and manually installed praw 4.4 and both times it keeps telling me "Version 2.1.18 of praw is outdated. Version 5.2.0 was released Tuesday October 24, 2017." and when I edit the below: reddit = praw.Reddit(client_id='8888', client_secret='8888', user_agent='8888_API:v1') subreddit= r.subreddit('learnpython') to reddit = praw.Reddit(client_id='8888', client_secret='8888', user_agent='8888_API:v1') subreddit= r.get_subreddit('learnpython') i.e. the old syntax, it runs fine. So it seems to think I have praw 2.1.18 even though I don't. Full w/ traceback: runfile('C:/Users/..../rAPI.py', wdir='C:/Users/....') Version 2.1.18 of praw is outdated. Version 5.2.0 was released Tuesday October 24, 2017. Traceback (most recent call last): File "&lt;ipython-input-88-ab9c8af5b7e2&gt;", line 1, in &lt;module&gt; runfile('C:/Users/..../rAPI.py', wdir='C:/Users/....') File "C:\Users\....\AppData\Local\Continuum\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 866, in runfile execfile(filename, namespace) File "C:\Users\....\AppData\Local\Continuum\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile exec(compile(f.read(), filename, 'exec'), namespace) File "C:/Users/..../rAPI.py", line 14, in &lt;module&gt; subreddit= r.subreddit('learnpython') AttributeError: 'Reddit' object has no attribute 'subreddit'
tagged with: python
tagged with: praw

http://stackoverflow.com/q/47846686
tagged with: performance
has comment: http://stackoverflow.com/comment/82657494
has body: Yesterday I wrote two possible reverse functions for lists to demonstrate some one different ways to do list inversion. But then I noticed that the function using branching recursion (rev2) is actually faster than the function using linear recursion (rev1), even though the branching function takes more calls to finish and the same number of calls (minus one) of non-trivial calls (that are actually more computation intensive) than the non-trivial calls of the linearly recursive function. Nowhere am I explicitly triggering parallelism, so where does the performance difference come from that makes a function with more calls that are more involved take less time? from sys import argv from time import time nontrivial_rev1_call = 0 # counts number of calls involving concatentation, indexing and slicing nontrivial_rev2_call = 0 # counts number of calls involving concatentation, len-call, division and sclicing length = int(argv[1]) def rev1(l): global nontrivial_rev1_call if l == []: return [] nontrivial_rev1_call += 1 return rev1(l[1:])+[l[0]] def rev2(l): global nontrivial_rev2_call if l == []: return [] elif len(l) == 1: return l nontrivial_rev2_call += 1 return rev2(l[len(l)//2:]) + rev2(l[:len(l)//2]) lrev1 = rev1(list(range(length))) print ('Calls to rev1 for a list of length {}: {}'.format(length, nontrivial_rev1_call)) lrev2 = rev2(list(range(length))) print ('Calls to rev2 for a list of length {}: {}'.format(length, nontrivial_rev2_call)) print() l = list(range(length)) start = time() for i in range(1000): lrev1 = rev1(l) end = time() print ("Average time taken for 1000 passes on a list of length {} with rev1: {} ms".format(length, (end-start)/1000*1000)) start = time() for i in range(1000): lrev2 = rev2(l) end = time() print ("Average time taken for 1000 passes on a list of length {} with rev2: {} ms".format(length, (end-start)/1000*1000)) Example call: $ python reverse.py 996 calls to rev1 for a list of length 996: 996 calls to rev2 for a list of length 996: 995 …
has title: Why is branching recursion faster than linear recursion (example: list inversion)
tagged with: python
type: Question
has comment: http://stackoverflow.com/comment/82657391
upvote count: 3
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/82657438
accepted answer: http://stackoverflow.com/a/47846749
has comment: http://stackoverflow.com/comment/82657478
favorite count: 0
has answer: http://stackoverflow.com/a/47846749
type: AnsweredQuestion
tagged with: recursion
score: 3

http://stackoverflow.com/q/47768406
accepted answer: http://stackoverflow.com/a/47774712
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47774712
has comment: http://stackoverflow.com/comment/82500732
has body: I have a dataframe that looks like this: A B C 0 1 2 PRODUCT_1 1 3 2 PRODUCT_2 2 3 2 PRODUCT_4 3 3 2 PRODUCT_5 4 5 2 PRODUCT_1 5 3 2 PRODUCT_3 I want to, for each unique product, perform a model prediction with A and B columns, and store the corresponding accuracy. unique = ["PRODUCT_1", ...] # unique products accuracy for i in unique: first_subset = ??? # all rows for product `i` - how do I implement this correctly? X = first_subset[:, 0] Y = first_subset[:, 1] prediction_product_1 = model.predict(X) accuracy_product_1 = np.sum( (prediction_product_1)/np.sum(Y) ) accuracy.append([accuracy_product_1, PRODUCT_1]) How could I implement the second point in Python?
tagged with: group-by
tagged with: python
has comment: http://stackoverflow.com/comment/82502032
has title: Extract Uniques and loop
score: -1
has comment: http://stackoverflow.com/comment/82497960
type: AnsweredQuestion
tagged with: pandas
linked to: http://stackoverflow.com/q/20109391
has comment: http://stackoverflow.com/comment/82502279
upvote count: 0
has comment: http://stackoverflow.com/comment/82510439
answer count: 1
has comment: http://stackoverflow.com/comment/82509985
has comment: http://stackoverflow.com/comment/82501991
downvote count: 1
tagged with: unique

http://stackoverflow.com/a/69162167
answers question: http://stackoverflow.com/q/47841985
has body: The main issue, as already explained in the other answers by @Martijn Pieters and @Mikhail Gerasimov is that app.run is blocking, so the line loop.run_forever() is never called. You will need to manually set up and maintain a run loop on a separate thread. Fortunately, with Flask 2.0, you don't need to create, run, and manage your own event loop anymore. You can define your route as async def and directly await on coroutines from your route functions. https://flask.palletsprojects.com/en/2.0.x/async-await/ Using async and await New in version 2.0. Routes, error handlers, before request, after request, and teardown functions can all be coroutine functions if Flask is installed with the async extra (pip install flask[async]). It requires Python 3.7+ where contextvars.ContextVar is available. This allows views to be defined with async def and use await. Flask will take care of creating the event loop on each request. All you have to do is define your coroutines and await on them to finish: https://flask.palletsprojects.com/en/2.0.x/async-await/#performance Performance Async functions require an event loop to run. Flask, as a WSGI application, uses one worker to handle one request/response cycle. When a request comes into an async view, Flask will start an event loop in a thread, run the view function there, then return the result. Each request still ties up one worker, even for async views. The upside is that you can run async code within a view, for example to make multiple concurrent database queries, HTTP requests to an external API, etc. However, the number of requests your application can handle at one time will remain the same. Tweaking the original example from the question: import asyncio from flask import Flask, jsonify async def send_notif(x: int): print(f"Called coro with {x}") await asyncio.sleep(1) return {"x": x} app = Flask(__name__) @app.route("/") async def notify(): futures = [send_notif(x) for x in range(5)] results = await asyncio.gather(*futures) r…
downvote count: 0
score: 7
upvote count: 7
type: Answer

http://stackoverflow.com/comment/82649109
comment on: http://stackoverflow.com/q/47842339
has text: please show a few lines of code preceding and following. it's a syntax error. it likely has nothing t to with MNIST
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82727407
type: AnswerComment
has text: 1. `driver.execute_script("window.open(URL)` allows to open URL in new tab while `driver.get(URL)` - in the same tab. 2. I'm not sure I understand what do you mean by *placeholder* in this case... This line allows you to get window from the list of currently available windows which is different from initial window...
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47853488

http://stackoverflow.com/a/47796744
type: Answer
downvote count: 0
score: 1
upvote count: 1
has body: Edit just one loop: x = ["a", "b", "c"] with open("teste.txt", "w") as f: for i in x[:-1]: f.write("letter " + i + " and" + '\n' + '\n') f.write("letter " + x[-1] + " and")
answers question: http://stackoverflow.com/q/47796541
has comment: http://stackoverflow.com/comment/82554728
has comment: http://stackoverflow.com/comment/82554360

http://stackoverflow.com/comment/82602230
score: 0
comment on: http://stackoverflow.com/q/47819819
has text: Ah ok, I didn't make that connection.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47709472
type: Answer
score: 1
has body: You can use something like this to capture a screenshot: def takeScreenShot(application): img = capture(SCREEN) # img is an image file .png in temp folder now ts = time.time() st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d_%H-%M-%S') if not os.path.exists('PATH'): os.makedirs('') shutil.move(img, 'PATH\\%(appName)s\\%(timeStamp)s.png' %{"appName": application, "timeStamp": st}) You can call this method as a part of a try catch block.
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47699811
answers question: http://stackoverflow.com/q/47699811

http://stackoverflow.com/q/47749631
downvote count: 0
favorite count: 0
tagged with: qstandarditem
type: Question
type: AnsweredQuestion
tagged with: hash
has comment: http://stackoverflow.com/comment/82475189
has body: I found when converting some Python2/Qt4 code to Python3/Qt5, that apparently QStandardItem can no longer be used as a dict key in as it doesn't have __hash__ implemented, and therefore is not considered immutable anymore. Those two snippets show the issue: PyQt4: &gt;&gt;&gt; from PyQt4 import QtGui &gt;&gt;&gt; a = QtGui.QStandardItem() &gt;&gt;&gt; b = {} &gt;&gt;&gt; b[a] = "1" &gt;&gt;&gt; a.__hash__() 2100390 PyQt5: &gt;&gt;&gt; from PyQt5 import QtGui &gt;&gt;&gt; a = QtGui.QStandardItem() &gt;&gt;&gt; b = {} &gt;&gt;&gt; b[a] = "1" TypeError: unhashable type: 'QStandardItem' &gt;&gt;&gt; a.__hash__() TypeError: 'NoneType' object is not callable Why was the change done? Should I not use QStandardItem as a dict key? The obvious workaround would be to subclass QStandardItem and reimplement a trivial version of __hash__ (which I've done). But is there anything I'm missing?
has title: QStandardItem missing __hash__ method
tagged with: python
accepted answer: http://stackoverflow.com/a/47760846
score: 4
has answer: http://stackoverflow.com/a/47760846
tagged with: qt
upvote count: 4
tagged with: pyqt
answer count: 1

http://stackoverflow.com/a/47762446
answers question: http://stackoverflow.com/q/47762345
has comment: http://stackoverflow.com/comment/82486540
type: Answer
has comment: http://stackoverflow.com/comment/82486467
has comment: http://stackoverflow.com/comment/82486515
has comment: http://stackoverflow.com/comment/82486550
has comment: http://stackoverflow.com/comment/82487466
upvote count: 3
has comment: http://stackoverflow.com/comment/82486456
has body: It's not the quotes that increase the size, it's the fact that it's a string so it has to be denoted as such - when pickled, via optcodes. Pickle is also not really intended to be very space-efficient (or even fast) unless you use at least protocol=2 while pickling. If you're after a minimum size (without compression) while storing strings, CSV should do it: import csv a3 = [['5x', '1x'], ['5x', '21'], ['5x', '1c'], ['5x', '21'], ['5x', '1o'], ['5x', '20'], ['5x', '1p']] with open("saved_data.csv", "wt", newline="") as f: writer = csv.writer(f) writer.writerows(a3) This will produce a 49 bytes CSV file (saved_data.csv) and you can't get lower than that without compression. By comparison, even pickling with protocol=4 will take 93 bytes for this data.
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47762345
score: 3

http://stackoverflow.com/a/47703850
downvote count: 0
has body: I think you need to define a mother class: class Shape: pass then sub-classes class Triangle(Shape): # whatever methods there are What you're describing is a factory function which creates the proper object according to some parameter: def create(type): if type=="Triangle": return Triangle() elif type=="Square": return Square() but it's not very useful since the caller has to pass the name of the class instead: c = create("Triangle") instead of just doing: c = Triangle() Well, it may have its interest when saving/restoring a program state from a text file containing the type(s) of the objects in the program memory when saved (if you don't want to use pickle).
answers question: http://stackoverflow.com/q/47703730
accepted answer of: http://stackoverflow.com/q/47703730
type: AcceptedAnswer
type: Answer
score: 3
upvote count: 3

http://stackoverflow.com/a/47820816
has body: You need return DataFrame of colors for set styles. So need create new df with same index and columns with default values - here background-color: red and then change values by condition: def highlight(x): c1 = 'background-color: red' c2 = 'background-color: black' #if want set no default colors #c2 = '' m = x['c'] &gt; x['b'] df1 = pd.DataFrame(c2, index=x.index, columns=x.columns) df1.loc[m, 'b'] = c1 return df1 df.style.apply(highlight, axis=None)
accepted answer of: http://stackoverflow.com/q/47820721
has comment: http://stackoverflow.com/comment/82604160
has comment: http://stackoverflow.com/comment/82604066
answers question: http://stackoverflow.com/q/47820721
has comment: http://stackoverflow.com/comment/82606953
type: Answer
upvote count: 6
has comment: http://stackoverflow.com/comment/82604928
type: AcceptedAnswer
downvote count: 0
score: 6

http://stackoverflow.com/a/47851375
has comment: http://stackoverflow.com/comment/82667230
downvote count: 0
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/82667244
answers question: http://stackoverflow.com/q/47851181
has body: Instead of using a list nested in a dict you can use a dict nested in a dict: node[node.lst_id] = {node1.unique_id: node1, node2.unique_id: node2, ... } Assuming ID_TO_REMOVE is a unique_id you can remove it with: node_to_remove = nodes_hash[ID_TO_REMOVE] del node_lsts[node_to_remove.lst_id][node_to_remove.unique_id] Full code: class Node(object): def __init__(self, lst_id, unique_id): self.lst_id = lst_id self.unique_id = unique_id def __repr__(self): return "[lst_id: {}, unique_id: {}]".format(self.lst_id, self.unique_id) n1 = Node('a', 1) n2 = Node('a', 2) n3 = Node('b', 3) node_lsts = {} for node in [n1,n2,n3]: if not node.lst_id in node_lsts: node_lsts[node.lst_id] = {} node_lsts[node.lst_id][node.unique_id] = node nodes_hash = {n1.unique_id: n1, n2.unique_id: n2, n3.unique_id: n3} ID_TO_REMOVE = 1 print("node_lsts", node_lsts) node_to_remove = nodes_hash[ID_TO_REMOVE] print("node_to_remove", node_to_remove) del node_lsts[node_to_remove.lst_id][node_to_remove.unique_id] print("node_lsts", node_lsts) OUTPUT node_lsts {'a': {1: [lst_id: a, unique_id: 1], 2: [lst_id: a, unique_id: 2]}, 'b': {3: [lst_id: b, unique_id: 3]}} node_to_remove [lst_id: a, unique_id: 1] node_lsts {'a': {2: [lst_id: a, unique_id: 2]}, 'b': {3: [lst_id: b, unique_id: 3]}} Since we're now using dictionaries everything is done in O(1) and we avoid the performance issue that was presented when we try to remove an element from a list.
type: Answer

http://stackoverflow.com/comment/82507099
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47772828
has text: getting a keyerror for ur logic,anyhow i posted my logic once see it and try to upgrade it

http://stackoverflow.com/a/47838630
score: 1
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82641494
upvote count: 1
has body: The outputs of np.linalg.svd are ndarray objects, for which the operator * is element-wise multiplication. You want to compute the matrix product, for which you need to use np.dot() or the @ operator. The multiplication should be: u[:, :k].dot(np.diag(sigma[:k])).dot(vt[:k])
accepted answer of: http://stackoverflow.com/q/47838531
has comment: http://stackoverflow.com/comment/82641629
type: Answer
answers question: http://stackoverflow.com/q/47838531
has comment: http://stackoverflow.com/comment/82641426

http://stackoverflow.com/q/47779291
has comment: http://stackoverflow.com/comment/82519826
answer count: 0
type: UnansweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/82519822
has body: I am working with some json data in python. I want to plot a bargragh such that it will show the color according to a sequence of conditions. I'm running into an issue where only the else condition is ever satisfied.Q['AQI'] has AQI values of different locations,I want color in my graph according AQI color code Here's the code I'm working from: import plotly.plotly as py import plotly.graph_objs as go def colors(y): color1='#ffff00'#setting default value if((Q['AQI']&gt;=51).all() &amp; (Q['AQI']&lt;=100).all()): color1='rgb(0,222,0)' elif((Q['AQI']&gt;=101).all() &amp; (Q['AQI']&lt;=150).all()): color1='rgb(0,0,222)' elif((Q['AQI']&gt;=151).all() &amp; (Q['AQI']&lt;=200).all()): color1='rgb(0,222,0)' elif((Q['AQI']&gt;=201).all() &amp; (Q['AQI']&lt;=300).all()): color1='rgb(222,0,0)' elif((Q['AQI']&gt;=301).all() &amp; (Q['AQI']&lt;=600).all()): color1='rgb(0,0,222)' else: color1='rgb(222,0,0)' return color1 trace0 = go.Bar(x=Q['location'], y=Q['AQI'], marker=dict(color=colors(y))) data = [trace0] fig = go.Figure(data=data) py.iplot(fig, filename='color-bar')
tagged with: plotly
tagged with: python
has comment: http://stackoverflow.com/comment/82519855
type: Question
has title: set a color in bargraph according to if-else statement

http://stackoverflow.com/comment/82394119
has text: We are trying to run it against a different database, but the code implicitly calls the production database (as in the URI is hardcoded in), so i need to trick it somehow.
comment on: http://stackoverflow.com/q/47699275
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47774354
answers question: http://stackoverflow.com/q/47744349
score: 0
type: Answer
has body: your basic problem is that you try to assign a value and not to compare it. use if days_per_month[month] == 31: instead of if days_per_month[month] = 31: However i would suggest using datetime like this: from datetime import * a=datetime(2017,2,28,23,56,00) b=a+timedelta(minutes=5) what I do is initialize a with the Date 28.02.2017 23:56:00 and then add 5 minutes to this datetime and get the Date 01.03.2017 00:01:00 in b

http://stackoverflow.com/comment/82582325
comment on: http://stackoverflow.com/a/47807622
score: 0
type: AnswerComment
has text: It's actually not *that* complicated. You need to install the SCIP Opt Suite using the provided Windows installer, set your PATH and SCIPOPTDIR environment variables accordingly and then youcan run `pip install pyscipopt`. If there are problems you cannot solve, you my consider opening an issue on the PySCIPOpt GitHub page.
type: Comment

http://stackoverflow.com/q/47779104
downvote count: 1
favorite count: 0
score: 2
type: AnsweredQuestion
upvote count: 3
has comment: http://stackoverflow.com/comment/82519440
has comment: http://stackoverflow.com/comment/82519541
tagged with: python
has title: Programming : Aufbau principle
has answer: http://stackoverflow.com/a/47779220
accepted answer: http://stackoverflow.com/a/47779220
type: Question
has comment: http://stackoverflow.com/comment/82519559
has body: I am trying to produce a function establishing the electronic configuration of an element depending of it's atomic number def Klechkowski(Z): L=[] while Z!=0: if Z-2<=0: if Z-1==0: L.append("1s^1") else: L.append("1s^2") if Z-4<=0: if Z-3==0: L.append("2s^1") else: L.append("2s^2") if Z-10<=0: if Z-6==4: L.append("2s^1") else: L.append("2s^2") ... L2=(reversed(L)) the result should look like: 17 --> 1s^2 2s^2 2p^6 3s^2 3p^5 i cannot figure out the way of transforming my result and which process should i repeat for each layer
has comment: http://stackoverflow.com/comment/82519592
has comment: http://stackoverflow.com/comment/82519516
answer count: 1
has comment: http://stackoverflow.com/comment/82523570

trading
tags question: http://stackoverflow.com/q/47741224
type: Tag
tag name: trading
tags question: http://stackoverflow.com/q/47745124

http://stackoverflow.com/comment/82643874
type: Comment
type: AnswerComment
has text: Ah ok. The model doesn't know that though. I think this is part of what's giving you trouble. So assume that location was somehow part of the order model. You would just aggregate data from the order table. Correct?
comment on: http://stackoverflow.com/a/47826432
score: 1

http://stackoverflow.com/a/47821915
upvote count: 1
has body: Here's a way to draw additive RGB circles using Numpy. It converts the Numpy data to a Tkinter PhotoImage object using PIL (Pillow), and displays the results in a Tkinter Label. I use a black background because we're doing additive color mixing. import numpy as np from PIL import Image, ImageTk import tkinter as tk width, height = 400, 360 # Make RGB colors red, grn, blu = np.eye(3, dtype=np.uint8) * 255 class GUI: def __init__(self, width, height): self.root = root = tk.Tk() root.title('Circles') root.geometry('%dx%d' % (width, height)) self.img_label = tk.Label(self.root) self.img_label.pack(fill='both', expand=True) gui = GUI(width, height) # Increase the scale for smoother circles scale = 4 width *= scale height *= scale screen = np.zeros((height, width, 3), dtype=np.uint8) def show(fname=None): img = Image.fromarray(screen, 'RGB') img = img.resize((width // scale, height // scale), resample=Image.BILINEAR) gui.photo = ImageTk.PhotoImage(image=img) gui.img_label.config(image=gui.photo) gui.root.update() if fname is not None: img.save(fname) def disc(radius): diameter = 2 * radius yy, xx = np.mgrid[:diameter, :diameter] - radius c = xx * xx + yy * yy &lt; radius * radius return c.reshape(diameter, diameter, 1) def get_region(cx, cy, radius): ylo = cy - radius yhi = cy + radius xlo = cx - radius xhi = cx + radius return screen[ylo:yhi, xlo:xhi] radius = 120 * scale circle = disc(radius) cx = width // 2 cy = 130 * scale region = get_region(cx, cy, radius) region |= circle * red show() cy += 97 * scale cx -= 56 * scale region = get_region(cx, cy, radius) region |= circle * grn show() cx += 112 * scale region = get_region(cx, cy, radius) region |= circle * blu show('rgb.png') gui.root.mainloop() output
score: 1
answers question: http://stackoverflow.com/q/47819197
type: Answer
downvote count: 0

http://stackoverflow.com/q/47779391
has comment: http://stackoverflow.com/comment/82520016
has comment: http://stackoverflow.com/comment/82520193
has comment: http://stackoverflow.com/comment/82520374
tagged with: email
score: 1
type: Question
tagged with: tkinter
has title: SMTP Recipient Refused Python
answer count: 0
tagged with: one-time-password
type: UnansweredQuestion
downvote count: 0
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/82521093
has body: I'm coding a password changer in Python, I'm currently working on the section that creates an OTP then emails it to the user. It should function as: Create Otp -> Display tkinter window -> input email -> send otp to email But I'm getting this error when trying to send the email; File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/smtplib.py", line 880, in sendmail raise SMTPRecipientsRefused(senderrs) smtplib.SMTPRecipientsRefused: {'': (555, b'5.5.2 Syntax error. m201sm173146wma.13 - gsmtp')} The tkinter window is also not displaying beforehand to actually take an input. My code is: from tkinter import * import random import smtplib def main(): otp = create_otp() user_email = layout(otp) send_otp(otp, user_email) def layout(output): root = Tk() root.geometry('800x400') root.config(bg='#10416A') email_in = StringVar() email = Entry(root, textvariable=email_in, width=50) email.place(x=190, y=145) label_otp = Label(root, text="Enter email address: ", background='#10416A', font=('arial', 15, "bold"), fg='white').place(x=18, y=150) user_email = email_in.get() enter_button = Button(root, text="Enter") enter_button.pack() enter_button.config(bg='#10416A', command=send_otp(output, user_email)) root.mainloop() return user_email def create_otp(): contents = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$%^&amp;*()-_=+[]{}:;?/&gt;.&lt;,0123456789" pw_length = 8 output = "" for i in range(pw_length): next_index = random.randrange(len(contents)) output = output + contents[next_index] return output def send_otp(output, user_email): content = output mail = smtplib.SMTP('smtp.gmail.com', 587) mail.ehlo() mail.starttls() mail.login('myemail@gmail.com', 'mypass') mail.sendmail('myemail@gmail.com', user_email, content) mail.close main() 1st question: Why isn't the tkinter window showing up when I run the program? 2nd question: Why is the recipient being refused? Thanks in advance!
favorite count: 0
has comment: http://stackoverflow.com/comment/82520155
has comment: http://stackoverflow.com/comment/82523330
has comment: http://stackoverflow.com/comment/82520310
has comment: http://stackoverflow.com/comment/82520061
has comment: http://stackoverflow.com/comment/82523646

http://stackoverflow.com/q/47732236
has comment: http://stackoverflow.com/comment/82425084
score: 4
upvote count: 4
has answer: http://stackoverflow.com/a/47732349
has title: Python strings: backspace at the end of string behaves differently
type: AnsweredQuestion
answer count: 2
downvote count: 0
accepted answer: http://stackoverflow.com/a/47732704
possible better answer: http://stackoverflow.com/a/47732349
favorite count: 0
has answer: http://stackoverflow.com/a/47732704
has body: I'm experimenting with the backspace character \b in Python strings. I tried this: &gt;&gt;&gt; s = "The dog\b barks" &gt;&gt;&gt; print(s) The do barks This behaves as expected. The g character disappears because of the \b backspace. Now I try this: &gt;&gt;&gt; s = "The dog barks\b" &gt;&gt;&gt; print(s) The dog barks Strange... the s character didn't disappear. Why? Note: I work on a Windows 10 PC and did these experiments in the Windows cmd prompt (the terminal). I run Python 3.6
tagged with: python-3.x
tagged with: backspace
type: Question
tagged with: python

http://stackoverflow.com/a/47735013
has comment: http://stackoverflow.com/comment/82575517
has body: while True: try: age = int(input("\nHow old are you in years? ")) break except ValueError: print('please put in a number') This should do the Trick
has comment: http://stackoverflow.com/comment/82430469
has comment: http://stackoverflow.com/comment/82613189
answers question: http://stackoverflow.com/q/47734981
has comment: http://stackoverflow.com/comment/82571108
type: Answer
score: 0

http://stackoverflow.com/a/47821857
has comment: http://stackoverflow.com/comment/82606343
has comment: http://stackoverflow.com/comment/82606371
has body: This explains the a2 question: def do_something(a,b): a.insert(0, 'z') print(id(b)) b = ['z'] + b print(id(b)) a = ['a', 'b', 'c']; a1 = a; a2 = a[:] b = ['a', 'b', 'c']; b1 = b; b2 = b[:] do_something(a,b) for var in (a,a1,a2,b,b1,b2): print(id(var), end=" ") print(var) Prints 4639127112 # this is the id of b before new assign 4639513416 # this is the id of b inside the function after 4639486216 ['z', 'a', 'b', 'c'] # a (same as a1) 4639486216 ['z', 'a', 'b', 'c'] # a1 4639511944 ['a', 'b', 'c'] # a2 4639127112 ['a', 'b', 'c'] # b (same as b1) 4639127112 ['a', 'b', 'c'] # b1 4639487304 ['a', 'b', 'c'] # b2
has comment: http://stackoverflow.com/comment/82606448
type: Answer
score: 0
answers question: http://stackoverflow.com/q/47821792

http://stackoverflow.com/comment/82531426
score: 0
has text: some params has useful names and you know what for it is. Other you have to check - "what will happen if I don't use this param or I change it ie. I add 1 to number"
comment on: http://stackoverflow.com/q/47782788
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/82647363
has text: @Cleb, you're right! that was a typo- fixed it
comment on: http://stackoverflow.com/q/47841525
score: 1
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/82577676
score: 0
comment on: http://stackoverflow.com/q/47808198
type: Comment
type: QuestionComment
has text: `process` expects a dataframe, so why are you passing it a filepath?

http://stackoverflow.com/q/47755723
type: Question
score: 9
tagged with: numpy
has comment: http://stackoverflow.com/comment/82473171
answer count: 2
has body: I just discovered Numpy structured arrays and I find them to be quite powerful. The natural question arises in my mind: How in the world do I create a Numpy structure scalar. Let me show you what I mean. Let's say I want a structure containing some data: import numpy as np dtype = np.dtype([('a', np.float_), ('b', np.int_)]) ar = np.array((0.5, 1), dtype=dtype) ar['a'] This gives me array(0.5) instead of 0.5. On the other hand, if I do this: import numpy as np dtype = np.dtype([('a', np.float_), ('b', np.int_)]) ar = np.array([(0.5, 1)], dtype=dtype) ar[0]['a'] I get 0.5, just like I want. Which means that ar[0] isn't an array, but a scalar. Is it possible to create a structured scalar in a way more elegant than the one I've described?
has answer: http://stackoverflow.com/a/47757556
has comment: http://stackoverflow.com/comment/82479165
has comment: http://stackoverflow.com/comment/82482941
downvote count: 1
favorite count: 0
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47756864
possible better answer: http://stackoverflow.com/a/47756864
accepted answer: http://stackoverflow.com/a/47757556
tagged with: python
has comment: http://stackoverflow.com/comment/82482920
upvote count: 10
has title: Creating a Numpy structure scalar instead of array

http://stackoverflow.com/comment/82450970
type: Comment
has text: Right, that is the gist that I linked. It still seems to need to go to disk, right? It also seems like that gist doesn't use tensorflow's freeze graph function (it is commented out), and I was curious if there was a reason why.
type: AnswerComment
comment on: http://stackoverflow.com/a/47744837
score: 1

http://stackoverflow.com/q/47759551
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82480429
tagged with: arrays
tagged with: python
tagged with: sorting
has body: The task: Calculate a stat for each point using points that are the shortest distance away from the original point. To do this i have created a text file for each point where i write the distance from every other point. Then I open the text file and use csv to sort the distance and use the shorted few to calculate a value and write it in a new text file. Surely there must be a more efficient way of achieving this because i have thousands of points, this process seems awfully time-consuming.
has title: Efficient way to calculate distances between every point and use the shorted few to calculate a value then add it back to the array.
score: 0
tagged with: http://stackoverflow.com/tag/csv
type: Question
has comment: http://stackoverflow.com/comment/82480306

http://stackoverflow.com/q/47762272
has comment: http://stackoverflow.com/comment/82486282
has comment: http://stackoverflow.com/comment/82486206
has title: Functions and attributes of a person via dictionaries
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/82486514
has comment: http://stackoverflow.com/comment/82486120
has body: I'm really struggling trying to understand functions and how they can be used to create attributes or properties (in this case i'm tasked with a person) The following is my code to declare the person in a dictionary, def format(person): return "Name:\t" + person['name'] def display(person): print(format(person)) person = {'name':"Bilbo Baggins"} I then can call the display to produce; Name = Bilbo Baggins I then have to add to the dictionary a property storing the weight and height (say both of which are 0 for now) of my person, which i have done by; person['height'] = 0 person['weight'] = 0 I now need to create a function (called create_person) that has the 3 parameters (name, height and weight), and modify my earlier code to use this function and alongside printing Name: Bilbo Baggins also prints the weight(in kg) and height(in m). The overall aim of this is to find out the BMI of a person, BMI is calculated by weight/height2. I also need to add a function that takes a single person object from the previous dictionary/function as a parameter and returns the BMI of the person. Is that possible through linking the two?
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47762383
has answer: http://stackoverflow.com/a/47762383
tagged with: function
has comment: http://stackoverflow.com/comment/82486222
score: 0
has comment: http://stackoverflow.com/comment/82486061
answer count: 1
has comment: http://stackoverflow.com/comment/82486633
type: Question
has comment: http://stackoverflow.com/comment/82486464

http://stackoverflow.com/comment/82550201
type: Comment
score: 0
has text: @AnupYadav It seems to be an idea.
comment on: http://stackoverflow.com/q/47794595
type: QuestionComment

svd
type: Tag
tags question: http://stackoverflow.com/q/47838531
tag name: svd

http://stackoverflow.com/comment/82554755
score: 0
type: Comment
type: QuestionComment
has text: I cannot imagine in what simpler terms you would like to read this. If the plots are being created with e.g. `axes.titlesize : medium`, I would like to increment the size to the next bigger option, in that case, `axes.titlesize : large`.
comment on: http://stackoverflow.com/q/47782185

http://stackoverflow.com/q/47708233
has comment: http://stackoverflow.com/comment/82376649
linked to: http://stackoverflow.com/q/42699430
tagged with: python
tagged with: parsing
score: 2
upvote count: 2
has body: How do I get the text value of the title element? Is this even possible with a Dom Element? Will I have to parse out the text by hand? #-*-coding:utf8;-*- #qpy:3 #qpy:console import re import urllib.request from xml.dom import minidom def download(url): with urllib.request.urlopen(url) as res: return res.read().decode('latin-1') class RSSFeed(object): def __init__(self, url): self.url = url self.raw_xml = download(url) self.dom = minidom.parseString(self.raw_xml) self.links = self.dom.getElementsByTagName('link') def entries(self): ret = {} for element in self.dom.getElementsByTagName('entry'): title = element.getElementsByTagName('title')[0] print(title.toprettyxml()) def __str__(self): return self.dom.toprettyxml() feed_url = 'https://rickys-python-notes.blogspot.com/atom.xml?redirect=false&amp;start-index=1&amp;max-results=500' feed = RSSFeed(feed_url) dom = feed.dom print(feedHow totries())
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47709779
downvote count: 0
has comment: http://stackoverflow.com/comment/82376692
has comment: http://stackoverflow.com/comment/82377058
has title: How do i get the text from a xml.dom.minidom Dom Element?
has comment: http://stackoverflow.com/comment/82377672
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47710160
has answer: http://stackoverflow.com/a/47709980
answer count: 3
has comment: http://stackoverflow.com/comment/82399796
has comment: http://stackoverflow.com/comment/82377255

resolution
tag name: resolution
tags question: http://stackoverflow.com/q/47850132
type: Tag

http://stackoverflow.com/comment/82370656
comment on: http://stackoverflow.com/q/47705294
score: 1
type: QuestionComment
has text: This will depend on your __real__ function - can you provide a definition of the real function? For your current question the fastest would be: `test_df['result'] = test_df['x'] + test_df['y']`
type: Comment

http://stackoverflow.com/comment/82569310
type: QuestionComment
has text: Yes, I would like the last 5 digits of the middle column, and avg them @ShadowRanger
score: 0
comment on: http://stackoverflow.com/q/47803673
type: Comment

http://stackoverflow.com/q/47789275
score: 2
upvote count: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47790233
downvote count: 0
has title: How to execute join queries of MySQL in Django?
has body: My SQL query which runs perfectly in terminal looks like this: select t.txid, t.from_address, t.to_address, t.value, t.timestamp, t.conformations, t.spent_flag,t.spent_txid from transaction_details t where t.to_address =(select distinct a.address from address_master a inner join panel_user p on a.user = p.user and a.user= "auxesis"); Now I tried using it in Django like this: sql = """ select t.txid, t.from_address, t.to_address,t.value, t.timestamp, t.conformations, t.spent_flag,t.spent_txid from transaction_details t where t.to_address =(select distinct a.address from address_master a inner join panel_user p on a.user = p.user and a.user= "%s" """),%(user) cursor.execute(sql) res = cursor.fetchall() But ya its not working. So any one please help me with it?
answer count: 1
tagged with: mysql
has comment: http://stackoverflow.com/comment/82539963
favorite count: 0
has comment: http://stackoverflow.com/comment/82539566
type: Question
has answer: http://stackoverflow.com/a/47790233
tagged with: django
tagged with: python

http://stackoverflow.com/comment/82646249
comment on: http://stackoverflow.com/a/47840838
score: 0
type: AnswerComment
has text: JSON is just a way of representing data as text. Think in terms of the underlying data, not JSON syntax. What dictionary were you trying to construct?
type: Comment

http://stackoverflow.com/comment/82664331
type: Comment
has text: Your `ENTRYPOINT` line does not make any sense like that.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47849798

statsmodels
tags question: http://stackoverflow.com/q/47843086
tags question: http://stackoverflow.com/q/47714805
type: Tag
tags question: http://stackoverflow.com/q/47802360
tag name: statsmodels
tags question: http://stackoverflow.com/q/47783247
tags question: http://stackoverflow.com/q/47838961
tags question: http://stackoverflow.com/q/47705239
tags question: http://stackoverflow.com/q/47785483

http://stackoverflow.com/a/47770549
has comment: http://stackoverflow.com/comment/82502871
has comment: http://stackoverflow.com/comment/82505167
score: 0
answers question: http://stackoverflow.com/q/47770444
has body: A TypeError: 'module' object is not callable means you're trying to use something like a function when it's not actually a function or a method.You have problem with numba import, maybe you should try from numba import jit
type: Answer

http://stackoverflow.com/comment/82481424
score: 0
has text: that's just normal JavaScript :P Not anything jQuery related
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47759956

http://stackoverflow.com/q/47734387
has comment: http://stackoverflow.com/comment/82429367
favorite count: 0
has title: Python 3: find max elements equal to each other in list
has comment: http://stackoverflow.com/comment/82429296
accepted answer: http://stackoverflow.com/a/47734437
has body: how do I find out the maximum amount of 1s (or any element I would like) next to each other in a list? l = [2, 1, 2, 1, 1, 1, 1, 2, 2, 2, 1, 2, 7, 1, 1, 1] In this case I would need a function that will return a 4. Thank you.
duplicate of: http://stackoverflow.com/q/22214086
type: Question
has answer: http://stackoverflow.com/a/47734437
answer count: 2
tagged with: python
score: -3
tagged with: list
possible better answer: http://stackoverflow.com/a/47734484
type: AnsweredQuestion
upvote count: 0
linked to: http://stackoverflow.com/q/22214086
downvote count: 3
has answer: http://stackoverflow.com/a/47734484

http://stackoverflow.com/q/47701885
type: Question
has title: Is Logging Module's thread safety, thread safe on the network as well?
tagged with: multithreading
downvote count: 0
has body: We are dumping log's into a single file with timestamps from multiple computers (500) and each entry is less than 4KB's. Python's logging module apparently handles the locking and guarantees Thread-Safety. https://docs.python.org/2/library/logging.html#thread-safety Thanks @user2357112 for your feedback, here are some more information: Are you using some sort of network-attached storage? The storage is a network disk, which shares a writable logfile.txt that can be read/written. Are the computers logging things locally and synchronizing their log files somehow? The computers not logging locally but ones they are finished, they are using the 'Logger' to write to the end of the logfile.txt that is shared How are log records from different computers ending up in the same file? All of the computers are appending to logfile.txt So What can go wrong writing to a single file? Or is it safe to use?
answer count: 1
score: 1
has comment: http://stackoverflow.com/comment/82363841
upvote count: 1
has comment: http://stackoverflow.com/comment/82364051
has answer: http://stackoverflow.com/a/47703044
tagged with: logging
favorite count: 0
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82364557
accepted answer: http://stackoverflow.com/a/47703044
tagged with: python
has comment: http://stackoverflow.com/comment/82363821

http://stackoverflow.com/a/47724623
has body: Minutes after I figured out that I can create a function inside the for loop to get a new stack frame. This unfortunately does not seem at all Pythonic... for key in keys: def dummyForStackFrame(key): #Extra function to get a new stack frame with key def wrappedCallback(self, value): realCallback(self, key, value) return None doSomething(wrappedCallback dummyForStackFrame(key)
answers question: http://stackoverflow.com/q/47724589
type: Answer
score: 0

http://stackoverflow.com/comment/82504732
comment on: http://stackoverflow.com/a/47771936
type: Comment
score: 2
type: AnswerComment
has text: Just saying that this is tagged pandas. Also, the `groupby` solution was mine first :)

http://stackoverflow.com/comment/82596938
comment on: http://stackoverflow.com/q/47817448
has text: I cannot restart the python script every time because I use a data structure and I did not want to build it every time. Otherwise from c++ a simple system will be fine. I want the python program running and on-demand the c++ program pass its input.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82640659
comment on: http://stackoverflow.com/q/47823460
score: 0
type: Comment
type: QuestionComment
has text: Would you be able to do the same thing for this table? d = {'content': [1, 3, None, 6, 1, 59, None], 'target': [0,1,0,2,4,5,4]} df = pd.DataFrame(data=d) df

http://stackoverflow.com/q/47716033
tagged with: django
tagged with: python
favorite count: 0
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47717372
answer count: 1
tagged with: django-models
has answer: http://stackoverflow.com/a/47717372
tagged with: django-forms
type: Question
has body: I have a django model that has one date field. class Employee(AbstractUser): dob = models.DateField(verbose_name="Date of Birth", null=True) when i register this model in admin site and display this field on the form during update, I see this default text for date fields. How can i remove this default help_text Note: You are 5.5 hours ahead of server time I tried to override the help_text for date feild but it didn't work. dob = models.DateField(verbose_name="Date of Birth", null=True, help_text='')
upvote count: 2
tagged with: django-admin
has title: How to Hide default help_text fom date fields in django admin
downvote count: 0

http://stackoverflow.com/q/47724911
linked to: http://stackoverflow.com/q/41639816
has answer: http://stackoverflow.com/a/47726298
tagged with: wrapper
has body: I am currently trying to use Python 3.6's ctypes module to call functions from a library written in C++. Suppose I used ctypes to create a shared library object called myLibrary: # Python code myLibrary = ctypes.CDLL(mylib.dylib) The library I'm trying to make calls from uses C++ classes, and it is impossible with ctypes to make Python calls of the form myLibrary.class()-&gt;method() (see here). I am therefore first writing some intermediate C++ code which "wraps" the C++ class methods in a non-class form. For example, suppose Math is one of the classes, and Add() is one of its methods. My intermediate wrapper would look like this: // C++ intermediate code int Add(int num1, int num2){ // no reference to a class return Math()-&gt;Add(num1, num2); // reference to a class } I then plan on compiling this C++ into a shared library (a dylib file) on which I can make calls in Python using ctypes. For example: # Python code def add(num1, num2): myLibrary.add(num1, num2) That's the plan. Unfortunately, many methods in the library have exotic argument and value types. Some are simply variant type names created with the typedef keyword, but others are exotic structs. Further, there is a bit of enumeration in the original C++ code. My question is: How does one deal with custom argument and value types (and enumeration) when using ctypes? Looking at the ctypes documentation, I know that you must specify restypes and argtypes for the methods you're trying to call, but how to do this when the original C++ functions involve exotic types and structs? I thought the ctypes documentation might shed light on this, in section 15.17.1.6. ("Calling functions with your own custom data types"), but it just talks about the reverse scenario where you want to pass your own object types into the C++ functions. Similar questions that were helpful, but not totally: How to use C++ classes with ctypes? Obtaining address of custom data-type in C from Python using ctypes
score: 1
downvote count: 0
answer count: 1
upvote count: 1
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/1615813
tagged with: ctypes
type: UnansweredQuestion
tagged with: python
tagged with: http://stackoverflow.com/tag/c
has title: Using Python's ctypes to call functions involving custom types
tagged with: c++

http://stackoverflow.com/q/47845064
tagged with: pandas
tagged with: solr
has body: I would like to fill an solr index from a pandas dataframe. The dataframe is as follows: position value 5.6,-2.3 65 -35.6,-1.2 43.1 #... etc. I am doing the following to transform the dataframe to a json object and then adding it to solr: import json import pandas as pd import pysolr # I have a pandas dataframe df as described above jsonObject = json.loads(df.to_json(orient='records')) solrServer = pysolr.Solr('pathToMySolrIndex',timeout=100) solrServer.add(jsonObject) I get the following error: multiple values encountered for non multiValued field position If I change the name of the fied position to _position , then it kind of works. From pysolr's documentation page, I understand this creates a parent/child dependency which I don't really want. Indeed, reading back from the index using: results = solrServer.search(**{'q':'*'}) df2 = pd.DataFrame(list(results)) print(df2.head()) I get something like this: _position value [5.6,-2.3] [65] [-35.6,-1.2] [43.1] #... Despite this "hackish" solution, I'm still not getting a good result: Each element is a list. I would have preferred tuples for position, and simple floats for value. I guess this comes from the orient keyword when converting to json. Questions and Expected output First, I would like to avoid renaming position to _position . The Solr database doesn't have to contain renamed fields for the sake of pysolr. Second, I would like to avoid having lists when reading from the built Solr index. I know that Solr doesn't have to contain lists as numerical elements. The problem seems to come from the transformation from DataFrame to json. How to do this?
has comment: http://stackoverflow.com/comment/82714726
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82714693
has comment: http://stackoverflow.com/comment/82655552
has title: pySolr : Adding a multivalued field
tagged with: python
tagged with: pysolr
has comment: http://stackoverflow.com/comment/82714837
has comment: http://stackoverflow.com/comment/82714879
has comment: http://stackoverflow.com/comment/82656668
has comment: http://stackoverflow.com/comment/82715239
score: 0
answer count: 0

http://stackoverflow.com/comment/82722442
type: Comment
has text: Thanks Andrei. I went with Jan's solution but I do like the way you've done this. Jan's was just simpler to integrate with the rest of what I was doing.
comment on: http://stackoverflow.com/a/47871111
score: 0
type: AnswerComment

http://stackoverflow.com/a/47752590
accepted answer of: http://stackoverflow.com/q/47752524
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82465826
score: 6
has body: Just use sorted(place, reverse=True).
answers question: http://stackoverflow.com/q/47752524
upvote count: 6
type: Answer

http://stackoverflow.com/comment/84777043
comment on: http://stackoverflow.com/q/47753736
has text: Possible duplicate of [Custom eval\_metric\_ops in Estimator in Tensorflow](https://stackoverflow.com/questions/45643809/custom-eval-metric-ops-in-estimator-in-tensorflow)
type: QuestionComment
score: 0
type: Comment

http://stackoverflow.com/comment/82460027
type: Comment
type: QuestionComment
has text: sorry, edited my post with the source code
comment on: http://stackoverflow.com/q/47748989
score: 0

http://stackoverflow.com/q/47802786
type: Question
has comment: http://stackoverflow.com/comment/82588498
has title: Upstart: ImportError: No module named
tagged with: upstart
tagged with: python
type: AnsweredQuestion
has body: I have a simple python script import boto3 print('I know you are installed') I'm sure the boto3 module is installed pip3 install boto3 If run via terminal python3 test.py I get the expected output I know you are installed If I run the same script via Upstart description "test" author "me" start on runlevel [2345] stop on runlevel [!2345] respawn chdir /var/www/html/ script exec nohup /usr/bin/python3 -u /var/www/html/test.py &gt; /var/www/html/test.log end script I get tail: /var/www/html/test.log: file truncated Traceback (most recent call last): File "/var/www/html/test.py", line 1, in &lt;module&gt; import boto3 ImportError: No module named 'boto3' Why can't the boto3 module be found when running the script from Upstart?
tagged with: importerror
has comment: http://stackoverflow.com/comment/82572031
accepted answer: http://stackoverflow.com/a/47820450
score: 1
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/47820450
upvote count: 1
favorite count: 0

http://stackoverflow.com/comment/82480202
comment on: http://stackoverflow.com/q/47759123
score: 0
has text: stackoverflowuser2010: I guess I am underfitting, because my loss is massive, and with so few data I belive this is part of my problem? I will try that @djk47463, thank you!
type: Comment
type: QuestionComment

pandas-groupby
tags question: http://stackoverflow.com/q/47716125
tags question: http://stackoverflow.com/q/47710694
type: Tag
tags question: http://stackoverflow.com/q/47829357
tags question: http://stackoverflow.com/q/47810770
tags question: http://stackoverflow.com/q/47738165
tags question: http://stackoverflow.com/q/47775927
tags question: http://stackoverflow.com/q/47815004
tags question: http://stackoverflow.com/q/47848037
tags question: http://stackoverflow.com/q/47810051
tags question: http://stackoverflow.com/q/47755844
tags question: http://stackoverflow.com/q/47775512
tags question: http://stackoverflow.com/q/47832114
tags question: http://stackoverflow.com/q/47703634
tags question: http://stackoverflow.com/q/47774092
tags question: http://stackoverflow.com/q/47737418
tags question: http://stackoverflow.com/q/47703606
tags question: http://stackoverflow.com/q/47804045
tag name: pandas-groupby
tags question: http://stackoverflow.com/q/47756617
tags question: http://stackoverflow.com/q/47820571
tags question: http://stackoverflow.com/q/47851667
tags question: http://stackoverflow.com/q/47851540
tags question: http://stackoverflow.com/q/47797615
tags question: http://stackoverflow.com/q/47836380
tags question: http://stackoverflow.com/q/47774664
tags question: http://stackoverflow.com/q/47790564

http://stackoverflow.com/comment/82529575
score: 0
type: AnswerComment
has text: row_values += [row[i] + row[i + n]] would be really like this or not? row_values += [row[i] / row[i + n]]
comment on: http://stackoverflow.com/a/47784099
type: Comment

http://stackoverflow.com/a/49437512
score: 15
has comment: http://stackoverflow.com/comment/97682254
downvote count: 0
has body: You can wrap Tensorflow's tf.losses.huber_loss in a custom Keras loss function and then pass it to your model. The reason for the wrapper is that Keras will only pass y_true, y_pred to the loss function, and you likely want to also use some of the many parameters to tf.losses.huber_loss. So, you'll need some kind of closure like: def get_huber_loss_fn(**huber_loss_kwargs): def custom_huber_loss(y_true, y_pred): return tf.losses.huber_loss(y_true, y_pred, **huber_loss_kwargs) return custom_huber_loss # Later... model.compile( loss=get_huber_loss_fn(delta=0.1) ... )
has comment: http://stackoverflow.com/comment/100374454
has comment: http://stackoverflow.com/comment/118512979
type: Answer
answers question: http://stackoverflow.com/q/47840527
upvote count: 15

http://stackoverflow.com/a/72617566
answers question: http://stackoverflow.com/q/47714070
score: 1
downvote count: 0
upvote count: 1
has body: Another way is .env file pip install python-dotenv from dotenv import load_dotenv load_dotenv() class Config: SECRET_KEY = os.getenv("SECRET_KEY") Remember to gitignore .env as well
type: Answer

http://stackoverflow.com/comment/82741703
type: AnswerComment
score: 0
type: Comment
has text: ...lol..like the Dutch saying: "what the farmer does not know he does not eat".. as Simon said ;-)
comment on: http://stackoverflow.com/a/47862064

http://stackoverflow.com/a/47816831
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47803066
type: Answer
has body: Answering my own question. It was a matter of increasing the number of epochs and fiddling with the batch size. For example, here is the prediction for #epochs = 200, batch size = 10.
accepted answer of: http://stackoverflow.com/q/47803066

http://stackoverflow.com/q/47854012
answer count: 0
has comment: http://stackoverflow.com/comment/82676439
has comment: http://stackoverflow.com/comment/82672602
type: Question
has body: I am using Python 2.7 I have interactive Python script, named A, written using Cmd module. However, sometimes there is a need to activate script A from other Python scripts. It also could be nice if the interactive script A wouldn't exit in between commands given to them. I tried to search for solutions and I found couple here One is to pass a file from which the interactive script will read commands. It works well for me but it is not much liked. Another is to use echo which doesn't work for me (still trying). I wonder whether there are other solutions.....
type: UnansweredQuestion
has title: Calling to python interactive script from another script
tagged with: python
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/82676509

http://stackoverflow.com/comment/82476583
has text: @JonClements - me typing without thinking. Fixed, thanks!
comment on: http://stackoverflow.com/a/47756930
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47743463
has title: Running python scripts only when imported modules are modified
downvote count: 1
favorite count: 0
score: -1
type: Question
upvote count: 0
tagged with: testing
tagged with: automated-tests
type: UnansweredQuestion
has body: Is there a way of running python scripts only when imported modules are modified? This would be very useful for test automation purposes.
has answer: http://stackoverflow.com/a/47743549
answer count: 1
tagged with: python

http://stackoverflow.com/comment/82395209
type: Comment
has text: @Tim_Utrecht PS. I've never seen any performance advantage of `plot_ly` vs. `ggplotly`. See also [here](https://community.plot.ly/t/major-performance-difference-between-ggplotly-and-plot-ly/650) for an example where `ggplotly` is actually significantly *faster* than `plot_ly`.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47712635

http://stackoverflow.com/a/47820312
accepted answer of: http://stackoverflow.com/q/47819937
score: 0
has comment: http://stackoverflow.com/comment/82604724
type: AcceptedAnswer
has body: What am I missing here? You are missing argparse. Do your argument parsing with argparse, and you get automatic help messages, reasonable error messages when required arguments are missing, a consistent user interface. Consider this program with your three required arguments: #!/usr/bin/env python import argparse import dateutil.parser parser = argparse.ArgumentParser(description='The Constant Frobulator') parser.add_argument('-name', required=True, help='The name of frobulator') parser.add_argument('-age', required=True, type=int, help='The age of frobulator') parser.add_argument('-date', required=True, type=dateutil.parser.parse, help='The precise date frobulation began') args = parser.parse_args() print(args) And this demonstration of the program's features, courtesy argparse: $ ./myprog usage: myprog [-h] -name NAME -age AGE -date DATE myprog: error: argument -name is required $ ./myprog -h usage: myprog [-h] -name NAME -age AGE -date DATE The Constant Frobulator optional arguments: -h, --help show this help message and exit -name NAME The name of frobulator -age AGE The age of frobulator -date DATE The precise date frobulation began $ ./myprog -name George -age 47 -date "Mar 5, 2016" Namespace(age=47, date=datetime.datetime(2016, 3, 5, 0, 0), name='George') $ ./myprog -name George -age 47.5 -date "Mar 5, 2016" usage: myprog [-h] -name NAME -age AGE -date DATE myprog: error: argument -age: invalid int value: '47.5' $ ./myprog -name George -date "Mar 5, 2016" usage: myprog [-h] -name NAME -age AGE -date DATE myprog: error: argument -age is required
answers question: http://stackoverflow.com/q/47819937
type: Answer

openpyxl
tags question: http://stackoverflow.com/q/47709487
tags question: http://stackoverflow.com/q/47743714
tags question: http://stackoverflow.com/q/47782402
tags question: http://stackoverflow.com/q/47771831
tags question: http://stackoverflow.com/q/47700554
tags question: http://stackoverflow.com/q/47699872
tags question: http://stackoverflow.com/q/47732129
type: Tag
tags question: http://stackoverflow.com/q/47786882
tags question: http://stackoverflow.com/q/47703751
tags question: http://stackoverflow.com/q/47760505
tag name: openpyxl
tags question: http://stackoverflow.com/q/47760035

http://stackoverflow.com/a/47811020
upvote count: 1
has body: There are a couple of things to note here - You're calling replace on a column of floats, performing regex replacement which requires strings Your regular expression is incorrect, you should be using lookarounds, and you shouldn't do [^0-9] because ^ inside a character class performs negation (will find anything that is not a digit). I'd do this by first converting to string. You'll need to keep the trailing decimals for which str.format will help. Afterwards, call str.replace. s.apply('{:.2f}'.format).str.replace('\.', ',') 0 234,00 1 423,00 2 536,56 dtype: object Keep in mind that holding data in this format really serves no purpose computationally.
answers question: http://stackoverflow.com/q/47810780
type: Answer
score: 1
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47810780

http://stackoverflow.com/q/47814449
has answer: http://stackoverflow.com/a/67740060
has comment: http://stackoverflow.com/comment/82590209
type: Question
has comment: http://stackoverflow.com/comment/82591799
type: UnansweredQuestion
tagged with: python
has title: Pandas apply function running slow
score: 0
tagged with: pandas
answer count: 1
has body: I have this function that given an id, a number n and a dataframe returns the nth element on column "something" where the "id" is the id in the params. def find_something(id,n,df): table = df.loc[(df['id'] == id)] try: something = df['something'].iloc[n-1] except: something = float('NaN') return something When I run this for 1 id (the id is of format np.int32 and the df in the params has 20 million rows) it runs in 11.4 ns, but when I apply it to a dataframe column with 60K rows it takes hours to run: my_table['new_column'] = my_table['id'].apply(find_something, args=(1,df,)) So if I have: df = pd.DataFrame({'id' : [1, 2, 2, 2, 2,1,2,2], 'something' : np.random.randn(8)}) And: my_table = pd.DataFrame({'id' : [1, 2]}) my_table['new_column'] = my_table['id'].apply(find_something, args=(1,df,)) my_table should look like: id new_column 0 1 -0.396238 1 2 0.074007 Is there a more efficient way to do this? I don't see any reason why for 1 element it takes 11 ns but for 60K it takes hours.
has comment: http://stackoverflow.com/comment/82592021
has comment: http://stackoverflow.com/comment/82590538

http://stackoverflow.com/q/47722610
type: AnsweredQuestion
tagged with: algorithm
downvote count: 3
tagged with: python
has body: I have a large file that contains many lines of strings in a format of: A B D B C D C D C D As you can see C and D appears recurrently 3 times next to each other , so I want to parse the file to find the recurring pattern of them to output: A B D B repeat C D 3 times C D in actual case, it the recurring pattern of lines that next to each other may goes up to 3 lines but no more than that, e.g A B D B C D E C D E So the output would be: A B D B Repeat C D E 2 times C D E Here is the runnable code, but how could I find the longest repeat patterns if there are other repeated pattern ahead of it? def is_list_equal(left, right): if len(left) != len(right): return False for i in xrange(len(left)): if left[i] != right[i]: return False return True def find_dup_from_end(l, min_pattern_len, min_repeats): assert min_pattern_len * min_repeats &lt;= len(l) max_pattern_len = len(l) / min_repeats l = l[::-1] for i in xrange(max_pattern_len, min_pattern_len-1, -1): s1 = l[:i] for j in range(1, min_repeats): s2 = l[len(s1)*j:len(s1)*(j+1)] if not is_list_equal(s1, s2): break else: return (len(l)-len(s1)*min_repeats, len(s1)) return None, None def find_dup(file, min_pattern_len=2, max_pattern_len=10, min_repeats=2): assert min_pattern_len &gt; 0 assert min_repeats &gt; 1 assert min_pattern_len &lt;= max_pattern_len feed = [] min_feed_length = min_pattern_len*min_repeats max_feed_length = max_pattern_len*min_repeats start = None length = None with open(file) as f: mylist = f.read().splitlines() for line in mylist: line = line.strip() api = line fn = 'a' feed.append((fn, api)) if len(feed) &lt; min_feed_length: continue if len(feed) &gt; max_feed_length: fn2, api2 = feed[0] print fn2, api2 feed = feed[1:] feed1 = [api for _, api in feed] start, length = find_dup_from_end(feed1, min_pattern_len, min_repeats) if length: print(feed[start:start+length], min_repeats) break # print "length", length feed = feed[:(start - length*(min_repeats-1))] for fn2, api2 in feed: print fn2, api2 if __nam…
has comment: http://stackoverflow.com/comment/82450501
type: Question
has comment: http://stackoverflow.com/comment/82405811
has comment: http://stackoverflow.com/comment/82433133
has comment: http://stackoverflow.com/comment/82406184
score: -2
answer count: 1
has comment: http://stackoverflow.com/comment/82409754
accepted answer: http://stackoverflow.com/a/47741237
upvote count: 1
has answer: http://stackoverflow.com/a/47741237
favorite count: 0
has title: How do I find recurring pattern lines in a large file

http://stackoverflow.com/comment/82652250
comment on: http://stackoverflow.com/q/47843889
score: 0
type: Comment
type: QuestionComment
has text: I am using Python 2.7 32bit and windows is 64bit

http://stackoverflow.com/q/47733478
has comment: http://stackoverflow.com/comment/82427652
has comment: http://stackoverflow.com/comment/82427709
type: Question
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82428609
tagged with: python
tagged with: rgb
tagged with: image
tagged with: opencv
has body: Given, import numpy as np import cv2 img = cv2.imread('./my_img.jpg') b, g, r = cv2.split(img) I am confused why I get different values for im_sum = r + g + b versus im_sum2 = np.sum(img, axis=2) If I write h, w = img.shape[:2] for i in range(h): for j in range(w): if im_sum[i,j] != im_sum2[i,j]: print(im_sum[i,j] - im_sum2[i,j]) I get a whole bunch of print outs of 4294967040 Which is actually equal to 2**32 - 256 Can anyone enlighten me on this? Does it have something to do with uint32 vs. uint8 images?
has title: Summing R, G, and B Channels
score: 0
has comment: http://stackoverflow.com/comment/82427730
has comment: http://stackoverflow.com/comment/82427687

http://stackoverflow.com/q/47731633
has comment: http://stackoverflow.com/comment/82433328
tagged with: python
has comment: http://stackoverflow.com/comment/82436292
has comment: http://stackoverflow.com/comment/82423973
score: -1
tagged with: sql-server-2017
has comment: http://stackoverflow.com/comment/82433265
has title: Connect Python to SQL Server 2017 on Docker
has comment: http://stackoverflow.com/comment/82433252
upvote count: 0
has body: I'm trying to set up a new development environment on my Mac Development OS: MacOS 10.13.2 Python: 3.6 pyodbc: 4.0.21 driver manager: unixODBC 2.3.4 driver: FreeTDS 1.00.79 DB: MS SQL Server 2017 Developer [Microsoft SQL Server 2017 14.0.3008.27 (X64) Developer Edition (64-bit) on Linux (Ubuntu 16.04.3 LTS)] downloaded from https://learn.microsoft.com/en-us/sql/linux/quickstart-install-connect-docker#pull-and-run-the-container-image Issue telnet to mssql-linux2017 docker image on 1433 is fine sqlcmd fails with below error [ODBC][22520][1512841146.847871][SQLGetDiagFieldW.c][815] Entry: Connection = 0x7fcbe2010c00 Rec Number = 2 Diag Ident = 5 Diag Info Ptr = 0x7ffeec672b3c Buffer Length = -6 String Len Ptr = 0x0 [ODBC][22520][1512841146.848022][SQLGetDiagFieldW.c][835] Exit:[SQL_SUCCESS] [ODBC][22520][1512841146.848195][SQLGetDiagFieldW.c][815] Entry: Connection = 0x7fcbe2010c00 Rec Number = 2 Diag Ident = 6 Diag Info Ptr = 0x7fcbe200d200 Buffer Length = 2050 String Len Ptr = 0x7ffeec672b40 [ODBC][22520][1512841146.848367][SQLGetDiagFieldW.c][835] Exit:[SQL_SUCCESS] [ODBC][22520][1512841146.848539][SQLGetDiagFieldW.c][815] Entry: Connection = 0x7fcbe2010c00 Rec Number = 2 Diag Ident = 4 Diag Info Ptr = 0x7ffeec672b44 Buffer Length = 12 String Len Ptr = 0x7ffeec672b40 [ODBC][22520][1512841146.848711][SQLGetDiagFieldW.c][835] Exit:[SQL_SUCCESS] [ODBC][22520][1512841146.848939][SQLGetConnectAttrW.c][211]Error: SQL_INVALID_HANDLE ideally I want to do pyodbc.connect('DRIVER=ODBC Driver 13 for SQL Server;SERVER=localhost;PORT:1433;DATABASE=&lt;SOMEDB&gt;;UID=SA;PWD=&lt;myPass&gt;')
tagged with: freetds
type: UnansweredQuestion
tagged with: unixodbc
answer count: 1
downvote count: 1
tagged with: pyodbc
has answer: http://stackoverflow.com/a/47738072
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82433357

http://stackoverflow.com/q/47822353
has comment: http://stackoverflow.com/comment/82607511
has comment: http://stackoverflow.com/comment/82608128
downvote count: 0
has comment: http://stackoverflow.com/comment/82611295
has answer: http://stackoverflow.com/a/47826961
accepted answer: http://stackoverflow.com/a/47826961
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82615956
has title: Rect collision on a pygame display; pressing a second key, after collision, causes rect to jump
score: 3
has answer: http://stackoverflow.com/a/47825623
possible better answer: http://stackoverflow.com/a/47825623
has comment: http://stackoverflow.com/comment/82607627
upvote count: 3
tagged with: python
tagged with: pygame
has body: I'm having issues getting this collision to work 100%. If I only press one key at a time, the collision seems to work fine, but if I press a key and continue pressing, while colliding, then press another key, the collision seems to account for both keys at the same time. From researching, it seems like I need to do separate axis calculations, but I'm not sure exactly how to do that, using the algorithm I have for collision. I want this to be procedural style, if possible. If anyone could amend my code, with a working procedural solution, I'd greatly appreciate it. Thanks. import pygame as pg import sys from math import fabs pg.init() width = 600 height = 600 gameDisplay = pg.display.set_mode((width, height)) pg.display.set_caption('Block') white = (255, 255, 255) red = (255, 0, 0) clock = pg.time.Clock() closed = False FPS = 60 Player_Speed = 200 x, y = 270, 0 vx = 0 vy = 0 collision = False def Collision(hero, enemy): global vx, vy, x, y, collision deltay = fabs(block.centery - ENEMY.centery) deltax = fabs(block.centerx - ENEMY.centerx) if deltay &lt; ENEMY.height and deltax &lt; ENEMY.width: collision = True if vx &gt; 0: vx = 0 x = ENEMY[0] - block[2] if vx &lt; 0: vx = 0 x = ENEMY[0] + 30 if vy &gt; 0: vy = 0 y = ENEMY[1] - block[3] if vy &lt; 0: vy = 0 y = ENEMY[1] + 30 else: collision = False def xy_Text(x, y): font = pg.font.SysFont("Courier", 16, True) text = font.render("X: " + str(round(x)), True, (0,150,0)) text1 = font.render("Y: " + str(round(y)), True, (0,150,0)) gameDisplay.blit(text, (0,0)) gameDisplay.blit(text1, (0,14)) while not closed: for event in pg.event.get(): if event.type == pg.QUIT: closed = True dt = clock.tick(FPS)/1000 vx, vy = 0, 0 keys = pg.key.get_pressed() if keys[pg.K_ESCAPE]: closed = True if keys[pg.K_LEFT] or keys[pg.K_a]: vx = -Player_Speed if keys[pg.K_RIGHT] or keys[pg.K_d]: vx = Player_Speed if keys[pg.K_UP] or keys[pg.K_w]: vy = -Player_Speed if keys[pg.K_DOWN] or keys[pg.K_s]: vy = Player_Speed if vx != 0 and vy != 0: vx *…
favorite count: 0
type: Question
tagged with: python-3.x
answer count: 2

http://stackoverflow.com/comment/82403716
type: AnswerComment
has text: Yes, I'm sure it does have an optimal substructure property. I will check that link and create a substructure for the same, Thanks
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47721540

http://stackoverflow.com/a/47698104
type: Answer
has comment: http://stackoverflow.com/comment/82359685
has comment: http://stackoverflow.com/comment/82358226
has comment: http://stackoverflow.com/comment/82356180
downvote count: 0
has comment: http://stackoverflow.com/comment/82356084
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82357943
has comment: http://stackoverflow.com/comment/82356155
has comment: http://stackoverflow.com/comment/82356294
has comment: http://stackoverflow.com/comment/82357383
has comment: http://stackoverflow.com/comment/82358162
has comment: http://stackoverflow.com/comment/82357634
has comment: http://stackoverflow.com/comment/82356429
has comment: http://stackoverflow.com/comment/82356337
answers question: http://stackoverflow.com/q/47697988
has comment: http://stackoverflow.com/comment/82356804
has body: The first method is correct. One more way of doing this is via tf.add_n function: reg_losses = tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES) loss = tf.add_n([base_loss] + reg_losses, name="loss") The second method also works, but you'll have to define a single regularizer. So it works in your case, but may be inconvenient if you use different regularizers in different layers.
upvote count: 1
score: 1
accepted answer of: http://stackoverflow.com/q/47697988

http://stackoverflow.com/q/47835123
linked to: http://stackoverflow.com/q/15482539
has answer: http://stackoverflow.com/a/47895062
tagged with: distance
has comment: http://stackoverflow.com/comment/82634013
tagged with: a-star
upvote count: 2
type: AnsweredQuestion
has body: I am looking for an efficient solution to the following problem. This should work with python, but does not have to be in python. I have a 2D matrix, each element of the matrix represents a point in a 2D, orthogonal grid. I want to compute the shortest distance between couples of points in the grid. This would be trivial if there were no "obstacles" in the grid. A figure helps explaining: Each cell in the figure is one element of the matrix (the matrix is square, but it could be rectangular). Gray cells are obstacles, any path between two points must go around them. The green cells are those I am interested in. I am not interested in red cells, but a path can go trough them. The distance between points like A and B is trivial to compute, but how to compute the path between A and C as shown in the figure? I have read about the A* algorithm, but since I am working with a rather big grid, generally (few hundred) x (few hundred), I was wondering if there is a smarter alternative. Remember: I have to find the distance between all couples of "green cells", not just between two of them. If I have n green cells, I will have a number of combinations equal to the binomial coefficient (n 2). The grid is fixed, I have to compute all the distances once and them use them in further calculations, say accessing them based on the relevant indices in the matrix. Note: the problem is NOT this one, were coordinates are in a list. My 2D coordinates are organised in a 2D grid and the question is about exploiting this aspect for having a more efficient algorithm.
tagged with: arrays
score: 1
has comment: http://stackoverflow.com/comment/82636027
downvote count: 1
answer count: 1
favorite count: 0
has title: Compute distance between combinations of points in a grid
has comment: http://stackoverflow.com/comment/82641161
has comment: http://stackoverflow.com/comment/82633801
type: Question
tagged with: matrix
has comment: http://stackoverflow.com/comment/82633934
tagged with: python
has comment: http://stackoverflow.com/comment/82633792
accepted answer: http://stackoverflow.com/a/47895062

http://stackoverflow.com/comment/115251517
comment on: http://stackoverflow.com/a/47820438
has text: For anyone wondering, here's a `psycopg2` [github issue](https://github.com/psycopg/psycopg2/issues/653) that closed this request for automated casting as won't-fix.
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/82675177
has text: use the `__str__` ? https://docs.python.org/3/reference/datamodel.html#object.__str__ - or do you need it for other things then output? if so, edit your questions pls.
comment on: http://stackoverflow.com/q/47855577
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/47802375
tagged with: pytest
has title: How can I display GUI while testing PyQt5 app with pytest-qt?
type: Question
has answer: http://stackoverflow.com/a/47847347
downvote count: 0
accepted answer: http://stackoverflow.com/a/47847347
tagged with: user-interface
answer count: 1
score: 6
upvote count: 6
tagged with: pyqt5
has body: I am new to PyQt, but I am going to use pytest with pytest-qt plugin to test my PyQt5 application. I had some GUI testing experience in Java with SWTBot and RCPTT, where I could see what happens with controls and whole GUI during the test in real-time. I'd like to have such behavior with my new python tools, but it seems that pytest-qt tests GUI in some background way. All code works as I expect, but during testing I can't see the GUI. The code is simple as in tutorials: from tests.test import MyApp from time import sleep from PyQt5.QtCore import * from PyQt5.QtWidgets import * def test_myapp(qtbot): app = QApplication([]) window = MyApp() # window.show() # app.exec_() qtbot.addWidget(window) qtbot.mouseClick(window.buttonBox.buttons()[0], Qt.LeftButton) sleep(5) assert window.label.text() == 'accept' If I uncomment the window.show() line (they do so in the tutorial), I can see a strange window, that contains frozen background: I suppose that it is theoretically possible to show the interface because I know that PyQt5 works from the python shell (more): you can, for example, create widgets from the Python shell prompt, interact with them, and still being able to enter other Python commands But I don't know how to achieve it with pytest-qt
tagged with: python
favorite count: 0
type: AnsweredQuestion

http://stackoverflow.com/q/47825221
answer count: 3
tagged with: if-statement
tagged with: python
has comment: http://stackoverflow.com/comment/82612908
has title: Python 3.6 If Statement with Criteria
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/47825302
tagged with: function
has answer: http://stackoverflow.com/a/47825302
has comment: http://stackoverflow.com/comment/82612884
has body: I am trying to create a classic if statement with criteria in Python 3. I am able to input a number from this code, but am not able to figure out why the code will not print "hot" or "cold". What can I do to fix this? Do I need to have an elif with this statement? N = float(input(("Enter Number: "))) def is_hot (N): if N/2&gt;1 and N-1&gt;1: print (N, "is hot") else: N/2&lt;1 and N-1&lt;1 print (N, "is cold")
possible better answer: http://stackoverflow.com/a/47825264
has answer: http://stackoverflow.com/a/47825267
has comment: http://stackoverflow.com/comment/82631227
has comment: http://stackoverflow.com/comment/82612895
has answer: http://stackoverflow.com/a/47825264
type: AnsweredQuestion
score: 0

http://stackoverflow.com/comment/118401576
comment on: http://stackoverflow.com/a/47714013
has text: `[g, c].forEach(function (a) { a.forEach(merge);` in this how do we call?
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/47748579
has title: Remove whole days from pandas hourly dataframe
upvote count: 3
answer count: 1
downvote count: 0
tagged with: python
has body: I am working with an hourly dataframe that has rows for each hour of the day from 2016. From this hourly dataframe I want to delete some days that I have in 'df_outlayers' dataframe which is a daily dataframe. I tried the following: remove = df_hourly.loc[df_outlayers.index] df_clean = df_hourly.drop(remove.index) df_clean['2017-04-17'] But it just deletes the first hour of the days, for example it deletes the row 2017-04-17 00:00:00 but not 2017-04-17 01:00:00. How can I delete every hour for those given outlayers days? Note: My 'df_outlayers' dataframe has an index column called date, df_outlayers.index gives for example: DatetimeIndex(['2016-07-06', '2016-07-08', '2016-10-10', '2017-04-09', '2017-04-17', '2017-04-26', '2017-07-05', '2017-07-07', '2017-09-01', '2017-09-22', '2017-09-29'], dtype='datetime64[ns]', name='date', freq=None) And my df_hourly dataframe has an index column called 'date' aswell, df_hourly.index gives for example: DatetimeIndex(['2014-07-19 00:00:00', '2014-07-19 01:00:00', ...] dtype='datetime64[ns]', name='date', length=13214, freq=None)
favorite count: 0
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47748616
tagged with: pandas
score: 3
has answer: http://stackoverflow.com/a/47748616
tagged with: dataframe
type: Question

http://stackoverflow.com/comment/82556328
comment on: http://stackoverflow.com/q/47797744
type: QuestionComment
score: 0
has text: Try using `ImageGrab` from `PIL` which does the same thing as `autopy.bitmap.capture_screen()`. Link [here](http://pillow.readthedocs.io/en/3.1.x/reference/ImageGrab.html).
type: Comment

permissions
tag name: permissions
tags question: http://stackoverflow.com/q/47851671
type: Tag
tags question: http://stackoverflow.com/q/47749188

http://stackoverflow.com/q/47815647
has answer: http://stackoverflow.com/a/47817013
favorite count: 0
type: Question
answer count: 2
has body: Lost in asyncio. I'm learning Kivy and asyncio at the same time, and got stuck into solving the problem of running the Kivy and running the asyncio loop, as whatever the way I turn it, both are blocking calls and need to be executed sequentially (well, I hope I'm wrong), e.g. loop = asyncio.get_event_loop() loop.call_soon(MyAsyncApp().run()) loop.run_forever() My current attempt results in the application being launched, but no coroutine is being executed, e.g. when I click the "Connect" button, I should start scheduling and executing tasks using loop.call_soon, but nothing happens. Could someone have a look at my code and suggest a proper approach to the problem? import asyncio import random import time from kivy.app import App from kivy.lang import Builder ui = Builder.load_string(''' BoxLayout: orientation: 'vertical' GridLayout: rows: 2 cols: 2 Label: text: 'Status:' size_hint: 0.3, 1 Label: id: status text: '' Label: text: 'Data:' size_hint: 0.7, 1 Label: id: data text: '' BoxLayout: direction: 'horizontal' Button: text: 'Get Data' on_press: app.connect() Button: text: 'Stop Data' on_press: pass ''') class MyAsyncApp(App): def __init__(self): super(self.__class__, self).__init__() self.x_connected = None self.x_widget_data = None self.x_widget_status = None self.x_loop = asyncio.get_event_loop() def build(self): return ui def connect(self): # Get widget self.x_widget_status = self.root.ids.status # Update status self.x_widget_status.text = 'Preparing to connect...' # Connect using asyncio # --&gt; But the loop must be already running &lt;--- self.x_loop.call_soon(self.do_connect) async def do_connect(self): # Connect asynchronously # Get widget self.x_widget_data = self.root.ids.data # Update status self.x_connected = False self.x_widget_status.text = 'Connecting...' # Perform actual actions try: result = await self.feed_kivy() if result: self.x_widget_status.text = 'Service not available: ' + result return except Exception as e: self.x_widget_status.text = 'Er…
downvote count: 0
score: 6
has answer: http://stackoverflow.com/a/67489929
possible better answer: http://stackoverflow.com/a/67489929
tagged with: python
upvote count: 6
accepted answer: http://stackoverflow.com/a/47817013
type: AnsweredQuestion
tagged with: python-asyncio
has title: Mixing asyncio and Kivy: How to start the asyncio loop and the Kivy application at the same time?
tagged with: kivy

http://stackoverflow.com/comment/82574782
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47806611
has text: "it doesn't work" is rarely an helpful description of your problem

http://stackoverflow.com/a/47719782
has comment: http://stackoverflow.com/comment/82400382
accepted answer of: http://stackoverflow.com/q/47719494
has comment: http://stackoverflow.com/comment/82480039
has body: Thanks for posting the link to the Google Sheet. I downloaded it and loaded it via pandas: df = pd.read_excel(r'~\relatorio_vendas_CRM.xlsx', encoding = 'utf-8') df.columns = df.columns.str.replace('°', '') df.columns = df.columns.str.replace('º', '') Note that the two replace statements are replacing different characters, although they look very similar. Help from: Why do I get a SyntaxError for a Unicode escape in my file path?
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82400712
downvote count: 0
has comment: http://stackoverflow.com/comment/82428273
has comment: http://stackoverflow.com/comment/82400437
answers question: http://stackoverflow.com/q/47719494
has comment: http://stackoverflow.com/comment/82401213
has comment: http://stackoverflow.com/comment/82402680
has comment: http://stackoverflow.com/comment/82400314
type: Answer
has comment: http://stackoverflow.com/comment/82428259
upvote count: 4
score: 4
has comment: http://stackoverflow.com/comment/82501901

http://stackoverflow.com/comment/82476956
type: Comment
has text: You're already doing it with a functional API model. Having a sequential segment in the middle doesn't make it different. :) --- If you want, I can create the model from your picture entirely in the answer. (But I'll consider that you have two data boxes)
type: AnswerComment
comment on: http://stackoverflow.com/a/47743125
score: 0

http://stackoverflow.com/comment/82451915
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47744362
has text: Thankyou. Seems like with this approach the start date and end must be a known? Not always the case in my data set. Can you get around this?
type: AnswerComment

http://stackoverflow.com/comment/82432580
has text: @grantwardend do not know why we need multiple columns A here ...if so you can append more :-)
type: AnswerComment
comment on: http://stackoverflow.com/a/47736094
type: Comment
score: 0

http://stackoverflow.com/a/47739567
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47701761
has body: Figured it out in the meanwhile... the problem was that elpy-enable does install a hook. It does not directly invoke the elpy mode as I thought. Therefore only the second invocation of python-mode did actually result in a call of this function. Of course this is better... So now I have: (elpy-enable) (setq elpy-rpc-backend "jedi") (add-hook 'elpy-mode-hook '(lambda () (setq-local ac-max-width 0.5)))
accepted answer of: http://stackoverflow.com/q/47701761
type: Answer
score: 1
type: AcceptedAnswer

sensors
type: Tag
tags question: http://stackoverflow.com/q/47743497
tags question: http://stackoverflow.com/q/47780904
tag name: sensors

http://stackoverflow.com/q/47817172
type: Question
downvote count: 0
has title: Odoo custom module modifying crm.leads
answer count: 1
tagged with: python
has body: I'd like to add some fields from a custom module (following the tutorial here: https://www.odoo.com/documentation/11.0/howtos/backend.html#model-inheritance) to the lead form but I can't get it to work. I always get the following error: Odoo Server Error Traceback (most recent call last): File "/usr/lib/python3/dist-packages/odoo/models.py", line 971, in _validate_fields check(self) File "/usr/lib/python3/dist-packages/odoo/addons/base/ir/ir_ui_view.py", line 321, in _check_xml self.postprocess_and_fields(view.model, view_doc, view.id) File "/usr/lib/python3/dist-packages/odoo/addons/base/ir/ir_ui_view.py", line 919, in postprocess_and_fields self.raise_view_error(message, view_id) File "/usr/lib/python3/dist-packages/odoo/addons/base/ir/ir_ui_view.py", line 489, in raise_view_error raise ValueError(message) ValueError: Field `country` does not exist Error context: View `crm_case_form_view_leads_extended` [view_id: 990, xml_id: n/a, model: crm.lead, parent_id: 442] During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/lib/python3/dist-packages/odoo/tools/convert.py", line 741, in parse self._tags[rec.tag](rec, de, mode=mode) File "/usr/lib/python3/dist-packages/odoo/tools/convert.py", line 651, in _tag_record id = self.env(context=rec_context)['ir.model.data']._update(rec_model, self.module, res, rec_id or False, not self.isnoupdate(data_node), noupdate=self.isnoupdate(data_node), mode=self.mode) File "/usr/lib/python3/dist-packages/odoo/addons/base/ir/ir_model.py", line 1467, in _update record = record.create(values) File "/usr/lib/python3/dist-packages/odoo/addons/base/ir/ir_ui_view.py", line 384, in create return super(View, self).create(self._compute_defaults(values)) File "/usr/lib/python3/dist-packages/odoo/models.py", line 3289, in create self._fields[key].determine_inverse(record) File "/usr/lib/python3/dist-packages/odoo/fields.py", line 1078, in determine_inverse getattr(records, self.inverse)() F…
has answer: http://stackoverflow.com/a/47820679
accepted answer: http://stackoverflow.com/a/47820679
type: AnsweredQuestion
tagged with: odoo
score: 1
upvote count: 1
favorite count: 0

pivot-table
tag name: pivot-table
tags question: http://stackoverflow.com/q/47759982
type: Tag

http://stackoverflow.com/comment/82459698
comment on: http://stackoverflow.com/a/47749681
type: AnswerComment
has text: user is just an integer from validated_data['user_list'], so CompletedTest.objects.get(test_id=test, user_id=user) is correct
type: Comment
score: 0

http://stackoverflow.com/comment/82706942
comment on: http://stackoverflow.com/q/47851027
score: 0
type: Comment
type: QuestionComment
has text: Thank you for everyones help

http://stackoverflow.com/q/47759732
answer count: 1
has body: I am running from a batch file that basically runs the robot.bat command. Any suggestion on why would that be an issue and how to solve it? I see the packages are installed correctly. This is the first time I am attempting to run a test. $ ./bin/run-windows.bat &gt;C:\Users\kondalar\workspace\rafa\cra-ui-qa&gt;robot.bat --pythonpath C:/Users/kondalar/apps/conda/envs/robot-cray-ui-test2 --critical Critical --outputdir ..\report --variablefile C:/Users/kondalar/workspace/rafa/cra-ui-qa/config/windows-local-config.py C:/Users/kondalar/workspace/rafa/cra-ui-qa/cases/01* [ ERROR ] Error in file 'C:\Users\kondalar\workspace\rafa\cra-ui-qa\resources\project-import.robot': Importing test library 'C:/Users/kondalar/apps/conda/envs/robot-cray-ui-test2/Lib/site-packages/ExtendedSelenium2Library' failed: ImportError: No module named keywords Traceback (most recent call last): File "C:\Users\kondalar\apps\conda\envs\robot-cray-ui-test2\Lib\site-packages\ExtendedSelenium2Library\__init__.py", line 27, in &lt;module&gt; from ExtendedSelenium2Library.keywords import ExtendedElementKeywords File "C:\Users\kondalar\apps\conda\envs\robot-cray-ui-test2\Lib\site-packages\ExtendedSelenium2Library\keywords\__init__.py", line 24, in &lt;module&gt; from ExtendedSelenium2Library.keywords.extendedelement import ExtendedElementKeywords File "C:\Users\kondalar\apps\conda\envs\robot-cray-ui-test2\Lib\site-packages\ExtendedSelenium2Library\keywords\extendedelement.py", line 27, in &lt;module&gt; from Selenium2Library.keywords import _ElementKeywords PYTHONPATH: C:\Users\kondalar\apps\conda\envs\robot-cray-ui-test2 C:\Users\kondalar\apps\conda\envs\robot-cray-ui-test2 C:\Users\kondalar\apps\conda\envs\robot-ui-test\python27.zip C:\Users\kondalar\apps\conda\envs\robot-ui-test\DLLs C:\Users\kondalar\apps\conda\envs\robot-ui-test\lib C:\Users\kondalar\apps\conda\envs\robot-ui-test\lib\plat-win C:\Users\kondalar\apps\conda\envs\robot-ui-test\lib\lib-tk C:\Users\kondalar\apps\conda\envs\robot-ui-test C…
type: Question
has comment: http://stackoverflow.com/comment/82480947
type: AnsweredQuestion
score: 0
tagged with: selenium
tagged with: ui-automation
accepted answer: http://stackoverflow.com/a/47760114
tagged with: robotframework
has answer: http://stackoverflow.com/a/47760114
has title: ExtendedSelenium2Library - failed: ImportError: No module named keywords
has comment: http://stackoverflow.com/comment/82483628
tagged with: python

http://stackoverflow.com/q/47742481
tagged with: list
has body: I have the following Python dictionary: b = {'SP:1': 1.0, 'SP:2': 2.0, 'SP:3': 3.0, 'SP:4': 4.0, 'SP:5': 5.0, 'SP:6': 6.0, 'SP:7': 40.0, 'SP:8': 7.0, 'SP:9': 8.0} I want to take this list and iterate over it to create 9 lists, each successive list being a superset of its predecessor. So: [1.0] [1.0,2.0] [1.0,2.0,3.0] [1.0,2.0,3.0,4.0] ... [1.0,2.0,3.0,4.0,5.0,6.0,40.0,7.0,8.0] There is probably a really easy way of doing this with a list comprehension, but I cant work it out!
upvote count: 1
has comment: http://stackoverflow.com/comment/82445102
downvote count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47742506
has answer: http://stackoverflow.com/a/47742500
answer count: 2
possible better answer: http://stackoverflow.com/a/47742500
has comment: http://stackoverflow.com/comment/82445212
tagged with: python
tagged with: dictionary
tagged with: list-comprehension
has title: Python dictionary iteratively expanded into lists
has answer: http://stackoverflow.com/a/47742506
type: AnsweredQuestion
score: 0

http://stackoverflow.com/q/47840527
score: 18
accepted answer: http://stackoverflow.com/a/48791563
has title: Using Tensorflow Huber loss in Keras
tagged with: python
has body: I am trying to use huber loss in a keras model (writing DQN), but I am getting bad result, I think I am something doing wrong. My is code is below. model = Sequential() model.add(Dense(output_dim=64, activation='relu', input_dim=state_dim)) model.add(Dense(output_dim=number_of_actions, activation='linear')) loss = tf.losses.huber_loss(delta=1.0) model.compile(loss=loss, opt='sgd') return model
has answer: http://stackoverflow.com/a/48791563
upvote count: 18
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/78793916
possible better answer: http://stackoverflow.com/a/49437512
has answer: http://stackoverflow.com/a/56828180
downvote count: 0
has answer: http://stackoverflow.com/a/49437512
has answer: http://stackoverflow.com/a/47847372
tagged with: keras
tagged with: tensorflow
favorite count: 0
type: Question
tagged with: reinforcement-learning
answer count: 5

http://stackoverflow.com/comment/82480436
type: AnswerComment
has text: I fully understand your comment. I also see the limitations, however, a reviewer asked for it.
comment on: http://stackoverflow.com/a/47756137
score: 1
type: Comment

http://stackoverflow.com/comment/82606660
type: AnswerComment
score: 0
has text: @MatthewHarwood: then just store the whole map: `regionmap = {r['slug']: r for r in regions}`.
type: Comment
comment on: http://stackoverflow.com/a/47821959

http://stackoverflow.com/a/47740290
score: 4
upvote count: 4
downvote count: 0
has body: You only print the word when you encounter a non-letter character after. You need to also print it when you're finished looping over the string.
answers question: http://stackoverflow.com/q/47740198
type: Answer

http://stackoverflow.com/a/51969613
type: Answer
has body: You don't have to install pre-built version. It could be a limited ram issue. When you install tensorflow on any raspberry pi, it is suggested to add --no-cache option sudo apt-get install python-numpy python-scipy python-h5py python-opencv pip install numpy scipy h5py opencv enter code here pip install --no-cache-dir tensorflow pip install keras==2.1.5 --no-cache-dir --no-deps It is important to pay attention to which Python version you are installing to. In my above script, I installed to Python 2.7. According to tensorflow page: Installing Tensorflow on Raspbian This can take some time on certain platforms like the Pi Zero, where some Python packages like scipy that TensorFlow depends on need to be compiled before the installation can complete. The Python 3 version will typically be faster to install because piwheels.org has pre-built versions of the dependencies available, so this is our recommended option. So based on the above quote, it might be better to install on python 3. But my personal experience told me that it was actually easier to install on python 2.7. Check my blog for step-by-step instructions: Deep Learning with Raspberry Pi. I did installed on RPI 3, however I don't see why it wounldn't work on Pi Zero
score: 0
has comment: http://stackoverflow.com/comment/90889982
answers question: http://stackoverflow.com/q/47813824

http://stackoverflow.com/q/47804754
has body: I have data that is the sign of data in a numpy array: Data=[-1,1,-1,1,1,1,-1,1,-1,1,...,N] There is an obvious pattern from inspection where every 3rd element is negative: Pattern=[1,1-1,1,1,-1,1,1,-1...] But there is noise so I cant directly quantify this, so I would like to do a fourier transform to see how strong this spatial repetition is. I would expect to see a large peak at frequency=N/3 since this pattern seems to repeat every 3 values. So far I have tried: For a data of N=401 I have tried: y=numpy.fft.fft(Data) x = np.linspace(0,400,401) plt.plot(x,y.real) plt.show() but I am getting noise and no clear peaks which I know exist. I have a feeling I am not implementing the fft correctly.
favorite count: 0
type: Question
tagged with: numpy
answer count: 1
downvote count: 0
upvote count: 1
tagged with: fft
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47807176
has title: Sign flipping Fourier transform Python Numpy Array
has comment: http://stackoverflow.com/comment/82571861
has answer: http://stackoverflow.com/a/47807176
score: 1
tagged with: python
tagged with: scipy

dataframe
tags question: http://stackoverflow.com/q/47760766
tags question: http://stackoverflow.com/q/47788708
tags question: http://stackoverflow.com/q/47723737
tags question: http://stackoverflow.com/q/47802695
tags question: http://stackoverflow.com/q/47780312
tags question: http://stackoverflow.com/q/47705294
tags question: http://stackoverflow.com/q/47735848
tags question: http://stackoverflow.com/q/47719040
tags question: http://stackoverflow.com/q/47703250
tags question: http://stackoverflow.com/q/47818881
tags question: http://stackoverflow.com/q/47737167
tags question: http://stackoverflow.com/q/47817352
tags question: http://stackoverflow.com/q/47781464
tags question: http://stackoverflow.com/q/47699053
tags question: http://stackoverflow.com/q/47838699
tags question: http://stackoverflow.com/q/47841492
tags question: http://stackoverflow.com/q/47708345
tags question: http://stackoverflow.com/q/47829357
tags question: http://stackoverflow.com/q/47735845
tags question: http://stackoverflow.com/q/47803239
tags question: http://stackoverflow.com/q/47825061
tags question: http://stackoverflow.com/q/47830763
tags question: http://stackoverflow.com/q/47742111
tags question: http://stackoverflow.com/q/47743330
tags question: http://stackoverflow.com/q/47741750
tags question: http://stackoverflow.com/q/47837594
tags question: http://stackoverflow.com/q/47741763
tags question: http://stackoverflow.com/q/47767461
tags question: http://stackoverflow.com/q/47704925
tags question: http://stackoverflow.com/q/47771894
tags question: http://stackoverflow.com/q/47703606
tags question: http://stackoverflow.com/q/47841525
tags question: http://stackoverflow.com/q/47814062
tags question: http://stackoverflow.com/q/47823460
tags question: http://stackoverflow.com/q/47738451
tags question: http://stackoverflow.com/q/47784761
tags question: http://stackoverflow.com/q/47730983
tags question: http://stackoverflow.com/q/47760015
tags question: http://stackoverflow.com/q/47802118
tags question: http://stackoverflow.com/q/47838998
tags question: http://stackoverflow.com/q/47803876
tags question: http://stackoverflow.com/q/47743198
tags question: http://stackoverflow.com/q/47797290
tags question: http://stackoverflow.com/q/47713947
tags question: http://stackoverflow.com/q/47794835
tags question: http://stackoverflow.com/q/47704547
tags question: http://stackoverflow.com/q/47738856
tags question: http://stackoverflow.com/q/47838305
tags question: http://stackoverflow.com/q/47745595
tags question: http://stackoverflow.com/q/47793412
tags question: http://stackoverflow.com/q/47833044
tags question: http://stackoverflow.com/q/47815004
tags question: http://stackoverflow.com/q/47770973
tags question: http://stackoverflow.com/q/47717266
tags question: http://stackoverflow.com/q/47817250
tags question: http://stackoverflow.com/q/47804748
tags question: http://stackoverflow.com/q/47828481
tags question: http://stackoverflow.com/q/47767076
tags question: http://stackoverflow.com/q/47851540
tags question: http://stackoverflow.com/q/47749321
tags question: http://stackoverflow.com/q/47797955
tags question: http://stackoverflow.com/q/47818314
tags question: http://stackoverflow.com/q/47800625
tags question: http://stackoverflow.com/q/47801604
tags question: http://stackoverflow.com/q/47745139
tags question: http://stackoverflow.com/q/47703314
tags question: http://stackoverflow.com/q/47830085
tags question: http://stackoverflow.com/q/47809646
tags question: http://stackoverflow.com/q/47775664
tags question: http://stackoverflow.com/q/47766453
tags question: http://stackoverflow.com/q/47783833
tags question: http://stackoverflow.com/q/47849196
tags question: http://stackoverflow.com/q/47773629
tags question: http://stackoverflow.com/q/47831508
tags question: http://stackoverflow.com/q/47801056
tags question: http://stackoverflow.com/q/47740196
tags question: http://stackoverflow.com/q/47791878
tags question: http://stackoverflow.com/q/47810051
tags question: http://stackoverflow.com/q/47827484
tags question: http://stackoverflow.com/q/47716682

http://stackoverflow.com/comment/82519943
score: 0
comment on: http://stackoverflow.com/a/47778664
type: Comment
type: AnswerComment
has text: OK, I'm on SO almost every day. If I will tired of SO then maybe I go back to Python groups o FB: [Python](https://www.facebook.com/groups/gpython/) and [Python Programming Language](https://www.facebook.com/groups/python.programmers/)

http://stackoverflow.com/q/47832281
tagged with: python
has comment: http://stackoverflow.com/comment/82628462
score: 1
has title: Scrolling infinite page with Python/PhantomJS/Selenium
has body: I'm trying to scrape this one (infinite) page (www.mydealz.de) but I cannot get my webdriver to scroll down the page. Im using Python (3.5), Selenium (3.6) and PhantomJS. I already tried several approaches but the webdriver just wont scroll - it just gives me the first page. 1st approach (the ususal scrolling approach): last_height = driver.execute_script("return document.body.scrollHeight") while True: driver.execute_script("window.scrollTo(0, document.body.scrollHeight);") time.sleep(1) new_height = driver.execute_script("return document.body.scrollHeight") if new_height == last_height: break last_height = new_height 2nd approach (just pressing the down key several times and release it, tried wating inbetween presses, too): ActionChains(driver).key_down(Keys.ARROW_DOWN).perform() ActionChains(driver).key_up(Keys.ARROW_DOWN).perform() 3rd approach (find the last element in the "scrolling list" and scroll to its view to force scrolling): posts = driver.find_elements_by_css_selector("div.threadGrid") driver.execute_script("arguments[0].scrollIntoView();", posts[-1]) Nothing worked so far, does anybody know if there is another approach or where I made an error?
has comment: http://stackoverflow.com/comment/82628717
accepted answer: http://stackoverflow.com/a/47836166
type: Question
has answer: http://stackoverflow.com/a/47836166
answer count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/47833335
tagged with: selenium
tagged with: web-scraping
upvote count: 1
favorite count: 0
possible better answer: http://stackoverflow.com/a/47832585
tagged with: phantomjs
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47832585
has comment: http://stackoverflow.com/comment/82627676

http://stackoverflow.com/comment/82377330
comment on: http://stackoverflow.com/a/47703756
type: AnswerComment
has text: Of course, MaxU. It is what I'm going to do and I will choose your answer after testing it. I'm just surprised that something so simple has this complex solution. I thought that a transpose of my largest3 dataframe was enough to solve it. The problem is that I couldn't find this "simple" transpose.
score: 0
type: Comment

http://stackoverflow.com/comment/82460184
comment on: http://stackoverflow.com/q/47749744
type: Comment
score: 0
has text: Yes, I can do that but the issue is on my end is I am unable to call the functions
type: QuestionComment

http://stackoverflow.com/a/47878294
answers question: http://stackoverflow.com/q/47848641
accepted answer of: http://stackoverflow.com/q/47848641
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: A change from @permalink (which I was informed has been deprecated) to calling reverse directly seems to have done the trick: In the model code: def get_absolute_url(self): if not self.passthrough_page: return reverse('view_page', kwargs={'slug': self.slug}) else: return self.passthrough_link
score: 1
type: Answer

http://stackoverflow.com/a/47816149
answers question: http://stackoverflow.com/q/47815774
type: Answer
has comment: http://stackoverflow.com/comment/82594178
has body: Without knowing the text it has to search, you could use the regex: ([€|$|£]+[0-9a-zA-Z\,\.]+) to capture everything that contains €, £ or $, and then print the amount without following words or letters. See the example in action here: http://rubular.com/r/a7O7AGF9Zl. Using this regex we get this code: import re webpage = ''' one million dollars test123 $1bn asd €5euro $1923,1204bn €1293.1205 million''' regex = r'([€|$]+[0-9a-zA-Z\,\.]+)' res = re.findall(regex, webpage) print(res) with the output: ['$1bn', '€5euro', '$1923,1204bn', '€1293.1205'] EDIT: Using the same regex on the provided website, it returns the output of: ['$131bn', '$100bn', '$17.4bn.', '$52.4bn'] If you modify the regex further to find e.g. 500million, you can add 0-9 to your first bracket, as you then search for either £, €, $ or anything that starts with 0-9. Output of: webpage = ''' one million €1293.1205 million 500million ''' regex = r'([€|$0-9]+[0-9a-zA-Z\,\.]+)' Therefore becomes: ['€1293.1205', '500million']
has comment: http://stackoverflow.com/comment/82594395
score: 2
upvote count: 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47815774
downvote count: 0

http://stackoverflow.com/comment/82602900
comment on: http://stackoverflow.com/q/47820259
has text: Would both lists be always going to be sorted in the same "lead_status" asc order? Would these lists be of the same size all the time?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/82567479
comment on: http://stackoverflow.com/q/47803005
type: QuestionComment
has text: Alexander I know, I removed it. But whenever I call it, it won't stop.
score: 0
type: Comment

http://stackoverflow.com/comment/82648814
has text: @Nisa have you checked this link and click on run ? repl.it/@aadi1111/test1 Just click on that link and then click on run button , see the output
type: AnswerComment
comment on: http://stackoverflow.com/a/47838873
score: 0
type: Comment

http://stackoverflow.com/comment/82477425
type: Comment
score: 0
has text: @Rahul as you've seen, it is possible. I would still not do it. Modifying your classes like this sets you up for all kind of difficult to debug problems. If your team insists, they insist on doing something bad. Another option to solve your issue would be to create a subclass of car that inherits from both the mixin and the original car. This is safer, because it creates an explicit class instead of modifying global interpreter state.
type: AnswerComment
comment on: http://stackoverflow.com/a/47754262

http://stackoverflow.com/comment/82511999
type: Comment
has text: (+1) Minor point: Many people now use Power Shell instead of Command Line. You might want to include that (you have made quite a good answer though).
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47769638

http://stackoverflow.com/comment/82648847
has text: Hey, the data is being loaded from a CSV with a few hundred thousand values, I'm working to make it a variable and remove the "data" parameter for for the method but it works when it's just a variable not being loaded from a CSV. How would you solve the issue when the data is a dictionary created from a CSV with headers as keys?
comment on: http://stackoverflow.com/q/47842283
type: QuestionComment
score: 0
type: Comment

http://stackoverflow.com/comment/82476699
type: AnswerComment
type: Comment
has text: In fact I send a package and then wait 10us... Tried to change the baud rate and nothing changed.. I forget to mention that my coordinator is a XBee S2C...
comment on: http://stackoverflow.com/a/47726380
score: 0

binary
tags question: http://stackoverflow.com/q/47724521
tag name: binary
tags question: http://stackoverflow.com/q/47783829
tags question: http://stackoverflow.com/q/47713926
tags question: http://stackoverflow.com/q/47729486
type: Tag

http://stackoverflow.com/comment/82485748
score: 0
has text: use monospaced font to correctly format text in `Listbox`
type: Comment
comment on: http://stackoverflow.com/q/47761650
type: QuestionComment

http://stackoverflow.com/q/47834718
type: AnsweredQuestion
score: 4
answer count: 1
has title: plot horizontal line in all subplots
favorite count: 0
type: Question
tagged with: subplot
downvote count: 0
has body: I;m working in python and found a couple solutions to do this. But it requires creating each individual subplot. But since there's a parameter where you could do subplot=True, I'm wondering is there a way to to do it in one line of code...much how you could say sharey=True, can you make it "share" a horizontal constant? I've been playing around with it. At first, it was only showing up on the last graph, but now it's not showing at all. import matplotlib.pyplot as plt line_up_points.plot(subplots=True, layout=(3, 3),sharey=True, figsize=(18, 12)) plt.legend(loc='best') plt.axhline(y=125.08, color='r') Here's what it's showing: But I would like to have a horizontal line on each of those subplots at y=125.08 Any idea without individually creating 7 different graphs?
tagged with: python
accepted answer: http://stackoverflow.com/a/47834759
tagged with: plot
has answer: http://stackoverflow.com/a/47834759
upvote count: 4

http://stackoverflow.com/comment/82469817
comment on: http://stackoverflow.com/q/47754260
score: 0
has text: btw [data is already plural](https://www.theguardian.com/news/datablog/2010/jul/16/data-plural-singular)
type: QuestionComment
type: Comment

http://stackoverflow.com/q/47802468
has answer: http://stackoverflow.com/a/47802790
tagged with: expression
linked to: http://stackoverflow.com/q/15774555
linked to: http://stackoverflow.com/q/29906947
has title: Can't figure out how to use expressions to validate a Canadian postal code in Python
has answer: http://stackoverflow.com/a/47803070
has comment: http://stackoverflow.com/comment/82566528
favorite count: 0
type: Question
upvote count: 4
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82566438
has body: I'm trying to make a program that takes a postal code input from the user and checks to see if it's valid. So far I have: postalCode = input("Postal code: ") postalCode = postalCode.replace(" ", "") postalCode = postalCode.lower() letters = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"] numbers = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] valid = True for i in range(0, len(postalCode), 2): if postalCode[i] not in letters or postalCode[i+1] not in numbers: valid = False break if(valid): print("Valid postal code.") else: print("Not a valid postal code.") The code runs fine, but I know using expressions would be much more viable but I haven't been able to figure out how they work. The Canadian postal code format is: L/N/L N/L/N Thanks
has answer: http://stackoverflow.com/a/47804011
downvote count: 0
tagged with: python
score: 4
has comment: http://stackoverflow.com/comment/82567193
answer count: 3

http://stackoverflow.com/comment/82369649
has text: I would suggest using the default argument of `getattr`: `getattr(Object, name, "")`. if needed replace `""` with a `name` specific default. As this is closer to the OP's code.
comment on: http://stackoverflow.com/a/47704734
type: Comment
type: AnswerComment
score: 1

http://stackoverflow.com/comment/82604834
comment on: http://stackoverflow.com/a/47807085
type: Comment
score: 0
type: AnswerComment
has text: I lied @sytech, it does have REMOTE_USER. I accidentally tested it on a page not being authenticated by my own webserver. Thank you so much for your help, I really appreciate it.

http://stackoverflow.com/comment/82611043
has text: Paul - Node and Element ID's are model dependent but I'm working with models where a large model will have ID's up to around 100 million.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47823141

http://stackoverflow.com/q/47820060
accepted answer: http://stackoverflow.com/a/47820091
has title: Python passing self to the decorator
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82602411
score: 7
tagged with: python
upvote count: 10
has body: I'm trying to pass the self object to my decorator to access its contents but get the following error: def log_decorator(): def log_real_decorator(f): @wraps(f) def wrapper(self,*args, **kw): print "I am the decorator, I know that self is", self, "and I can do whatever I want with it!" print "I also got other args:", args, kw f(*args, **kw) return wrapper return log_real_decorator class Foo(object): @log_decorator def meth(self): print "I am the method, my self is", self f = Foo() f.meth() Error:- TypeError: log_decorator() takes no arguments (1 given)
tagged with: python-decorators
type: AnsweredQuestion
tagged with: python-3.x
downvote count: 3
answer count: 1
has answer: http://stackoverflow.com/a/47820091

http://stackoverflow.com/comment/82410530
type: QuestionComment
comment on: http://stackoverflow.com/q/47724885
type: Comment
has text: What's your error message? Show the value of `seatCapacity[seat]` (it's obviously a list). `seat` itself isn't defined in your example, nor is there an example of `prices.txt`. Please post a [mcve].
score: 1

http://stackoverflow.com/comment/82636027
type: Comment
comment on: http://stackoverflow.com/q/47835123
type: QuestionComment
has text: You can try likely cases of your data in [this visualisation of search algorithms](https://qiao.github.io/PathFinding.js/visual/) and decide, which one is likely to get the fastest results.
score: 1

http://stackoverflow.com/comment/82689940
type: AnswerComment
has text: Thanks Martijn. Above thing worked like a charm. I guess it doesnt work for alpha channel,so we need to remove that first then crop the image using getbbox. But for P mode it works perfectly. Thanks !!
comment on: http://stackoverflow.com/a/47855749
score: 0
type: Comment

http://stackoverflow.com/comment/82437464
comment on: http://stackoverflow.com/a/47738575
score: 0
type: AnswerComment
type: Comment
has text: For insert, can hash table just append the item at the end of linked list? It will take constant time.

http://stackoverflow.com/comment/82366622
comment on: http://stackoverflow.com/q/47703022
score: 2
has text: @ru111 you are going to need to provide a [mcve] or else one can only guess.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47788806
tagged with: python
has answer: http://stackoverflow.com/a/47789669
accepted answer: http://stackoverflow.com/a/47789071
score: 2
has body: I categorized keywords as following nest list, Keywords_33=[('File_2', ['with', 'as']), ('Module_2', ['from', 'import']), ('Constant_3', {'bool': ['False', 'True'], 'none': ['None']}), ('Operator_4', {'boolean_operation': {'or', 'and', 'not'}, 'comparison': {'is'}}), ('Container_operation_2', ['in', 'del']), ('Klass_1', ['class']), ('Function_7',['lambda', 'def', 'pass', 'global', 'nonlocal', 'return', 'yield']), ('Repetition_4', ['while', 'for', 'continue', 'break']), ('Condition_3', ['if', 'elif', 'else']), ('Debug_2', ['assert', 'raise']), ('Exception_3', ['try', 'except', 'finally'])] I intent to confirm every keyword in place by category without any left. The most convenient I consider is to convert Keywords_33 to string firstly. from keyword import kwlist In [55]: print(kwlist) ['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield'] In [54]: from keyword import kwlist ...: s = str(Keywords_33) ...: [keyword for keyword in kwlist if keyword not in s] ...: Out[54]: [] # It indicate no keyword left How to accomplish such a task elegantly?
has title: Check intersection of two lists
has comment: http://stackoverflow.com/comment/82539066
answer count: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/82539062
downvote count: 0
has comment: http://stackoverflow.com/comment/82538886
favorite count: 0
linked to: http://stackoverflow.com/q/2158395
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47789071
possible better answer: http://stackoverflow.com/a/47789669

http://stackoverflow.com/comment/82368565
has text: @Turksarama never mind! That method fixed my problem. Thank you so much!!
comment on: http://stackoverflow.com/q/47703921
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47756075
favorite count: 0
has comment: http://stackoverflow.com/comment/82475600
type: Question
tagged with: timer
score: 3
accepted answer: http://stackoverflow.com/a/47787464
has answer: http://stackoverflow.com/a/47787464
tagged with: python
has body: I have a Python script that does stuff based on D-Bus events, simplified version of that: import dbus from dbus.mainloop.glib import DBusGMainLoop import gobject DBusGMainLoop(set_as_default=True) bus = dbus.SystemBus() # Initialize a main loop mainloop = gobject.MainLoop() bus.add_signal_receiver(cb_udisk_dev_add, signal_name='DeviceAdded', dbus_interface="org.freedesktop.UDisks") bus.add_signal_receiver(cb_udisk_dev_rem, signal_name='DeviceRemoved', dbus_interface="org.freedesktop.UDisks") mainloop.run() This calls the cb_udisk_dev_add and -rem callback functions. Now I would like to have a timed callback function which I like to call, say every 5 minutes. It seems that mainloop.run() is a blocked function, so I think I need to add a timer of sorts to the mainloop...? I have tried implementing a few periodically executing functions from: Executing periodic actions in Python but they are all blocking too, soo the mainloop.run() doesn't get executed. Any suggestions?
tagged with: gobject
has comment: http://stackoverflow.com/comment/82475875
has title: python mainloop, add timed events
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82474420
upvote count: 3
answer count: 1
downvote count: 0
linked to: http://stackoverflow.com/q/8600161

http://stackoverflow.com/comment/82655004
comment on: http://stackoverflow.com/a/47845458
score: 0
type: AnswerComment
has text: Ah, thank you! I was quite puzzled at this behaviour, and I guessed it must be something like this. Thanks for confirming!
type: Comment

http://stackoverflow.com/q/47847084
downvote count: 0
answer count: 1
favorite count: 0
type: Question
upvote count: 12
tagged with: python-3.x
has body: Using Windows 7, Python 3.5.1: import subprocess subprocess.check_output(['echo', 'hello']) raises the error: Traceback (most recent call last): File "&lt;pyshell#8&gt;", line 1, in &lt;module&gt; subprocess.check_output(['echo', 'hello']) File "D:\Programs\Python 3.5.1\lib\subprocess.py", line 629, in check_output **kwargs).stdout File "D:\Programs\Python 3.5.1\lib\subprocess.py", line 696, in run with Popen(*popenargs, **kwargs) as process: File "D:\Programs\Python 3.5.1\lib\subprocess.py", line 950, in __init__ restore_signals, start_new_session) File "D:\Programs\Python 3.5.1\lib\subprocess.py", line 1220, in _execute_child startupinfo) FileNotFoundError: [WinError 2] The system cannot find the file specified This error occurs with all subprocess calls, such as subprocess.run, subprocess.call, and subproccess.Popen. The same error happens regardless of what command is used: subprocess.check_output(['['D:\path\to\exe\program.exe', 'argument']) FileNotFoundError: [WinError 2] The system cannot find the file specified As far as I can tell, this error usually occurs when the command tries to execute a nonexistent path, but I can't determine why it would occur in these cases.
has comment: http://stackoverflow.com/comment/82658327
tagged with: python
has comment: http://stackoverflow.com/comment/82658282
has title: Python: "FileNotFoundError" on all Subprocess calls
score: 12
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47847140
accepted answer: http://stackoverflow.com/a/47847140
tagged with: subprocess

http://stackoverflow.com/a/57329092
score: 12
downvote count: 0
answers question: http://stackoverflow.com/q/47851965
has body: I had a similar problem with my serializer, until I realized that the "fields"-attribute in class Meta represents the fields of the API and not the fields of the actual model. the "source"-parameter represents the fields of the model. So if this is approximately what your model looks like: class User(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) url = models.CharField(max_length=255) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) email = models.EmailField(max_length=255) address = models.CharField(max_length=255) phone = models.CharField(max_length=255) messenger_id = models.IntegerField() Then maybe this could work: class UserSerializer(serializers.ModelSerializer): customer_email = serializers.EmailField(source='email') customer_address = serializers.CharField(source='address') customer_phone = serializers.CharField(source='phone') messenger_user_id = serializers.IntegerField(source='messenger_id') class Meta: model = User fields = ('id', 'url', 'first_name', 'last_name', 'customer_email', 'customer_address', 'customer_phone', 'messenger_user_id',)
upvote count: 12
type: Answer

http://stackoverflow.com/a/47782122
answers question: http://stackoverflow.com/q/47782076
has body: Instead of adding a timedelta of 1/4. day, you could add a timedelta(hours=6). Otherwise, since you know you want your time to increase in 0.25 increments, you could simply generate an array of floats from the get go. Note that, on my version of python3, timetuple().tm_yday returns an integer, not a float.
score: 0
type: Answer

http://stackoverflow.com/a/47719109
type: Answer
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/47716539
score: 2
has body: Hellow ! I saw that you have already mentioned this issue as resolved. any way... you can add a description parameter in flask.abord() so it make sens to: falsk.abord(404, description="Lorem ipsum dolor...") @app.errorhandler(404) def page_not_found(e): return "{}, {}".format(e.message, e.description)

http://stackoverflow.com/comment/82417424
type: AnswerComment
comment on: http://stackoverflow.com/a/47728522
score: 0
type: Comment
has text: both the commands say there is only version of python is installed and that is the native version of python shipped with osx. what brew installed is called python2 not python. how do I fix this?

http://stackoverflow.com/q/47746025
has title: AttributeError: 'res.partner' object has no attribute 'journal_id' - Odoo v8
has body: I have this method: @api.multi @api.depends('order_picking', 'order_picking.isbn', 'contract_worksheet', 'state') def accounting_scenarios(self): for record in self: if not len(record.transporter): raise Warning('Please Enter Transporter !') elif not len(record.transporter.transp_transit): raise Warning('Please assign transit account to the transporter !') if record.state in ('awaitingraw'): #('cancel', 'done') acc_move = self.env['account.move'] move_lines = [ (0, 0, { 'name': 'name', 'debit': record.contract_worksheet.total_alles, 'credit': record.contract_worksheet.total_alles, 'account_id': record.transporter.transp_transit, 'date': date, 'partner_id': record.transporter, }), ] acc_move.create({ #'period_id': period_id, 'journal_id': record.transporter.journal_id.id, 'date':date, 'state': 'draft', 'line_id': move_lines, # this is one2many field to account.move.line }) elif record.state in ('work_in_progress'): record.temp2 = record.contract_worksheet.total_totals elif record.state in ('delivered'): record.transporter.transp_transit.debit = record.contract_worksheet.total_alles It throws me this: Traceback (most recent call last): File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\http.py", line 546, in _handle_exception File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\http.py", line 583, in dispatch File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\http.py", line 319, in _call_function File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\service\model.py", line 118, in wrapper File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\http.py", line 316, in checked_call File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\http.py", line 812, in __call__ File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\http.py", line 412, in response_wrap File "C:\Program Files (x86)\Odoo 8.0-20170914\server\openerp\addons\web\controllers\main.py", line 948, in call_button File "C:\Program Files (…
tagged with: python-2.7
type: AnsweredQuestion
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/82453681
accepted answer: http://stackoverflow.com/a/47752360
type: Question
has answer: http://stackoverflow.com/a/47752360
tagged with: odoo
tagged with: odoo-8
tagged with: python

http://stackoverflow.com/comment/82654260
has text: "we have never" should become "459 151439 27943935"
score: 0
comment on: http://stackoverflow.com/q/47844961
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82668995
type: QuestionComment
has text: If you've used threads in the Mac program, that could be an issue. If you're using Python 3, you'd want to try the [`spawn` start method](https://docs.python.org/3/library/multiprocessing.html#contexts-and-start-methods) on Mac too
comment on: http://stackoverflow.com/q/47852237
score: 1
type: Comment

mne-python
type: Tag
tags question: http://stackoverflow.com/q/47746683
tag name: mne-python

http://stackoverflow.com/q/47761625
favorite count: 0
type: Question
tagged with: python
tagged with: sqlalchemy
upvote count: 4
has body: I'm trying to filter a sqlalchemy query. My table is defined like this: class Classroom(db.Model, Entity): classroom_id = db.Column('classroom_id', db.Integer, primary_key=True) teachers = db.relationship( "User", secondary=lambda: classroom_teacher_table ) Where User is another table (with a user_id column). I want to query Classrooms to find all the classrooms in which the first teacher in the teachers list has a particular user_id. I am able to query classrooms to find all the classrooms in which ANY teacher in the teachers list has a particular user_id like this: tclassrooms = Classroom.query tclassrooms = tclassrooms.filter(Classroom.teachers.any(user_id=id)).all() But I can't figure out how to check only against the first teacher in the list. I've tried: tclassrooms = tclassrooms.filter(Classroom.teachers[0]['user_id']==id).all() and a bunch of variations on that, but always with an error like Traceback (most recent call last): File "/usr/local/lib/python2.7/site-packages/sqlalchemy/sql/operators.py", line 346, in __getitem__ return self.operate(getitem, index) File "/usr/local/lib/python2.7/site-packages/sqlalchemy/orm/attributes.py", line 175, in operate return op(self.comparator, *other, **kwargs) File "/usr/local/lib/python2.7/site-packages/sqlalchemy/sql/operators.py", line 346, in __getitem__ return self.operate(getitem, index) File "/usr/local/lib/python2.7/site-packages/sqlalchemy/sql/operators.py", line 186, in operate raise NotImplementedError(str(op)) Any ideas?
answer count: 0
type: UnansweredQuestion
downvote count: 0
score: 4
has title: sqlalchemy filter against first item in relationship's list
tagged with: flask-sqlalchemy
has comment: http://stackoverflow.com/comment/94561466

http://stackoverflow.com/comment/82454481
has text: (df['College/Univ'] == 'Texas A&M').sum() this worked~ Thanks
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47747201
score: 0

http://stackoverflow.com/q/47800726
tagged with: django
tagged with: python
score: 15
answer count: 11
has answer: http://stackoverflow.com/a/63007037
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/78146995
upvote count: 15
has answer: http://stackoverflow.com/a/51717399
downvote count: 0
has answer: http://stackoverflow.com/a/59416840
has comment: http://stackoverflow.com/comment/87165062
favorite count: 0
has answer: http://stackoverflow.com/a/55048316
type: Question
accepted answer: http://stackoverflow.com/a/55059670
possible better answer: http://stackoverflow.com/a/50456589
has comment: http://stackoverflow.com/comment/84653493
has answer: http://stackoverflow.com/a/55059670
has answer: http://stackoverflow.com/a/57106629
has answer: http://stackoverflow.com/a/50456589
has answer: http://stackoverflow.com/a/71526035
has answer: http://stackoverflow.com/a/73708439
tagged with: wsgi
has answer: http://stackoverflow.com/a/50325315
has title: Django ImproperlyConfigured: WSGI application 'myproject.wsgi.application' could not be loaded; Error importing module
has body: I have an almost fresh install of django and when I run python manage.py runserver. It is giving me this error: ImproperlyConfigured: WSGI application 'myproject.wsgi.application' could not be loaded; Error importing module. settings.py WSGI_APPLICATION = 'myproject.wsgi.application' wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings") application = get_wsgi_application()

http://stackoverflow.com/a/47847169
has comment: http://stackoverflow.com/comment/82658508
has comment: http://stackoverflow.com/comment/82658486
answers question: http://stackoverflow.com/q/47847111
has body: You can do the following: def increasing(m): return all(sum(r1) &lt; sum(r2) for r1, r2 in zip(m, m[1:])) This uses zip to pair adjacent rows and all to efficiently do the pairwise sum comparison. Without zip: return all(sum(m[i-1]) &lt; sum(m[i]) for i in range(1, len(m)))
score: 10
upvote count: 10
has comment: http://stackoverflow.com/comment/82658674
has comment: http://stackoverflow.com/comment/82658605
downvote count: 0
type: Answer

http://stackoverflow.com/a/47851306
has body: If any parts of the web page is rendered dynamically, for example using Javascript, beautifulsoup might not be able to work with that. I use Selenium + PhantomJS. I load the page (wait for it to fully load) and then enter the login details. Selenium has nice API which lets you programmatically check for specific html elements and wait for them to appear which is very useful in such cases.
score: 1
accepted answer of: http://stackoverflow.com/q/47851288
type: Answer
answers question: http://stackoverflow.com/q/47851288
downvote count: 0
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/a/47825757
has comment: http://stackoverflow.com/comment/82615343
type: Answer
has comment: http://stackoverflow.com/comment/82614058
has body: Let's use set_index, unstack and fillna: df.set_index(['shop_id','item_id','date'])['sales'].unstack()\ .add_prefix('date_').reset_index().fillna(0).astype(int) Output: date shop_id item_id date_0 date_1 date_2 date_3 0 0 19 1 0 13 11 1 1 19 0 3 0 0
score: 2
upvote count: 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47825709
downvote count: 0
has comment: http://stackoverflow.com/comment/82613951
answers question: http://stackoverflow.com/q/47825709

http://stackoverflow.com/comment/82548840
type: Comment
type: AnswerComment
has text: Thank you so much! that paragraph is required for mu programming class. its nothing really important.
comment on: http://stackoverflow.com/a/47755620
score: 1

http://stackoverflow.com/comment/82497370
has text: I think InMemoryUploadedFile class in Django may be useful for you. Because my code context is different with yours , I can't give you the example code, but you can do try it
comment on: http://stackoverflow.com/q/47767901
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82826081
has text: You are missing a bunch of '*' in your code.
comment on: http://stackoverflow.com/q/47821301
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/a/73681471
has body: There are two cases: i) train data feature/column having more categories than test column ii) test data feature/column having more categories than corresponding train column test data should only be transformed using encoding, not fit&amp;transform. The general case of OHE usage: onehotencoder=OneHotEncoder() enc_data_train=onehotencoder.fit_transform(X_train[cat_columns]).toarray()) X_train=X_train[num_columns].join(enc_data_train) enc_data_test=onehotencoder.transform(X_test[cat_columns]).toarray()) X_test=X_test[num_columns].join(enc_data_test) cat_columns are the categorical columns and num_columns are the numerical columns. You never fit X_test. The following code is wrong X_test=onehotencoder.fit_transform(X_test[cat_columns]).toarray()). this is not how we should encode test data. Now coming to the problem of mismatch.Train or Test having different number of categories, so different number of columns. Two ways to solve it: i) fit using the entire data (train &amp; test) and only transform X_train and X_test ii) ignore new features in test i) example code onehotencoder=OneHotEncoder() enc_data=onehotencoder.fit(X[cat_columns]) X_train, X_test, Y_train, Y_test = train_test_split(X, Y, random_state=0, train_size = .75) enc_data_train= pd.DataFrame (onehotencoder.transform(X_train[cat_columns]).toarray()) X_train=X_trainnum_columns.join(enc_data_train) enc_data_test=pd.DataFrame (onehotencoder.transform(X_test[cat_columns]).toarray()) X_test=X_testnum_columns.join(enc_data_test) ii) using handle_unknown, fit&amp;transform using train onehotencoder=OneHotEncoder(handle_unknown='ignore') enc_data_train=pd.DataFrame (onehotencoder.fit_transform(X_train[cat_columns]).toarray()) X_train=X_trainnum_columns.join(enc_data_train) enc_data_test=pd.DataFrame (onehotencoder.transform(X_test[cat_columns]).toarray()) X_test=X_testnum_columns.join(enc_data_test) This second way will ignore the new features in test. The number of columns will be same in both trai…
answers question: http://stackoverflow.com/q/47786637
type: Answer
score: 0

http://stackoverflow.com/comment/82557119
comment on: http://stackoverflow.com/a/47796623
type: Comment
has text: Sounds like what you need is a source search followed by source fitting. It's a non-trivial problem and the algorithms to choose depend on your data and how much time you want to invest to do something simple or fancy. There's a ton of papers in astronomy and image processing concerning source search and making catalogs and fitting sources. Are you aware of https://photutils.readthedocs.io ? Trying a few of the methods available there might be a good starting point.
score: 2
type: AnswerComment

http://stackoverflow.com/comment/82641589
comment on: http://stackoverflow.com/q/47831287
score: 0
has text: Getting `ValueError: mismatch between the number of fields and the number of arrays` for the edited sample. I am on 1.13.3 NumPy, Python 2.7.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82466033
comment on: http://stackoverflow.com/q/47752711
type: Comment
has text: In pandas 0.21, sum of all NaNs returns NaN. So if I do what you suggest, I would then have to apply a mask for the case when both dataframe and series are NaN. Nothing crazy, but I am just surprised pandas does not support the operation I described above and I would like to know if there's a better solution.
score: 0
type: QuestionComment

http://stackoverflow.com/a/54566900
downvote count: 0
has body: My problem was caused by indentation mismatch. Most of the document was indented with spaces but there were some tabs copied in that caused the Py:DEDENT error. Replacing the tabs with spaces fixed the error.
score: 9
upvote count: 9
type: Answer
answers question: http://stackoverflow.com/q/47776315

http://stackoverflow.com/q/47764876
tagged with: python-3.x
tagged with: pyinstaller
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47764891
tagged with: python
downvote count: 0
has comment: http://stackoverflow.com/comment/82494952
has body: I am trying to cythonise a python file. I get: python setup.py build_ext --inplace 'python' is not recognized as an internal or external command, operable program or batch file. I have installed visual Studio, downloaded cython, setuptools through pip. Any idea how I can fix this issue? This issue seem to pop up when I reinstall python. set %path%; C:\Users\13\Miniconda3 C:\Users\13\Miniconda3 not defined
score: 1
upvote count: 1
answer count: 1
tagged with: cython
has title: 'python' is not recognized as an internal or external command python setup.py build_ext --inplace
favorite count: 0
type: Question

http://stackoverflow.com/q/47722877
has answer: http://stackoverflow.com/a/47722943
type: UnansweredQuestion
has title: How to increment numbers on the end of variables?
tagged with: python
has body: I have a Python/Tkinter program and I am trying to increment some numbers that are at the end of a variable used for tk.Entry boxes. For example, self.output0, self.output1, self.output2, etc (Sorry, my code is long so I tried shortening it up for an example.) self.entries = [] self.output0 = tk.Entry(self, width=149, justify='center', bd='0', bg='#E0E0E0') self.output0.grid(column=0, row=6, columnspan=5, padx=1) self.output1 = tk.Entry(self, width=149, justify='center', bd='0', bg='#E0E0E0') self.output1.grid(column=0, row=7, columnspan=5, padx=1) I grab the users input with another entry box such as 'self.first_entry' and run a SQL query on the user input. For example: class Adder(ttk.Frame): """The adders gui and functions.""" def __init__(self, parent, *args, **kwargs): ttk.Frame.__init__(self, parent, *args, **kwargs) self.root = parent self.init_gui() def authenticate(self): return pypyodbc.connect('Driver={SQL Server};Server=MYSERVERNAME;Database=MYDATABASENAME;Trusted_Connection=yes;') def calculate(self): firstname = str(self.first_entry.get()) # converts user entry into variable lastname = str(self.last_entry.get()) license = str(self.lic_entry.get()) try: connection = self.authenticate() except pypyodbc.Error as ex: sqlstate = ex.args[0] if sqlstate == '28000': self.output0.delete(0, END) self.output0.insert(0,"You do not have access.") cursor = connection.cursor() if (firstname and not lastname and not license): # "You entered first name." SQLCommand = ("SELECT LASTNAME, FIRSTNAME, LICNUMBER " "FROM MyTABLEName " # table name "with (nolock)" "WHERE FIRSTNAME LIKE ?") Values = [firstname + '%'] else: SQLCommand = ("SELECT LASTNAME, FIRSTNAME, LICNUMBER " "FROM MyTABLEName " # table name "(nolock)" "WHERE FIRSTNAME LIKE ? AND LASTNAME LIKE ? AND LICNUMBER LIKE ?") Values = [firstname + '%', lastname + '%', '%' + license + '%'] cursor.execute(SQLCommand,Values) results = cursor.fetchmany(10) if results: self.output0.delete(0, END) # clears entry self.output…
tagged with: tkinter
has comment: http://stackoverflow.com/comment/82406505
score: 0
answer count: 1
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82406921

http://stackoverflow.com/comment/82478075
type: QuestionComment
score: 0
has text: What's the question that you have?
comment on: http://stackoverflow.com/q/47758409
type: Comment

http://stackoverflow.com/a/47834251
score: 1
type: Answer
has body: Create method like this; def get_letter(number){ if number%3 == 0: data[i] ='a' if number%3 == 1: data[i] ='b' if number%3 == 2: data[i] ='c' } And call in main function; data = [2, 0, 5, 1, 0] data2 = [] for i in range (len(data)): data2.append(get_letter(data[i])); print data2;
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47834078

http://stackoverflow.com/q/47725669
has answer: http://stackoverflow.com/a/47725871
type: Question
has title: Upload_Path_Handler file path for Django ImageField cannot retrieve image in HTML file
upvote count: 2
type: UnansweredQuestion
downvote count: 2
answer count: 1
tagged with: django
has body: I've attempted to use Upload_Path_Handler in order to allow for dynamic folder names (such as the upload date, item ID, etc.) in saving image files uploaded by users, so as to prevent duplicate instances. The problem is that the directory which I've returned is too 'deep' to be retrieved through the HTML file, in that, it begins with the name of the app (in this case, 'vault'). The broken path served for the image in the HTML file is as follows: &lt;img src="vault/static/vault/images/recordimages/r_1/2017-12-09_03-27-42/300x300.jpg"&gt; However, by using inspector element to exclude the app name 'vault' at the beginning, I am able to successfully retrieve the image: &lt;img src="/static/vault/images/recordimages/r_1/2017-12-09_03-27-42/300x300.jpg"&gt; The broken path is served in the raw html file as: &lt;img src="{{ record.w_image }}"&gt; And the model referenced, w_image, is as follows in models.py: w_image = models.ImageField(null=False, blank=True, verbose_name='Record Image:', upload_to=upload_path_handler) Then, of course, is upload_path_handler: def upload_path_handler(self, filename): return "vault/static/vault/images/recordimages/r_{id}/{date}/{file}".format(id=self.id, file=filename, date=datetime.datetime.utcnow().strftime('%Y-%m-%d_%H-%M-%S')) If I were to begin the return path at /static/, it would then instead save the images in WebsiteName/static/../.. as opposed to WebsiteName/vault/static/../.. (Remember, the aim here is to keep the /static/ directory a subdirectory of our app, 'vault') How can I allow for the image to be retrievable without compromising on the path as a subdirectory of 'vault'?
tagged with: python
favorite count: 0
score: 0
has comment: http://stackoverflow.com/comment/82414815
tagged with: http://stackoverflow.com/tag/html
tagged with: django-models

http://stackoverflow.com/comment/126841030
type: QuestionComment
comment on: http://stackoverflow.com/q/47743154
has text: I have the same question. Surprised this hasn't been answered adequately in 4 years
score: 0
type: Comment

http://stackoverflow.com/q/47788417
answer count: 1
tagged with: selenium
has title: Selenium PhantomJS webdriver get partial screenshot
has answer: http://stackoverflow.com/a/47794982
tagged with: phantomjs
score: 0
has body: This code save full web page, but I need to save just first view that user see(without scrolling down). Is it possible? browser = webdriver.PhantomJS() browser.set_window_size(1920, 1080) browser.set_page_load_timeout(60) browser.get(url) browser.save_screenshot(png_path) Update: Here is example of save_screenshot of https://github.com/keras-team/keras/issues/3223, but I'm looking just for first view that user can see when he loads the page.
tagged with: python
linked to: http://stackoverflow.com/q/44770796
type: Question
has comment: http://stackoverflow.com/comment/82547948
tagged with: screenshot
type: UnansweredQuestion

http://stackoverflow.com/comment/82391330
has text: I don't know why but the output of this code gives me a completelt empty 0 KB csv file
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47710363

http://stackoverflow.com/comment/139855580
score: 0
type: AnswerComment
has text: Note that the approach of iterating through the collections breaks in [version 3.8.0](https://matplotlib.org/stable/api/prev_api_changes/api_changes_3.8.0.html#contourset-is-now-a-single-collection): this can simply be replaced by `cs.set_rasterized(True)`. See [issue #27669](https://github.com/matplotlib/matplotlib/issues/27669).
type: Comment
comment on: http://stackoverflow.com/a/47704213

http://stackoverflow.com/a/47891763
downvote count: 0
type: Answer
has body: You need to use all items of each dict while sorting, and d.items() iterates items in arbitrary order, so they need to be sorted. And this is your sorting key: a = [{1: 2, 7: 8}, {7: 8, 3: 4}, {5: 6}] b = [{3: 4, 7: 8}, {7: 8, 1: 2}, {5: 6}] sorted(a, key=lambda d: sorted(d.items())) Out: [{1: 2, 7: 8}, {3: 4, 7: 8}, {5: 6}] sorted(b, key=lambda d: sorted(d.items())) Out: [{1: 2, 7: 8}, {3: 4, 7: 8}, {5: 6}] x = [{1: 2},{1: 3}] y = [{1: 3},{1: 2}] sorted(x, key=lambda d: sorted(d.items())) Out: [{1: 2}, {1: 3}] sorted(y, key=lambda d: sorted(d.items())) Out: [{1: 2}, {1: 3}] Note that sorted(a, key=...) creates a new list, while a.sort(key=...) makes sorting in place.
accepted answer of: http://stackoverflow.com/q/47795746
score: 3
answers question: http://stackoverflow.com/q/47795746
upvote count: 3
has comment: http://stackoverflow.com/comment/116615253
has comment: http://stackoverflow.com/comment/82772738
has comment: http://stackoverflow.com/comment/82772736
type: AcceptedAnswer

http://stackoverflow.com/q/47699012
tagged with: geocoding
has comment: http://stackoverflow.com/comment/82399410
has answer: http://stackoverflow.com/a/64177873
has body: I am using the geocoder package in Python to obtain the coordinates for a set of addresses (around 30k). I get the following error: Status code Unknown from https://maps.googleapis.com/maps/api/geocode/json: ERROR - HTTPSConnectionPool(host='maps.googleapis.com', port=443): Max retries exceeded with url: /maps/api/geocode/json?address=Rancho+Palos+Verdes%2CCA%2CUS&amp;bounds=&amp;components=&amp;region=&amp;language= (Caused by ProxyError('Cannot connect to proxy.', timeout('timed out',))) The number of times I receive the error reduces if I add the time.sleep(x) function but it significantly increases the time taken to execute the code. Is there a more efficient way to run the code? Following is a snippet of the code: for add in clean_address: g=geocoder.google(add) time.sleep(7) if(g.ok==True): lat.append(str(g.lat)) lon.append(str(g.lng)) if(g.ok==False): lat.append("") lon.append("")
type: Question
answer count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/47699209
has comment: http://stackoverflow.com/comment/82358159
has title: Geocoding in Python
favorite count: 0
tagged with: python-3.x
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48712298
upvote count: 3
score: 3
accepted answer: http://stackoverflow.com/a/48712298
has comment: http://stackoverflow.com/comment/84423413
has comment: http://stackoverflow.com/comment/84421779
has comment: http://stackoverflow.com/comment/82358191
tagged with: python
possible better answer: http://stackoverflow.com/a/64177873

http://stackoverflow.com/comment/82421280
has text: Yes. According to the documentation on the Oracle page, MMM should accomplish that, but no format i've tried as any effect. https://docs.oracle.com/javase/tutorial/i18n/format/simpleDateFormat.html
type: QuestionComment
comment on: http://stackoverflow.com/q/47730265
type: Comment
score: 0

http://stackoverflow.com/comment/82373222
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47706494
has text: Also, this loop is totally pointless. Just do `x_train = np.array(sensor_data).flatten()`
score: 1

http://stackoverflow.com/a/47855159
answers question: http://stackoverflow.com/q/47854978
type: AcceptedAnswer
type: Answer
has body: Still not sure I understand exactly what you want to do. But if it's only about adding # in URL then you can simply aplly this solution: url = "http://centrebet.com/" current_url = driver.current_url # http://centrebet.com/Sports/12313443 new_url = url + "#".join(current_url.split(url)) # http://centrebet.com/#Sports/12313443 or url = "http://centrebet.com/" current_url = driver.current_url # http://centrebet.com/Sports/12313443 new_url = current_url.replace(url, url + "#") # http://centrebet.com/#Sports/12313443
accepted answer of: http://stackoverflow.com/q/47854978
score: 0

http://stackoverflow.com/a/47871089
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47810164
score: 1
type: Answer
has body: As it is a spark cluster, lib must be installed on every node. Therefore, I need to execute the install command via the "script action" on the HD Insight interface. But, as I am using a virtual env, the command needs the -n env option to be added. The final command to run is : #!/usr/bin/env bash /usr/bin/anaconda/bin/conda install -c conda-forge shapely -n py35
accepted answer of: http://stackoverflow.com/q/47810164
type: AcceptedAnswer

http://stackoverflow.com/q/47765478
has body: After reading my csv file using read_csv() in Pandas, I want to convert some of the column dataypes to float64 for further processing, since they are currently represented as object dtype. Upon trying the attribute dtype in read_csv, I get the error. Following is the description: import pandas as pd file_ = pd.read_csv("/home/rahul/yearly_data_no_ecb.csv", dtype = {"DAX":"float64"}) Following is the full trace for the error: ValueError Traceback (most recent call last) &lt;ipython-input-14-554c18573267&gt; in &lt;module&gt;() ----&gt; 1 file_ = pd.read_csv("/home/rahul/yearly_data_no_ecb.csv", dtype = {"DAX":"float64"}) 2 #file1 = pd.to_numeric(file_) 3 file_.values 4 file_.dtypes /home/rahul/anaconda/lib/python2.7/site-packages/pandas/io/parsers.pyc in parser_f(filepath_or_buffer, sep, delimiter, header, names, index_col, usecols, squeeze, prefix, mangle_dupe_cols, dtype, engine, converters, true_values, false_values, skipinitialspace, skiprows, nrows, na_values, keep_default_na, na_filter, verbose, skip_blank_lines, parse_dates, infer_datetime_format, keep_date_col, date_parser, dayfirst, iterator, chunksize, compression, thousands, decimal, lineterminator, quotechar, quoting, escapechar, comment, encoding, dialect, tupleize_cols, error_bad_lines, warn_bad_lines, skipfooter, skip_footer, doublequote, delim_whitespace, as_recarray, compact_ints, use_unsigned, low_memory, buffer_lines, memory_map, float_precision) 703 skip_blank_lines=skip_blank_lines) 704 --&gt; 705 return _read(filepath_or_buffer, kwds) 706 707 parser_f.__name__ = name /home/rahul/anaconda/lib/python2.7/site-packages/pandas/io/parsers.pyc in _read(filepath_or_buffer, kwds) 449 450 try: --&gt; 451 data = parser.read(nrows) 452 finally: 453 parser.close() /home/rahul/anaconda/lib/python2.7/site-packages/pandas/io/parsers.pyc in read(self, nrows) 1063 raise ValueError('skipfooter not supported for iteration') 1064 -&gt; 1065 ret = self._engine.read(nrows) 1066 1067 if self.options.get('as_recarray'):…
accepted answer: http://stackoverflow.com/a/47765823
tagged with: http://stackoverflow.com/tag/csv
answer count: 2
has answer: http://stackoverflow.com/a/47765695
has answer: http://stackoverflow.com/a/47765823
tagged with: python
tagged with: python-2.7
tagged with: pandas
score: 2
upvote count: 2
type: AnsweredQuestion
downvote count: 0
favorite count: 0
has title: Changing the datatype of specific dataframe columns - Pandas
possible better answer: http://stackoverflow.com/a/47765695
type: Question

http://stackoverflow.com/a/47766087
has comment: http://stackoverflow.com/comment/138598070
accepted answer of: http://stackoverflow.com/q/47766045
upvote count: 5
type: Answer
answers question: http://stackoverflow.com/q/47766045
score: 5
has body: {% csrf_token %} Repeat Sentence? Next and in view if request.method=="POST": form = AnnotateForm(request.POST) if form.is_valid(): print(request.POST)#prints only csrf_token in Query_dict print(form.cleaned_data["something"])#Always false you need to give a name in the input field or else it wont be captured
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/82477114
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47747211
type: QuestionComment
has text: Thanks, I will look into that. I did find a torch.multiprocessing module and was trying it out yesterday, but I'm running into a memory error in my GPU (no memory error before), so I must be doing something wrong.

http://stackoverflow.com/comment/83257395
has text: Yes, I made that pull request in addition to answering the question. However, I will still need to add rasterization to all mpl3d methods.
comment on: http://stackoverflow.com/a/47821219
score: 1
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/82378213
has text: Meanwhile I will try to take some inspiration from this http://matthewrocklin.com/blog/work/2017/10/16/streaming-dataframes-1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47709010
score: 0

key
tags question: http://stackoverflow.com/q/47855725
type: Tag
tag name: key
tags question: http://stackoverflow.com/q/47821377
tags question: http://stackoverflow.com/q/47732604
tags question: http://stackoverflow.com/q/47770786

http://stackoverflow.com/comment/82500662
score: 0
type: Comment
type: QuestionComment
has text: `break` specifically means "stop the loop". you probably want another loop, where this is just the beginning part of it..
comment on: http://stackoverflow.com/q/47769790

http://stackoverflow.com/comment/82478655
type: Comment
has text: ya is 9, sorry for the typo
score: 0
comment on: http://stackoverflow.com/q/47758720
type: QuestionComment

display
tags question: http://stackoverflow.com/q/47852048
type: Tag
tag name: display

http://stackoverflow.com/comment/82533657
score: 0
type: Comment
has text: So I know this isn't what was initially asked but what would I do I wanted to encode the number in a character format. For example, a = 0, b = 1, etc
type: AnswerComment
comment on: http://stackoverflow.com/a/47786031

http://stackoverflow.com/q/47814557
has comment: http://stackoverflow.com/comment/82591083
score: 0
has answer: http://stackoverflow.com/a/47815680
answer count: 1
tagged with: arrays
has comment: http://stackoverflow.com/comment/82590882
type: Question
type: UnansweredQuestion
has title: How to get compare variables of a list individually?
tagged with: python
has comment: http://stackoverflow.com/comment/82590878
has body: So I have this code below that I'm trying to make, to where it will sort any list I give it so the lowest variable will be at the beginning, in position [0]. The problem I think is when the while loop comes in it compares uList[y] to the sum of uList[z:p] but, I was hoping it would compare it to each of the numbers individually so that if uList[y] is greater than ANY variable in uList[z:p] it would step into the loop how ever it does not. How would I go about making it compare the variables individually rather to the sum of them all, if that is whats happening. Code: import random import sys import os import time clear = lambda: os.system('cls') clear() y = 0 z = 1 x = 0 nNum = 1 uList = [] sList = [] listL = int(raw_input("How many elements would you like to be in your list?")) clear() while x &lt; listL: uList.append(int(raw_input("Num %s:" %(nNum)))) x = x + 1 nNum = nNum + 1 p = len(uList) - 1 clear() print("Your list was %s!" %(uList)) while z &lt;= p: while uList[y] &gt; uList[z]: j = uList[y] del uList[y] uList.append(j) print(uList) P.S. Any other tips or advice on anything about my code would be greatly appreciated as I am very obviously knew to python and coding in general lol, thank you so much!

http://stackoverflow.com/q/47723819
downvote count: 2
answer count: 1
has comment: http://stackoverflow.com/comment/82408461
has comment: http://stackoverflow.com/comment/82410463
has comment: http://stackoverflow.com/comment/82410422
favorite count: 0
type: Question
has body: I am creating a program that checks for a password's strength. I want to block the ability for someone to type a commonly used password such as 'Password1'. I was also looking into password entropy and couldn't really figure out how to incorporate that into my code. I'm new with python and have been trying my best, so please forgive me. Maybe some of you have ideas on what I can do. import re def password(): print ('Hello and welcome to Austin’s Password Checker!\n\nThe password must be between 6 and 12 characters\n\nConsider a capital, lowercase and number for best results!\n') while True: password = input('Enter a password:') if 6 &lt;= len(password) &lt; 12: break print ('The password must be between 6 and 12 characters.\nConsider having a capital, lowercase and a number for best results!') password_scores = {0:'Terrible', 1:'Weak', 2:'Medium', 3:'Strong'} password_strength = dict.fromkeys(['up', 'down', 'num','spcl'], False) if re.search(r'[A-Z]', password): password_strength['up'] = True if re.search(r'[a-z]', password): password_strength['down'] = True if re.search(r'[0-9]', password): password_strength['num'] = True score = len([b for b in password_strength.values() if b]) print ('Password is %s' % password_scores[score]) password()
score: -2
has answer: http://stackoverflow.com/a/47723877
tagged with: python
has comment: http://stackoverflow.com/comment/82409940
has comment: http://stackoverflow.com/comment/82408350
has title: How to stop submissions of commonly used passwords
upvote count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/124134772
comment on: http://stackoverflow.com/a/67501637
type: Comment
has text: Thanks, I spent too long racking my brain on this. I used `django-admin makemigrations users` instead of `python manage.py makemigrations users`
score: 0
type: AnswerComment

http://stackoverflow.com/a/47734845
has body: Here's an alternative a way to get what you're looking for with Pandas: import pandas as pd sdd = {k:[x for x in v] for k,v in student_data_dict} df = pd.DataFrame(sdd) df = df.reindex_axis(sorted(df.columns, key = lambda col: int(col.split("_")[-1])), axis=1) df.index = [f"Question {i+1}" for i in df.index] {k:''.join(v) for k,v in zip(df.index, df.values)}
score: 0
answers question: http://stackoverflow.com/q/47734740
type: Answer

http://stackoverflow.com/comment/82391270
score: 0
type: QuestionComment
has text: I have not, but i will check it out :D
type: Comment
comment on: http://stackoverflow.com/q/47714805

http://stackoverflow.com/comment/82399910
type: AnswerComment
comment on: http://stackoverflow.com/a/47716315
score: 0
type: Comment
has text: btw: google or duckduckgo etc works fine...do you have an idea what the problem could be here?

http://stackoverflow.com/comment/82680249
comment on: http://stackoverflow.com/a/47857429
has text: You're totally asking the wrong guy about that. I don't ever choose to use either Qt or GTK in my applications, but I'm deeply biased having written parts of Tk.
score: 1
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47764684
tagged with: python
has comment: http://stackoverflow.com/comment/128113980
score: 4
upvote count: 4
has comment: http://stackoverflow.com/comment/82490947
has body: I am using python apscheduler module to trigger job at irregular intervals for example at 1:30 AM and 11:10 PM on every day, but not able to find a solution to this. Could you please help me how to do it. I don't want to create two jobs, one for 1:30 AM and 11:10 PM. At least let me know how to do it with crontab so that I will do same with apscheduler. Thanks. I went through this link https://apscheduler.readthedocs.io/en/v2.1.2/cronschedule.html#available-fields but not getting an idea of how to do it.
type: AnsweredQuestion
has title: How to use apscheduler to trigger job at specific times?
downvote count: 0
has answer: http://stackoverflow.com/a/47810565
accepted answer: http://stackoverflow.com/a/47810565
tagged with: apscheduler
answer count: 1
has comment: http://stackoverflow.com/comment/82490919
favorite count: 0
type: Question

http://stackoverflow.com/comment/82578419
has text: @You'reawesome https://imgur.com/a/GfOf7
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47807902

http://stackoverflow.com/q/47821792
tagged with: list
has title: Python list addition and equating variables
has comment: http://stackoverflow.com/comment/82606133
has comment: http://stackoverflow.com/comment/82606821
has comment: http://stackoverflow.com/comment/82606752
score: 1
has answer: http://stackoverflow.com/a/47821857
has comment: http://stackoverflow.com/comment/82606194
favorite count: 0
type: Question
answer count: 2
has body: I have the following code def do_something(a,b): a.insert(0, 'z') b = ['z'] + b a = ['a', 'b', 'c'] a1 = a a2 = a[:] b = ['a', 'b', 'c'] b1 = b b2 = [:] do_something(a,b) After this is executed, these are what all the variables refer to: a = ['z','a','b','c'] a1 = ['z','a','b','c'] a2 = ['a','b','c'] b = ['a','b','c'] b1 = ['a','b','c'] b2 = ['a','b','c'] My questions are: why did a1 change to include 'z' but a2 did not? why did b, b1 and b2 not change at all even though b = ['z'] + b was executed? Thank you
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82606355
downvote count: 0
upvote count: 1
tagged with: python
tagged with: variables
has answer: http://stackoverflow.com/a/47821866
has comment: http://stackoverflow.com/comment/82606287
has comment: http://stackoverflow.com/comment/82606316

http://stackoverflow.com/a/47767655
score: 1
has comment: http://stackoverflow.com/comment/82497058
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47767183
answers question: http://stackoverflow.com/q/47767183
type: Answer
has comment: http://stackoverflow.com/comment/82497150
has body: If i understand your problem correct you can just read in the hole dataframe as one and then use transform to find the last date corresponding to each hash and then drop duplicates of hash and keep the first entry. df = pd.concat([ pd.read_csv("real_estate(" + date.strftime("%d-%m-%Y") + ").csv") for date in daterange(start_date, end_date) ]) df = df.sort_values('date') df['last_seen'] = df.groupby('hash_id')['date'].transform('last') df = df.drop_duplicates(subset='hash_id', keep='first')

http://stackoverflow.com/comment/82622290
type: QuestionComment
has text: I installed 3 but still the error showed up.So i read up in a blog and tried to changed the google-webdesigner.postrm file by adding permission but the files could not be updated because it did not allow to change the permission.
comment on: http://stackoverflow.com/q/47788346
score: 0
type: Comment

http://stackoverflow.com/comment/82369087
score: 0
has text: Welcome to StackOverflow. Please read and follow the posting guidelines in the help documentation. [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: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47704461

http://stackoverflow.com/a/71984361
answers question: http://stackoverflow.com/q/47715337
has body: One option is with conditional_join from pyjanitor, which avoids a cartesian join (helpful with memory, and performance, depending on the data size): # pip install pyjanitor import pandas as pd import janitor (df_B .conditional_join( df_A, ('created_date', 'amin', '&gt;='), ('created_date', 'amax', '&lt;='), how = 'right') .assign(label = lambda df: df.created_date.notna().astype(int)) .drop(columns='created_date') ) amin amax label 0 2016-07-16 19:37:03 2016-07-17 11:16:32 1 1 2016-07-04 21:15:54 2016-07-05 10:57:46 1 2 2016-07-24 23:30:41 2016-07-25 15:38:02 0 3 2016-07-12 03:02:38 2016-07-12 22:11:01 1
score: 0
type: Answer

http://stackoverflow.com/q/47809195
has title: How to maintain constant record result when separated by comma using python?
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82579712
has comment: http://stackoverflow.com/comment/82579798
has comment: http://stackoverflow.com/comment/82580354
has comment: http://stackoverflow.com/comment/82579945
downvote count: 0
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/47809722
has comment: http://stackoverflow.com/comment/82579573
has body: facing some issue with output now. I am reading a file with is of 2199 length and trying to place commas at required positions. in an output I am getting like below, commas are coming into next line. This is happening for few records. Ex: 000XXXXXX,062,035,00,00 &lt;=== First line ,000C160YYYYY,086,047,00, &lt;=== next line Code is for line in file: string=list(line) commas=[15,18,21,23,25] for i in reversed(commas): string.insert(i, ',') result=''.join(string) outfile.write(result) How can I get the uniform output as expected?: 000XXXXXX,062,035,00,00 &lt;=== First line 000C160YYYYY,086,047,00 &lt;=== 2nd line
answer count: 1
has comment: http://stackoverflow.com/comment/82580109
favorite count: 0
has comment: http://stackoverflow.com/comment/82579828
type: Question
has comment: http://stackoverflow.com/comment/82580419
has comment: http://stackoverflow.com/comment/82579658

http://stackoverflow.com/comment/82365678
has text: Is there a downvoting police in S.O.? I need to sue somebody.
type: Comment
comment on: http://stackoverflow.com/a/47699209
score: 0
type: AnswerComment

http://stackoverflow.com/q/47835771
accepted answer: http://stackoverflow.com/a/47836305
tagged with: google-chrome
has answer: http://stackoverflow.com/a/47836305
favorite count: 0
has comment: http://stackoverflow.com/comment/82636362
type: Question
has comment: http://stackoverflow.com/comment/82635610
has comment: http://stackoverflow.com/comment/82636581
tagged with: user-permissions
linked to: http://stackoverflow.com/q/47716814
tagged with: python
has title: How to allow permissions to content in Chrome
linked to: http://stackoverflow.com/q/21628904
tagged with: selenium-webdriver
score: 2
type: AnsweredQuestion
has body: I am in stuck and cannot allow using camera and microphone in WebDriver: How can I handle this by WebDriver? I did not find any helpful info on the Internet related to this. Thanks in advance. PS: How can I close the microphone/camera popup in Python / Selenium? -- is not solving my case (I don't need "fake").
upvote count: 2
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/82538149
type: QuestionComment
comment on: http://stackoverflow.com/q/47788548
has text: Under what conditions is `flag!=1`? You're never setting it to anything else... A 1 indicates it fired twice? Why not a 2?
score: 1
type: Comment

http://stackoverflow.com/comment/82893014
has text: You could use : `counts.repartition(1).write.csv("hdfs://home/myDir/text_file.csv")`. But please note the `repartition` algorithm does a full shuffle of the data and creates equal sized partitions of data. `coalesce` combines existing partitions to avoid a full shuffle. The `repartition` method can be used to either increase or decrease the number of partitions in a DataFrame. However, the `coalesce` algorithm obviously cannot increate the number of partitions.
type: Comment
comment on: http://stackoverflow.com/a/47863316
type: AnswerComment
score: 1

http://stackoverflow.com/a/47711461
has comment: http://stackoverflow.com/comment/82382966
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/47711431
type: Answer
has body: Use list comprehension, In [4]: list3 = [i for i in list1+list2 if i not in list2] In [5]: list3 Out[5]: ['gender', 'location'] OR In [23]: [i for i in list1+list2 if (list1+list2).count(i) == 1] Out[23]: ['gender', 'location']
downvote count: 0

http://stackoverflow.com/q/47767973
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/47768068
linked to: http://stackoverflow.com/q/1419046
upvote count: 1
tagged with: python
has title: 'int' object has no attribute python
has body: Hello I tried to program EEPROM FTDI with using a FTDI library -> https://github.com/snmishra/ftd2xx/blob/master/ftd2xx/ftd2xx.py and D2XX FTDI Programming Guide def eeProgram(self, progdata=None, *args, **kwds): if progdata is None: progdata = _ft.ft_program_data(**kwds) progdata.Signature1 = _ft.DWORD(0) progdata.Signature2 = _ft.DWORD(0xffffffff) progdata.Version = _ft.DWORD(2) call_ft(_ft.FT_EE_Program, self.handle, progdata) return None I created instance to FTD2XX(Object) handler = _ft.FT_HANDLE() call_ft(_ft.FT_Open, 0, c.byref(handler)) device = FTD2XX(handler) And call a function eeProgram device.eeProgram(0,0xffffffff,2,"FTDI","FT") device.close() After that i got error: Traceback (most recent call last): File "ftd2xx.py", line 678, in &lt;module&gt; device.eeProgram(0,0xffffffff,2,"FTDI","FT") File "ftd2xx.py", line 573, in eeProgram progdata.Signature1 = _ft.DWORD(0) AttributeError: 'int' object has no attribute 'Signature1' I can connect and communicate with device via python but that function doesn't work. Anyone know what I should do to program a device with that function?
score: 1
has comment: http://stackoverflow.com/comment/82496967
has comment: http://stackoverflow.com/comment/82497200
has comment: http://stackoverflow.com/comment/82498047
has comment: http://stackoverflow.com/comment/82500187
has comment: http://stackoverflow.com/comment/82497106
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82496988
type: UnansweredQuestion

http://stackoverflow.com/q/47846988
upvote count: 2
has title: For each line in the file, find the immediate next line whose timestamp difference is at least n seconds
has answer: http://stackoverflow.com/a/47847448
tagged with: python
tagged with: timestamp
type: AnsweredQuestion
tagged with: pandas
score: 1
answer count: 1
accepted answer: http://stackoverflow.com/a/47847448
has body: I am new to time series programming with Python. Here is the sample file: DateTime&lt;space&gt; Price &lt;space&gt; Data1&lt;space&gt; Data2 Sample file contents: 20171105 09:20:01.134 2123.00 12.23 34.12 20171105 09:20:01.789 2133.00 32.43 45.62 20171105 09:20:02.238 2423.00 35.43 55.62 20171105 09:20:02.567 3423.00 65.43 56.62 20171105 09:20:02.948 2463.00 45.43 58.62 Date Format: YYYYMMDD hh:mm:ss.mi YYYY =&gt; Year MM =&gt; Month starting from 01 DD =&gt; Day of month starting from 01 hh =&gt; hour mm =&gt; minute ss =&gt; second mi =&gt; milliseconds Assume that we have to shift price by n seconds. For each line in the file, find the immediate next line whose timestamp difference is at least n seconds. Say we are at line l1 and the immediate next line with timestamp difference as n seconds is l2. Then the shifted time of l1 is Price of l2 - Price of l1. Lets work out the above logic. Assume shifting time interval is 1 second. Then the lines which are 1 second apart are: the pairs (first line, third line), (second line, fifth line). Third, fourth and fifth lines does not have a pair ie there are no lines whose timestamp difference is greater than or equal to 1 second. Shifted price of first line is 2423.00 - 2123.00 = 300 Shifted price of second line is 2463.00 - 2133.0 = 330 There are no shifted price for line number 3, 4 and 5. Can someone help me write the code for this in Pandad.. Many Thanks in advance.
downvote count: 1
favorite count: 0
type: Question
tagged with: time-series

http://stackoverflow.com/a/47727926
has body: Your data is in &lt;script&gt; between data: and queue: in JSON format. You can use standard string functions (ie. find(), slicing) to cut off this part. And then you can use module json to convert to python dictionary. And then you have to only find where moneyLine is in this dictionary. scrapy shell 'http://www.espn.com/nfl/schedule/_/week/1' # get `&lt;script&gt;` as text items = response.xpath("//script[contains(., 'moneyLine')]/text()") txt = items.extract_first() # find start and end of data #(I found this manually checking txt) start = txt.find('data:') + 6 # manually found how many add to get correct JSON string end = txt.find('queue:') - 6 # manually found how many substract to get correct JSON string json_string = txt[start:end] # convert to python dictionary import json data = json.loads(json_string) # example data #(I found this manually using `data.keys(), data['sports'][0].keys(), etc.) data['sports'][0]['leagues'][0]['events'][0]['odds']['home']['moneyLine']
answers question: http://stackoverflow.com/q/47725714
score: 3
accepted answer of: http://stackoverflow.com/q/47725714
type: Answer
upvote count: 3
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82431557

http://stackoverflow.com/q/47759519
type: UnansweredQuestion
answer count: 1
has body: I am very new to Python and am working on a simple project that part of which is supposed to search for a user defined variable, and if found, return a string based on the row it was found. I've read many posts that lead me to the code that I have, but when ran, while I don't get an error, the code continues onto the next part. In this case I omitted the following parts, but if run by itself, breaks after the input variable. import csv #CSV File Handling #Define variables for customer file reading and appending custData = open('custData.csv', 'a+') custFields = ['ContactLast','ContactFirst','Company','Credit','Phone','Address','City','State','Zip'] reader = csv.DictReader(custData, delimiter=',') writer = csv.DictWriter(custData, fieldnames=custFields) search = '' #Open the file with custData: #Display the Welcome Message and Main Menu mainmenugo = 'Y' while (mainmenugo.upper() == 'Y'): print ('-------------------- What would you like to do? ------------------\n' '--- (1) Lookup Account (2) New Account (quit) Shutdown ---\n' '------------------------------------------------------------------') mainmenugo = 'n' #Stop the loop from itirating forever on start mainmenuselect = input('Type your selection and press return : ') if mainmenuselect == '1': ## Account Options Mode search = input('Enter the contact last name to search : ') for row in reader: if search == row['ContactLast']: print (row['Company'], 'has a balance of $', row['Credit'], '. What would you like to do?') Part of the code was omitted for clarity, but that is why I have it setup as it is, though I am sure there are simpler ways of going about it. I have tried a few different things but am really not sure where to begin as I am getting very few errors with this one but no output. Thanks!
score: 0
tagged with: windows
has answer: http://stackoverflow.com/a/47893154
type: Question
has title: Python - Searching for a value in CSV column and return string
tagged with: python

http://stackoverflow.com/q/47797480
type: AnsweredQuestion
score: 2
accepted answer: http://stackoverflow.com/a/47851973
upvote count: 3
has title: implementing search functionality in google cloud platform
answer count: 1
has answer: http://stackoverflow.com/a/47851973
has body: Hi I am implementing search functionality using Full Text Search(document api) of google app engine following is the procedure how i have saved data in my documents For instance if user enters "hello world" then i save "hello world h he hel hell hello w wo wor worl world" in my documents as shown in this question (Google App Engine (python) : Search API : String Search) it is working fine WRT following examples if I have a string in db "this is a amazing and beautiful house" and now if I will search "this" ---> this will work "this is a amazing" ---> this will work "beautiful house" ---> this will work but if i will search "amazing house" this will not work I want it to work this way too Can you guys suggest some idea how to do this
tagged with: full-text-search
downvote count: 1
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/10960384
tagged with: google-app-engine
tagged with: python
tagged with: search

http://stackoverflow.com/q/47832180
has body: My code runs perfectly when I run the code via command line, but when the system tries to run the code using cron it doesn't execute the other file. os.system(file) returns the value 256 and I'm not able to understand the reason. from datetime import datetime, timedelta import requests import os print(1) #Login API to get the token reqLogin = requests.post('http://139.162.29.201:3001/auth/sign_in', json = {'email': 'aa', 'password': 'aa'}) reqLogin = reqLogin.json() print(2) #Get all the clients reqClient = requests.request('GET', 'http://139.162.29.201:3001/clients', headers = {'Authorization': 'JWT '+ reqLogin['token']}) reqClient = reqClient.json() print(3) #Initialize time #time = (datetime.now() + timedelta(hours = 5, minutes = 30)).strftime('%H:%M:%S') time = "05:59:50" timeInSecondsList = time.split(":") time = timedelta(hours = int(timeInSecondsList[0]), minutes = int(timeInSecondsList[1])) print(4) #Initialize date dateTime = (datetime.now() + timedelta(hours = 5, minutes = 30)).strftime('%Y-%m-%d') dateTimeYesterday = (datetime.now() + timedelta(days = -1, hours = 5, minutes = 30)).strftime('%Y-%m-%d') print(5) for eachClient in reqClient: #Get the shift timing against the client reqShiftTiming = requests.post('http://139.162.29.201:3001/getShiftTiming', headers = {'Authorization': 'JWT '+reqLogin['token']}, json = {'clientId': eachClient['clientId']}) reqShiftTiming = reqShiftTiming.json() print(6) shiftAList = reqShiftTiming[0]['shiftA'].split(":") shiftBList = reqShiftTiming[0]['shiftB'].split(":") shiftCList = reqShiftTiming[0]['shiftC'].split(":") print(7) if time == timedelta(hours = int(shiftBList[0]), minutes = int(shiftBList[1]) - 1): print(8) file = 'python /quad/finalMachineEfficiency.py '+ eachClient['clientId'] + ' ' + timeInSecondsList[0] + ':' + timeInSecondsList[1] + ' ' + dateTime os.system(file) print(os.system(file)) if time == timedelta(hours = int(shiftCList[0]), minutes = int(shiftCList[1]) - 1): print(9) file = 'python /quad/finalMac…
favorite count: 0
type: Question
upvote count: 4
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/96893005
downvote count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/82630277
score: 4
tagged with: cron
has title: os.system returns the value 256 when run from crontab
tagged with: os.system
has comment: http://stackoverflow.com/comment/82631242

http://stackoverflow.com/comment/82434207
type: AnswerComment
has text: Wow, thanks a lot! I'll wait a little more but I somehow doubt a better answer will come up.
score: 0
comment on: http://stackoverflow.com/a/47736935
type: Comment

http://stackoverflow.com/comment/82606583
type: Comment
has text: @OnlyPython Yes, the intermediate results are discarded as they are never assigned back.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47806857

http://stackoverflow.com/q/47813824
tagged with: keras
favorite count: 0
has answer: http://stackoverflow.com/a/51969613
type: Question
has title: Load a trained Keras neural network model on Raspberry Pi
tagged with: neural-network
has comment: http://stackoverflow.com/comment/82628178
tagged with: python
type: UnansweredQuestion
has body: I trained a neural network in Keras and saved it as an HDF5 file (*.h5). The aim is to classify data and distinguish between several classes directly on a Raspberry Pi Zero which is gaining data trough Grove sensors using the GrovePi shield. I would like to perform the classification task on the Raspberry Pi in real-time using the trained Keras model. However, it is not possible to install Tensorflow on the Raspberry Pi Zero which is required to use the built-in Keras functions to load the model and classify incoming data. Is there another possibility to load a Keras model in Python and classify the data without using the Tensorflow or Keras packages? Thanks for your help!
has answer: http://stackoverflow.com/a/47816782
has comment: http://stackoverflow.com/comment/82592111
tagged with: python-2.7
tagged with: raspberry-pi
score: 2
upvote count: 2
downvote count: 0
answer count: 3
has answer: http://stackoverflow.com/a/50334988

http://stackoverflow.com/q/47781852
type: AnsweredQuestion
tagged with: python-2.7
has title: GDB not stopping with "interrupt" command from python script
answer count: 5
has answer: http://stackoverflow.com/a/70885454
accepted answer: http://stackoverflow.com/a/70885454
has body: I've been ripping my hair out over this. I've searched the internet and can't seem to find a solution to my problem. I'm trying to auto test some code using the gdb module from python. I can do basic command and things are working except for stopping a process that's running in the background. Currently I continue my program in the background after a break point with this: gdb.execute("c&amp;") I then interact with the running program reading different constant values and getting responses from the program. Next I need to get a chunk of memory so I run these commands: gdb.execute("interrupt") #Pause execution gdb.execute("dump binary memory montiormem.bin 0x0 (&amp;__etext + 4)") #dump memory to file But when I run the memory dump I get an error saying the command can't be run when the target is running, after the error the interrupt command is run and the target is paused, then from the gdb console window I can run the memory dump. I found a similar issue from awhile ago that seems to not be answered here. I'm using python2.7. I also found this link which seems to be the issue but no indication if it's in my build of gdb (which seems unlikely).
tagged with: python
linked to: http://stackoverflow.com/q/10607021
has answer: http://stackoverflow.com/a/65873293
type: Question
upvote count: 2
score: 2
tagged with: gdb
has answer: http://stackoverflow.com/a/68001063
possible better answer: http://stackoverflow.com/a/68001063
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/52788400
has answer: http://stackoverflow.com/a/78702927

http://stackoverflow.com/q/47780180
accepted answer: http://stackoverflow.com/a/47780232
has answer: http://stackoverflow.com/a/47780232
has comment: http://stackoverflow.com/comment/82521545
tagged with: python
has body: Why doesn't the following code work? import numpy grid = numpy.matrix([[1,0,1,1],[1,1,0,0],[1,0,1,0],[0,0,0,1]]) i = 0 for line in grid: for block in line: if block == 1: i += 1 print("Grid has " + str(i) + " times number 1") I thought it's gonna first cycle through every line and then every element of the line and compare it with 1, but I get this error: Traceback (most recent call last): File "python", line 7, in &lt;module&gt; ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
tagged with: numpy
type: AnsweredQuestion
tagged with: for-loop
tagged with: matrix
answer count: 1
downvote count: 0
score: 1
upvote count: 1
has title: Looping through a numpy matrix
favorite count: 0
type: Question
tagged with: python-3.x

http://stackoverflow.com/a/47822851
answers question: http://stackoverflow.com/q/47822764
has comment: http://stackoverflow.com/comment/82608657
type: Answer
has comment: http://stackoverflow.com/comment/82608667
has body: for j in range(i + 1, len(aList)): if aList[j] &gt;= aList[j - 1]: break aList[j], aList[j - 1] = aList[j - 1], aList[j] minIndex = aList.index(aList[j - 1]) Selection sort is sorting by iteratively finding the minimum element in the list. Just set the first element as minimum, iterate through the list, if the current element smaller than the minimum then record it as the minimum and record its index. The part after is correct.
score: 0

http://stackoverflow.com/q/47775993
tagged with: pie-chart
tagged with: api
answer count: 1
type: Question
has body: I'm using the Plot.ly API for the first time and I am trying to visualize the below data for a pie chart. I can't figure out how to generate a title for the pie chart. I thought that filename='Events by Categories' would generate the title. Any help would be great, I would like the title to say "Events by Categories". Thanks! def plot_events_by_categories(category_events): labels = [] values = [] for each in category_events: labels.append(each) value = category_events[each] values.append(len(value)) trace = go.Pie(labels=labels, values=values) py.plot([trace], filename='Events by Categories')
has title: Plot.ly API adding Title
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47811749
tagged with: python
score: 0

http://stackoverflow.com/comment/82425042
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47731358
has text: always put full error message (Traceback) in question (as text, not screenshot). There are other useful informations.
score: 0

pip
tags question: http://stackoverflow.com/q/47714891
tags question: http://stackoverflow.com/q/47779372
tags question: http://stackoverflow.com/q/47851671
tags question: http://stackoverflow.com/q/47781215
tags question: http://stackoverflow.com/q/47706116
tags question: http://stackoverflow.com/q/47804206
tags question: http://stackoverflow.com/q/47846084
tags question: http://stackoverflow.com/q/47744807
tags question: http://stackoverflow.com/q/47727890
tags question: http://stackoverflow.com/q/47822324
tags question: http://stackoverflow.com/q/47818157
tags question: http://stackoverflow.com/q/47728705
type: Tag
tags question: http://stackoverflow.com/q/47797231
tags question: http://stackoverflow.com/q/47838635
tags question: http://stackoverflow.com/q/47786134
tags question: http://stackoverflow.com/q/47757195
tags question: http://stackoverflow.com/q/47796427
tags question: http://stackoverflow.com/q/47713936
tags question: http://stackoverflow.com/q/47767236
tags question: http://stackoverflow.com/q/47814920
tags question: http://stackoverflow.com/q/47752023
tag name: pip
tags question: http://stackoverflow.com/q/47757283
tags question: http://stackoverflow.com/q/47757167
tags question: http://stackoverflow.com/q/47855792
tags question: http://stackoverflow.com/q/47822731
tags question: http://stackoverflow.com/q/47816761
tags question: http://stackoverflow.com/q/47784713
tags question: http://stackoverflow.com/q/47714993
tags question: http://stackoverflow.com/q/47742144
tags question: http://stackoverflow.com/q/47763408
tags question: http://stackoverflow.com/q/47844326

http://stackoverflow.com/comment/82367966
has text: @Prune gave beautiful answer, however, keep in your head, that writing one-liners is not *pythonic* way, and writing readable code is best practice! But now again, @Prune's answer is still readable enough, although you could import `from random import random` instead of `import random`, therefore you could use `random()` instead of `random.random()` to save space and increase redability.
type: Comment
score: 1
comment on: http://stackoverflow.com/q/47703599
type: QuestionComment

http://stackoverflow.com/comment/82561269
type: QuestionComment
has text: You can just try `line.split('|').index('column1')`. This will give you the position of 'column1' in your columns list or raise `ValueError` if nothing would be found.
comment on: http://stackoverflow.com/q/47800007
score: 3
type: Comment

http://stackoverflow.com/a/47863863
answers question: http://stackoverflow.com/q/47854863
type: Answer
has body: from PIL import Image img = Image.open('Image.png') print(x,y) img.show() cropbox_1 = img.getbbox() new_image_1 = img.crop(cropbox_1) new_image_1.save('Cropped_image,png') new_image_1.show() This code completely crops the image to the edges. Only if the images are having alpha channel, you might have to remove that channel by converting it. ex. If it is a RGBA mode make it RGB and then use getbbox(). img = image.convert('RGB') cropbox = img.getbbox() image_1 = img.crop(cropbox) addition of this should do the task.
score: 0

http://stackoverflow.com/a/47704937
type: AcceptedAnswer
has body: If the directory of train is not made it will create this error, you may ensure the creation of the full directory path by calling this first Run this before you call to_csv directory = path.join(data_dir, "train/lastfm.train.0") if not os.path.exists(directory): os.makedirs(directory) EDIT: Another issue will be a file permission issue. Change the permission of the folder you are trying to write in sudo chmod 755 train Or on windows right click the folder and uncheck read-only
accepted answer of: http://stackoverflow.com/q/47704899
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/82370257
answers question: http://stackoverflow.com/q/47704899
has comment: http://stackoverflow.com/comment/82371071

http://stackoverflow.com/comment/82474744
comment on: http://stackoverflow.com/q/47755571
has text: Your code trial please?
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47761817
favorite count: 0
duplicate of: http://stackoverflow.com/q/19124601
score: 3
tagged with: python-2.7
tagged with: pandas
has comment: http://stackoverflow.com/comment/105929113
has body: I have a csv file which I am reading using Pandas. I want to print the entire dataframe so that I can check which columns are of string data type, because I want to apply pd.to_numeric() function to such columns to convert them into float data type. The dataframe is only 156x30,so printing it in it's entirety should not be much of a problem. I checked dataframe.values method but there is no parameter I can specify to do this directly. Following is my code: import pandas as pd file_ = pd.read_csv("path/to/csvfile") file_.values which returns: array([[1991, 'Berlin', 4.8, ..., '25,428.00', 4.8, nan], [1992, 'Berlin', 5.0, ..., '32,054.00', 5.0, nan], [1993, 'Berlin', 5.3, ..., '22,193.00', 5.3, nan], ..., [2014, 'Stuttgart', 4.8, ..., '103,027.00', 4.8, nan], [2015, 'Stuttgart', 4.4, ..., '110,668.00', 4.4, nan], [2016, 'Stuttgart', 3.9, ..., '108,562.00', 3.9, nan]], dtype=object) I want to print this dataframe in it's entirety. Is there any way to do that? Thanks.
type: Question
has title: How do I print an entire Pandas dataframe?
answer count: 0
linked to: http://stackoverflow.com/q/19124601
upvote count: 3
type: UnansweredQuestion
downvote count: 0
tagged with: python

http://stackoverflow.com/a/47752142
has body: Example for writing to a file and then reading it back and printing it: import csv with open('ex1.csv', 'w') as f: # open file BEFORE you loop writer = csv.writer(f) # declare your writer on the file for rows in range(0,4): # do one loop per row myRow = [] # remember all column values, clear list here for colVal in range(0,10): # compute 10 columns m = colVal * rows # heavy computing (your m or n) myRow.append(m) # store column in row-list writer.writerow(myRow) # write list containing all columns with open('ex1.csv', 'r') as r: #read it back in print(r.readlines()) # and print it Output: ['0,0,0,0,0,0,0,0,0,0\r\n', '0,1,2,3,4,5,6,7,8,9\r\n', '0,2,4,6,8,10,12,14,16,18\r\n', '0,3,6,9,12,15,18,21,24,27\r\n'] which translates to a file of 0,0,0,0,0,0,0,0,0,0 0,1,2,3,4,5,6,7,8,9 0,2,4,6,8,10,12,14,16,18 0,3,6,9,12,15,18,21,24,27 You can also stuff each rows list (copy it by myList[:]) into another list and use writer.writerows([ [1,2,3,4],[4,5,6,7] ]) to write all your rows in one go . See: https://docs.python.org/2/library/csv.html#writer-objects or https://docs.python.org/3/library/csv.html#writer-objects
score: 1
downvote count: 0
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/47751164

http://stackoverflow.com/q/47715816
has answer: http://stackoverflow.com/a/65285167
tagged with: python
has answer: http://stackoverflow.com/a/55084528
answer count: 4
tagged with: paramiko
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82571042
upvote count: 2
type: UnansweredQuestion
has body: I am trying to push config into multiple juniper devices. But as a test I enter into config mode and change config. client1 = paramiko.SSHClient() client1.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client1.connect(IP, username=username, password=password) configure = client1.invoke_shell() configure.send('configure') configure.send('set interfaces ge-0/0/10 description "test"') configure.send('show | compare') print configure.recv(1000) client1.close() I am expecting the output as below: [edit interfaces ge-0/0/10] - description "Internet Simulation Interface connect to QFX ge-0/0/21"; + description test; But the actual output is this: JUNOS 12.3X50-D35 built 2013-10-22 07:02:18 UTC
tagged with: juniper
downvote count: 1
has comment: http://stackoverflow.com/comment/82571059
has title: Configuring Juniper switch with python(paramiko)
has answer: http://stackoverflow.com/a/48572788
has answer: http://stackoverflow.com/a/48043956
score: 1

http://stackoverflow.com/comment/82570853
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47804632
has text: @sascha Sorry I am new to the field. What does #nnz/2 mean? Thank you
score: 0

http://stackoverflow.com/comment/82438004
has text: Python, on its own without external “powers”, cannot do this. Also, that code uses a lot of CPU because it is [busy waiting](https://en.wikipedia.org/wiki/Busy_waiting) and even worse spawning subprocesses every second. That is obviously bringing your computer to its knees.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47738690

http://stackoverflow.com/q/47802020
has title: os.path.abspath("..") returns "C://User//" which is false + __file__ is not defined --> execution from Spyder3 (Python 3.6)
score: 0
has body: I want to develop a python application which is based on modularity. It is my first python application, so I try to sum up my situation as detailled as possible: I am coding in Python for a few months. Now i am currently developing an application for statistics issues. Since I dont wan't to write my code into a single, endless .py-file , I intend to organize my application in single py files and related folders. So each py file is then related to a functionality which can be used by another .py file. To give an example for my application folder structure: My Directory structure is: Notebook.ipynb __init__.py A/ function1.py function2.py function3.py __init__.py B/ function4.py function5.py function6.py __init__.py C/ imp.csv The application shall be executed from the notebook.ipynb and uses the functions. E.g: Notebook.ipynb (uses) --&gt; function1.py (uses) --&gt; function4.py (imports) --&gt; imp.csv I have searched for ways here to realize that: I found out that i could import modules (.py files) into other .py files. Regarding to my example: function1.py would import function4.py from the sibling folder B. Due to the fact that the folder A and B are silbings, functionalities determining relative paths of a certain script would help me. But I got issues on using the most consulted ways of realizing that. I used: __file__ throws the error "name file is not defined" os.path.abspath("..") // returns "C:/USERS" which is definetly not the parentfolder of the script I executed (real path is much deeper than that; something like C:USERS/name/folder1/folder2/applicationfolder/folderA) Remark: I didn't run the whole script but (for testing purposes) the single statements in Spyder3 (Python3.6). My assumption here is that the issues are related to the execution of single statements. --- My questions are: Am I correctly with my assumption? If yes: How do I test the import of a .py file? If no: what is the problem here? Regarding the final application in the end. I need a st…
has comment: http://stackoverflow.com/comment/82565464
answer count: 0
has comment: http://stackoverflow.com/comment/82565359
has comment: http://stackoverflow.com/comment/82565672
tagged with: relative-path
tagged with: modularity
type: Question
tagged with: python-3.x
linked to: http://stackoverflow.com/q/595305
has comment: http://stackoverflow.com/comment/82566162
has comment: http://stackoverflow.com/comment/82565403
type: UnansweredQuestion
tagged with: python
duplicate of: http://stackoverflow.com/q/595305

http://stackoverflow.com/comment/82588016
score: 1
has text: @seanysull I can be done but it will feel like going from London to NY through Moskow. You could count the dots in every entry (say `n`), and replace the first `n-1` instances of it with `''`.
comment on: http://stackoverflow.com/a/47813144
type: Comment
type: AnswerComment

http://stackoverflow.com/a/47829077
type: Answer
has comment: http://stackoverflow.com/comment/87844538
has body: You are almost there. Indeed, csv.reader expects iterator which returns strings (not bytes). Such iterator is provided by sibling of BytesIO - io.StringIO. from io import StringIO csv_rec = b'QmFyY29kZSxRdHkKQTIzMjMsMTAKQTIzMjQsMTUKNjUxMDA1OTUzMjkyNSwxMgpBMjMyNCwxCkEyMzI0LDEKQTIzMjMsMTAK' bytes_data = base64.decodestring(csv_rec) # decode() method is used to decode bytes to string string_data = StringIO(bytes_data.decode()) read_file = csv.reader(string_data, quotechar='"', delimiter=',') next(read_file)
answers question: http://stackoverflow.com/q/47828854
type: AcceptedAnswer
score: 5
upvote count: 5
accepted answer of: http://stackoverflow.com/q/47828854
downvote count: 0

http://stackoverflow.com/comment/82371814
type: QuestionComment
has text: There is a space before `import` in line 1
type: Comment
comment on: http://stackoverflow.com/q/47705836
score: 2

http://stackoverflow.com/q/47836998
type: Question
linked to: http://stackoverflow.com/q/21274898
tagged with: time
type: UnansweredQuestion
score: 10
has body: I'm running the following code line on my terminal to get a profile of my program. python3 -m cProfile -s time main.py However the output it prints is gigantic. I only want to know the 10 most time-consuming tasks or to sort them in ascending order. How can I tell this to cprof?
tagged with: compilation
tagged with: python
has answer: http://stackoverflow.com/a/68741962
has answer: http://stackoverflow.com/a/51296604
answer count: 4
has answer: http://stackoverflow.com/a/76763833
has title: Making cProf give only the 10 most time-consuming tasks or sort them by time in reverse order
tagged with: profiling
downvote count: 0
has answer: http://stackoverflow.com/a/50776922
upvote count: 10
favorite count: 0

http://stackoverflow.com/comment/82533691
comment on: http://stackoverflow.com/a/47784369
score: 0
has text: Hi, if you install Azure CLI on docker, if you could not upgrade it, you could uninstall it firstly and re-install it. Uninstall `docker rmi -f microsoft/azure-cli` install `docker run -it azuresdk/azure-cli-python:2.0.22`
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/82666343
type: AnswerComment
has text: Can `a[x] *= 5` be decomposed into `a[x] = (a[x] * 5)`? Is, therefore, `a[x] *= 5` equivalent to `a.__setitem__(x, a.__getitem__(x)*5)`? Am I getting this right or wrong?
comment on: http://stackoverflow.com/a/47850611
type: Comment
score: 0

http://stackoverflow.com/q/47791378
has comment: http://stackoverflow.com/comment/82563167
type: Question
has comment: http://stackoverflow.com/comment/82543889
has comment: http://stackoverflow.com/comment/82570201
has comment: http://stackoverflow.com/comment/82589254
has comment: http://stackoverflow.com/comment/82570268
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82570228
linked to: http://stackoverflow.com/q/4607128
tagged with: arrays
upvote count: 1
tagged with: python
tagged with: http://stackoverflow.com/tag/c
score: -10
has comment: http://stackoverflow.com/comment/82570178
has comment: http://stackoverflow.com/comment/82544035
has body: While programming in python 3.6, I came across with some problem in list : l = [2,2,3,3,3] for n in range(len(l)): print(l[n+1]) #increasing value of n by 1 This code will obviously give an error : IndexError: list index out of range But in case of c language : #include&lt;stdio.h&gt; int main() { int i =0; int arr[5] = {1,2,3,4,5}; for(i = 0 ; i&lt;=4;i++){ printf("%d " , arr[i+1]); } return(0); } Gives the correct output(including garbage value): 2 3 4 5 32764 I wanted to know why are we not getting the value of elements of list in python by using the future values of n whereas in c it is just reverse?
has comment: http://stackoverflow.com/comment/82563198
has comment: http://stackoverflow.com/comment/82543860
has comment: http://stackoverflow.com/comment/82543965
downvote count: 11
has title: Lists in Python vs Arrays in C
tagged with: list
has comment: http://stackoverflow.com/comment/82543914
has answer: http://stackoverflow.com/a/47791671
has comment: http://stackoverflow.com/comment/82543909
answer count: 1
has comment: http://stackoverflow.com/comment/82566915
has comment: http://stackoverflow.com/comment/82544062
favorite count: 0

http://stackoverflow.com/comment/82530294
score: 0
comment on: http://stackoverflow.com/q/47784424
has text: You can you [Retrying](https://pypi.python.org/pypi/retrying) package. It has lot of options on handling the retrying behaviour in case of an error.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82410700
has text: the solution that was right in front of me the whole time. thanks!
comment on: http://stackoverflow.com/a/47707256
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/47797461
possible better answer: http://stackoverflow.com/a/47798030
has answer: http://stackoverflow.com/a/47798030
type: AnsweredQuestion
answer count: 2
has answer: http://stackoverflow.com/a/47798099
score: 3
upvote count: 3
tagged with: rsa
downvote count: 0
tagged with: cryptography
has title: Python Why do I have Special Characters in RSA encrypting
has body: Hello i'm currently programming an application in python using Pyzmq for the communication between a PC client and a raspberry server. I need the PC client to send encrypted password to the raspberry serv. I will just post the RSA parts of my code, so if you need more informations or others parts of my program, please tell me. So on my raspberry I do this to generate a RSA key: from Crypto.Hash import MD5 from Crypto.PublicKey import RSA from Crypto.Util import randpool alea = randpool.RandomPool() RSAKey = RSA.generate(1024,alea.get_bytes) Then I get n and e parameters of this RSAKey which correspond at the Public Key to send them to my PC client. When my PC receive these informations from the Raspberry, i construct the Public Key on the client: from Crypto.Hash import MD5 from Crypto.PublicKey import RSA def create_public_key(n,e): key_params = (long(n),long(e)) return RSA.construct(key_params) Then, when the user enters his password, I want to encrypt it: def encrypt(text): crypted = Client_Public_Key.encrypt(text,32) return crypted[0] Here is the crypted I get for the text "12345": ('C?\xd2\xca7j\xa0\x0cw\x8b+R"\xc37\xe8IR\xa1\x9fu\xe7v\x0c\xcaW-\xfcXb;]\x887\xc9\xfd\xf6\x0f\xe7\xae\x08\xfe\x0b\xaa*\xfa\x1b\x95:c\x99\xcb\xc6\x9f\x1d\xe1\x84\xa6\xcb\x8adh\x97w\xacR\xff\x8c\x80\xedX\xcc\xf3\xc3\x99\x99\xe9\x92\x8e\xbf]&gt;5\xc5\xbe\x0e*G\xe2\xf2m\xdeN\xa4\x19\xbf\xd6\xd6\x9c\xba\xf9\xc8f\xa7_\xef\x84q\x877\x90\xd3\xd5\x93\xef\x81\xfc $\x9e\x03\t\x9c\xb4\xb1D,Q',) I tried different way of encrypting (like Cipher's PKCS1_OAEP for example) and I always get these weird strings. Why I don't get a normal sequence of numbers ? I would like to continue to use the decrypt function of this library because it's very fast, but the encrypt function keeps annoying me. What can I do ? Thanks ! On my PC, I use Spyder with Python 2.7.14. On my Raspberry, I use Python 3.5.x.
favorite count: 0
accepted answer: http://stackoverflow.com/a/47798099
type: Question
linked to: http://stackoverflow.com/q/19210414
has comment: http://stackoverflow.com/comment/82556995
tagged with: encryption
tagged with: python

http://stackoverflow.com/a/47839488
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47839248
score: 3
answers question: http://stackoverflow.com/q/47839248
type: Answer
has body: Your function convert_to_integer returns 20060606, which indeed is August 21th, 1970 in number of seconds elapsed since 1970. You should instead use the method datetime.timestamp()
upvote count: 3

http://stackoverflow.com/a/47750365
has comment: http://stackoverflow.com/comment/82484516
type: Answer
has comment: http://stackoverflow.com/comment/82495742
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47744347
has body: You are using different testing data than would have been available - use just the test.csv file to find the best model and value for C, then evaluate it only on the impermium_verification_set.csv. When the competition was running, looks like only test was available to find a model, then models were locked and leaderboard was based on the verification set. You are using the full set of both to select the best model. You can always ask on the discussion boards on the Kaggle competition page if you want - I'm sure people there will help also. Also some of the top placers, including the winner, have posted their code on the discussion page for interest.
accepted answer of: http://stackoverflow.com/q/47744347

http://stackoverflow.com/q/47794452
tagged with: class
score: -1
has comment: http://stackoverflow.com/comment/82550730
has comment: http://stackoverflow.com/comment/82550349
tagged with: python-3.x
answer count: 3
type: UnansweredQuestion
downvote count: 2
upvote count: 1
favorite count: 0
type: Question
tagged with: static
has answer: http://stackoverflow.com/a/47794666
has comment: http://stackoverflow.com/comment/82550739
has answer: http://stackoverflow.com/a/47797246
has title: Static initializer for Python classes
has comment: http://stackoverflow.com/comment/82551010
has answer: http://stackoverflow.com/a/47794565
has comment: http://stackoverflow.com/comment/82551371
tagged with: python
has body: I'm looking for an equivalent to the static { ... } block in Java that can be used in Python classes. Specifically, I want to be able to access static resources like the arguments of the class constructor and store them in a field of the class, like so: class A: constructor_args = A.__init__.__code__.co_varnames def __init__(self, foo=0, bar=1): ... This example doesn't work, because class A is not yet initialized when I call A.__init__.__code__.co_varnames. My current workaround is to alter the static field after the class has been created like so: class A: constructor_args = ... def __init__(self, foo=0, bar=1): ... constructor_args = A.__init__.__code__.co_varnames But this solution is rather ugly because I change a static field of a class outside of the class context and if the class contains a lot of code, it's easy to miss out on what is going on here. So basically I need a way to call a function right after the class has been initialized, and I want to define this function inside of the class.

http://stackoverflow.com/q/47806016
tagged with: pinax
type: UnansweredQuestion
tagged with: package
has body: I'm trying to start a Pinax Project for Django. I setup my Python Virtual Environment. Upgraded setup tools. Upgraded pip. Installed Pinax. Then when I tried 'pinax start blog my_site', it gave the following error: Installing Django... Traceback (most recent call last): File "/usr/local/bin/pinax", line 11, in &lt;module&gt; sys.exit(main()) File "/usr/local/lib/python2.7/dist-packages/click/core.py", line 700, in __call__ return self.main(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/click/core.py", line 680, in main rv = self.invoke(ctx) File "/usr/local/lib/python2.7/dist-packages/click/core.py", line 1027, in invoke return _process_result(sub_ctx.command.invoke(sub_ctx)) File "/usr/local/lib/python2.7/dist-packages/click/core.py", line 873, in invoke return ctx.invoke(self.callback, **ctx.params) File "/usr/local/lib/python2.7/dist-packages/click/core.py", line 508, in invoke return callback(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/click/decorators.py", line 63, in new_func return ctx.invoke(f, obj, *args[1:], **kwargs) File "/usr/local/lib/python2.7/dist-packages/click/core.py", line 508, in invoke return callback(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/pcli.py", line 97, in start pip_install("Django") File "/usr/local/lib/python2.7/dist-packages/pcli.py", line 23, in pip_install command.run(opts, [package]) File "/usr/local/lib/python2.7/dist-packages/pip/commands/install.py", line 335, in run wb.build(autobuilding=True) File "/usr/local/lib/python2.7/dist-packages/pip/wheel.py", line 749, in build self.requirement_set.prepare_files(self.finder) File "/usr/local/lib/python2.7/dist-packages/pip/req/req_set.py", line 380, in prepare_files ignore_dependencies=self.ignore_dependencies)) File "/usr/local/lib/python2.7/dist-packages/pip/req/req_set.py", line 634, in _prepare_file abstract_dist.prep_for_dist() File "/usr/local/lib/python2.7/dist-packages/pip/req/req_set.py", line 129, in prep_for_dist self.re…
tagged with: django
tagged with: python
tagged with: virtualenv
has answer: http://stackoverflow.com/a/47806056
has answer: http://stackoverflow.com/a/47851278
score: 0
answer count: 2
has title: InstallationError: Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-Jr1szu/Django/
type: Question

http://stackoverflow.com/q/47814599
tagged with: python
tagged with: pyramid
has title: How to call a function in another python file in my wsgi file?
tagged with: mod-wsgi
type: AnsweredQuestion
score: 0
answer count: 1
has body: I am using mod_wsgi with pyramid and have different wsgi files per environment/server like the pyramid-test.wsgi and pyramid-prod.wsgi These files contains code to set environment variables that are different per environment. Example: os.environ['SQLALCHEMY_URL'] = 'TODO' I try to move this code to a file called settings.py that will be called in the .wsgi file. These settings files will be hold next to the .wsgi file or preferable in a secure sub dir, such that others can't read the settings (like db password), but can however deploy a new version and overwrite the .wsgi file such that the app is automatically reloaded by Apache. How can I call the python code in the settings.py file from the .wsgi file? When I try to do that, it can't find it, as it's not part of the app module.
accepted answer: http://stackoverflow.com/a/47821932
type: Question
has answer: http://stackoverflow.com/a/47821932

http://stackoverflow.com/q/47804572
has comment: http://stackoverflow.com/comment/82570735
tagged with: 2d
score: 0
tagged with: list
has body: I am trying to insert values, one at at time, from several python lists of lists (i.e. 2D lists) into another 2D list. (I know numpy is better at this, but I am trying to compare the performance of lists to numpy, so please don't just suggest numpy.) I want to insert the values at specific locations, hence the indexing on the left hand side. resampled_pix_spot_list is a 240 by 240 list of lists, and pix_spot_list is a 225 by 225 list of lists. The error I am getting, from the final four lines in the example, is "TypeError: 'float' object is not subscriptable". I get that pix_prod_bl[0][0], for example, is a float, but I don't understand why I can't insert it into a particular set of indices in resampled_pix_spot_list. Edit 1- added minimal working example. Edit 2- in adding the working example, I found that I accidentally had the line commented where I convert the lists back to numpy, and somehow I misinterpreted the Spyder console about where the error was originating. Anyway it works now, thank you very much for the quick feedback. I guess I'll leave this here in case it's helpful to anyone else. Edit 3- pix_spot_values is an array of data, so just a random array of floats between 0 and 1 will suffice. xc=57 yc=189 rebin=15 # fraction pixel offset requiring interpolation dx=xc*rebin-int(np.floor(xc*rebin)) # positive value between 0 and 1 dy=yc*rebin-int(np.floor(yc*rebin)) # positive value between 0 and 1 # weights for interpolation w00=(1-dy)*(1-dx) w10=dy*(1-dx) w01=(1-dy)*dx w11=dy*dx # now the rest of the offset is an integer shift dx=int(np.floor(xc*rebin))-int(np.floor(xc))*rebin # positive integer between 0 and 14 dy=int(np.floor(yc*rebin))-int(np.floor(yc))*rebin # positive integer between 0 and 14 def new_pix_spot(w00, w10, w01, w11, pix_spot_list, ny_spot, nx_spot, rebin, dy, dx): #first change numpy array to list pix_spot_list=pix_spot_values.tolist() #preallocate array of zeros resampled_pix_spot_list=[[0 for x in range (ny_spot + rebin)] for y in ran…
has title: Inserting values into 2D Python list using indexing
type: UnansweredQuestion
answer count: 1
tagged with: arrays
has comment: http://stackoverflow.com/comment/82570715
type: Question
tagged with: indexing
has comment: http://stackoverflow.com/comment/82571472
tagged with: python
has answer: http://stackoverflow.com/a/51065695

http://stackoverflow.com/comment/82433051
score: 0
type: AnswerComment
type: Comment
has text: Hi, @jarmod! first thanks for your answer, it make sense, but when user created the required IAM role for my app with our account id then how can i use his credentials from app via api? can you help me with a code example, please!
comment on: http://stackoverflow.com/a/47729843

http://stackoverflow.com/comment/82642912
has text: The name of my python code is untitled0.py I put everything in one .py file.
comment on: http://stackoverflow.com/q/47839456
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/82577521
type: QuestionComment
comment on: http://stackoverflow.com/q/47807144
score: 0
type: Comment
has text: @max375 I added a generic answer which handles your case.

http://stackoverflow.com/q/47699384
downvote count: 0
answer count: 1
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/47699855
favorite count: 0
has answer: http://stackoverflow.com/a/47699855
type: AnsweredQuestion
has body: I'm making an application in which a user can create categories to put items in them. The items share some basic properties, but the rest of them are defined by the category they belong to. The problem is that both the category and it's special properties are created by the user. For instance, the user may create two categories: books and buttons. In the 'book' category he may create two properties: number of pages and author. In the buttons category he may create different properties: number of holes and color. Initially, I placed these properties in a JsonProperty inside the Item. While this works, it means that I query the Datastore just by specifying the category that I am looking for and then I have to filter the results of the query in the code. For example, if I'm looking for all the books whose author is Carl Sagan, I would query the Item class with category == books and the loop through the results to keep only those that match the author. While I don't really expect to have that many items per category (probably in the hundreds, unlikely to get to one thousand), this looks inefficient. So I tried to use ndb.Expando to make those special properties real properties that are indexed. I did this, adding the corresponding special properties to the item when putting it to the Datastore. So if the user creates an Item in the 'books' category and previously created in that category the special property 'author', an Item is saved with the special property expando_author = author in it. It worked as I expected until this point (dev server). The real problem though became visible when I did some queries. While they worked in the dev server, they created composite indexes for each special/expando property, even if the query filters were equality only. And while each category can have at most five properties, it is evident that it can easily get out of control. Example query: items = Item.query() for p in properties: items = items.filter(ndb.GenericProperty(p)==propert…
has title: How can I query for multiple properties not known in advance using Expando?
score: 1
type: Question
tagged with: google-cloud-datastore
tagged with: google-app-engine
tagged with: app-engine-ndb

http://stackoverflow.com/comment/82610753
comment on: http://stackoverflow.com/a/47824008
type: Comment
has text: You can probably just give a direct path to the file then, eg `df = pd.read_csv("C:\Temp\Myfolder\myData.csv"), or `df = `pd.read_csv("./RelativeFolder/myData.csv")`, etc.
score: 0
type: AnswerComment

http://stackoverflow.com/q/47716680
tagged with: django-login
has comment: http://stackoverflow.com/comment/82423392
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82436556
has answer: http://stackoverflow.com/a/47731339
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52827981
tagged with: django
tagged with: python
tagged with: django-rest-framework
has answer: http://stackoverflow.com/a/71899353
has title: Issue with Django logout URL redirection
has body: I have configured login and logout redirect setting in Django settings as below - LOGOUT_REDIRECT_URL = '/login/' LOGIN_REDIRECT_URL = '/locations/' However, after logging out the redirection is done on the next= parameter, ie., the url is redirected to the same page from where logout is clicked. For the reference, here is login/logout URL from my urls.py - url(r'^', include('rest_framework.urls', namespace='rest_framework')), PS: I am using Django 1.11 &amp; DRF 3.7.3
score: 3
upvote count: 3
downvote count: 0
answer count: 3
tagged with: django-authentication

http://stackoverflow.com/a/47758876
score: 0
has body: TCP is a streaming protocol, meaning it has no concept of what constitutes a complete message. You have to implement your own message protocol layer on top of TCP to make sure you send and receive complete messages. You are responsible for buffering data received until you have a complete message, and you have to define what a complete message is. Some options: Send fixed length messages. Send a fixed number of bytes representing the length of the message, then the message. Separate messages with a sentinel byte. Then, call recv and accumulate the results until you have a complete message in the buffer.
has comment: http://stackoverflow.com/comment/82479124
has comment: http://stackoverflow.com/comment/82479079
has comment: http://stackoverflow.com/comment/82479156
has comment: http://stackoverflow.com/comment/82479213
has comment: http://stackoverflow.com/comment/82479723
has comment: http://stackoverflow.com/comment/82479021
has comment: http://stackoverflow.com/comment/82479936
type: Answer
has comment: http://stackoverflow.com/comment/82485262
has comment: http://stackoverflow.com/comment/82478973
has comment: http://stackoverflow.com/comment/82484621
has comment: http://stackoverflow.com/comment/82479252
answers question: http://stackoverflow.com/q/47758023

http://stackoverflow.com/comment/82607611
type: QuestionComment
has text: http://dpaste.com/2MBFSXE <-- what I see. Really strange.
type: Comment
comment on: http://stackoverflow.com/q/47822163
score: 0

http://stackoverflow.com/comment/82386737
type: Comment
comment on: http://stackoverflow.com/a/47705508
score: 0
type: AnswerComment
has text: @pookie, glad it helps! :)

http://stackoverflow.com/comment/82493149
score: 0
comment on: http://stackoverflow.com/q/47765824
type: Comment
type: QuestionComment
has text: `NoneTye` means you get `None`. Did you found WHY and WHEN you get none in variable?

http://stackoverflow.com/q/47819168
has comment: http://stackoverflow.com/comment/82600379
has comment: http://stackoverflow.com/comment/82600269
upvote count: 0
answer count: 1
downvote count: 3
score: -3
has comment: http://stackoverflow.com/comment/82600492
has answer: http://stackoverflow.com/a/47819414
has comment: http://stackoverflow.com/comment/82600489
favorite count: 0
type: Question
tagged with: opencv
accepted answer: http://stackoverflow.com/a/47819414
has comment: http://stackoverflow.com/comment/82600293
has body: I just built the opencv and tried one lane detection script. Script fails with the error message "AttributeError: module 'cv2' has no attribute 'inRange'". Has my build failed or is there something I am still missing? Code is from someone elses github: https://github.com/georgesung/road_lane_line_detection
tagged with: python
has title: AttributeError: module 'cv2' has no attribute 'inRange'
has comment: http://stackoverflow.com/comment/82600966
type: AnsweredQuestion

http://stackoverflow.com/q/47738406
score: 1
has answer: http://stackoverflow.com/a/47751671
answer count: 1
has comment: http://stackoverflow.com/comment/82463427
downvote count: 0
has comment: http://stackoverflow.com/comment/82445614
upvote count: 1
has body: Follwing the documentation, I have the following tables defined and populated but no relations have been defined yet. class CountryAssociation(Base): __tablename__ = 'Country_Region_Mapping' country_id = Column(Integer, ForeignKey('countries.uid'), primary_key=True) region_id = Column(Integer, ForeignKey('regions.uid'), primary_key=True) region = relationship('Region', back_populates='country') country = relationship('Countries', back_populates='region') extra_data = Column(String(50)) class Countries(Base): __tablename__ = 'countries' uid = Column(Integer, primary_key=True) countryname = Column('English_short_name', String(255), unique=True, nullable=False) region = relationship('CountryAssociation', back_populates='country') class Region(Base): __tablename__ = 'regions' uid = Column(Integer, primary_key=True) region = Column(String(255), unique=True, nullable=False) country = relationship('CountryAssociation', back_populates='region') I now want to create many to many relations between the tables. docs Base = automap_base() #reflecting the orm way engine = create_engine('sqlite:///mydatabse.db') Base.prepare(engine, reflect=True) Session = sessionmaker(bind=engine) session = Session() table_countries = Base.classes.countries table_regions = Base.classes.regions r = session.query(table_regions).filter(table_regions.region == "Western Europe").first() c = session.query(table_countries).filter(table_countries.English_short_name == "Germany").first() c.region.append(r) # this fails with AttributeError: 'countries' object has no attribute 'region' This however works: c.countryname # Germany I dont get what I am doing wrong here (beginner)...
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82441996
tagged with: many-to-many
tagged with: python
tagged with: sqlalchemy
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47751671
has title: Adding many to many relation in SQLAlchemy after Reflection

http://stackoverflow.com/comment/82539159
type: QuestionComment
has text: Can you add sample? Do you need rename columns with timeseries?
comment on: http://stackoverflow.com/q/47788909
score: 0
type: Comment

http://stackoverflow.com/a/47734652
type: Answer
has body: import numpy as np np.random.choice(np.arange(0, 4), p=[0.14, 0.58, 0.14, 0.14])
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47734625
answers question: http://stackoverflow.com/q/47734625

http://stackoverflow.com/comment/82504265
score: 0
comment on: http://stackoverflow.com/q/47771364
has text: If on UBUNTU try `sudo apt-get install sqlite3 libsqlite3-dev`
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82534558
type: AnswerComment
has text: Glad I could help. Look to the `dtype` and `converter` arguments in the [`read_csv` docs](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html) to generalize beyond the specific problem you raised in your post.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47786619

http://stackoverflow.com/comment/82504070
has text: Are you sure you dont want to: `dictionary = np.load(path2sink + 'dict.npy').items()` instead?
type: QuestionComment
comment on: http://stackoverflow.com/q/47771358
type: Comment
score: 0

http://stackoverflow.com/q/47815456
has answer: http://stackoverflow.com/a/47815654
has title: python dictionary do not print if there is no value
has answer: http://stackoverflow.com/a/47816419
accepted answer: http://stackoverflow.com/a/47816419
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82597669
has body: I have written a short script to print some info based on information in a CSV file. What I need to be able to do is to make the print function not print if there is no value for the key, or if there is a default value such as 'n/a'. Or it may be that if there is a default or empty cell in the CSV, that it doesn't get added to the dictionary? Not sure what is the best option. import csv with open('lhcdes.csv', 'rb') as testcsv: myfile = csv.DictReader(testcsv) for row in myfile: print 'Key1 %s' % row.get('Key1') + '\n' + 'and ' + 'Key2:%s ' % row.get('Key2') + 'Key3:%s ' % row.get('Key3:') the CSV Format is as follow: Key1,Key2,Key3,Key4,Key5,Key6 Gi0/3/0/1.1838,CustA,EU1,AN-12345,TAL12345,Host1_London Gi0/3/0/1.2072,CustB,EU2,AN-12346,TAL12346,Host2_Manchester Gi0/3/0/2.3761,CustB,EU3,AN-12347,TAL12347,Not Found Gi0/3/0/3.3573,CustC,EU7,AN-12348,TAL12348,Host5_Swansea Gi0/3/0/3.3702,CustD,EU5,AN-12349,N/A,Host4_Glasgow Gi0/3/0/3.3917,CustB,EU6,AN-12350,TAL12350,Not Found Gi0/3/0/3.3918,CustA,EU2,AN-12351,TAL12351,N/A Gi0/3/0/3.3919,CustE,EU9,AN-12352,Not Found,Not Found Gi0/3/0/3.3923,CustE,EU9,AN-12353,TAL12353,N/A Gi0/3/0/4.512,CustC,EU8,AN-12354,TAL12354,Not Found The output should look like interface Gi0/3/0/1.1838 Client:CustA EU:EU1 IR:AN-12345 CR:TAL12345 R:Host1_London interface Gi0/3/0/1.2072 Client:CustB EU:EU2 IR:AN-12346 CR:TAL12346 R:Host2_Manchester Where info is absent or n/a interface Gi0/3/0/3.3919 Client:CustE EU:EU9 IR:AN-12352
score: 1
downvote count: 1
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/82596976
favorite count: 0
type: Question
upvote count: 2
answer count: 2
has comment: http://stackoverflow.com/comment/82596933
possible better answer: http://stackoverflow.com/a/47815654

http://stackoverflow.com/q/47833369
has answer: http://stackoverflow.com/a/47835166
has comment: http://stackoverflow.com/comment/82631817
has comment: http://stackoverflow.com/comment/82629818
tagged with: python
has comment: http://stackoverflow.com/comment/82629957
has comment: http://stackoverflow.com/comment/82632994
has comment: http://stackoverflow.com/comment/82629736
has body: I need to apply a function to a big list such as [funz(x) for x in my_list] each evaluation has to be very quick. Let's say that funz(x) should execute in less than 0.1 seconds. I would like my funz to return None if it takes more than 0.1 secs to execute. In practice if my_list has n elements. The code should execute in less than 0.1*n seconds. What is the best way to do it?
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/82629916
has title: python stop function with very short timeout
type: UnansweredQuestion
tagged with: signals
answer count: 1
has comment: http://stackoverflow.com/comment/82630007
has comment: http://stackoverflow.com/comment/82632779
linked to: http://stackoverflow.com/q/27324494
type: Question
has comment: http://stackoverflow.com/comment/82630075
tagged with: timer

http://stackoverflow.com/comment/82514193
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47775715
type: Comment
has text: I am new to Python and dont quite understand how this pre-populates the entry boxes as per my example. This part is obvious an advance setting and why I am struggling

http://stackoverflow.com/comment/82740985
comment on: http://stackoverflow.com/a/47838322
score: 0
type: AnswerComment
has text: try to name your package PYDRIVE instead of PYTHON_PYDRIVE
type: Comment

http://stackoverflow.com/a/47726325
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/82413261
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47725845
has body: The main problem is that you're only writing a single row after the header: writer.writerow([name, times]) Instead, you need to write each row of the data, which you can do in your second for loop. You also need to calculate out how many Shift# columns there are by finding the max length of a player times list. This can be done simply by using a loop, or the built-in max function: # the loop way shift_count = 0 for times in players.values(): if len(times) &gt; shift_count: shift_count = len(times) # the quicker built-in way shift_count = max( len(shift_times) for shift_times in players.values() ) # then make the column names shift_cols = [ "Shift{}".format(num) for num in range(1, shift_count + 1) ] Putting these two together: # Move the file prep above the loop outfile = open("ShiftData.csv","a",newline='') writer = csv.writer(outfile) shift_count = max( len(shift_times) for shift_times in players.values() ) shift_cols = [ "Shift{}".format(num) for num in range(1, shift_count + 1) ] writer.writerow(["Player"] + shift_cols) for t in players.items(): print(t) row = [ t[0], # the first column is the player's name ] row += t[1] # then all of the shift times next to it writer.writerow(row) outfile.close()
answers question: http://stackoverflow.com/q/47725845

http://stackoverflow.com/comment/82438762
type: AnswerComment
has text: I'm sure it doesn't work. No need to test it. Also you do not need to call `MyDialog().ui.setupUi(QDialog())` since `self.ui.setupUi(self)` is already called into the constructor of `MyDialog`
type: Comment
comment on: http://stackoverflow.com/a/47739173
score: 0

http://stackoverflow.com/q/47810814
upvote count: 0
type: UnansweredQuestion
tagged with: python
score: -1
downvote count: 1
has comment: http://stackoverflow.com/comment/82583190
answer count: 4
has answer: http://stackoverflow.com/a/47811558
has comment: http://stackoverflow.com/comment/82582954
has answer: http://stackoverflow.com/a/47811695
has answer: http://stackoverflow.com/a/47811185
has comment: http://stackoverflow.com/comment/82583276
favorite count: 0
has title: Functions, simple encryption beginner level
type: Question
has body: My assigment is to make a program with 2 functions. The first function is that the user inserts a word and the program prints out the same word but with "*" in between every letter e.g. "*t*a*b*l*e*", this is working ok. I need help with the second function, the program will print out the same word but the letters has moved one place, example "ABCD" will be "BCDE". I have started by making an array with the alphabet but I don't know how to continue. Here is my code: for i in range(len(s)): print("*",s[i],sep='',end='') print("*") def krypt(): for i in(alfabet): print() text = input("write a word ") stars(text) krypt() print()
has answer: http://stackoverflow.com/a/47811203

http://stackoverflow.com/q/47770723
has comment: http://stackoverflow.com/comment/82513940
tagged with: pandas
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/82509159
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/82502541
accepted answer: http://stackoverflow.com/a/47778417
answer count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82512909
has body: I have two pandas dataframes, a, and b. a and b share two common colums, say x and y, containing english language strings. Each combination of x and y is uniq within a and b. There is a common subset of x and y, which I can compute like c = pandas.merge(a, b, on=['x', 'y']) What I am interested in is the rest, d = a - c, which should be the rows in a not in b, with respect to the two columns x and y. What I currently do is I add another colum xy: a['xy'] = a['x'] + a['y'] c['xy'] = c['x'] + c['y'] and then d = a[~a['xy'].isin(c['xy'])] This seems clumsy to me, is there a more elegant way to do this?
tagged with: dataframe
tagged with: python
has title: Find two dimensional complement in pandas
has answer: http://stackoverflow.com/a/47778417
has comment: http://stackoverflow.com/comment/82509298

http://stackoverflow.com/a/47794873
answers question: http://stackoverflow.com/q/47794161
has body: The more simple way to do that is using method replace like below: text= "one two three" text = text.replace("two", "2") For multiple replaces I suggest a loop like this: text= "one two three" replaceable = {'one': '1', 'two': '2', 'three': '3'} for string, new_string in replaceable.items(): text = text.replace(string, new_string)
upvote count: 1
downvote count: 0
score: 1
type: Answer

http://stackoverflow.com/comment/82378093
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47708963
has text: avoid raising an exception from the except block , remove the line `raise ex`

http://stackoverflow.com/q/47808863
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82619104
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/82641796
has comment: http://stackoverflow.com/comment/82595212
has title: Query for distinct model instances using values from a many to one table in Django ORM
has comment: http://stackoverflow.com/comment/82595364
has comment: http://stackoverflow.com/comment/82584078
has body: I have three models, called Order, Adjustment, and Location, respectively. My Order model (truncated to only show relevant fields) looks like this: class Order(models.Model): id = models.CharField(max_length=48, primary_key=True) status = models.IntegerField(null=True, default=None) amount = models.FloatField(null=True, default=None) while the Adjustment model looks like this: class Adjustment(models.Model): id = models.CharField(max_length=48, primary_key=True) order = models.ForeignKey(Order, related_name='adjustments', null=True, default=None) type = models.CharField(max_length=50, null=True, default=None) amount = models.FloatField(null=True, default=None) location = models.ForeignKey(Location, null=True, blank=True, default=None) and finally the Location model looks like this: class Location(models.Model): city = models.CharField(max_length=255, null=True, default=None) state = models.CharField(max_length=60, null=True, default=None) state_long = models.CharField(max_length=200, null=True, default=None) county = models.CharField(max_length=60, null=True, default=None) country = models.CharField(max_length=60, null=True, default=None) country_long = models.CharField(max_length=200, null=True, default=None) zipcode = models.CharField(max_length=32, null=True, default=None) longitude = models.FloatField(max_length=10, null=True, default=None) latitude = models.FloatField(max_length=10, null=True, default=None) timezone = models.CharField(max_length=60, null=True, default=None) The code for the query in question lies here: orders = Order.objects.filter( adjustments__type='payment', adjustments__location__isnull=False, status__gte=200, status__lt=300 ).exclude( adjustments__location__zipcode__in=['', '0000', '00000', 0000, 00000] ).values( # 'id', 'adjustments__location__city', 'adjustments__location__state', 'adjustments__location__country' ).annotate( bookings=Count('amount'), #, distinct=True), total_booking_value=Sum('amount'), average_booking_value=Avg('amount'…
type: UnansweredQuestion
tagged with: django-orm
score: 0
answer count: 1
tagged with: orm
has answer: http://stackoverflow.com/a/47826432
tagged with: mysql
upvote count: 1
has comment: http://stackoverflow.com/comment/82584232
downvote count: 1

http://stackoverflow.com/comment/82691662
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47855156
has text: @BùiChíThanh Post your result, otherwise, we cannot diagnose it.
type: Comment

http://stackoverflow.com/q/47820478
score: 0
has comment: http://stackoverflow.com/comment/82603549
has body: I try to make my code faster so I want the loops to run in parallel. My first question was, how do I implement a parallel loop in Python and which loop do I parallelize? Here is my code: from joblib import Parallel, delayed import multiprocessing as mp import numpy as np import time def compR(R, M, I, l): for p in range(ppl): for i in range(N): R[l][p] += np.dot(M[l][p],I[i]) return R level = 20 ppl = 8 x = 70 y = 10 N = 15 M = [[np.random.rand(x,y) for p in range(ppl)] for l in range(level)] R = [[np.zeros((x,1)) for p in range(ppl)] for l in range(level)] I = [np.random.rand(y,1) for n in range(N)] # Seriell t0 = time.time() for l in range(level): for p in range(ppl): for i in range(N): R[l][p] += np.dot(M[l][p],I[i]) t1 = time.time() print(t1-t0) R = [[np.zeros((x,1)) for p in range(ppl)] for l in range(level)] num_cores = mp.cpu_count() # Parallel t0 = time.time() R = Parallel(n_jobs=num_cores)(delayed(compR)(R, M, I, l) for l in range(level)) t1 = time.time() print(t1-t0) Is the implementation correct? I tried to let the level loop run in parallel since normally level > N > ppl. When I run to code for larger numbers of level and x and y the performance of the parallel loop is really bad. What do I do wrong?
has comment: http://stackoverflow.com/comment/82603429
answer count: 0
has title: Poor Performance of Parallel Nested Loop in Python
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/47587939
has comment: http://stackoverflow.com/comment/82603381
has comment: http://stackoverflow.com/comment/82603583
duplicate of: http://stackoverflow.com/q/47587939
has comment: http://stackoverflow.com/comment/82603658
has comment: http://stackoverflow.com/comment/82603270
tagged with: python-multiprocessing
has comment: http://stackoverflow.com/comment/82603463
has comment: http://stackoverflow.com/comment/82603488
type: Question

http://stackoverflow.com/comment/82385893
type: QuestionComment
comment on: http://stackoverflow.com/q/47712517
has text: Possible duplicate of [pyserial serialwin32.py has attribute error](https://stackoverflow.com/questions/34574311/pyserial-serialwin32-py-has-attribute-error)
score: 0
type: Comment

http://stackoverflow.com/q/47743469
type: Question
tagged with: python-3.x
tagged with: importerror
tagged with: python
has title: python3 calling python2 package when python3 package also available
has comment: http://stackoverflow.com/comment/82447057
tagged with: python-import
answer count: 0
type: UnansweredQuestion
score: 0
has body: (Using ubuntu 16.04) Several times already I've run into the following problem: I have two versions of the same package 'package', for python2 and python3 In a virtual environment that defaults to python3 I run python my_program.py which does 'import package' Python then goes to the folder for python2 version of the package and fails because it's written in python2. Some example error: &nbsp; from mpi4py import MPI ImportError: /usr/lib/python2.7/dist-packages/mpi4py/MPI.so: undefined symbol: _Py_ZeroStruct When I'm desperate to run it immediately I just go and remove the package manually (here I would do: sudo rm -rf /usr/lib/python2.7/dist-packages/mpi4y). Then python goes to the python3 version of the package and runs smoothly. This is clearly not the correct long-term solution. What is going on and how can I fix it?
has comment: http://stackoverflow.com/comment/82447067

http://stackoverflow.com/comment/82638649
score: 0
has text: "*It keeps tellung me, that the above ndarray a tuple*" - Please copy-paste the precise error message. Fetching a column from that array [works for me](https://ideone.com/tXfkaz).
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47837093

http://stackoverflow.com/a/77454113
has body: I see this error in postgres "to_sql" UnicodeDecodeError: 'utf-8' codec can't decode byte 0xf3 in position 85: invalid continuation byte, having configured the database in utf8, passing a pandas dataframe by average following the instruction df.to_sql("table", connection, schema="schema", index=False, if_exists="replace"), actually had accents in the letter search on the web for the error and find nothing, but well Debugging tells me that this error description is poorly defined as a response to the library, my problem was that the database did not have the table schema created.
score: 0
answers question: http://stackoverflow.com/q/47837976
type: Answer

http://stackoverflow.com/comment/82362139
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47700462
has text: `object_id = can.create_oval(..)` and now you can use `object_id` with canvas' functions to move oval.

http://stackoverflow.com/comment/82511292
comment on: http://stackoverflow.com/q/47775072
score: 0
type: Comment
has text: `f = open('example.csv', 'a')`
type: QuestionComment

http://stackoverflow.com/q/47841163
has title: I'm having trouble with web scraping to Python
linked to: http://stackoverflow.com/q/590747
type: UnansweredQuestion
score: -3
tagged with: http://stackoverflow.com/tag/html
has comment: http://stackoverflow.com/comment/82646727
tagged with: python
has body: I'm very new to coding and I've tried to write a code that imports the current price of litecoin from coinmarketcap. However, I can't get it to work, it prints and empty list. import urllib import re htmlfile = urllib.urlopen('https://coinmarketcap.com/currencies/litecoin/') htmltext = htmlfile.read() regex = 'span class="text-large2" data-currency-value=""&gt;$304.08&lt;/span&gt;' pattern = re.compile(regex) price = re.findall(pattern, htmltext) print(price) Out comes "[]" . The problem is probably minor, but I'm very appreciative for the help.
has comment: http://stackoverflow.com/comment/82646714
answer count: 2
upvote count: 0
tagged with: screen-scraping
has answer: http://stackoverflow.com/a/47841269
downvote count: 3
tagged with: web
has answer: http://stackoverflow.com/a/47841304
favorite count: 0
has comment: http://stackoverflow.com/comment/82646594
type: Question

google-cloud-dataflow
tags question: http://stackoverflow.com/q/47821942
tags question: http://stackoverflow.com/q/47837443
tag name: google-cloud-dataflow
tags question: http://stackoverflow.com/q/47778854
tags question: http://stackoverflow.com/q/47855836
type: Tag

http://stackoverflow.com/comment/82497060
score: 0
comment on: http://stackoverflow.com/q/47767194
type: QuestionComment
has text: Glad to hear. Please write that up as an answer and accept it.
type: Comment

http://stackoverflow.com/comment/82670725
type: QuestionComment
score: 0
has text: @Ivan86 I've been testing around and the most optimal solution has been marked below. Thanks for all the help guys.
comment on: http://stackoverflow.com/q/47847283
type: Comment

http://stackoverflow.com/comment/82475572
has text: sorry for the grammar
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47757219

http://stackoverflow.com/a/47767432
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/82516386
type: AcceptedAnswer
score: 1
type: Answer
answers question: http://stackoverflow.com/q/47767262
has comment: http://stackoverflow.com/comment/82498762
has body: I cannot see what the rest of your dictionary looks like but here's a simple example. Let's say that this is your JSON dictionary: dic={1:{'name': 'Tom','nick': 'T','class': '2'}, 2:{'name': 'Ron','nick': 'R','class': '5'}} dic[1]['class']=int(dic[1]['class']) dic[2]['class']=int(dic[2]['class']) dic {1: {'class': 2, 'name': 'Tom', 'nick': 'T'}, 2: {'class': 5, 'name': 'Ron', 'nick': 'R'}} type(dic[1]['class']) int Inside your JSON structure is there any keys for each of the two values inside the curly braces similar to 1: and 2: ? those are keys.
accepted answer of: http://stackoverflow.com/q/47767262

http://stackoverflow.com/q/47851832
tagged with: web-scraping
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47851853
has body: could anybony help because i am struggling two days in order to retrive basic information on the product (product name, picture,rating , price) in the link provided here. this my code and i am new to python import urllib.request from bs4 import BeautifulSoup from random import randint from bs4.dammit import EncodingDetector import re import sys url='https://fr.aliexpress.com/category/205000316/men-clothing-accessories.html' headers = {} headers['User-Agent'] = "Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:48.0) Gecko/20100101 Firefox/48.0,Mozilla/5.0 (Windows NT 6.3; rv:36.0) Gecko/20100101 Firefox/36.0',Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10; rv:33.0) Gecko/20100101 Firefox/33.0',Mozilla/5.0 (compatible, MSIE 11, Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko',Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; EN; rv:11.0) like Gecko',Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)',Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/5.0)',Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.75.14 (KHTML, like Gecko) Version/7.0.3 Safari/7046A194A'" req = urllib.request.Request(url, headers = headers) html = urllib.request.urlopen(req).read() soup = BeautifulSoup(html.decode('utf8', 'ignore'), "html.parser") # retrive infos such product name, price , rating Prod=soup.find_all('ul', class_='util-clearfix son-list') for item in Prod: print(item.contents[0].find_all("span",{"class:","star star-s "[0].text) print(item.contents[0].find_all("span",{"class:","star star-s "[0].text) print(item.contents[0].find_all("span",{"class:","star star-s "[0].text)
type: Question
has comment: http://stackoverflow.com/comment/82668059
downvote count: 1
score: -1
favorite count: 0
tagged with: beautifulsoup
tagged with: python-3.x
has title: AttributeError: 'NavigableString' object has no attribute and Index out of range
upvote count: 0
has answer: http://stackoverflow.com/a/47851923
answer count: 2
has comment: http://stackoverflow.com/comment/82667970

http://stackoverflow.com/a/47780225
type: Answer
accepted answer of: http://stackoverflow.com/q/47779982
score: 2
answers question: http://stackoverflow.com/q/47779982
type: AcceptedAnswer
has body: You may be able to achieve what you want by using https://pypi.python.org/pypi/pynput. See also its docs on pythonhosted http://pythonhosted.org/pynput/, especially the section about monitoring the keyboard http://pythonhosted.org/pynput/keyboard.html#monitoring-the-keyboard. The following is an example from the docs: from pynput.keyboard import Key from pynput.keyboard import Listener def on_press(key): print('{0} pressed'.format( key)) def on_release(key): print('{0} release'.format( key)) if key == Key.esc: # Stop listener return False # Collect events until released with Listener( on_press=on_press, on_release=on_release) as listener: listener.join() It will print every key you press until you press ESC, after which it will terminate. Note that there are some operating system specific things to consider, for example on OSX the process must run as root.
upvote count: 2
downvote count: 0

http://stackoverflow.com/q/47720421
duplicate of: http://stackoverflow.com/q/41340341
tagged with: pandas-loc
tagged with: list
has answer: http://stackoverflow.com/a/47720450
upvote count: 14
tagged with: pandas
tagged with: python
answer count: 4
linked to: http://stackoverflow.com/q/40006276
has answer: http://stackoverflow.com/a/63348686
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/61011741
possible better answer: http://stackoverflow.com/a/47721117
duplicate of: http://stackoverflow.com/q/40006276
has title: Select row using the length of list in pandas cell
has answer: http://stackoverflow.com/a/47721117
score: 13
downvote count: 1
has body: I have a table df a b c 1 x y [x] 2 x z [c,d] 3 x t [e,f,g] Just wondering how to select the row using the length of c column such as df.loc[len(df.c) &gt;1] I know this is not right.... what should be the right one?
accepted answer: http://stackoverflow.com/a/47720450
type: AnsweredQuestion

scikit-learn
tags question: http://stackoverflow.com/q/47847946
tags question: http://stackoverflow.com/q/47753239
tags question: http://stackoverflow.com/q/47783247
tags question: http://stackoverflow.com/q/47723547
tags question: http://stackoverflow.com/q/47702097
tags question: http://stackoverflow.com/q/47747195
tags question: http://stackoverflow.com/q/47708489
tags question: http://stackoverflow.com/q/47804326
tags question: http://stackoverflow.com/q/47826673
tag name: scikit-learn
tags question: http://stackoverflow.com/q/47801977
tags question: http://stackoverflow.com/q/47820700
tags question: http://stackoverflow.com/q/47725664
tags question: http://stackoverflow.com/q/47702750
tags question: http://stackoverflow.com/q/47723021
tags question: http://stackoverflow.com/q/47700151
type: Tag
tags question: http://stackoverflow.com/q/47703641
tags question: http://stackoverflow.com/q/47715748
tags question: http://stackoverflow.com/q/47778403
tags question: http://stackoverflow.com/q/47788981
tags question: http://stackoverflow.com/q/47708865
tags question: http://stackoverflow.com/q/47728069
tags question: http://stackoverflow.com/q/47782571
tags question: http://stackoverflow.com/q/47723402
tags question: http://stackoverflow.com/q/47765017
tags question: http://stackoverflow.com/q/47717818
tags question: http://stackoverflow.com/q/47838306
tags question: http://stackoverflow.com/q/47711184
tags question: http://stackoverflow.com/q/47716016
tags question: http://stackoverflow.com/q/47745288
tags question: http://stackoverflow.com/q/47850136
tags question: http://stackoverflow.com/q/47733590
tags question: http://stackoverflow.com/q/47807463
tags question: http://stackoverflow.com/q/47714011
tags question: http://stackoverflow.com/q/47770920
tags question: http://stackoverflow.com/q/47793569
tags question: http://stackoverflow.com/q/47815198
tags question: http://stackoverflow.com/q/47810490
tags question: http://stackoverflow.com/q/47820941
tags question: http://stackoverflow.com/q/47775652
tags question: http://stackoverflow.com/q/47796389
tags question: http://stackoverflow.com/q/47778928
tags question: http://stackoverflow.com/q/47732108
tags question: http://stackoverflow.com/q/47819930
tags question: http://stackoverflow.com/q/47762314
tags question: http://stackoverflow.com/q/47852014
tags question: http://stackoverflow.com/q/47792803
tags question: http://stackoverflow.com/q/47719001
tags question: http://stackoverflow.com/q/47786637
tags question: http://stackoverflow.com/q/47742698
tags question: http://stackoverflow.com/q/47767162
tags question: http://stackoverflow.com/q/47799305
tags question: http://stackoverflow.com/q/47821624
tags question: http://stackoverflow.com/q/47789184
tags question: http://stackoverflow.com/q/47716588
tags question: http://stackoverflow.com/q/47749250
tags question: http://stackoverflow.com/q/47788673
tags question: http://stackoverflow.com/q/47756510
tags question: http://stackoverflow.com/q/47790854
tags question: http://stackoverflow.com/q/47744347
tags question: http://stackoverflow.com/q/47788389
tags question: http://stackoverflow.com/q/47755800

http://stackoverflow.com/comment/82436806
comment on: http://stackoverflow.com/a/47738226
type: Comment
has text: @PatrickArtner, no, the identical version would be: `skiprows=3, header=0` - i've added it to the demo...
score: 0
type: AnswerComment

http://stackoverflow.com/q/47795351
score: 0
has comment: http://stackoverflow.com/comment/82578680
has body: I am trying to import a csv format file. this is tick trading data info. The file is as follows: 0,2017-09-18 02:00:06,12568.00,1,201,12567.00,12568.00,5462,0,0,C, 0,2017-09-18 02:00:06,12568.50,2,203,12567.00,12568.00,5463,0,0,C, 0,2017-09-18 02:00:06,12569.00,1,204,12567.00,12569.00,5468,0,0,C, 0,2017-09-18 02:00:06,12569.00,1,205,12567.00,12569.00,5470,0,0,C, 0,2017-09-18 02:00:06,12569.50,3,208,12567.00,12569.00,5471,0,0,C, I am using this python code: import pandas as pd df = pd.read_csv("XG#/20170918.txt", names=['empty', 'date time', 'last', 'last size', 'bid', 'ask']) print(df.head(1)) my output is this: empty date time last \ 0 2017-09-18 02:00:06 12567.0 200.0 200.0 12567.0 12567.0 5430.0 0.0 last size bid ask 0 2017-09-18 02:00:06 12567.0 200.0 200.0 12567.0 0.0 C NaN Process finished with exit code 0 My questions are: Why my "names" (headers) are not starting on the first column? How do I make 2nd column as date-time and index? How do I widen the result so I will see all the data in one line (I am using pycharm)? since I need to make date-time as index, I need to remove column 0 but when using df.drop(df.index[0]) nothing happens. Any help is welcome!
tagged with: pycharm
tagged with: pandas
has comment: http://stackoverflow.com/comment/82578523
has comment: http://stackoverflow.com/comment/82578635
answer count: 1
tagged with: pandas-datareader
has title: Wrong parsing when importing csv file in python
has comment: http://stackoverflow.com/comment/82578601
has comment: http://stackoverflow.com/comment/82578770
has comment: http://stackoverflow.com/comment/82578668
type: Question
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/82578546
tagged with: python
has answer: http://stackoverflow.com/a/47809582
has comment: http://stackoverflow.com/comment/82551556
accepted answer: http://stackoverflow.com/a/47809582
has comment: http://stackoverflow.com/comment/82578959
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82578739

http://stackoverflow.com/a/59968753
downvote count: 0
upvote count: 1
has body: If you first convert your input_datetime you can call the minutes (or years etc) of your dataframe with .dt.minute input_datetime = pd.to_datetime(datetime.strptime(date_string, "%m/%d/%Y %H:%M")).replace(tzinfo=timezone) df = pd.DataFrame({"datetime":[input_datetime]}) df['datetime'].dt.minute
type: Answer
answers question: http://stackoverflow.com/q/47822277
score: 1

http://stackoverflow.com/comment/82376692
comment on: http://stackoverflow.com/q/47708233
type: Comment
has text: Ignore those lines I was hoping nobody would notice that.
type: QuestionComment
score: 0

http://stackoverflow.com/a/47718256
answers question: http://stackoverflow.com/q/47717637
type: Answer
has comment: http://stackoverflow.com/comment/82397325
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82396990
accepted answer of: http://stackoverflow.com/q/47717637
has body: I was able to solve similar issue by deleting the migration files and sqlite db. Make sure to backup your db before deleting
score: 0

http://stackoverflow.com/a/79456976
downvote count: 0
upvote count: 1
has body: This is a minimal version of @BryanOakley's version, useful to get the core idea: import tkinter as tk, random class DynamicGrid(tk.Frame): def __init__(self, parent, *args, **kwargs): tk.Frame.__init__(self, parent, *args, **kwargs) self.text = tk.Text(self, wrap="char", borderwidth=0, highlightthickness=0, state="disabled") self.text.pack(fill="both", expand=True) def add_box(self, color=None): box = tk.Frame(self.text, bd=1, background=random.choice(("red", "orange", "green", "blue", "violet")), width=100, height=100) self.text.window_create("end", window=box) root = tk.Tk() dg = DynamicGrid(root, width=500, height=200) dg.pack(side="top", fill="both", expand=True) for i in range(20): dg.add_box() root.mainloop()
answers question: http://stackoverflow.com/q/47704736
type: Answer
score: 1

http://stackoverflow.com/comment/126740581
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47743692
score: 0
has text: Have a look at this quiestion https://stackoverflow.com/questions/71440069/forward-message-album-telethon

http://stackoverflow.com/q/47812543
answer count: 1
downvote count: 0
tagged with: javascript
tagged with: python
has answer: http://stackoverflow.com/a/47812797
accepted answer: http://stackoverflow.com/a/47812797
tagged with: node.js
type: AnsweredQuestion
score: 1
upvote count: 1
has body: i'm trying to send some data via socket from js to py server. JS Client: &lt;script src="/socket.io/socket.io.js"&gt;&lt;/script&gt; &lt;script&gt; var socket = io.connect('http://localhost:1729'); socket.send("1234"); &lt;/script&gt; Py Server: import socket server_socket4=socket.socket() server_socket4.bind(('localhost', 1729)) server_socket4.listen(1) (client_socket,client_adress)=server_socket4.accept() print client_socket.recv(1024) server_socket4.close() It's printing this: GET /socket.io/?EIO=3&amp;transport=polling&amp;t=M1KiY71 HTTP/1.1 Referer: http://localhost:8000/index.html Accept: */* Accept-Language: en-US,en;q=0.7,he;q=0.3 Accept-Encoding: gzip, deflate User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko Host: localhost:1729 DNT: 1 Connection: Keep-Alive How can I make it print "1234"?
has title: Sending data from js client to py server via socket don't work
favorite count: 0
type: Question
tagged with: client-server
tagged with: sockets

http://stackoverflow.com/comment/83486142
score: 0
has text: Yes, X is created in a calculator filter, but I have always:"AttributeError: 'VTKCompositeDataArray' object has no attribute 'GetVariantValue' and getVariantValue and GetValue and getvalue also. Can be different if the orignal source is OpenFoam based or Ensight? Sorry a lot, but for me it is essential to find the solution.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48113501

deserialization
type: Tag
tags question: http://stackoverflow.com/q/47849449
tag name: deserialization

http://stackoverflow.com/q/47721315
favorite count: 0
type: Question
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/47721869
type: AnsweredQuestion
tagged with: selection-sort
has answer: http://stackoverflow.com/a/47721869
score: 1
has title: Python: selectionsort algorithm with queues
downvote count: 0
answer count: 1
has body: I have come across an exercise in Python: Read in some strings and put them into a queue Sort the strings lexicographically into a new queue, but the original queue shouldn't be changed. I should write a function from scratch (e.g. the sorted function cannot be used) The use of arrays is not allowed I think I have managed to come up with a function for step 1, but I have been struggling with step 2 for hours. I would really appreciate any kind of help! Here is my code snippet for step 1: q1 = [] def DisplayQueue(queue): for Item in queue: print(Item) def PushQueue(queue): x = True while x: user_input = input("Please enter a string (for exit type: exit): ") if user_input == "exit": x = False else: queue.append(user_input) return queue queue = PushQueue(q1)
tagged with: string
tagged with: queue

http://stackoverflow.com/tag/csv
tags question: http://stackoverflow.com/q/47828854
tags question: http://stackoverflow.com/q/47759321
type: Tag
tags question: http://stackoverflow.com/q/47801886
tags question: http://stackoverflow.com/q/47831944
tags question: http://stackoverflow.com/q/47775072
tags question: http://stackoverflow.com/q/47705691
tags question: http://stackoverflow.com/q/47736789
tags question: http://stackoverflow.com/q/47833755
tags question: http://stackoverflow.com/q/47848892
tags question: http://stackoverflow.com/q/47759724
tags question: http://stackoverflow.com/q/47703793
tags question: http://stackoverflow.com/q/47795351
tags question: http://stackoverflow.com/q/47815559
tags question: http://stackoverflow.com/q/47814362
tags question: http://stackoverflow.com/q/47733641
tags question: http://stackoverflow.com/q/47703641
tags question: http://stackoverflow.com/q/47776460
tags question: http://stackoverflow.com/q/47718488
tags question: http://stackoverflow.com/q/47703796
tags question: http://stackoverflow.com/q/47750362
tags question: http://stackoverflow.com/q/47825184
tags question: http://stackoverflow.com/q/47832820
tag name: csv
tags question: http://stackoverflow.com/q/47843681
tags question: http://stackoverflow.com/q/47714790
tags question: http://stackoverflow.com/q/47778579
tags question: http://stackoverflow.com/q/47803784
tags question: http://stackoverflow.com/q/47779214
tags question: http://stackoverflow.com/q/47784761
tags question: http://stackoverflow.com/q/47723508
tags question: http://stackoverflow.com/q/47844328
tags question: http://stackoverflow.com/q/47771524
tags question: http://stackoverflow.com/q/47740673
tags question: http://stackoverflow.com/q/47786968
tags question: http://stackoverflow.com/q/47743198
tags question: http://stackoverflow.com/q/47723378
tags question: http://stackoverflow.com/q/47777694
tags question: http://stackoverflow.com/q/47720252
tags question: http://stackoverflow.com/q/47847946
tags question: http://stackoverflow.com/q/47841302
tags question: http://stackoverflow.com/q/47709058
tags question: http://stackoverflow.com/q/47797723
tags question: http://stackoverflow.com/q/47735771
tags question: http://stackoverflow.com/q/47830223
tags question: http://stackoverflow.com/q/47787737
tags question: http://stackoverflow.com/q/47798050
tags question: http://stackoverflow.com/q/47770575
tags question: http://stackoverflow.com/q/47805205
tags question: http://stackoverflow.com/q/47834230
tags question: http://stackoverflow.com/q/47725231
tags question: http://stackoverflow.com/q/47758409
tags question: http://stackoverflow.com/q/47733763
tags question: http://stackoverflow.com/q/47759551
tags question: http://stackoverflow.com/q/47850260
tags question: http://stackoverflow.com/q/47819255
tags question: http://stackoverflow.com/q/47823477
tags question: http://stackoverflow.com/q/47836499
tags question: http://stackoverflow.com/q/47719932
tags question: http://stackoverflow.com/q/47751164
tags question: http://stackoverflow.com/q/47788748
tags question: http://stackoverflow.com/q/47732878
tags question: http://stackoverflow.com/q/47788448
tags question: http://stackoverflow.com/q/47774002
tags question: http://stackoverflow.com/q/47774601
tags question: http://stackoverflow.com/q/47698221
tags question: http://stackoverflow.com/q/47765478
tags question: http://stackoverflow.com/q/47781076
tags question: http://stackoverflow.com/q/47707210
tags question: http://stackoverflow.com/q/47773765
tags question: http://stackoverflow.com/q/47723011
tags question: http://stackoverflow.com/q/47754920
tags question: http://stackoverflow.com/q/47820002
tags question: http://stackoverflow.com/q/47712295
tags question: http://stackoverflow.com/q/47823180
tags question: http://stackoverflow.com/q/47782007
tags question: http://stackoverflow.com/q/47734621
tags question: http://stackoverflow.com/q/47756559
tags question: http://stackoverflow.com/q/47767183
tags question: http://stackoverflow.com/q/47829588

http://stackoverflow.com/q/47735949
upvote count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/59083514
has comment: http://stackoverflow.com/comment/82432605
has answer: http://stackoverflow.com/a/48846370
has comment: http://stackoverflow.com/comment/82432684
tagged with: python
has comment: http://stackoverflow.com/comment/82432629
has comment: http://stackoverflow.com/comment/82432550
has comment: http://stackoverflow.com/comment/82432691
has comment: http://stackoverflow.com/comment/82432573
has comment: http://stackoverflow.com/comment/82432600
has body: I am currently working through a book teaching myself Python and I have come across a bug I can't seem to get a good answer for. The error is: 'File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pyperclip/__init__.py", line 596, in lazy_load_stub_paste return paste() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pyperclip/__init__.py", line 109, in paste_osx_pbcopy return stdout.decode(ENCODING) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa8 in position 197: invalid start byte' The problematic line of code: text = str(pyperclip.paste()) The full script: import pyperclip, re phoneRegex = re.compile(r'''( (\d{3}|\(\d{3}\))? # area code (\s|-|\.)? # separator (\d{3}) # first 3 digits (\s|-|\.)? # separator (\d{4}) # last 4 digits (\s*(ext|x|ext.)\s*(\d{2,5}))? #extension )''', re.VERBOSE) emailRegex = re.compile(r'''( [a-zA-Z0-9._%+-]+ # username @ # @ symbol [a-zA-Z0-9.-]+ # domain name (\.[a-zA-Z]{2,4}) # dot-something )''', re.VERBOSE) text = str(pyperclip.paste()) matches = [] for groups in phoneRegex.findall(text): phoneNum = '-'.join([groups[1], groups[3], groups[5]]) if groups[8] != '': phoneNum += ' x' +groups[8] matches.append(phoneNum) for groups in emailRegex.findall(text): matches.append(groups[0]) if len(matches) &gt; 0: pyperclip.copy('\n'.join(matches)) print('Copied to clipboard:') print('\n'.join(matches)) else: print('No phone numbers of email addresses found.') Let me know if there is anything else I may provide to solve this. From my searching, it seems to be an encoding error, but I haven't the slightest idea how to solve it. I appreciate any feedback. Thank you.
score: 1
has comment: http://stackoverflow.com/comment/82489330
has comment: http://stackoverflow.com/comment/82432529
has comment: http://stackoverflow.com/comment/82432443
tagged with: utf-8
has comment: http://stackoverflow.com/comment/82440550
has comment: http://stackoverflow.com/comment/82487432
has comment: http://stackoverflow.com/comment/82483346
has comment: http://stackoverflow.com/comment/82433255
has comment: http://stackoverflow.com/comment/82432690
downvote count: 1
has comment: http://stackoverflow.com/comment/82432402
favorite count: 0
has comment: http://stackoverflow.com/comment/82432499
type: Question
tagged with: pyperclip
has title: UnicodeDecodeError: 'utf-8' codec can't decode byte ... invalid start byte
answer count: 2
has comment: http://stackoverflow.com/comment/82454649
has comment: http://stackoverflow.com/comment/82440518

http://stackoverflow.com/a/47771098
has comment: http://stackoverflow.com/comment/82503381
answers question: http://stackoverflow.com/q/47700467
has comment: http://stackoverflow.com/comment/82503311
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/82503442
has body: if stderr.read() print "Error: %s" % stderr.read() print type(stderr.read()) The first call to stderr.read() makes subsequent calls to it return nothing. Change it to something like: for line in stderr: print "Error: %s" % line

http://stackoverflow.com/a/47745803
has comment: http://stackoverflow.com/comment/82485587
upvote count: 2
downvote count: 0
has body: This way seems quite fast. See below for a brief discussion. import re df['new'] = df['sometext'] for v in ['a','ff']: df['new'] = df.apply( lambda x: re.sub( v, x[v], x['new']), axis=1 ) Results: sometext a ff new 0 asdff b g bsdg 1 asdff c hh csdhh 2 aaf d i ddf Discussion: I expanded the sample to 15,000 rows and this was the fastest approach by around 10x or more compared to the existing answers (although I suspect there might be even faster ways). The fact that you want to use the columns to make row specific substitutions is what complicates this answer (otherwise you would just do a simpler version of @wen's df.replace). As it is, that simple and fast approach requires further code in both my approach and wen's although I think they are more or less working the same way.
answers question: http://stackoverflow.com/q/47745139
type: Answer
has comment: http://stackoverflow.com/comment/82485966
score: 2

http://stackoverflow.com/q/47855220
type: Question
has title: Python functional programming, scope and variable. Where am I going wrong?
has comment: http://stackoverflow.com/comment/82674745
upvote count: 0
score: -2
downvote count: 2
answer count: 1
accepted answer: http://stackoverflow.com/a/47855386
has answer: http://stackoverflow.com/a/47855386
has comment: http://stackoverflow.com/comment/82674689
favorite count: 0
has comment: http://stackoverflow.com/comment/82674722
tagged with: scope
tagged with: opencv
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/82674667
has comment: http://stackoverflow.com/comment/82674990
has comment: http://stackoverflow.com/comment/82674768
has comment: http://stackoverflow.com/comment/82674552
has body: I am assembling a list of class functions from graphical item selections, at the end of the chain, I pass the function list to a loop for processing. All fine there. Except the loop doesn't seem to accumulate but only applies whatever the last class function applied was. I think this is due to scope but was wondering if some experienced guru can point me in the right direction. Here is a code snippet without the loop that works as expected. There are just two functions for clarity: frame=cv2.GaussianBlur(frame,(15,15),0) and frame=cv2.flip(frame, 1) The function setups an incoming video stream from video card or camera using self.capture() and then frame = cv2.cvtColor(), to provide an individual frame object that can be processed separately, in this instance the frames are blurred and flipped in orientation, using openCV (cv2) class functions, as expected, fine. def display_video_stream(self): self.capture = cv2.VideoCapture(0) frame = self.capture.read() frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) #want to replace these class functions with function list frame = cv2.GaussianBlur(frame,(15,15),0) frame = cv2.flip(frame, 1) image = QImage(frame, frame.shape[1], frame.shape[0], frame.strides[0], QImage.Format_RGB888) self.image_label.setPixmap(QPixmap.fromImage(image)) So, now I replace the two functions with a list that is processed within a for loop as below. However, when I do this, I don't get the same result. It's only the last operation in the function list applied. So instead of blurred then flipped, I get blurred or flipped, according to the order of the list. I checked the loop is looping with a print statement and that's fine, the index numbers are looping over in the console fine as the video source streams, so it is processing the functions OK but whereas the first example accumulates the frame output by passing the result of the first operation as the new source value for the second operation, the loop version doesn't. I think this is scope within the…
has comment: http://stackoverflow.com/comment/82674928
tagged with: python
tagged with: loops

http://stackoverflow.com/q/47736568
has comment: http://stackoverflow.com/comment/82433543
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47736661
has comment: http://stackoverflow.com/comment/82433526
tagged with: self
tagged with: oop
tagged with: python
has comment: http://stackoverflow.com/comment/82433545
tagged with: class
type: Question
score: 0
has body: class demo(): c_v=[] def __init__(self): demo.c_v.append('one') class demo(): c_v=[] def __init__(self): self.c_v.append('one') Both yield same result? What are the usecases of both?
has answer: http://stackoverflow.com/a/47736661
linked to: http://stackoverflow.com/q/68645
answer count: 1
has title: What is the difference between using self.classvariable and class.classvariable inside methods?
tagged with: variables
has comment: http://stackoverflow.com/comment/82433767

http://stackoverflow.com/q/47712517
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82385138
has body: Python3 Code: import serial arduinoData = serial.Serial(4, 9600) while(1): if (arduinoData.inWaiting()&gt;0): myData= arduinoData.readline() print (myData) arduinoData.open() Error: Traceback (most recent call last): File "E:/Scripts/Examples/arduinopython.py", line 3, in &lt;module&gt; arduinoData = serial.Serial(4, 9600) File "C:\Users\Om\AppData\Local\Programs\Python\Python36-32\lib\site-packages\serial\serialwin32.py", line 31, in __init__ SerialBase.__init__(self, *args, **kwargs) File "C:\Users\Om\AppData\Local\Programs\Python\Python36-32\lib\site-packages\serial\serialutil.py", line 171, in __init__ self.open() File "C:\Users\Om\AppData\Local\Programs\Python\Python36-32\lib\site-packages\serial\serialwin32.py", line 47, in open if port.upper().startswith('COM') and int(port[3:]) &gt; 8: AttributeError: 'int' object has no attribute 'upper' Can anyone help in finding where I am going wrong ?
linked to: http://stackoverflow.com/q/34574311
type: UnansweredQuestion
tagged with: python
score: -1
has title: Python and arduino Serial Communication error
has comment: http://stackoverflow.com/comment/82385893
upvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/47713051

http://stackoverflow.com/q/47804924
has comment: http://stackoverflow.com/comment/82571529
linked to: http://stackoverflow.com/q/1936466
tagged with: http://stackoverflow.com/tag/html
has body: I am trying to remove the text inside the &lt;>(html tags) and write the outcome to a new file. For example, one line of text could be: &lt; asdf&gt; Text &lt;here&gt;more text&lt; /asdf &gt; So the program would write to the output file: "Text more text", excluding those inside the html tags. This is my attempt so far: import urllib.request data=urllib.request.urlopen("some website").read() text1=data.decode("utf-8") import re def asd(text1): x=re.compile("&lt;&gt;") y=re.sub(x,"",text1) file1=open("textfileoutput.txt","w") file1.write(y) return y asd(text1) It doesn't seem to write the clean version, still has the tags. Thank you for your help.
tagged with: python
tagged with: regex
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/47804981
type: UnansweredQuestion
has title: Python removing website html tags not working
has answer: http://stackoverflow.com/a/47805004
tagged with: html-parsing
has comment: http://stackoverflow.com/comment/82571602
type: Question
linked to: http://stackoverflow.com/q/1732348
has comment: http://stackoverflow.com/comment/82571481

http://stackoverflow.com/q/47712263
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47712392
has answer: http://stackoverflow.com/a/47712433
score: 0
has answer: http://stackoverflow.com/a/47712460
possible better answer: http://stackoverflow.com/a/47712460
has answer: http://stackoverflow.com/a/47712503
tagged with: python
accepted answer: http://stackoverflow.com/a/47712503
has answer: http://stackoverflow.com/a/47712488
has answer: http://stackoverflow.com/a/47712452
type: AnsweredQuestion
has body: I had started learning python recently, and I have encountered a awkward behavior with rstrip. My understanding is that the str.rstrip() will delete all characters as soon as it encounters one of the character it took in an argument. &gt;&gt;&gt; a = 'HelloWorld' &gt;&gt;&gt; a.rstrip('l') 'HelloWorld' &gt;&gt;&gt; a = 'HelloWorld' &gt;&gt;&gt; a.rstrip('World') 'He' I'm totally confused by the result I've got. Shouldn't the first code supposed be producing 'He' instead?
has title: rstrip on python behaving awkwardly: 'HelloWorld'.rstrip('World') deletes everything after 'He'
upvote count: 1
answer count: 6
tagged with: string

http://stackoverflow.com/comment/82432672
comment on: http://stackoverflow.com/q/47735413
score: 0
has text: BTW if you get string `["1", "2", "3"]` then you have correct JSON string and you can use `json` module to convert to python list.
type: QuestionComment
type: Comment

http://stackoverflow.com/q/47743442
has title: python - interpreting two spaces as one from text file
has answer: http://stackoverflow.com/a/47743646
has comment: http://stackoverflow.com/comment/82447255
favorite count: 0
type: Question
tagged with: python-3.x
upvote count: 0
type: UnansweredQuestion
downvote count: 2
has body: I'm trying to make a program that translates morse code from a text file. In theory it should be pretty easy but the problem is that I find the formatting of the text file a bit silly (its school work so can't change that). What I meant by that is that in the file one space separates two characters (like this -. ---) but two spaces equal end of a word (so space in the translated text). Like this: .--. .-.. . .- ... . .... . .-.. .--. .-.-.- This is what I have, but it gives me translated text without the spaces. translator = {} #alphabet and the equivalent code, which I got from another file message = [] translated = ("") msg_file = open(msg.txt,"r") for line in msg_file: line = line.rstrip() part = line.rsplit(" ") message.extend(part) for i in message: if i in translator.keys(): translated += (translator[i]) print(translated) I also dont know how to intercept the line change (\n).
tagged with: python
score: -2
has comment: http://stackoverflow.com/comment/82447114
has answer: http://stackoverflow.com/a/47743711
has comment: http://stackoverflow.com/comment/82447200
answer count: 2

http://stackoverflow.com/comment/82565213
score: 0
type: Comment
type: QuestionComment
has text: What do you mean underscores? If you mean actual hyperlinks, Excel doesn't allow having more than one per cell.
comment on: http://stackoverflow.com/q/47801945

http://stackoverflow.com/comment/127039702
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/51198428
score: 0
has text: what if the product is listed inside a One2many field? let's say, something we usually called order lines in sales order?

http://stackoverflow.com/comment/82670647
type: QuestionComment
has text: So its not docker but gunicorn. I tried to curl inside container and it doesn't return any response. Added gunicorn script above. I see several connections in CLOSE_WAIT on netstat
score: 0
comment on: http://stackoverflow.com/q/47841820
type: Comment

http://stackoverflow.com/comment/89461718
comment on: http://stackoverflow.com/a/50456589
type: AnswerComment
has text: It's better to remove this line, not comment out the code. Also some explanation would be helpful, since this is caused by deleting SessionAuthenticationMiddleware in django 2.0 (which was deprecated earlier in django 1.10).
score: 11
type: Comment

http://stackoverflow.com/comment/82580942
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/47805305
type: Comment
has text: The speed of the animation is steered by the `interval` argument. A lower `interval` makes the animation faster. Apart this question is completely unclear. See [ask] and [mcve].

http://stackoverflow.com/q/47719040
type: AnsweredQuestion
answer count: 2
tagged with: pandas
tagged with: join
score: 1
has comment: http://stackoverflow.com/comment/82399217
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82400090
has comment: http://stackoverflow.com/comment/82399597
accepted answer: http://stackoverflow.com/a/47720392
has title: Joining 2 df through look up in Python using Pandas
downvote count: 0
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/47720392
possible better answer: http://stackoverflow.com/a/47720039
has comment: http://stackoverflow.com/comment/82400185
has comment: http://stackoverflow.com/comment/82399351
has body: I'm having a headache with performing a join on data frames through look up: df1, Name ID1 StartDate1 EndDate1 StartDate2 EndDate2 ab 111 1/1/2017 3/1/2017 2/1/2017 4/1/2017 bc 112 2/1/2017 3/1/2017 2/1/2017 4/1/2017 cd 113 1/1/2017 2/1/2017 2/1/2017 4/1/2017 df 114 2/1/2017 4/1/2017 2/1/2017 4/1/2017 fe 115 4/1/2017 5/1/2017 2/1/2017 4/1/2017 df2, ID1 ID2 Date Id1_num id2_num 111 10 1/1/2017 10 11 111 10 2/1/2017 10 111 10 3/1/2017 13 13 111 10 4/1/2017 15 13 112 20 2/1/2017 11 19 112 20 3/1/2017 12 112 20 4/1/2017 19 113 20 1/1/2017 17 5 113 20 2/1/2017 17 14 114 30 2/1/2017 11 13 114 30 3/1/2017 10 114 30 4/1/2017 18 13 115 30 4/1/2017 7 5 115 30 5/1/2017 13 19 I want my result df3, Name ID1 ID2 StartDate1 EndDate1 StartDate2 EndDate2 ID1Date1Count ID1Date1Average ID1Date2Count ID1Date2Average ID2Date1Count ID2Date1Average ID2Date2Count ID2Date2Average ab 111 10 1/1/2017 3/1/2017 2/1/2017 4/1/2017 2 11.5 2 14 3 11.33 3 12 bc 112 20 2/1/2017 3/1/2017 2/1/2017 4/1/2017 2 11.5 2 11.5 1 19 2 19 cd 113 20 1/1/2017 2/1/2017 2/1/2017 4/1/2017 2 17 1 17 1 14 1 14 df 114 30 2/1/2017 4/1/2017 2/1/2017 4/1/2017 3 13 3 13 2 13 2 13 fe 115 30 4/1/2017 5/1/2017 2/1/2017 4/1/2017 1 19 0 0 1 19 0 0 Where ID1Date1Count is the entries count from the date interval [StartDate1, EndDate1], ID1Date2Count is the entries count from the date interval [StartDate2, EndDate2] ID2Date1Count is the entries count from the date interval [StartDate1, EndDate1] ID2Date2Count is the entries count from the date interval [StartDate2, EndDate2] Along with their average. The extra condition here is that we do not include num if num &lt; 10. Thanks a bunch!
has answer: http://stackoverflow.com/a/47720039

http://stackoverflow.com/comment/82588277
type: Comment
comment on: http://stackoverflow.com/a/47813144
type: AnswerComment
has text: @Ev.Kounis Yep, that would basically be falling back to pure python at that point.
score: 0

http://stackoverflow.com/a/47769479
answers question: http://stackoverflow.com/q/47769453
score: 34
upvote count: 34
has comment: http://stackoverflow.com/comment/82500818
type: Answer
has comment: http://stackoverflow.com/comment/126232134
accepted answer of: http://stackoverflow.com/q/47769453
has body: I think you can create dictionary of DataFrames: dfs = dict(tuple(df.groupby('STORENAME'))) And then select by STORENAME: store1 = dfs['Store1'] store2 = dfs['Store2'] print (store1) PRICE Name PER CATEGORY STORENAME 0 9.99 MF gram Indica Store1 print (store2) PRICE Name PER CATEGORY STORENAME 1 9.99 HY gram Herb Store2 2 9.99 FF gram Herb Store2
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/126236880

http://stackoverflow.com/q/47846521
has title: I continuously receive `Invalid HTTP_HOST header` error email after I upgrade my django site from http to https
has answer: http://stackoverflow.com/a/47851675
answer count: 3
downvote count: 0
score: 29
tagged with: django
tagged with: http
tagged with: https
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47847614
accepted answer: http://stackoverflow.com/a/49817720
tagged with: nginx
has body: Recently, I upgrade one of my django sites from http to https. However, after that, I continuously receive Invalid HTTP_HOST header error email while before I never received such type of emails. Here are some log messages: [Django] ERROR (EXTERNAL IP): Invalid HTTP_HOST header: '123.56.221.107'. You may need to add '123.56.221.107' to ALLOWED_HOSTS. [Django] ERROR (EXTERNAL IP): Invalid HTTP_HOST header: 'www.sgsrec.com'. You may need to add 'www.sgsrec.com' to ALLOWED_HOSTS. [Django] ERROR (EXTERNAL IP): Invalid HTTP_HOST header: 'sgsrec.com'. You may need to add 'sgsrec.com' to ALLOWED_HOSTS. Report at /apple-app-site-association Invalid HTTP_HOST header: ‘sgsrec.com’. You may need to add ‘sgsrec.com’ to ALLOWED_HOSTS. Invalid HTTP_HOST header: ‘www.pythonzh.cn’. You may need to add ‘www.pythonzh.cn’ to ALLOWED_HOSTS. Report at / Invalid HTTP_HOST header: ‘www.pythonzh.cn’. You may need to add ‘www.pythonzh.cn’ to ALLOWED_HOSTS. Request Method: GET Request URL: http://www.pythonzh.cn/ Django Version: 1.10.6 [Django] ERROR (EXTERNAL IP): Invalid HTTP_HOST header: 'pythonzh.cn'. You may need to add 'pythonzh.cn' to ALLOWED_HOSTS. What the strange thing is that I only change my blog site www.zmrenwu.com nginx configuration, but seems all of my sites which hosted on 123.56.221.107 are effected. Of cause, I set ALLOWED_HOSTS correctly: ALLOWED_HOSTS = ['.zmrenwu.com'] ALLOWED_HOSTS = ['.sgsrec.com'] ALLOWED_HOSTS = ['.pythonzh.cn'] Nginx configuration of my blog site www.zmrenwu.com: server { charset utf-8; server_name zmrenwu.com www.zmrenwu.com; listen 80; return 301 https://www.zmrenwu.com$request_uri; } server { charset utf-8; server_name zmrenwu.com; listen 443; ssl on; ssl_certificate /etc/ssl/1_www.zmrenwu.com_bundle.crt; ssl_certificate_key /etc/ssl/2_www.zmrenwu.com.key; return 301 https://www.zmrenwu.com$request_uri; } server { charset utf-8; listen 443; server_name www.zmrenwu.com; ssl on; ssl_certificate /etc/ssl/1_www.zmrenwu.com_bundle.crt; ssl_certificat…
has answer: http://stackoverflow.com/a/49817720
tagged with: python
upvote count: 29
possible better answer: http://stackoverflow.com/a/47851675
type: AnsweredQuestion

http://stackoverflow.com/comment/82563287
comment on: http://stackoverflow.com/a/47798311
type: AnswerComment
has text: You may want to also think about making trade_id bigint
score: 0
type: Comment

http://stackoverflow.com/q/47764271
has body: I am attempting to create an SDN network from a python file I created, but it can't seem to find the directory. Is there anything I am doing wrong? Here is the syntax I used: sudo mn --custom ~/mininet/custom/project.py --topo project Here's the directory the python file is in: And just in case, I am also providing my code from my python file: from mininet.topo import Topo class Project( Topo ): def __init__( self ): # Initialize topology Topo.__init__( self ) # Add hosts h1 = self.addHost('h1') h2 = self.addHost('h2') h3 = self.addHost('h3') h4 = self.addHost('h4') h5 = self.addHost('h5') h6 = self.addHost('h6') h7 = self.addHost('h7') h8 = self.addHost('h8') h9 = self.addHost('h9') h10 = self.addHost('h10') h11 = self.addHost('h11') h12 = self.addHost('h12') h13 = self.addHost('h13') h14 = self.addHost('h14') h15 = self.addHost('h15') h16 = self.addHost('h16') h17 = self.addHost('h17') h18 = self.addHost('h18') # Add switches s1 = self.addSwitch('s1') s2 = self.addSwitch('s2') s3 = self.addSwitch('s3') s4 = self.addSwitch('s4') s5 = self.addSwitch('s5') s6 = self.addSwitch('s6') s7 = self.addSwitch('s7') s8 = self.addSwitch('s8') # Add links self.addLink(h1,s1) self.addLink(h2,s1) self.addLink(h3,s1) self.addLink(h4,s2) self.addLink(h5,s2) self.addLink(h6,s2) self.addLink(h7,s3) self.addLink(h8,s3) self.addLink(h9,s3) self.addLink(s1,s7) self.addLink(s2,s7) self.addLink(s3,s7) self.addLink(s7,s8) self.addLink(s8,s4) self.addLink(s8,s5) self.addLink(s8,s6) self.addLink(s4,h10) self.addLink(s4,h11) self.addLink(s4,h12) self.addLink(s5,h13) self.addLink(s5,h14) self.addLink(s5,h15) self.addLink(s6,h16) self.addLink(s6,h17) self.addLink(s6,h18) topos = { 'project': ( lambda: Project() )}
upvote count: 2
type: UnansweredQuestion
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/124053913
has answer: http://stackoverflow.com/a/48363895
tagged with: mininet
answer count: 5
score: 1
has answer: http://stackoverflow.com/a/68028708
has title: How to Run Custom Topology in Mininet?
tagged with: python
has answer: http://stackoverflow.com/a/47788050
has answer: http://stackoverflow.com/a/76963041
has answer: http://stackoverflow.com/a/47799414

http://stackoverflow.com/comment/82398702
comment on: http://stackoverflow.com/a/47716340
type: AnswerComment
score: 0
has text: Thanks so much - I will try it out.
type: Comment

http://stackoverflow.com/comment/82526906
has text: nope... if you want to see the data GET https://min-api.cryptocompare.com/data/all/coinlist , I'm looking at the TotalCoinSupply key
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47782580

http://stackoverflow.com/q/47730005
favorite count: 0
has answer: http://stackoverflow.com/a/47769848
has title: Problems faced by Manually Implementing a FIFOQueue in tensorflow
type: AnsweredQuestion
has body: I am trying to come up with a method that could implement a FIFOQueue in tensorflow. So on every iteration, the purpose is to assign a placeholder a certain number, then store it in a Variable named: buffer. After each assignment, I am incrementing an index. The buffer size is [5], so that index should range from 0 to 4. Finally, after the buffer is full, I would set buffer[0:4] to be buffer[1:5], and then add the new value to buffer[4]. So here is my code: import tensorflow as tf import numpy as np import random dim = 30 lst = [] for i in range(dim): lst.append(random.randint(1, 10)) data = np.reshape(lst, [dim, 1]) print(lst) # create a buffer: buffer_input = tf.placeholder(tf.int32, shape=[1]) buffer = tf.Variable(tf.zeros([5], tf.int32)) index = tf.Variable(tf.constant(0)) def fillBufferBeforeFilled(): update_op1 = tf.scatter_update(buffer, indices=[index], updates=buffer_input) index_assign_add = tf.assign_add(index, 1) return update_op1, index_assign_add def fillBufferAfterFilled(): tmp = tf.slice(buffer, begin=[0], size=[4]) update_op2 = tf.scatter_update(buffer, indices=[0, 1, 2, 3], updates=tmp) update_op3 = tf.scatter_update(buffer, indices=[index], updates=buffer_input) return update_op2, update_op3 cond = tf.cond(tf.equal(index, 4), lambda: fillBufferBeforeFilled(), lambda: fillBufferAfterFilled()) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) for i in range(dim): cond_ = sess.run(cond, feed_dict={buffer_input: data[i]}) buf = sess.run(buffer, feed_dict={buffer_input: data[i]}) print('buf: ', buf) Problem: The index Variable is not incremented after each call, while the first element of the buffer is being assigned to the value passed to the placeholder. I would like to know why I'm getting this behavior and what is the solution to this problem. any help is much appreciated!!
accepted answer: http://stackoverflow.com/a/47776715
score: 1
has answer: http://stackoverflow.com/a/47776715
tagged with: python
tagged with: queue
tagged with: tensorflow
type: Question
answer count: 2
downvote count: 0
upvote count: 1
possible better answer: http://stackoverflow.com/a/47769848
tagged with: lambda

http://stackoverflow.com/a/47764454
has comment: http://stackoverflow.com/comment/82490482
has comment: http://stackoverflow.com/comment/82490341
has body: You can do the following: &gt;&gt; x.groupby("person").rating.apply(lambda x: x[x &lt;= 4].count()) person a 4 b 5 and &gt;&gt; x.groupby("person").rating.apply(lambda x: x[x == 4].count()) person a 2 b 1
answers question: http://stackoverflow.com/q/47764095
type: Answer
has comment: http://stackoverflow.com/comment/82490318
upvote count: 1
has comment: http://stackoverflow.com/comment/82490687
downvote count: 1
has comment: http://stackoverflow.com/comment/82490827
score: 0

http://stackoverflow.com/a/47778755
answers question: http://stackoverflow.com/q/47778601
has comment: http://stackoverflow.com/comment/82518654
has comment: http://stackoverflow.com/comment/82518609
type: Answer
has comment: http://stackoverflow.com/comment/82519128
has comment: http://stackoverflow.com/comment/82519150
has comment: http://stackoverflow.com/comment/82519347
has comment: http://stackoverflow.com/comment/82518636
score: 0
has body: This will help you test_list = ['test1','test2','test3'] for test in test_list: f = open('{}.txt'.format(test),'wb') # f.write(test) f.close() for more visit : https://www.tutorialspoint.com/python/python_files_io.htm
accepted answer of: http://stackoverflow.com/q/47778601
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82518959
has comment: http://stackoverflow.com/comment/82519247

http://stackoverflow.com/comment/82372545
comment on: http://stackoverflow.com/a/47706195
score: 0
has text: See new text "hard part"
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47718013
has comment: http://stackoverflow.com/comment/82396693
tagged with: matplotlib
has title: matplotlib legend avoids points when manually setting coordinates
has answer: http://stackoverflow.com/a/47718314
accepted answer: http://stackoverflow.com/a/47718314
type: Question
answer count: 1
linked to: http://stackoverflow.com/q/4700614
tagged with: python
has comment: http://stackoverflow.com/comment/82396570
type: AnsweredQuestion
score: 0
has body: In the following code, I generate a scatterplot where the legend is manually placed: #!/usr/bin/env python3 import pandas as pd import matplotlib.pyplot as plt import numpy as np frame = frame = pd.DataFrame({"x": [1, 2, 3, 4], "y": [4, 3, 2, 1]}) ax = frame.plot.scatter(x="x", y="y", label="dots") plt.savefig("dots.pdf") for y in [0.6, 0.7, 0.8]: ax.legend(bbox_to_anchor=(0.5, y), bbox_transform=ax.transAxes) plt.savefig("dots_{}.png".format(y)) It looks like the legend does not obey the placement instructions when it would make it hide a point: Is there a way to avoid this? I mean, how to really force the placement of the legend?

http://stackoverflow.com/comment/82596777
comment on: http://stackoverflow.com/q/47817250
has text: Possible duplicate of [Python linear interpolation of values in dataframe](https://stackoverflow.com/questions/34362629/python-linear-interpolation-of-values-in-dataframe)
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82674336
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47855011
type: Comment
has text: yes, it will not close it if you don't call this ```session.close()``` because ```engine.dispose()``` only close the idle connections. you can see this documentation http://docs.sqlalchemy.org/en/latest/core/pooling.html#sqlalchemy.pool.Pool.dispose.

http://stackoverflow.com/comment/82401165
type: Comment
type: QuestionComment
has text: By default Jinja [escapes](https://stackoverflow.com/questions/3206344/passing-html-to-template-using-flask-jinja2) all your HTML syntax, so it is displayed as is. You can use `safe`, but moving all HTML to templates would be a better option. You can store your data list in the form of dictionaries and access them via dot in the template.
comment on: http://stackoverflow.com/q/47717891
score: 0

http://stackoverflow.com/comment/82597149
type: Comment
score: 0
type: AnswerComment
has text: Checking it right now. Added Unique=True to model, but it still let registrate new user the same email. Checked the db, my email field called 'email'. Maybe something is wrong with user?
comment on: http://stackoverflow.com/a/47816133

http://stackoverflow.com/q/47722336
has body: from tkinter import * class App(): def __init__(self, root): self.root = root def Function(self): self.grid = [] for i in range(7): row = [] for j in range(6): row.append(Button(self.root,width=2,height=1,command=lambda i=i, j=j: self.Click1(i, j))) row[-1].grid(row=i,column=j) self.grid.append(row) def Click1(self, i, j): self.grid[i][j]["bg"]="blue" root = Tk() app = App(root) app.Function() root.mainloop() I need this to function without class. I tried removing the class option but I think that will cause a chain effect for everything else. Please help me remove the classes and just keep methods.
type: Question
accepted answer: http://stackoverflow.com/a/47722770
tagged with: python
has answer: http://stackoverflow.com/a/47722770
has title: How can I make this function without classes - Python 3 Tkinter
has comment: http://stackoverflow.com/comment/82405375
type: AnsweredQuestion
score: 0
answer count: 1

http://stackoverflow.com/comment/82420887
type: Comment
score: 0
type: AnswerComment
has text: Manu!: I have edited my question now, is it possible for you to help me now.
comment on: http://stackoverflow.com/a/47723605

http://stackoverflow.com/comment/82583120
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47810149
score: 2
has text: To get better help, please provide a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve). In particular check out [How to make good reproducible pandas examples](https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples)

http://stackoverflow.com/q/47825709
answer count: 3
tagged with: pandas
has comment: http://stackoverflow.com/comment/82725596
possible better answer: http://stackoverflow.com/a/47826503
has answer: http://stackoverflow.com/a/47826503
has body: What I have is a four columns matrix. I want to keep the first two columns and turn last two columns into a sort of occurrence matrix(but with corresponding values). I tried to groupby ['shop_id', 'item_id', 'date'] but have no idea how to fill 0 for those empty date. Anyone have an idea? many thanks given: shop_id item_id date sales 0 19 0 1 0 19 2 13 0 19 3 11 1 19 1 3 result: shop_id item_id date_0 date_1 date_2 date_3 0 19 1 0 13 11 1 19 0 3 0 0
favorite count: 0
type: Question
has title: How to make occurrence matrix with pandas columns
upvote count: 2
has answer: http://stackoverflow.com/a/47825840
downvote count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/47825757
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47825757

http://stackoverflow.com/comment/82633140
type: QuestionComment
has text: In my system button widget centers its text both horizontally and vertically by default.
comment on: http://stackoverflow.com/q/47834896
score: 1
type: Comment

http://stackoverflow.com/a/47841523
answers question: http://stackoverflow.com/q/47841438
downvote count: 0
has comment: http://stackoverflow.com/comment/82647354
score: 1
type: Answer
upvote count: 1
has body: This is what I get using python 3 &gt;&gt;&gt; print (math.log(8)) 2.0794415416798357 &gt;&gt;&gt; print (math.log(2)) 0.6931471805599453 &gt;&gt;&gt; print (math.log(8) / math.log(2)) 3.0 &gt;&gt;&gt; print (2.07944154168 % 0.69314718056) 0.0 &gt;&gt;&gt; print (math.log(8) % math.log(2)) 0.6931471805599452 &gt;&gt;&gt; print (2.0794415416798357 % 0.6931471805599453) 0.6931471805599452 It looks like in your example (python 2 ?), the precision of math.log is not enough.

http://stackoverflow.com/a/47794670
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47794440
accepted answer of: http://stackoverflow.com/q/47794440
type: Answer
has body: You can use if-else while initializing input value to map() Case 1: &gt;&gt;&gt; sample['AD'] = [8,14] &gt;&gt;&gt; ','.join(map(str, sample['AD'] if isinstance(sample['AD'], list) else list(str(sample['AD'])))) '8,14' Case 2 : &gt;&gt;&gt; sample['AD'] = 5 &gt;&gt;&gt; ','.join(map(str, sample['AD'] if isinstance(sample['AD'], list) else list(str(sample['AD'])))) '5'
score: 0

http://stackoverflow.com/a/47760086
has comment: http://stackoverflow.com/comment/82481934
downvote count: 0
upvote count: 1
has body: Or we using replace and isnull df.loc[:,df.replace(dict(zip(list(myset), [np.nan]*len(myset)))).isnull().any().values] Out[907]: one two a 76 94 b 46 36 c 28 86 d 83 17 e 15 98 Edit : df.loc[:,df.loc'd'.replace(dict(zip(list(myset), [np.nan]*len(myset)))).isnull().any().values]
score: 1
answers question: http://stackoverflow.com/q/47759947
type: Answer

http://stackoverflow.com/comment/82588427
has text: Exactly what I was thinking of, using `__eq__`.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47813600
type: AnswerComment

http://stackoverflow.com/comment/82558396
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47798708
type: QuestionComment
has text: please share ur answer

http://stackoverflow.com/q/47768212
favorite count: 0
has answer: http://stackoverflow.com/a/47768284
possible better answer: http://stackoverflow.com/a/47768284
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47768239
accepted answer: http://stackoverflow.com/a/47768239
answer count: 3
has title: Inserting data into MySQL DB using Python
linked to: http://stackoverflow.com/q/9173073
tagged with: python
duplicate of: http://stackoverflow.com/q/9173073
type: Question
score: 0
has comment: http://stackoverflow.com/comment/82497509
upvote count: 1
has answer: http://stackoverflow.com/a/47768345
tagged with: mysql
has comment: http://stackoverflow.com/comment/82497882
has body: I want to insert data to Mysql database using python. Here is my code def insert_db(time_spent): global user_id global total_time_spent user = user_id project = get_project_id() timesingle = time_spent timeall = total_time_spent #connect to the database connect_db = mysql.connector.connect(user='root',password='',host='127.0.0.1',database='python_test') cursor = connect_db.cursor() cursor.execute("INSERT INTO time (user_id,project_id,spent_time,total_time) VALUES (%s,%s,%s,%s)",(user,project,timesingle,timeall)) # insert new row to table if cursor.lastrowid: print('last insert id', cursor.lastrowid) else: print('last insert id not found') #close the cursor and database connection cursor.close() connect_db.close() The problem is when I execute this function, even 'last insert row id' is showing the id, the data is not inserting to the database. I checked all the variables in this function and they are not empty. How can I fix this issue
downvote count: 1

http://stackoverflow.com/comment/82645257
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47840138
type: Comment
has text: I run it on Python 3.6, Linux Mint 18.2 and it works. It only informs that I should use `lxml` or `html.parser` in `BeautifulSoup(r, 'lxml')` but it doesn't give your error message.

http://stackoverflow.com/comment/82528391
score: 0
has text: Your question is very difficult to read. Please try to [format](https://stackoverflow.com/editing-help) it. It is difficult to tell what exactly is in the input file and what your expected output is.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47783480

http://stackoverflow.com/comment/82418786
type: QuestionComment
has text: I think what you are doing now is correct. What were the results from training the network on this code ?
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47726870

http://stackoverflow.com/comment/82488300
score: 2
has text: What is the question?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47763341

http://stackoverflow.com/comment/82405038
comment on: http://stackoverflow.com/q/47722168
score: 2
type: Comment
has text: `users` is a list. Items in a list are numbered. You want a dictionary: `users = {}`
type: QuestionComment

http://stackoverflow.com/comment/82371808
score: 0
comment on: http://stackoverflow.com/q/47705840
has text: calling a class method automatically sends itself as an argument. What class is `map`?
type: Comment
type: QuestionComment

http://stackoverflow.com/a/56516135
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47752749
type: Answer
score: 1
has body: In your example you are passing the --nukeassist arg. I think you should be passing the --nukex arg (list of args) Also, if this script will be running from within nuke then you can just pass in nuke.root().name() which will return the path to the currently opened file(or "root" if unsaved). nukeProcess = subprocess.Popen(["C:\Program Files\Nuke11.3v2\Nuke11.3.exe", "--nukex", nuke.root().name()])

http://stackoverflow.com/comment/82636873
type: AnswerComment
comment on: http://stackoverflow.com/a/47786168
score: 0
type: Comment
has text: Example how "registry" class at some container class Registry(type): def registry_class(cls): container = cls.container if not container: return container.classes[cls.kind] = cls def __new__(meta, name, bases, dct): cls = super(Registry, meta).__new__(meta, name, bases, dct) cls.registry_class() return cls

http://stackoverflow.com/comment/82426787
score: 0
type: AnswerComment
type: Comment
has text: hello! Yes, I did that
comment on: http://stackoverflow.com/a/47722267

http://stackoverflow.com/q/47799510
downvote count: 0
has comment: http://stackoverflow.com/comment/82562549
has title: Python3 custom decode
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82560808
type: UnansweredQuestion
has body: When i migrate my code from python2 to python3.My code is not producing desired result instead it generate error: code snippet and error log as shown below. import os import sys import base64 def decode(key, enc): dec = [] enc = base64.urlsafe_b64decode(enc) print(enc) for i in range(len(enc)): key_c = key[i % len(key)] print(key_c) dec_c = chr((256 + ord(enc[i]) - ord(key_c)) % 256) print(dec_c) dec.append(dec_c) return "".join(dec) contents = "p6KisaignLOinZqgmqKin6OT0uTZ0tSTlaKmpI+klJ+loI" decodedLicense = decode('crab',contents) Error Log: File "s.py", line 16, in decode dec_c = chr((256 + ord(enc[i]) - ord(key_c)) % 256) TypeError: ord() expected string of length 1, but int found
tagged with: python
has answer: http://stackoverflow.com/a/47801583
has comment: http://stackoverflow.com/comment/82560796
score: 2
has comment: http://stackoverflow.com/comment/82561733
has comment: http://stackoverflow.com/comment/82560614
has comment: http://stackoverflow.com/comment/82573124
upvote count: 2
answer count: 1

http://stackoverflow.com/comment/82612144
comment on: http://stackoverflow.com/q/47824211
type: QuestionComment
has text: Just added a bit of grammar and clarification and capitalized some I's.
score: 0
type: Comment

http://stackoverflow.com/a/47738572
score: 0
answers question: http://stackoverflow.com/q/47738554
has body: Because in order to insert and delete, you need to make search and search takes O(n) in worst case. Therefore, it should also takes at least O(n) in worst case as well.
type: Answer

http://stackoverflow.com/a/47866010
type: Answer
score: 0
answers question: http://stackoverflow.com/q/47708932
has body: The Tensorflow needs an empty network structure before the saved variables are restored. If you do not like this, I recommend the Keras. In this example, the famous AlexNet is restored to classify some images. I hope it contains the code that you need. import time import tensorflow as tf from alexnet import AlexNet from imageio import imread import numpy as np from caffe_classes import class_names #Tensor x = tf.placeholder(tf.float32, (None, 227, 227, 3)) probs = AlexNet(x, feature_extract=False) sess = tf.Session() sess.run(tf.global_variables_initializer()) saver = tf.train.Saver() save_file = './model.ckpt' saver.restore(sess, save_file) # Read Images im1 = (imread(".\Example_Figs\weasel.png")[:, :, :3]).astype(np.float32) im1 = im1 - np.mean(im1) im1[:, :, 0], im1[:, :, 2] = im1[:, :, 2], im1[:, :, 0] im2 = (imread(".\Example_Figs\poodle.png")[:, :, :3]).astype(np.float32) im2 = im2 - np.mean(im2) im2[:, :, 0], im2[:, :, 2] = im2[:, :, 2], im2[:, :, 0] im3 = (imread(".\Example_Figs\dog.png")[:, :, :3]).astype(np.float32) im3 = im3 - np.mean(im3) im3[:, :, 0], im3[:, :, 2] = im3[:, :, 2], im3[:, :, 0] im4 = (imread(".\Example_Figs\dog2.png")[:, :, :3]).astype(np.float32) im4 = im4 - np.mean(im4) im4[:, :, 0], im4[:, :, 2] = im4[:, :, 2], im4[:, :, 0] im5 = (imread(".\Example_Figs\quail.jpg")[:, :, :3]).astype(np.float32) im5 = im5 - np.mean(im5) im5[:, :, 0], im5[:, :, 2] = im5[:, :, 2], im5[:, :, 0] t = time.time() output = sess.run(probs, feed_dict={x: [im1, im2, im3, im4, im5]}) # Print Output for input_im_ind in range(output.shape[0]): inds = np.argsort(output)[input_im_ind, :] print("Image", input_im_ind) for i in range(5): print("%s: %.3f" % (class_names[inds[-1 - i]], output[input_im_ind, inds[-1 - i]])) print() print("Time: %.3f seconds" % (time.time() - t))

http://stackoverflow.com/comment/82560366
type: QuestionComment
comment on: http://stackoverflow.com/q/47799382
score: 0
has text: if you use `mitmproxy` without installing then you shouldn't have access to `urwid`.
type: Comment

http://stackoverflow.com/comment/137055338
score: 0
has text: have you tried to use this with Google Fonts? Thanks.
type: Comment
comment on: http://stackoverflow.com/a/72544131
type: AnswerComment

http://stackoverflow.com/q/47770914
favorite count: 0
type: Question
tagged with: reactive-programming
tagged with: rx-py
has title: RxPY - flat_map emissions waits for next generator value
type: UnansweredQuestion
downvote count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/82705168
tagged with: rxjs
score: 3
has body: Hi! I'm trying to get my first RxPY project done, but I'm having some problems undestanding the behavior of flat_map in Python. In this project there is an Observable created from a generator (a Kafka consumer). It emits values when a message is received, then performs a query based on the message, and emits a value for each result. I made some changes to the code in order to make it easier to reproduce. Kafka consumer was replaced by a generator that takes a lot of time between emissions, and query results were replaced by an Observable that emits 3 values. Behavior is still the same. from rx import Observable generator = (i for i in range(100000000) if i == 0 or i == 50000000) Observable.from_(generator) \ .flat_map(lambda i: Observable.from_(['a', 'b', 'c'])) \ .subscribe(on_next=lambda i: print(i)) Output: a (...waits a long time...) b a (...waits a long time...) c b c I was expecting something like this: a b c (...waits a long time...) a b c What is the reason for this behavior? What should I do to get the expected result? Thank you! :)
has answer: http://stackoverflow.com/a/65682938
upvote count: 3
answer count: 1
tagged with: system.reactive

http://stackoverflow.com/a/73998721
upvote count: 6
score: 6
has comment: http://stackoverflow.com/comment/138923079
downvote count: 0
has comment: http://stackoverflow.com/comment/134296100
answers question: http://stackoverflow.com/q/47743246
has body: I did some test with multiple library. decord ffprobe MoviePy PyAV pyffms2 OpenCV import av import cv2 import json import os import shutil import sys import subprocess import time from decimal import Decimal from decord import VideoReader from ffms2 import VideoSource from moviepy.editor import VideoFileClip from typing import List def with_movie_py(video: str) -> List[int]: """ Link: https://pypi.org/project/moviepy/ My comments: The timestamps I get are not good compared to gMKVExtractGUI or ffms2. (I only tried with VFR video) Parameters: video (str): Video path Returns: List of timestamps in ms """ vid = VideoFileClip(video) timestamps = [ round(tstamp * 1000) for tstamp, frame in vid.iter_frames(with_times=True) ] return timestamps def with_cv2(video: str) -> List[int]: """ Link: https://pypi.org/project/opencv-python/ My comments: I don't know why, but the last 4 or 5 timestamps are equal to 0 when they should not. Also, cv2 is slow. It took my computer 132 seconds to process the video. Parameters: video (str): Video path Returns: List of timestamps in ms """ timestamps = [] cap = cv2.VideoCapture(video) while cap.isOpened(): frame_exists, curr_frame = cap.read() if frame_exists: timestamps.append(round(cap.get(cv2.CAP_PROP_POS_MSEC))) else: break cap.release() return timestamps def with_pyffms2(video: str) -> List[int]: """ Link: https://pypi.org/project/ffms2/ My comments: Works really well, but it doesn't install ffms2 automatically, so you need to do it by yourself. The easiest way is to install Vapoursynth and use it to install ffms2. Also, the library doesn't seems to be really maintained. Parameters: video (str): Video path Returns: List of timestamps in ms """ video_source = VideoSource(video) # You can also do: video_source.track.timecodes timestamps = [ int( (frame.PTS * video_source.track.time_base.numerator) / video_source.track.time_base.denominator ) for frame in video_source.track.frame_info_list ] return timestamps def with_decord(video: str) -…
has comment: http://stackoverflow.com/comment/132250454
type: Answer

http://stackoverflow.com/comment/82394691
comment on: http://stackoverflow.com/q/47716598
score: 0
type: Comment
type: QuestionComment
has text: Do you have any example inputs and expected outputs?

http://stackoverflow.com/comment/82593245
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47810767
has text: mysetup could be and import instruction, but here I'm not using any lib sot mysetup="" =>nothing
type: Comment

http://stackoverflow.com/q/47776066
favorite count: 0
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82513589
has title: Using .split to isolate undefined keyword in Python
accepted answer: http://stackoverflow.com/a/47776279
has comment: http://stackoverflow.com/comment/82513406
tagged with: python
score: 2
upvote count: 2
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82513748
tagged with: split
has body: I'm taking an image, running it through pytesseract to get a list of text, and saving that list as a variable: img = Image.open(path_to_some_image) imgtxt = pytesseract.image_to_string(img) print(imgtxt) &gt;&gt; Some text here keyword Random strings Random chars My challenge is getting keyword without defining it, as it changes depending on when the program is run. I've found that keyword always follows Some text here, whereby Some and here are always constant, and text fluctuates between two words, so I split the output at here. Now, I get the following: print(imgtxt.split("here",1)[1]) &gt;&gt; keyword Random strings Random chars This removes everything before keyword without defining it, but now I'd like to remove everything after. My question, then, is how could I remove Random strings and Random chars without making keyword into a variable?
tagged with: environment-variables
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/47776279
has comment: http://stackoverflow.com/comment/82513488

http://stackoverflow.com/comment/82676442
comment on: http://stackoverflow.com/a/47855840
score: 0
type: Comment
has text: What is value in index `7`? `print(df.loc[7, 'amount_years'])`?
type: AnswerComment

http://stackoverflow.com/comment/82455164
score: 3
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47747299
has text: I think [Aaron Hall♦'s answer](https://stackoverflow.com/a/28353158/4014959) at the linked question covers everything nicely.

http://stackoverflow.com/q/47772083
has answer: http://stackoverflow.com/a/47773257
has body: For some reason the I cant identify the the button element in the below html button class="next". Ive tried various methods but I never get a positive hit. Ive confirmed its not in an iframe and as all the methods i have tried (id, class, xpath("//li[@class='next']/button")) Im hoping someone could point out my stupidity. 1 2 3 4 5 6 7 8 9 10 Next Next <g class="small-icon" style="fill-opacity: 1"> </g>
type: UnansweredQuestion
tagged with: python
tagged with: selenium-webdriver
tagged with: xpath
score: 0
has comment: http://stackoverflow.com/comment/82505013
answer count: 1
tagged with: selenium
has title: Selenium issues with finding an element
type: Question

http://stackoverflow.com/a/47763354
accepted answer of: http://stackoverflow.com/q/47763138
type: AcceptedAnswer
has body: Since all you are doing is a max you can use "max comprehension": dict_of_x = ( {'key':0,'value':0,'duration_to_cancel':10}, {'key':0,'value':1,'duration_to_cancel':15}, {'key':0,'value':2,'duration_to_cancel':1}, {'key':1,'value':3,'duration_to_cancel':2}, {'key':2,'value':4,'duration_to_cancel':None} ) def yours(): dictionary = {} for x in dict_of_x: if x['duration_to_cancel'] == None or x['duration_to_cancel'] &gt; 5: key = x['key'] value = x['value'] if key not in dictionary or value &gt; dictionary[key]: dictionary[key] = value return dictionary print yours() {0: 1, 2: 4} def mine(): dictionary = {key : max(x['value'] for x in dict_of_x if x['key'] == key) \ for key in set(x['key'] for x in dict_of_x if x['duration_to_cancel'] == None or x['duration_to_cancel'] &gt; 5)} return dictionary print mine() {0: 1, 2: 4} Note however that list/dict/set/max comprehension just for the sake of it is not necessarily a good thing for readability. Also in you implementation you go through your dict only once, while my code will loop several times through it, which also comes with reduced speed: %timeit yours() 1000000 loops, best of 3: 855 ns per loop %timeit mine() 100000 loops, best of 3: 2.32 µs per loop
type: Answer
answers question: http://stackoverflow.com/q/47763138
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/comment/82582761
score: 0
has text: You know that will make them strings so you can no longer operate with them, right?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47810780

file
tags question: http://stackoverflow.com/q/47835269
type: Tag
tags question: http://stackoverflow.com/q/47793724
tags question: http://stackoverflow.com/q/47833840
tags question: http://stackoverflow.com/q/47725059
tags question: http://stackoverflow.com/q/47729870
tags question: http://stackoverflow.com/q/47848559
tags question: http://stackoverflow.com/q/47792429
tags question: http://stackoverflow.com/q/47756936
tags question: http://stackoverflow.com/q/47846234
tag name: file
tags question: http://stackoverflow.com/q/47727525
tags question: http://stackoverflow.com/q/47783480
tags question: http://stackoverflow.com/q/47737141
tags question: http://stackoverflow.com/q/47725684
tags question: http://stackoverflow.com/q/47726633
tags question: http://stackoverflow.com/q/47842780
tags question: http://stackoverflow.com/q/47784843
tags question: http://stackoverflow.com/q/47845900
tags question: http://stackoverflow.com/q/47829603
tags question: http://stackoverflow.com/q/47782404
tags question: http://stackoverflow.com/q/47739197
tags question: http://stackoverflow.com/q/47848426
tags question: http://stackoverflow.com/q/47698647
tags question: http://stackoverflow.com/q/47721816
tags question: http://stackoverflow.com/q/47790125
tags question: http://stackoverflow.com/q/47809298
tags question: http://stackoverflow.com/q/47839877

http://stackoverflow.com/a/47737392
has comment: http://stackoverflow.com/comment/82435171
score: 2
has body: I made a couple of changes to your Queue class. Primarily, the .dequeue method didn't return the item it pops, so it returns the default value of None. I also changed the .size method to __len__ so you can pass Queue instances to the built-in len function. And gave it an iter method to you can easily use it in for loops, or pass it to .join. I also changed the .isEmpty to .is_empty to conform with Python's PEP-0008 style guide. Since you want each name to be randomly added to the queue without repetition we don't want random.choice here. Instead we can userandom.shuffle; another option is to use random.sample, although that's more suitable when you want to make a partial selection from a list. from random import seed, shuffle, randrange # Seed the randomizer so we can reproduce results while testing seed(9) class Queue: def __init__(self): self.container = [] def __len__(self): return len(self.container) def is_empty(self): return len(self) == 0 def enqueue(self, item): self.container.append(item) def dequeue(self): return self.container.pop(0) def peek(self) : return self.container[0] def __iter__(self): return iter(self.container) names = ["Alvin", "James", "Peter"] # Enqueuing q = Queue() # Make a temporary copy of the names that we can # shuffle without affecting the original list temp = names.copy() shuffle(temp) # Put the shuffled names onto the queue for name in temp: q.enqueue(name) # Dequeuing and Printing print("Contacting the following") print('\n'.join(q)) #for name in q: #print(name) while not q.is_empty(): name = q.dequeue() print('\nNow Calling -', name) answered = randrange(2) booked = randrange(2) if answered: print("Phone answered: Yes") if booked: print("Booked an appointment: Yes") print("Booking successful.") else: print("Booked an appointment: No") print("Reshedule an appointment again.") else: print("Phone answered: No") print("Reshedule a callback.") output Contacting the following Alvin Peter James Now Calling - Alvin Phone answered: Yes Boo…
upvote count: 2
has comment: http://stackoverflow.com/comment/82436231
downvote count: 0
has comment: http://stackoverflow.com/comment/82435403
has comment: http://stackoverflow.com/comment/82435188
accepted answer of: http://stackoverflow.com/q/47737343
has comment: http://stackoverflow.com/comment/82436393
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47737343
type: Answer

http://stackoverflow.com/q/47758601
favorite count: 0
type: Question
tagged with: numpy
has title: Re-occurrence count
has answer: http://stackoverflow.com/a/47758637
has body: I have a dataframe like the follow: Col1 0 C 1 A 3 D 4 A 5 A I would like to count the step/index that a certain value will re-occur so I would get the following: Col1 Col2 0 C NaN 1 A 2 3 D NaN 4 A 1 5 A NaN Any ideas on how to do it ? Thanks for help !
upvote count: 1
accepted answer: http://stackoverflow.com/a/47758637
tagged with: python
type: AnsweredQuestion
downvote count: 0
tagged with: pandas
score: 1
answer count: 1
tagged with: dataframe

http://stackoverflow.com/comment/82386180
type: QuestionComment
has text: Postgres has its own `COPY` command for loading CSV directly, [see here](https://stackoverflow.com/questions/2987433/how-to-import-csv-file-data-into-a-postgresql-table). I'm not sure you even need to involve Python if you don't want to.
comment on: http://stackoverflow.com/q/47713150
score: 1
type: Comment

http://stackoverflow.com/q/47721452
has answer: http://stackoverflow.com/a/47722868
type: Question
tagged with: python
answer count: 1
tagged with: subprocess
type: AnsweredQuestion
score: 0
has title: Runing multiple processes within python script
accepted answer: http://stackoverflow.com/a/47722868
has body: Within my python script I need to launch several processes : 1) I need to run another python script ( a flask app with the command python app.py) 2)then I need to launch the command ngrok http 5000 and from this command output get the url on which ngrok is forwarding. I have tried to use the subprocess module, but when it executes : subprocess.Popen( "python app/app.py",shell=True) it launches the interactive shell and blocks the execution of my script. What is the correct way to achieve this ?

http://stackoverflow.com/q/47804020
downvote count: 1
score: 19
favorite count: 0
tagged with: one-to-one
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47804082
tagged with: postgresql
has answer: http://stackoverflow.com/a/47804082
tagged with: python
has body: Working with Django 1.11 and a postgreSQL Database (just switched from sqlite and didn't have this problem before) So I have 3 models: models.py class Person(models.Model): is_parent = models.BooleanField() class VideoGamePurchase(models.Model): bought_by = models.ForeignKey(Person) after_homework = models.OneToOneField(HomeWork, OPTIONS???) class HomeWork(models.Model): done_by = models.ForeignKey(Person) content = models.CharField(blablaba) So the logic I'm try to implement is that if Person.is_parent is True a VideoGamePurchase instance can be created with an empty or null field for after_homework. However, if Person.is_parent is False, I want this field to be the primary key of a unique HomeWork object. I can't find the right options to achieve this: If I don't have primary_key=True then the makemigrations fails: You are trying to add a non-nullable field 'id' to video_game_purchase without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Quit, and let me add a default in models.py so I guess I hav to have primary_key=True. But then it seems like I can't have null=Trueor blank=True. Is there a way to have a OneToOneField optionally empty with postgreSQL? Is there a other/simpler way to implement this sort of logic? Thanks for your help!
type: Question
has title: Django OneToOneField with possible blank field
upvote count: 20
answer count: 1
tagged with: django

raspberry-pi
tags question: http://stackoverflow.com/q/47792922
tags question: http://stackoverflow.com/q/47776068
tags question: http://stackoverflow.com/q/47760335
tags question: http://stackoverflow.com/q/47772909
tags question: http://stackoverflow.com/q/47797041
type: Tag
tags question: http://stackoverflow.com/q/47715886
tags question: http://stackoverflow.com/q/47823332
tags question: http://stackoverflow.com/q/47772911
tags question: http://stackoverflow.com/q/47783372
tags question: http://stackoverflow.com/q/47787870
tags question: http://stackoverflow.com/q/47751919
tags question: http://stackoverflow.com/q/47720081
tags question: http://stackoverflow.com/q/47783708
tags question: http://stackoverflow.com/q/47842106
tags question: http://stackoverflow.com/q/47739887
tags question: http://stackoverflow.com/q/47720239
tag name: raspberry-pi
tags question: http://stackoverflow.com/q/47773620
tags question: http://stackoverflow.com/q/47816303
tags question: http://stackoverflow.com/q/47755484
tags question: http://stackoverflow.com/q/47813824
tags question: http://stackoverflow.com/q/47824302
tags question: http://stackoverflow.com/q/47762068
tags question: http://stackoverflow.com/q/47773474
tags question: http://stackoverflow.com/q/47749188

http://stackoverflow.com/q/47804129
answer count: 2
possible better answer: http://stackoverflow.com/a/47805473
downvote count: 0
tagged with: button
has answer: http://stackoverflow.com/a/47805473
tagged with: gtk3
favorite count: 0
has body: Preface In gnome 3 applications some buttons are highlighted by having a tinted background instead of that greyish color of a normal button. These buttons aren't only colored differently when using the standard Adwaita Theme, but are also implemented in a variety of other themes. Below are examples of a normal button and a colored one respectively for the Adwaita and the Flat Plat Theme. Adwaita Flat Plat Now to my problem I would like to be able to also implement these "important buttons" in my Gtk3 applications. During research on how to do that I discovered in the theme files that these "important buttons" have a special CSS class called needs-attention. I then tried to set the CSS class of my button to needs-attention as well. However that didn't work. I'm still getting a grey standard button. To demonstrate what I did I'm appending a minimal script and a screenshot of the running program. The "Rename" button should be highlighted just like in the screenshot above. How do I do that? My Code #!/usr/bin/env python3 import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk class ButtonWindow(Gtk.Window): def __init__(self): Gtk.Window.__init__(self, title="Needs Attention Button") self.set_border_width(10) hbox = Gtk.Box(spacing=6) self.add(hbox) button = Gtk.Button.new_with_label("Remove") hbox.pack_start(button, True, True, 0) button = Gtk.Button.new_with_mnemonic("Rename") button.get_style_context().add_class("needs-attention") hbox.pack_start(button, True, True, 0) win = ButtonWindow() win.connect("delete-event", Gtk.main_quit) win.show_all() Gtk.main()
type: Question
has answer: http://stackoverflow.com/a/47817235
accepted answer: http://stackoverflow.com/a/47817235
tagged with: gnome-3
tagged with: gnome
tagged with: python
has title: Gtk3/Gnome 3 colored button: apply ".needs-attention" css styles
type: AnsweredQuestion
score: 3
upvote count: 3

http://stackoverflow.com/comment/82627456
comment on: http://stackoverflow.com/a/47831078
type: AnswerComment
score: 0
type: Comment
has text: Maybe we can use set_index and map here. This solution looks better

twitter
tags question: http://stackoverflow.com/q/47726484
tags question: http://stackoverflow.com/q/47797110
tags question: http://stackoverflow.com/q/47852557
tags question: http://stackoverflow.com/q/47733345
tag name: twitter
tags question: http://stackoverflow.com/q/47852373
tags question: http://stackoverflow.com/q/47841431
tags question: http://stackoverflow.com/q/47832807
tags question: http://stackoverflow.com/q/47733763
tags question: http://stackoverflow.com/q/47781870
type: Tag
tags question: http://stackoverflow.com/q/47847408
tags question: http://stackoverflow.com/q/47739967
tags question: http://stackoverflow.com/q/47787004
tags question: http://stackoverflow.com/q/47817606
tags question: http://stackoverflow.com/q/47763438
tags question: http://stackoverflow.com/q/47851662
tags question: http://stackoverflow.com/q/47725645

http://stackoverflow.com/comment/82631889
score: 0
comment on: http://stackoverflow.com/q/47833910
type: Comment
type: QuestionComment
has text: Where is the file come from, it is static file or it's a model field?

http://stackoverflow.com/q/47723643
accepted answer: http://stackoverflow.com/a/47723659
type: AnsweredQuestion
has title: How to pass object as paramaters to function?
score: 3
upvote count: 3
tagged with: python
favorite count: 0
has body: I have defination of function: def setup(self, **kwargs): pass And calling this like: params = { "advert_id": adv_id, "enabled": True, "from_hour": 2, "to_hour": 1, "interval": 0, "weekdays": [1] } setup(params) I tried to pass params as object, but it does not work. I know correct way is: setup(advert_id=1,enabled=True,from_hour=3,to_hour=4,interval=0,weekdays=[]) Anyway I don't want to enumerate all parameters and want to pack it to object.
type: Question
tagged with: python-2.7
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/47723659

http://stackoverflow.com/comment/82367428
comment on: http://stackoverflow.com/q/47702536
type: QuestionComment
has text: Aha! If you are sure that the directory structure is *exactly the same*, `os.walk` will recurse in the order that `dirs` returns, so just make sure to add a `dirs.sort()` on every iteration, and the two-iterator approach should work! so `for (root, dirs, files), (troot,tdirs,_) in zip(...)` then use `dirs.sort()` and `tdirs.sort()` and use `troot` when you try to open the target-file.
score: 0
type: Comment

http://stackoverflow.com/q/47768394
has comment: http://stackoverflow.com/comment/82498123
tagged with: multithreading
tagged with: python
has title: Python3 weakref WeakMethod and thread safety
type: AnsweredQuestion
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/82498049
has answer: http://stackoverflow.com/a/47768899
accepted answer: http://stackoverflow.com/a/47768899
type: Question
has body: I am trying to create a simple callback that can be registered to an object from another thread. The initial object that calls the callback is running on its own thread in this case. This is best illustrated through the following example: from pprint import pprint import sys import weakref import threading import time class DummyController(object): def __init__(self): self.name = "fortytwo" def callback(self): print("I am number : " + self.name) class SomeThread(threading.Thread): def __init__(self, listener): threading.Thread.__init__(self) self.listener = listener def run(self): time.sleep(1) dummy = DummyController() self.listener.register_callback(dummy.callback) time.sleep(5) del dummy class Listener(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.runner = weakref.WeakMethod(self.default_callback) self.counter = 20 def default_callback(self): print("Not implemented") def register_callback(self, function): self.runner = weakref.WeakMethod(function) def run(self): while self.counter: try: self.runner()() except Exception as e: pprint(e) self.counter -= 1 time.sleep(1) listen = Listener() some = SomeThread(listen) listen.start() some.start() Now the above code works just fine. But I am concerned about thread-safety here. Reading through weakref docs, it isn't very clear if weakref is really thread safe or not, except for the line: Changed in version 3.2: Added support for thread.lock, threading.Lock, and code objects. I might be simply not reading that right. Do I need to add locking, or is everything actually fine and pretty thread safe? Many thanks

http://stackoverflow.com/q/47714540
downvote count: 0
score: 18
has answer: http://stackoverflow.com/a/47956359
has body: I was wondering how one rotates the x-labels, something in the lines of: theme(axis.text.x = element_text(angle = 90, hjust = 1)) in ggplot? Thank you.
type: Question
tagged with: ggplot2
type: AnsweredQuestion
upvote count: 18
tagged with: python
accepted answer: http://stackoverflow.com/a/47956359
has title: Plotnine rotating labels
favorite count: 0
tagged with: plotnine
answer count: 1

http://stackoverflow.com/a/47852701
type: Answer
answers question: http://stackoverflow.com/q/47852441
score: 1
downvote count: 0
upvote count: 1
has body: A simple approach, preserving the code you already have, would be to use a format specification to pad and right align the output: total = 0 x = range(1, 8) for i in x: total = 'T' * i print("{:&gt;8}".format(total), end='\n\n') It's worth one's time to learn the various transformations that print() and str.format() can perform: &gt; python3 test.py T TT TTT TTTT TTTTT TTTTTT TTTTTTT &gt;

http://stackoverflow.com/q/47705060
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: python
tagged with: google-bigquery
has answer: http://stackoverflow.com/a/47707105
has title: Running Bigquery query uncached using Python API
tagged with: google-cloud-platform
score: 1
has body: Hi I am using BigQuery and with its Python API submitting Queries to get results. I am using the method - bqclient.query("PASS THE QUERY") to execute the query programmatically. I am trying to do a performance test but BigQuery returns cached results. Is there a way I can set cache = False in the Python API while calling the bqclient.query method. Through the BigQuery documentation I have see that we can set useQueryCache property to false, but am not sure where to set it. Current Code job_config = bigquery.QueryJobConfig() job_config.use_query_cache = False query_job = bigquery.query(select_query, job_config = job_config) query represents the query that I want to run. Thank you
answer count: 1

http://stackoverflow.com/q/47764171
type: UnansweredQuestion
tagged with: boto3
has answer: http://stackoverflow.com/a/65876387
has answer: http://stackoverflow.com/a/70502290
has answer: http://stackoverflow.com/a/47765390
tagged with: amazon-s3
score: 2
has comment: http://stackoverflow.com/comment/82491027
has title: boto3 signed url resulting in SignatureDoesNotMatch
has answer: http://stackoverflow.com/a/63704878
has comment: http://stackoverflow.com/comment/82490052
favorite count: 0
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/82490123
has answer: http://stackoverflow.com/a/77002561
has body: My code is successfully uploading documents into the correct bucket. I can login and see the docs in the buckets on AWS S3. When I try to use the generate_signed_url method in boto3 to obtain a URL for these documents that can then be sent to users for accessing the doc, I'm getting a SignatureDoesNotMatch with the message saying "The request signature we calculated does not match the signature you provided. Check your key and signing method." When i save the object (verified that it is working correctly by logging into AWS and downloading the files manually), I use: s3 = boto3.client('s3', region_name='us-east-2', aws_access_key_id='XXXX', aws_secret_access_key='XXXX', config=Config(signature_version='s3v4')) s3.put_object(Bucket=self.bucket_name,Key=path, Body=temp_file.getvalue(),ACL='public-read') Then, when I try to get the URL, I'm using: s3 = boto3.client('s3', region_name='us-east-2', aws_access_key_id='XXXX', aws_secret_access_key='XXXX', config=Config(signature_version='s3v4')) url = s3.generate_presigned_url( 'put_object', Params={ 'Bucket':self.pdffile_storage_bucket_name, 'Key':self.pdffile_url }, ExpiresIn=604799, ) I saw quite a bit of users on the web talking about making sure your AWS access key doesn't include any special characters. I did this, and I still get the same issue.
downvote count: 0
answer count: 5
has comment: http://stackoverflow.com/comment/82490883
tagged with: python

http://stackoverflow.com/a/47742053
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/82444436
has comment: http://stackoverflow.com/comment/82446677
has comment: http://stackoverflow.com/comment/82445539
type: Answer
has body: You are only testing the length of gp after each full pass of going through optgrid and newneighbor; presumably, the length starts below 100 in one such pass, and reaches 111 by the end. If you want to stop as soon as it reaches 100, you need to test the length whenever you add to gp. A break statement can be used to stop a loop.
has comment: http://stackoverflow.com/comment/82447647
answers question: http://stackoverflow.com/q/47742004
downvote count: 0

http://stackoverflow.com/comment/82489064
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47754949
has text: @tripleee so should I be using json.dumps instead of json.loads in my python script?
score: 0

http://stackoverflow.com/a/48751456
accepted answer of: http://stackoverflow.com/q/47777288
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47777288
has body: I was able to experiment with and get it working using below code, fully automated. No user intervention client_id = 1 client_secret = "XXXXXXXXX" redirect_uri = "http://localhost:8080/testing" from mendeley import Mendeley # These values should match the ones supplied when registering your application. mendeley = Mendeley(client_id, redirect_uri=redirect_uri) auth = mendeley.start_implicit_grant_flow() # The user needs to visit this URL, and log in to Mendeley. login_url = auth.get_login_url() import requests res = requests.post(login_url, allow_redirects = False, data = { 'username': 'xxxx@gmail.com', 'password': 'xxxxx' }) auth_response = res.headers['Location'] # After logging in, the user will be redirected to a URL, auth_response. session = auth.authenticate(auth_response) print(session.files.list().items) The last line prints [&lt;mendeley.models.files.File object at 0x1115b5400&gt;] which means the access if working
has comment: http://stackoverflow.com/comment/84507651
has comment: http://stackoverflow.com/comment/84505949
has comment: http://stackoverflow.com/comment/84505982
upvote count: 6
type: Answer
score: 6
has comment: http://stackoverflow.com/comment/84505256

http://stackoverflow.com/comment/82576333
has text: I'm assuming your Models directory has an \__init__.py for the Models package to work. If in that file you import classes from that package's modules (such as Create, Delete, Restore), you can reference them from the package and not the module. As far as examples go, you could look at requests (https://github.com/requests/requests/blob/master/requests/__init__.py#L116). When creating a requests session, one imports requests.Session instead of requests.sessions.Session.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47786316
type: AnswerComment

http://stackoverflow.com/comment/82583743
type: QuestionComment
has text: **Don't add a external function to mainloop**
comment on: http://stackoverflow.com/q/47811125
score: 0
type: Comment

http://stackoverflow.com/comment/82640524
comment on: http://stackoverflow.com/q/47838333
has text: @CoryKramer Actually, `if choice not in {1, 2, 3}` would be optimal.
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47853935
answers question: http://stackoverflow.com/q/47853770
type: Answer
accepted answer of: http://stackoverflow.com/q/47853770
has comment: http://stackoverflow.com/comment/82675965
score: 2
has comment: http://stackoverflow.com/comment/82675775
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has body: You return an int with getbmi() so your res is cast to int so 1.6002 / 75 / 75 = 0.00028448, so the cast produce a 0. But you tell to python that the return type is float so python interpret int as float. float getbmi(float h, float w); float getbmi(float h, float w) { return w / h / h; }

http://stackoverflow.com/a/47753174
has comment: http://stackoverflow.com/comment/82471819
has comment: http://stackoverflow.com/comment/82472031
has body: This portal uses JavaScript to get data from server and put on page. Using DevTool in Chrome/Firefox you can see that javaScript sends POST request with JSON parameters and it gets all data as JSON. If you get it then you have all as dictionary. import requests params = { 'q': 'iot', 'page': '1', 'app': '', 'sort': 'default', 'ignoreSpellSuggestion': 'false', } url = 'https://www.mckinsey.com/services/ContentAPI/SearchAPI.svc/search' for page in range(1, 3): params['page'] = str(page) r = requests.post(url, json=params) data = r.json() print() print("data['data'].keys():\n", data['data'].keys()) print() print(' currentPage:', data['data']['currentPage']) print(' totalPages:', data['data']['totalPages']) print('totalResults:', data['data']['totalResults']) print() print("data['data']['results'][0].keys():\n", data['data']['results'][0].keys()) print() for item in data['data']['results']: print(item['title']) print(item['url']) print('---') Result: data['data'].keys(): dict_keys(['totalResults', 'totalPages', 'currentPage', 'recommendations', 'results']) currentPage: 1 totalPages: 17 totalResults: 166 data['data']['results'][0].keys(): dict_keys(['title', 'subtitle', 'imageurl', 'dek', 'tag', 'mimetype', 'url']) Taking the pulse of enterprise IoT https://www.mckinsey.com/global-themes/internet-of-things/our-insights/taking-the-pulse-of-enterprise-iot --- An executive's guide to the Internet of Things https://www.mckinsey.com/business-functions/digital-mckinsey/our-insights/an-executives-guide-to-the-internet-of-things --- Internet of Things | Internet of Things https://www.mckinsey.com/global-themes/internet-of-things/how-we-help-clients --- Unlocking the potential of the Internet of Things https://www.mckinsey.com/business-functions/digital-mckinsey/our-insights/the-internet-of-things-the-value-of-digitizing-the-physical-world --- Internet of Things https://www.mckinsey.com/global-themes/internet-of-things/our-insights --- Six ways CEOs can promote cybersecurity in t…
downvote count: 0
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/47752535
has comment: http://stackoverflow.com/comment/82472550
has comment: http://stackoverflow.com/comment/82470999
accepted answer of: http://stackoverflow.com/q/47752535
score: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82469905

http://stackoverflow.com/a/47802629
answers question: http://stackoverflow.com/q/47802564
accepted answer of: http://stackoverflow.com/q/47802564
downvote count: 0
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/82566830
has body: Right now you are creating a new array and just printing it each time through the loop. Try something like this: total_array = [] for key, val in DoL.items(): fobId = val["FaceOuterBound"] edgeloop_txt = re.findall(r'\n#'+str(fobId)+r'\D*#(\d+).*;', text) total_array += [int(edgeloop) for edgeloop in edgeloop_txt] print(total_array) This will loop through your items, continually adding to total_array, and print the entire array when the loop is complete.
score: 1
type: AcceptedAnswer

http://stackoverflow.com/q/47734675
accepted answer: http://stackoverflow.com/a/47734725
has body: I have a dataframe with this values: +--------+-------+--------------+-----+ |tag_html|tag_css|tag_javascript|count| +--------+-------+--------------+-----+ | 0.0| 0.0| 0.0| 8655| | 1.0| 0.0| 0.0| 141| | 0.0| 0.0| 1.0| 782| | 1.0| 0.0| 1.0| 107| | 0.0| 1.0| 0.0| 96| | 0.0| 1.0| 1.0| 20| | 1.0| 1.0| 1.0| 46| | 1.0| 1.0| 0.0| 153| +--------+-------+--------------+-----+ I want the rows where "1" is not repeated in the other columns like this +--------+-------+--------------+-----+ |tag_html|tag_css|tag_javascript|count| +--------+-------+--------------+-----+ | 1.0| 0.0| 0.0| 141| | 0.0| 0.0| 1.0| 782| | 0.0| 1.0| 0.0| 96| what I have done is this, using the function where() df['count'].where(((asdf['tag_html'] == 1) | (asdf['tag_css'] == 0) | (asdf['tag_javascript'] == 0)) &amp; ((asdf['tag_html'] == 0) | (asdf['tag_css'] == 1) | (asdf['tag_javascript'] == 0)) &amp; ((asdf['tag_html'] == 0) | (asdf['tag_css'] == 0) | (asdf['tag_javascript'] == 1))) this is the result 0 8655.0 1 141.0 2 782.0 3 NaN 4 96.0 5 NaN 6 46.0 7 NaN Is there a better way to do this in pandas or pyspark?
tagged with: pyspark
tagged with: python
type: AnsweredQuestion
score: 0
has title: How to filter pandas or pyspark dataframe values in columns?
tagged with: pandas
answer count: 1
type: Question
has answer: http://stackoverflow.com/a/47734725

http://stackoverflow.com/comment/82647354
type: AnswerComment
type: Comment
has text: Yes, I was trying in Tutorialspoint, with Python 2.7
comment on: http://stackoverflow.com/a/47841523
score: 0

http://stackoverflow.com/comment/82649712
has text: Yup. I got it fixed though, newbie mistake. I skipped the step of restarting the system after uninstalling before reinstalling it again.
comment on: http://stackoverflow.com/q/47842607
type: Comment
type: QuestionComment
score: 0

py2exe
tags question: http://stackoverflow.com/q/47770859
type: Tag
tag name: py2exe

http://stackoverflow.com/comment/82558461
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47798672
has text: Yes, the new SeleniumLibrary was completely re-implemented with some sort of dynamic api, making it harder (or at least, undocumented) to extend.
score: 0

http://stackoverflow.com/a/47739848
type: Answer
has comment: http://stackoverflow.com/comment/82444877
has comment: http://stackoverflow.com/comment/82451382
score: 0
has body: Asynchronous functions can only be called from other asynchronous functions. You must call _fetch like this: @gen.coroutine def f(): async_http_client = MyAsyncHTTPClient() res_body = yield async_http_client._fetch(url) If you're not doing this in the context of a tornado server, the best way to call a coroutine from your __main__ block is like this: tornado.ioloop.IOLoop.current().run_sync(f)
answers question: http://stackoverflow.com/q/47739236
has comment: http://stackoverflow.com/comment/82447788
has comment: http://stackoverflow.com/comment/82444809
has comment: http://stackoverflow.com/comment/82439830
has comment: http://stackoverflow.com/comment/82448145
has comment: http://stackoverflow.com/comment/82457631

http://stackoverflow.com/q/47843870
upvote count: 0
has comment: http://stackoverflow.com/comment/82656318
answer count: 2
has comment: http://stackoverflow.com/comment/136936698
has answer: http://stackoverflow.com/a/47844046
has comment: http://stackoverflow.com/comment/82651744
type: UnansweredQuestion
has title: Putting try inside for gives IndentationError
tagged with: python
has comment: http://stackoverflow.com/comment/82651746
has body: I wonder why a simple 3 line code is popping this error. I've checked that the indentation is proper. I want to put some statements under try block immediately after the body of for begins. Here's the code: for i in range(1,10): try: print i Sample run: papagolf@Sierra ~/My Files/My Programs % python test.py File "test.py", line 4 ^ IndentationError: unexpected unindent But if remove that try from the code, it works perfectly. I know that except is not mandatory after a try but I tried putting it too. It simply doesn't work. Can someone explain what's going on? I'm using Python 2.7.13 on Linux, in case it matters.
has comment: http://stackoverflow.com/comment/82652148
tagged with: indentation
duplicate of: http://stackoverflow.com/q/10239668
downvote count: 1
score: -1
has answer: http://stackoverflow.com/a/47843930
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/10239668

http://stackoverflow.com/q/47705371
type: Question
has title: Using dictionary to store data (array) in multiple key groups
has comment: http://stackoverflow.com/comment/82370853
has comment: http://stackoverflow.com/comment/82372128
has comment: http://stackoverflow.com/comment/82371884
has comment: http://stackoverflow.com/comment/82372602
linked to: http://stackoverflow.com/q/47103742
tagged with: python
tagged with: dictionary
accepted answer: http://stackoverflow.com/a/47705479
tagged with: defaultdict
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47705479
has body: I am trying to store arrays in multiple key groups to generate group-wise summaries. I thought dict of dicts may be a solution. Based on this answer, I tried to make a dict of dict. Here is the code import numpy from collections import defaultdict s1 = numpy.array([[1L, 'B', 4], [1L, 'A', 3], [1L, 'B', 10], [1L, 'A', 0.0], [2L, 'A', 11], [2L, 'B', 13], [2L, 'B', 1], [2L, 'A', 6]], dtype=object) def make_dict(): return defaultdict(make_dict) d = defaultdict(make_dict) for x in s1: d[x[0]][x[1]] = x[2] So, d[1]['B'] gives 10 while I was expecting [4,10]. Looks like d is picking up the last combination. Is there a way to append all the values that fit a particular key combination? I thought defaultdict should take care of this. Where am I going wrong? Is there any other solution to this? I can easily do it in pandas and I love the library. But I am requiring an non-pandas solution. Update The question was answered (@juanpa.arrivillaga ) but looks like my example data was inadequate. How about if we had the following as data? s1 = numpy.array([ [1L, 'B', 4,3], [1L, 'A', 3,5], [1L, 'B', 10,23], [2L, 'A', 11,1], [2L, 'B', 1,8], [2L, 'A', 6,23] ], dtype=object) We may not be able to use defaultdict(lambda:defaultdict(list)) as the dictionary container. How to extend the solution to include and append 2D-array instead of list. I expect d[1]['A'] should give me [[3,5],[11,1]]
downvote count: 0
answer count: 1
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/82370869
has comment: http://stackoverflow.com/comment/82370914
favorite count: 0

http://stackoverflow.com/q/47830386
type: UnansweredQuestion
score: -1
upvote count: 0
answer count: 2
has body: I used scipy to interpolate some real data. I wished to evaluate fitted spline on some complex data, is there some trick to force scipy to do it? If not, are there some python packages that provide this functionality? import scipy.interpolate as inter spl = inter.InterpolatedUnivariateSpline( x, y ) When trying to evaluate it on complex 1.0j a casting error in _fitpack._spl_ fires up.
tagged with: scipy
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/53446549
type: Question
tagged with: cubic-spline
has title: Evaluating python's UnivariateSpline on complex data
tagged with: complex-numbers
has answer: http://stackoverflow.com/a/47837258
tagged with: python

http://stackoverflow.com/a/47740013
has comment: http://stackoverflow.com/comment/82445422
answers question: http://stackoverflow.com/q/47739197
type: Answer
score: -1
has comment: http://stackoverflow.com/comment/82440380
upvote count: 0
downvote count: 1
has body: To ensure that the buffer is empty, you could add sys.stdout.flush() after your loop completes to make sure it's empty (as sys.stdout is line buffered).

http://stackoverflow.com/comment/82708344
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47780828
has text: Ah, so that's why my cars kept reappearing in position (0,0). As for the UpperCaseNames, I didn't know that since I'm pretty new to python and stackoverflow.
type: Comment

http://stackoverflow.com/a/47779220
has comment: http://stackoverflow.com/comment/82524331
downvote count: 1
has comment: http://stackoverflow.com/comment/82520679
has comment: http://stackoverflow.com/comment/82520317
accepted answer of: http://stackoverflow.com/q/47779104
score: 3
has comment: http://stackoverflow.com/comment/82519753
answers question: http://stackoverflow.com/q/47779104
type: Answer
has body: Regardless of the input, there is a fixed ordering in which you want to fill the orbitals: 1s, 2s, 2p, 3s, 3p, .... Just subtract the size of the orbital from the argument until you reach zero. Something like: def klechkowski(n): orbitals = [("1s", 2), ("2s", 2), ("2p", 6), ("3s", 2), ...] output = [] for orbital, size in orbitals: k = min(size, n) output.append("%s^%d" % (orbital, k)) n -= k if n &lt;= 0: break return " ".join(output)
has comment: http://stackoverflow.com/comment/84373339
has comment: http://stackoverflow.com/comment/82520535
upvote count: 4
has comment: http://stackoverflow.com/comment/82520837
type: AcceptedAnswer

http://stackoverflow.com/comment/82392395
comment on: http://stackoverflow.com/a/47715407
type: Comment
type: AnswerComment
has text: @cryseth I just made an edit. I add the suffix `_train` and `_pred` to make the distinction between the training and the prediction set. By the way, you may find the API of [`sklearn.linear_model.LinearRegression`](http://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LinearRegression.html#sklearn.linear_model.LinearRegression) more convenient.
score: 2

http://stackoverflow.com/q/47745447
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47745581
tagged with: relative-import
has comment: http://stackoverflow.com/comment/82451054
tagged with: python
has body: I'm tired of reading one-off use cases of relative imports so I figured I'd as a question to get an example of how to do a relative import from a directory above and bellow, for both importing module functions and class objects. directory structure: . ├── lib │ ├── __init__.py │ └── bar.py └── src ├── main.py └── srclib ├── __init__.py └── foo.py bar.py def BarFunc(): print("src Bar function") class BarClass(): def __inti__(self): print("src Bar Class") def test(self): print("BarClass working") foo.py def FooFunction(): print("srclib Foo function") class FooClass(): def __init__(self): print("srclib Foo Class") def test(self): print("FooClass working") Question: What is the syntax in python 3 to import for these use cases? main.py # What is the syntax to import in python 3? # I want to be able to call FooFunc() foo.FooFunc() # I want to be able to create a FooClass() object foo_class = foo.FooClass() foo_class.test() # I want to be able to call FooFunc() bar.BarFunc() # I want to be able to create a BarClass() object bar_class = bar.BarClass() bar_class.test()
score: 0
has comment: http://stackoverflow.com/comment/82451013
has title: Python3 relative imports
has comment: http://stackoverflow.com/comment/82464557
answer count: 1
has comment: http://stackoverflow.com/comment/82451040
type: Question
has comment: http://stackoverflow.com/comment/82451035
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/110894450
linked to: http://stackoverflow.com/q/28400690

kivy-language
type: Tag
tags question: http://stackoverflow.com/q/47753083
tags question: http://stackoverflow.com/q/47776914
tags question: http://stackoverflow.com/q/47809443
tags question: http://stackoverflow.com/q/47726858
tags question: http://stackoverflow.com/q/47755980
tags question: http://stackoverflow.com/q/47721433
tag name: kivy-language
tags question: http://stackoverflow.com/q/47714154
tags question: http://stackoverflow.com/q/47821478
tags question: http://stackoverflow.com/q/47763066

http://stackoverflow.com/comment/82408931
comment on: http://stackoverflow.com/q/47723790
type: Comment
has text: @furas I just added the sql from postgresql that created the table. The "dot_number" looks like it was created.
type: QuestionComment
score: 0

http://stackoverflow.com/a/47738709
downvote count: 0
has body: You need to cycle through EVERY pygame event and check if the event is a quit. while not excape: for event in pygame.event.get(): print(event) if event.type == pygame.QUIT: pygame.quit() excape = True
upvote count: 1
has comment: http://stackoverflow.com/comment/82437744
score: 1
type: Answer
answers question: http://stackoverflow.com/q/47738631
accepted answer of: http://stackoverflow.com/q/47738631
type: AcceptedAnswer

http://stackoverflow.com/a/47784001
type: Answer
has comment: http://stackoverflow.com/comment/82529539
has comment: http://stackoverflow.com/comment/82529452
has body: In your template the named URLs your removed are being referenced. The template tag url performs a reverse on the URL and is informing you (correctly) that it can't be found. Where they are referenced in the templates they will need to be removed or commented out with {# &lt;content to be commented out&gt; #}. Commenting out the HTML will not be sufficient as it will still get processed by the template engine. Edit: to clarify where this needs to occur is every template file that is used not the removed templates.
answers question: http://stackoverflow.com/q/47783812
has comment: http://stackoverflow.com/comment/82529716
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/q/47802937
score: 0
tagged with: sql
has comment: http://stackoverflow.com/comment/82567745
answer count: 1
type: Question
has answer: http://stackoverflow.com/a/47804306
has comment: http://stackoverflow.com/comment/82567466
has comment: http://stackoverflow.com/comment/82567487
has title: How to migrate similar data between two different database structures using python with sql alchemy?
type: UnansweredQuestion
tagged with: database-migration
has body: I have been given a task to migrate data from SQL SERVER to Oracle database. The structure of those two databases is diferent and each table has at least 20 columns and there are at least 500 tables to migrate. I need your recomendation to choose good tools for this task. My initial choice for this task is sqlalchemy. There structure of databases is already there and is different. I can't edit tables. Lets see some simplified examples. Lets say that I have a tables Person and PersonAdress in SQL Server. It has fields like name, name2, surname and keeps person_address_id as foreign key, birth_date. In Oracle database I have a model PERSON_DATA and PERSON_ADDRES where I have fields like NAME, NAME2, SUERNAME, DATE_OF_BIRTH. The tablePERSON_ADRESSkeeps thePERSON_DATA_IDasforeign key`. So there are two problems: 1)Name of fieelds can be different(birth_date in SQL Server and DATE_OF_BIRTH in ORACLE) but represents the same concept. 2)Data that represent the same concept may be in different tables(person_address_id is a foreign key in table Person in SQL_SERVER where PERSON_ADRESS keeps the PERSON_DATA_ID as `foreign key in Oracle). I though about using from automap_base from sqlalchemy.ext.automap to query models. But i dont know it it is the best idea. This is my pseudo code snippet. Maybe It would help to show what I have tried to do so far.. Please note that this is more pseudo-code. from sqlalchemy import create_engine, MetaData from sqlalchemy.ext.automap import automap_base class PersonModel: # DO i need this model? It suppose to represent Person table in # SQL SERVER def __init__(self, name, name2, birth_date, ...): self.name = name self.name2 = name2 ... class PERSON_DATAModel: # Do I need this model? It supose to represent table in Oracle def __init__(self, NAME, NAME2, DATE_OF_BIRTH, ...): self.NAME = NAME self.NAME2 = NAME2 metadata = MetaData() sql_server_engine = create_engine('..') metadata.reflect(sql_server_engine) BaseSQLSERVER= automap_base(metadata=me…
tagged with: database
tagged with: python
tagged with: sqlalchemy

http://stackoverflow.com/comment/82642091
type: AnswerComment
score: 1
type: Comment
comment on: http://stackoverflow.com/a/47833358
has text: 1. The question is how to... "wait until all elements of a page has loaded?" Your answer is Yes and you provided the code to check for ready state == complete. 2. Use Selenium. You don't need documentation to know that this is the case. Write a script that clicks a button and then clicks a button on the next page with no waits and no implicit waits. It will fail because the following element doesn't exist... that's because Selenium doesn't wait. If you want something specific, read this https://github.com/SeleniumHQ/selenium/issues/2626.

http://stackoverflow.com/comment/82525528
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47778165
has text: Haters gonna hate.
type: Comment

http://stackoverflow.com/comment/82529474
type: Comment
score: 0
type: AnswerComment
has text: this wont be binary if a single element occurs more than once in a row
comment on: http://stackoverflow.com/a/47784018

http://stackoverflow.com/comment/82373416
has text: _"'raw_input()' and 'input()' apparently handle things differently. "_ - Well in Python 2 they are. In Python 3, `raw_input` was renamed `input` and the old `input` function was removed.
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47706622

http://stackoverflow.com/comment/82405124
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47722201
has text: You need to show your current code here. Preferably a minimised example that focuses exactly on the problem.
type: QuestionComment

http://stackoverflow.com/q/47725838
tagged with: numpy
has title: Vectorising a for loop where logic spans rows
possible better answer: http://stackoverflow.com/a/47725933
tagged with: back-testing
has comment: http://stackoverflow.com/comment/82413828
tagged with: python
has answer: http://stackoverflow.com/a/47725933
has comment: http://stackoverflow.com/comment/82413833
has comment: http://stackoverflow.com/comment/82412824
type: AnsweredQuestion
score: 3
answer count: 2
accepted answer: http://stackoverflow.com/a/47725888
tagged with: pandas
upvote count: 3
has answer: http://stackoverflow.com/a/47725888
downvote count: 0
has body: The table below shows an example of a strategy where a signal is generated in row 2 and then an opposite signal is generated in row 5. row open_signal close_signal live 1 0 0 0 2 1 0 1 3 0 0 1 4 0 0 1 5 0 1 0 6 0 0 0 I want to optimise the calculation of the live column. Is there a way to vectorise this problem in either Pandas or Numpy for improved performance, generating the same result as the for loop example below? import pandas as pd from datetime import datetime example = {'date': [str(datetime(2017,1,1)), str(datetime(2017,1,2)),str(datetime(2017,1,3)),str(datetime(2017,1,4)),str(datetime(2017,1,5)),str(datetime(2017,1,6)), str(datetime(2017,1,7)), str(datetime(2017,1,8)),str(datetime(2017,1,9)), str(datetime(2017,1,10)),str(datetime(2017,1,11)), str(datetime(2017,1,12)), str(datetime(2017,1,13)),str(datetime(2017,1,14))], 'open': [142.11, 142.87, 141.87, 142.11, 142.00, 142.41, 142.50, 142.75, 140.87, 141.25, 141.10, 141.15, 142.55, 142.75], 'close': [142.87, 141.87, 142.11, 142.00, 142.41, 142.50, 142.75, 140.87, 141.25, 141.10, 141.15, 142.55, 142.75, 142.11], 'open_signal': [False, False, False, False, False, True, False, False, False, False, False, False, False, False], 'close_signal':[False, False, False, False, False, False, False, False, False, True, False, False, False, False] } data = pd.DataFrame(example) in_trade = False for i in data.iterrows(): if i[1].open_signal: in_trade = True if i[1].close_signal: in_trade = False data.loc[i[0],'in_trade'] = in_trade
tagged with: algorithmic-trading
favorite count: 0
type: Question

http://stackoverflow.com/comment/124229262
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/57805512
has text: If you use pyad a lot, a hook can be used instead: `>@app.before_request`, `>def hook():`, `> pythoncom.CoInitialize()`
type: Comment

http://stackoverflow.com/a/47743823
accepted answer of: http://stackoverflow.com/q/47743737
score: 0
type: Answer
answers question: http://stackoverflow.com/q/47743737
has comment: http://stackoverflow.com/comment/82448438
has body: There is only one element in data; the key symbols. It is data["symbols"] you should be iterating over. And you don't need indice at all. for symbol in data["symbols"]: print(symbol["optionType"]) # etc
type: AcceptedAnswer

http://stackoverflow.com/a/47771184
has comment: http://stackoverflow.com/comment/82510723
has comment: http://stackoverflow.com/comment/82543004
accepted answer of: http://stackoverflow.com/q/47759986
type: Answer
has comment: http://stackoverflow.com/comment/82510471
has comment: http://stackoverflow.com/comment/82510645
score: 0
has body: You can indeed use Cloud SQL from App Engine without having to run your own MySQL instance. To do so, you can have a look at the information in the official documentation. Make sure that you are configuring your environment variables correctly (you can do so directly from the app.yaml configuration file) and importing the MySQLdb library, as explained in the corresponding section in that same page. There you will find some sample code and also additional information regarding how to test your application both in the development and production environments.
has comment: http://stackoverflow.com/comment/82518710
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47759986

http://stackoverflow.com/a/67177997
answers question: http://stackoverflow.com/q/47812526
has body: You can also try using first() function. It returns the first row from the dataframe, and you can access values of respective columns using indices. df.groupBy().sum().first()[0] In your case, the result is a dataframe with single row and column, so above snippet works.
type: Answer
score: 0

http://stackoverflow.com/comment/82949852
score: 0
type: Comment
has text: Possible duplicate of [Writing a list to a file with Python](https://stackoverflow.com/questions/899103/writing-a-list-to-a-file-with-python)
type: QuestionComment
comment on: http://stackoverflow.com/q/47845258

http://stackoverflow.com/comment/82878164
comment on: http://stackoverflow.com/q/47701162
type: Comment
type: QuestionComment
score: 0
has text: I have edited the code

http://stackoverflow.com/q/47740072
downvote count: 0
answer count: 1
favorite count: 0
type: Question
has body: I have a Python script that runs 24hrs a day. A module from this script is using variables values that I wish to change from time to time, without having to stop the script, edit the module file, then launch the script again (I need to avoid interruptions as much as I can). I thought about storing the variables in a separate file, and the module would, when needed, fetch the new values from the file and use them. Pickle seemed a solution but is not human readable and therefore not easily changeable. Maybe a JSON file, or another .py file I import over again ? Another advantage of doing so, for me, is that in case of interruption (eg. server restart), I can resume the script with the latest variable values if I load them from a separate file. Is there a recommended way of doing such things ? Something along the lines : # variables file: variable1 = 10 variable2 = 25 # main file: while True: import variables print('Sum:', str(variable1+variable2)) time.sleep(60)
has answer: http://stackoverflow.com/a/47740280
tagged with: python
linked to: http://stackoverflow.com/q/14359557
has title: Python variable value from separate file?
accepted answer: http://stackoverflow.com/a/47740280
score: 2
upvote count: 2
type: AnsweredQuestion

http://stackoverflow.com/comment/82664382
comment on: http://stackoverflow.com/q/47849923
has text: You probable run it as python-3.x. Usually two programs are installed `python` which is Python-2.x, and `python3`, which is Python-3.x
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/47850270
favorite count: 0
has answer: http://stackoverflow.com/a/47850303
possible better answer: http://stackoverflow.com/a/47850303
type: Question
has title: Sum of first elements in nested lists
has answer: http://stackoverflow.com/a/47850309
accepted answer: http://stackoverflow.com/a/47850309
tagged with: python
has body: I am trying to get the first element in a nested list and sum up the values. eg. nested_list = [[1, 'a'], [2, 'b'], [3, 'c'], [4, 'd']] print sum(i[0] for i in nested_list) However, there are times in which the first element in the lists None instead nested_list = [[1, 'a'], [None, 'b'], [3, 'c'], [4, 'd']] new = [] for nest in nested_list: if not nest[0]: pass else: new.append(nest[0]) print sum(nest) Wondering what is the better way that I can code this?
type: AnsweredQuestion
tagged with: list
tagged with: numbers
answer count: 2
score: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/138512679
type: AnswerComment
has text: This worked for me. I see a few ways to come up with tokens. I will try each of those until I can find one that is sufficiently long-lived. I am not on Business+/Enterprise.
comment on: http://stackoverflow.com/a/53506688
score: 0
type: Comment

http://stackoverflow.com/a/47755411
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/47754759
has body: An other fast way : np.where(a1==0,r,a1+a2).
type: Answer

http://stackoverflow.com/comment/82579071
score: 1
type: Comment
comment on: http://stackoverflow.com/q/47808926
type: QuestionComment
has text: Check out this question https://stackoverflow.com/questions/29214888/typeerror-cannot-create-a-consistent-method-resolution-order-mro

http://stackoverflow.com/a/47820128
answers question: http://stackoverflow.com/q/47820127
type: Answer
score: 1
downvote count: 0
has body: Here are the full instructions, adapted for Windows. Find the sagetex.sty file of your sage installation, probably it is in C:\Program Files\SageMath 8.0\runtime\opt\sagemath-8.0\local\share\texmf\tex\latex\sagetex\sagetex.sty. (On for example Arch Linux, you have to install both the sage and sagetex packages, then the file will be in /usr/share/texmf/tex/latex/sagetex/sagetex.sty) Find out which sagetex.sty your computer is finding by running the TeX command kpsewhich sagetex.sty anywhere on your command prompt. Probably this is your MikTeX (or TeX Live or whatever distribution you are using) directory which contains an old sagetex.sty which is causing the version mismatch. If you get a popup asking you to install something, then don't install! I'm not completely sure but I think you can just copy the new package file of your sage installation to your distribution's sagetex directory (for MikTeX something like C:\Users\s156757\AppData\Roaming\MiKTeX\2.9\tex\latex\sagetex) overwriting the old sagetex.sty that is there. If not, make sure to remove the old one and use your new file, for example by placing it next to your tex file. Probably you need to install the package fancyvrb which sagetex needs manually using for example the MikTeX package manager. Every time you add new Sage to your LaTeX: run your LaTeX file, start the Sage shell and go to the directory where the just made myfile.sagetex.sage was placed, which is the same directory as where all your auxiliary files are: cd "C:/path/to/auxiliary/files" and sage myfile.sagetex.sage, then run LaTeX again. Both the .scmd and .sout files are needed for for example other people to compile your LaTeX. Use SageTeX with for example $\sage{1+1}$ or with the sageblock environment.
upvote count: 1

http://stackoverflow.com/comment/82422544
score: 0
has text: i'm using windows. i edited the question with more details and a screenshot of the problem. please check it.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47730259

http://stackoverflow.com/q/47752354
has answer: http://stackoverflow.com/a/47765554
answer count: 4
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82465153
upvote count: 2
accepted answer: http://stackoverflow.com/a/47767665
downvote count: 2
has answer: http://stackoverflow.com/a/47767665
has answer: http://stackoverflow.com/a/63065220
has title: How to print a 2D list in one line?
has answer: http://stackoverflow.com/a/70788348
type: AnsweredQuestion
score: 0
tagged with: multidimensional-array
has body: I'm trying to print a 2-dimensional array on a single output line (without \n). The closest I've got is to this output [28098, 24390, 15876] [8352, 12876, 12644] using print(*result) I'd like to remove the commas (substitute them with spaces) and remove the brackets.
possible better answer: http://stackoverflow.com/a/47765554
tagged with: python
has comment: http://stackoverflow.com/comment/82465014

http://stackoverflow.com/q/47788587
score: 0
has body: I have a huge csv to parse by chyunk and write to multiple files I am using pandas read_csv function to get chunks by chunks. It was working fine but slower than the performance we need. So i decided to do this parsing in threads pool = ThreadPoolExecutor(2) with ThreadPoolExecutor(max_workers=2) as executor: futures = executor.map(process, [df for df in pd.read_csv( downloaded_file, chunksize=chunksize, compression='gzip', low_memory=False, skipinitialspace=True, encoding='utf-8')], file_index) for future in concurrent.futures.as_costmpleted(futures): pass Here is my function that has a responsibility to parse and write to csv def process(df, file_index): """ Process the csv chunk in a separate thread :param df: :param file_index: :param chunk_index: """ chunk_index = random.randint(1, 200) print "start processing chunk" # some heaving processing... handle = open(outfile_name) df.to_csv(outfile_name, index=False, compression='gzip', sep='\t', quoting=1, encoding='utf-8') handle.close() del df print "end processing chunk" return True I never see my print debug lines and the cpu and memory reach to 100% and my script get killed. It looks like the read_csv it self is always yielding and the executor.map is still waiting for the first argument. Thanks
tagged with: pandas
has answer: http://stackoverflow.com/a/47799685
tagged with: python
has comment: http://stackoverflow.com/comment/82538297
type: UnansweredQuestion
tagged with: multithreading
answer count: 1
has title: Multiprocessing with pandas read csv and threadpool executor
has comment: http://stackoverflow.com/comment/82539259
has comment: http://stackoverflow.com/comment/82539229
type: Question

http://stackoverflow.com/comment/82462789
comment on: http://stackoverflow.com/q/47748081
type: QuestionComment
has text: or maybe you need [Populate nested items with itemLoader](https://stackoverflow.com/questions/41333735/scrapy-populate-nested-items-with-itemloader)
score: 0
type: Comment

http://stackoverflow.com/comment/82511562
type: QuestionComment
has text: Is your desired output for n=2 correct? Do you base your output only on the measured values or on the already "corrected" previous values?
type: Comment
comment on: http://stackoverflow.com/q/47775108
score: 0

http://stackoverflow.com/comment/82360530
has text: @MattFletcher Note that you are doing `self.translations.values()`, whereas my code would correspond to `self.translations[0].values()`, i.e. get the `values` from the dicts _inside_ the list, not the list itself. Of course, in your case you should probably use a loop like `for d in self.translations: key, *lang = d.values()`
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47700040
score: 0

http://stackoverflow.com/q/47800065
score: 3
upvote count: 3
answer count: 1
downvote count: 0
tagged with: python-requests
accepted answer: http://stackoverflow.com/a/47800158
has comment: http://stackoverflow.com/comment/82563155
has body: I'm trying to write a function that does a GET request to download a file from server A, then immediately POST the file to server B. I'm trying to look for a way to do it by streaming the output of the GET request into the input of the POST request. The following article discusses doing this in nodeJS. How would I do this with Python Requests?
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47800158
has title: How to GET file and stream it into a POST request with Python Requests?
has comment: http://stackoverflow.com/comment/82561811
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/47736022
has answer: http://stackoverflow.com/a/54866762
possible better answer: http://stackoverflow.com/a/47736070
has body: I've seen similar questions but mine is more direct and abstract. I have a dataframe with "n" rows, being "n" a small number.We can assume the index is just the row number. I would like to convert it to just one row. So for example if I have A,B,C,D,E --------- 1,2,3,4,5 6,7,8,9,10 11,12,13,14,5 I want as a result a dataframe with a single row: A_1,B_1,C_1,D_1,E_1,A_2,B_2_,C_2,D_2,E_2,A_3,B_3,C_3,D_3,E_3 -------------------------- 1,2,3,4,5,6,7,8,9,10,11,12,13,14,5 What would be the most idiomatic way to do this in Pandas?
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47736070
has title: Convert a Pandas DataFrame into a single row DataFrame
tagged with: python
has answer: http://stackoverflow.com/a/47736061
answer count: 4
type: AnsweredQuestion
downvote count: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/47736119
accepted answer: http://stackoverflow.com/a/47736119
upvote count: 7
score: 7

http://stackoverflow.com/comment/82607504
score: 0
has text: Does the line `'http://wikipedia.org', 'http://wordpress.com', ',` occur the same way in your code? There is a quoting error there
comment on: http://stackoverflow.com/q/47822369
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47847285
type: AnsweredQuestion
upvote count: 3
has answer: http://stackoverflow.com/a/47847519
score: 3
tagged with: apache-spark-sql
has answer: http://stackoverflow.com/a/54055712
possible better answer: http://stackoverflow.com/a/54055712
tagged with: pyspark
has title: Truncate a string with pyspark
tagged with: python
has comment: http://stackoverflow.com/comment/82659179
accepted answer: http://stackoverflow.com/a/47847519
answer count: 2
tagged with: apache-spark
downvote count: 0
has body: I am currently working on PySpark with Databricks and I was looking for a way to truncate a string just like the excel right function does. For example, I would like to change for an ID column in a DataFrame 8841673_3 into 8841673. Does anybody knows how I should proceed?
favorite count: 0
type: Question

http://stackoverflow.com/a/47855497
downvote count: 0
has body: I think you make the problem harder than it is. We can construct a None-safe function: def nonesafe_loads(obj): if obj is not None: return json.loads(obj) This will return the json.loads(obj) in case obj is not None, and otherwise it will return None. Or we can construct a "best effort" JSON loads, that aims to json.loads the string, or in case that fails, returns the obj itself: def besteffort_loads(obj): try: return json.loads(obj) except (TypeError, ValueError): return obj Now we can just use our nonesafe_loads in the program: data1 = '{"foo":"bar"}' data2 = None sensor = {'header':'Info', 'data1': nonesafe_loads(data1), 'data2': nonesafe_loads(data2)} output = json.dumps(sensor)
score: 7
upvote count: 7
has comment: http://stackoverflow.com/comment/82675414
accepted answer of: http://stackoverflow.com/q/47855469
has comment: http://stackoverflow.com/comment/128781679
answers question: http://stackoverflow.com/q/47855469
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82675843
type: Answer

http://stackoverflow.com/a/47764366
has comment: http://stackoverflow.com/comment/82490344
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47764230
has body: You can use V=np.einsum("ni,nj-&gt;n",A,A)
type: Answer
has comment: http://stackoverflow.com/comment/82490273
upvote count: 2
score: 2
accepted answer of: http://stackoverflow.com/q/47764230
downvote count: 0

http://stackoverflow.com/a/47780072
has body: **strong text**elif x.upper()=="Y": k=input("Enter the 1st letter of the name (upper-Case):") y=open("Names.txt","r") found = False for i in y.readlines(): if k.upper() in i: print (i[:-1]) found = True if not found: print("no results")
type: Answer
answers question: http://stackoverflow.com/q/47780016
upvote count: 3
downvote count: 0
score: 3

http://stackoverflow.com/comment/82393813
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47716682
type: Comment
has text: @ChrisM I did that. Check my edit, beforehand it was just a single block of text. How else do you think it should be broken down? I could change to bullet points if that's better? But certainly I couldn't follow it with it all packed into a single paragraph.

http://stackoverflow.com/comment/82600900
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47738922
score: 0
has text: what version of python are you using?

http://stackoverflow.com/comment/82389171
score: 0
comment on: http://stackoverflow.com/a/47714521
has text: Thanks , i did think that other methods,like list comprehension might be the better idea here , but i wanted to learn/try out more with lambda/map/filter. Thats why i chose to try it this way. Again thank all your help though.
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47786886
tagged with: beautifulsoup
has comment: http://stackoverflow.com/comment/82534898
has answer: http://stackoverflow.com/a/47816840
has answer: http://stackoverflow.com/a/47794428
type: UnansweredQuestion
has body: I'm using BeautifulSoup to pull the elements of an HTML table into a python dict. The problem I'm having is, when I create the dict, the first record from the table is repeatedly loaded into the the dict. Printing the variable rows shows the expected number of different records returned in the response, but only the first record is printed when print(d) is called. import requests from bs4 import BeautifulSoup as bs url = 'http://host.com/user_activity?page=3' r = requests.get(url) #print(r.text) soup = bs(r.text, 'lxml') table = soup.find_all('table')[0] rows = table.find_all('td') #records = soup.find_all('td') #print(table.prettify()) ct=0 for record in rows : if ct &lt; 20: keys = [th.get_text(strip=True)for th in table.find_all('th')] values = [td.get_text(strip=True) for td in rows] d = dict(zip(keys, values)) print(d) ct+=1
tagged with: python
has comment: http://stackoverflow.com/comment/82535743
has comment: http://stackoverflow.com/comment/82535582
has comment: http://stackoverflow.com/comment/82545413
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/82561930
has title: Python Web Scraping Script not iterating over HTML table properly
has comment: http://stackoverflow.com/comment/82545545
type: Question

http://stackoverflow.com/comment/122332753
comment on: http://stackoverflow.com/a/47851262
score: 0
type: Comment
type: AnswerComment
has text: Understand this is a old post, but this is exactly what I am trying to do and it works! BUT how do I stop web.run_app once it returns the result? Thanks!

http://stackoverflow.com/a/47844033
has comment: http://stackoverflow.com/comment/82652921
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47843478
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/82652971
type: Answer
accepted answer of: http://stackoverflow.com/q/47843478
has comment: http://stackoverflow.com/comment/82652832
has comment: http://stackoverflow.com/comment/82653326
has body: You are closing the database connection before Qt's main loop is started, move all Postgres related stuff into the thread. class ThreadClass(QtCore.QThread): updateTable = pyqtSignal(dict) def __init__(self, parent=None): super().__init__() def run(self): conn = psycopg2.connect("dbname=XXX user=YYYY password=ZZZ host=localhost port=5555") cur = conn.cursor() cur.execute("select * from events") orderbook = cur.fetchall() for rowNum, rowData in enumerate(orderbook): self.updateTable.emit({"insertRow": 0}) for colNum, data in enumerate(rowData): self.updateTable.emit({"setItem": [rowNum, colNum, data]}) cur.close() conn.close()
score: 1

pygame
tags question: http://stackoverflow.com/q/47851953
tags question: http://stackoverflow.com/q/47803512
tags question: http://stackoverflow.com/q/47735269
tags question: http://stackoverflow.com/q/47771351
tags question: http://stackoverflow.com/q/47802465
tags question: http://stackoverflow.com/q/47761364
tag name: pygame
tags question: http://stackoverflow.com/q/47734648
tags question: http://stackoverflow.com/q/47746583
tags question: http://stackoverflow.com/q/47730434
tags question: http://stackoverflow.com/q/47707559
tags question: http://stackoverflow.com/q/47847649
tags question: http://stackoverflow.com/q/47764623
tags question: http://stackoverflow.com/q/47732604
tags question: http://stackoverflow.com/q/47735944
tags question: http://stackoverflow.com/q/47830982
tags question: http://stackoverflow.com/q/47707228
tags question: http://stackoverflow.com/q/47758248
tags question: http://stackoverflow.com/q/47707784
tags question: http://stackoverflow.com/q/47771578
tags question: http://stackoverflow.com/q/47855834
tags question: http://stackoverflow.com/q/47721597
tags question: http://stackoverflow.com/q/47751594
tags question: http://stackoverflow.com/q/47740814
tags question: http://stackoverflow.com/q/47733600
tags question: http://stackoverflow.com/q/47829248
tags question: http://stackoverflow.com/q/47727344
tags question: http://stackoverflow.com/q/47730829
tags question: http://stackoverflow.com/q/47738631
tags question: http://stackoverflow.com/q/47838446
tags question: http://stackoverflow.com/q/47754838
tags question: http://stackoverflow.com/q/47717043
tags question: http://stackoverflow.com/q/47855725
tags question: http://stackoverflow.com/q/47848852
tags question: http://stackoverflow.com/q/47702271
tags question: http://stackoverflow.com/q/47733992
tags question: http://stackoverflow.com/q/47726023
tags question: http://stackoverflow.com/q/47735159
tags question: http://stackoverflow.com/q/47775391
tags question: http://stackoverflow.com/q/47780166
tags question: http://stackoverflow.com/q/47822233
tags question: http://stackoverflow.com/q/47780828
tags question: http://stackoverflow.com/q/47822353
tags question: http://stackoverflow.com/q/47847396
tags question: http://stackoverflow.com/q/47733596
tags question: http://stackoverflow.com/q/47758376
tags question: http://stackoverflow.com/q/47800180
tags question: http://stackoverflow.com/q/47773461
tags question: http://stackoverflow.com/q/47735902
tags question: http://stackoverflow.com/q/47797253
tags question: http://stackoverflow.com/q/47744596
type: Tag

http://stackoverflow.com/q/47766577
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82495785
has answer: http://stackoverflow.com/a/47766604
has comment: http://stackoverflow.com/comment/82495005
tagged with: python
has comment: http://stackoverflow.com/comment/82494351
has comment: http://stackoverflow.com/comment/82494745
has answer: http://stackoverflow.com/a/47769232
has title: Convert Unicode to Dictionary
has comment: http://stackoverflow.com/comment/82497382
answer count: 2
has comment: http://stackoverflow.com/comment/82494330
has comment: http://stackoverflow.com/comment/82494266
has body: Version: Python 2.7.10. I have the following: r = requests.post(url = API_ENDPOINT, headers = headers, data = data) print(r.text) print(type(r.text)) print(r.text[2]) The output {"type":"quote","symbol":"SPY","bid":266.52,"bidsz":5,"bidexch":"P","biddate":"1513040398000","ask":266.55,"asksz":100,"askexch":"P","askdate":"1513040399000"} {"type":"trade","symbol":"SPY","exch":"P","price":"266.31","size":"0","cvol":"83077533","date":"1513040400000","last":"266.31"} {"type":"summary","symbol":"SPY","open":"265.58","high":"266.38","low":"265.4793","prevClose":"265.51","close":"266.31"} &lt;type 'unicode'&gt; b I would like to get the output "SPY". I added the following: new = simplejson.loads(r.text) print(new) Now, I get the following: Traceback (most recent call last): File "example.py", line 63, in &lt;module&gt; new = simplejson.loads(r.text) File "/Library/Python/2.7/site-packages/simplejson/__init__.py", line 518, in loads return _default_decoder.decode(s) File "/Library/Python/2.7/site-packages/simplejson/decoder.py", line 373, in decode raise JSONDecodeError("Extra data", s, end, len(s)) simplejson.errors.JSONDecodeError: Extra data: line 1 column 160 - line 1 column 407 (char 159 - 406) I changed: r = requests.post(url = API_ENDPOINT, headers = headers, data = data).json() Now, I get: Traceback (most recent call last): File "example.py", line 51, in &lt;module&gt; r = requests.post(url = API_ENDPOINT, headers = headers, data = data).json() File "/Library/Python/2.7/site-packages/requests/models.py", line 884, in json self.content.decode(encoding), **kwargs File "/Library/Python/2.7/site-packages/simplejson/__init__.py", line 518, in loads return _default_decoder.decode(s) File "/Library/Python/2.7/site-packages/simplejson/decoder.py", line 373, in decode raise JSONDecodeError("Extra data", s, end, len(s)) simplejson.errors.JSONDecodeError: Extra data: line 1 column 160 - line 1 column 407 (char 159 - 406) I added: new = json.dumps(r.text) print(new) print(type(ne…
type: UnansweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/82495070
downvote count: 0
upvote count: 1
tagged with: unicode

http://stackoverflow.com/comment/82428146
type: Comment
has text: I did think about this, but the year changes through out the data. I'm trying to have just the years in this column, but in the order of the years first appearance, which i why I have `currentYear`
type: QuestionComment
comment on: http://stackoverflow.com/q/47733663
score: 0

http://stackoverflow.com/comment/82436007
score: 0
has text: @Liberty Verleysen `If` should be `if`.
comment on: http://stackoverflow.com/a/47737620
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/107850968
type: Comment
type: AnswerComment
score: 0
has text: @PhilMacKay _Still, "conda" takes an eternity_ To download, or to install? Or are you referring to the time it takes to resolve dependencies? According to the Anaconda website, Miniconda is 50 MB (the installer, at least).
comment on: http://stackoverflow.com/a/50253635

http://stackoverflow.com/q/47788080
tagged with: wagtail
answer count: 2
has title: How can I create Page and set its StreamField value programmatically?
downvote count: 0
tagged with: django
has body: I want to create a BlogPage programmatically in wagtail with setting its StreamField value. I can set heading field. But I'm getting AttributeError: 'unicode' object has no attribute 'source' when I try to set the paragraph field. I want to set an image too. This is my BlogPage model. models.py class BlogPage(Page): template = 'wagtail/test_page.html' author = models.CharField(max_length=255) date = models.DateField("Post date") body = StreamField([ ('heading', blocks.CharBlock(classname="full title")), ('paragraph', blocks.RichTextBlock()), ('image', ImageChooserBlock()), ]) content_panels = Page.content_panels + [ FieldPanel('author'), FieldPanel('date'), StreamFieldPanel('body'), ] this my code to create page by running this script. create_page.py new_image_page = BlogPage( title='Blog', slug='michael', author='michael', date='2017-12-13', body=[('heading','New Heading'), ('heading','New Heading 23232'), ('paragraph','My Paragraph')] ) directory_page = Page.objects.get(slug='home') directory_page.add_child(instance=new_image_page) revision = new_image_page.save_revision() revision.publish() new_image_page.save()
has answer: http://stackoverflow.com/a/47788896
favorite count: 0
upvote count: 8
type: Question
accepted answer: http://stackoverflow.com/a/47795891
possible better answer: http://stackoverflow.com/a/47788896
has answer: http://stackoverflow.com/a/47795891
tagged with: python
score: 8
type: AnsweredQuestion

http://stackoverflow.com/comment/82609397
type: Comment
type: QuestionComment
has text: Yeah, because the script runs inside the AWC EC2 instance (I have uploaded it into it and started it also inside the instance). I mean that after closing my terminal and starting the session again, the output txt-file was empty..
comment on: http://stackoverflow.com/q/47823240
score: 0

http://stackoverflow.com/comment/82423927
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47731543
has text: @furas where would i use the ontimer function? i'm trying not to call any turtle functions outisde of the frame() function (if possible) and the bullets themselves are not actually turtles.
type: Comment

http://stackoverflow.com/q/47705691
type: Question
tagged with: multithreading
has title: Is Celery needed for asynchronous file writing functionality in Django?
tagged with: django
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/47711672
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47711672
tagged with: http://stackoverflow.com/tag/csv
score: 1
answer count: 1
has body: I'm planning to add some functionality to my Django app that will write a row of data to a csv file when certain views are called: session_dict = collectUserDataFromRequest(request) #....collect parameters from request if os.path.isfile(filename): with open(filename, 'a') as csv_file: a = csv.DictWriter(csv_file,session_dict.keys()) a.writerow(session_dict) csv_file.close() else: with open(filename, 'w') as csv_file: w = csv.DictWriter(csv_file,session_dict.keys()) w.writeheader() w.writerow(session_dict) csv_file.close() # then proceed to render the html A problem I am facing is dealing with potential race conditions when multiple users are accessing my app at the same time. While the data can be added to the csv file in any order, I don't want some user's to wait longer for a view to load while waiting for a lock to be released on the csv file. As such, I think an Asynchronous queue of string data to be written to the file that can run in the background sounds like a good workaround. I have been told that Celery is a good framework for adding asynchronous processes to my Django app. But looking through several tutorials, I am seeing that additional frameworks such as Redis are usually required. I worry that this may be overkill for what I aim to accomplish. Will I get away with using a standard multiprocessing approach, such as explained here or are there other drawbacks to using multi-threading in a Django production environment.
downvote count: 0
tagged with: asynchronous
linked to: http://stackoverflow.com/q/26596714
favorite count: 0

server
tags question: http://stackoverflow.com/q/47739105
tags question: http://stackoverflow.com/q/47754487
tags question: http://stackoverflow.com/q/47736881
type: Tag
tags question: http://stackoverflow.com/q/47740521
tags question: http://stackoverflow.com/q/47786463
tags question: http://stackoverflow.com/q/47811514
tags question: http://stackoverflow.com/q/47812420
tags question: http://stackoverflow.com/q/47733376
tags question: http://stackoverflow.com/q/47764460
tags question: http://stackoverflow.com/q/47702665
tags question: http://stackoverflow.com/q/47740889
tag name: server

http://stackoverflow.com/q/47723677
has comment: http://stackoverflow.com/comment/82408170
type: Question
has comment: http://stackoverflow.com/comment/82408096
tagged with: python-3.x
answer count: 2
accepted answer: http://stackoverflow.com/a/47725491
has body: Ok so I got everything figured out. But now I am trying to use an if statement to tell the loop to take the average mpg (from the .txt file) from vehicles that get less than 22 mpg and then just average that up and output it IDLE. I feel like I should run the if statement before the loop. I am just not sure what I really need to change. I figure I should be able to slice variable holding the text file data. anyways here is my code. Can someone help me understand what I am not doing right? def cityGasGuzzler(): # Input:that assigns a text file to a value and provides other definition values cityGuzz = open("carModelData_city.","r") # Process: For loop to get average of gas guzzling city street driving vehicles for line in cityGuzz: # Process: Uses if statement to get the average of lower mpg or gas guzzlers if cityGuzz[0:-1] &lt; 22: sum = sum + eval(line) count = count + 1 avrg = sum / count # Output: using the round function to get average to the 2nd decimal place # and prints string and rounded variable to IDLE. print("The average city MPG is,", round(avrg, 2)) cityGasGuzzler() Just to clarify, my main objective is as follows, take the numeric values from the text file that are less than 22, average those up and output the average to IDLE.
tagged with: python
has answer: http://stackoverflow.com/a/47725491
has answer: http://stackoverflow.com/a/47723725
type: AnsweredQuestion
has title: Obtaining an average from if statement Python 3
score: 0
possible better answer: http://stackoverflow.com/a/47723725
has comment: http://stackoverflow.com/comment/82408156

http://stackoverflow.com/q/47752313
type: Question
score: 0
answer count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47753214
tagged with: django
has comment: http://stackoverflow.com/comment/82465157
linked to: http://stackoverflow.com/q/23256536
has comment: http://stackoverflow.com/comment/82465970
has title: Python/django application not running with supervisord
has comment: http://stackoverflow.com/comment/82466787
has body: I am trying to run Python Django app via supervisor with below configuration file. [program:test3] command=python manage.py runserver directory=/home/ubuntu/code/example/current/project/ stdout_logfile=/var/log/test3.log stderr_logfile=/var/log/test3.log user=ubuntu environment=PATH="/home/ubuntu/code/example/bin/",PROJECT_ENV="dev" autostart=true autorestart=true startsecs=10 stopwaitsecs=600e autorestart=true startsecs=10 stopwaitsecs=600 After running I was able to see there are 2 python process running at the moment. ubuntu 29853 0.1 2.0 354468 41196 ? Sl 11:33 0:00 python manage.py runserver ubuntu 29860 1.1 3.4 516944 69768 ? Sl 11:33 0:04 /home/ubuntu/code/analytics/bin/python manage.py runserver I have mentioned the log file under supervisord config file and was able to see the below error in "/var/log/test3.log". Error: ImportError: No module named pyspark.ml.evaluation I have already fulfilled all pip requirements in the directory. Any idea?
has comment: http://stackoverflow.com/comment/82464969
has answer: http://stackoverflow.com/a/47753340
tagged with: supervisord
tagged with: python

http://stackoverflow.com/comment/82420736
comment on: http://stackoverflow.com/q/47729678
has text: I changed the code to be less and more precise.
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/q/47763104
type: AnsweredQuestion
has title: How to run python script forever EC2?
score: 0
has body: Problem is when I run a script like: python scripy.py Then when I close the terminal the process is killed. How to run script forever under Ubuntu 16.04.3 LTS? I have created a service in /etc/init/publisher.conf like this: description "Publisher" author "alissada@gmail.com.com" start on runlevel [2345] stop on runlevel [!2345] env AN_ENVIRONMENTAL_VARIABLE=i-want-to-set respawn exec /var/www/__init__.py When I tried to run this service: service publisher start I get an error: Failed to start publisher.service: Unit publisher.service not found. Why?
has comment: http://stackoverflow.com/comment/82487836
answer count: 1
tagged with: ubuntu-16.04
tagged with: python
type: Question
accepted answer: http://stackoverflow.com/a/47763289
has answer: http://stackoverflow.com/a/47763289
has comment: http://stackoverflow.com/comment/82487717
tagged with: amazon-ec2

http://stackoverflow.com/q/47822346
has comment: http://stackoverflow.com/comment/82607755
type: AnsweredQuestion
score: 0
tagged with: boto3
has title: Boto3 python change date format
answer count: 1
has comment: http://stackoverflow.com/comment/82608913
has comment: http://stackoverflow.com/comment/82607631
type: Question
has comment: http://stackoverflow.com/comment/82609156
has comment: http://stackoverflow.com/comment/82607671
tagged with: amazon-s3
has comment: http://stackoverflow.com/comment/82608385
has comment: http://stackoverflow.com/comment/82609082
linked to: http://stackoverflow.com/q/4830535
tagged with: python
accepted answer: http://stackoverflow.com/a/47823319
has body: I'm using boto3 and python to get information about objects in an S3 bucket. I' using boto as below: context = super(s3, self).get_context_data(**kwargs) data = [] aws = boto3.resource('s3') buckets = aws.buckets.all() #Get data from each bucket for bucket in buckets: bucketData = {} totalSize = 0 bucketName = bucket.name fileBuckets = boto3.resource('s3').Bucket(bucketName) #Get data for each object inside each bucket for file in fileBuckets.objects.all(): totalSize += file.size bucketData['bucketName'] = bucket.name bucketData['createdAt'] = bucket.creation_date bucketData['totalSize'] = file_size(totalSize) data.append(bucketData) context['buckets'] = data return context And I display the creation date in the template like this: {{ bucket.createdAt }} {{ bucket.totalSize }}/4GB This is fine however I want to change the datetime stamp to just date. Currently I'm getting this: Dec. 3, 2017, 2:11 p.m But I would like to change it to display date only: 3/12/2017 I've been googling for a while but couldn't find anything. Any idea how this can be achieved?
has comment: http://stackoverflow.com/comment/82608042
has answer: http://stackoverflow.com/a/47823319

http://stackoverflow.com/comment/82578756
type: QuestionComment
has text: only once I saw (the newest) Ubuntu with Python but without Tkinter. I had to install `apt python-tk`. BTW: you can install Python 3 and still keep Python 2 for system. On Linux Mint based on Ubuntu I have now Python 2.7, 3.5 and 3.6 but earlier I had also 2.6 and 2.3 at the same time. [unofficial python repo for Ubuntu](https://launchpad.net/~deadsnakes/+archive/ubuntu/ppa)
comment on: http://stackoverflow.com/q/47788346
score: 0
type: Comment

http://stackoverflow.com/a/47775650
has comment: http://stackoverflow.com/comment/82525451
score: 0
answers question: http://stackoverflow.com/q/47725804
has comment: http://stackoverflow.com/comment/82521444
has comment: http://stackoverflow.com/comment/83233595
type: Answer
has comment: http://stackoverflow.com/comment/82525596
has comment: http://stackoverflow.com/comment/83227460
has body: The server 'remembers' your search with a session cookie. Your code discards all cookies returned by the server, so the memory is reset each time you make a new request. Use a session object to record incoming cookies, and send them out again with subsequent requests: with requests.Session() as sess: sess.headers['User-Agent'] = 'Mozilla/5.0' r = sess.get("replace_with_above_url", params=payload) # ... res = sess.post(r.url, data=payload) You can then submit GET requests for the /index?s=opportunity&amp;mode=list&amp;tab=list&amp;pageID= URLs with numeric page ids starting at 1, until you encounter an empty result set: page_id = 0 page_url = 'https://www.fbo.gov/index?s=opportunity&amp;mode=list&amp;tab=list&amp;pageID={}' while True: page_id += 1 page = sess.get(page_url.format(page_id)) soup = BeautifulSoup(page.text, "lxml") rows = soup.select('.solr-lst table tr') if len(rows) &lt;= 1: break for row in rows[1:]: print([c.get_text(strip=True) for c in rows[1].select('td')])
has comment: http://stackoverflow.com/comment/82525603
has comment: http://stackoverflow.com/comment/82525659
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82525661
accepted answer of: http://stackoverflow.com/q/47725804
has comment: http://stackoverflow.com/comment/83232514
has comment: http://stackoverflow.com/comment/82525732

http://stackoverflow.com/a/47805104
has comment: http://stackoverflow.com/comment/82572270
has body: Python walks up MRO when you ask it to, it's not implicit to keep checking higher. Change your code to use cooperative inheritance with super() (a request to walk the MRO to the next class up) when you would otherwise return NotImplemented and it should work. It removes the need for either C or D to define __mul__ at all, since they don't add anything to its functionality: class A(): def __mul__(self, other): return "A * %s" % other class B(): def __mul__(self, other): if isinstance(other, int): return "B * %s" % other try: return super().__mul__(other) # Delegate to next class in MRO except AttributeError: return NotImplemented # If no other class to delegate to, NotImplemented class C(B, A): pass class D(B, A): pass # Look ma, no __mul__! Then testing: &gt;&gt;&gt; d = D() &gt;&gt;&gt; d * 1 'B * 1' &gt;&gt;&gt; d * 'x' 'A * x' The magic of super() is that it works even in multiple inheritance scenarios where one class, B in this case, knows nothing about A, but will still happily delegate to it (or any other available class) if a child happens to inherit from both. If it doesn't, we handle the resulting AttributeError to make the result NotImplemented, as before, so stuff like this works as expected (it tries str's __rmul__ which doesn't recognize non-int and explodes): &gt;&gt;&gt; class E(B): pass &gt;&gt;&gt; e = E() &gt;&gt;&gt; e * 1 'B * 1' &gt;&gt;&gt; e * 'x' Traceback (most recent call last) ... TypeError: can't multiply sequence by non-int of type 'E'
type: Answer
answers question: http://stackoverflow.com/q/47804919
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47804919

http://stackoverflow.com/a/47779005
answers question: http://stackoverflow.com/q/47754276
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47754276
has body: This fixes the issue completely. Assigning self to self.exampleDialog = ExampleDialog(self) and updating self.exampleDialog.setWindowFlags to include self.exampleDialog.windowFlags() eliminates the second taskbar entry. Elements of the dialog can be accessed using self.exampleDialog.&lt;element&gt; for example self.exampleDialog.setWindowTitle('Example Dialog') from PyQt5 import uic from PyQt5.Qt import Qt from PyQt5.QtWidgets import QApplication, QDialog, QMainWindow import sys Ui_MainWindow = uic.loadUiType('TestMainWindow.ui')[0] Ui_ExampleDialog = uic.loadUiType('TestExampleDialog.ui')[0] class ExampleDialog(QDialog, Ui_ExampleDialog): def __init__(self, parent = None, flags = Qt.Dialog): QDialog.__init__(self, parent, flags) self.setupUi(self) class MainWindow(QMainWindow, Ui_MainWindow): def __init__(self, parent = None, flags = Qt.Window): QMainWindow.__init__(self, parent, flags) self.setupUi(self) self.setWindowTitle('MCVE') # Assign 'self' to 'ExampleDialog' so we can # access elements of the dialog. self.exampleDialog = ExampleDialog(self) self.itemInfoBtn.clicked.connect(self.showExampleDialog) self.setupItemInfo() def showExampleDialog(self): self.exampleDialog.setWindowFlags(self.exampleDialog.windowFlags() | Qt.WindowCloseButtonHint) self.exampleDialog.closeButton.clicked.connect(self.exampleDialog.accept) self.exampleDialog.exec_() # CREATES A TASKBAR ENTRY ... BUT WHY? def setupItemInfo(self): val = {'Entry #3', 'Entry #2', 'Entry #1'} self.exampleDialog.setWindowTitle('Example Dialog') self.exampleDialog.exampleCombo.insertItems(0, val) self.exampleDialog.exampleCombo.setCurrentIndex(1) if __name__ == "__main__": app = QApplication(sys.argv) w = MainWindow() w.show() sys.exit(app.exec_())
type: Answer

http://stackoverflow.com/a/47821575
answers question: http://stackoverflow.com/q/47821540
type: AcceptedAnswer
downvote count: 0
has body: You can parse the JSON with json.loads, do the manipulation, and then convert back to JSON via json.dumps. Note that I had to edit your JSON to make it valid. ("Gateway" was missing the enclosing double quotes.) import json values = [20.8, 21.2, 22.4] timeStamps = ["2013/25/11 12:23:20", "2013/25/11 12:25:20", "2013/25/11 12:28:20"] myJSON = '{ "Gateway": {"serial":"1001", "status":"ok"}, "Tag":{"TID":"FF01", "EPC":"EE01"}, "DataSet":{"sensorType":"temperature", "values":[], "timeStamps":[] } }' o = json.loads(myJSON) o["DataSet"]["values"] = values o["DataSet"]["timeStamps"] = timeStamps newJSON = json.dumps(o) print(newJSON) # Output: # {"Gateway": {"serial": "1001", "status": "ok"}, "Tag": {"TID": "FF01", "EPC": "EE01"}, "DataSet": {"sensorType": "temperature", "values": [20.8, 21.2, 22.4], "timeStamps": ["2013/25/11 12:23:20", "2013/25/11 12:25:20", "2013/25/11 12:28:20"]}}
score: 4
type: Answer
accepted answer of: http://stackoverflow.com/q/47821540
upvote count: 4

http://stackoverflow.com/comment/82640400
type: Comment
comment on: http://stackoverflow.com/a/47834707
type: AnswerComment
has text: @ Manuel - I tried your solution, but I get the following error: `KeyError: the label [-1] is not in the [index]`. This error is caused from the last line of your code. Shouldn't the last line be `df.loc[row[0], col] = df.loc[row[0]+1, col]`? It would be appreciative if you can include in-line comments in your answer to explain your logic. I am new to Python Pandas and would like to better understand your logic here. Thank you.
score: 0

http://stackoverflow.com/q/47851218
type: Question
has body: I've got an application which uses pyodbc to connect to database. It can by run with different db engines. Now I try to adapt it to Firebird. For some db engines (tested with sqlite, Sybase) I can use native pyodbc way to handle binding parametres: cnxn = pyodbc.connect(connect_string, autocommit=True) cur = cnxn.cursor() cur.execute("insert into files (file_type_id, path, md5) values (?, ?, ?)", file_type_id, path, md5) For Oracle I had to prepare some special SQL to be run: cnxn = pyodbc.connect(connect_string, autocommit=True) cur = cnxn.cursor() sql = """DECLARE v_file_type_id INT; v_path varchar2(1024); v_md5 varchar2(32); BEGIN v_file_type_id := %d; v_path := '%s'; v_md5 := '%s'; insert into files (file_type_id, path, md5) values (v_file_type_id, v_path, v_md5); END;""" % (file_type_id, path, md5) cur.execute(sql) First way doesn't work with Firebird. I receive error: pyodbc.IntegrityError: ('23000', '[23000] [ODBC Firebird Driver][Firebird]validation error for column FILE_TYPE_ID, value "*** null ***" (-625) (SQLExecDirectW)'). I tried to prepare dedicated SQL, just like for Oracle, but I've got some problems with it. cnxn = pyodbc.connect(connect_string, autocommit=True) cur = cnxn.cursor() sql = """set term ^ ; execute block as declare v_file_type_id int = %d; declare v_path varchar(1024) = '%s'; declare v_md5 varchar(32) = '%s'; begin insert into files (file_type_id, path, md5) values (:v_file_type_id, :v_path, :v_md5); end ^ set term ; ^""" % (file_type_id, path, md5) cur.execute(sql) It doesn't work. The rror this time is: pyodbc.Error: ('HY000', '[HY000] [ODBC Firebird Driver][Firebird]Dynamic SQL Error\nSQL error code = -104\nToken unknown - line 1, column 5\nterm (-104) (SQLExecDirectW)'). I'm looking for any sollution, so I'll be able to run it in any of that 2 ways. Performance aspect is also very important - application isn't run very often, but each time that part of code makes about 50k inserts to files table.
tagged with: firebird
linked to: http://stackoverflow.com/q/26774655
accepted answer: http://stackoverflow.com/a/47853832
tagged with: python
tagged with: pyodbc
type: AnsweredQuestion
downvote count: 0
upvote count: 1
score: 1
has answer: http://stackoverflow.com/a/47853832
answer count: 1
has title: Binding parameters using pyodbc with connection to Firebird
has comment: http://stackoverflow.com/comment/82667445
favorite count: 0

http://stackoverflow.com/comment/101393593
comment on: http://stackoverflow.com/q/47777460
type: Comment
type: QuestionComment
has text: I am sorry to say that my solution was to regenerate all the data with unix timestamp, which is universal, instead of the Matlab datetime type...
score: 0

http://stackoverflow.com/comment/82622917
type: QuestionComment
comment on: http://stackoverflow.com/q/47830097
type: Comment
has text: are you hoping to store a copy of the dataset in the code? which controls/technologies are you using, perhaps post a code example. For example a common place to store arbitrary information in say winform controls is Tag
score: 0

http://stackoverflow.com/comment/82440518
has text: @johnashu This workaround still gave me an error.
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47735949

http://stackoverflow.com/q/47740128
has comment: http://stackoverflow.com/comment/82455003
tagged with: python-3.5
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47900650
has title: Video capture in openCV 3.1 not working with python3
has body: I have installed openCV 3.1.0 with python3.5 every thing seemed to work fine during installation however when I am trying to execute even the following simple program, it doesn't work. OpenCV doesn't detect the camera. I checked, and the webcam has the id 0, I also tried other values (1,2,-1) but none of them seems to work, it always shows false. I have gone through similar questions on stack overflow, but none of the solutions seems to work. I have also tried re-installing openCV multiple times, it doesn't help either. Please help.
tagged with: opencv
tagged with: opencv3.1
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/82442953
type: Question

http://stackoverflow.com/comment/82479020
comment on: http://stackoverflow.com/a/47724643
type: AnswerComment
has text: I don't have pip installed where I work. Is there any other way to check the version?
score: 0
type: Comment

http://stackoverflow.com/a/47814192
has comment: http://stackoverflow.com/comment/82590049
type: Answer
answers question: http://stackoverflow.com/q/47814123
upvote count: 4
has comment: http://stackoverflow.com/comment/82589807
has comment: http://stackoverflow.com/comment/82590375
downvote count: 1
score: 3
has body: When you write Decimal(0.3) you're using a floating point value 0.3 which is subject to precision errors. &gt;&gt;&gt; Decimal(0.3) Decimal('0.299999999999999988897769753748434595763683319091796875') Use strings to avoid floating point entirely. &gt;&gt;&gt; Decimal('0.3') + Decimal('0.3') + Decimal('0.3') + Decimal('0.1') Decimal('1.0')

http://stackoverflow.com/comment/82396193
comment on: http://stackoverflow.com/q/47717866
has text: It's always a good idea to know which version you are using ;) The future of Python is Python 3, so if your project works with 3.5 then stick with that.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/82424546
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47731970
type: QuestionComment
has text: `map(func, items)` applies a func to a list of items, one at a time. You wouldn't use None as a func. None doesn't do anything. The "fix" you found is for converting a working map call in Python 2 to a Python 3 compatible version. But your initial map call is flawed, so wrapping it in a list doesn't help. You could say `map(str, [1, 2, 3])` in Python 2, and that would give you back `['1', '2', '3']` In your case, `map(str, a)`, since your **a** is a list, would give the same result.

http://stackoverflow.com/comment/82600652
type: Comment
comment on: http://stackoverflow.com/q/47819024
type: QuestionComment
has text: Seems very likely that any operation offering the `inplace` option can do it ... in place.
score: 1

http://stackoverflow.com/q/47824325
tagged with: python
type: UnansweredQuestion
tagged with: for-loop
downvote count: 0
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/47824355
answer count: 1
favorite count: 0
has body: I'm having trouble with this homework problem. SPECIAL_SYMBOLS = '!@#$%^&amp;*()_+=[]?/' def symbol_count(s:str): -&gt; int """Return the largest number of consecutive "special symbols" in the string s. &gt;&gt;&gt; symbol_count(’c0mput3r’) 0 &gt;&gt;&gt; symbol_count(’H! [here’) 1 &gt;&gt;&gt; symbol_count(’h3!!&amp;o world@#’) 3 """ lst = [] count = 0 for i in range(len(s)-1): if s[i] in SPECIAL_SYMBOLS: count +=1 if s[i+1] not in SPECIAL_SYMBOLS: lst.append(count) count = 0 else: count += 1 if lst == []: return 0 return max(lst) however, for the last example i get 5 instead of 3 so im guessing my count is not reinitializing to 0. I was wondering why this was the case. Thank you for the help.
type: Question
has title: Return the largest number of consecutive "special symbols" in the string s

http://stackoverflow.com/q/47704911
has comment: http://stackoverflow.com/comment/82370301
upvote count: 2
type: AnsweredQuestion
score: 2
tagged with: python-2.7
has title: How to zip the contents of a whole directory?
downvote count: 0
has comment: http://stackoverflow.com/comment/82370355
has answer: http://stackoverflow.com/a/47705373
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/82369975
type: Question
has body: I'm using python 2.7 and try to archive a directory: the object is to: archive the whole folder's content subject: C:\User\blah\blah\parentfolder structure:C...parentfolder\ 1.docx 2.xlxs 4.pdf subfolder\5.pdf 6.txt Now I know that shutil.make_archive() can zip me the folder, but it turned out to be like this C:\\User\\blah\\blah\\zipfile_name\\parentfolder\ 1.docx 2.xlxs 4.pdf subfolder\5.pdf 6.txt but I want a to skip the parentfolder layer in the zipfile_name folder, that is:(This is where the problem is different, I did learn shutil.make_archive from that question, but as I open the shutil module, I found out that make_archive has four intakes. I didn't know what makes them different and used the four input one, that's where I had my question. The previous one didn't not point out why it used just three inputs, and the other answers were using very complicated self-defined functions or so. The answer I chose in this problem compared and explained the difference, which I really appreciate. As a non-computer science majored, I think this kind of details help a lot of people.) C:\\User\\blah\\blah\\zipfile_name\\ 1.docx 2.xlxs 4.pdf subfolder\5.pdf 6.txt if I use os.path.walk and so on to write every file to zipfile_name, it seems it will be super complicated, as I will need to first 1.list everything in the folder--while:1 file?--write into zip folder while:0 directory?--make_directory , and list all items, and while loop again this process( do until no directory exists in the last directory) Plus I don't know how to make a directory in a .zip folder. So all this just seems complicated. So is there a way to change a folder into an archive folder while keeping the folder structure?
linked to: http://stackoverflow.com/q/1855095
accepted answer: http://stackoverflow.com/a/47705373
tagged with: python

http://stackoverflow.com/a/47787427
has comment: http://stackoverflow.com/comment/82558207
has body: try following: key_df = pd.DataFrame(key_dict) key_df.set_index('coordinates', inplace=True) key_df.loc[value_dict['coordinates']]
score: 0
has comment: http://stackoverflow.com/comment/82557966
type: Answer
answers question: http://stackoverflow.com/q/47786968

http://stackoverflow.com/comment/82709067
type: AnswerComment
has text: Tank you for your time skyoxZ. Your solution indeed is faster than mine. Adam Brown provided an answer that is slower on a small number of columns to remove but much faster on many columns. That's why i accepted his answer. Still +1 because for some use cases your solution could be interesting for some people
comment on: http://stackoverflow.com/a/47836852
score: 0
type: Comment

http://stackoverflow.com/comment/82526503
has text: @quant: the *specific error mode here* shows it is Python 3. `filter()` in Python two would have resulting in a list of strings, each an individual character.
score: 0
comment on: http://stackoverflow.com/a/47782466
type: Comment
type: AnswerComment

restructuredtext
tags question: http://stackoverflow.com/q/47714943
type: Tag
tags question: http://stackoverflow.com/q/47730413
tag name: restructuredtext
tags question: http://stackoverflow.com/q/47715781

http://stackoverflow.com/comment/82409233
score: 0
has text: Is the h4 tag a child of the span.myclass tag ?
type: Comment
comment on: http://stackoverflow.com/q/47724241
type: QuestionComment

http://stackoverflow.com/comment/82449285
type: QuestionComment
has text: It can be done with `urllib` and `threading`
comment on: http://stackoverflow.com/q/47744558
type: Comment
score: 1

http://stackoverflow.com/comment/82547653
score: 0
type: QuestionComment
has text: I don't know if I need to use some Django Events who reacts at the POST request
type: Comment
comment on: http://stackoverflow.com/q/47793282

http://stackoverflow.com/q/47841705
tagged with: if-statement
has comment: http://stackoverflow.com/comment/82647806
has answer: http://stackoverflow.com/a/47841732
possible better answer: http://stackoverflow.com/a/47841796
tagged with: python
has answer: http://stackoverflow.com/a/47841796
answer count: 4
type: Question
tagged with: text
accepted answer: http://stackoverflow.com/a/47841748
score: 0
has comment: http://stackoverflow.com/comment/82647637
has answer: http://stackoverflow.com/a/47841737
has comment: http://stackoverflow.com/comment/82647599
has title: Python always print else statement
has body: I have code like this: from tabulate import tabulate def search_movie_title(): movies = open('movies.txt','r').readlines() title = input("Input movie title: ").lower() for i in movies: movie = i.strip("\n").split("|") if title == movie[0].lower(): table = [['Name:',movie[0]],['Genre:',movie[1]],['Running:',movie[2]],['Director:',movie[3]],['Starring:', movie[4]],['Country:', movie[5]], ['Realised:', movie[6]]] print (tabulate(table)) else: print("Nothing found! Try again.") search_movie_title() And text file like this: A fistful of Dolars|Western|100|Sergio Leone|Clint Eastwood|Italia|1964 For a few dolars more|Western|130|Sergio Leone|Clint Eastwood|Italia|1965 The Good, the Bad and the Ugly|Western|179|Sergio Leone|Clint Eastwood|Italia|1966 March on the Drina|War movie|107|Zika Mitrovic|LJuba Tadic|Serbia|1964 If I use use only if statement it works "fine", but if I input nonexistent movie, then program just stop running, obvious. In case I use if and else it will always print else statement (except for first line in text file) Question is: How to print only finded and also movie and how to print message if movie is not found?
has answer: http://stackoverflow.com/a/47841748
has comment: http://stackoverflow.com/comment/82647603
type: AnsweredQuestion

http://stackoverflow.com/comment/82429859
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47726367
has text: Right, I apologize if it seems that way. I was just trying to see if I could solve the error at hand and work it into the solution. I thought my file was in the right place, but on further inspection I'll work on the positioning. I'll also work on printing out variables. Thanks!
score: 0

http://stackoverflow.com/a/47721267
score: 3
accepted answer of: http://stackoverflow.com/q/47716409
type: Answer
answers question: http://stackoverflow.com/q/47716409
upvote count: 3
has comment: http://stackoverflow.com/comment/82499522
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82532002
has body: You can prove the two formulations are the same by using the definitions of the weights and meanT. meanT = weight1*mean1 + weight2*mean2 (1) weight1 + weight2 = 1 (2) If you insert (1) into your first formula, you end up with something like this [(mean1-mean2)**2]*[weight1*weight2**2] + [(mean1-mean2)**2]*[weight2*weight1**2] If you factor that and use (2), you'll get your result. The complete proof is below, and the definitions can be checked in Otsu's original paper here. Hope this helps.

http://stackoverflow.com/q/47738712
tagged with: python
has comment: http://stackoverflow.com/comment/82437719
tagged with: list
score: 0
has answer: http://stackoverflow.com/a/47738768
has comment: http://stackoverflow.com/comment/82437683
answer count: 1
type: Question
has comment: http://stackoverflow.com/comment/82438496
has title: Python, storing a list of strings into a file and get the data back
has comment: http://stackoverflow.com/comment/82437976
type: UnansweredQuestion
has body: So i'm trying to write a basic TODO list program and i'm stuck on reading the data back from my file. I managed to store the content of my list in the file but when trying to read it back i never get the result i want, i tried splitting each line, read(), readline() and then append line to my list and either i get each of my list index counted as being only index[0] or if i manage to get it working then when i add some more stuff and overwrite my file with the new list it does a completely different thing when reading the data back .. #!/usr/bin/python3 import os from time import sleep import platform import getpass import socket import netifaces as ni from requests import get toDoList = [] backup = 'TODOlist.txt' cwd = os.getcwd() def clean(): if platform.system() == "Linux": os.system("clear") else: os.system("cls") def printList(givenList): i = 0 for task in givenList: print("\n[%d]: %s" % (i, task)) i += 1 print('\n') def addToList(listToAdd): task = str(input("\n:")) listToAdd.append(task) print('\n[*]Task [%s] has been added successfully' % (task)) def removeFromList(listToRemove): iterator = int(input("\nNumero of the task to remove :")) removed = listToRemove[iterator] if len(toDoList) == 1: listToRemove.append('') listToRemove.pop(iterator) print("[*]\nTask [%d]: %s has been removed successfully" % (iterator, removed)) def storageFile(filename, listToStore): overwrite = '' if os.path.isfile(filename): while overwrite != 'y' or overwrite != 'n': choice = str(input('\n[!]This will overwrite your already saved list, are you sure? y/n : ')) if choice == 'y': with open(filename, 'w+') as f: for task in listToStore: f.write(task) print('[*]\nDone.') break else: break else: with open(filename, 'w') as f: for task in listToStore: f.write(task) print('\n[*]%s created in %s' % (filename, cwd)) def main(): toDoList = [] clean() while True: print("\n---------------Otions------------------") print("1: Print your TODO list") print("2: Add something") print("3: Remove som…

http://stackoverflow.com/comment/82474568
type: QuestionComment
comment on: http://stackoverflow.com/q/47756555
has text: What is the desired result if there are 2 (or more) None next to each other?
score: 0
type: Comment

http://stackoverflow.com/q/47757946
upvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82477383
downvote count: 2
has comment: http://stackoverflow.com/comment/82477129
has answer: http://stackoverflow.com/a/47757988
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47758080
has body: I want to add more values to specific key for example, consider my dictionary is FinalData = {} and it contains key value pair as: {'12345,70':xyz,'12345,71':pqr} and now I want to add value ('abc') for same key '12345,70'so that my final dictionary becomes {'12345,70':xyz,abc,'12345,71':pqr} I tried to append second value by FinalData[key].append(value) but it gives me error: AttributeError: 'str' object has no attribute 'append' So is their any way to resolve this, I'm new to python please help.
score: -2
has title: How to add multiple values in dictionary having specific key
tagged with: python
has answer: http://stackoverflow.com/a/47758010
has comment: http://stackoverflow.com/comment/82477101
tagged with: dictionary
answer count: 4
has answer: http://stackoverflow.com/a/47758036

http://stackoverflow.com/q/47699625
upvote count: 0
score: -2
downvote count: 2
has comment: http://stackoverflow.com/comment/82359417
tagged with: python
has comment: http://stackoverflow.com/comment/82359880
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82359358
has comment: http://stackoverflow.com/comment/82359333
has title: Python Function Arguments: NameError argumant is not defined
has comment: http://stackoverflow.com/comment/82359588
answer count: 1
has comment: http://stackoverflow.com/comment/82359318
has body: I am new to Python. I want to call a function that detect null value in a excel table and passing "Fail" to a variable stat. def checkBlank(tb): book=xlrd.open_workbook(reportFile) sheet = book.sheet_by_name(tb) s= "Pass" for i in range(sheet.nrows): row = sheet.row_values(i) for cell in row: if cell =='': s="Fail" return s print checkBlank('Sheet1') Above code will return "Fail" but below code will give: NameError: name 'stat' is not defined def checkBlank(tb,stat): book=xlrd.open_workbook(reportFile) sheet = book.sheet_by_name(tb) s= "Pass" for i in range(sheet.nrows): row = sheet.row_values(i) for cell in row: if cell =='': s="Fail" print checkBlank('Sheet1', stat) print stat How can I assign "Fail" to stat if the function find the empty cell?
has answer: http://stackoverflow.com/a/47699706
accepted answer: http://stackoverflow.com/a/47699706
has comment: http://stackoverflow.com/comment/82359297
linked to: http://stackoverflow.com/q/986006
has comment: http://stackoverflow.com/comment/82359690
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82359365

http://stackoverflow.com/comment/82423183
has text: What I meant is that this is a python feature. If you import a module, change it in the background and then import again python will not pick up the changes. You either have to restart the interpreter or you can use `importlib.reload`.
type: Comment
comment on: http://stackoverflow.com/q/47730966
score: 0
type: QuestionComment

http://stackoverflow.com/q/47704790
has comment: http://stackoverflow.com/comment/82370270
has comment: http://stackoverflow.com/comment/82369755
has comment: http://stackoverflow.com/comment/82369737
has comment: http://stackoverflow.com/comment/82370187
answer count: 0
score: 1
has body: I have created a Guest Check-In Program and everything works except for my radio buttons. Whether you select "Yes" or you select "No", the program always prints "No". The conditional seems right to me, but it is obviously failing. (This is just a portion of the full program, obviously, but this is what pertains to my issue.) global emails emails = IntVar() Radiobutton(window, text='Yes', variable = emails, value = True).grid(row = 5, column = 5, sticky = W+E) Radiobutton(window, text='No', variable = emails, value = False).grid(row = 5, column = 6, sticky = W+E) print(self.title.get(), self.firstname.get(),self.middle.get(), self.lastname.get(), self.street.get(), self.city.get(), self.state.get(), self.zipcode.get(),self.birthDay.get(), self.birthMonth.get(), self.birthYear.get()) if emails == 1: print("Yes") else: print("No") print(self.reply.get(), self.comments.get()) I've tried an in-line conditional as well and got the same result.
downvote count: 0
has comment: http://stackoverflow.com/comment/82369924
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82370154
type: UnansweredQuestion
has title: Radio buttons value is not correct in the results
tagged with: python

scons
tag name: scons
type: Tag
tags question: http://stackoverflow.com/q/47741748

php
tags question: http://stackoverflow.com/q/47700707
tags question: http://stackoverflow.com/q/47790603
tags question: http://stackoverflow.com/q/47826658
tags question: http://stackoverflow.com/q/47770687
tags question: http://stackoverflow.com/q/47728499
tags question: http://stackoverflow.com/q/47728841
tags question: http://stackoverflow.com/q/47833289
tag name: php
tags question: http://stackoverflow.com/q/47720160
type: Tag

http://stackoverflow.com/comment/82539302
type: QuestionComment
score: 0
has text: Have a look at this stackoverflow answer: https://stackoverflow.com/questions/34145950/is-there-a-way-to-redirect-stderr-to-file-in-jupyter
type: Comment
comment on: http://stackoverflow.com/q/47778449

http://stackoverflow.com/comment/139061400
comment on: http://stackoverflow.com/a/69032145
score: 0
type: AnswerComment
has text: this require admin permission
type: Comment

http://stackoverflow.com/comment/82693445
has text: Are data confidental?
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47827561

music21
type: Tag
tags question: http://stackoverflow.com/q/47704052
tag name: music21

http://stackoverflow.com/q/47846116
has body: First of all I should mention that I'm new to Python as well as Django. I have a Django project with an sqlite3 database. I have created a couple of classes for calculating some physical problems, and I want to access the result of these through my website using forms. My previous approach to this was to change my classes to functions, and create several model fields for my objects. Then I reached a point where the output of my function was a 2D-array, which I have issues saving in my model. So I decided it would be easier just to store the entire object in the database - then I wouldn't have to change my classes to functions in order to utilize it in Django. I'm using inputs for my calculations in a form, a and b below. Is it possible to store objects in my model? I have made a hypothetic example, not sure if the code works but hope that you get the point. class Butterfly_model(models.Model): a = models.FloatField(verbose_name='a') b = models.FloatField(verbose_name='b') results = &gt;&gt;&gt;Some_Object_Field&lt;&lt;&lt; my computation script could contain something like this: class Compute: def __init__(self, a, b): self.X=[] self.Y=[] for i in range(0,a): self.X.append(i) self.Y.append(i+b) And my view.py contains following: if form_input.is_valid(): instance = form_input.save(commit=False) instance.results = Compute(instance.a,instance.b) instance.save() If not possible, does any of you have a suggestion for how handle calculations and resulting data like this? Best regards, Joachim
tagged with: python
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/82657581
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/82694388
favorite count: 0
type: Question
has title: Django save object in database
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47846802
tagged with: django

http://stackoverflow.com/q/47755200
tagged with: deep-learning
score: 0
answer count: 1
type: Question
has body: I don't know the the operating mechanism of lasagne functions. for the code below. class WScaleLayer(lasagne.layers.Layer): def __init__(self, incoming, **kwargs): super(WScaleLayer, self).__init__(incoming, **kwargs) W = incoming.W.get_value() scale = np.sqrt(np.mean(W ** 2)) incoming.W.set_value(W / scale) self.scale = self.add_param(scale, (), name='scale', trainable=False) self.b = None if hasattr(incoming, 'b') and incoming.b is not None: b = incoming.b.get_value() self.b = self.add_param(b, b.shape, name='b', regularizable=False) del incoming.params[incoming.b] incoming.b = None self.nonlinearity = lasagne.nonlinearities.linear if hasattr(incoming, 'nonlinearity') and incoming.nonlinearity is not None: self.nonlinearity = incoming.nonlinearity incoming.nonlinearity = lasagne.nonlinearities.linear def get_output_for(self, v, **kwargs): v = v * self.scale if self.b is not None: pattern = ['x', 0] + ['x'] * (v.ndim - 2) v = v + self.b.dimshuffle(*pattern) return self.nonlinearity(v) Can you tell me whether self.scale is constant in the training process after initialization?
tagged with: theano
accepted answer: http://stackoverflow.com/a/47871145
has title: Is it constant for self.scale variables defined in constructor function?
tagged with: python
has answer: http://stackoverflow.com/a/47871145
tagged with: lasagne
type: AnsweredQuestion

http://stackoverflow.com/comment/82585615
has text: Sorry my bad. I have changed the code. Does looks good now? @dsgdfg
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47810541

http://stackoverflow.com/q/47821478
type: Question
has answer: http://stackoverflow.com/a/47823904
tagged with: python-3.x
tagged with: kivy-language
tagged with: android
tagged with: python
tagged with: kivy
score: 4
has answer: http://stackoverflow.com/a/47823173
has title: Kivy - How do I call a function from the ListView?
upvote count: 4
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/47827348
answer count: 3
has answer: http://stackoverflow.com/a/47827348
has body: So I'm struggling with this one small bit where I cannot find a way to pass a value through a procedure when a ListView item is pressed. The example below is a simpler version of what I want to happen and how my main code is set out. The goal is so a can see ChangeScreen(self.index) on the hash tagged on_release: in the KV file. However the issue is I do not know how to call ChangeScreen successfully. Thanks! Kivy: #: import main main #: import ListAdapter kivy.adapters.listadapter.ListAdapter AppScreenManager: DemoScreen1: id: screen1 DemoScreen2: id: screen2 &lt;DemoScreen1&gt;: name: "demoscreen1" BoxLayout: orientation: "vertical" ListView: adapter: ListAdapter(data=["Screen 1","Screen 2"], cls=main.ListButton) &lt;DemoScreen2&gt;: name: "demoscreen2" orientation: "vertical" BoxLayout: orientation: "vertical" Label: id: labText text: "Hello World" &lt;ListButton&gt;: height: self.texture_size[1] on_release: ### HOW DO I CALL THE ChangeScreen FUNCTION HERE Python: import kivy from kivy.app import App from kivy.uix.screenmanager import ScreenManager, Screen from kivy.properties import StringProperty, ObjectProperty, ListProperty from kivy.uix.listview import ListItemButton class DemoScreen1(Screen): def ChangeScreen(self, option): if option == 0: print("Screen1") self.parent.ids.screen2.labelUpdater("Screen 1 was pressed") else: print("Screen2") self.parent.ids.screen2.labelUpdater("Screen 2 was pressed") self.parent.current = "demoscreen2" class DemoScreen2(Screen): labText = StringProperty() def labelUpdater(self,newText): self.ids.labText.text = newText class ListButton(ListItemButton): data = ListProperty() class AppScreenManager(ScreenManager): pass class Tester(App): pass if __name__ == '__main__': Tester().run()
downvote count: 0
accepted answer: http://stackoverflow.com/a/47823904
favorite count: 0

http://stackoverflow.com/comment/82672514
has text: So lets suppose I declare sTCP in the loop and I do .connect() in the loop.... Do I have to put sTCP.close() or sTCP.shutdown() at the end of the loop in order to make it work in the next interaction of the while? @freakish
comment on: http://stackoverflow.com/a/47854189
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/47728772
answers question: http://stackoverflow.com/q/47728022
has comment: http://stackoverflow.com/comment/82418272
has comment: http://stackoverflow.com/comment/82418054
has comment: http://stackoverflow.com/comment/82418331
type: Answer
has comment: http://stackoverflow.com/comment/82417958
accepted answer of: http://stackoverflow.com/q/47728022
has comment: http://stackoverflow.com/comment/82418153
has comment: http://stackoverflow.com/comment/82418236
has comment: http://stackoverflow.com/comment/82418186
has comment: http://stackoverflow.com/comment/82418293
downvote count: 0
has comment: http://stackoverflow.com/comment/82418363
has body: You could use pd.concattoo: import pandas as pd data = {'A': {'2000-01-01': 0.469112, '2000-01-02': 1.212112, '2000-01-03': -0.861849, '2000-01-04': 0.7215550000000001, '2000-01-05': -0.424972, '2000-01-06': -0.67369, '2000-01-07': 0.40470500000000004, '2000-01-08': -0.370647}, 'B': {'2000-01-01': -0.28286300000000003, '2000-01-02': -0.173215, '2000-01-03': -2.1045689999999997, '2000-01-04': -0.706771, '2000-01-05': 0.56702, '2000-01-06': 0.113648, '2000-01-07': 0.5770460000000001, '2000-01-08': -1.157892}} # Create dataframe df = pd.DataFrame(data) # Create a series to append "empty" column in loop extra_col = pd.Series(index=df.index,data=[""]*len(df)) # Create loop while True: df = pd.concat((df,extra_col,df),axis=1) # Let's break if more than 10 columns if len(df.T) &gt; 10: break # Optional rename columns alphabet = list("ABCDEFGHIJKLMNOPQRSTUVWXYZ") df.columns = (alphabet[i] for i in list(range(len(df.columns)))) # Output df.to_excel("test.xlsx",header=False,index=False)
upvote count: 1
score: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82418104
has comment: http://stackoverflow.com/comment/82418435
has comment: http://stackoverflow.com/comment/82417997

http://stackoverflow.com/q/47720594
tagged with: python
has answer: http://stackoverflow.com/a/47720828
has comment: http://stackoverflow.com/comment/82401747
accepted answer: http://stackoverflow.com/a/47720828
type: Question
answer count: 2
has title: Reading Words from a File and Writing Them on The Same Line
linked to: http://stackoverflow.com/q/23598410
has answer: http://stackoverflow.com/a/47720717
has comment: http://stackoverflow.com/comment/82405022
possible better answer: http://stackoverflow.com/a/47720717
has body: I have a file that contains a word per a line. Each sentence is separated by an empty line. I want to read the file and write the whole words of a sentence on the same line. For example: This is a sample input Hello World !! The desired output is: This is a sample input Hello World !! I try this: file = open('Words.txt', "r") Writfile = open('Sent.txt','w') for line in file: if line in ['\n']: Writfile.write('\n') else: Writfile.write(line + " ",)
has comment: http://stackoverflow.com/comment/82401764
type: AnsweredQuestion
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/82403861

http://stackoverflow.com/comment/82723034
comment on: http://stackoverflow.com/q/47838954
type: Comment
type: QuestionComment
has text: Hi, @MuhammadNizami. It's KKBox's churn prediction. Competition ends now. Maybe you can download the dataset from the Kaggle page.
score: 0

http://stackoverflow.com/q/47746307
tagged with: python
score: 0
has answer: http://stackoverflow.com/a/47747260
has comment: http://stackoverflow.com/comment/82453511
tagged with: celery
has body: I have a django 1.11.4, python3.5, gunicorn 19.7.1 server with supervisor, redis 2.10.6 and celery 4.1.0. My File structure is like so: samy_python ├── celery.py ├── __init__.py ├── settings ├── urls.py ├── wsgi.py website ├── static ├── templates ├── samy | ├── samy_firebase.py | ├── tasks.py ├── views.py I get my secret with: # settings.py SECRET_KEY = os.environ.get("secret_KEY") My supervisor conf file for celery is: [program:gunicorn] .... environment = secret_KEY="12345" ..... [program:celery] directory=/home/username/Projects/samy/samy_python command=/home/username/Projects/samy/samy_python/env/bin/celery --app=samy_python.celery.app worker -B -l info user=username stdout_logfile=/var/log/celery/celery.log stderr_logfile=/var/log/celery/celery.log autostart=false autorestart=false startsecs=10 My Celery File: # celery.py from __future__ import absolute_import import os import logging logger = logging.getLogger('myapp.celery.py') from celery import Celery from django.conf import settings os.environ.setdefault("DJANGO_SETTINGS_MODULE", "samy_python.settings") # Celery App # TODO # [START Celery App] app = Celery('samy_python') app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) # [END Celery App] My init file: # __init__.py from __future__ import absolute_import from .celery import app as celery_app The Configuration in my settings.py file for celery: BROKER_URL = 'redis://localhost:6379/1' CELERY_RESULT_BACKEND = 'redis://localhost:6379/1' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' Where the error could be coming from is in my settings.py file I use an env variable to set the environment. (Production, Dev, or Test): DEBUG = False DJANGO_TESTING = False DJANGO_DEVELOPMENT = False DJANGO_ENV = os.environ.get('DJANGO_ENV') if DJANGO_ENV == 'DJANGO_TESTING': DJANGO_TESTING = True elif DJANGO_ENV == 'DJANGO_DEVELOPMENT': DJANGO_DEVELOPMENT = True T…
type: Question
answer count: 2
tagged with: redis
has comment: http://stackoverflow.com/comment/82453740
has answer: http://stackoverflow.com/a/47747074
has title: Django, Celery Supervisor: Secret Key Error: django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty
type: UnansweredQuestion
tagged with: django

http://stackoverflow.com/q/47745541
tagged with: python
type: UnansweredQuestion
has body: I am trying to implement shadow removal in python OpenCV using the method of entropy minimization by Finlayson, et. al.: "Intrinsic Images by Entropy Minimization", Finlayson, et. al. I can't seem to match the results from the paper. My entropy plot does not match up with those from the paper and I am getting the wrong minimum entropy. Any thoughts? (I have much more source code and papers upon request) ############# # LIBRARIES ############# import numpy as np import cv2 import os import sys import matplotlib.image as mpimg import matplotlib.pyplot as plt from PIL import Image import scipy from scipy.optimize import leastsq from scipy.stats.mstats import gmean from scipy.signal import argrelextrema from scipy.stats import entropy from scipy.signal import savgol_filter root = r'\path\to\my_folder' fl = r'my_file.jpg' ############# # PROGRAM ############# if __name__ == '__main__': #----------------------------------- ## 1. Create Chromaticity Vectors ## #----------------------------------- # Get Image img = cv2.imread(os.path.join(root, fl)) img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) h, w = img.shape[:2] plt.imshow(img) plt.title('Original') plt.show() img = cv2.GaussianBlur(img, (5,5), 0) # Separate Channels r, g, b = cv2.split(img) im_sum = np.sum(img, axis=2) im_mean = gmean(img, axis=2) # Create "normalized", mean, and rg chromaticity vectors # We use mean (works better than norm). rg Chromaticity is # for visualization n_r = np.ma.divide( 1.*r, g ) n_b = np.ma.divide( 1.*b, g ) mean_r = np.ma.divide(1.*r, im_mean) mean_g = np.ma.divide(1.*g, im_mean) mean_b = np.ma.divide(1.*b, im_mean) rg_chrom_r = np.ma.divide(1.*r, im_sum) rg_chrom_g = np.ma.divide(1.*g, im_sum) rg_chrom_b = np.ma.divide(1.*b, im_sum) # Visualize rg Chromaticity --&gt; DEBUGGING rg_chrom = np.zeros_like(img) rg_chrom[:,:,0] = np.clip(np.uint8(rg_chrom_r*255), 0, 255) rg_chrom[:,:,1] = np.clip(np.uint8(rg_chrom_g*255), 0, 255) rg_chrom[:,:,2] = np.clip(np.uint8(rg_chrom_b*255), 0, 255) plt.im…
has answer: http://stackoverflow.com/a/48875676
tagged with: image
has comment: http://stackoverflow.com/comment/89025653
has title: Shadow Removal in Python OpenCV
has comment: http://stackoverflow.com/comment/82484280
has comment: http://stackoverflow.com/comment/117347798
has comment: http://stackoverflow.com/comment/82473940
downvote count: 0
answer count: 1
favorite count: 0
tagged with: opencv
type: Question
upvote count: 9
score: 9
has comment: http://stackoverflow.com/comment/99437127
has comment: http://stackoverflow.com/comment/82460571
tagged with: shadows

http://stackoverflow.com/comment/82697056
score: 0
type: Comment
type: QuestionComment
has text: could you provide the screenshot of toaster. i thought you added machine variable in toaster. am I Right? and tell me the yocto version?
comment on: http://stackoverflow.com/q/47845229

http://stackoverflow.com/a/47747387
has body: JSON is a convenient option. import json read the docs for specifics and examples https://docs.python.org/2/library/json.html https://docs.python.org/3/library/json.html
type: Answer
answers question: http://stackoverflow.com/q/47746899
score: 0
has comment: http://stackoverflow.com/comment/82464679
has comment: http://stackoverflow.com/comment/82475838
has comment: http://stackoverflow.com/comment/82475291

http://stackoverflow.com/q/47704482
tagged with: unit-testing
has answer: http://stackoverflow.com/a/47724734
favorite count: 0
type: Question
has title: how to pass magic mocked references to main method in python
tagged with: mocking
upvote count: 0
tagged with: python
score: -1
type: AnsweredQuestion
answer count: 1
accepted answer: http://stackoverflow.com/a/47724734
has body: I've tried to stub out classes constructed in the main function so that I can test against main and assert that classes are initialized with specific data. However main function still does not pick up the mocked instances. How can I pass along the mocked instance to main. from unittest.mock import patch from contextlib import contextmanager @contextmanager def use_mocked(method, cls, ret_value): class MockedClass(cls): pass def func(cls): return ret_value def fullname(o): return o.__module__ + "." + o.__name__ setattr(MockedClass, method, classmethod(func)) with patch(fullname(cls), MockedClass): yield This is the patching utility to make sure main is passed the mocked reference. I may be confused on my understanding of how its functioning. def test_main(): magic_b = MagicMock(spec_set=Benchmark, wraps=Benchmark) with use_mocked("__new__", DataStream, magic_b): main.main() magic_b.assert_called_once_with() # fails in the main module, I have a main method defined as... import benchmark.Benchmark def main(): b = benchmark.Benchmark() # &lt;- this is not the mocked instance ...
downvote count: 1

http://stackoverflow.com/comment/84696892
type: Comment
has text: Eh? Read the stack trace -- the exception is from *inside the library*; it has nothing to do with casting the returned value. Also, `str()` in Python 2 is what Python 3 calls a bytestring. It doesn't *require* that contents be printable ASCII, or otherwise constrain them.
score: 0
comment on: http://stackoverflow.com/a/48846370
type: AnswerComment

http://stackoverflow.com/q/47798672
has comment: http://stackoverflow.com/comment/82558461
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/49935275
tagged with: python-2.7
has body: I am trying to extend the RobotFramework SeleniumLibrary: class ReusableModule(SeleniumLibrary): ROBOT_LIBRARY_SCOPE = 'GLOBAL' def __init__(self, timeout=0.5, implicit_wait=15.0, **kwargs): logger.info("Reusable __init__") SeleniumLibrary.__init__(self, timeout=timeout, implicit_wait=implicit_wait, **kwargs) @keyword def open_browser(self, url, browser=env.capabilities.get("browserName"), alias=None, remote_url=env.host, desired_capabilities=env.capabilities, ff_profile_dir=None): logger.info("Reusable open browser") return super(ReusableModule, self).open_browser(url=url, browser=browser, alias=alias, remote_url=remote_url, desired_capabilities=desired_capabilities, ff_profile_dir=ff_profile_dir) I am getting the following error when I call this keyword in the RobotFramework Test: AttributeError: 'super' object has no attribute 'open_browser' Note: This worked in the past for Selenium2Library.
score: 1
has title: Not able to Extend RobotFramework SeleniumLibrary
downvote count: 0
answer count: 1
tagged with: selenium
upvote count: 1
favorite count: 0
type: Question
tagged with: robotframework

http://stackoverflow.com/q/47782031
tagged with: plot
type: Question
has title: Sequential plotting on one pair of axes using python
tagged with: matplotlib
tagged with: python
favorite count: 0
score: 2
upvote count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/47788228
has comment: http://stackoverflow.com/comment/82525447
type: UnansweredQuestion
answer count: 1
has body: The following is code to plot cosine and sine on one pair of axes, from DeCaria's wonderful book Python Programming and Visualization for Scientists. How to I produce the same plot but by plotting cos first, pausing, then plotting sin? Ultimately, I want to plot many functions sequentially and be able to watch for patterns in the family of functions as they emerge. import matplotlib.pyplot as plt import numpy as np x = np.arange(0,100.0) y1 = np.cos(2*np.pi*x/50.0) y2 = np.sin(2*np.pi*x/50.0) plt.plot(x, y1, 'b-', label = 'Cosine') plt.plot(x, y2, 'r--', label = 'Sine') plt.legend(('Cosine', 'Sine')) plt.show() Thank you for any help that might be available.

http://stackoverflow.com/a/47837195
upvote count: 3
type: Answer
answers question: http://stackoverflow.com/q/47836772
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47836772
score: 3
has body: Inertia in this case is a tuple. odeint expects a tuple of arguments as its args parameter, so Inertia gets unpacked and the arguments to diff become y0, t, M, L, a. To circumvent this, you should pack Inertia in another tuple to make Inertia a single argument, like so: sol = odeint(diff, y0, t, args=(Inertia,)) Note the , after Inertia. this makes it a tuple ((a) == a, (a,) == tuple(a))

http://stackoverflow.com/comment/82489330
type: QuestionComment
comment on: http://stackoverflow.com/q/47735949
has text: @xaav, Thank you. bug reported.
score: 0
type: Comment

http://stackoverflow.com/q/47722077
tagged with: np
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/47722234
score: 0
has title: Solving 3 non linear equations using fsolve
answer count: 1
has body: I want to find the valuews of a,b,c. It gives me error: from scipy.optimize import fsolve def equations(p): a,b,c = p return (a*np.log10([-b])+c, a*np.log10([100-b])+c-100, a*np.log10([80-b])+c-20) a,b,c = fsolve(equations, (1, 1, 1)) print(a,b,c) &gt; print(a,b,c) TypeError: fsolve: there is a mismatch between the input and output shape of the 'func' argument 'equations'.Shape should be (3,) but it is (3, 1).
type: Question

http://stackoverflow.com/comment/82364627
has text: @boulderj Brute force, you can just do a global search for python.exe (on Windows) or python (on OSX/UNIX), and see where they are.
type: AnswerComment
comment on: http://stackoverflow.com/a/47702119
score: 0
type: Comment

http://stackoverflow.com/comment/82411460
score: 0
type: Comment
has text: If I made another syntaxe error I'm sorry I'm tired I'm going to sleep, but you have essence of my ideas in the comment and in the example. I specify : these are 2 different methods. Especially with the comments haha
comment on: http://stackoverflow.com/a/47725332
type: AnswerComment

http://stackoverflow.com/a/47801595
has comment: http://stackoverflow.com/comment/82567356
downvote count: 0
answers question: http://stackoverflow.com/q/47800252
has body: I dont really know the logic you are after, that is not even my point, my point is that probably you can't focus on the logic because you are too busy with those index thing. So I have taken the liberty to modify your code a little bit to show what is important, and if you are using python, you should take advantage of this feature, because readability counts. from operator import attrgetter class Person: def __init__(self, name, lan): self.name = name self.lan = lan def is_compatible(self, other): if other.lan == self.lan: return True return False class Requester(Person): def __init__(self, *args, problem, mode, time, **kwargs): super().__init__(*args, **kwargs) self.problem = problem self.mode = mode self.time = time class Operator(Person): def __init__(self, *args, expertise, hour, time, **kwargs): super().__init__(*args, **kwargs) self.expertise = expertise self.hour = hour self.time = time self.assigned = False operators = [ Operator(name='Atilio Moreno', lan='portuguese', expertise=('laptops',), hour='10:58', time=104), . . . Operator(name='Romana Cerveny', lan='czech', expertise=('phones',), hour='11:13', time=213), ] requests = [ Requester(name='Christina Holtzer', lan='german', problem='hifi', mode='fremium', time=7), . . . Requester(name='Feliciano Santos', lan='portuguese', problem='phones', mode='fremium', time=12), ] With this done, the task of thinking about the logic becomes much simpler, just type what you are thinking: def assign_tasks(operators, requests, current_time): operators.sort(key=attrgetter('hour', 'time', 'name')) requests.sort(key=attrgetter('mode')) tasks = [] for requester in requests: for operator in operators: if requester.is_compatible(operator) and requester.problem in operator.expertise and operator.time &lt; 240: if not operator.assigned: tasks.append([current_time, requester.name, operator.name]) operator.assigned = True operator.time += requester.time break # Breaks out of second for-loop so we go to the next requester else: #I…
score: 3
has comment: http://stackoverflow.com/comment/82564934
has comment: http://stackoverflow.com/comment/82568633
has comment: http://stackoverflow.com/comment/82564573
type: Answer
has comment: http://stackoverflow.com/comment/82567737
upvote count: 3

http://stackoverflow.com/q/47790517
has body: I have a Model which has a self foreign key. models.py class Employee(AbstractUser): manager = models.ForeignKey('self', on_delete=models.SET_NULL, related_name=_('manger'), null=True) Now when i add this Model to admin site and try to update an employee users's can set themself as their own manager. So if i am trying to update employee ID #1, I dont want employee ID #1 to be displayed in the managers dropdown. Additional Question I know that i can add clean method that validates this condition in my Update form, however i do not know how to get the current object ID to check against manager ID. forms.py class EmployeeChangeForm(UserChangeForm): class Meta: model = Employee fields = '__all__' def clean_manager(self): # An Employee Cannot have himself assigned as a manager eID = ?? # how do i get the id of Current Employee here ? mgr = self.cleaned_data["manager"] if eID == mgr: raise forms.ValidationError("Employee and Manger should be diffrent !!") return mgr The above approach will not allow the current user to block employee from setting himself as setting as his manager however, the employee will still show in the dropdown of the manager field. I would prefer if the current employee does not show in the dropdown at all. Is there a way to do that ? Update: I just learned about ForeignKey.limit_choices_to which limits the choices to a particuler set from related table. However, again i do not know how will i pass the current user id to the set. for example: models.py from django.db.models import Q class Employee(AbstractUser): manager = models.ForeignKey( 'self', on_delete=models.SET_NULL, related_name=_('manger'), null=True, limit_choices_to=~Q(id=3), ) the above code limits my manager choices to all manager's except 3. but i dont know how to make this valie dynamic. I cant do limit_choices_to=~Q(id=self.pk) or limit_choices_to=~Q(id=self.id) Please help
answer count: 1
has answer: http://stackoverflow.com/a/47935773
tagged with: django-forms
type: Question
has comment: http://stackoverflow.com/comment/82544619
tagged with: django-admin
tagged with: django
tagged with: django-models
tagged with: python
type: AnsweredQuestion
has title: How to block same object reference for Foreign key in same table in Django?
score: 0
accepted answer: http://stackoverflow.com/a/47935773
linked to: http://stackoverflow.com/q/6325681

http://stackoverflow.com/q/47821883
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47821959
tagged with: python-2.7
answer count: 2
score: 1
possible better answer: http://stackoverflow.com/a/47821920
has comment: http://stackoverflow.com/comment/82606708
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/82606603
has comment: http://stackoverflow.com/comment/82606694
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82606676
has comment: http://stackoverflow.com/comment/82606383
has answer: http://stackoverflow.com/a/47821959
tagged with: python
has answer: http://stackoverflow.com/a/47821920
tagged with: dictionary
has body: Background: I'm getting some data from the backend (regions =[]) and I need to add a property (order = []) to each dict in the list by matching slug. Where I will sort by this property in the jinja template filter. In javascript I would use a functional Array methods like map, zip etc; unfortunately, I'm a python noob and I don't know what's the equivalent of these methods. Question: How can I concisely flatten the list order into regions and receive the expected output regions_with_order in python? Repl # I made this to zip into regions order = [ {'slug': 'north-america', 'order': 1}, {'slug': 'latin-america', 'order': 2}, {'slug': 'europe', 'order': 3}, {'slug': 'asia-pacific', 'order': 4}, {'slug': 'africa-middle-east', 'order': 5}, ] # I received this from backend cms. regions = [ {'slug': 'africa-middle-east', 'lat': '123'}, {'slug': 'europe','lat': '1231'}, {'slug': 'asia-pacific', 'lat': '1230'}, {'slug': 'latin-america', 'lat': '1232'}, {'slug': 'north-america', 'lat': '1234'}, ] # Expected OUTPUT # regions_with_order = [ # {'slug': 'north-america', 'lat': '1234', 'order': 1}, # {'slug': 'latin-america', 'lat': '1232', 'order': 2}, # {'slug': 'europe','lat': '1231', 'order': 3}, # {'slug': 'asia-pacific', 'lat': '1230','order': 4}, # {'slug': 'africa-middle-east', 'lat': '123','order': 5} # ]
has title: Flatten two lists of dicts by matching inner dicts property in python?

http://stackoverflow.com/a/47815427
answers question: http://stackoverflow.com/q/47806836
score: 0
upvote count: 1
downvote count: 1
has body: Here's some compromise solution: cursor.execute("""SELECT * FROM tags_table;""") rows = cursor.fetchall() for row in rows: print(row[0]) ¯ \ _ (ツ) _ / ¯
type: Answer

http://stackoverflow.com/comment/82400236
comment on: http://stackoverflow.com/a/47719774
has text: The `static` tag has nothing to do with serving user-uploaded images.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/82420068
has text: I want to remove the punctuation from the whole file. But my more important question is how to import each text file into the function. It's simply not doing that.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47729654
type: QuestionComment

http://stackoverflow.com/comment/82395929
score: 0
type: AnswerComment
type: Comment
has text: @Andrea, especially with that setup, I think Charlie is right. It's been my observation that any time you have to work with sheets, though, it really kills performance.
comment on: http://stackoverflow.com/a/47703801

http://stackoverflow.com/q/47826517
upvote count: 2
type: UnansweredQuestion
tagged with: python
score: 2
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/47827730
linked to: http://stackoverflow.com/q/14158868
has title: Import space delimited .csv into python3, ignoring text at the start?
has body: I would like to import the following .csv data (.txt file) into python lists for each column of data, ignoring the text at the start. I can't change the format of the file. I'm getting the error: "Traceback (most recent call last): File "/Users/Hamish/Desktop/Python/AWBM/Import.py", line 13, in &lt;module&gt; rain_column = float(row[7]) IndexError: list index out of range" This is the code which I'm trying to get working... import csv import numpy as np file = open('Data_Bris.txt') reader = csv.reader(file, delimiter=' ') datelist = [] rainlist = [] evaplist = [] for row in reader: # row = [date, day, date2, T.Max, Smx, T.Min, Smn, Rain, Srn, Evap, Sev, Rad, Ssl, VP, Svp, maxT, minT, Span, Ssp] date_column = str(row[0]) rain_column = float(row[7]) evap_column = float(row[9]) datelist.append([date_column]) rainlist.append([rain_column]) evaplist.append([evap_column]) date = np.array([datelist]) rain = np.array([rainlist]) evap = np.array([evaplist]) timeseries = np.arange(rain.size) This is the data file that I would like to import (continues the same beyond)... "17701231" 365 31/12/1770 -99.9 999 -99.9 999 9999.9 999 999.9 999 999.9 999 999.9 999 9999.9 9999.9 9999.9 999 "" " This file is SPACE DELIMITED for easy import into both spreadsheets and programs." "The first line 17701231 contains dummy data and is provided to allow spreadsheets to sense the columns" " To read into a spreadsheet select DELIMITED and SPACE." " " " " "========= The following essential information and notes should be kept in the data file ==========" " " "The Data Drill system and data are copyright to the Queensland Government Department of Science, Information Technology and Innovation (DSITI)." "SILO data, with the exception of Patched Point data for Queensland, are supplied to the licencee only and may not be given, lent, or sold to any other party" " " "Notes:" " * Data Drill for Lat, Long: -27.5000 153.0000 (DECIMAL DEGREES), 27 30'S 153 00'E Your Ref: Data_Bris" " * Elevation: 102m " "…
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82615366

http://stackoverflow.com/q/47819252
has title: Kivy VKeyboard object doesn't popup on request method
upvote count: 1
tagged with: kivy
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: python
has body: I wanted to request a keyboard via Window method request_keyboard() in kivy however it doesn't assign the widget itself -> self.keyboard.widget is None. I read that it may be due to the wrong configuration in Config but I tried every configuration and my vkeyboard still doesn't popup. Am I missing something? self.show_keyboard() doesn't work too. class DataTextInput(TextInput, FocusBehavior): def __init__(self, **kwargs): super(DataTextInput, self).__init__(**kwargs) self._keyboard = Window.request_keyboard(self._keyboard_closed, self, 'text') if self._keyboard.widget: print("exists") EDIT: ok I realized that Window.allow_vkeyboard flag was set to False, so it must be something wrong with Config.
answer count: 0
score: 1
downvote count: 0

http://stackoverflow.com/q/47715337
has comment: http://stackoverflow.com/comment/82391410
upvote count: 5
has comment: http://stackoverflow.com/comment/82391120
has comment: http://stackoverflow.com/comment/82391496
score: 5
has comment: http://stackoverflow.com/comment/82391269
tagged with: pandas
has title: check if timestamp column is in date range from another dataframe
possible better answer: http://stackoverflow.com/a/47729006
downvote count: 0
has answer: http://stackoverflow.com/a/52383223
has answer: http://stackoverflow.com/a/71984361
favorite count: 0
tagged with: timestamp
accepted answer: http://stackoverflow.com/a/47719588
type: AnsweredQuestion
has body: I have a dataframe, df_A with two columns 'amin' and 'amax', which is a set of time range. My objective is to find whether a column in df_B lies between any of the rows of range in df_A 'amin' and 'amax' columns. df_A[['amin','amax'] ] amin amax 0 2016-07-16 19:37:03 2016-07-17 11:16:32 1 2016-07-04 21:15:54 2016-07-05 10:57:46 2 2016-07-24 23:30:41 2016-07-25 15:38:02 3 2016-07-12 03:02:38 2016-07-12 22:11:01 df_B['created_date'] created_date 2016-07-17 01:16:32 2016-07-05 10:15:54 2016-07-12 12:11:01 df_A['amin'] = pd.to_datetime(df_A['amin'], errors='coerce') df_A['amax'] = pd.to_datetime(df_A['amax'], errors='coerce') df_B['created_date'] = pd.to_datetime(df_B['created_date'],errors='coerce') def dt2epoch(value): epoch = (value - pd.to_datetime(datetime(2015,12,31).strftime('%Y-%m-%d %H:%M:%S.%f'))).total_seconds() return epoch df_A['amax_epoch']=df_A['amax'].apply(dt2epoch) df_A['amin_epoch']=df_A['amin'].apply(dt2epoch) df_B['created_date_epoch']=df_B['created_date'].apply(dt2epoch) def make_tuple(row): n= len(row) row = [(x,row[n - 1]) for x in row] return row minMaxTuple = minMax.apply(make_tuple, axis =1) Above is part of my code, I've tried below(not sure if it's necessary): convert them to epoch values convert df_A into a tuple. However, df_A and df_B has a different number of rows. Also, I dont have any id column to merge them together. label = [] for l in df_B['created_date_epoch']: if (m[0] for m in minMaxTuple) &lt;= l &lt;= (m[1] for m in minMaxTuple): label.append('1') else: label.append('0') However, when I run this, the result I get for 'label' is an empty list. Also, the label should be a column that has the same number of rows as df_A. Ultimately, I would like to add a new 'label' column in df_A: minMaxTuple label (2016-07-16 19:37:03, 2016-07-17 11:16:32) 1 (2016-07-04 21:15:54, 2016-07-05 10:57:46) 1 (2016-07-24 23:30:41, 2016-07-25 15:38:02) 0 (2016-07-12 03:02:38, 2016-07-12 22:11:01) 1
has comment: http://stackoverflow.com/comment/82391173
has answer: http://stackoverflow.com/a/47729006
has comment: http://stackoverflow.com/comment/82391354
tagged with: range
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/82392045
answer count: 4
has comment: http://stackoverflow.com/comment/82391589
type: Question
has answer: http://stackoverflow.com/a/47719588
has comment: http://stackoverflow.com/comment/82391012
has comment: http://stackoverflow.com/comment/82391520

http://stackoverflow.com/comment/82590851
type: Comment
type: QuestionComment
has text: @asergey OP uses amoste the same code as in marked answer in your link. OP has even `stream=True`. I don't see difference
score: 0
comment on: http://stackoverflow.com/q/47811129

http://stackoverflow.com/comment/82648943
score: 0
type: QuestionComment
has text: Thanks Sam. that partially solved my problem. I didn't make it clear in the question. I don't need all the x's value marked on the x axis. but need what plt.plot (x,y) does, mark some x's values. for example, I have 6000 data points on x axis, I need the x's value marked on the x axis every 1000 data points.
type: Comment
comment on: http://stackoverflow.com/q/47842156

http://stackoverflow.com/q/47715457
has body: I am trying to plot my keys and values in this nice barchart. However, some values are not plotted. In the image below you see for instance key '20' having value 120, however, in the chart key 20 has value 0. This happens for multiple keys, however, for most of them, the values plotted seem to be correct. How is this possible? And how can I solve this? I work in iPynb, Python 3.5, matplotlib version 2.1.0.
score: 0
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/82391504
tagged with: python
tagged with: dictionary
favorite count: 0
type: Question
answer count: 0
type: UnansweredQuestion
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/82391451
has title: Matplotlib: when plotting dict, not all values are plotted

http://stackoverflow.com/comment/82561022
type: Comment
type: QuestionComment
has text: @ronganjosh Meh well if you want to do that much debug statements I suppose thats a personal choice, but my point was that it would have to be a TON of logging before its going to be the bottle neck in your process. If you program spends more time logging then anything else, then I think you are logging too much.
comment on: http://stackoverflow.com/q/47797507
score: 1

http://stackoverflow.com/q/47781679
has comment: http://stackoverflow.com/comment/82525051
has answer: http://stackoverflow.com/a/47781937
answer count: 3
score: 1
has comment: http://stackoverflow.com/comment/82524931
tagged with: authentication
upvote count: 1
has comment: http://stackoverflow.com/comment/82524951
linked to: http://stackoverflow.com/q/1369526
tagged with: append
favorite count: 0
type: Question
has title: How can i create a login with a text file
has body: So I've been trying to create a quiz where you have to have an account which means you can register and login. I managed to code the register part(which i'm pretty proud of) and it saves the login details to a separate text file, when it saves the login details it looks like this: username:password Now i'm struggling with the login part, I think you have to read the text file and then split the username and password, then I some how have to compare the inputted username and password to the saved ones. This is what I done for the login part so far but it doesn't work: def login(): filename = 'Accounts.txt' openfile = open('Accounts.txt', "r") Userdata = openfile.readlines() with open('Accounts.txt', 'r') as file: for line in file: user2, passw = line.split(':') login2 = input("Enter username: ") passw2 = input("Enter passwordd: ") if login2 == user2 and passw2 == passw: print("Logged in") else: print("User or password is incorrect!") openfile.close(); Now this is how the whole code looks like(if needed): import time print("Welcome to my quiz") #Creating username def create(): print ("We will need some information from you!") time.sleep(1) Veri = input("Would you like to continue (yes or no): ") def createAccount(): while True: name = input("Enter your first name: ") if not name.isalpha(): print("Only letters are allowed!") else: break while True: surname = input("Enter your surname: ") if not surname.isalpha(): print("Only letters are allowed!") else: break while True: try: age = int(input("Enter your age: ")) except ValueError: print("Only numbers are allowed!") continue else: break if len(name) &gt;= 3: username = name[0:3]+str(age) elif len(surname) &gt;= 3: username = surname[0:3]+str(age) else: username = input("Create a username: ") print ("Your username is:",username) while True: password = input("Create a password: ") password2 = input("Confirm your password: ") if password != password2: print("Password does not match!") else: break account = '%s:%s\n'%(usern…
has answer: http://stackoverflow.com/a/47781809
type: UnansweredQuestion
downvote count: 0
tagged with: python
has answer: http://stackoverflow.com/a/47782145
tagged with: logging

http://stackoverflow.com/comment/82423835
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47714013
score: 0
has text: when I tried this solution with a bigger data set it only returns only the last object instead of all of the objects it looped through. I am thinking its because reduce only returns a single value. I switched reduce with a map and it didn't work either

http://stackoverflow.com/a/47758975
type: Answer
score: 3
upvote count: 3
downvote count: 0
has body: I hope this program will help. import pygame,sys from pygame.locals import * pygame.init() screen = pygame.display.set_mode((400,400)) white=(255,255,255) blue=(0,0,255) bright_red = (255,0,0) red = (200,0,0) black=(0,0,0) color=white def changecolor(newcolor): global color color=newcolor while True: screen.fill(color) for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() elif event.type == MOUSEBUTTONUP: # Whenever somebody clicks on the screen the color # will change from the initial color to the color # value you send to the function. Using this you could # make it specifically for your button. Like calling # the change color function whenever the button is clicked. changecolor(blue) pygame.display.update()
answers question: http://stackoverflow.com/q/47758248

http://stackoverflow.com/comment/82488750
has text: Awesome. Just logon using any SQL client and do a `SELECT * FROM MyTable`. Assuming you're on windows and have access to the Postgres psql client, open a command prompt and connect like so: `psql -W <db_name> <user_name>.` Then put in the password when prompted. You may have to futz around to connect to the correct database/namespace that houses your table. A couple links: https://www.postgresql.org/docs/9.5/static/tutorial-accessdb.html https://www.a2hosting.com/kb/developer-corner/postgresql/connect-to-postgresql-from-the-command-line
score: 0
comment on: http://stackoverflow.com/a/47744840
type: Comment
type: AnswerComment

http://stackoverflow.com/a/49151040
answers question: http://stackoverflow.com/q/47780712
downvote count: 0
score: 1
upvote count: 1
has body: I think you have to delete the file created at ~/.credentials/calendar-python-quickstart.json so the program ask for permissions again
type: Answer

http://stackoverflow.com/comment/82391867
score: 4
has text: Missing a closing `)` after `display_pic(all_pics[7]`
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47715886

enigma-catalyst
type: Tag
tag name: enigma-catalyst
tags question: http://stackoverflow.com/q/47725531

http://stackoverflow.com/comment/82622398
has text: Yes that is possible. A good starting point for an example would be your setup code for one database.
comment on: http://stackoverflow.com/q/47829903
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/q/47711595
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/34540634
tagged with: arrays
tagged with: python
has comment: http://stackoverflow.com/comment/82383223
linked to: http://stackoverflow.com/q/18842779
has comment: http://stackoverflow.com/comment/82383184
linked to: http://stackoverflow.com/q/12648424
has comment: http://stackoverflow.com/comment/82383183
answer count: 0
has title: Python string array without delimiter becomes one single entry
score: 1
duplicate of: http://stackoverflow.com/q/18842779
downvote count: 0
has body: I'm wondering why the following python array is valid (notice the missing comma between 'foo' and 'bar': a = ['hello', 'world', 'foo' 'bar'] Printing 'a' outputs the following: ['hello', 'world', 'foobar'] Why is it even allowed, to omit a comma, if there is at least one comma? I thought there'd be an error like You started the array with comma delimited strings, why on earth are you now, all of a sudden, omitting commas? Are you sure that's not mistake?
upvote count: 1
tagged with: string
duplicate of: http://stackoverflow.com/q/12648424
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82383352

http://stackoverflow.com/comment/82629093
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47833057
score: 5
has text: Try to avoid global and let them be input and output variables

http://stackoverflow.com/q/47775000
downvote count: 0
has body: Is there a way to apply cell format in xlswriter without setting a value? And in terms of worksheet.write use of A1 notation, can it be done to a range? Like: format = workbook.add_format() format.set_border(1) format.set_bold() worksheet.write(row=0, col=0, format=format) worksheet.write('A1:C3', format=format)
accepted answer: http://stackoverflow.com/a/47777797
favorite count: 0
tagged with: excel
has answer: http://stackoverflow.com/a/47777797
type: Question
score: 3
tagged with: python
has title: Is there a way to apply cell format in xlswriter without setting a value?
type: AnsweredQuestion
upvote count: 3
tagged with: xlsxwriter
answer count: 1

http://stackoverflow.com/comment/82629031
comment on: http://stackoverflow.com/q/47833044
type: Comment
type: QuestionComment
has text: @Shiven Singh its a basic binning operation, linked answer above will help
score: 1

http://stackoverflow.com/a/47760649
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82483500
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/47760319
has comment: http://stackoverflow.com/comment/82483250
has body: after() executes function only once and you run some lambda which doesn't uses after() to execute function again. Better use after(2000, blink) and inside blink count how many times it was executed EDIT: you can use two functions with after() blink will use after to call remove and remove will use after to call blink. This way you can use it two different times to display and to hide the number. import tkinter as tk from random import randint def blink(): number.config(text=randint(1,10)) number.after(2000, remove) def remove(): global repeat number.config(text='') repeat -= 1 if repeat &gt; 0: number.after(2000, blink) repeat = 3 root = tk.Tk() number = tk.Label(root, width=20, height=10) number.pack() blink() root.mainloop()
answers question: http://stackoverflow.com/q/47760319
downvote count: 0

http://stackoverflow.com/a/47781368
score: 10
has comment: http://stackoverflow.com/comment/82524274
type: Answer
answers question: http://stackoverflow.com/q/47781324
has comment: http://stackoverflow.com/comment/82524494
accepted answer of: http://stackoverflow.com/q/47781324
has comment: http://stackoverflow.com/comment/82524211
type: AcceptedAnswer
downvote count: 0
upvote count: 10
has body: Output is buffered. You have to flush this buffer: import os import sys print('Hi') sys.stdout.flush() os.system('cat a.py')
has comment: http://stackoverflow.com/comment/82524336

http://stackoverflow.com/a/47761779
upvote count: 2
has comment: http://stackoverflow.com/comment/82486142
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82485902
downvote count: 0
score: 2
has body: In NumPy 1.13, there's the new __array_ufunc__ API. This API is provisional, and backward compatibility is not yet guaranteed. numpy.ndarray delegates to NumPy ufuncs for its operators, and NumPy ufuncs will delegate to __array_ufunc__ to implement ufunc behavior, if they find it. The rules for this skip numpy.ndarray.__array_ufunc__, so if you implement your own __array_ufunc__, it will always take priority when using your instances with NumPy arrays. If you want to disable all ufuncs on your objects, you can set __array_ufunc__ = None on your class: class CustomArray(...): __array_ufunc__ = None Alternatively, if you want to implement it, the signature is def __array_ufunc__(self, ufunc, method, *inputs, **kwargs) where for the case you're interested in, ufunc is the ufunc object (for example, numpy.add for +), method is "__call__", inputs is the tuple (left operand, right operand), and kwargs is empty. For more advanced cases, method, inputs, and kwargs may be different, so return NotImplemented if you don't want to deal with those cases. As an example, if you want to overload + with NumPy arrays, you could write def __array_ufunc__(self, ufunc, method, *inputs, **kwargs): if ufunc is not numpy.add: return NotImplemented if method != "__call__": return NotImplemented if kwargs: return NotImplemented return my_addition_logic(*inputs) You will also still need to implement __add__.
type: Answer
accepted answer of: http://stackoverflow.com/q/47761312
answers question: http://stackoverflow.com/q/47761312

http://stackoverflow.com/comment/82508979
has text: @Dark how exactly?
comment on: http://stackoverflow.com/q/47773706
type: QuestionComment
score: 0
type: Comment

http://stackoverflow.com/comment/82560377
score: 0
has text: I like your answer, and I think it is pretty much the fastest you can do. I will modify the title of the question and give accept your answer.
type: Comment
comment on: http://stackoverflow.com/a/47785005
type: AnswerComment

http://stackoverflow.com/a/47793101
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82548736
has comment: http://stackoverflow.com/comment/82548752
has comment: http://stackoverflow.com/comment/82547773
has comment: http://stackoverflow.com/comment/82547568
has comment: http://stackoverflow.com/comment/82547631
type: Answer
accepted answer of: http://stackoverflow.com/q/47792979
score: 4
upvote count: 4
has comment: http://stackoverflow.com/comment/82547252
answers question: http://stackoverflow.com/q/47792979
has body: data["TX"] &lt; 0 gives you a mask. Make use of this to find the longest sequence of sub-zero temperatures. import pandas as pd data = pd.read_csv("klimaat.csv") i = data['TX'] &lt; 0 j = i.ne(i.shift()).cumsum() freeze = j[i].value_counts().max() The trick here is to get all consecutive groups of True values (corresponding to sub-zero temperatures) and find the largest group. print(freeze) 8 Details i 0 True 1 True 2 True 3 True 4 True 5 True 6 True 7 True 8 False Name: TX, dtype: bool j[i] 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 Name: TX, dtype: int64 j[i].value_counts() 1 8 Name: TX, dtype: int64
has comment: http://stackoverflow.com/comment/82547791
downvote count: 0
has comment: http://stackoverflow.com/comment/82548698

http://stackoverflow.com/q/47745124
tagged with: algorithm
tagged with: if-statement
tagged with: python
score: -1
has body: I'm working on getting the current buy and sell price from a Trading API, compare it to the position I bought in at, then take the appropriate action - sell or buy There are sell and buy prices due to transaction fees There are 5 components: Start buy price where I got the stock Current buy price for the stock Current sell price for the stock Previous buy price (where I bought the stock) Previous sell price (where I sold the stock at) I need to see what the first price change is relative to my start position, if I can buy lower, then buy; if I can sell it for more, sell. But I want to repeat lots and lots of times. So if I bought more, set the previous buy price, then if current sell price rises above that, sell. Then the same on the buy side This is the logic I need help with putting into if statements: Start_buy_price = 100 Start scenario 1: # buy price from start price drops to 90 buy_price = 90: buy_price &lt; start_buy_price: buy! set previous_buy_price = buy_price # price to sell then rises to 95 sell_price = 95 sell_price &gt; previous_buy_price: Sell! set previous_sell_price = sell_price Start scenario 2: # price to sell rises to 105 sell_price = 105 sell_price &gt; start_buy_price: Sell! set previous_sell_price = sell_price # price to buy then falls to 100 buy_price = 100 buy_price &lt; previous_sell_price: Buy! set previous_buy_price = buy_price ---------------------------------------------------------------------- Following run through of the code: Following scenario 1: # price to buy is lower than previous sell price buy_price &lt; previous_sell_price: Buy! set previous_buy_price = buy_price # price to sell is higher than previous buy price sell_price &lt; previous_buy_price: Sell! set previous_sell_price = sell_price repeat! I've been staring at this for about 3 hours now, trying to do it in Python. Here is my code so far: def run_this_code(): start_buy_price = 100 # enter what I bought in at get_buy_price = client.get_buy_price(buy_price) get_sell_pric…
favorite count: 0
type: Question
tagged with: trading
accepted answer: http://stackoverflow.com/a/47811411
answer count: 2
has comment: http://stackoverflow.com/comment/82450293
has answer: http://stackoverflow.com/a/47811411
upvote count: 0
has comment: http://stackoverflow.com/comment/82450333
has title: Python if statements: Trading logic based on my entry position, then setting variables based on action
has comment: http://stackoverflow.com/comment/82450325
possible better answer: http://stackoverflow.com/a/47745173
downvote count: 1
tagged with: logic
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47745173

http://stackoverflow.com/comment/82404821
score: 0
has text: the problem is that if the days are not consecutive (i.e. two odd days in a row) I need to make the second odd day an even day...
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47713771

http://stackoverflow.com/a/47715933
upvote count: 3
type: Answer
has comment: http://stackoverflow.com/comment/122037235
accepted answer of: http://stackoverflow.com/q/47713158
has body: Looking at the source for vscode-python at 0.7.0, on line 30. The message template argument is explicitly overridden. The purpose for this is to keep a consistent API for the result of every specific linter implementation. See the abstract BaseLinter class for this. public runLinter(document: TextDocument, cancellation: CancellationToken): Promise&lt;baseLinter.ILintMessage[]&gt; { ... this.run(pylintPath, pylintArgs.concat(['--msg-template=\'{line},{column},{category},{msg_id}:{msg}\'', '--reports=n', '--output-format=text', document.uri.fsPath]), document, this.workspaceRootPath, cancellation).then(messages =&gt; { messages.forEach(msg =&gt; { msg.severity = this.parseMessagesSeverity(msg.type, this.pythonSettings.linting.pylintCategorySeverity); }); resolve(messages); }, reject); }); } Next Steps here: Write an issue on the repository. Fix the implementation to use pylintArgs over the default.
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47713158
score: 3
has comment: http://stackoverflow.com/comment/82417287

http://stackoverflow.com/comment/82370053
type: AnswerComment
comment on: http://stackoverflow.com/a/47704868
score: 1
type: Comment
has text: @MaxU agree :-)

http://stackoverflow.com/comment/82536722
has text: https://stackoverflow.com/questions/291978/short-description-of-the-scoping-rules
type: QuestionComment
comment on: http://stackoverflow.com/q/47787764
score: 1
type: Comment

http://stackoverflow.com/comment/82543931
has text: @Rahul I think you then don't write unit tests, but integration tests ;) And your team would be well advised to invest into decoupling and provent test-patterns, instead of pointing more guns at their feet, ready to shoot themselves. But that's beyond the scope of this question I agree. Good luck!
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47754262
score: 0

http://stackoverflow.com/q/47779560
upvote count: 3
linked to: http://stackoverflow.com/q/41042042
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/47790514
favorite count: 0
tagged with: plot
has body: I have historical baseball data that I'm trying to visualize in a simple matplotlib plot Within 1 subplot I want to have a table that shows average statistics over the past year, a line chart for each statistic, and then a final score which is calculated independently. I know matplotlib has a table function so it would be simple to create a 5x3 table, but is it possible to insert plots as a value in a table? If not, are there any suggestions on what I should do? I guess I could create several subplots, but formatting would be wacky and not very dynamic. Appreciate the help. Using @TheImportanceofBeingErnest's code, I'm encountering a bug with matplotlib where I can't see the x axis when I use gridspec: fig = plt.figure(figsize=(8.5,11)) gs_row1left = gridspec.GridSpec(1,1) gs_row1right = gridspec.GridSpec(1,1) summaryplot2subplot(fig, gs_row1left[0], data, col1, col2, finalsc) ax.axis('off') ax2 = fig.add_subplot(gs_row1right[0, 0]) df = pd.DataFrame({'year':['2001-01','2002-01','2003-01','2004-01','2005-01'], 'value':[100,200,300,400,500]}) barax = ax2.twinx() df['value1']= df['value']*0.4 df['value2'] = df['value']*0.6# Let them be strings! df.plot(x = ['year'], y = ['value'], kind = 'line', ax = ax2) df.plot(x = ['year'], y= ['value1','value2'], kind = 'bar', ax = barax) gs_row1left.update(left = 0.05, right = 0.48) gs_row1right.update(left = 0.55, right = 0.98) plt.show()
type: AnsweredQuestion
score: 3
tagged with: matplotlib
accepted answer: http://stackoverflow.com/a/47790514
has title: Matplotlib- Creating a table with line plots in cells?
tagged with: python
type: Question
tagged with: pandas

http://stackoverflow.com/a/47715533
downvote count: 0
answers question: http://stackoverflow.com/q/47715486
type: Answer
has body: There are no predefined variables in python. print(a) will return NameError: name 'a' is not defined as long as a has not been defined earlier.
score: 2
upvote count: 2

parsing
tags question: http://stackoverflow.com/q/47708233
tags question: http://stackoverflow.com/q/47766702
tags question: http://stackoverflow.com/q/47724433
tags question: http://stackoverflow.com/q/47834384
tags question: http://stackoverflow.com/q/47839339
tag name: parsing
tags question: http://stackoverflow.com/q/47821563
tags question: http://stackoverflow.com/q/47806393
tags question: http://stackoverflow.com/q/47730785
tags question: http://stackoverflow.com/q/47799742
tags question: http://stackoverflow.com/q/47813330
tags question: http://stackoverflow.com/q/47733402
tags question: http://stackoverflow.com/q/47817395
tags question: http://stackoverflow.com/q/47772094
tags question: http://stackoverflow.com/q/47717038
tags question: http://stackoverflow.com/q/47704190
tags question: http://stackoverflow.com/q/47707008
tags question: http://stackoverflow.com/q/47792217
type: Tag
tags question: http://stackoverflow.com/q/47828176
tags question: http://stackoverflow.com/q/47721929

http://stackoverflow.com/a/56841154
type: Answer
has body: I had the same issue and then solved it by running PyCharm as administrator.
answers question: http://stackoverflow.com/q/47807709
downvote count: 0
upvote count: 1
score: 1

google-oauth
type: Tag
tags question: http://stackoverflow.com/q/47830305
tag name: google-oauth
tags question: http://stackoverflow.com/q/47798220
tags question: http://stackoverflow.com/q/47782592

http://stackoverflow.com/q/47763408
has body: i've seen a lot of people having trouble with this here, and i always see them saying other to use pip3 or just pip to install it. But in my case i've uninstalled it and installed id multiple times both using pip or pip3 and none of them seem to work. I've added 'rest_framework' to my settings as well and still doesn't seem to work. Help me out please EDIT Here is my settings INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'agenda.apps.AgendaConfig', 'rest_framework', ] REST_FRAMEWORK = { # Use Django's standard `django.contrib.auth` permissions, # or allow read-only access for unauthenticated users. 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly' ] } Collecting djangorestframework Downloading djangorestframework-3.7.3-py2.py3-none-any.whl (1.5MB) 100% |████████████████████████████████| 1.5MB 506kB/s Installing collected packages: djangorestframework Successfully installed djangorestframework-3.7.3 Still not working EDIT 2 &gt; Traceback (most recent call last): File &gt; "/usr/local/lib/python2.7/dist-packages/django/utils/autoreload.py", &gt; line 226, in wrapper &gt; fn(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/runserver.py", &gt; line 121, in inner_run &gt; self.check(display_num_errors=True) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", &gt; line 374, in check &gt; include_deployment_checks=include_deployment_checks, File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", &gt; line 361, in _run_checks &gt; return checks.run_checks(**kwargs) File "/usr/local/lib/python2.7/dist-packages/django/core/checks/registry.py", &gt; line 81, in run_checks &gt; new_errors = check(app_configs=app_configs) File "/usr/local/lib/python2.7/dist-packages/django/core/checks/urls.py", &gt; line 14…
tagged with: pip
has comment: http://stackoverflow.com/comment/82489180
tagged with: django
tagged with: python
tagged with: django-rest-framework
has comment: http://stackoverflow.com/comment/82492698
has comment: http://stackoverflow.com/comment/82488457
has comment: http://stackoverflow.com/comment/82488545
upvote count: 2
score: 2
has comment: http://stackoverflow.com/comment/82489063
has answer: http://stackoverflow.com/a/47771959
has comment: http://stackoverflow.com/comment/82488995
has title: No module named rest_framework
answer count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/82488799
has comment: http://stackoverflow.com/comment/82488622
has comment: http://stackoverflow.com/comment/82489001
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82488588
has comment: http://stackoverflow.com/comment/82488418
has comment: http://stackoverflow.com/comment/82489010
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82488278
has answer: http://stackoverflow.com/a/74242697
has answer: http://stackoverflow.com/a/47763825
has comment: http://stackoverflow.com/comment/82488853

http://stackoverflow.com/q/47763066
has body: I'm using a popup as a pause menu in my kivy app. But I can't figure out how to change screens with it. I tried root.manager.current but that didn't work since my popup widget isn't a screen. I also tried to create a function in python using self.manager.current but alas that did not work either. This is the only idea I can think of now but it doesn't work either. Any and all help is appreciated. python snippet class PausePopup(Popup): pass class MahScreenManager(ScreenManager): pass class MahMenu(Screen): pass class MahGame(Screen): class MahGameApp(App): def build(self): window_color = get_color_from_hex("#eaeaea") Window.clearcolor = window_color return MahScreenManager() MahGameApp().run() kv &lt;MahScreenManager&gt;: MahMenu: name: "menu" id: menu MahGame: name: "game" id: game &lt;PausePopup&gt;: title: "Gahme is paused" size_hint: .5, .7 BoxLayout: orientation: "vertical" padding: 10 spacing: 10 Button: text: "Continue" on_release: root.dismiss() Button: text: "Settings" on_release: app.open_settings() Button: text: "Main Menu" on_release: Factory.MahGame().current = "menu" &lt;MahMenu&gt;: BoxLayout: padding: 50 spacing: 25 orientation: "vertical" Button: text: "Start Mah Gahme" on_release: root.manager.transition.direction = "left" root.manager.current = "game" Button: text: "Quit" on_release: app.stop() &lt;MahGame&gt;: Button: text: "Pause" size_hint: 0.1, 0.1 on_release: Factory.PausePopup().open()
has title: How to change screen with a popup widget in kivy?
tagged with: python
tagged with: kivy
type: AnsweredQuestion
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/47763151
accepted answer: http://stackoverflow.com/a/47763151
type: Question
tagged with: kivy-language

http://stackoverflow.com/q/47773706
has comment: http://stackoverflow.com/comment/82509069
has comment: http://stackoverflow.com/comment/82508979
answer count: 2
accepted answer: http://stackoverflow.com/a/47774915
has title: Creating a numpy array from list of lists, with various data types
has comment: http://stackoverflow.com/comment/82509010
possible better answer: http://stackoverflow.com/a/57613081
has comment: http://stackoverflow.com/comment/82508964
has comment: http://stackoverflow.com/comment/82509106
has comment: http://stackoverflow.com/comment/82510172
tagged with: arrays
tagged with: python
has comment: http://stackoverflow.com/comment/82510115
has answer: http://stackoverflow.com/a/57613081
type: AnsweredQuestion
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/82509316
has comment: http://stackoverflow.com/comment/82508943
has body: I'd like to create a numpy array with a list of lists. The data type should be float, float, string. Why doesn't this work? (Note: I already read this question). import numpy print numpy.array([[u'1.2', u'1.3', u'hello'], [u'1.4', u'1.5', u'hi']], dtype='f,f,str') Output: [[(4.2245014868923476e-39, 7.006492321624085e-44, '') (4.2245014868923476e-39, 7.146622168056567e-44, '') (9.275530846997402e-39, 9.918384925297198e-39, '')] [(4.2245014868923476e-39, 7.286752014489049e-44, '') (4.2245014868923476e-39, 7.42688186092153e-44, '') (9.642872831629367e-39, 0.0, '')]]
score: 0
has answer: http://stackoverflow.com/a/47774915
linked to: http://stackoverflow.com/q/32304370
has comment: http://stackoverflow.com/comment/82509364
has comment: http://stackoverflow.com/comment/82519332
type: Question
has comment: http://stackoverflow.com/comment/82509399
tagged with: numpy

http://stackoverflow.com/comment/82594378
comment on: http://stackoverflow.com/a/47815286
has text: Yes, that would work, but you wouldn't be very specific on where to but the actual marker... Say I want a marker on 'a3', then I would need to guess what my y-value would be. Right?
score: 1
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/82408911
comment on: http://stackoverflow.com/a/47724064
type: Comment
has text: Ah, ok. I think I get it. I'll try it out now and see if it works.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/82646077
type: Comment
comment on: http://stackoverflow.com/a/47731429
has text: If you have not yet, copy these [125k words, sorted by frequency](http://pasted.co/c1666a6b) into a text file and put the file in the same folder as your Python file.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/82428133
comment on: http://stackoverflow.com/a/47733762
type: AnswerComment
has text: In your `str.format()` example, at least use the `:d` format specifier if you are going to make it equivalent to the printf-style template.
score: 1
type: Comment

http://stackoverflow.com/q/47740102
has comment: http://stackoverflow.com/comment/82445228
score: -1
tagged with: pandas
has comment: http://stackoverflow.com/comment/82440944
linked to: http://stackoverflow.com/q/20109391
answer count: 1
has comment: http://stackoverflow.com/comment/82444826
has title: How to use Pandas to get the Top5 occurance of the numbers from CSV
downvote count: 1
favorite count: 0
type: Question
has body: I use the following python code to read a CSV with 50K rows. Every row has a 4 digit code, for example '1234'. import csv import pandas as pd import re df = pd.read_csv('Parkingtickets.csv', sep=';',encoding='ISO-8859-1') df['Parking tickets'] I would like to sort the code and get the count of the top 5 occurrence of the same code. codes = df['Parking tickets'] Counter(codes).most_common(5) With this is got kind of what I'm looking for, but it doesn't count only the digit codes and some may have two codes in the same row. How can I use "re.findall(r'\d{4}')"? I know I need to use it, but don't understand how to implement it.
upvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82441122
tagged with: python
has answer: http://stackoverflow.com/a/47742670
tagged with: sorting

http://stackoverflow.com/comment/82525480
has text: I edited my initial post, thank you for the clarifying question.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47781374

http://stackoverflow.com/comment/82595360
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47816813
type: QuestionComment
has text: I don't want to include the value if my Key already has this value.

http://stackoverflow.com/comment/82357837
type: QuestionComment
comment on: http://stackoverflow.com/q/47698771
score: 2
has text: But where did you get those trig functions? There's no `import` statement in the code you posted.
type: Comment

http://stackoverflow.com/a/47740749
answers question: http://stackoverflow.com/q/47740673
score: 0
upvote count: 1
downvote count: 1
has body: It looks to me like the web page you're trying to access requires authentication. If so, you'll have to figure out how to programmatically log in to the site before going to the page you want. Trying to manually go to that URL, I get the following in my browser: { "finance": { "error": { "code": "Unauthorized", "description": "Invalid cookie" } } }
type: Answer

http://stackoverflow.com/a/47790260
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47787955
accepted answer of: http://stackoverflow.com/q/47787955
upvote count: 1
score: 1
type: Answer
has body: It appears that your code page is set to cp437. Try setting python output to utf-8 by entering the following line in your terminal before running your python script. set PYTHONIOENCODING=UTF-8 python core-backup.py
downvote count: 0

http://stackoverflow.com/a/47812118
has comment: http://stackoverflow.com/comment/82586273
has comment: http://stackoverflow.com/comment/82585681
upvote count: 2
has comment: http://stackoverflow.com/comment/82585571
type: Answer
has comment: http://stackoverflow.com/comment/82586376
accepted answer of: http://stackoverflow.com/q/47811663
score: 2
answers question: http://stackoverflow.com/q/47811663
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82586127
has comment: http://stackoverflow.com/comment/82586433
has comment: http://stackoverflow.com/comment/82586259
has body: You can fetch only the htmlfield value with: Htmlfiles.objects.values('htmlfile') Which, for each row, will give you an dictionary like so: {'htmlfile': 12345} So to print all the htmlfile values something like this is what you need: objects = Htmlfiles.objects.values('htmlfile') for obj in objects: print(obj['htmlfile'])

http://stackoverflow.com/q/47733013
tagged with: django
answer count: 1
has title: Passing table values from template to view
type: Question
tagged with: http://stackoverflow.com/tag/html
tagged with: python
accepted answer: http://stackoverflow.com/a/47733149
has body: I have template with table which is dynamically created by javascript. Then I want retrieve with submit button only value within &lt;td name="plu"&gt;&lt;/td&gt; tags and process it in view to save as json into CharField in model. I tried to use form tag with method post and request.POST.get('plu') in view but it won't work. I want to get that values and then process it with model methods. Here are parts of code: @login_required() def cash_register(request): """plus = [123,345,567] newtrans = Transaction() newtrans.set_plu_list(plus) newtrans.save()""" if request.method == 'POST': x = request.POST.get('plu', False) # ??? try: products = Product.objects.all().values_list('plu_num', 'art_name', 'sales_price_brutto') products_json = json.dumps(list(products), cls=DjangoJSONEncoder) except Product.DoesNotExist: raise Http404('Products cant\'t be found!') return render(request, 'panel/cash_register.html', {'products_json': products_json}) class Transaction(models.Model): plu_list = models.CharField(max_length=255) transaction_date = models.DateField(auto_now_add=True) is_ksk = models.BooleanField(default=False) ksk_num = models.IntegerField(null=True) def set_plu_list(self, x): self.plu_list = json.dumps(x) def get_plu_list(self): return json.loads(self.plu_list) And html: https://pastebin.com/RFn5qNn2
has answer: http://stackoverflow.com/a/47733149
type: AnsweredQuestion
score: 0

http://stackoverflow.com/a/62822257
upvote count: 2
type: Answer
score: 2
has body: You can follow the Guide on how to plot images from Canada which is explained here: Python: how to create a choropleth map out of a shapefile of Canada? Afterwards, you need to replace the geo pandas shape file with German shapes. You can obtain these and add to geopandas as described here: https://juanitorduz.github.io/germany_plots/
downvote count: 0
answers question: http://stackoverflow.com/q/47740200

http://stackoverflow.com/a/47765819
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47765195
has body: Because the input field you are trying to fill in is within iframe. First switch it and then try to do what you did earlier: import time from selenium import webdriver from selenium.webdriver.common.keys import Keys driver = webdriver.Chrome() driver.get('http://www.techfetch.com/JS/dashboard.aspx?page=fetchjobs') time.sleep(5) driver.switch_to_frame(driver.find_element_by_id("contentframe")) ##switch it driver.find_element_by_xpath('//*[@id="txtKeyword"]').send_keys("Java")
type: Answer
accepted answer of: http://stackoverflow.com/q/47765195

http://stackoverflow.com/a/47818328
has body: You're current code adds a ', ' after every element so of course there will be one at the end. The str.join(sep, it) method only puts the sep string in between each element of it. So replace for re in assignments[i]: timetable.write(str(re)+', ') with timetable.write(', '.join(map(str, assignments[i]))) For the record, never do for i in range(len(assignments)): do_something(assignments[i]) instead do for assignment in assignments: timetable.write(', '.join(map(str, assignment))) If you need the indices of assignments, use enumerate.
answers question: http://stackoverflow.com/q/47818281
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/82600751
score: 3
type: Answer
has comment: http://stackoverflow.com/comment/82600325

http://stackoverflow.com/comment/82613748
type: QuestionComment
has text: Yeah that's what I was checking. Call it outside the context of running test!. What i thought is to have something like import 'keywordfile.txt' , call keyword ("Keyword name", parameters)
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47805772

http://stackoverflow.com/comment/82583135
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47810702
has text: Thx :) dealt with that ~

http://stackoverflow.com/comment/82623569
comment on: http://stackoverflow.com/a/47830438
type: Comment
has text: I think so too, but thanks for the effort and solution :)
score: 0
type: AnswerComment

http://stackoverflow.com/a/47804858
score: 4
type: Answer
has body: Since there hasn't been any movement on this question, I'll just post my own workaround to this problem. Basically the loader process was shutting down the que after it finished processing and queuing up the examples. It wasn't waiting for the trainer process to finish, so when the trainer process was going to get the next minibatch, it couldn't find it. I don't quite know why the loader process was prematurely shutting down the que, the documentation for que.close() says that this should only tell the que no more objects are being sent to the que, but it shouldn't actually shut down the que. Also, deleting que.close() did not solve the issue, so I don't think the error had to do with that command. What solved this issue for me was putting a time.sleep(2) command after the que.close() command. This forces the que to sleep for a couple of seconds after it finishes putting everything in the que, and it allows the program to complete and exit without error.
answers question: http://stackoverflow.com/q/47762973
upvote count: 4
downvote count: 0
has comment: http://stackoverflow.com/comment/137301675

http://stackoverflow.com/a/47829621
score: 2
upvote count: 2
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47829248
downvote count: 0
has body: The first two arguments get assigned to the x and y attributes of the rect, the coordinates of the topleft corner. So if you want to create a rect that is positioned at the coordinates (200, 300), you can write: rect = pygame.Rect(200, 300, 40, 50). The third and fourth argument are indeed the dimensions of the resulting rect instance. pygame.Rects also have a lot of other attributes which you can use to position your rect. x,y top, left, bottom, right topleft, bottomleft, topright, bottomright midtop, midleft, midbottom, midright center, centerx, centery If you want to move a rect, you can assign the new position to the x, y, topleft or one of the other attributes. rect.x = 5 rect.y = 10 # That's pretty much the same as writing: rect.topleft = (5, 10) # You can also increment the position. rect.x += 5 # Or use the `rect.move_ip` method. rect.move_ip(5, 10) Rects are used to store the blit position of sprites or images and for collision detection, for example with the colliderect or collidepoint methods.
accepted answer of: http://stackoverflow.com/q/47829248
type: Answer

http://stackoverflow.com/q/47838328
has answer: http://stackoverflow.com/a/47847239
has body: How to draw a graph with vertices and edges of different sizes? I'm using ipython and holoviews library. For instance, Edges input start,ends 1,4 2,4 3,5 3,6 2,6 Nodes input x,y,index,type 0.0,1.0,1,a 0.5,1.0,2,a 1.0,1.0,3,a 0.4,0.0,4,b 0.5,0.0,5,b 0.6,0.0,6,b main.py import numpy as np import pandas as pd import holoviews as hv import networkx as nx from holoviews.operation.datashader import datashade, bundle_graph hv.extension('bokeh') %opts Nodes Graph [width=800 height=200 xaxis=None yaxis=None] %opts Graph (node_size=8 edge_line_width=0.5) colors = ['#000000']+hv.Cycle('Category20').values edges_df = pd.read_csv('edges.csv') nodes = hv.Nodes(pd.read_csv('nodes.csv')).sort() graph = hv.Graph((edges_df, nodes)) graph = graph.redim.range(x=(-0.05, 1.05), y=(-0.05, 1.05)).opts(style=dict(cmap=colors)) bundled = bundle_graph(graph) bundled Output I tried to modify this lines: node_size=[3,4,5,8,3,8] edge_size=[0.5,0.6,0.8,1.5,0.5] %opts Graph (node_size=node_size edge_line_width=edge_size) However, this is not working. Can anyone help me? How to create nodes and edges of different sizes?
possible better answer: http://stackoverflow.com/a/47847239
tagged with: ipython
has answer: http://stackoverflow.com/a/47868358
accepted answer: http://stackoverflow.com/a/47868358
type: Question
tagged with: graph
tagged with: holoviews
tagged with: python
has title: How to draw graphs with vertices and edges of different sizes using the holoviews library?
type: AnsweredQuestion
score: 0
answer count: 2

http://stackoverflow.com/q/47802360
has body: This python code is ramdomly generating "PerfectSeparationError". This is a group a 50 random[-2 to 2] points centered [-2,2] and 50 random[-2 to 2] centered [2,2]. First 50 is assigned to 0 and the result to 1. I do not understand why this error occurs, I think points are enough separated to get a result import numpy as np import matplotlib.pyplot as plt import pandas as pd import statsmodels.api as sm from scipy import stats stats.chisqprob = lambda chisq, df: stats.chi2.sf(chisq, df) N = 100 D = 2 X = np.random.randn(N,D) # center the first 50 points at (-2,-2) X[:50,:] = X[:50,:] - 2*np.ones((50,D)) # center the last 50 points at (2, 2) X[50:,:] = X[50:,:] + 2*np.ones((50,D)) # labels: first 50 are 0, last 50 are 1 T = np.array([0]*50 + [1]*50) # add a column of ones y = pd.Series(T.tolist()) Xb = pd.concat([pd.Series(X[:,0].tolist()), pd.Series(X[:,1].tolist())], axis=1) logit_model=sm.Logit(y,Xb) result=logit_model.fit() print(result.summary()) Whats the reason that randomy shows: "PerfectSeparationError: Perfect separation detected, results not available"?
score: 0
has title: Why this Logit example randomly generating "PerfectSeparationError: Perfect separation detected, results not available"
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82574137
tagged with: python
has comment: http://stackoverflow.com/comment/82566195
tagged with: statsmodels
answer count: 0

http://stackoverflow.com/q/47733250
has answer: http://stackoverflow.com/a/47733285
tagged with: python
has title: python - splitting huge list in multiple lists; loop over each of them
has comment: http://stackoverflow.com/comment/82427156
linked to: http://stackoverflow.com/q/47680897
has comment: http://stackoverflow.com/comment/82427121
has comment: http://stackoverflow.com/comment/82427183
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82427256
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/82427211
has comment: http://stackoverflow.com/comment/82427151
tagged with: subset
accepted answer: http://stackoverflow.com/a/47733426
tagged with: loops
has answer: http://stackoverflow.com/a/47733426
has body: In reference to this question of mine, I realized that the corpus is too big and needs be split up in multiple mini-lists before going through the levenshtein calculations. The following code is my simple attempt, but I was wondering if there's a more elegant way to do it: import csv#, StringIO import itertools, Levenshtein # open the newline-separated list of words path = '/Users/path/' file = path + 'wordlist.txt' output1 = path + 'ortho1.csv' output2 = path + 'ortho2.csv' output3 = path + 'ortho3.csv' output4 = path + 'ortho4.csv' output5 = path + 'ortho5.csv' output6 = path + 'ortho6.csv' words = sorted(set(s.strip() for s in open(file))) # words is a list with 16349, so I split it in to 6 mini lists verbs1 = words[:3269] verbs2 = words[3269:13080] verbs3 = words[13081:9811] verbs4 = words[9812:6542] verbs5 = words[6543:3273] verbs6 = words[3274:len(words)] For each of the above lists, I then compute the following loop: with open(output1, 'wb') as f: writer = csv.writer(f, delimiter=",", lineterminator="\n") for a, b in itertools.product(verbs1, words): if (a &lt; b and Levenshtein.distance(a,b) &lt;= 5): writer.writerow([a, b, Levenshtein.distance(a,b)]) Again, everything works, but I was wondering there's a more elegant way to code a single loop for each of the mini-lists.
type: Question
linked to: http://stackoverflow.com/q/24527006
possible better answer: http://stackoverflow.com/a/47733285

http://stackoverflow.com/q/47761782
favorite count: 0
has comment: http://stackoverflow.com/comment/82485216
has comment: http://stackoverflow.com/comment/82485267
tagged with: python-3.x
type: Question
score: 5
has comment: http://stackoverflow.com/comment/82485169
type: UnansweredQuestion
tagged with: python
has body: import pandas as pd import matplotlib.pyplot as plt from PIL import Image import numpy as np import wordcloud from wordcloud import WordCloud,STOPWORDS # Read the whole text. remarks = open(r'C:\Users\marmar\Documents\Remarks.txt').read() #Create words over an image mask = np.array(Image.open(r'C:\users\marmar\Documents\cloud.png')) #set the stopwords list stopwords= set(STOPWORDS) #append new words to the stopwords list new_words =open(r'C:\Users\marmar\comments.txt').read() new_stopwords=stopwords.union(new_words) #generate the word cloud with parameters wc = WordCloud(background_color="white", max_words=2000, mask=mask, min_font_size =12, max_font_size=20, relative_scaling = 0.5, stopwords=new_stopwords, normalize_plurals= True) wc.generate(remarks) plt.figure(figsize=(25,25)) plt.imshow(wc, interpolation="bilinear") plt.axis("off") #Show the wordcloud plt.show() Basically, I'm using Python 3 ( Jupyter Notebook) to create a wordcloud with an actual cloud picture. WordCloud packages actually has its own stopwords function. However, i want to include some words in the stopwords list that I don't want to see in my cloud. I tried to include some words in that text file, but I can see the words in my cloud. For example the text file looks like : customer, CSR Customer, satisfied, Item Completed How do I go about adding more words to the list. I tried add, append, both of these functions and they won't work. Thank you in advance.
answer count: 1
downvote count: 1
upvote count: 6
tagged with: word-cloud
has comment: http://stackoverflow.com/comment/82485172
has comment: http://stackoverflow.com/comment/82485107
has title: How do I remove words from my wordcloud? (Python 3)
has answer: http://stackoverflow.com/a/47762075
has comment: http://stackoverflow.com/comment/82485109

http://stackoverflow.com/comment/82379874
has text: Are you sure [`\s([a-zA-Z0-9]+)=(['"]?)(.*?)\2(?!\S)`](https://regex101.com/r/vGcyYC/1) is not enough? If not, use something like [`\s([a-zA-Z0-9]+)=(?:(['"])(.*?)\2|\S+)(?!\S)`](https://regex101.com/r/vGcyYC/2). See [**this Python demo**](https://ideone.com/67QUBs).
comment on: http://stackoverflow.com/q/47705710
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/82547748
has text: if you inherit from other class - ie. `class OptionMenu(tk.Frame)` - then you have to use `super().__init__()` to execute original `__init__()` - ie. `tk.Frame.__init__()` which does many important things.
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/47778664
type: Comment

http://stackoverflow.com/comment/82592072
score: 0
type: Comment
type: QuestionComment
has text: In the current state, we are searching for an appropriate built-in function. We know how to determine the amount of the values with collections.counter, but it does not help us to determine the length if an list is interruptet, e.G. 3 Times a 'B' and then a 'W'. Moreover, our teacher told us to use for this part of the work less than 25 lines
comment on: http://stackoverflow.com/q/47814968

http://stackoverflow.com/comment/122963905
score: 0
type: Comment
has text: @jtlz2 Referring to loading the `training.log` file with `csv`? You should be able to find something in the [python documentation](https://docs.python.org/3/library/csv.html). There's a useful example at the top. As for the other question - I believe it warrants opening a new SO question.
type: AnswerComment
comment on: http://stackoverflow.com/a/51945256

http://stackoverflow.com/a/47777866
upvote count: 1
downvote count: 1
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/82540071
answers question: http://stackoverflow.com/q/47777585
has body: Sadly, your method won't work because the angle you calculate by this method is only the actual angle if the camera is held exactly perpendicular to the plane of the joint. You need a reference square in your images in order to be able to calculate the angle at which the camera is held so as to be able to correct for the camera angle. And the reference square has to be placed on the same flat surface as the pipe joint.

http://stackoverflow.com/a/47722943
type: Answer
score: 2
has body: You could add all the outputs to a list: self.outputs = [self.output0, self.output1, self.output2] #etc... And then loop through them: for output in self.outputs: output.delete(0, END) #etc... You can even create outputs like such: self.outputs = [] for i in range(4): output = tk.Entry( self, width=149, justify='center', bd='0', bg='#E0E0E0' ) output.grid(column=0, row=6, columnspan=5, padx=1) self.outputs.append(output) Though you would need to add a way to change the row number and whatever else needs to be different for each iteration.
downvote count: 0
answers question: http://stackoverflow.com/q/47722877
upvote count: 2

http://stackoverflow.com/q/47728607
answer count: 1
tagged with: containers
tagged with: python
tagged with: spring
tagged with: docker
tagged with: rest
downvote count: 0
has title: Spring Boot Application which triggers another App with CLI
has body: I am currently developing a Spring Boot Application which triggers a Python program via CLI. I've used Processbuilder to do that and it's been working ok so far. Now I'm trying to get the Spring Boot Application and the Python program in a Docker container. Since I'm new to Docker I don't know the best way to do this. I've tried using COPY to copy the whole folder to create an image but for some reason the folder pythonapp in the Container is always empty. Am I missing something or is there a better way to do this? FROM openjdk:8u151-jdk-slim EXPOSE 8080 ADD springbootapp-0.0.1.jar app.jar COPY . /root/pythonapp RUN sh -c 'touch /app.jar' RUN apt-get update &amp;&amp; apt-get install -y python \ python-gi \ gir1.2-gtk-3.0 ENV JAVA_OPTS="" ENTRYPOINT [ "sh", "-c", "java $JAVA_OPTS -Djava.security.egd=file:/dev/./urandom -jar /app.jar" ]
score: 1
upvote count: 1
favorite count: 0
type: Question
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47728654

http://stackoverflow.com/q/47780904
tagged with: sensors
has title: How to remove consecutive bad data points in Pandas
downvote count: 0
favorite count: 0
type: Question
tagged with: time-series
tagged with: pandas
has body: I have a Pandas dataframe that looks like: import pandas as pd import numpy as np df = pd.DataFrame({"Dummy_Var": [1]*12, "B": [6, 143.3, 143.3, 143.3, 3, 4, 93.9, 93.9, 93.9, 2, 2, 7], "C": [4.1, 23.2, 23.2, 23.2, 4.3, 2.5, 7.8, 7.8, 2, 7, 7, 7]}) B C Dummy_Var 0 6.0 4.1 1 1 143.3 23.2 1 2 143.3 23.2 1 3 143.3 23.2 1 4 3.0 4.3 1 5 4.0 2.5 1 6 93.9 7.8 1 7 93.9 7.8 1 8 93.9 2.0 1 9 2.0 7.0 1 10 2.0 7.0 1 11 7.0 7.0 1 Whenever the same numbers show up consecutively three times or more in a row, that data should be replaced with NAN. So the result should be: B C Dummy_Var 0 6.0 4.1 1 1 NaN NaN 1 2 NaN NaN 1 3 NaN NaN 1 4 3.0 4.3 1 5 4.0 2.5 1 6 NaN 7.8 1 7 NaN 7.8 1 8 NaN 2.0 1 9 2.0 NaN 1 10 2.0 NaN 1 11 7.0 NaN 1 I have written a function that does that: def non_sense_remover(df, examined_columns, allowed_repeating): def count_each_group(grp, column): grp['Count'] = grp[column].count() return grp for col in examined_columns: sel = df.groupby((df[col] != df[col].shift(1)).cumsum()).apply(count_each_group, column=col)["Count"] &gt; allowed_repeating df.loc[sel, col] = np.nan return df df = non_sense_remover(df, ["B", "C"], 2) However, my real dataframe has 2M rows and 18 columns! It is very very slow to run this function on 2M rows. Is there a more efficient way to do this? Am I missing something? Thanks in advance.
tagged with: python
accepted answer: http://stackoverflow.com/a/47781099
score: 4
has answer: http://stackoverflow.com/a/47781099
upvote count: 4
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/47392758
possible better answer: http://stackoverflow.com/a/47781150
answer count: 3
has answer: http://stackoverflow.com/a/47781102
has answer: http://stackoverflow.com/a/47781150

http://stackoverflow.com/a/47779635
has body: You are fitting a function gaussFunction that does not care whether sigma is positive or negative. So whether you get a positive or negative result is mostly a matter of luck, and taking the absolute value of the returned sigma is fine. Also consider other possibilities: (Suggested by Thomas Kühn): modify the model function so that it cares about the sign of sigma. Bringing it closer to the normalized Gaussian form would be enough: the formula A/np.sqrt(sigma)*np.exp(-(x-mu)**2/(2.*sigma**2)) would ensure that you get positive sigma only. A possible, mild downside is that the function takes a bit longer to compute. Use the variance, sigma_squared, as a parameter: A, mu, sigma_squared = p return A*np.exp(-(x-mu)**2/(2.*sigma_squared)) This is probably easiest in terms of keeping the model equation simple. You will need to square your initial guess for that parameter, and take square root when you need sigma itself. Aside: you hardcoded 0.1 as a guess for standard deviation. This probably should be based on data, like this: peak = X[Y &gt; np.exp(-0.5)*Y.max()] guess_sigma = 0.5*(peak.max() - peak.min()) The idea is that within one standard deviation of the mean, the values of the Gaussian are greater than np.exp(-0.5) times the maximum value. So the first line locates this "peak" and the second takes half of its width as the guess for sigma. For the above to work, X and Y should be already converted to NumPy arrays, e.g., X = np.array([16.4697402328,16.4701402404,..... This is a good idea in general: otherwise, you are making each NumPy method that receives X or Y make this conversion again.
answers question: http://stackoverflow.com/q/47773178
type: Answer
has comment: http://stackoverflow.com/comment/82543906
type: AcceptedAnswer
downvote count: 0
score: 6
accepted answer of: http://stackoverflow.com/q/47773178
upvote count: 6

http://stackoverflow.com/comment/82787508
comment on: http://stackoverflow.com/a/47794982
has text: The problem is that is saves full html page, but I need only upper part of it and I obviously can't load full page and then crop upper part for performace reasons. Test url: `https://github.com/keras-team/keras/issues/3223`
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47761528
accepted answer: http://stackoverflow.com/a/47761613
favorite count: 0
type: Question
tagged with: radix
has comment: http://stackoverflow.com/comment/82484509
has answer: http://stackoverflow.com/a/47761613
has comment: http://stackoverflow.com/comment/82484533
has comment: http://stackoverflow.com/comment/82485435
has comment: http://stackoverflow.com/comment/82485215
has comment: http://stackoverflow.com/comment/82484744
tagged with: python
has body: I'm trying to make a function that takes in a number in base 10 and can be changed to any base from 2 though 9. I'm trying to only use the math module and just some simple math. My code involves strings and I would like to eliminate them, and instead have the function do some math instead of using the numbers in a string. Also I'm trying to make the output integers. def conver(n,b): digits = ('0123456789') ans = "" while n &gt; 0: ans = digits[n%b] + ans n //= b return ans For example the user could in put in the values (14,2) and get the output 1110
has comment: http://stackoverflow.com/comment/82484694
has comment: http://stackoverflow.com/comment/82485130
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82485289
has comment: http://stackoverflow.com/comment/82484875
has title: Converting a base 10 number to any base without strings
linked to: http://stackoverflow.com/q/2267362
has comment: http://stackoverflow.com/comment/82484410
has comment: http://stackoverflow.com/comment/82484852
upvote count: 3
has comment: http://stackoverflow.com/comment/82485068
answer count: 1
has comment: http://stackoverflow.com/comment/82484724
downvote count: 1
has comment: http://stackoverflow.com/comment/82484484

http://stackoverflow.com/q/47855193
upvote count: 0
answer count: 2
downvote count: 2
has comment: http://stackoverflow.com/comment/82674965
has title: Beginner in Python: Directory help needed
has comment: http://stackoverflow.com/comment/82674918
has comment: http://stackoverflow.com/comment/82674746
favorite count: 0
has comment: http://stackoverflow.com/comment/82674676
has body: What I want to do here is that I want to create a list 'image_paths' which contains the path for all the .pgm files (except the 3.pgm file that I wish to use as a test image for the facial recognition program). For the images except '3.pgm' I want to superimpose them and for this I used one of the pictures from the database '8.pgm' as a base image, over which I applied the addWeighted() function which iterates through each of the paths in the image_paths list and keeps on adding each image over the base_image. I use the resize() in the for loop to keep the size of the images same. I am using the AT&amp;T facial database which has the format of .pgm files. What I am facing the issue is in the path line of code. Where I create a list of the paths of each .pgm file. import cv2 import numpy as np import os path=['test/'] #Appends all paths of images in the list image_paths. **I am facing error in this line of code** image_paths = [os.path.join(path, f) for f in os.listdir(path) if not f.endswith('2.pgm')] #initializing a base_image over which other images will be superimposed base_image=cv2.imread('8.jpg') #resizing the base image so it matches the size of the database pics (113(rows),97(columns)) base_image=cv2.resize(base_image,(97,113)) #cv2.imshow('lol',base_image) //for testing purposes for pics in image_paths: im=cv2.imread(os.path.expanduser(pics)) base_image=cv2.addWeighted(base_image,0.5,im,0.5,0) base_image=cv2.resize(base_image(91,113)) cv2.imshow('compiledimg.jpg',imstack) k = cv2.waitKey(0) &amp; 0xFF if k == 27: cv2.destroyAllWindows() elif k == ord('s'): cv2.imwrite('compiledimg.jpg',imstack) cv2.destroyAllWindows() The error that I am facing is: image_paths = [os.path.join(path, f) for f in os.listdir(path) if not f.endswith('2.pgm')] TypeError: coercing to Unicode: need string or buffer, list found
has comment: http://stackoverflow.com/comment/82674616
has comment: http://stackoverflow.com/comment/82674538
tagged with: opencv
has comment: http://stackoverflow.com/comment/82674896
score: -2
has comment: http://stackoverflow.com/comment/82674777
tagged with: python
tagged with: image-processing
has answer: http://stackoverflow.com/a/47855449
type: UnansweredQuestion
type: Question
has answer: http://stackoverflow.com/a/54203579

http://stackoverflow.com/q/47808181
tagged with: http://stackoverflow.com/tag/html
has comment: http://stackoverflow.com/comment/82577794
type: Question
has answer: http://stackoverflow.com/a/47808667
answer count: 2
has body: I'm trying to display 2 views on the same page (both from different apps). I've imported the views into a third app which I want to use to put the 2 files together. At the moment I'm able to show 1 of the 2 apps. I'm retrieving the views of the app like this: def bar(request): # Get the template template = loader.get_template('topbar.html') #render the template and store the outcome in 'render' render = template.render({}, request) #return the rendered template return render after this I can get this view from another app like this: render = bar(request) return HttpResponse(render) This works and the html file is showing nicely but now I want to append the second view (which can be requested in the same way) to the first one. Is this possible? Am I doing it the right way?
has comment: http://stackoverflow.com/comment/82577755
type: UnansweredQuestion
has title: Is it possible to append templates in django
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/82577865
has comment: http://stackoverflow.com/comment/82577632
has comment: http://stackoverflow.com/comment/82577563
has answer: http://stackoverflow.com/a/47808919
score: 0
tagged with: django-views

http://stackoverflow.com/a/47846600
upvote count: 2
type: Answer
score: 2
has body: No, __getitem__ does not "look for" len. It's simply that in order to reverse a sequence you must know its last item, and for that you need the length of the sequence, or the __reversed__ magic method. So, Python's reversed first finds the length of the sequence and retrieves its elements starting from the last one: def python_reverse(data): for x in range(data.__len__() - 1, -1, -1): yield data.__getitem__(x) (It's not Pythonic to call magic methods explicitly. These calls are here just to show their usage. In real code please use len and the index notation data[x] instead).
answers question: http://stackoverflow.com/q/47846537
downvote count: 0

http://stackoverflow.com/q/47725238
upvote count: 2
downvote count: 2
has body: I know how to calculate binomial coefficients for choose(5,2), but now I want to know if there is a function that I can calculate choose(5,2.1) in python or R programming language?
tagged with: binomial-coefficients
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82411363
has answer: http://stackoverflow.com/a/47725290
has answer: http://stackoverflow.com/a/47725352
has title: how to calculate binomial coefficents with non-integer numbers
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82411210
tagged with: python
tagged with: http://stackoverflow.com/tag/r
score: 0
has answer: http://stackoverflow.com/a/47725299
answer count: 3

http://stackoverflow.com/a/47733426
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82427615
upvote count: 1
has comment: http://stackoverflow.com/comment/82428561
has comment: http://stackoverflow.com/comment/82427647
has comment: http://stackoverflow.com/comment/82428465
has comment: http://stackoverflow.com/comment/82427927
has comment: http://stackoverflow.com/comment/82428397
has comment: http://stackoverflow.com/comment/82427548
has body: There are a few problems with your code, and other points you could improve: instead of having six different variables for verbs and output each, use two lists; this way you can more easily adapt the "splitting points" or number of sublists, and you do not have to copy-paste the code block for comparing the words six times; just use another loop the sublist words[13081:9811] is empty, and also any others where the second index is smaller than the first with verbs1 = words[:3269] and verbs2 = words[3269:13080], words[3269] will be in neither of the sublists, as the second index is exclusive; same for the following lists just in case this was your intention, splitting the list will not reduce the complexity or the running time, as you still have to compare each of the words; a*x + b*x + c*x is the same as (a+b+c) * x instead of checking a &lt; b and dismissing half of the product, use combinations instead (but this only works when not splitting the list) if you are only interested in pairs with an edit distance &lt;= 5, you could do a few other checks first, like comparing the length of the two words, or the set difference of contained characters; both of those checks will be faster then the actual edit distance check, which is O(n²), and might rule out many combinations for the same reason, do not calculate the edit distance twice, once in the check and again for writing it to the file, but just once and store it in a temporary variable if you split the file so that the output file does not become too large for Excel to handle (as I understood one of your comments), your approach might not work, as the size of the output file can vary drastically, depending on how many matches there are in that sublist Combining the above, you could try something like this (not tested): path = '/Users/path/' with open(path + 'wordlist.txt') as infile: words = set(s.strip() for s in infile) combs = itertools.combinations(words, 2) max_count = 10**6 # or whatever Excel can handle for i…
type: Answer
has comment: http://stackoverflow.com/comment/82428312
answers question: http://stackoverflow.com/q/47733250
has comment: http://stackoverflow.com/comment/82428585
accepted answer of: http://stackoverflow.com/q/47733250
score: 1

http://stackoverflow.com/comment/82435439
type: QuestionComment
has text: no life expectancy data no gini data
score: 0
comment on: http://stackoverflow.com/q/47737141
type: Comment

http://stackoverflow.com/q/47729147
has comment: http://stackoverflow.com/comment/83205060
has comment: http://stackoverflow.com/comment/83373892
type: AnsweredQuestion
upvote count: 3
has comment: http://stackoverflow.com/comment/82481717
answer count: 1
downvote count: 0
has title: Bokeh server : Customize row ratio
tagged with: bokeh
accepted answer: http://stackoverflow.com/a/50752301
favorite count: 0
linked to: http://stackoverflow.com/q/40413198
type: Question
has answer: http://stackoverflow.com/a/50752301
score: 3
tagged with: python
has body: I am using Bokeh to vizualize scientific data for a while and I fail to customize my layout as I wish. from bokeh.plotting import figure from bokeh.io import show from bokeh.layouts import row from bokeh.models.widgets import Button tools_to_show = 'hover, box_zoom, save, reset, pan' p = figure(tools=tools_to_show, output_backend = "webgl") p.line([1, 2, 3, 4], [9, 5, 7, 6]) b_valid = Button(label="valid") my_plot = row(p, b_valid, sizing_mode="stretch_both") show(my_plot) I have a plot area and a controls area. The controls area should be smaller, maybe 1/3 of available width to let the plot with a bigger area (2/3 of available width). I'm using sizing_mode = "stretch_both" to be sure to use all available space in screen. I need to keep using the bokeh server (bokeh serve myapp.py) to get python callback working, so the embbeded solution suggested here is not working for me. Maybe there is a way with serving directory with bokeh command because there is a template mechanism, but I can't figure how to get seperate div for plot and controls. Have you any (simple) idea ? Edit : it seems that it's not a feature currently available on bokeh. A promising solution is to be able to place components embedded in template using bokeh server : amilestone is scheduled

http://stackoverflow.com/q/47791974
has title: Python function not optimizing
tagged with: scipy
has body: I am trying to solve the problem of homography (Computer Vision) using the optimization technique instead of the DLT (Direct Linear Transform) method. The simple illustration of this cost function is here: Illustration of cost function I have implemented this cost function in python as: - def costFunc(H, p1, p2): cost = 0. H = H.reshape((3, 3)) H_inv = inv(H) for i in range(0, p1.shape[0]): # Forward Transformation x = p1[i, :] x_dash = p2[i, :] x = numpy.reshape(x, [1, 3]) x_dash_estimated = applyTransformation(H, x) diff = numpy.sum(numpy.square(numpy.subtract(x_dash_estimated, x_dash))) cost = cost + diff # # Inverse Transformation x = p2[i, :] x_dash = p1[i, :] x = numpy.reshape(x, [1, 3]) x_dash_estimated = applyTransformation(H_inv, x) diff = numpy.sum(numpy.square(numpy.subtract(x_dash_estimated, x_dash))) cost = cost + diff return cost/p1.shape[0] Here, H is the same as H matrix (but flattened to a 1x9 vector) from the image given and p1 and p2 are 4 corresponding pairs of homogeneous points. They are both a 4x3 matrix. The corresponding points between the images are given below:- refPt = numpy.array([[[182, 267, 1], [119, 270, 1]], [[264, 111, 1], [202, 110, 1]], [[544, 92, 1], [479, 95, 1]], [[329, 356, 1], [269, 357, 1]]]) Each row represents two corresponding points in the images. They are seperated into p1 and p2 as: - p1 = refPt[:, 0, :] p2 = refPt[:, 1, :] The function applyTransformation simply applies homography to the input point. It is given as:- def applyTransformation(H, points): output = numpy.zeros(shape=[points.shape[0], 3], dtype=numpy.int32) for i in range(0, points.shape[0]): temp = numpy.dot(H, points[i, :]) temp = temp / temp[2] temp[0] = numpy.round(temp[0]) temp[1] = numpy.round(temp[1]) output[i, :] = temp return output Now, when I try to minimize this function, I get stuck in some local minima and global optimal value is never achieved. My optimization code is given below: - initial_H = numpy.random.rand(3, 3) * 1. initial_h = initia…
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/82545430
has comment: http://stackoverflow.com/comment/82546059
type: UnansweredQuestion
tagged with: python
tagged with: computer-vision
tagged with: optimization
answer count: 0
has comment: http://stackoverflow.com/comment/82546470
score: 0

http://stackoverflow.com/q/47752565
downvote count: 0
has body: I have the following dataframe &amp; I want to manipulate the values in the TypeName column so that it contains only the part before the parentheses start DeviceName DispName TypeName 0 TYZ:SB_INCOMING Incoming Incoming(TYZ:SB_INCOMING) 1 TYZ:SB_SECTION Add Section TYZ:SB_SECTION 2 TYZ:SB_FDR_WL WL Main(TYZ:SB_FDR_WL) 3 TYZ:SB_VLMCCB MCCB Main(TYZ:SB_VLMCCB) 4 TYZ:SB_FDR_BPS BPS Main(TYZ:SB_FDR_BPS) I have tried this doc_df.TypeName, doc2= doc_df.TypeName.str.split("(")[0] What this does is it sets the same value for all the rows in the dataframe for the TypeName column. Can someone please point out the mistake The current ouput which I am getting is DeviceName DispName TypeName 0 TYZ:SB_INCOMING Incoming Incoming 1 TYZ:SB_SECTION Add Section Incoming 2 TYZ:SB_FDR_WL WL Incoming 3 TYZ:SB_VLMCCB MCCB Incoming 4 TYZ:SB_FDR_BPS BPS Incoming Expected is DeviceName DispName TypeName 0 TYZ:SB_INCOMING Incoming Incoming 1 TYZ:SB_SECTION Add Section TYZ:SB_SECTION 2 TYZ:SB_FDR_WL WL Main 3 TYZ:SB_VLMCCB MCCB Main 4 TYZ:SB_FDR_BPS BPS Main
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82465553
tagged with: dataframe
tagged with: python
accepted answer: http://stackoverflow.com/a/47752622
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47752622
has comment: http://stackoverflow.com/comment/82465486
tagged with: pandas
upvote count: 2
has title: How to Split the values of a column in a Pandas dataframe?
answer count: 1

http://stackoverflow.com/q/47762460
downvote count: 0
answer count: 0
tagged with: javascript
score: 7
upvote count: 7
has body: javascript = """ &lt;script type="text/Javascript"&gt; function exec_code(){ var res = confirm("Hello"); var kernel = IPython.notebook.kernel; console.log("show:" + res); var callbacks = { iopub : { output : res, } } IPython.notebook.kernel.execute(res, callbacks); } exec_code(); &lt;/script&gt; """ HTML(javascript) I want to have a confirm popup in javascript, and depending on whether user does "OK" or "Cancel", store the value in variable res. Then I want to expose that to python in the same cell in jupyter notebook. I tried callbacks.iopub.output, but does not seem to work. I want to do a print(output) to display the value in res -- true or false.
favorite count: 0
type: Question
tagged with: python
type: UnansweredQuestion
tagged with: jupyter-notebook
has title: Communicate between javascript and python in Jupyter notebook

http://stackoverflow.com/comment/82489377
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47763997
has text: I don't know either until I see the actual error...
score: 3

http://stackoverflow.com/comment/82487023
comment on: http://stackoverflow.com/a/47741488
has text: "text" means text , not color. When you create label then you can set color `Label(root, bg="green")` and it means you can change it later with `L['bg'] = 'red'` or `L.config( bg="red" )` - see parameters in [Label.config()](http://effbot.org/tkinterbook/label.htm#Tkinter.Label.config-method)
type: Comment
score: 0
type: AnswerComment

relative-path
type: Tag
tags question: http://stackoverflow.com/q/47780166
tag name: relative-path
tags question: http://stackoverflow.com/q/47802020

http://stackoverflow.com/comment/82573275
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47805945
has text: You can use the `locals` and `global` functions.
score: 0

matplotlib-3d
tags question: http://stackoverflow.com/q/47835726
type: Tag
tag name: matplotlib-3d

http://stackoverflow.com/a/47780912
accepted answer of: http://stackoverflow.com/q/47780845
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/47780845
type: AcceptedAnswer
has body: Keeping everything else fixed, changing M1 and M2 to M1 = np.vstack([l1.T, l2.T]) M2 = np.concatenate([x1, y1]) should do the job.
type: Answer
has comment: http://stackoverflow.com/comment/82523460

http://stackoverflow.com/comment/82372255
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47704158
has text: You can always call `np.median` directly. Median doesn't always make sense, as with binary distributions, stepped values, etc. Look at the code for `stats.describe`. It does do any custom calculation; it's all delegated to to other functions such as `np.mean` and ones in the `stats` package.
type: Comment

http://stackoverflow.com/a/47831583
type: Answer
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47831096
has body: With lxml.etree.xpath() method: from lxml import etree tree = etree.parse('yourfile.xml') nodes = tree.xpath('/main/a[count(./b) &gt; 1]') for a in nodes: print(list(a)) # getting child nodes of the current &lt;a&gt; node The output (consecutively: a node with 2 b childs and a node with 4 b childs): [&lt;Element b at 0x1577d08&gt;, &lt;Element b at 0x1577d48&gt;] [&lt;Element b at 0x1577d48&gt;, &lt;Element b at 0x1577d88&gt;, &lt;Element b at 0x1577dc8&gt;, &lt;Element b at 0x1577e08&gt;]
answers question: http://stackoverflow.com/q/47831096

http://stackoverflow.com/comment/82554924
comment on: http://stackoverflow.com/q/47797032
type: QuestionComment
has text: http://idownvotedbecau.se/noattempt/ (Joke: You watch Rick & Morty, your IQ should be high enough to solve this problem)
type: Comment
score: 0

http://stackoverflow.com/q/47851181
has comment: http://stackoverflow.com/comment/82666922
has title: Remove item in list from hash lookup of memory location?
has comment: http://stackoverflow.com/comment/82667147
has answer: http://stackoverflow.com/a/47851409
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/82667011
has comment: http://stackoverflow.com/comment/82667115
has comment: http://stackoverflow.com/comment/82666936
tagged with: memory
has comment: http://stackoverflow.com/comment/82667294
has comment: http://stackoverflow.com/comment/82667089
has comment: http://stackoverflow.com/comment/82666879
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82666946
has comment: http://stackoverflow.com/comment/82666915
has comment: http://stackoverflow.com/comment/82667217
tagged with: list
has answer: http://stackoverflow.com/a/47851375
has body: I have objects that each have a unique ID and these objects are inserted to various lists. These objects need to be removed frequently from the middle of its corresponding list which would be O(n) typically, so I'd like to keep their locations in a dict and retrieve the object's location in O(1) each time I want to remove it. class Node(object): def __init__(self, lst_id, unique_id): self.lst_id = lst_id self.unique_id = unique_id n1 = Node('a', 1) n2 = Node('a', 2) n3 = Node('b', 3) node_lsts = {} for node in [n1,n2,n3]: if node.lst_id in node_lsts: node_lsts[node.lst_id].append(node) else: node_lsts[node.lst_id] = [node] nodes_hash = {n1.unique_id: n1, n2.unique_id: n2, n3.unique_id: n3} ID_TO_REMOVE = 1 In example above, if I simply called del nodes_hash[ID_TO_REMOVE], the corresponding object in node_lsts remains even though it is removed from the dictionary - how should I get it removed from its corresponding list in O(1)? In C++ I can keep the pointers to list neighbors as node member variables (linked list) and look up a node by its memory address, get pointers to its neighbors, unlink that node from its neighbors (thereby removing it from the 'list') and finally free the node. I'm trying to replicate this behavior.
answer count: 2
has comment: http://stackoverflow.com/comment/82666997
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/82667097
has comment: http://stackoverflow.com/comment/82667276
tagged with: pointers
has comment: http://stackoverflow.com/comment/82666894
has comment: http://stackoverflow.com/comment/82666830
has comment: http://stackoverflow.com/comment/82666829
favorite count: 0
possible better answer: http://stackoverflow.com/a/47851375
type: Question
accepted answer: http://stackoverflow.com/a/47851409
has comment: http://stackoverflow.com/comment/82667069
has comment: http://stackoverflow.com/comment/82666852

http://stackoverflow.com/comment/82657986
score: 0
type: AnswerComment
has text: I did like this, but synonyms are not closer to each other. Do you know Word Embeddings by Baroni el. al? Is there any other to solve embeddings of sentences?
type: Comment
comment on: http://stackoverflow.com/a/47845473

http://stackoverflow.com/q/47795001
has comment: http://stackoverflow.com/comment/82551040
favorite count: 0
type: Question
has body: I use pandas and get my data from a SQL database I have two tickers. One is a U.S stock, the other an European stock. Dates are not necessarily the same for both stocks (holidays, etc). All my data is stored in a multi-index DataFrame. Looking to fill missing values based on levels Running the below code: import pandas as pd import datetime ticker_date = [('US',datetime.date.today()-datetime.timedelta(3)), ('US',datetime.date.today()-datetime.timedelta(2)), ('US',datetime.date.today()-datetime.timedelta(1)), ('EU',datetime.date.today()-datetime.timedelta(3)), ('EU',datetime.date.today()-datetime.timedelta(1))] index_df = pd.MultiIndex.from_tuples(ticker_date) example = pd.DataFrame([12.2,12.5,12.6,15.1,15],index_df,['value']) Output: Output from code above I am looking for a method to reshape my output filling the missing data with the previous value: Objective: add a dec 11th line and fill with previous value
tagged with: missing-data
has title: Python - Pandas - Fill missing data based on existing Levels
tagged with: python
has comment: http://stackoverflow.com/comment/82551085
possible better answer: http://stackoverflow.com/a/59057841
accepted answer: http://stackoverflow.com/a/47798134
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/59057841
answer count: 2
has comment: http://stackoverflow.com/comment/82550987
has answer: http://stackoverflow.com/a/47798134
tagged with: pandas
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/82551203
downvote count: 0
tagged with: levels

http://stackoverflow.com/comment/82579436
score: 0
comment on: http://stackoverflow.com/q/47808887
type: Comment
type: QuestionComment
has text: Thanks. As it takes time to write the csv file, I do not want to wait for the process of writing file to finish and return. I want to concurrently writing file and return the data, not sequential processes.

http://stackoverflow.com/comment/83045815
type: Comment
type: QuestionComment
has text: @Obsession Sorry you saw it that way. I gave you a link pointing to why people downvoted your question (and how to improve it) and then tried to lighten the mood with some humour you'd understand. In future I'll avoid Rick & Morty jokes.
comment on: http://stackoverflow.com/q/47797032
score: 0

http://stackoverflow.com/comment/82392691
comment on: http://stackoverflow.com/q/47716237
score: 2
type: Comment
type: QuestionComment
has text: It seems that each element in you list is a tuple. You want to get the data inside the tuple right?

http://stackoverflow.com/q/47748528
type: Question
has comment: http://stackoverflow.com/comment/82487310
answer count: 0
has body: I've setup my RPi, motion detector and camera to capture an image whenever motion is detected. Each time an image is captured, I'd like to automatically upload that image to Google Drive (and delete it from my RPi). Everything seems to be working with one exception - my script captures and uploads the first image to Google Drive with no problems but then it continues to upload that same image and only that image each time the camera is subsequently triggered. The subsequent images are being captured and stored on my RPi properly, just not uploaded to Google Drive. I'm only a couple weeks into coding so please have mercy on me (and sincere thanks for any help). Relevant bits below: class MotionUploader: def __init__(self, config_file_path): config = ConfigParser.ConfigParser() config.read(config_file_path) def upload_snapshot(self, snapshot_file_path): """Upload a snapshot to the specified folder. Remove duplicates.""" folder_id = self._get_folder_id(self.snapshot_folder) file_name = os.path.basename(snapshot_file_path) media = MediaFileUpload(snapshot_file_path, mimetype='image/jpeg') self.drive_service.files().insert(media_body=media, body={'title':file_name, 'parents':[{u'id': folder_id}]}).execute() while True: i=GPIO.input(11) if i==0: #When output from motion sensor is LOW print "All quiet... too quiet...",i GPIO.output(3, 0) #Turn OFF LED time.sleep(3) elif i==1: #When output from motion sensor is HIGH print "!Achtung!",i GPIO.output(3, 1) #Turn ON LED now = datetime.datetime.now().strftime("%m_%d_%Y_%H_%M_%S") camera.rotation = 180 camera.start_preview() camera.capture("/home/pi/motion-uploader/Photos/"+ now + ".jpg") cfg_path = sys.argv[1] vid_path = sys.argv[2] MotionUploader(cfg_path).upload_snapshot(vid_path) camera.stop_preview() time.sleep(3)
type: UnansweredQuestion
tagged with: upload
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/82480196
has title: Can only upload the first image each time my camera takes a picture
tagged with: capture
score: 0
has comment: http://stackoverflow.com/comment/82457207
tagged with: camera
tagged with: python
tagged with: image
favorite count: 0

http://stackoverflow.com/a/47794174
score: 0
type: Answer
answers question: http://stackoverflow.com/q/47793608
has body: source_list = ['dialog #', 'a', 'b', 'dialog #', ... ] new_list = [] begin = 0 local_list = [] for item in source_list: if item == 'dialog #': if begin == 0: local_list.append(item) begin = 1 else: new_list.append(local_list) local_list = [item] else: local_list.append(item) new_list.append(local_list) I do not check it...

http://stackoverflow.com/a/47735079
score: 2
has body: You can use the built-in function .sort() and module locale to sort the words. A simple example would be: alphabet = ['Ж', 'Жь', 'Гъ'] # obviously the list should contain all the letters import locale locale.setlocale(category=locale.LC_ALL, locale="kbd") alphabet.sort(key=locale.strxfrm) print(alphabet) ['Гъ', 'Ж', 'Жь']
has comment: http://stackoverflow.com/comment/82437017
has comment: http://stackoverflow.com/comment/82434628
has comment: http://stackoverflow.com/comment/82445570
upvote count: 2
has comment: http://stackoverflow.com/comment/82436295
downvote count: 0
answers question: http://stackoverflow.com/q/47734554
has comment: http://stackoverflow.com/comment/82438817
type: Answer
has comment: http://stackoverflow.com/comment/82430696
has comment: http://stackoverflow.com/comment/82437078

http://stackoverflow.com/comment/82365511
score: 0
has text: @ahed87 do you have reccomendation of code to use by just using conda to write like I am attempting to?
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47702119

http://stackoverflow.com/comment/82493160
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47765944
has text: @xaav How do I get around it? I did not have problem yesterday. Is it corrupt files?
type: Comment

http://stackoverflow.com/a/47776499
score: 0
type: Answer
has body: I'm sure there are better ways to do it, but have you tried merging the dataframes (as you already are), creating a new column that compares Status_1 and Status_2, and then dropping any rows where that match is True? If you dropped that "do they match" column afterwards, I believe you'll wind up with your desired output.
answers question: http://stackoverflow.com/q/47776356

http://stackoverflow.com/a/47783888
answers question: http://stackoverflow.com/q/47783822
type: Answer
accepted answer of: http://stackoverflow.com/q/47783822
has comment: http://stackoverflow.com/comment/82530508
score: 0
type: AcceptedAnswer
upvote count: 1
has body: Try this? def numberToList(number): # base case if number == 0: return [] # recurse return numberToList(number / 10) + [ number % 10 ] Run it like this: &gt;&gt;&gt; numberToList(1234) [4, 3, 2, 1]
downvote count: 1

http://stackoverflow.com/q/47698691
tagged with: automation
tagged with: jira-rest-api
downvote count: 0
upvote count: 1
answer count: 1
favorite count: 0
type: Question
tagged with: pytest
has answer: http://stackoverflow.com/a/48115372
has title: Py.test results reporting to Jira, Adaptavist
has body: Looking for a solution for collecting results from py.test automation framework to Jira, Adaptavist plug-in. Kanoah is providing documentation for Adaptavist Test Management for JIRA REST API. The documentation is not clear about how to Post results from the py.test or another test automation framework. Example of : [ { "status": "Fail", "testCaseKey": "JQA-T1234", "environment": "Firefox", "comment": "The test has failed on some automation tool procedure.", "userKey": "vitor.pelizza", "executionTime": 180000, "executionDate": "2016-01-30T14:54:00Z", "issueLinks": ["JQA-123", "JQA-456"], "scriptResults": [ { "index": 0, "status": "Fail", "comment": "This step has failed." } ] }, { "status": "Fail", "testCaseKey": "JQA-T5678" } ] The Question is: How to set up the the py.test framework? Pytest has the following options for reporting results of automation tests. But I'm sure how to setup of the options to send the results to Jira, Adaptavist. 1. JUnit-Style Logs You can generate JUnit-style XML log files by running the following command: py.test --junitxml=result.xml The XML file will be generated in the current directory. 2. Generating a Plain Result py.test --resultlog=result.log 3. Sending a Test Report to Online pastebin Service The following command sends the entire execution log to an online remote pastebin service: py.test -v --pastebin=all Thanks in advance!
tagged with: reporting
tagged with: python
type: UnansweredQuestion
score: 1

http://stackoverflow.com/comment/82475826
has text: @Nae What do you mean by memory leak, want to understand what have done better.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47757219
type: Comment

http://stackoverflow.com/q/47850118
has title: My telegram bot on Python not working
has answer: http://stackoverflow.com/a/48407725
has comment: http://stackoverflow.com/comment/82669817
score: 2
answer count: 2
upvote count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/49608377
has body: I wrote a bot in Python. Periodically, it stops working. The virtual machine works stably. The running service is always active. I'm using this library - https://github.com/eternnoir/pyTelegramBotAPI Works on a virtual machine on the Azure service (Ubuntu 16.04.5). Here is the Python script code: # -*- coding: utf-8 -*- import re import config import telebot bomg = "Бомж" regRusLetters = re.compile("^[а-яА-Яё]+$") bot = telebot.TeleBot(config.token) def second_vowels(text): pos = 0 i = 1 while i &lt; len(text): if text[i] in "ауоыиэяюёе": pos = i break i = i + 1 return pos @bot.message_handler(commands=['start', 'help']) def send_welcome(message): bot.reply_to(message, "Пришли мне слово на Русском и я его бомжирую!") @bot.message_handler(content_types=["text"]) def repeat_all_mesages(message): response = "не могу бомжировать..." text = message.text.lower() if re.match(regRusLetters, text): pos = second_vowels(text) response = bomg + text[pos:] bot.send_message(message.chat.id, response) bot.polling(none_stop=True) Configured as a service using systemd. Here is the bot.service file: [Unit] Description=TelegramBot After=network.target [Service] Type=idle ExecStart=/usr/bin/python3.5 /home/rhanza/TelegramBot/bot.py Restart=always [Install] WantedBy=multi-user.target When I connect through ssl and check the status of the process, I see the following: status bot.service ● bot.service - TelegramBot Loaded: loaded (/etc/systemd/system/bot.service; enabled; vendor preset: enabled) Active: active (running) since Sat 2017-12-16 21:06:31 UTC; 3min 8s ago Main PID: 3823 (python3.5) Tasks: 4 Memory: 19.2M CPU: 930ms CGroup: /system.slice/bot.service └─3823 /usr/bin/python3.5 /home/rhanza/TelegramBot/bot.py &amp; Dec 16 21:06:31 botholder1 systemd[1]: bot.service: Service hold-off time over, scheduling restart. Dec 16 21:06:31 botholder1 systemd[1]: Stopped TelegramBot. Dec 16 21:06:31 botholder1 systemd[1]: Started TelegramBot. The bot does not always respond to messages, althou…
favorite count: 0
type: Question
tagged with: telegram-bot
tagged with: systemd
type: UnansweredQuestion
tagged with: azure
tagged with: python

http://stackoverflow.com/a/62902953
score: 0
has body: **Use this following for your new.html file and keep your other files unchanged like forms and models ** gffdfdf {% csrf_token %} Team {% for field in form %} {{ field.errors }} {{ field.label_tag }} : {{ field }} {% endfor %} {{ form.players.management_form }} {{ form.players.empty_form }} Product Instance(s) player name highest score age {% for player in form.players %} {{ player.pname }} {{ player.hscore }} {{ player.age }} {% endfor %} save
answers question: http://stackoverflow.com/q/47748174
type: Answer

http://stackoverflow.com/comment/82519516
type: QuestionComment
comment on: http://stackoverflow.com/q/47779104
score: 0
has text: @Elazar consider that the last line within the loop is Z += -1
type: Comment

http://stackoverflow.com/comment/82392231
type: AnswerComment
comment on: http://stackoverflow.com/a/47715594
has text: Proper formatting and some explanation would be useful here.
type: Comment
score: 0

http://stackoverflow.com/comment/82671517
type: Comment
type: QuestionComment
has text: i figured it out.thanks for offering help sebastien
score: 0
comment on: http://stackoverflow.com/q/47831143

http://stackoverflow.com/q/47835203
upvote count: 1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82634070
score: -2
has body: I have the following problem, i have a 7 x 7 grid filled with butoons and the following problem is: I want to replace the text later on the buttons, but with the help of the rows and columns, how is that possible? import tkinter as tk def click(row, col): print(row, col) label.configure(text="you clicked row %s column %s" % (row, col)) test_text = "TEST" root = tk.Tk() for row in range(1,8): for col in range(1,8): button = tk.Button(root, text=test_text, command=lambda row=row, col=col: click(row, col)) button.grid(row=row, column=col, sticky="nsew") label = tk.Label(root, text="") label.grid(row=8, column=1, columnspan=8, sticky="new") root.grid_rowconfigure(10, weight=1) root.grid_columnconfigure(10, weight=1) root.mainloop()
downvote count: 3
tagged with: python
has title: Python Tkinter changing Button Text with row and column
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: tkinter
has answer: http://stackoverflow.com/a/47835381
answer count: 1
accepted answer: http://stackoverflow.com/a/47835381
has comment: http://stackoverflow.com/comment/82634155

http://stackoverflow.com/q/47851895
has comment: http://stackoverflow.com/comment/82668220
has comment: http://stackoverflow.com/comment/82668488
has comment: http://stackoverflow.com/comment/82668541
has comment: http://stackoverflow.com/comment/82675532
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/82668786
has comment: http://stackoverflow.com/comment/82668524
has title: Python check-if-exists-and-update atomic operation
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/82677675
has comment: http://stackoverflow.com/comment/82668490
type: Question
has comment: http://stackoverflow.com/comment/82668849
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82668451
tagged with: multithreading
has comment: http://stackoverflow.com/comment/82675070
has body: I need a thread-safe (atomic?) data structure in Python that can ensure the following: # visited : defaultdict() if node not in visited: assert node not in visited visited[node] = True
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/47856742

http://stackoverflow.com/q/47707228
has title: Hold down key to constantly move tank
tagged with: python
tagged with: pygame
has answer: http://stackoverflow.com/a/47707304
accepted answer: http://stackoverflow.com/a/47707304
type: Question
answer count: 1
has comment: http://stackoverflow.com/comment/82374533
type: AnsweredQuestion
score: 0
has body: I'm currently trying to make the tanks move(whhich they already do) but I want to make it so that you can just hold down WASD or the 4 arrow keys to have it contantly moving. Right now, you have to click the arrow key over and over again for it to move. import pygame, assetloader from pygame.locals import * import random, time, math import pygame GRAD = math.pi/180 blue = (0, 0, 255) wallRects = [] maze = [[] for i in range(25)] assetloader.set_asset_path("assets/") class Player(pygame.sprite.Sprite): def __init__(self, x, y, pos): pygame.sprite.Sprite.__init__(self) self.image, self.rect = assetloader.load_image("Tank.png", -1) self.rect.x = x self.rect.y = y self.rect.clamp_ip(screen.get_rect()) self.dir = 0 self.vel_y = 0 self.vel_x = 0 self.rows = pos[0] self.cols = pos[1] self.x = self.cols * gsize self.y = self.rows * gsize self.orig_image, self.orig_rect = assetloader.load_image("Tank.png", -1) self.orig_rect.x = self.x self.orig_rect.y = self.y self.orig_gun_pos = self.orig_rect.midtop self.ammo = 5 self.vel = [0, 0] self.dead = False def draw(self, screen): image = pygame.transform.rotate(self.image, self.dir) screen.blit(image, self.rect) def update(self): oldCenter = self.rect.center self.rect = self.image.get_rect() self.rect.center = oldCenter screen_rect = screen.get_rect() keys = pygame.key.get_pressed() if keys[K_UP]: if (0 &lt; self.dir and self.dir &lt; 90) or (-360 &lt; self.dir and self.dir &lt; -270): self.vel_x = -1 self.vel_y = -1 elif (270 &lt; self.dir and self.dir &lt; 360) or (-90 &lt; self.dir and self.dir &lt; 0): self.vel_x = 1 self.vel_y = -1 if (90 &lt; self.dir and self.dir &lt; 180) or (-270 &lt; self.dir and self.dir &lt; -180): self.vel_x = -1 self.vel_y = 1 elif (180 &lt; self.dir and self.dir &lt; 270) or (-180 &lt; self.dir and self.dir &lt; -90): self.vel_x = 1 self.vel_y = 1 if self.dir == 0 : self.vel_x = 0 self.vel_y = -1 if self.dir == 90 : self.vel_x = -1 self.vel_y = 0 if self.dir == 180: self.vel_x = 0 self.vel_y = 1 if…

http://stackoverflow.com/q/47708331
score: -1
type: Question
linked to: http://stackoverflow.com/q/32845391
has comment: http://stackoverflow.com/comment/82376518
has comment: http://stackoverflow.com/comment/82386140
upvote count: 0
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/82386259
tagged with: web-scraping
downvote count: 1
favorite count: 0
tagged with: beautifulsoup
has answer: http://stackoverflow.com/a/47709635
has body: I'm trying to scrap a page and take it's hrefs data which are in tag, but i can't get result. This is an assignment for my school. May someone help me please to resolve this issue? This is my code: from bs4 import BeautifulSoup import re import requests for i in range (1,5): base_url = 'https://www.leboncoin.fr/locations' url = 'https://www.leboncoin.fr/locations/1152669519.htm?ca=22_s' res = requests.get(url) soup = BeautifulSoup(res.text) locations = [] links = soup.find_all(['li','a'], href=re.compile('.*\/locations\/+(i)+')) for l in links: full_link = base_url + l['href'] titre = l'li', 'section', 'h2'.strip() res = requests.get(full_link) soup = BeautifulSoup(res.text) loyer = soup.find(['h2','span'], attrs={"class": "value\^((?![A-Z]).)*$"}) loyers = loyer.text ville = soup.find(['h2','span'], attrs={"class": "value", "itemprop": "adresse"}) villes = ville.text surface = soup.find(['h2','span'], attrs={"class": "clearfix", "calss": "value"}) surfaces = surface.text description = soup.find('p', attrs={"class": "value", "itemprop": "description"}) descriptions = description.text shops.append(titre, loyers, villes, surfaces, descriptions) print(locations) I got this like result: [] [] [] [] Thanks in advance for your answers.
tagged with: href
has title: Scraping a page + click on its href and takes hrefs data
has comment: http://stackoverflow.com/comment/82386934
tagged with: http://stackoverflow.com/tag/html
tagged with: python

http://stackoverflow.com/a/47705622
score: 2
accepted answer of: http://stackoverflow.com/q/47705598
has comment: http://stackoverflow.com/comment/82371399
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has body: depends on whether you are using python 2.x or 3.x in 3.x input always gives you a string, so a quick fix is: varthree = int(varone) * int(vartwo)
type: Answer
answers question: http://stackoverflow.com/q/47705598

http://stackoverflow.com/q/47711644
has comment: http://stackoverflow.com/comment/82383848
has answer: http://stackoverflow.com/a/47713558
score: 0
has body: I'm trying to create a new user in my Ionic app using Django as the backend. So far I can create a user no problem using Postman, but when I try to make an HTTP post request through my app I get the following error: {"password":["This field is required."],"username":["This field is required."]}. I am passing the username and password field to my Django app, but for some reason it doesn't register it. Is my post call wrong? DJANGO APP CODE serializers.py class UserSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True) languages = serializers.ListField(child=serializers.CharField(max_length=30, allow_blank=True), source="userprofile.languages") class Meta: model = User fields = ('first_name', 'last_name', 'email', 'username', 'password', 'languages') def create(self, validated_data, instance=None): profile_data = validated_data.pop('userprofile') user = User.objects.create(**validated_data) user.set_password(validated_data['password']) user.save() UserProfile.objects.update_or_create(user=user, **profile_data) return user views.py @api_view(['POST']) @permission_classes((AllowAny,)) def create_user(request): serialized = UserSerializer(data=request.data) if serialized.is_valid(): serialized.save() return Response(serialized.data, status=status.HTTP_201_CREATED) else: return Response(serialized._errors, status=status.HTTP_400_BAD_REQUEST) IONIC APP CODE http.ts register(username, password, email, first_name, last_name, languages) { let url = "https://www.example.com/api/create_user/"; let headers = new Headers() headers.append("Content-Type", "application/x-www-form-urlencoded"); return this.http.post(url, {"first_name": first_name, "last_name": last_name, "email": email, "username": username, "password": password, "languages": languages }, {headers: headers}) .map(res =&gt; res.json()); } register.ts import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams } from 'ionic-angular'; import { HttpProvider …
has comment: http://stackoverflow.com/comment/82384019
tagged with: ionic-framework
answer count: 1
type: Question
tagged with: django
tagged with: python
type: UnansweredQuestion
has title: Ionic Framework Posting to Django Rest Framework Using HTTP Requests

http://stackoverflow.com/comment/82480309
type: QuestionComment
has text: Is your data partitioned? Or can you partition the data when storing in parquet? Also, you get OOM error in driver or executor? what does logs have ? Once you know where you have OOM you can tune memory requirement of driver/executor accordingly.
comment on: http://stackoverflow.com/q/47751542
score: 0
type: Comment

jupyter
tags question: http://stackoverflow.com/q/47843222
tags question: http://stackoverflow.com/q/47824131
tags question: http://stackoverflow.com/q/47847214
type: Tag
tags question: http://stackoverflow.com/q/47726971
tags question: http://stackoverflow.com/q/47757753
tags question: http://stackoverflow.com/q/47781464
tags question: http://stackoverflow.com/q/47743635
tags question: http://stackoverflow.com/q/47726924
tags question: http://stackoverflow.com/q/47833192
tags question: http://stackoverflow.com/q/47785444
tags question: http://stackoverflow.com/q/47840667
tags question: http://stackoverflow.com/q/47723101
tags question: http://stackoverflow.com/q/47740602
tags question: http://stackoverflow.com/q/47742120
tags question: http://stackoverflow.com/q/47835361
tags question: http://stackoverflow.com/q/47855420
tags question: http://stackoverflow.com/q/47742900
tags question: http://stackoverflow.com/q/47734730
tag name: jupyter
tags question: http://stackoverflow.com/q/47736541

http://stackoverflow.com/comment/82426573
type: QuestionComment
has text: The value for blanks is basically: blanks = ["string1", "string2", "string3", "string4"]
comment on: http://stackoverflow.com/q/47722590
type: Comment
score: 0

http://stackoverflow.com/q/47848500
accepted answer: http://stackoverflow.com/a/47848619
answer count: 1
linked to: http://stackoverflow.com/q/7585307
has title: Unicode-objects Array Python 3.7
type: Question
tagged with: encoding
tagged with: arrays
has answer: http://stackoverflow.com/a/47848619
tagged with: python
tagged with: unicode
has body: This is my second python project (I'm not experienced) and I seem to be struggling with a problem regarding encoding. I believe the problem to be existing within an array. I have tried pre-encoding the inputs as well as the '297aae72' that I took using a similar resolution that I found here .encode('utf-8') but I experience the same error. I believe this is a hashing problem due to an encoding conflict within the array that is being constructed. This file is speed test.py, where I believe the error to be found. import hashlib from hashlib import md5 import urllib.request, urllib.error, urllib.parse import sys from urllib.parse import parse_qs import functions ping = 16 accuracy = 8 server = functions.setup() def speed_test(up, down): get_data = [ 'download=%s' % down, 'ping=%s' % ping, 'upload=%s' % up, 'promo=', 'startmode=%s' % 'pingselect', 'recommendedserverid=%s' % server, 'accuracy=%s' % 8, 'serverid=%s' % server, 'hash=%s' % md5('%s-%s-%s-%s' % (ping, up, down, '297aae72') ).hexdigest()] request = urllib.request.Request('http://www.speedtest.net/api/api.php', data='&amp;'.join(get_data)) request.add_header('Referer', 'http://c.speedtest.net/flash/speedtest.swf') connection = urllib.request.urlopen(request) response = connection.read() response_code = connection.code connection.close() if int(response_code) != 200: print('There was an issue submitting data') sys.exit(1) qs_args = parse_qs(response) result_id = qs_args.get('resultid') if not result_id or len(result_id) != 1: print('No speedtest image found?') sys.exit(1) print(('Speedtest Results: http://www.speedtest.net/result/%s.png' % result_id[0])) down_input = input("Please enter your download speed (EX: 375.520): ") down_input = down_input.replace(".", "") up_input = input("Please enter your upload speed (EX: 375.520): ") up_input = up_input.replace(".", "") speed_test(up_input, down_input) This file is funcitons.py import math import urllib.request, urllib.error, urllib.parse import os import time from …
type: AnsweredQuestion
score: 0

http://stackoverflow.com/q/47740521
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82441371
tagged with: django
tagged with: python
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/82441325
has comment: http://stackoverflow.com/comment/82441256
has body: I've create a project in a server with CentOS, Django 1.10.1 and using python 3.5. When I run in the terminal py manage.py runserver 0.0.0.0:8000 it shows Performing system checks... System check identified no issues (0 silenced). December 10, 2017 - 15:45:23 Django version 1.10.1, using settings 'samplepy35.settings' Starting development server at http://0.0.0.0:8000/ Quit the server with CONTROL-C. When I use the command netstat -tuplen it says that python is listening on PORT 8000. But when I try to access on the browser it doesn't respond. What can the problem be?
has comment: http://stackoverflow.com/comment/82441460
type: Question
has comment: http://stackoverflow.com/comment/82441240
has comment: http://stackoverflow.com/comment/82441432
has comment: http://stackoverflow.com/comment/82441477
has comment: http://stackoverflow.com/comment/82441277
tagged with: server
has comment: http://stackoverflow.com/comment/82441350
has title: Running Django runserver doesn't respond on the browser

http://stackoverflow.com/comment/82416967
comment on: http://stackoverflow.com/q/47728148
type: Comment
has text: Does the result _need_ to be a tuple, or is a list ok?
type: QuestionComment
score: 0

http://stackoverflow.com/q/47836226
downvote count: 0
tagged with: pandas
linked to: http://stackoverflow.com/q/25488675
has comment: http://stackoverflow.com/comment/82638346
has comment: http://stackoverflow.com/comment/82642150
has comment: http://stackoverflow.com/comment/82641743
favorite count: 0
type: Question
answer count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47840115
has answer: http://stackoverflow.com/a/47840214
tagged with: python
upvote count: 4
has title: How to find the input line with mixed types
score: 4
linked to: http://stackoverflow.com/q/24251219
has body: I am reading in a large csv in pandas with: features = pd.read_csv(filename, header=None, names=['Time','Duration','SrcDevice','DstDevice','Protocol','SrcPort','DstPort','SrcPackets','DstPackets','SrcBytes','DstBytes'], usecols=['Duration','SrcDevice', 'DstDevice', 'Protocol', 'DstPort','SrcPackets','DstPackets','SrcBytes','DstBytes']) I get: sys:1: DtypeWarning: Columns (6) have mixed types. Specify dtype option on import or set low_memory=False. %!PS-Adobe-3.0 How can I find the first line in the input which is causing this warning? I need to do this to debug the problem with the input file, which shouldn't have mixed types.
has comment: http://stackoverflow.com/comment/82642100
has comment: http://stackoverflow.com/comment/82642125

http://stackoverflow.com/comment/82570043
comment on: http://stackoverflow.com/a/47804237
has text: I'd like to understand the 'x' and 'y' behaviour. Is it a known and wanted behaviour or just some side effect to consider ?
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47714290
tagged with: http://stackoverflow.com/tag/json
tagged with: python
has answer: http://stackoverflow.com/a/47714611
has body: I have a json dictionary (result_dict_tag) as follows: {'10644906845': {'photo': {'id': '10644906845', 'tags': {'tag': [{'_content': 'srilanka', 'author': '34665545@N05', 'authorname': 'CrishyM', 'id': '34660205-10644906845-23098', 'machine_tag': 0, 'raw': 'sri lanka'}, {'_content': 'navy', 'author': '34665545@N05', 'authorname': 'CrishyM', 'id': '34660205-10644906845-7137', 'machine_tag': 0, 'raw': 'navy'}, {'_content': 'vessel', 'author': '34665545@N05', 'authorname': 'CrishyM', 'id': '34660205-10644906845-8792', 'machine_tag': 0, 'raw': 'vessel'}]}}, 'stat': 'ok'}, '11778819726': {'photo': {'id': '11778819726', 'tags': {'tag': [{'_content': 'sri', 'author': '44455081@N07', 'authorname': 'Vinchel', 'id': '44433751-11778819726-12165', 'machine_tag': 0, 'raw': 'sri'}, {'_content': 'lanka', 'author': '44455081@N07', 'authorname': 'Vinchel', 'id': '44433751-11778819726-12166', 'machine_tag': 0, 'raw': 'lanka'}, {'_content': 'mirissa', 'author': '44455081@N07', 'authorname': 'Vinchel', 'id': '44433751-11778819726-1158107', 'machine_tag': 0, 'raw': 'mirissa'}]}}, 'stat': 'ok'}} What I want is to extract the 'raw' words from each dictionary (e.g.result_dict_tag['10644906845']['photo']["tags"]['tag'][0]['raw']) and and create a dataframe consisting user id and relevant raw words for each user. I feel this need some for loop. I have written one and it only results the 'raw' words related to first user only. I have gone through documentation and various questions similar to this. But couldn't figure it out. Any help is appreciated.
tagged with: list
linked to: http://stackoverflow.com/q/47651708
answer count: 2
has answer: http://stackoverflow.com/a/47714782
upvote count: 0
has title: extracting components from json dictionary
downvote count: 2
has comment: http://stackoverflow.com/comment/82388473
favorite count: 0
type: Question
type: UnansweredQuestion
score: -2

http://stackoverflow.com/comment/82613863
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47825174
has text: So, it is definitely working now, thank you a ton. But now I get this error. Traceback (most recent call last): File "a:\PythonCryptoBot\Bot1.0\CoinbaseExhangeAuth.py", line 88, in <module> print(r.json())

http://stackoverflow.com/comment/112816221
type: Comment
comment on: http://stackoverflow.com/a/47811709
score: 0
type: AnswerComment
has text: Yes, I pretty much use requests module for the all the network calls in Python3

http://stackoverflow.com/comment/82670226
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47852830
has text: If you put it in a layout it handles those properties using its policies, ie the functions move () and setGeometry () will not work, a possible option is to place a suitable QSpacerItem. The idea of the QLayouts (QVBoxLayout, QHBoxLayouts, etc) is to manage the sizes and positions managing the policies that we establish.

http://stackoverflow.com/comment/82568869
has text: Really like the sphere approach, also easy to conceptualise.
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47802862

http://stackoverflow.com/a/47802790
answers question: http://stackoverflow.com/q/47802468
upvote count: 5
type: Answer
has body: No regex Solution: Get your facts straight - a-z is wrong, some letters are omitted due to similarity: A Neufundland B Nova Scotia C Prince Edward Island E New Brunswick G Québec-Ost H Montréal und Laval J Québec-West K Ontario-Ost L Ontario-Mitte M Groß-Toronto N Ontario-Südwest P Ontario-Nord R Manitoba S Saskatchewan T Alberta V British Columbia X NW-Territ. Nunavut Y Yukon Code: def CheckCanadianPostalcodes(p, strictCapitalization=False, fixSpace=True): '''returns a Tuple of (boolean, string): - (True, postalCode) or - (False, error message) By default lower and upper case characters are allowed, a missing middle space will be substituted.''' pc = p.strip() # copy p, strip whitespaces front/end if fixSpace and len(pc) == 6: pc = pc[0:3] + " " + pc[3:] # if allowed / needed insert missing space nums = "0123456789" # allowed numbers alph = "ABCEGHJKLMNPRSTVWXYZ" # allowed characters (WZ handled below) mustBeNums = [1,4,6] # index of number mustBeAlph = [0,2,5] # index of character (WZ handled below) illegalCharacters = [x for x in pc if x not in (nums + alph.lower() + alph + " ")] if strictCapitalization: illegalCharacters = [x for x in pc if x not in (alph + nums + " ")] if illegalCharacters: return(False, "Illegal characters detected: " + str(illegalCharacters)) postalCode = [x.upper() for x in pc] # copy to uppercase list if len(postalCode) != 7: # length-validation return (False, "Length not 7") for idx in range(0,len(postalCode)): # loop over all indexes ch = postalCode[idx] if ch in nums and idx not in mustBeNums: # is is number, check index return (False, "Format not 'ADA DAD'") elif ch in alph and idx not in mustBeAlph: # id is character, check index return (False, "Format not 'ADA DAD'") # alpha / digit elif ch == " " and idx != 3: # is space in between return (False, "Format not 'ADA DAD'") if postalCode[0] in "WZ": # no W or Z first char return (False, "Cant start with W or Z") return (True,"".join(postalCode)) # yep - all good Testing: testCases = [(Tr…
score: 5
has comment: http://stackoverflow.com/comment/82639055
downvote count: 0
has comment: http://stackoverflow.com/comment/82646071

http://stackoverflow.com/q/47835479
has title: How can I load a class based view by slug?
upvote count: 0
tagged with: django
tagged with: python
score: -1
accepted answer: http://stackoverflow.com/a/47835594
type: AnsweredQuestion
tagged with: django-views
has body: I've created a view to edit a user: class UsersEditView(UpdateView): model = User fields = ['first_name', 'last_name', 'email', 'password'] success_url = reverse('user-list') which edits this model: class User(AbstractUser): email = EmailField(unique=True) slug = AutoSlugField(populate_from='email', max_length=10, unique=True) REQUIRED_FIELDS = [] USERNAME_FIELD = 'email' I defined the url this way: urlpatterns = [ path('', UsersListView.as_view(), name='user-list'), path('new/', UsersCreateView.as_view(), name='user-new'), path('edit/&lt;str:slug&gt;/', UsersEditView.as_view(), name='user-edit') ] and I test it like this: class EditUserTest(AbstractTest): @classmethod def setUpClass(cls): super().setUpClass() user = User(email='email@provider', first_name='Test', last_name='User', slug='slug', password='qqq') user.save() def test_edit_user(self): response = EditUserTest.client.get(reverse('user-edit', args=('slug', ))) except response is always 404: ipdb&gt; response.status_code 404 So, what am I missing? This is for Django 2.0.
answer count: 1
has comment: http://stackoverflow.com/comment/82634430
downvote count: 1
has answer: http://stackoverflow.com/a/47835594
favorite count: 0
type: Question
tagged with: python-3.x

http://stackoverflow.com/a/47717672
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47716531
answers question: http://stackoverflow.com/q/47716531
has comment: http://stackoverflow.com/comment/82396194
type: Answer
score: 2
upvote count: 2
has body: I'm not sure, but it looks like simple modulo arithmetics to me. You can subtract 1 from all vectors (and do resetting to zero) to make it simpler to analyze. You start with counterVec == [a,b,c] == [1,1,1] and calculate in each iteration (where v == littleVec) [ (a+1)%v[0], (b+1)%v[1], (c+1)%v[1] ] And you stop when this vector is eqal to [0,0,0]. Clearly, the first component hits zero every time a was incremented an integer multiple of v[0] times (minus one, because you start with all ones). For all elements to hit zero at once, the same statement must be true: integer multiple of the corresponding v[i]. So eventually you end up at [ (1 + n_a * v[0] - 1)%v[0], (1 + n_b * v[1] - 1)%v[1], (1 + n_c * v[2] - 1)%v[2] ] == [ 0, 0, 0 ] # ^ initial value ^ correction for the initial value Which is true for every choice of the integers (n_a, n_b, n_c). Since you increment all vector components jointly, there must be a smallest number of increments X such that X = n_a * v[0] = n_b * v[1] = n_c * v[2] for some integers n_i. In other words, there will be a smallest X that is divisible by all of v[i]. As others have pointed out, this must be the least common multiple of all v[i]. For the numbers in your example, it's 60 (you see 59 iterations because you start with 1 and not with 0). So if you start with littleVec = ([5, 3, 7, 8, 10, 8, 5, 7, 5, 7]) You will get lcm([5, 3, 7, 8, 10, 8, 5, 7, 5, 7]-1) = 252 minus one iterations until the loop stops.

http://stackoverflow.com/comment/82527074
score: 0
comment on: http://stackoverflow.com/q/47782780
type: Comment
type: QuestionComment
has text: Why would you append anything to `sys.path`? That won't change your script output, just where you import modules from.

http://stackoverflow.com/a/47807677
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/82627756
has body: It seems you are looking for the integrate_times function: It lets you specify a range of exact times for which the observer will be invoked, adjusting the step size to reach every time step exactly, if necessary. Especially for adaptive methods, this is quite useful as it computes the solution at the exact times you specified while still controlling the time step size to not exceed the error bounds. So your current call could be modified to something like auto stepper = make_controlled&lt;error_stepper_type&gt;( 1.0e-10 , 1.0e-16 ); // std::vector&lt;time&gt; times; // std::vector&lt;state&gt; x_vec; // time tstep; auto tbegin = times.begin(); auto tend = times.end(); integrate_times(stepper, dynamics, x, tbegin, tend, tstep, push_back_state(x_vec));
accepted answer of: http://stackoverflow.com/q/47806199
type: Answer
answers question: http://stackoverflow.com/q/47806199
score: 1

http://stackoverflow.com/a/47784659
has comment: http://stackoverflow.com/comment/82534541
has comment: http://stackoverflow.com/comment/82531024
upvote count: 10
type: Answer
answers question: http://stackoverflow.com/q/47783833
has comment: http://stackoverflow.com/comment/82541337
downvote count: 0
score: 10
has body: This is very simple if you use value_counts over columns i.e pd.DataFrame(lst).apply(pd.value_counts,1).fillna(0) apple banana carrots 0 1.0 1.0 1.0 1 1.0 0.0 0.0 2 0.0 1.0 1.0
has comment: http://stackoverflow.com/comment/82531036

http://stackoverflow.com/comment/82658508
type: AnswerComment
has text: This does do more `sums` than necessary
score: 1
comment on: http://stackoverflow.com/a/47847169
type: Comment

http://stackoverflow.com/q/47835836
has body: I want to load a file in a numpy array and take a value in the column 3 since a condition is found at column 1. Following there is a sample of my data in .csv format: step,lambda,rate,etotal 1001,0.0,0.1,-48044.2760681363 2000,0.0,0.1,-48031.1794623084 3000,0.1,0.1,-43205.9046309046 4000,0.2,0.1,-38388.9135212169 5000,0.3,0.1,-33578.2019598638 6000,0.4,0.1,-28770.5652389722 7000,0.5,0.1,-23964.1873174772 8000,0.7,0.1,-14375.4972097742 9000,0.8,0.1,-9572.458083405 10000,0.9,0.1,-4767.3654814475 11000,1,0.1,32.5943003495421 My simplified code is: import numpy as np df = np.genfromtxt('teste.csv', delimiter = ',') rate = 0.1 idx = np.arange(0, 1+rate, rate) for i in idx: print(df[:,3][df[:,1] == i]) I am getting the following output: %run "plot_data.py" 0.0 [-48044.27606814 -48031.17946231] 0.1 [-43205.9046309] 0.2 [-38388.91352122] 0.3 [] 0.4 [-28770.56523897] 0.5 [-23964.18731748] 0.6 [] 0.7 [] 0.8 [-9572.4580834] 0.9 [-4767.36548145] 1.0 [ 32.59430035] One can see that for the values 0.3, 0.6, 0.7 on column 1 Python is returning an empty array. I don't understand why. If I type in a Python pane, the same command but changing manually i for 0.3 in a Python pane, I find my desired answer as one can note: In [17]: df[:,3][df[:,1] == 0.3] Out[17]: array([-33578.20195986]) What am I not understanding and doing wrongly?
has title: Python error: Mean of empty slice
tagged with: python
score: 4
upvote count: 4
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/47836076
accepted answer: http://stackoverflow.com/a/47836057
answer count: 2
has answer: http://stackoverflow.com/a/47836076
has answer: http://stackoverflow.com/a/47836057
downvote count: 0
favorite count: 0
type: Question
tagged with: numpy

http://stackoverflow.com/comment/82410498
comment on: http://stackoverflow.com/a/47724780
type: AnswerComment
score: 0
has text: Incidentally, I have changed the condition of Problem from a//b to int(a//b), but this question and answer are still valid.
type: Comment

http://stackoverflow.com/comment/82558900
comment on: http://stackoverflow.com/q/47785444
score: 0
type: Comment
type: QuestionComment
has text: did you try `os.listdir()` to see what files can see script ?

http://stackoverflow.com/comment/82490653
score: 0
type: Comment
type: AnswerComment
has text: It's probably due to integer division. What this means, is that when python divides an integer with another integer, the result gets rounded down. For example, 10/6 would return 1 instead of 1.666... . The solution is to make sure that you are dividing with or by a float (or a number with a decimal point) so that it will also return a float. So in this instance, if we divide 10.0/6, 10/6.0, or 10.0/6.0 you will get the desired 1.666... I'll update the code in a while, but I'll just add a decimal to point to the 7 divisor you used.
comment on: http://stackoverflow.com/a/47764429

http://stackoverflow.com/q/47716598
has body: Given a relation as a list of tuples [(1,2), (1,3), (2,3), (2,1), (2,2), (3,2), (3,3)] I have a dictionary that maps a key to list of its equivalent class {1: [2, 3], 2: [3, 1, 2], 3: [2, 3]} I would like to write a function that, given this dictionary checks if relation is transitive and symmetric, which means ∀ a, b, c : if (a,b) ∈ Relation and (b,c) ∈ Relation ==&gt; (a,c) ∈ Relation ∀ a, b : if (a,b) ∈ Relation ==&gt; (b,a) ∈ Relation Is it possible to write this in an efficient way, without abusing nested loops? Using a dictionary is helpful in other parts of the program, but I am not sure if it is here. Help?
has answer: http://stackoverflow.com/a/47717027
tagged with: python
tagged with: dictionary
type: Question
upvote count: 4
has comment: http://stackoverflow.com/comment/82394691
type: UnansweredQuestion
answer count: 1
downvote count: 0
has title: Testing equivalence relation on dictionary in python
score: 4
favorite count: 0

http://stackoverflow.com/comment/82611459
type: QuestionComment
score: 0
has text: What happens when you try to run it from the command line? Post the command you're running, and what the cli gives you back.
comment on: http://stackoverflow.com/q/47824422
type: Comment

http://stackoverflow.com/q/47777148
tagged with: python
has body: I have a text file that has three lines and would like the first number of each line stored in an array, the second in another, so on and so fourth. And for it to print the array out. The text file: 0,1,2,3,0 1,3,0,0,2 2,0,3,0,1 The code I'm using (I've only showed the first array for simplicity): f=open("ballot.txt","r") for line in f: num1=line[0] num1=[] print(num1) I expect the result for it to print out the first number of each line: 0 1 2 the actual result i get is [] [] []
upvote count: 4
has title: Transferring numbers from a text file to an array
has answer: http://stackoverflow.com/a/47777238
answer count: 2
has answer: http://stackoverflow.com/a/47777216
tagged with: arrays
has comment: http://stackoverflow.com/comment/82515422
linked to: http://stackoverflow.com/q/40735266
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82515472
has comment: http://stackoverflow.com/comment/82515915
tagged with: python-3.x
score: 3
type: UnansweredQuestion

simplex-noise
type: Tag
tags question: http://stackoverflow.com/q/47707784
tag name: simplex-noise

http://stackoverflow.com/comment/82480167
score: 4
comment on: http://stackoverflow.com/q/47759436
type: Comment
type: QuestionComment
has text: From the Zen of Python: "Flat is better than nested". In any event -- this is more of a question for [codereview.se] rather than here.

http://stackoverflow.com/q/47791765
duplicate of: http://stackoverflow.com/q/925024
has title: How to remove the border of a Scipy generated and Matplotlib plotted dendrogram without remove the labels?
tagged with: plot
type: Question
linked to: http://stackoverflow.com/q/925024
has body: Here is my code: import matplotlib.pyplot as plt import pandas as pd from scipy.cluster import hierarchy as hier df = pd.read_excel('some_symmetricmatrix.xlsx') Z = hier.linkage(df, 'ward') hier.set_link_color_palette(['#d95f02','#7570b3']) fig = plt.figure(figsize=(3, 6)) ax = fig.add_subplot(1,1,1) ax.set_xlabel('Distance') den = hier.dendrogram( Z, leaf_font_size=10., orientation = 'left', above_threshold_color= '#1b9e77' ) ax.tick_params(axis='x',top='off') plt.savefig('somedendrogram.png', bbox_inches='tight', transparent = True, dpi = 300) plt.close() This give me an image like this: I would like to remove the borders (or axes) of the dendrogram, but I would like to keep the ticks and the labels. I've already tried 2 methods from the net: 1. add ax.axis('off') to the code 2. use this piece of code to turn the visibility of the axes off. Both of these give this: I tried to Google this, but I couldn't find anything. I hope you can help me. :)
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/82546351
tagged with: python
tagged with: scipy
favorite count: 0
score: 2
upvote count: 2
answer count: 0
downvote count: 0
tagged with: dendrogram
type: UnansweredQuestion

http://stackoverflow.com/q/47822021
tagged with: python-2.7
has body: if args.daemon: pid = os.fork() if pid &gt; 0: sys.exit(0) os.close(0) os.close(1) os.close(2) main() def main(): # some code p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) I get IOError: [Errno 9] only when main is called as a deamon ie (forked off process and stdin/stdout/stderr closed i suspect its from closing those pipes but if i don't, my program wont return. is there way to execute subprocess within a daemon?
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/47825225
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82609522
type: UnansweredQuestion
has title: 'IOError: [Errno 9] Bad file descriptor when calling subprocess in a daemon
tagged with: python
has comment: http://stackoverflow.com/comment/82607748
score: 4
has comment: http://stackoverflow.com/comment/82612177
has comment: http://stackoverflow.com/comment/82610442
has comment: http://stackoverflow.com/comment/82607066
upvote count: 4
has comment: http://stackoverflow.com/comment/82608448

http://stackoverflow.com/a/47837746
answers question: http://stackoverflow.com/q/47837571
has body: in any language? How about VBA: Cells.Copy Cells.PasteSpecial Paste:=xlPasteValues ActiveWorkbook.SaveAs Filename:="C:\path\filename.xlsm"
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/82685508

http://stackoverflow.com/comment/82475830
comment on: http://stackoverflow.com/a/47720765
has text: For Sure, but how would I do that?
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/82576714
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47800755
type: Comment
has text: I am trying to add my code but struggling with formatting problems. working on it

http://stackoverflow.com/q/47798471
score: 1
upvote count: 3
downvote count: 2
has answer: http://stackoverflow.com/a/47798575
favorite count: 0
type: Question
has body: I have a list of lists [[1,2,3,4],[0,2,3,4],[0,1,3,4],[0,1,2,4],[0,1,2,3]] and I would like to create a dictionary, where the keys are indices of list and the values are a list of tuples, such that 0 : [(0,1),(0,2),(0,3),(0,4)] 1 : [(1,0),(1,2),(1,3),(1,4)] 2 : [(2,0),(2,1),(2,3),(2,4)] and so on. Is it possible to do so, using a comprehension? or without using too many nested loops?
accepted answer: http://stackoverflow.com/a/47798575
has comment: http://stackoverflow.com/comment/82557858
has title: Dictionary with values as lists of tuples
tagged with: python
possible better answer: http://stackoverflow.com/a/47798699
tagged with: dictionary
has answer: http://stackoverflow.com/a/47798699
type: AnsweredQuestion
answer count: 2

http://stackoverflow.com/comment/82450364
comment on: http://stackoverflow.com/q/47745147
has text: Can you share with us the code/steps that you are using to create your `virtualenv`? Also, I don't know much about it, but would [this SO question](https://stackoverflow.com/questions/34327355/microsoft-jscript-runtime-error-object-expected-code-800a13f#34327433) be related? Are you double-clicking on that file to get this error?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/82414804
has text: Hope the following work : worked on python 2.7 ... odd
type: Comment
comment on: http://stackoverflow.com/a/47719732
score: 0
type: AnswerComment

http://stackoverflow.com/a/47769718
score: 0
type: Answer
has body: The problem is neither with Python nor with Json but with the shell itself. When you feed the shell with the following line: sudo python3 release.py $json_str here is what happens in that order: the variable is replaced by its value giving sudo python3 release.py {"ecommerce": "master","app_compat":"master" the line is tokenized in words: 1:sudo 2:python3 3:release.py 4:{"ecommerce": 5:"master","app_compat":"master" because of the space between : and "master" The common way to avoid that splitting is to enclose the variable to be substituted in quotes. Unfortunately you cannot do it here because the string already contains quotes. I can only imagine 2 solutions: ensure that the substitution string contains no unescaped space (one single \ because it occurs inside simple quotes): json_str='{"ecommerce":\ "master","app_compat":"master"}' use the standard input to read the string Python3: input_release = input() or Python2: input_release = rawinput() shell: echo $json_str | sudo python release.py, or with a here document: sudo python release.py &lt;&lt;END $json_str END
answers question: http://stackoverflow.com/q/47769147

http://stackoverflow.com/q/47812933
answer count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/82592187
tagged with: parameter-passing
type: UnansweredQuestion
has title: How do I pass a variable in element_to_be_clickable of WebDriverWait selenium modules?
has answer: http://stackoverflow.com/a/47813424
tagged with: selenium-webdriver
has comment: http://stackoverflow.com/comment/82587405
has comment: http://stackoverflow.com/comment/82606007
has comment: http://stackoverflow.com/comment/82596079
score: 0
tagged with: selenium
has comment: http://stackoverflow.com/comment/82632512
has answer: http://stackoverflow.com/a/47834709
has comment: http://stackoverflow.com/comment/82587392
type: Question
has body: I have a problem about how to pass a string in element_to_be_clickable as variable I would parametrize the string "input[class='loginTextEntry'][id='user']" in a variable named InputVar and pass it to element_to_be_clickable of WebDriverWait For example for the following (working fine) instruction in python script WebDriverWait(driver, explicit_TO).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input[class='loginTextEntry'][id='user']"))).send_keys(userinfo[0]) I would code it as : InputVar = "input[class='loginTextEntry'][id='user']" WebDriverWait(driver, explicit_TO).until(EC.element_to_be_clickable((By.CSS_SELECTOR, InputVar))).send_keys(userinfo[0]) But doesn't work I have tried some other attempts: InputVar = "\"input[class=\'loginTextEntry\'][id=\'user\']\"" WebDriverWait(driver, explicit_TO).until(EC.element_to_be_clickable((By.CSS_SELECTOR, InputVar))).send_keys(userinfo[0]) InputVar = "input[class=\'loginTextEntry\'][id=\'user\']" WebDriverWait(driver, explicit_TO).until(EC.element_to_be_clickable((By.CSS_SELECTOR, \" + InputVar +\" ))).send_keys(userinfo[0]) But I didn't find any solution. How could I code it ? That is important for me because the InputVar could point to different cases and I would automatize
has comment: http://stackoverflow.com/comment/82615208

http://stackoverflow.com/a/47868358
type: AcceptedAnswer
downvote count: 0
has body: Currently scaling of node sizes and edge line width is not exposed directly (although it soon will be), however you can directly modify the data source and glyph to do this kind of thing. Here is an example defining a so called finalize_hook which will modify the data source and glyph to let you define custom scaling of both: node_size=[3,4,5,8,3,8] edge_size=[0.5,0.6,0.8,1.5,0.5] def scale_sizes(plot, element): plot.handles['scatter_1_source'].data['node_size'] = node_size plot.handles['scatter_1_glyph'].size = 'node_size' plot.handles['multi_line_1_source'].data['edge_size'] = edge_size plot.handles['multi_line_1_glyph'].line_width = 'edge_size' %opts Graph [finalize_hooks=[scale_sizes]]
accepted answer of: http://stackoverflow.com/q/47838328
upvote count: 2
answers question: http://stackoverflow.com/q/47838328
type: Answer
score: 2

http://stackoverflow.com/comment/82407700
type: AnswerComment
comment on: http://stackoverflow.com/a/47723447
score: 0
has text: note that `open` `w` on an existing file truncates the file already so `truncate` is redundant (unnecessary)
type: Comment

http://stackoverflow.com/comment/118401855
type: Comment
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/47714013
has text: please see third approach.

http://stackoverflow.com/comment/82467377
has text: This solution uses `pop`, `list`, `yield`, `while`, and even `def` but the OP asked for `argmin` only :(
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/47752733
type: Comment

http://stackoverflow.com/q/47737021
favorite count: 0
type: Question
tagged with: decode
tagged with: byte
upvote count: 2
type: UnansweredQuestion
has body: I am trying to convert/decode byte to string and the code I've tried is shown as below: body = "" path = "C:\\Users\\...\\Demo" listing = os.listdir(path) for em in listing: mail = os.path.join(path, em) file = open(mail, 'rb') e_content = file.read() file.close() b = email.message_from_bytes(e_content) bbb = b['from'] bbb = str(bbb) if '&lt;' in bbb: bbb = bbb.split("&lt;",1)[1] bbb = bbb[:-1] ccc = b['to'] if b.is_multipart(): for part in b.walk(): ctype = part.get_content_type() cdispo = str(part.get('Content-Disposition')) # skip any text/plain (txt) attachments if ctype == 'text/plain' and 'attachment' not in cdispo: body = part.get_payload(decode=True) # decode break else: body = b.get_payload(decode=True) mystring = str(body, 'utf-8','ignore') print(mystring) Unfortunately, this code came out with this error: mystring = str(body, 'utf-8','ignore') TypeError: decoding str is not supported What should I do to fix this? Any help is appreciated. :)
has comment: http://stackoverflow.com/comment/82434587
tagged with: python
has comment: http://stackoverflow.com/comment/82434323
score: 2
has title: How to convert byte to string, Python
has answer: http://stackoverflow.com/a/47737082
answer count: 1
downvote count: 0
tagged with: utf-8
tagged with: string
has comment: http://stackoverflow.com/comment/82434422

http://stackoverflow.com/a/47760834
has body: In your comment you mentioned wanting to get the input from the user (aka "dynamic" like you called it) use this: # This will prompt the user to write something in the console and save it as user_input variable user_input = input('query &gt;&gt; ') data = {'q': user_input} response = requests.post(url, data=data)
answers question: http://stackoverflow.com/q/47760212
score: 0
has comment: http://stackoverflow.com/comment/82495044
type: Answer

http://stackoverflow.com/comment/99716961
has text: I had to add the constraint `blas=*=openblas` to prevent `mkl` from being installed. Found this recommendation [here](https://github.com/conda-forge/numpy-feedstock/issues/108#issuecomment-428749055).
comment on: http://stackoverflow.com/a/52899702
type: AnswerComment
score: 3
type: Comment

http://stackoverflow.com/comment/82507410
comment on: http://stackoverflow.com/a/47771340
type: Comment
type: AnswerComment
has text: Ahh, but `nonzero` doesn't always return the coordinates in sorted order. Gotcha.
score: 0

http://stackoverflow.com/q/47803361
favorite count: 0
type: Question
has title: Python - RGB Tuples
linked to: http://stackoverflow.com/q/9763116
upvote count: 1
tagged with: python
type: UnansweredQuestion
answer count: 1
duplicate of: http://stackoverflow.com/q/9763116
score: 0
has body: I have currently a tuple of: ('(102,117,108)', '(108,32,116)', '(101,120,116)', '(32,105,115)', '(32,103,111)', '(111,100,32)') How would I convert it to: ((102,117,108), (108,32,116), (101,120,116), (32,105,115), (32,103,111), (111,100,32)) Any help is much appreciated!
has answer: http://stackoverflow.com/a/47803388
downvote count: 1

http://stackoverflow.com/a/47832728
answers question: http://stackoverflow.com/q/47831176
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/82629089
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82629886
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/82628664
has body: Handling user prompts automatically is harder than it seems, and printf is unfortunately not good enough to simulate it completely. If you do not want to touch the python code itself, you'll probably have to use expect, which is a scripting language written to handle interactive programs. If it isn't on your system (which is likely), install it with sudo apt install expect or sudo yum install expect. This crude thing here that I have mushed together should be able to handle your requirements: expect_script.exp #!/usr/bin/expect -f set steps [lindex $argv 0] set size [lindex $argv 1] set plus_or_minus [lindex $argv 2] set script_name [lindex $argv 3] spawn python3 ${script_name} # Or `spawn eval_python ${script_name}`, as long as it is a python 3 interpreter as well # If it is python 2, all `input` calls within need to be changed to `raw_input` expect "steps" send -- "${steps}\r" expect "size" send -- "${size}\r" expect "Counting" send -- "${plus_or_minus}\r" expect eof And then call it like this: ./expect_script.exp 10 3 + steps.py If you have questions regarding syntax or semantics, feel free to ask. But don't expect much (ha ha), I am not very good at weird Unix tools. edit with variable amount of parameters: expect_script.exp #!/usr/bin/expect -f spawn python3 [lindex $argv 0] # Or `spawn eval_python [lindex $argv 0]`, as long as it is a python 3 interpreter as # well. If it is python 2, all `input` calls within need to be changed to `raw_input`. set sleep_time 0.1 # using `sleep` to wait for the next prompt is, usually, # a very bad idea. Maybe you can control your input calls # by including unique identifiers in them, such as 1, 2, 3.. # and using `except` to properly wait for them? for {set i 1} {$i &lt; [llength $argv]} {incr i 1} { sleep $sleep_time send -- [lindex $argv $i]\r } expect eof Call order has changed because we need to call our python script before sending the parameters its way: ./expect_script.exp test.py 10 3 + Alternatively, change the python…
accepted answer of: http://stackoverflow.com/q/47831176
has comment: http://stackoverflow.com/comment/82630025

http://stackoverflow.com/a/47817864
answers question: http://stackoverflow.com/q/47816669
has comment: http://stackoverflow.com/comment/139273172
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/83999662
has body: You can import modules in separate threads. Here is the solution. Create a file load_modules.py: from concurrent.futures import ThreadPoolExecutor import importlib import sys modules_to_load = ['numpy', 'pandas', 'matplotlib'] def do_import(module_name): thismodule = sys.modules[__name__] module = importlib.import_module(module_name) setattr(thismodule, module_name, module) print(module_name, 'imported') executor = ThreadPoolExecutor() for module_name in modules_to_load: executor.submit(do_import, module_name) Then you can start interpreter with a command: python -ic "exec(open(\"load_modules.py\").read(), globals())" Or just run exec(open("load_modules.py").read(), globals()) in your interpreter to load modules.
has comment: http://stackoverflow.com/comment/139240506
upvote count: 8
accepted answer of: http://stackoverflow.com/q/47816669
type: Answer
has comment: http://stackoverflow.com/comment/139273120
score: 8

http://stackoverflow.com/q/47843086
type: AnsweredQuestion
tagged with: statsmodels
tagged with: linear-regression
score: 1
tagged with: scipy
favorite count: 0
has title: How to fix y-intercept value in linear regression?
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/47843349
accepted answer: http://stackoverflow.com/a/47843349
answer count: 2
has body: I'm trying to fit a least square line across my data using scipy's linregress() with something like this: from scipy import stats import numpy as np y = [30, 60, 19, 28, 41, 49, 62, 75, 81] x = np.arange(0,9) grad, intercept, r_value, p_value, std_err = stats.linregress(x,y) However, I would also like to fix the y-intercept at a particular point. Ideally, I'm planning to fix it at the first value in y list. In other words, what I'm really trying to do is I want the best fit line to pass through the first value in the y list, which is 30 in my example. But it seems like Scipy is deciding the y-intercept for me. How can I fix the y-intercept to a particular value in scipy's linear regression method? PS: I've also tried using statsmodels' OLS, but it only allows me to either stay at y-intercept=0 or let it decides the best intercept for me.
has answer: http://stackoverflow.com/a/47845372
possible better answer: http://stackoverflow.com/a/47845372
downvote count: 0
upvote count: 1
tagged with: python

http://stackoverflow.com/a/47740301
answers question: http://stackoverflow.com/q/47731284
score: 1
upvote count: 1
has body: You can get service name by port using getservbyport function from socket module, try to do something like that: &gt;&gt;&gt; import socket &gt;&gt;&gt; socket.getservbyport(80) 'http' There are no clear way to get info (or definition) about specific service in python, so try to search about website do that (and provide API to using it with python).
type: Answer
downvote count: 0

http://stackoverflow.com/q/47737417
tagged with: gdal
has body: I got a practice task, which I can not get any further. The task is the following: Project Description The goal of the projects is to create a map view similar to the Google Maps, where the user can see some imagery data captured by drones. User should be able to move around the map freely, as well as zoom in and zoom out to take a closer look at the captured imagery data. It is strongly desired that the served imagery data will support transparency while minimizing the file size and bandwidth usage. This does not have to be implemented, but solution ideas are welcomed. The raw imagery data will be provided as GeoTIFF files. Imagery visible on the map can be added by placing a file inside a directory that is read by the server. Project Delivery Method Project should be delivered as a Git repository with documentation required to setup and run the project. Requirements 1. Server implementation in Python 3.5+ 2. Project must be able to run on Ubuntu Server 16.04 3. Optimal disk space usage for imagery data displayed to the user (as the app may be processing terabytes of satellite imagery data) 4. Relatively conservative bandwidth usage Notes: 1. The project will be deployed on a machine that is already running other Python software. Dependency conflicts must be avoided. (virtualenv, Docker) 2. The UI can be a simple HTML page with embedded libraries and inline scripts. In addition, it was specified in an e-mail: "The test task is not code but just the approach and rough app architecture ```I'm attaching a tank spec. Like I've mentioned. I'm more interested in problem-solving and your ideas. I expect a working prototype tough. Use any libraries you wish to use. Create an elegant, easy to understand the solution. You can use as much time as you want. Would be great if you could deliver the code by git.... ```" So far I have done: Ubuntu as VM Venv Postgres and PostGIS installed (Django writes error-free in a database) Django project and app created Documentation up to t…
upvote count: 2
type: UnansweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/73385593
tagged with: raster
tagged with: django
tagged with: python
score: 2
has title: Django / Geodjango / Raster / geotiff: Problems with practice task
tagged with: geodjango
answer count: 1
favorite count: 0
type: Question

http://stackoverflow.com/comment/82498922
type: Comment
type: QuestionComment
score: 0
has text: @vishes_shell yeah I really need to develop the thought process, if there is anything you recommend for that it'll be very helpful.
comment on: http://stackoverflow.com/q/47767262

http://stackoverflow.com/comment/82523384
comment on: http://stackoverflow.com/a/47780832
score: 0
type: Comment
has text: @DiogoDaniel Essentially. But you can actually define instance variables in any method at any time. As soon as you define a variable on `self` that variable becomes an instance variable. Which means if you had some function `def foo(self)` that declared `self.bar = True` and that method was called, you could access `self.bar` inside your `firstname(self)` function if you wanted.
type: AnswerComment

http://stackoverflow.com/comment/82478884
score: 1
comment on: http://stackoverflow.com/a/47758801
has text: Yes. It will then return me the amount of row. Thanks. It solved the question. Let's include my solution into yours and will accept this answer after 10 minutes.
type: Comment
type: AnswerComment

http://stackoverflow.com/a/47976255
type: Answer
has comment: http://stackoverflow.com/comment/82921542
has comment: http://stackoverflow.com/comment/82921537
answers question: http://stackoverflow.com/q/47711689
score: 0
has body: Have you tried doing a dB ping , and if that fails reconnecting before each call? The other thing I found with flask was if I didn’t close the connection after each call I would end up with situations like this. Sorry for lack of detail but I’m typing this on a phone and scrolling through all your code was had work :-) class MyDatabase(): def __init__(self, host, user, passwd, db, charset): self.host = host self.usr = user self.passwd = passwd self.db = db self.curclass = pymysql.cursors.DictCursor self.charset = charset self.connection = pymysql.connect(host=self.host, user=self.usr, passwd=self.passwd, db=self.db, cursorclass=self.curclass, charset=self.charset) def get_keywords(self): self.connection.connect() cur = self.connection.cursor() sql = """ SELECT * FROM input_keywords """ rows = None try: cur.execute(sql) rows = cur.fetchall() except Exception as e: print(e) self.connection.rollback() finally: cur.close() self.connection.commit() self.connection.close() return rows This then lets Flask create a connection for each request, and close it at the end. So any method I call uses this pattern. This also allows for multiple requests etc (websites do that) I'm not saying its perfect, but for every request to the db, you are creating, and closing the db connection so it should never time out. This is very basic, and again, you could combine it with the ping() and allow this to create a new connection etc
has comment: http://stackoverflow.com/comment/82952967

http://stackoverflow.com/comment/82565284
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47801935
has text: WOW my file name is go.csv can you share a code how to read it and then apply above process. sorry i am newbie

join
type: Tag
tag name: join
tags question: http://stackoverflow.com/q/47854282
tags question: http://stackoverflow.com/q/47818984
tags question: http://stackoverflow.com/q/47719040
tags question: http://stackoverflow.com/q/47718590
tags question: http://stackoverflow.com/q/47719657

http://stackoverflow.com/a/47708639
has comment: http://stackoverflow.com/comment/82377299
type: Answer
has body: if sum(1 for e in a if 3.0 &lt;= e &lt; 4.0) &gt;= 2: something() 1 for e in a if 3.0 &lt;= e &lt; 4.0 will return the iterator (1, 1) (i.e. a value 1 for each e such that it is between 3.0 and 4.0); then summing those ones gets us the count of the elements that satisfies the condition. will this early exit when the list a is very long? No. This will, tho, but it makes the logic a bit more complex: from itertools import accumulate if any(n for n in accumulate(1 for e in a if 3.0 &lt;= e &lt; 4.0) if n &gt;= 2): something()
accepted answer of: http://stackoverflow.com/q/47708608
has comment: http://stackoverflow.com/comment/82377179
upvote count: 4
has comment: http://stackoverflow.com/comment/82377134
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47708608
has comment: http://stackoverflow.com/comment/82377873
score: 4

http://stackoverflow.com/q/47850868
has title: definition of axis in pandas any
has answer: http://stackoverflow.com/a/47851165
accepted answer: http://stackoverflow.com/a/47851165
tagged with: python
has body: I have noticed some inconsistent behaviour in how axes are defined (as discussed in in this forum: What does axis in pandas mean?), and I just would like to make sure I understand correctly that: For dropna axis=0 means: the algorithm goes through each row and checks for na's, if there are any/all it deletes that row. For any axis=0 means: the algorithm goes through each column and checks for condition True, if there are any/all it deletes that column So the definition of row and column are switched (although the pandas doc explains 'any' axis as {index (0), columns (1)}. Is this correct?
linked to: http://stackoverflow.com/q/22149584
score: 2
upvote count: 2
type: AnsweredQuestion
tagged with: pandas
tagged with: axis
answer count: 1
downvote count: 0
favorite count: 0
type: Question

http://stackoverflow.com/a/48507987
has body: Overall I wanted to create a PDF report that included a map, and image and some tabular data stored in an Esri geodatabase. Due to lack of info on the above methods and time crunch, I ended up relying on arcpy.Mapping to update map layers elements including an image and export the layout. I used MatplotLib to generate additional charts and tables since there are many examples and threads to assist. As well comes installed with ArcGIS Desktop and Server to avoid having a prerequisite to install 3rd party libs for a client. Here is the sample: import matplotlib.pyplot as plt import xlrd import xlwt import datetime import os import glob import arcpy import SSReport as REPORT import numpy as NUM from matplotlib.backends.backend_pdf import PdfPages as PDF import matplotlib.pyplot as PLT # get path for mxd template from location of script filePath = os.path.dirname(os.path.abspath(__file__)) templatePath = os.path.join(filePath,"templates") def TabletoPDF2(outdir, outputPDF): tables = [os.path.join(outdir,'scratch.gdb', 'table1'), os.path.join(outdir, 'scratch.gdb', 'table2')] pp = PDF(outputPDF) for table in tables: # convert to format for creating charts. ntab = arcpy.da.TableToNumPyArray(table, "*") columns = [fld for fld in ntab.dtype.names if fld not in ["OBJECTID"]] cell_text = [] for row in ntab.tolist(): cell_text.append(row[1:]) fig = PLT.figure(figsize=(8.2, 10.6)) # Create PIECHART (percent lengeth) ax1 = PLT.subplot(211) data = ntab["percent_len"].tolist() vals = [x for x in data if x &gt; 0.] labels = ntab[columns[0]].tolist() labels = [n for n, v in zip(labels, data) if v &gt; 0] ax1.pie(vals, autopct='%1.1f%%', shadow=True, startangle=90) ax1.axis('equal') ax1.legend(labels, loc='center right', fontsize=8, bbox_to_anchor=(1, 1)) # Create TABLE of values ax2 = PLT.subplot(212) the_table = PLT.table(cellText=cell_text, colLabels=columns, loc='center') the_table.auto_set_font_size(True) PLT.axis('off') PLT.tight_layout() #### Set Title #### title = os.path.bas…
answers question: http://stackoverflow.com/q/47819697
type: Answer
score: 0

http://stackoverflow.com/comment/82673022
type: Comment
has text: You are assigning that self.driver to driver variable. Try to use the same in the next function.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47853754

http://stackoverflow.com/a/51717399
score: 1
downvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/47800726
has body: I encountered the same problem because I added the debug_toolbar Middleware to my settings.py 'debug_toolbar.middleware.DebugToolbarMiddleware', I solved the problem by removing the debug_toolbar Middleware. I also had to remove debug_toolbar from my INSTALLED APPS.
upvote count: 2

http://stackoverflow.com/comment/82545413
comment on: http://stackoverflow.com/q/47786886
type: Comment
score: 0
type: QuestionComment
has text: you always use the same `rows` so it always get the same first row of data and put to dictionary. It will not "jump" to next row in every loop. you have to get new row in every loop or try to slice current `rows` - like `rows[10:]`, `rows[40:]`, etc.

http://stackoverflow.com/comment/82690565
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47855569
has text: @JacquesdeHooge I know about that python start (pack/unpack) and C++ star (pointer), but in your approach you assign to a, b and unit a value, but I don't want it, I declare a,b,unit as statics. I want only assign some value to *arg.

http://stackoverflow.com/q/47746393
score: 0
linked to: http://stackoverflow.com/q/10262920
has title: Python: Inplace Merge sort implementation issue
has comment: http://stackoverflow.com/comment/82453292
answer count: 1
tagged with: mergesort
accepted answer: http://stackoverflow.com/a/47746824
has answer: http://stackoverflow.com/a/47746824
type: Question
has comment: http://stackoverflow.com/comment/82474103
tagged with: python
linked to: http://stackoverflow.com/q/13299427
has body: I am implementing inplace merge sort algorithm in python3. Code takes an input array and calls it self recursively (with split array as input) if length of the input array is more than one. After that, it joins two sorted arrays. Here is the code def merge_sort(array): """ Input : list of values Note : It divides input array in two halves, calls itself for the two halves and then merges the two sorted halves. Returns : sorted list of values """ def join_sorted_arrays(array1, array2): """ Input : 2 sorted arrays. Returns : New sorted array """ new_array = [] # this array will contain values from both input arrays. j = 0 # Index to keep track where we have reached in second array n2 = len(array2) for i, element in enumerate(array1): # We will compare current element in array1 to current element in array2, if element in array2 is smaller, append it # to new array and look at next element in array2. Keep doing this until either array2 is exhausted or an element of # array2 greater than current element of array1 is found. while j &lt; n2 and element &gt; array2[j]: new_array.append(array2[j]) j += 1 new_array.append(element) # If there are any remaining values in array2, that are bigger than last element in array1, then append those to # new array. for i in range(j,n2): new_array.append(array2[i]) return new_array n = len(array) if n == 1: return array else: # print('array1 = {0}, array2 = {1}'.format(array[:int(n/2)], array[int(n/2):])) array[:int(n/2)] = merge_sort(array[:int(n/2)]) array[int(n/2):] = merge_sort(array[int(n/2):]) # print('array before joining : ',array) array = join_sorted_arrays(array[:int(n/2)],array[int(n/2):]) # print('array after joining : ',array) return array Now if the code is tested, a = [2,1,4,3,1,2,3,4,2,7,8,10,3,4] merge_sort(a) print(a) out : [1, 1, 2, 2, 3, 3, 4, 2, 3, 4, 4, 7, 8, 10] If you uncomment the print statements in the above function, you will notice that, a = given output, just before the last call of join_sorted_arrays. After …
has comment: http://stackoverflow.com/comment/82452921
type: AnsweredQuestion

http://stackoverflow.com/a/47717970
has comment: http://stackoverflow.com/comment/82396234
type: Answer
score: 6
upvote count: 6
answers question: http://stackoverflow.com/q/47717866
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47717866
has body: The error suggests that you have forgotten quotes when naming a URL pattern. For example you have name=my_view, url('^my-url/$', my_view, name=my_view) when you should use a string name='my_view': url('^my-url/$', my_view, name='my_view')

http://stackoverflow.com/a/63343412
has comment: http://stackoverflow.com/comment/120104551
type: Answer
has body: I've been struggling a bit with this myself and when you're working with MultiIndex Julien's suggestion becomes a little impractical. The solution, however, is relatively simple once you get used to it: simply reindex the dataframe with a new index. In your case this is really very easy: days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri'] df2 = df.reindex(days) df2 A B Sun 3 0 Mon 6 7 Tue 2 1 Wed 5 1 Thu 7 1 Fri 4 2 Note that you cannot perform this operation in place. But it's probably worth noting that you might have to create the index – you certainly do for a dataframe multiple indices. So be prepared to create the index properly using pd.Index() or pd.MultiIndex() When combined with df.swaplevel() this gives you great flexibility.
answers question: http://stackoverflow.com/q/47841373
upvote count: 3
downvote count: 0
score: 3

http://stackoverflow.com/a/47841174
type: Answer
accepted answer of: http://stackoverflow.com/q/47841108
score: 26
type: AcceptedAnswer
has body: You should use request.form if you're posting your data as a regular POST body query, i.e.: @app.route('/schedule/&lt;int:adv_id&gt;', methods=['POST']) def schedule(adv_id): if "time" in request.form: pass # do whatever you want with it
downvote count: 0
has comment: http://stackoverflow.com/comment/82646751
upvote count: 26
has comment: http://stackoverflow.com/comment/82646787
answers question: http://stackoverflow.com/q/47841108

http://stackoverflow.com/comment/82519218
score: 1
type: Comment
type: AnswerComment
has text: @ForceBru it will if you change `wb` to `w+`. I was talking about the use of `with open` in terms of correct methods.
comment on: http://stackoverflow.com/a/47778843

http://stackoverflow.com/comment/82479806
has text: Provide sample data to get assist. Look around how other ppl do.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47758127
type: QuestionComment

http://stackoverflow.com/comment/84359257
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47872756
has text: @ 1st question : Because the output shape of the model is (?, 2, 1). You want to substract square of the whole training set for distance between anchor and positive (which is [:, 0, 0]), and square of the whole training set for distance between anchor and negative (which is [:, 1, 0]).
type: Comment

http://stackoverflow.com/a/47834995
upvote count: 7
score: 7
type: AcceptedAnswer
has body: Python processes tend to retain allocated memory, so if one of your python processes allocates a lot of memory for a given operation (a Django view, a celery task...) it will indeed keep it as long as it's running. As long as memory usage stays mostly stable (I mean: grows to a certain amount after process startup then stays at this amount) and your server doesn't swap, there's usually nothing to worry about, as the processes will keep on reusing the already allocated memory. Now if you find out the memory use keeps on growing ever and ever you possibly have some memory leak somewhere indeed. Beware that running celery - or django FWIW - with settings.DEBUG will cause memory leaks - but you should never run your production processes with the `settings.DEBUG flag set anyway as this is also a security issue. If that's not your case, then you can start searching here and elsewhere on the net for "debugging python memory leak". You may find a good starting point here: It’s not so easy for a Python application to leak memory. Usually there are three scenarios: some low level C library is leaking your Python code have global lists or dicts that grow over time, and you forgot to remove the objects after use there are some reference cycles in your app and here: For celery in particular, you can roll the celery worker processes regularly. This is exactly what the CELERYD_MAX_TASKS_PER_CHILD setting does.
answers question: http://stackoverflow.com/q/47833991
has comment: http://stackoverflow.com/comment/82641021
type: Answer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47833991

http://stackoverflow.com/comment/82570735
type: Comment
type: QuestionComment
has text: Also a minimal working example would be helpful here. What are the values of `dy`, `dx`, `w00`, `pix_spot_list` etc. so we can try rerunning it ourselves?
score: 0
comment on: http://stackoverflow.com/q/47804572

http://stackoverflow.com/q/47701756
tagged with: http://stackoverflow.com/tag/json
answer count: 1
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/5607551
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82363590
tagged with: python
has comment: http://stackoverflow.com/comment/82363497
has title: Dialogflow, How to url encode json as part of the text param?
has comment: http://stackoverflow.com/comment/82363948
upvote count: 2
score: 0
has body: Im trying to create a script, either by Python or PHP, that can receive JSON from Dialogflow webhooks. The data value will be from resolvedQuery. I want to parse the data then send to the below URL: https://joinjoaomgcd.appspot.com/_ah/api/messaging/v1/sendPush?text=***JSON GOES HERE ***&amp;deviceId=18c972b753ad&amp;apikey=5b48aed7 The data from resolvedQuery needs to be sent to the about URL where *JSON GOES HERE * is. Here is the Python code I have been trying: from flask import Flask from flask import request from flask import make_response import json import logging as l import requests app = Flask(__name__) @app.route('/') def hello(): """Return a friendly HTTP greeting.""" l.info("reached the hello() module...") return 'Hello Beautiful World!\n' @app.route('/apiai', methods=['POST']) def apiai_response(): requests_session = requests.session() requests_session.headers.update({'Content-Type': 'application/json'}) requests_session.headers.update({'charset':'utf-8'}) post_data = '[{ "resolvedQuery": "" }]' requests_response = requests_session.post(url="https://joinjoaomgcd.appspot.com/_ah/api/messaging/v1/sendPush?text=***JSON GOES HERE ***&amp;deviceId=18c972b753ad&amp;apikey=5b48aed7", data=post_data) print requests_response.content @app.errorhandler(404) def page_not_found(e): """Return a custom 404 error.""" return 'Sorry, nothing at this URL.', 404
has comment: http://stackoverflow.com/comment/82364659
downvote count: 2
has answer: http://stackoverflow.com/a/47702006

http://stackoverflow.com/a/47706292
type: Answer
has body: I found a solution: {{ title }} {% if packageURLs is defined %} {% for i,x in packagesList %} {{ i }} {% endfor %} {" else "} {% for i in packagesList: %} {{ i }} {% endfor %} {% endif %} Which is populated using zip() in the python script: f = t.render(title=dataType,packagesList=zip(Info,packageURLs),packageURLs=packageURLs) I kept the last variable out of laziness as a check since I still want to only execute those different chunks sometimes.
score: 0
answers question: http://stackoverflow.com/q/47706076

http://stackoverflow.com/comment/82554691
score: 2
has text: Provide the error you get and more of your code, where is the `if...` located in your program, this might be a scope issue.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47796896

http://stackoverflow.com/comment/82359873
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47699473
has text: It's almost as if you want random points on a line. The end points of the line are the min and max that you mentioned.
score: 0

http://stackoverflow.com/comment/82570353
score: 0
type: AnswerComment
has text: @IMCoins it's well defined behaviour, it's called [short-circuit evaluation](https://stackoverflow.com/questions/2580136/does-python-support-short-circuiting)
type: Comment
comment on: http://stackoverflow.com/a/47804237

http://stackoverflow.com/q/47721146
has title: Wagtail: How does one define a custom Block's js_initializer so that subblocks' js_initializers also run?
tagged with: python
has body: I originally asked this question on the wagtail issue queue, which I guess was the wrong place for it. (Though I do think this is a bug in the documentation.) Anyway, my issue is that I have a custom StructBlock class that uses a ListBlock inside it. I need to define a js_initializer() method on my custom class that causes the form to trigger both my own initializer and ListBlock's initializer. My initial attempt, based on the docs, looked like this: # my_blocks.py class ImageGalleryBlock(blocks.StructBlock): images = ListBlock(ImageChooserBlock(label='Image')) def js_initializer(self): return "ImageGallery" @property def media(self): return forms.Media( js=['app/js/admin/image-gallery.js'] ) # image-gallery.js function ImageGallery(prefix) { // Set up the Image Gallery block's custom form behavior... } This make the ImageGallery() function run, but did not run the ListBlock's initializer, so none of its buttons worked. On the wagtail issue queue, I was recommended to try something like this: def js_initializer(self): initializer_js = super(HeadingBlock, self).js_initializer() my_custom_js = 'ImageGallery("%s")' % self.definition_prefix if initializer_js: # child blocks have custom JS initializers and need to be used return '%s,\n%s' % (initializer_js, my_custom_js) return my_custom_js # image-gallery.js function ImageGallery(prefix) { var init_image_gallery = function(element_prefix) { // Do stuff... }; return init_image_gallery; } I had to make a few improvements to the original suggestion to get the ImageGallery() part to function, but it still doesn't run the ListBlock initializer. Here's what the initializer code that gets generated for ImageGalleryBlock looks like: { 'name': ('ImageGalleryBlock'), 'initializer': (StructBlock({ 'images': (ListBlock({ 'definitionPrefix': ('blockdef-63') })) }), ImageGallery("blockdef-91")) }, I get the feeling that what I actually need to do is add another key to the dict being passed into StructBlock, but I haven't got the fogg…
type: Question
has answer: http://stackoverflow.com/a/47743729
tagged with: wagtail
answer count: 1
tagged with: wagtail-streamfield
has comment: http://stackoverflow.com/comment/82411912
accepted answer: http://stackoverflow.com/a/47743729
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/82408963

http://stackoverflow.com/comment/82667562
type: AnswerComment
has text: Thank you @Sruthi, its worked. But what is the difference between your print function implementation and mine. I changed to `if current == None:` and it worked as it is.
type: Comment
comment on: http://stackoverflow.com/a/47851420
score: 0

http://stackoverflow.com/comment/82392652
score: 1
type: Comment
comment on: http://stackoverflow.com/q/47716239
type: QuestionComment
has text: Perhaps you could add your desired output with an example case, in order to clarify what you're asking.

http://stackoverflow.com/comment/82661160
comment on: http://stackoverflow.com/q/47848354
has text: `return` in programming does not exactly mean "go to somewhere else", it means to "give back that variable to the calling function"
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47749684
type: UnansweredQuestion
tagged with: python
score: 4
has body: I got "No module named requests" error while this module is installed (more details after the error): [ ERROR ] Error in file '/Users/adikeller/Applications/GIT/BeAm/Beacon_4.10/STABILITY/beacon_stability_random_beacon_types.txt': Importing test library 'BeAm.beacon.tests.BeaconTesting' failed: ImportError: No module named requests Traceback (most recent call last): File "/Users/adikeller/Applications/GIT/BeAm/BeAm/beacon/tests.py", line 5, in &lt;module&gt; from BeAm.beacon.counters import BeaconCounter File "/Users/adikeller/Applications/GIT/BeAm/BeAm/beacon/counters.py", line 1, in &lt;module&gt; import requests PYTHONPATH: /Users/adikeller/vevn/bin /Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg /Users/adikeller/Applications/GIT/BeAm /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python27.zip /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7 /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-old /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload /Library/Python/2.7/site-packages /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/PyObjC Things I already done: Add working directory to PYTHONPATH: export PYTHONPATH=$PYTHONPATH:/Users/adikeller/Applications/GIT/BeAm Installed "requests" module: sudo pip install requests pip freeze: ... request==0.0.22 requests==2.18.3 robot==20071211 robotframework==3.0.2 robotframework-databaselibrary==0.8.1 robotframework-DiffLibrary2==0.0.2.dev0 robotframework-httplibrary==0.4.2 robotframework-pycurllibr…
downvote count: 0
answer count: 1
upvote count: 4
has answer: http://stackoverflow.com/a/47750608
favorite count: 0
type: Question
has title: Robotframework - "failed: ImportError: No module named requests"
tagged with: robotframework

http://stackoverflow.com/q/47725736
tagged with: allure
type: Question
accepted answer: http://stackoverflow.com/a/47764766
has answer: http://stackoverflow.com/a/47764766
answer count: 1
type: AnsweredQuestion
has body: I am trying to use Allure report with Python3, although the libraries used for Python Pytest are not supported, from what I can see. The documentation say that Allure plugin for pytest support the previous version of allure only. Is there a workaround to use pytest on python3, and get the Allure reports created?
score: 0
tagged with: pytest
has title: Use Allure report V2 via pytest on Python3
tagged with: python

http://stackoverflow.com/comment/82583942
score: 0
type: AnswerComment
has text: If the dictionary contains both the lower and upper case letters, you will only need one pass over the string. And by generalising the shift with a parameter, you get a Caesar cipher.
type: Comment
comment on: http://stackoverflow.com/a/47811203

http://stackoverflow.com/q/47837122
tagged with: python-3.x
upvote count: 2
has comment: http://stackoverflow.com/comment/82638837
has body: This is a followup to Python. How to print a certain part of a line after it had been "re.searched" from a file Here is the initial code, based on the accepted answer to the linked question: import re VSP = input("Номер ВСП (четыре цифры): ") c = re.compile('(\d+\.226\.\S+)\s+\S+' + VSP) Tunnel0_IP_VSP = re.search(c, open('OUS_IP.txt').read()) print (Tunnel1_IP_VSP.group(1)) Номер ВСП (четыре цифры): 1020 10.226.27.60 I was able to find the requested IP address in text file. My goal is to somehow convert the string "10.226.27.60" to a format that would allow me to use it in mathematical formulas. For example, I want to get another address "10.226.27.59" by subtracting 1 from the last octet of the original address.
has answer: http://stackoverflow.com/a/47837470
possible better answer: http://stackoverflow.com/a/47837453
has comment: http://stackoverflow.com/comment/82638386
downvote count: 1
has comment: http://stackoverflow.com/comment/82638674
has answer: http://stackoverflow.com/a/47837453
has title: Converting group() to float or int format
type: AnsweredQuestion
answer count: 3
accepted answer: http://stackoverflow.com/a/47837381
score: 1
has answer: http://stackoverflow.com/a/47837381
tagged with: python
linked to: http://stackoverflow.com/q/47820803
has comment: http://stackoverflow.com/comment/82638552
favorite count: 0
type: Question

http://stackoverflow.com/comment/82564214
has text: Yes; if A comes before B, then `A.say_hello` will always be called before `B.say_hello`, which will prevent `B.say_hello` from being called at all.
score: 2
comment on: http://stackoverflow.com/a/47801465
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47707692
has body: So I am trying to work on a project for school and I wanted to create a prompt function that would allow me to enter in the question, type of prompt, the function that it would run if the input was "Y", and the response string it would output if the user replied "N". This is my code: #Will Steve Become a Millionaire? #Interactive Fiction #Zachary Williams ##Type 0 prompt = Y/N, Type 1 prompt = Int input. def prompt(question, qType, yFunction, nResponse): print(question) answer=input() if qType==0: if answer=="Y" or answer=="y": yFunction() elif answer=="N" or answer=="n": print(nResponse) if answer=="X": print("test") else: print("\"" + answer + "\" is not one of the options. Please type \"Y\" or \"N\".") elif qType==1: print("test") else: print("Error creating prompt.") ##Start the story. def start_program(): print("It was 3:45 AM on a Saturday night. The only light in the room shone upon Steve's face, coming from the screen of his laptop, which he had been staring at for almost 12 hours straight. This was nothing new for Steve, but then an email popped up.") prompt("\nWould you like to read the email? (Y/N)", 0, open_email(), "Steve closed the notification. It was time to go to bed.") def opening(): print("Will Steve Become a Millionaire?") prompt("Starting the program.", 0, start_program(), "Okay then.") def open_email(): print("\nSteve opened the email.") print("\n\"I am Prince Kufour Otumfuo,\" the email read, \"I am transferring $75,000,000 USD to the United States, and need your help to transport it into the country. If you help me do so, I will only have you transfer $65,000,000 to my account, leaving you with $10,000,000 to keep. If you would be so kind, please reply to this email.\"") opening() Currently, this is what it returns when I run the program: Will Steve Become a Millionaire? It was 3:45 AM on a Saturday night. The only light in the room shone upon Steve's face, coming from the screen of his laptop, which he had been staring at for almost 12 hours…
has title: Why is my function running without asking for the input first?
type: AnsweredQuestion
answer count: 2
has answer: http://stackoverflow.com/a/47707799
score: 1
possible better answer: http://stackoverflow.com/a/47707777
downvote count: 0
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47707799
has comment: http://stackoverflow.com/comment/82375367
has answer: http://stackoverflow.com/a/47707777
upvote count: 1
tagged with: python

http://stackoverflow.com/a/47846727
type: Answer
score: 3
upvote count: 3
downvote count: 0
answers question: http://stackoverflow.com/q/47845448
has body: Usually, this means that something converges to infinity. As @desertnaut pointed out in the comment, reducing the learning rate might help. But the root of the issue is your input data. What do these 425 data points mean? Are they from different sources, different features, different parameters? Finding outliners or normalizing the data, could help. Your code looks fine otherwise.

http://stackoverflow.com/comment/82474053
type: Comment
type: QuestionComment
has text: I just edited the image to show the image_batch = [] is within the if statement. The code I'm referring to is between for p in images_path: and if bi % 100 == 0
score: 0
comment on: http://stackoverflow.com/q/47756176

http://stackoverflow.com/comment/82484484
comment on: http://stackoverflow.com/q/47761528
type: QuestionComment
has text: `digits[n%b]` can be replaced by `chr(48 + n%b)` therefore `digits` can be removed then.
score: 0
type: Comment

http://stackoverflow.com/comment/82547367
score: 0
type: AnswerComment
has text: in our chat, I asked you a question about the code you gave me. Please can you help me with it @NickA
comment on: http://stackoverflow.com/a/47774095
type: Comment

http://stackoverflow.com/q/47698334
has comment: http://stackoverflow.com/comment/82393415
has comment: http://stackoverflow.com/comment/82357489
has comment: http://stackoverflow.com/comment/82357558
has comment: http://stackoverflow.com/comment/82357592
type: Question
has comment: http://stackoverflow.com/comment/82379435
has comment: http://stackoverflow.com/comment/82357262
has answer: http://stackoverflow.com/a/64769839
has comment: http://stackoverflow.com/comment/82371589
has body: I would like to be able to do, for example: pmap = persistent_map(function, iterable(args)) foo = map(bar, pmap) baz = map(bar, pmap) # right-hand side intentionally identical to that of the previous line. The interpreter would know to reset pmap before using it to construct baz. I know that I could store the result of pmap as a tuple, list, or other structure (which is what I have done in my present application), but I don't want to have do that because of the possibilities of 1) huge storage requirements (also consider copies) and 2) different results on reevalation, as when iterable is produced from a dynamic file. If the equivalent of persistent_map exists, what is the corresponding built-in feature or standard library feature? Alternatively, is there a third-party (hopefully reliable and readily available) persistent_map equivalent? If only extant option is third-party, how might you create persistent_map using only built-in and, possibly, standard library features? In response to @MartijnPieters comment, "that's what generators are for", are you saying that one solution would be something like def persistent_map(function, iterable): from functools import partial return partial(map, function, iterable) foo = map(bar, pmap()) baz = map(bar, pmap()) # A toy example: pmap = persistent_map(hex, range(3)) foo = map(len , pmap()) baz = map(hash, pmap()) print(*zip(pmap(), foo, baz)) ('0x0', 3, 982571147) ('0x1', 3, 982571146) ('0x2', 3, 982571145) In response to @kmiya ("Bit too late...") and also, now that I think I understand better what @MartijnPieters meant by "that's what generators are for," I would do it this way: class PersistentMap: def __init__(self, func, generator): self.func = func self.generator = generator def __iter__(self): return map( self.func, # THIS IS HOW "The interpreter [knows] to reset:" self.generator() ) # AN EXAMPLE GENERATOR. # NOTE THAT STORING "ALL" THE GENERATED VALUES IS IMPOSSIBLE. def tictoc(): k = 0 while True: yield k k = 1 - k pm…
has title: How do you create a reusable or persistent map in Python 3?
type: UnansweredQuestion
answer count: 1
downvote count: 0
upvote count: 1
tagged with: dictionary
has comment: http://stackoverflow.com/comment/82359434
tagged with: copy
favorite count: 0
has comment: http://stackoverflow.com/comment/82359539
tagged with: persistent-storage
linked to: http://stackoverflow.com/q/231767
has comment: http://stackoverflow.com/comment/82356722
has comment: http://stackoverflow.com/comment/82357358
score: 1
has comment: http://stackoverflow.com/comment/82356793
tagged with: reset
tagged with: python

http://stackoverflow.com/a/47725138
downvote count: 0
has comment: http://stackoverflow.com/comment/82411018
has comment: http://stackoverflow.com/comment/82411073
score: 4
has comment: http://stackoverflow.com/comment/82411121
type: Answer
answers question: http://stackoverflow.com/q/47725110
has body: I usually use ast.literal_eval to parse “elementary” data types: type(ast.literal_eval('50')) # outputs int You need however a set of quotes to mark something as a string (otherwise every input could be taken as a string): type(ast.literal_eval('run')) # error type(ast.literal_eval('"run"')) # string If you want to allow unqouted strings you could do the following: def parse_data(x): """Takes a string x and returns the "value" of x""" try: return ast.literal_eval(x) except (ValueError, SyntaxError): return x
upvote count: 4
accepted answer of: http://stackoverflow.com/q/47725110
type: AcceptedAnswer

http://stackoverflow.com/comment/82515334
score: 0
has text: It's not clear what you are trying to do here. You get a ticker symbol from an API, but then attempt to use a serializer with an existing queryset to create an object. Why? What is the point of the serializer here? And why are you treating a queryset (`currency`) like a dictionary?
type: QuestionComment
comment on: http://stackoverflow.com/q/47777090
type: Comment

http://stackoverflow.com/q/47850260
tagged with: python
has comment: http://stackoverflow.com/comment/82665807
has answer: http://stackoverflow.com/a/47850295
possible better answer: http://stackoverflow.com/a/47850322
tagged with: listings
type: AnsweredQuestion
answer count: 2
has body: i want to write listings to csv as coloumns. Every listing have more then 100 output. I give example of csv below thanks csv output example: coloumn 1 coloumn 2 coloumn 3 coloumn 4 coloumn 5 listing 1_output1 listing 2_output1 ... ... ... listing 1_output2 listing 2_output2 ... ... ... listing 1_output3 listing 2_output3 ... ... ... ... ... ... ... ... import bs4 as bs import urllib.request import csv sauce = urllib.request.urlopen('http...').read() soup = bs.BeautifulSoup(sauce, 'lxml') for listing in soup.find_all('div', class_='bigletter1'): for listing2 in soup.find_all('td', class_='bigletter2'): for listing3 in soup.find_all('td', class_='bigletter3'): for listing4 in soup.find_all('td', class_='bigletter4'): for listing5 in soup.find_all('td', class_='bigletter5'): thank you for your answers but also i have non-numeric class also like class_='models' how can i write to in csv?
has comment: http://stackoverflow.com/comment/82665524
upvote count: 0
has comment: http://stackoverflow.com/comment/82671675
downvote count: 2
has title: python writing listing csv as columns
has comment: http://stackoverflow.com/comment/82665962
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47850322
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/82665356
score: -2
accepted answer: http://stackoverflow.com/a/47850295

http://stackoverflow.com/comment/82412225
has text: try to use just jquery and pure html without bootstrap and pooper.js, your code is okay, if it won't work try to connect jquery cdn
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47713934
type: Comment

http://stackoverflow.com/a/60647800
upvote count: 2
has body: You're almost success! What you want could be: def _kernel_is_idle(self): return EC.visibility_of_element_located( (By.XPATH, '//*[@id="kernel_indicator_icon" and @title="Kernel Idle"]') )(driver) Here, you should pass the webdriver object as an argument.
downvote count: 0
answers question: http://stackoverflow.com/q/47790010
type: Answer
score: 2

http://stackoverflow.com/q/47808950
has title: Not getting output with cycle tag in django
score: 0
has body: I am trying my hand on cycle tag of django, but when i use the below code the output is not as expected ``` this is a world which is {{ html_temp }} {% for o in list %} {{ o }} {% endfor %} ``` I got the output as black text instead of colored text because I make the classes row1 and row2 as blue and green respectively. where I am getting it wrong?
has comment: http://stackoverflow.com/comment/82580856
type: Question
has comment: http://stackoverflow.com/comment/82580573
answer count: 0
tagged with: django
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82580782

http://stackoverflow.com/comment/82607000
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47821248
has text: I did try that, the location is correct. FYI I am using a Mac. Thanks for your pointers, is there anything else that you may suggest ?
score: 0

http://stackoverflow.com/q/47709324
tagged with: screen-scraping
tagged with: selenium
downvote count: 0
has body: I am scraping a pool of urls with selenium/geckodriver and joblib in paralell: Parallel(n_jobs=40)(delayed(scrape)(URL) for URL in final_url_list) The current challenge is that I am getting EmptyDataError for for a significant amount of joblib runs/URLs although I know the data are there and online. My temporary solution is to repeat the iteration/run whenever EmptyDataError comes up: def scrape(URL): while True: try: scraping_logic[...] # Do the scraping except EmptyDataError: # handle EmptyDataError print "scraping failed due to unknown reason - repeat" # notify continue # repeat scraping this URL else: break # finish However, I keep having ~20 repeats for some URLs in extreme cases. Therefore, this solution is not optimal. Q1: What is the cause of this error, given that the to-be-scraped data are in fact there? Q2: How to tweak the code to minimize the chance of wasting time on too many repeating iterations? Note that this error also comes up in the same frequency when I run joblib with n_jobs = 1, therefore we can exclude the root cause to be too many joblib workers.
upvote count: 1
tagged with: joblib
favorite count: 0
type: Question
type: UnansweredQuestion
has title: EmptyDataError while scraping with selenium and joblib although data are there
tagged with: python
answer count: 0
score: 1

http://stackoverflow.com/comment/82589572
score: 0
has text: Yes, that part seems a bit odd, as myfunction is not a class method. Not sure how this would or could work.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47813835

http://stackoverflow.com/a/47721936
accepted answer of: http://stackoverflow.com/q/47721524
upvote count: 2
score: 2
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47721524
has comment: http://stackoverflow.com/comment/82405154
has comment: http://stackoverflow.com/comment/82404973
type: Answer
has body: I think that multiprocessing takes quite a long time to create and start each process. I have changed the program to make 10 times the size of arr and changed the way that the processes are started and there is a slight speed-up: (Also note python 3) import time import multiprocessing, threading from multiprocessing import Queue import random def calc_square_q(numbers,q): while q.empty(): pass return calc_square(numbers) if __name__ == "__main__": random.seed(1) # note how big arr is now vvvvvvv arr = [random.randint(1, 11) for i in range(10000000)] print("init completed") # ... # other stuff as before # ... processes=[] q=Queue() for arrs in newarr: processes.append(multiprocessing.Process(target=calc_square_q, args=(arrs,q))) print('start processes') for p in processes: p.start() # even tho' each process is started it waits... print('join processes') q.put(None) # ... for q to become not empty. start_time = time.time() for p in processes: p.join() end_time = time.time() print("mp: " + str(end_time - start_time)) Also notice above how I create and start the processes in two different loops, and then finally join with the processes in a third loop. Output: init completed serial: 0.53214430809021 split complete start threads mt: 0.5551605224609375 start processes join processes mp: 0.2800724506378174 Another factor of 10 increase in size of arr: init completed serial: 5.8455305099487305 split complete start threads mt: 5.411392450332642 start processes join processes mp: 1.9705185890197754 And yes, I've also tried this in python 2.7, although Threads seemed slower.
has comment: http://stackoverflow.com/comment/82404882
has comment: http://stackoverflow.com/comment/82404454
has comment: http://stackoverflow.com/comment/82404951
has comment: http://stackoverflow.com/comment/82405117

http://stackoverflow.com/comment/82366955
has text: Thats actually perfect. Thanks a ton! But there are several start and stop in the file, how do I separate them individual suppose there are 5-6 sets of start and stop. So while parsing when start comes it writes into a file/df and when stop comes just exit, so the df consists of just one set of start stop values.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47703309
type: AnswerComment

http://stackoverflow.com/a/47724464
upvote count: 7
has body: Fixed the error by updating to Keras version 2.1.2.
answers question: http://stackoverflow.com/q/47724077
score: 7
type: Answer
has comment: http://stackoverflow.com/comment/92520909
has comment: http://stackoverflow.com/comment/90743635
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47724077

http://stackoverflow.com/a/47735443
has comment: http://stackoverflow.com/comment/82449481
has body: Let's see what happens if we calculate the mouse position and offset with pygame.mouse.get_pos() and vectors. Check out if this program produces the same error: import pygame from pygame.math import Vector2 pygame.init() game_display = pygame.display.set_mode((800,600)) pygame.mouse.set_visible(False) pygame.event.set_grab(True) clock = pygame.time.Clock() game_exit = False previous_pos = Vector2(pygame.mouse.get_pos()) while not game_exit: mouse_move = (0,0) for event in pygame.event.get(): if event.type == pygame.QUIT: game_exit = True elif event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: game_exit = True current_pos = Vector2(pygame.mouse.get_pos()) print(current_pos-previous_pos) previous_pos = current_pos clock.tick(3) # 3 frames per second. pygame.quit()
type: Answer
has comment: http://stackoverflow.com/comment/82555113
score: 0
has comment: http://stackoverflow.com/comment/82440462
answers question: http://stackoverflow.com/q/47735159

tableau-api
type: Tag
tag name: tableau-api
tags question: http://stackoverflow.com/q/47720252

http://stackoverflow.com/q/47760423
has answer: http://stackoverflow.com/a/47761080
accepted answer: http://stackoverflow.com/a/47761080
favorite count: 0
type: Question
tagged with: turtle-graphics
score: -3
tagged with: python
has comment: http://stackoverflow.com/comment/82482901
type: AnsweredQuestion
upvote count: 0
has title: Using print if a window is clicked?
downvote count: 3
answer count: 1
has body: I want to create a program in Python turtle graphics so that if the window is clicked it will print "hello." Is there any certain code to be used here?

http://stackoverflow.com/q/47778342
has title: Delete items from nested dict recursively
tagged with: python
possible better answer: http://stackoverflow.com/a/47778572
tagged with: recursion
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/82518124
accepted answer: http://stackoverflow.com/a/47778436
has body: Sorry for stupid question, but what am i doing wrong? I have nested dict, which i was hope to dump into json. [{'text': 'Root', 'children': [{'text': 'X', 'children': [None, None], 'id': 2}, {'text': 'Y', 'children': [], 'id': 3}], 'id': 1}] I need to remove all 'None' values from it. Here is my code: for items in sub_tree_dicts: del_null(items['children']) def del_null(childrens): for child in childrens: if child is None: childrens.remove(child) else: del_null(child['children']) Unfortunately, code does not work as expected and removes only first 'None' from the list. Where am I wrong? Thanx.
has answer: http://stackoverflow.com/a/47778436
has answer: http://stackoverflow.com/a/47778572
has comment: http://stackoverflow.com/comment/82518093
has comment: http://stackoverflow.com/comment/82518021
type: Question
has comment: http://stackoverflow.com/comment/82517832
answer count: 2

http://stackoverflow.com/q/47854980
tagged with: python
has comment: http://stackoverflow.com/comment/82674550
score: 0
has answer: http://stackoverflow.com/a/47855058
has title: How to add an element to the list in the dictionary in python?
has comment: http://stackoverflow.com/comment/82674146
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/82674669
has answer: http://stackoverflow.com/a/47855052
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82675424
has body: import itertools from collections import defaultdict my_tree={'parent':'Smith', 'children':[{'parent':'Connor', 'children':[{'parent':'Alexis','children': [{'parent':'Joe', 'children':[{'parent':'Clark','children':[]}]}]},{'parent':'Sue','children':[]}]}, {'parent':'Cooper', 'children':[{'parent':'Max','children':[{'parent':'Luis', 'children':[]},]}, {'parent':'Elvis', 'children':[]},{'parent':'Steven', 'children':[]}]}]} class Person: ID = itertools.count() def __init__(self, name, parent=None, level=0): self.id = self.__class__.ID.next() self.parent = parent self.name = name self.level = level self.children = [] def createTree(d, parent=None, level=0): if d: member = Person(d['parent'], parent, level) level = level + 1 member.children = [createTree(child, member, level) for child in d['children']] return member t = createTree(my_tree) def printout(parent, indent=0): print '\t'*indent, parent.name for child in parent.children: printout(child, indent+1) printout(t) I want to add elements into the list in my_tree dictionary. For example, I want to add a new child for Sue.

http://stackoverflow.com/comment/82423783
comment on: http://stackoverflow.com/a/47730438
score: 0
type: Comment
type: AnswerComment
has text: Thanks! Can I ask another one?

http://stackoverflow.com/q/47734084
has answer: http://stackoverflow.com/a/47734213
tagged with: pandas
score: 0
type: Question
answer count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47734225
has body: Basically, what I'm working with is a dataframe with all of the parking tickets given out in one year. Every ticket takes up its own row in the unaltered dataframe. What I want to do is group all the tickets by date so that I have 2 columns (date, and the amount of tickets issued on that day). Right now I can achieve that, however, the date is not considered a column by pandas. import numpy as np import matplotlib as mp import pandas as pd import matplotlib.pyplot as plt df1 = pd.read_csv('C:/Users/brett/OneDrive/Data Science Fundamentals/Parking_Tags_Data_2012.csv') unnecessary_cols = ['tag_number_masked', 'infraction_code', 'infraction_description', 'set_fine_amount', 'time_of_infraction', 'location1', 'location2', 'location3', 'location4', 'province'] df1 = df1.drop (unnecessary_cols, 1) df1 = (df1.groupby('date_of_infraction').agg({'date_of_infraction':'count'})) df1['frequency'] = (df1.groupby('date_of_infraction').agg({'date_of_infraction':'count'})) print (df1) df1 = (df1.iloc[121:274]) The output is: date_of_infraction date_of_infraction frequency 20120101 1059 NaN 20120102 2711 NaN 20120103 6889 NaN 20120104 8030 NaN 20120105 7991 NaN 20120106 8693 NaN 20120107 7237 NaN 20120108 5061 NaN 20120109 7974 NaN 20120110 8872 NaN 20120111 9110 NaN 20120112 8667 NaN 20120113 7247 NaN 20120114 7211 NaN 20120115 6116 NaN 20120116 9168 NaN 20120117 8973 NaN 20120118 9016 NaN 20120119 7998 NaN 20120120 8214 NaN 20120121 6400 NaN 20120122 6355 NaN 20120123 7777 NaN 20120124 8628 NaN 20120125 8527 NaN 20120126 8239 NaN 20120127 8667 NaN 20120128 7174 NaN 20120129 5378 NaN 20120130 7901 NaN ... ... ... 20121202 5342 NaN 20121203 7336 NaN 20121204 7258 NaN 20121205 8629 NaN 20121206 8893 NaN 20121207 8479 NaN 20121208 7680 NaN 20121209 5357 NaN 20121210 7589 NaN 20121211 8918 NaN 20121212 9149 NaN 20121213 7583 NaN 20121214 8329 NaN 20121215 7072 NaN 20121216 5614 NaN 20121217 8038 NaN 20121218 8194 NaN 20121219 6799 NaN 20121220 7102 NaN 20121221 7616 NaN 20121222 5575 Na…
tagged with: dataframe
tagged with: python
has title: I'm trying modify a pandas data frame so that I will have 2 columns. A frequency column and a date column.

http://stackoverflow.com/comment/83350712
has text: Okay, so one should share inputs. but what about results? (I have the same problem, but on the results of my computation that seems to be too big...)
score: 0
comment on: http://stackoverflow.com/a/47776649
type: Comment
type: AnswerComment

selenium
tags question: http://stackoverflow.com/q/47830384
tags question: http://stackoverflow.com/q/47711009
tags question: http://stackoverflow.com/q/47783834
tags question: http://stackoverflow.com/q/47848426
tags question: http://stackoverflow.com/q/47791232
tags question: http://stackoverflow.com/q/47768123
tags question: http://stackoverflow.com/q/47832281
tags question: http://stackoverflow.com/q/47817665
tags question: http://stackoverflow.com/q/47714808
tags question: http://stackoverflow.com/q/47801788
tags question: http://stackoverflow.com/q/47832693
tags question: http://stackoverflow.com/q/47708815
tags question: http://stackoverflow.com/q/47814507
tags question: http://stackoverflow.com/q/47787289
tags question: http://stackoverflow.com/q/47699006
tags question: http://stackoverflow.com/q/47853073
tags question: http://stackoverflow.com/q/47710581
tags question: http://stackoverflow.com/q/47753932
tags question: http://stackoverflow.com/q/47716814
tags question: http://stackoverflow.com/q/47783718
tags question: http://stackoverflow.com/q/47826527
tags question: http://stackoverflow.com/q/47749117
tags question: http://stackoverflow.com/q/47706246
tags question: http://stackoverflow.com/q/47739636
tags question: http://stackoverflow.com/q/47710452
tags question: http://stackoverflow.com/q/47854978
tags question: http://stackoverflow.com/q/47751529
tags question: http://stackoverflow.com/q/47730240
tags question: http://stackoverflow.com/q/47807790
tags question: http://stackoverflow.com/q/47718513
tags question: http://stackoverflow.com/q/47818177
tags question: http://stackoverflow.com/q/47843889
tags question: http://stackoverflow.com/q/47841851
tags question: http://stackoverflow.com/q/47822507
tags question: http://stackoverflow.com/q/47770163
tags question: http://stackoverflow.com/q/47724502
tags question: http://stackoverflow.com/q/47737685
tags question: http://stackoverflow.com/q/47759732
tags question: http://stackoverflow.com/q/47710144
tags question: http://stackoverflow.com/q/47817006
tags question: http://stackoverflow.com/q/47770694
tags question: http://stackoverflow.com/q/47785882
tags question: http://stackoverflow.com/q/47834384
tags question: http://stackoverflow.com/q/47822369
tags question: http://stackoverflow.com/q/47833818
tags question: http://stackoverflow.com/q/47709324
tags question: http://stackoverflow.com/q/47782650
tags question: http://stackoverflow.com/q/47828481
tags question: http://stackoverflow.com/q/47789436
tags question: http://stackoverflow.com/q/47722143
tags question: http://stackoverflow.com/q/47813386
tags question: http://stackoverflow.com/q/47746261
tags question: http://stackoverflow.com/q/47838519
tags question: http://stackoverflow.com/q/47772143
tags question: http://stackoverflow.com/q/47842660
tags question: http://stackoverflow.com/q/47774281
tags question: http://stackoverflow.com/q/47698704
tags question: http://stackoverflow.com/q/47765944
tags question: http://stackoverflow.com/q/47782503
tags question: http://stackoverflow.com/q/47759491
tags question: http://stackoverflow.com/q/47788448
tags question: http://stackoverflow.com/q/47728220
tags question: http://stackoverflow.com/q/47831039
tags question: http://stackoverflow.com/q/47811895
tags question: http://stackoverflow.com/q/47815334
tags question: http://stackoverflow.com/q/47712425
tags question: http://stackoverflow.com/q/47762071
tags question: http://stackoverflow.com/q/47765114
tags question: http://stackoverflow.com/q/47812933
tags question: http://stackoverflow.com/q/47745226
type: Tag
tags question: http://stackoverflow.com/q/47749627
tags question: http://stackoverflow.com/q/47699197
tags question: http://stackoverflow.com/q/47854372
tags question: http://stackoverflow.com/q/47788417
tags question: http://stackoverflow.com/q/47855781
tags question: http://stackoverflow.com/q/47719291
tags question: http://stackoverflow.com/q/47854129
tags question: http://stackoverflow.com/q/47772911
tags question: http://stackoverflow.com/q/47853754

http://stackoverflow.com/comment/82452988
comment on: http://stackoverflow.com/a/47742378
type: Comment
has text: +1 for detailed information, I am trying to upload images from client(javascript) to s3, And generating s4 signature from backend(python). Unfortunately I am not able upload image. Because of signature missmatch. Do you have any doc for complete S4 process for my need. I tried multiple ways but I failed.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/82508462
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47773650
score: 0
has text: I specified it a bit. I haven't tried anything as I didn't find anything similar, or just don't know how to look for it :/

sorting
tags question: http://stackoverflow.com/q/47754920
tags question: http://stackoverflow.com/q/47740102
tags question: http://stackoverflow.com/q/47853828
tags question: http://stackoverflow.com/q/47775624
tags question: http://stackoverflow.com/q/47843504
tags question: http://stackoverflow.com/q/47847649
tags question: http://stackoverflow.com/q/47776176
tags question: http://stackoverflow.com/q/47787204
tags question: http://stackoverflow.com/q/47800782
tags question: http://stackoverflow.com/q/47734554
tags question: http://stackoverflow.com/q/47708239
tags question: http://stackoverflow.com/q/47795746
tag name: sorting
tags question: http://stackoverflow.com/q/47713028
tags question: http://stackoverflow.com/q/47815650
tags question: http://stackoverflow.com/q/47710068
tags question: http://stackoverflow.com/q/47760015
tags question: http://stackoverflow.com/q/47745677
tags question: http://stackoverflow.com/q/47746361
tags question: http://stackoverflow.com/q/47762563
tags question: http://stackoverflow.com/q/47752662
tags question: http://stackoverflow.com/q/47716940
tags question: http://stackoverflow.com/q/47759551
tags question: http://stackoverflow.com/q/47703921
tags question: http://stackoverflow.com/q/47760355
tags question: http://stackoverflow.com/q/47770599
tags question: http://stackoverflow.com/q/47819417
tags question: http://stackoverflow.com/q/47750532
type: Tag

http://stackoverflow.com/comment/82422948
comment on: http://stackoverflow.com/a/47712701
type: AnswerComment
score: 0
type: Comment
has text: It's not only for NUKE users)) For Photoshop users too: To prepare your images for consistent display quality you’ll need to convert files to the sRGB color profile. sRGB is the color profile used by most web browsers to display images on the web.

http://stackoverflow.com/a/47782466
has body: filter() is an iterator object; you'll need to actually iterate over it to pull out the results. In this case, you want a string back, so you could use str.join() to do the iteration and put everything back into a single string: line2 = ''.join(filter(str.isalnum, line)) Note that you shouldn't really need to use a while True loop with file1.readline() calls. You can use a for loop directly over the file to get the lines by replacing the while True, line = file1.readline() and if len(line) == 0: break lines with: for line in file1: # ...
downvote count: 0
has comment: http://stackoverflow.com/comment/82527444
has comment: http://stackoverflow.com/comment/82528771
has comment: http://stackoverflow.com/comment/82526307
score: 3
has comment: http://stackoverflow.com/comment/82526313
has comment: http://stackoverflow.com/comment/82526286
type: Answer
has comment: http://stackoverflow.com/comment/82526503
has comment: http://stackoverflow.com/comment/82526536
has comment: http://stackoverflow.com/comment/82526472
answers question: http://stackoverflow.com/q/47782404
upvote count: 3

http://stackoverflow.com/q/47855082
has body: I have various functions accepting the same arguments and returning the same type. They do similar things (eg. performing integration with different approximate methods) and differ only in name. I want to force all variations to have the same signature. It could be done by wrapping them into classes, but there's no conceptual reason to. So, is there a concept similar to interface for functions? That is, is there any way to do something like abstract Double integration(Double[] xs, Double[] ys); Double RiemmannIntegration implements integration(...) {...} Obviously, the question makes sense only for languages in which functions are first class objects (i'm mostly interested in python/javascript).
has comment: http://stackoverflow.com/comment/82674313
tagged with: javascript
has answer: http://stackoverflow.com/a/47855532
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47855398
tagged with: python
tagged with: language-agnostic
score: -1
has comment: http://stackoverflow.com/comment/82674248
has comment: http://stackoverflow.com/comment/82675089
has comment: http://stackoverflow.com/comment/82675146
has comment: http://stackoverflow.com/comment/82675574
has title: Is there a concept like *interface* for functions?
answer count: 2
upvote count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/47783594
has answer: http://stackoverflow.com/a/47799033
type: UnansweredQuestion
has title: Calculate values shifting by column or looping over column
tagged with: loops
has comment: http://stackoverflow.com/comment/82530033
has comment: http://stackoverflow.com/comment/82528976
type: Question
tagged with: pandas
has answer: http://stackoverflow.com/a/47784099
tagged with: python
has comment: http://stackoverflow.com/comment/82528635
tagged with: python-3.x
score: 0
answer count: 2
has body: I have the following dataframe, first to calculate the following math operation year+n/year.value==2009 for every cohort and then perform the mean for each cohort df id year 2009 2010 2011 2012 2013 2014 2015 cohort 2009.0 72092.0 60513.0 48797.0 40968.0 34919.0 30452.0 26961.0 2010.0 NaN 73735.0 61899.0 50263.0 42184.0 36150.0 31516.0 2011.0 NaN NaN 76809.0 64093.0 51372.0 43277.0 36994.0 2012.0 NaN NaN NaN 69776.0 57621.0 46453.0 39098.0 2013.0 NaN NaN NaN NaN 71613.0 58996.0 47657.0 2014.0 NaN NaN NaN NaN NaN 65430.0 52540.0 2015.0 NaN NaN NaN NaN NaN NaN 67121.0 2016.0 NaN NaN NaN NaN NaN NaN NaN 2017.0 NaN NaN NaN NaN NaN NaN NaN I will show the math operation that i want to perform because my english is not good and math is a universal language :) For whenever 1 year pass since 2009: (n=1) first value needed = ((60513.0/72092.0) + (61899.0/73735.0) + (64093.0+76809.0) + (57621.0/69776.0) + (58996.0+71613.0) + (52540.0/65430.0))/6 For whenever 2 year pass since 2009: (n=2) second value needed = ((48797.0/72092.0) + (50263.0/73735.0) + (51372.0/76809.0) + (46453.0/69776.0) + (47657.0/71613.0))/5 For whenever 3 year pass since 2009: (n=3) (Last one, i think with this one the looping of what i want to do will be understand) third value needed = ((40968.0/72092.0) + (42184.0/73735.0) + (43277.0/76809.0) + (39098.0/69776.0))/4 And so on until the last value would be last value = 26961.0/72092.0 Thanks in advance and sorry for my english I am trying somethin like this, maybe it can help First value: ((df1.iloc[0,1]/df1.iloc[0,0]) + (df1.iloc[1,2]/df1.iloc[1,1]) + (df1.iloc[2,3]/df1.iloc[2,2]) + (df1.iloc[3,4]/df1.iloc[3,3]) + (df1.iloc[4,5]/df1.iloc[4,4]) + (df1.iloc[5,6]/df1.iloc[5,5]))/6 Second value: ((df1.iloc[0,2]/df1.iloc[0,0]) + (df1.iloc[1,3]/df1.iloc[1,1]) + (df1.iloc[2,4]/df1.iloc[2,2]) + (df1.iloc[3,5]/df1.iloc[3,3]) + (df1.iloc[4,6]/df1.iloc[4,4]))/5 Third value: ((df1.iloc[0,3]/df1.iloc[0,0]) + (df1.iloc[1,4]/df1.iloc[1,1]) + (df1.iloc[2,5]/df1.iloc[2,2]…

http://stackoverflow.com/a/47698735
has body: You can convert your day/month format to day in year format and then compare each element in the list based on the year then the day
answers question: http://stackoverflow.com/q/47698688
type: Answer
score: 0

django-apps
tag name: django-apps
tags question: http://stackoverflow.com/q/47784922
type: Tag

http://stackoverflow.com/comment/82571395
type: QuestionComment
score: 0
has text: I'm not sure about the specific module but one approach is to change the for loop to `for e in event: print(e)` and find out what kind of objects come out.
comment on: http://stackoverflow.com/q/47804880
type: Comment

http://stackoverflow.com/q/47814048
tagged with: seaborn
type: UnansweredQuestion
score: 1
tagged with: boxplot
tagged with: python
has body: I have created a boxplot using pandas dataframe and now I want to mark specific values in the same plot, with an "X" (hopefully in screaming red!). Some data: df = pd.DataFrame( [ [2, 4, 5, 6, 1], [4, 5, 6, 7, 2], [5, 4, 5, 5, 1], [10, 4, 7, 8, 2], [9, 3, 4, 6, 2], [3, 3, 4, 4, 1] ], columns=['a1', 'a2', 'a3', 'a4', 'b']) mark_values = pd.DataFrame( [ [2,1], [8.25,2] ], columns=['a1', 'b']) df_long = pd.melt(df, "b", var_name="a", value_name="c") g = sns.boxplot(x='c', y='a', hue='b', data=df_long, palette=sns.color_palette("Blues_d"), orient='h') sns.despine(left=True) This generates a boxplot. I would now like to add markers as red crosses, e.g. marking the category a1, subgroup 1 with an X at "4", and subgroup 2 with an X at "8.25" etc. and still keep my nice boxplots. The values that would be marked should be defined and stored as in the dataframe mark_values defined above. As in the example: mark_values Out[1]: a1 b 0 4.00 1 1 8.25 2 Any easy solution to this? Thanks
has title: Mark specific value in Boxplot using Pandas
has answer: http://stackoverflow.com/a/47823257
has answer: http://stackoverflow.com/a/47815286
answer count: 2
tagged with: pandas
downvote count: 0
upvote count: 1
favorite count: 0
type: Question

iterable-unpacking
type: Tag
tag name: iterable-unpacking
tags question: http://stackoverflow.com/q/47842352

http://stackoverflow.com/q/47790212
type: Question
accepted answer: http://stackoverflow.com/a/47790594
has answer: http://stackoverflow.com/a/47790594
answer count: 1
downvote count: 0
type: AnsweredQuestion
score: 3
has body: I found myself running into the gotcha under 'evaluation time discrepancy' from this list today, and am having a hard time working around it. As a short demonstration of my problem, I make infinite generators that skip every nth number, with n going from [2..5]: from itertools import count skip_lists = [] for idx in range(2, 5): # skip every 2nd, 3rd, 4th.. number skip_lists.append(x for x in count() if (x % idx) != 0) # print first 10 numbers of every skip_list for skip_list in skip_lists: for _, num in zip(range(10), skip_list): print("{}, ".format(num), end="") print() Expected output: 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 1, 2, 4, 5, 7, 8, 10, 11, 13, 14, 1, 2, 3, 5, 6, 7, 9, 10, 11, 13, Actual output: 1, 2, 3, 5, 6, 7, 9, 10, 11, 13, 1, 2, 3, 5, 6, 7, 9, 10, 11, 13, 1, 2, 3, 5, 6, 7, 9, 10, 11, 13, Once I remembered that great feature, I tried to "solve" it by binding the if clause variable to a constant that would be part of the skip_list: from itertools import count skip_lists = [] for idx in range(2, 5): # bind the skip distance skip_lists.append([idx]) # same as in the first try, but use bound value instead of 'idx' skip_lists[-1].append(x for x in count() if (x % skip_lists[-1][0]) != 0) # print first 10 numbers of every skip_list for skip_list in (entry[1] for entry in skip_lists): for _, num in zip(range(10), skip_list): print("{}, ".format(num), end="") print() But again: 1, 2, 3, 5, 6, 7, 9, 10, 11, 13, 1, 2, 3, 5, 6, 7, 9, 10, 11, 13, 1, 2, 3, 5, 6, 7, 9, 10, 11, 13, Apart from an actual solution, I would also love to learn why my hack didn't work.
upvote count: 3
has title: Working around evaluation time discrepancy in generators
tagged with: python
favorite count: 0
tagged with: generator

http://stackoverflow.com/a/47744136
score: 1
type: AcceptedAnswer
upvote count: 1
answers question: http://stackoverflow.com/q/47744072
downvote count: 0
has body: You need to import re as import re then add a for loop with a regex for x in names: print(re.sub('\d+','*',x))
type: Answer
accepted answer of: http://stackoverflow.com/q/47744072

http://stackoverflow.com/a/47702561
accepted answer of: http://stackoverflow.com/q/47702406
has body: How about: df.groupBy("A", "B").avg("Price") or if you want to include aggregates by single column: df.cube("A", "B").avg("Price")
type: Answer
has comment: http://stackoverflow.com/comment/82365293
answers question: http://stackoverflow.com/q/47702406
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/82657478
has text: Instead of just counting the number of function calls in your two routines, count up the total number of list-items copied across all the calls in each routine.
type: Comment
type: QuestionComment
score: 3
comment on: http://stackoverflow.com/q/47846686

http://stackoverflow.com/a/47716626
has body: You can add the builtin 404 error handler: @app.errorhandler(404) def page_not_found(e): return "I don't care what they say, tomato is not a fruit" @app.route('/fruit/&lt;fruit_name&gt;', methods=["GET"]) def fruit_route(fruit_name): if fruit_name == "tomato": return flask.redirect('/404')
upvote count: 5
type: Answer
answers question: http://stackoverflow.com/q/47716539
score: 5
accepted answer of: http://stackoverflow.com/q/47716539
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/72543142
has body: Because types.MethodType doesn't mutate either the function or the instance, it just returns a new callable object which holds both the function and the instance. (You seem to have been expecting "bind" to mean "mutate one of the objects to hold a reference to the other", and so it sorta makes sense that you thought of it as adding the function onto the instance, but the best way to think of "bind" is that it produces a new function copy which has the instance bound as its first argument.)
upvote count: 0
downvote count: 1
type: Answer
score: -1
answers question: http://stackoverflow.com/q/47797661

http://stackoverflow.com/q/47703942
has title: TransformationError Reasons get_serving_url / Images API
has comment: http://stackoverflow.com/comment/82395237
tagged with: python
has answer: http://stackoverflow.com/a/75027500
score: 2
downvote count: 0
has body: I'm running into the following error using get_serving_url in order to serve images from my bucket. Traceback (most recent call last): File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 570, in dispatch return method(*args, **kwargs) File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/ext/ndb/tasklets.py", line 1087, in synctasklet_wrapper return taskletfunc(*args, **kwds).get_result() File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/ext/ndb/tasklets.py", line 1057, in tasklet_wrapper result = func(*args, **kwds) File "/base/data/home/apps/e~tileserve20171207t210519.406056180994857717/blob_upload.py", line 70, in post bf.put_async() File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/ext/ndb/model.py", line 3473, in _put_async self._pre_put_hook() File "/base/data/home/apps/e~tileserve/20171207t210519.406056180994857717/blob_files.py", line 124, in _pre_put_hook print images.get_serving_url(None, filename='/gs' + '/tileserve.appspot.com/user2test4test4RGB20170927.tif') File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/api/images/__init__.py", line 1868, in get_serving_url return rpc.get_result() File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/api/apiproxy_stub_map.py", line 613, in get_result return self.__get_result_hook(self) File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/api/images/__init__.py", line 1972, in get_serving_url_hook raise _ToImagesError(e, readable_blob_key) TransformationError When I upload an image to my bucket then it works but when I create an image through processing which should be exposed through get_serving_url I get TransformationError. I tried two variants for serving images: test = blobstore.create_gs_key('/gs' + '/path2object') images.get_serving_url(test, secure_url=True) images.get_serving_url(Non…
has comment: http://stackoverflow.com/comment/82374150
tagged with: image
tagged with: google-cloud-storage
has answer: http://stackoverflow.com/a/47718002
favorite count: 0
has comment: http://stackoverflow.com/comment/100211783
type: Question
upvote count: 2
answer count: 2
type: UnansweredQuestion
tagged with: google-app-engine
has comment: http://stackoverflow.com/comment/82383417
has comment: http://stackoverflow.com/comment/82392499
has comment: http://stackoverflow.com/comment/82395265

http://stackoverflow.com/q/47717529
has title: Why I got that problems when I run my script?
favorite count: 0
has comment: http://stackoverflow.com/comment/82395367
type: Question
has comment: http://stackoverflow.com/comment/82395597
has answer: http://stackoverflow.com/a/47717955
accepted answer: http://stackoverflow.com/a/47717955
has comment: http://stackoverflow.com/comment/82395647
linked to: http://stackoverflow.com/q/18066424
tagged with: python
has comment: http://stackoverflow.com/comment/82395404
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/17271319
upvote count: 0
downvote count: 4
has body: What is the solution for this error code? Traceback (most recent call last): File "./weevely.py", line 2, in <module> from core.terminal import Terminal File "/Users/ismailtaibi/Desktop/isdo/scripts/weevely/core/terminal.py", line 6, in <module> from core.module import Status File "/Users/ismailtaibi/Desktop/isdo/scripts/weevely/core/module.py", line 14, in <module> from core.vectorlist import VectorList File "/Users/ismailtaibi/Desktop/isdo/scripts/weevely/core/vectorlist.py", line 15, in <module> from core.vectors import Os File "/Users/ismailtaibi/Desktop/isdo/scripts/weevely/core/vectors.py", line 11, in <module> from mako.template import Template ImportError: No module named mako.template
has comment: http://stackoverflow.com/comment/82395368
has comment: http://stackoverflow.com/comment/82395681
has comment: http://stackoverflow.com/comment/82395341
has comment: http://stackoverflow.com/comment/82395506
score: -4
answer count: 1
has comment: http://stackoverflow.com/comment/82395494

http://stackoverflow.com/q/47718184
answer count: 0
tagged with: python-3.5
upvote count: 1
has comment: http://stackoverflow.com/comment/82396996
has comment: http://stackoverflow.com/comment/82396887
downvote count: 1
has comment: http://stackoverflow.com/comment/82396862
has comment: http://stackoverflow.com/comment/82396971
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82396784
has comment: http://stackoverflow.com/comment/82398840
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82396783
has comment: http://stackoverflow.com/comment/82398168
has comment: http://stackoverflow.com/comment/82396992
tagged with: python
has comment: http://stackoverflow.com/comment/82396814
tagged with: python-3.6
has body: Im getting an TypeError: slice indices must be integers or None or have an __index__ method while running this code. The thing is that it works fine on python 3.5.2 (conda) but it gives this error when on python 3.6.1 (conda). Anyone has idea how to change it to make it work on both versions? Or at least the newer one? import numpy as np import random import math def geneticAlgorithm(f, x_min, x_max, cel, popSize, pMut, maxIter): result = { 'x_opt': None, 'f_opt': None, 'x_hist': [], 'f_hist': [], 'f_mean': [] } # Check the number of dimensions Dim = len(x_min) # Initialize Population population = np.full((popSize, cel*Dim), None) for i in range(popSize): population[i,:] = np.random.uniform(cel*Dim)&lt;0 coordinates = getCoordinates(population, cel, x_min, x_max, pMut) # Calculate fittness of individuals objFunction = [None]*popSize for i in range(popSize): objFunction[i] = f(coordinates[i,:]) # Assign the first population to output result['x_opt'] = coordinates[np.argmin(objFunction),] result['f_opt'] = f(coordinates[np.argmin(objFunction),]) # The generational loop finished = False currIter = 1 while(finished == False): # Assign the output if currIter &lt;= maxIter: if result['f_opt'] &gt; f(coordinates[np.argmin(objFunction),]): result['x_opt']= coordinates[np.argmin(objFunction),] result['f_opt']= f(coordinates[np.argmin(objFunction),]) result['f_hist'].append(result['f_opt']) result['x_hist'].append(coordinates[np.argmin(objFunction)]) result['f_mean'].append(np.mean(objFunction)) else: finished = True # Translate binary coding into real values coordinates = getCoordinates(population, cel, x_min, x_max, pMut) # Calculate fittness of the individuals objFunction = [None]*popSize for i in range(popSize): objFunction[i] = f(coordinates[i,:]) rFitt = min(objFunction)/objFunction # Relative Fittness nrFitt = rFitt / sum(rFitt) # Relative Normalized (sum up to 1) Fittness # Selection operator (Roulette wheel) selectedPool = [0] * popSize for i in range(popSize): selec…
has title: Typerror on python 3.6.1
has comment: http://stackoverflow.com/comment/82397113
has comment: http://stackoverflow.com/comment/82399984
score: 0
has comment: http://stackoverflow.com/comment/82396673

http://stackoverflow.com/a/47825174
type: Answer
accepted answer of: http://stackoverflow.com/q/47824793
answers question: http://stackoverflow.com/q/47824793
score: 20
has comment: http://stackoverflow.com/comment/82614247
downvote count: 0
has comment: http://stackoverflow.com/comment/82613863
type: AcceptedAnswer
has body: The code you're using is written for Python2, you can't expect it to run as it is. I've modified some parts to make it Python3 compatible. Original code: import json, hmac, hashlib, time, requests, base64 from requests.auth import AuthBase # Create custom authentication for Exchange class CoinbaseExchangeAuth(AuthBase): def __init__(self, api_key, secret_key, passphrase): self.api_key = api_key self.secret_key = secret_key self.passphrase = passphrase def __call__(self, request): timestamp = str(time.time()) message = timestamp + request.method + request.path_url + (request.body or '') hmac_key = base64.b64decode(self.secret_key) signature = hmac.new(hmac_key, message, hashlib.sha256) signature_b64 = signature.digest().encode('base64').rstrip('\n') request.headers.update({ 'CB-ACCESS-SIGN': signature_b64, 'CB-ACCESS-TIMESTAMP': timestamp, 'CB-ACCESS-KEY': self.api_key, 'CB-ACCESS-PASSPHRASE': self.passphrase, 'Content-Type': 'application/json' }) return request api_url = 'https://api.gdax.com/' auth = CoinbaseExchangeAuth(API_KEY, API_SECRET, API_PASS) # Get accounts r = requests.get(api_url + 'accounts', auth=auth) print r.json() # [{"id": "a1b2c3d4", "balance":... # Place an order order = { 'size': 1.0, 'price': 1.0, 'side': 'buy', 'product_id': 'BTC-USD', } r = requests.post(api_url + 'orders', json=order, auth=auth) print r.json() Modified code: import json, hmac, hashlib, time, requests, base64 from requests.auth import AuthBase # Create custom authentication for Exchange class CoinbaseExchangeAuth(AuthBase): def __init__(self, api_key, secret_key, passphrase): self.api_key = api_key self.secret_key = secret_key self.passphrase = passphrase def __call__(self, request): timestamp = str(time.time()) message = timestamp + request.method + request.path_url + (request.body or b'').decode() hmac_key = base64.b64decode(self.secret_key) signature = hmac.new(hmac_key, message.encode(), hashlib.sha256) signature_b64 = base64.b64encode(signature.digest()).decode() request…
has comment: http://stackoverflow.com/comment/82614112
has comment: http://stackoverflow.com/comment/82615241
upvote count: 20
has comment: http://stackoverflow.com/comment/82615837
has comment: http://stackoverflow.com/comment/82614439
has comment: http://stackoverflow.com/comment/82616168

http://stackoverflow.com/comment/82643243
score: 0
has text: what is the type of `data`? Is it a dict? Or are parts of it iterables?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47839582

http://stackoverflow.com/a/47796857
type: Answer
answers question: http://stackoverflow.com/q/47796104
type: AcceptedAnswer
has body: The main problem is ranint(1,10) which can give values 1...10,not 1...9. So finally it generates 4-digits number instead of 3-digits one. (but it could generate even 6-digits number "101010" - "10" + "10" + "10") Use randint(1, 9) or randrange(1, 10) import tkinter as tk from random import randint # --- functions --- def compare(): print(number_str == answer.get()) def generate(): global index lab.config(text=number_str[index]) index += 1 root.after(2000, remove) def remove(): global repeat lab.config(text='') repeat -= 1 if repeat &gt; 0: root.after(1000, generate) # --- main --- number_of_digits = 3 repeat = number_of_digits index = 0 number_str = "" for _ in range(number_of_digits): number_str = number_str + str(randint(1,9)) #print(number_str) root = tk.Tk() answer = tk.StringVar() lab = tk.Label(root, width=20, height=10) lab.pack() ent = tk.Entry(root, textvariable=answer, width=20, bd=3) ent.pack() but = tk.Button(text="Check", command=compare) but.pack() generate() root.mainloop()
score: 0
accepted answer of: http://stackoverflow.com/q/47796104
has comment: http://stackoverflow.com/comment/82554593

http://stackoverflow.com/a/47786274
has body: If you directly want to access file like " open('test.txt') ", make sure that this file exists in the directory from where you run your jupyter notebook. Paths with double backslashes "\\" work in windows environment. If you are using Linux, then use "/". Use os.getcwd() to get your current working directory and use the path accordingly.
answers question: http://stackoverflow.com/q/47785444
has comment: http://stackoverflow.com/comment/82558846
type: Answer
score: 0

http://stackoverflow.com/q/47843265
has answer: http://stackoverflow.com/a/47844324
has comment: http://stackoverflow.com/comment/82652493
downvote count: 0
accepted answer: http://stackoverflow.com/a/51945256
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/47844324
has answer: http://stackoverflow.com/a/51945256
has title: How can I get a Keras models' history after loading it from a file in Python?
upvote count: 27
has body: I have saved a keras model as a h5py file and now want to load it from disk. When training the model I use: from keras.models import Sequential model = Sequential() H = model.fit(....) When the model is trained, I want to load it from disk with model = load_model() How can I get H from the model variable? It unfortunately does not have a history parameter that I can just call. Is it because the save_model function doesn't save history?
tagged with: python
tagged with: keras
score: 27
type: AnsweredQuestion
answer count: 2

http://stackoverflow.com/comment/99434326
has text: You should also consider closing the session [using `on_shutdown`](https://docs.aiohttp.org/en/stable/web_advanced.html#graceful-shutdown)
score: 1
comment on: http://stackoverflow.com/a/47702504
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47839668
type: Question
has answer: http://stackoverflow.com/a/47839750
has answer: http://stackoverflow.com/a/47839751
has body: Python 3 - I am using a for loop to print values from a dictionary. Some dictionaries within rawData have "RecurringCharges" as an empty list. I am checking to see if the list is empty and either populating with "0.0" if empty or the "Amount" if populated. Creating the IF statement in my For Loop presents a new print statement and prints to a new line. I would like it to be one continuous line. for each in rawData['ReservedInstancesOfferings']: print('PDX', ',' , each['InstanceType'], ',' , each['InstanceTenancy'], ',' , each['ProductDescription'], ',' , each['OfferingType'], ',' , each['Duration'], ',' , each['ReservedInstancesOfferingId'], ',' , each['FixedPrice'], ',', ) if not each['RecurringCharges']: print("0.0") else: print(each['RecurringCharges'][0].get('Amount'))
has answer: http://stackoverflow.com/a/47839749
accepted answer: http://stackoverflow.com/a/47839749
linked to: http://stackoverflow.com/q/493386
tagged with: python
answer count: 4
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/82643337
upvote count: 1
has title: How to print to the same line - If Statement within a For Loop
downvote count: 1
has answer: http://stackoverflow.com/a/47839723
possible better answer: http://stackoverflow.com/a/47839723
favorite count: 0

http://stackoverflow.com/a/47772901
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/110839531
has comment: http://stackoverflow.com/comment/91048068
answers question: http://stackoverflow.com/q/47769641
has body: This is depending on your project settings, the project interpreter to be specific. The project interpreter can be set to one of the following: an interpreter installed globally on your system an interpreter in a shared virtual environment an interpreter in a virtual environment associated with a project Now the approach I'd recommend would be to create a shared virtual environment where you install your packages to, and use this environment for all your project. That way, you have the desired result of needing to install your packages only once, but still have an environment isolated from your system environment. To create such an environment, follow these steps: Settings -> Project -> Project Interpreter Click the cogwheel / gear icon right-side the interpreter dropdown Select "Add Local..." -> Virtualenv Environment Select a path as a root directory for the new environment Select base interpreter you want to use Tick the checkbox "Make available to all projects" Click the "OK" button to save the new environment
type: Answer
accepted answer of: http://stackoverflow.com/q/47769641
score: 52
upvote count: 52
downvote count: 0

http://stackoverflow.com/q/47734748
upvote count: 1
score: 1
accepted answer: http://stackoverflow.com/a/47734880
tagged with: tensorflow
favorite count: 0
has title: TensorFlow - shape does not match the shape stored in checkpoint
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47734880
tagged with: python
has body: I am very new to TensorFlow and I am trying Simple Neural Network on my data. I have a .csv data with 19 columns and the last column being the target column. It is 0 or 1. I started from here https://www.tensorflow.org/get_started/estimator and trying to modify to suit my data. I produced this. ... # Data sets IRIS_TRAINING = "Training.csv" IRIS_TEST = "Test.csv" def main(): # Load datasets. training_set = tf.contrib.learn.datasets.base.load_csv_without_header( filename=IRIS_TRAINING, target_dtype=np.int, features_dtype=np.float32) test_set = tf.contrib.learn.datasets.base.load_csv_without_header( filename=IRIS_TEST, target_dtype=np.int, features_dtype=np.float32) # Specify that all features have real-value data feature_columns = [tf.feature_column.numeric_column("x", shape=[18])] **# SOMETHING WRONG HERE** classifier = tf.estimator.DNNClassifier(feature_columns=feature_columns, hidden_units=[18], n_classes=2, model_dir="/tmp/iris_model") # Define the training inputs train_input_fn = tf.estimator.inputs.numpy_input_fn( x={"x": np.array(training_set.data)}, y=np.array(training_set.target), num_epochs=None, shuffle=True) # Train model. classifier.train(input_fn=train_input_fn, steps=2000) # Define the test inputs test_input_fn = tf.estimator.inputs.numpy_input_fn( x={"x": np.array(test_set.data)}, y=np.array(test_set.target), num_epochs=1, shuffle=False) # Evaluate accuracy. accuracy_score = classifier.evaluate(input_fn=test_input_fn)["accuracy"] print("\nTest Accuracy: {0:f}\n".format(accuracy_score)) if __name__ == "__main__": main() I just changed the hidden units to make it 1 layer and changed the shape to 18 because I have 18 features. However, I am getting this error. InvalidArgumentError (see above for traceback): tensor_name = dnn/hiddenlayer_0/bias/t_0/Adagrad; shape in shape_and_slice spec [18] does not match the shape stored in checkpoint: [10] [[Node: save/RestoreV2_1 = RestoreV2[dtypes=[DT_FLOAT], _device="/job:localhost/replica:0/task:0/device:CPU:0"](_a…
type: Question
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/82644147
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47839981
has text: Possible duplicate of [Efficiently carry out multiple string replacements in Python](https://stackoverflow.com/questions/3367809/efficiently-carry-out-multiple-string-replacements-in-python)

http://stackoverflow.com/comment/82551345
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47779876
has text: @AyodhyankitPaul please check my expected output..your method is giving only strings.

http://stackoverflow.com/comment/82546428
comment on: http://stackoverflow.com/a/47792049
has text: Great tip, especially, regarding internet explorer. Thanks ;)
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/47722819
answer count: 1
has comment: http://stackoverflow.com/comment/82406249
tagged with: runtime-error
score: 0
has answer: http://stackoverflow.com/a/47722909
has comment: http://stackoverflow.com/comment/82406251
has comment: http://stackoverflow.com/comment/82406327
tagged with: python
has comment: http://stackoverflow.com/comment/82406579
has comment: http://stackoverflow.com/comment/82406282
has comment: http://stackoverflow.com/comment/82406470
type: Question
has body: This piece of code is supposed to find account balance after withdraw from bank(fee=0.5). wd,ac=raw_input().split(" ") wd=int(wd) ac=float(ac) if(ac&lt;wd): print(ac) elif(wd%5==0): if(ac&gt;wd+0.50): print(ac-wd-0.50) else: print(ac) else: print(ac) I got a Runtime NZEC Error while submitting on codechef. I am newbie and had searched for resolve and had used split(" ") in place of int(input()), which I had tried previously, but the problem still occurs. Geeksforgeeks says: "In python, generally multiple inputs are separated by commas and we read them using input() or int(input()), but most of the online coding platforms while testing gives input separated by space and in those cases int(input()) is not able to read the input properly and shows error like NZEC" Given that I've tried to account for that... What is wrong with my code?
tagged with: python-3.x
has title: Python3 NZEC Error
has comment: http://stackoverflow.com/comment/82406624
type: UnansweredQuestion

http://stackoverflow.com/comment/82480252
type: QuestionComment
comment on: http://stackoverflow.com/q/47755807
type: Comment
has text: Then there are two options for this: nuitka and PyInstaller. The former has significantly better performance, but it is also much more difficult to get it to work. While nuitka literally compiles Python files (just like Cython), PyInstaller actually generates a self-extracting archive that then runs Python.
score: 0

http://stackoverflow.com/q/47827812
tagged with: python
has title: In odoo 10, using the UI I cannot get my "Server action +Automated action" to work
possible better answer: http://stackoverflow.com/a/47842818
type: AnsweredQuestion
score: 2
has answer: http://stackoverflow.com/a/47842818
answer count: 2
accepted answer: http://stackoverflow.com/a/48395538
tagged with: odoo-10
upvote count: 2
has body: I have the "reviewer" field available in my task, and I want to switch the reviewer with the task assignee automatically when the task is moved from the 'In progress' stage to the 'Review' stage. I have the following Python code in my server action: picture of the code in context def assignrev(self): for record in self: if record['project.task.type.stage_id.name']=='Review': a=self.res.users.reviewer_id.name b=self.res.users.user_id.name record['res.users.user_id.name']=a record['res.users.reviewer_id.name']=b and below are links to pictures of my automated action settings: Server action to run "When to run" settings Unfortunately, changing the task stage to 'Review' does not give the expected results. Any suggestion please? Kazu
downvote count: 0
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48395538

http://stackoverflow.com/comment/100374454
comment on: http://stackoverflow.com/a/49437512
score: 1
has text: _If_ I remember correctly, then there was no good reason to not specify it directly.
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/82527675
type: AnswerComment
comment on: http://stackoverflow.com/a/47763650
has text: I appreciate the response and help, but would this let me use json.loads when reading from the new file? I don't believe it is in JSON format to begin with, right?
type: Comment
score: 0

http://stackoverflow.com/comment/82632855
score: 0
has text: @seanysull yw:-) happy coding
type: Comment
comment on: http://stackoverflow.com/a/47816523
type: AnswerComment

http://stackoverflow.com/comment/82571909
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47804795
type: AnswerComment
has text: @Pankaj If you're just looking to print the items in the lists, the second option in this answer is the way to go. It's the cleanest and easiest to understand for anyone looking at your code!

http://stackoverflow.com/q/47826029
linked to: http://stackoverflow.com/q/36471904
has body: Note: I particularly deal with this website How can I use selenium with Python to get the reviews on this page to sort by 'Most recent'? What I tried was: driver.find_element_by_id('sort-order-dropdown').send_keys('Most recent') from this didn't cause any error but didn't work. Then I tried from selenium.webdriver.support.ui import Select select = Select(driver.find_element_by_id('sort-order-dropdown')) select.select_by_value('recent') select.select_by_visible_text('Most recent') select.select_by_index(1) I've got: Message: Element &lt;select id="sort-order-dropdown" class="a-native-dropdown" name=""&gt; is not clickable at point (66.18333435058594,843.7999877929688) because another element &lt;span class="a-dropdown-prompt"&gt; obscures it This one element = driver.find_element_by_id('sort-order-dropdown') element.click() li = driver.find_elements_by_css_selector('#sort-order-dropdown &gt; option:nth-child(2)') li.click() from this caused the same error msg This one from this caused the same error also Select(driver.find_element_by_id('sort-order-dropdown')).select_by_value('recent').click() So, I'm curious to know if there is any way that I can select the reviews to sort from the most recent first. Thank you
has comment: http://stackoverflow.com/comment/82617692
linked to: http://stackoverflow.com/q/24498976
tagged with: automation
linked to: http://stackoverflow.com/q/44912203
linked to: http://stackoverflow.com/q/22524621
has comment: http://stackoverflow.com/comment/82616526
has comment: http://stackoverflow.com/comment/82617113
tagged with: python
has comment: http://stackoverflow.com/comment/82617640
has comment: http://stackoverflow.com/comment/82617308
has comment: http://stackoverflow.com/comment/82617062
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82617400
answer count: 2
has comment: http://stackoverflow.com/comment/82615545
possible better answer: http://stackoverflow.com/a/47828574
has title: How to select a value from a drop-down using Selenium from a website with special setting- Python
has comment: http://stackoverflow.com/comment/82616820
score: 1
has answer: http://stackoverflow.com/a/47828574
accepted answer: http://stackoverflow.com/a/47827959
downvote count: 0
tagged with: selenium
has comment: http://stackoverflow.com/comment/82615138
has comment: http://stackoverflow.com/comment/82617473
upvote count: 1
has comment: http://stackoverflow.com/comment/82617000
has answer: http://stackoverflow.com/a/47827959
favorite count: 0
type: Question

django-rest-auth
tag name: django-rest-auth
type: Tag
tags question: http://stackoverflow.com/q/47751798

http://stackoverflow.com/comment/82513192
type: QuestionComment
has text: Because `and` returns the first value only if it is falsey. It *short circuits* when it can't produce a true value.
comment on: http://stackoverflow.com/q/47776065
score: 1
type: Comment

http://stackoverflow.com/comment/82573350
has text: That's because they're (well, `local` is) built-in functions.
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47805945

http://stackoverflow.com/q/47844555
favorite count: 0
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47849275
tagged with: bit-shift
has body: My question is about how to retrieve the original string if information might have been lost in the process. I'm reviewing an encoding routine that uses byte shifts in something like this: def encode(string): encoded = '' for char in string: encoded += chr(ord(char) ^ (ord(char) &gt;&gt; 1)) return encoded With one bit if being shifted right I'm loosing information in certain cases, but I'm trying to figure out a way to reconstruct the original string in a way such that def decode(string): decoded = '' for char in string: decoded += ........ return decoded As I'm loosing information for a list of given chars: In [90]: ord('A') &gt;&gt; 1 &lt;&lt; 1 Out[90]: 64 In [91]: ord('B') &gt;&gt; 1 &lt;&lt; 1 Out[91]: 66 In [92]: ord('C') &gt;&gt; 1 &lt;&lt; 1 Out[92]: 66 Would it be possible to reverse the encoded string? I've been bugging my head for a while and I have a sense that this can be done, but my brain seems to be stuck here.
tagged with: python
accepted answer: http://stackoverflow.com/a/47849275
type: Question
has answer: http://stackoverflow.com/a/47844650
answer count: 2
has title: Best way to decode encoding with byte shifts
tagged with: bit-manipulation
downvote count: 0
score: 1
upvote count: 1
tagged with: bitwise-operators
possible better answer: http://stackoverflow.com/a/47844650

http://stackoverflow.com/comment/82507614
score: 0
has text: It might seem that learning Python 2 first and then extending your knowledge to Python 3 is a logical progression. But really, the main changes that Python 3 has made are mostly because certain language features of Python 2 turned out to be bad design choices. So it's actually easier to learn Python 3 first, and then when your Python 3 knowledge is solid you can go back and learn the old-fashioned stuff, if you need to maintain or read old code.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47770319

http://stackoverflow.com/comment/82423450
score: 0
comment on: http://stackoverflow.com/q/47731358
has text: @Kevin- "hide widgets is not defined"
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82591125
score: 0
has text: Please read [Under what circumstances may I add “urgent” or other similar phrases to my question, in order to obtain faster answers?](//meta.stackoverflow.com/q/326569) - the summary is that this is not an ideal way to address volunteers, and is probably counterproductive to obtaining answers. Please refrain from adding this to your questions.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47814335

http://stackoverflow.com/comment/82480771
has text: Im using Python 2.7 and still I never get response. Seams like I am missing something. I also tried sending other commands to activate my device but doesn't work. You getting response for the code?
type: Comment
comment on: http://stackoverflow.com/a/47702633
score: 0
type: AnswerComment

http://stackoverflow.com/comment/82600898
type: QuestionComment
comment on: http://stackoverflow.com/q/47819417
score: 3
has text: You know that dictionaries often have multiple keys, right?
type: Comment

http://stackoverflow.com/q/47821864
downvote count: 0
tagged with: django-queryset
has body: I am using Django 2 I have a model within which I have written a queryset class to add the search function. I want to display only those results which are associated with the authenticated user. For that I'm using user=self.request.user in filter in queryset Notes/model.py class NoteQuerySet(models.query.QuerySet): def authenticated(self): return self.filter(user=self.request.user) def search(self, query): lookups = Q(title__icontains=query) | Q(tags__icontains=query) return self.filter(lookups).authenticated().distinct() class NoteManager(models.Manager): def get_queryset(self): return NoteQuerySet(self.model, using=self._db) def search(self, query): return self.get_queryset().search(query) class Note(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=250, blank=True, default='Untitled') tags = models.CharField(max_length=150, blank=True) objects = NoteManager() def __str__(self): return self.title def get_absolute_url(self): return reverse('notes:update', kwargs={'pk': self.pk}) In Notes/views.py class SearchNoteView(ListView): template_name = 'notes/my_notes.html' context_object_name = 'notes' def get_queryset(self, *args, **kwargs): query = self.request.GET.get('q', None) if query is not None: return Note.objects.search(query) But this return errors as AttributeError: 'NoteQuerySet' object has no attribute 'request' As the error states, it is trying to locate request funtion withing the class. How can I use the request in the queryset class?
upvote count: 1
answer count: 1
tagged with: django
accepted answer: http://stackoverflow.com/a/47822096
favorite count: 0
type: AnsweredQuestion
has title: using self.request.user in model queryset in Django
has comment: http://stackoverflow.com/comment/82607461
score: 1
has comment: http://stackoverflow.com/comment/82606721
tagged with: django-models
tagged with: python
has answer: http://stackoverflow.com/a/47822096
type: Question
has comment: http://stackoverflow.com/comment/82606810

http://stackoverflow.com/comment/82524685
type: AnswerComment
comment on: http://stackoverflow.com/a/47781639
has text: Aha, so "cell" is the name for individual code blocks `[in]`/`[out]` in Jupyter?
score: 0
type: Comment

http://stackoverflow.com/q/47842896
downvote count: 0
has title: Django signals not working with channels in multicontainer setup
answer count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47873300
tagged with: django-channels
tagged with: django
tagged with: daphne
tagged with: python
type: UnansweredQuestion
tagged with: docker
has body: I have django app and implementing websocket support with channels and channels api. I am using demultiplexer with bindings to my models. For example when i save a model it will send the change to my open websocket connection. Everything works OK if i run ./manage.py runserver 0:80 and have all in one container. But if i separate my app to UWSGI, daphne and the worker containers using docker the signals are not triggered. For example i want any celery worker (task) to trigger the signal and send update via the websocket. In my multicontainer setup the websocket connection is established OK and web works OK, but nothing triggers that signals. How the signals are defined you can see here on github. I am using django 1.9.12, python 2.7, docker and build on debian stretch. docker-compose.yml web: build: . ports: ["8001:80"] daphne: build: . command: daphne -b 0.0.0.0 -p 8000 --access-log - -v 2 my_proj.asgi:channel_layer ws_worker: build: . command: ./manage.py runworker -v 2 celery_worker: build: . command: /usr/local/bin/celery -A my_proj worker nginx.conf upstream django { server unix:/home/docker/app.sock; } server { listen 80; server_name 127.0.0.1; charset utf-8; client_max_body_size 1000M; location /static/ { alias /home/docker/static/; } # proxy to other container location /ws/ { proxy_pass http://daphne:8000; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; } location / { uwsgi_pass django; include /home/docker/uwsgi_params; } }
score: 2
upvote count: 2

http://stackoverflow.com/a/47785030
answers question: http://stackoverflow.com/q/47777585
has body: As you can see, the line in the binary image is not that straight, also there are so many lines similar. So directly doing HoughLine on such an image is a bad choice, not responsibility. I try to binary the image , drop the left-top region (3*w/4, h*2/3), then I get the two separate regions: img = cv2.imread("img04.jpg", 0) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) th, threshed = cv2.threshold(gray, 100, 255, cv2.THRESH_BINARY_INV|cv2.THRESH_OTSU) H,W = img.shape[:2] threshed[:H*2//3,:W*3//4] = 0 cv2.imwrite("regions.png", threshed) Then you can do other post steps as you like.
downvote count: 0
upvote count: 2
type: Answer
score: 2

http://stackoverflow.com/a/47750783
has comment: http://stackoverflow.com/comment/82461981
score: 1
accepted answer of: http://stackoverflow.com/q/47750711
has body: Use following code: ct='sadasdasdasdsa dasdasdasdffsdf [sdas] aaa dfdsfdsfdfds bbb' a = ['aaa','bbb'] b = ['343242','bbb'] flag=True for i in a: if i not in ct: flag=False for i in b: if i in ct: flag=False if flag: print('OK') else: print('NO')
answers question: http://stackoverflow.com/q/47750711
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 1

http://stackoverflow.com/comment/82505192
type: Comment
comment on: http://stackoverflow.com/q/47758585
type: QuestionComment
has text: Still can't figure it out, i added a username argument
score: 0

http://stackoverflow.com/a/47763937
has comment: http://stackoverflow.com/comment/82515295
has body: Here's a way to remove the 'message same' line for every function with a signature that contains 'function' and 'two'. This assumes that the structure of your input file is very consistent. # read file into list of lists (each inner list is a block) with open('code_blocks.txt', 'r') as f: blocks = [block.split('\n') for block in f.read().split('\n\n')] # iterate over blocks for block in blocks: # if first line contains 'function' and 'two' and second line contains 'message same' if 'function' in block[0] and '::' in block[0] and 'message_same' in block[1]: # remove message same block.pop(block.index(block[1])) # combine list of lists back into single string and write it out with open('code_blocks_out.txt', 'w') as f: f.write('\n\n'.join(['\n'.join(block) for block in blocks]))
type: Answer
has comment: http://stackoverflow.com/comment/82489398
score: 0
answers question: http://stackoverflow.com/q/47763716

http://stackoverflow.com/a/47730835
type: Answer
has body: Indenting the :: and then further indenting the dictionary, got it recognized as a codeblock. This was using .. autofunction:: do_stuff and sphinx 1.5.2. def do_stuff(foo, bar): """Do some stuff :param foo: I'm an argument :param bar: So am I :return: dict :: { "success": (Boolean) True if stuff was done "meta": { "aaa": A nested return value "bbb": Another nested return value } } """ When I separated out the dict part, I had to format like so. def do_stuff(foo, bar): """Do some stuff :param foo: I'm an argument :param bar: So am I :rtype: dict :return: :: { "success": (Boolean) True if stuff was done "meta": { "aaa": A nested return value "bbb": Another nested return value } } """
answers question: http://stackoverflow.com/q/47730413
upvote count: 3
type: AcceptedAnswer
downvote count: 0
score: 3
accepted answer of: http://stackoverflow.com/q/47730413

http://stackoverflow.com/q/47743246
has comment: http://stackoverflow.com/comment/82448665
score: 45
tagged with: frame-rate
upvote count: 45
downvote count: 0
has answer: http://stackoverflow.com/a/66445112
accepted answer: http://stackoverflow.com/a/47743467
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/73998721
has answer: http://stackoverflow.com/a/47743467
has body: I have recorded several videos from the front cam of my tablet with an Android 5.2 application I have written. I have stored the start timestamp in milliseconds (Unix time) for each video. Unfortunately each video has a different framerate (ranging from 20 to 30). With OpenCV I'm able to get the framerate for each video: import cv2 video = cv2.VideoCapture(videoFile) fps = video.get(cv2.CAP_PROP_FPS) This works well and theoretically I could just add 1000/fps (due to milliseconds) for each frame in the video. But this assumes that the framerate remains stable throughout the whole recording. I don't know if this is the case. Is there a possibility in Python to get the timestamp (in milliseconds) of each frame in the video independent of the framerate?
has answer: http://stackoverflow.com/a/69324627
answer count: 5
has answer: http://stackoverflow.com/a/69492206
tagged with: python
has title: Getting timestamp of each frame in a video
tagged with: opencv
type: AnsweredQuestion
tagged with: video
possible better answer: http://stackoverflow.com/a/69492206

http://stackoverflow.com/a/53350644
type: Answer
upvote count: 3
score: 3
has body: Use for i in kk instead of for i in range(kk) because kk is already a range. You were trying to do for i in range(np.arange(1, 17)) which does not make sense because range takes input in as a number, not another range.
answers question: http://stackoverflow.com/q/47825291
downvote count: 0

http://stackoverflow.com/a/47859820
type: Answer
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47843644
answers question: http://stackoverflow.com/q/47843644
score: 0
has body: The key is to use map &lt;expr&gt; &lt;leader&gt;&lt;leader&gt; ... so that &lt;leader&gt;&lt;leader&gt; can be mapped to a dynamically-generated binding. The below code snippet from a .vimrc file works with Vim 8.0: " open a terminal directly below current window nnoremap &lt;leader&gt;t :split&lt;cr&gt;&lt;c-w&gt;&lt;c-j&gt;:terminal ++curwin&lt;cr&gt;&lt;c-w&gt;&lt;c-k&gt; " save current file and run python on it in terminal window directly below nnoremap &lt;expr&gt; &lt;leader&gt;&lt;leader&gt; ':w&lt;cr&gt;&lt;c-w&gt;&lt;c-j&gt;python ' . expand('%:p') . '&lt;cr&gt;&lt;c-w&gt;&lt;c-k&gt;' This maps &lt;leader&gt;t to open a new terminal buffer, and &lt;leader&gt;&lt;leader&gt; to run python in that terminal buffer. Note that the terminal stays in Terminal-Job mode the whole time. Slight modification will be needed for this to work with NeoVim: " open a terminal directly below current window nnoremap &lt;leader&gt;t :split&lt;cr&gt;&lt;c-w&gt;&lt;c-j&gt;:terminal&lt;cr&gt;&lt;c-w&gt;&lt;c-k&gt; " save current file and run python on it in terminal window directly below nnoremap &lt;expr&gt; &lt;leader&gt;&lt;leader&gt; ':w&lt;cr&gt;&lt;c-w&gt;&lt;c-j&gt;ipython ' . expand('%:p') . '&lt;cr&gt;&lt;c-\&gt;&lt;c-n&gt;&lt;c-w&gt;&lt;c-k&gt;' In the NeoVim version, we must change from Terminal-Normal mode to Terminal-Job mode before passing input to the terminal, and then return to Terminal-Normal mode.

http://stackoverflow.com/a/47700195
score: 5
has body: Python's file objects are actually wrappers around FILE* object (in C language), so they are buffered streams. Because of buffering, Python's operations with file don't translate them into the syscalls with the same parameters, but attempt to optimize request time (both for current and future operations). Method open() accepts buffering parameter as 3d argument. Passing 0 should disable the buffering, so python will translate all file's requests directly to the underlying system: open("/dev/chardevice", "r+b", 0)
upvote count: 5
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/47698035
accepted answer of: http://stackoverflow.com/q/47698035
type: AcceptedAnswer

http://stackoverflow.com/comment/102440605
type: AnswerComment
has text: @CarlosCordoba. Based on https://stackoverflow.com/q/58018003/2988730, I think that the expectation would be that there would be a third non-nuclear option: run the script in the current console, but don't contaminate the script's namespace when you're running it.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/47738834

http://stackoverflow.com/comment/82660195
comment on: http://stackoverflow.com/q/47847960
type: Comment
type: QuestionComment
score: 1
has text: If your code is working, consider asking on [codereview.se].

http://stackoverflow.com/q/47765771
type: AnsweredQuestion
score: 0
tagged with: vuejs2
answer count: 1
has title: Best practice working with python variables in javascript django
type: Question
accepted answer: http://stackoverflow.com/a/47767239
has answer: http://stackoverflow.com/a/47767239
tagged with: django
tagged with: javascript
tagged with: python
has body: I am currently accessing my python data in JavaScript like this: &lt;script&gt; var x =; var l =; var sf =; &lt;/script&gt; this works but does not seem like the most ideal way to transfer data. What is the best practice for accessing and saving data between python and javascript using django? What I am trying to do is send data from the view, manipulate it using the ui in javascript/vue.js and then save the calculated data.
has comment: http://stackoverflow.com/comment/82493328

http://stackoverflow.com/q/47787931
tagged with: c#
has answer: http://stackoverflow.com/a/47788053
has comment: http://stackoverflow.com/comment/82537349
type: UnansweredQuestion
tagged with: python
has title: Corrupted JSON HTTP response
answer count: 2
tagged with: http://stackoverflow.com/tag/json
score: 0
has body: I am getting a HTTP request for a website and the content type is JSON. However, I am getting a nested JSON that is a unicode and is causing consistency problems. Here is an example: {"key1":"value", "key2":"value", "key3":{ u'key31':u'value', u'key32':u'value'}} This reminds me of python 2.7 troubles but I am not sure how to fix this JSON. I am using C# to parse it. Everything works correctly until I try to access key3. The content should be a JSON object type but it is considered rather a value or a string. Thanks for ya help. Is there a way to fix it if it is actually corrupted or am I parsing it wrongly?
tagged with: unicode
has answer: http://stackoverflow.com/a/47788369
has comment: http://stackoverflow.com/comment/82537163
has comment: http://stackoverflow.com/comment/82537495
type: Question

http://stackoverflow.com/a/47849047
has body: I downloaded your page with program wgetand checked it in text editor - it doesn't use &amp;lt; for &lt; so scrapy has problems - but only with &lt;&lt;+ and &lt;+ I replaced &lt;&lt;+ with &amp;lt&amp;lt+ and &lt;+ with &amp;lt+ body = response.body.replace(b'&lt;&lt;+', b'&amp;lt;&amp;lt;+').replace(b'&lt;+', b'&amp;lt;+') And then I create selector selector = scrapy.Selector(text=body.decode('utf-8')) which I can use with css() and it gives me correct results #!/usr/bin/env python3 import scrapy class MySpider(scrapy.Spider): name = 'myspider' start_urls = ['http://www.usfigureskating.org/leaderboard/results/2018/25073/SEGM001.html'] def parse(self, response): print('url:', response.url) body = response.body.replace(b'&lt;&lt;+', b'&amp;lt;&amp;lt;+').replace(b'&lt;+', b'&amp;lt;+') selector = scrapy.Selector(text=body.decode('utf-8')) i = 1 for x in selector.css('.elem::text').extract(): if 'Elements' in x: print('---', i, '---') i += 1 else: print(x) # --- it runs without project and saves in `output.csv` --- from scrapy.crawler import CrawlerProcess c = CrawlerProcess({ 'USER_AGENT': 'Mozilla/5.0', # save in CSV or JSON #'FEED_FORMAT': 'csv', # 'json #'FEED_URI': 'output.csv', # 'output.json }) c.crawl(MySpider) c.start() Results: Executed --- 1 --- 2Ab1+2T ChSt1 2Ab1 2Lz+1Lo+2Lo 2Lz FSSp4 2F CCoSp4 Executed --- 2 --- 2Ab1 ChSt1 2Ab1+1Lo+2F CCoSp2V 2Lz+2Lo 2Lo 2Lz LSp4 Executed --- 3 --- CCoSp4 ChSt1 2Ab1+2Lo 2Lz+1Lo+2Lo 2Ab1 2Lz 2Fe FSSp4 Executed --- 4 --- 2Ab1+1Lo+2Lo 2Ab1 LSp4 ChSt1 2Lz 2F 2Lz+2T CCoSp4 Executed --- 5 --- 2Ab1 LSp2 ChSt1 2Ab1+1Lo+1Lo 2Lz+2Lo 2Lz 2F CCoSp3 Executed --- 6 --- 2Lz 1A SSp3 ChSt1 2Lz+1Lo+2Lo CCoSp3 2F+2Lo 2F Executed --- 7 --- 2F 2Ab1 CCoSp4 2Lz 2Ab1&lt;+2T ChSt1 2Lz+1Lo+2F LSp4 Executed --- 8 --- 1A LSp4 ChSt1 2Lz 2Lz+2T 2Lo+2T+1Lo 2F CCoSp4 Executed --- 9 --- 2A&lt;&lt; CCoSp4 ChSt1 2F+1Lo+2Lo 2Lze+2Lo 2Lze 2F SSp4 Executed --- 10 --- 2Lz 2Ab1 SSp3 ChSt1 2A&lt;&lt;+REP 2Lz+2Lo 2F CCoSp4 Executed --- 11 --- FSSp4 2Ab1&lt;+2Lo …
accepted answer of: http://stackoverflow.com/q/47840862
downvote count: 0
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47840862
score: 1
type: Answer

http://stackoverflow.com/comment/82415794
has text: Thank you for the help! I did as you adviced. I used not text field as a foreign key but primary key, which is a number. It works now.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47721618
type: QuestionComment

http://stackoverflow.com/comment/82510132
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47758693
type: Comment
has text: Did the command `pip install pyscipopt` even work correctly? I suppose not, if you ran it *before* setting up the SCIP Opt Suite installation.

http://stackoverflow.com/comment/82649526
type: AnswerComment
has text: This answers my second question from [this issue](https://github.com/GoogleCloudPlatform/google-cloud-python/issues/4605). Thanks!
type: Comment
comment on: http://stackoverflow.com/a/47842039
score: 0

http://stackoverflow.com/q/47850992
has answer: http://stackoverflow.com/a/48537937
has title: pyinstaller cannot use tkinter
answer count: 2
tagged with: tkinter
possible better answer: http://stackoverflow.com/a/49219026
score: 1
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/49219026
accepted answer: http://stackoverflow.com/a/48537937
has comment: http://stackoverflow.com/comment/82671235
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82666849
tagged with: python-3.x
tagged with: pyinstaller
has body: I'm trying to get an otherwise working Python program to freeze to a single-file executable file using pyinstaller, but I keep running into the same error related to pyinstaller. I have reduced to program to the absolute minimum to provoke the error, ie. importing tkinter. Test program: import tkinter as tk Terminal command: pyinstaller --clean --hidden-import tkinter test.py Output: 1625 INFO: PyInstaller: 3.4.dev0+ab8fd9753 1625 INFO: Python: 3.6.3 1647 INFO: Platform: Darwin-17.3.0-x86_64-i386-64bit 1648 INFO: wrote /Users/jacob/test/test.spec 1653 INFO: UPX is not available. 1654 INFO: Removing temporary files and cleaning cache in /Users/jacob/Library/Application Support/pyinstaller 1655 INFO: Extending PYTHONPATH with paths ['/Users/jacob/test', '/Users/jacob/test'] 1656 INFO: checking Analysis 1656 INFO: Building Analysis because out00-Analysis.toc is non existent 1656 INFO: Initializing module dependency graph... 1658 INFO: Initializing module graph hooks... 1666 INFO: Analyzing base_library.zip ... 5415 INFO: Analyzing hidden import 'tkinter' 5568 INFO: running Analysis out00-Analysis.toc 5595 INFO: Caching module hooks... 5600 INFO: Analyzing /Users/jacob/test/test.py 5604 INFO: Loading module hooks... 5604 INFO: Loading module hook "hook-_tkinter.py"... 5623 INFO: checking Tree 5624 INFO: Building Tree because out00-Tree.toc is non existent 5624 INFO: Building Tree out00-Tree.toc 5704 INFO: checking Tree 5704 INFO: Building Tree because out01-Tree.toc is non existent 5704 INFO: Building Tree out01-Tree.toc 5746 INFO: Loading module hook "hook-encodings.py"... 5840 INFO: Loading module hook "hook-xml.py"... 6143 INFO: Loading module hook "hook-pydoc.py"... 6157 INFO: Looking for ctypes DLLs 6157 INFO: Analyzing run-time hooks ... 6159 INFO: Including run-time hook 'pyi_rth__tkinter.py' 6168 INFO: Looking for dynamic libraries 6453 INFO: Looking for eggs 6453 INFO: Using Python library /Library/Frameworks/Python.framework/Versions/3.6/Python 6456 INFO: Warn…
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/82506795
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47772828
has text: exactly bro i missed it sorry for that

http://stackoverflow.com/a/47794732
type: Answer
has body: Try replacing buildings with building. The correct OSM key is building without an "s" at the end. In fact, most OSM keys are singular.
has comment: http://stackoverflow.com/comment/82569531
downvote count: 0
answers question: http://stackoverflow.com/q/47784074
upvote count: 1
score: 1

http://stackoverflow.com/a/47779993
has body: You can try regular expression : One line solution: import re pattern = r'[a-z]+' string_1 = [(0,'0.897*"allah" + 0.120*"indeed" + 0.117*"lord" + 0.110*"said" + 0.101*"people" + 0.093*"upon" + 0.083*"shall" + 0.082*"unto" + 0.072*"believe" + 0.070*"earth"')] print([k if isinstance(k, int) else [i.group() for i in re.finditer(pattern, str(string_1))] for i in string_1 for k in i]) output: [0, ['allah', 'indeed', 'lord', 'said', 'people', 'upon', 'shall', 'unto', 'believe', 'earth']] Detailed solution: final_list=[] for i in string_1: for k in i: if isinstance(k,int): final_list.append(k) else: for i in re.finditer(pattern, str(string_1)): final_list.append(i.group()) print(final_list) regex explanation: **[a-z]** Match a single character present in the list below [a-z]+ **+ Quantifier** — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy) Edited answer as per your request : import re pattern = r'[a-z]+' string_1 = [(0, '0.897*"allah" + 0.120*"indeed" + 0.117*"lord" + 0.110*"said" + 0.101*"people" + 0.093*"upon" + 0.083*"shall" + 0.082*"unto" + 0.072*"believe" + 0.070*"earth"'), (1, '0.495*"lord" + 0.398*"said" + -0.377*"allah" + 0.253*"shall" + 0.241*"people" + 0.236*"unto" + 0.196*"indeed" + 0.131*"upon" + 0.118*"come" + 0.109*"thou"'), (2, '-0.682*"lord" + 0.497*"shall" + 0.349*"unto" + 0.125*"thou" + 0.125*"thee" + -0.098*"indeed" + 0.092*"come" + -0.092*"said" + 0.092*"people" + 0.080*"truth"')] print([k if isinstance(k, int) else [i.group() for i in re.finditer(pattern, str(i))] for i in string_1 for k in i]) output: [0, ['allah', 'indeed', 'lord', 'said', 'people', 'upon', 'shall', 'unto', 'believe', 'earth'], 1, ['lord', 'said', 'allah', 'shall', 'people', 'unto', 'indeed', 'upon', 'come', 'thou'], 2, ['lord', 'shall', 'unto', 'thou', 'thee', 'indeed', 'come', 'said', 'people', 'truth']] if you want more specific result then you can try: print([[k if isinstance(k, int) else tuple([i.group() for i in re.finditer(p…
has comment: http://stackoverflow.com/comment/82549558
score: 2
answers question: http://stackoverflow.com/q/47779876
downvote count: 0
type: Answer
upvote count: 2
has comment: http://stackoverflow.com/comment/82532354
has comment: http://stackoverflow.com/comment/82521550
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47779876

http://stackoverflow.com/comment/82517688
type: Comment
type: QuestionComment
has text: Converting the list into a set would not work at all. It would remove duplicates preventing him from counting the ones that show up N times.
score: 2
comment on: http://stackoverflow.com/q/47778162

http://stackoverflow.com/comment/82464679
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47747387
type: Comment
has text: Seems like a good idea , however how can I pass "json" from python2 to python3 ? tks for your reply = )

http://stackoverflow.com/q/47771894
has comment: http://stackoverflow.com/comment/82505501
has answer: http://stackoverflow.com/a/47771958
tagged with: dataframe
tagged with: python
has body: I need to change the value of a group label of rows if they do not have enough points. For example, +-----+ |c1|c2| +-----+ |A |1 | |A |2 | |B |1 | |A |2 | |E |5 | |E |6 | |W |1 | +-----+ If I were to group on the value within c2 and the minimum number of points within each group has to be greater than or equal to 2. c2: 1 : count(c1) = 3 2 : count(c1) = 2 5 : count(c1) = 1 6 : count(c1) = 1 Clearly, groups 5 and 6 have only 1 element in each so then I would like to relabel those row's c2 values to -1. This can be seen below. +-----+ |c1|c2| +-----+ |A |1 | |A |2 | |B |1 | |A |2 | |E |-1| |E |-1| |W |1 | +-----+ This is the code I have written, however it is not updating the dataframe. labels = df["c2"].unique() for l in labels: group_size = df[DB["c2"]==l].shape[0] if group_size&lt;=minPts: df[df["c2"]==l]["c2"] = -1
type: AnsweredQuestion
tagged with: pandas
linked to: http://stackoverflow.com/q/20109391
score: 1
has title: Pandas - Change Value of Group
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47771958

http://stackoverflow.com/a/47712873
has comment: http://stackoverflow.com/comment/82385783
has comment: http://stackoverflow.com/comment/82385610
type: Answer
answers question: http://stackoverflow.com/q/47712813
has body: If the file names always have the exact same form, with exactly two periods, then you can do: &gt;&gt;&gt; name, surname, ext = "john.doe.csv".split(".") &gt;&gt;&gt; name 'john' &gt;&gt;&gt; surname 'doe' &gt;&gt;&gt; ext 'csv' &gt;&gt;&gt;
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/comment/82493991
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/47766095
type: Comment
has text: Ok, looking good now :-) Another interesting way of getting behavior like this is to write `(notes or undefined_s)`, taking advantage of `or`'s tendency to evaluate to its leftmost truthy operand.

http://stackoverflow.com/q/47817024
has comment: http://stackoverflow.com/comment/82595885
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82595762
duplicate of: http://stackoverflow.com/q/14827650
has title: Radius of matplotlib scatter plot
has body: I'm struggling to set a size of matplotlib's scatter plot. Here, let's consider a way to put a circle in a 2D square cell, and the size of the cell is 10*10. Our aimed radius of the circle is 1. The code below is my current situation to realize this motivation, except for the radius of the circle: import matplotlib.pyplot as plt fig = plt.figure(figsize=(5,5))# The unit of this figsize is in inches ax = fig.add_subplot(1,1,1) ax.set_xlim(0,10) ax.set_ylim(0,10) ax.scatter(5,5,marker='o',s=1) plt.show() The biggest obstacle is a behavior of s in plt.scatter. What is the unit of s? Points? Inches? What geometrical correspondence does the value of s have? My question might be solved by previous answers by many gurus. But I couldn't find any question that has exactly the same motivation, so I post this. Thank you in advance!
type: UnansweredQuestion
tagged with: python
answer count: 0
score: 1
tagged with: matplotlib
linked to: http://stackoverflow.com/q/14827650
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/47834220
upvote count: 1
has comment: http://stackoverflow.com/comment/82632189
has body: I'd use a dedicated precision timer for that: import sys import time # a cross-platform precision timer get_timer = time.clock if sys.platform == "win32" else time.time distance = 20 input("Press enter to start.") start_time = get_timer() input("Press enter to stop.") stop_time = get_timer() delta_time = stop_time - start_time # passed time in seconds speed = distance / delta_time # the unit depends on the unit of your `distance` value
type: Answer
has comment: http://stackoverflow.com/comment/82631792
accepted answer of: http://stackoverflow.com/q/47834112
score: 1
answers question: http://stackoverflow.com/q/47834112
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/82512165
type: QuestionComment
score: 0
has text: Can you provide an input example?
type: Comment
comment on: http://stackoverflow.com/q/47775317

http://stackoverflow.com/comment/82511007
type: Comment
comment on: http://stackoverflow.com/a/47774474
type: AnswerComment
has text: @user7740248 Okay. For any N * M array where M is even, this will work: `np.diff(x.reshape(-1, 2), axis=1).reshape(-1, x.shape[1] // 2)`.
score: 0

http://stackoverflow.com/a/47804091
upvote count: 1
has body: I agree with Brett Beatty answer to use list comprehensions, but if you want to know how to improve your original code you could do the following. 1) rename variable 'sum' to an other variable like "my_sum" because sum() is python in built function 2) create a list (field1 = []) before the loop and append to this list at every step of the loop. at the end of loop you will have a list with all the entries of the column. 3) you can calculate the average of the last five entries of the column by using inbuilt function sum(field1[-5:])/n like shown below: import sys td = open(r"Qdata.csv", "r") # opening the file to variable ("file handle") td my_sum = 0 n = 0 firstround = True field1 = [] # make an empty list for line in td: if (firstround): firstround = False # nothing else is done for the first line (header) else: fields = line.split() # This creates a list containing the strings on # the line, by default separated by spaces or tabs. # Now fields[0] contains the date, fields[1] the # 1st data value and fields[2] the 2nd one. try: my_sum = my_sum + float(fields[1]) # increasing the cumulative value #field1 = (fields[1]) field1.append(float(fields[1])) # add elements to the end of the list n = 5 # Handling possible errors. except IndexError: # IndexError occurs e.g. in the case of empty lines # (when fields[2], for example, doesn't exist) continue except ValueError: # ValueError occurs e.g. if there are letters instead of # numbers (when conversion to float causes an error) print("Incorrect values in the file.") sys.exit() print("Average over the whole period was ", my_sum / n) print("Total number of values was ", n) print("average of last 5 elements of field1: " , sum(field1[-5:])/5)
answers question: http://stackoverflow.com/q/47803673
downvote count: 0
type: Answer
score: 1

http://stackoverflow.com/a/72089541
upvote count: 2
downvote count: 0
type: Answer
score: 2
answers question: http://stackoverflow.com/q/47844529
has body: First, you need to indicate index columns: df1.set_index('key', inplace=True) df2.set_index('key', inplace=True) Then, combine the dataframes to get all the index keys in place (this will not update the df1 values! See: combine_first manual): df1 = df1.combine_first(df2) Last step is updating the values in df1 with df2 and resetting the index df1.update(df2) df1.reset_index(inplace=True)

http://stackoverflow.com/q/47722470
has title: Passing and retrieving objects using pythonnet
tagged with: python
tagged with: python.net
score: 3
has comment: http://stackoverflow.com/comment/82411057
has body: How do , In general pass and return objects using pythonnet. For example, this works fine if I'm to return a number: dynamic par = Python.Runtime.Py.Import("mypackage.pythonfile"); var t = par.GetPPMError(100, 100.001); where I import a package which as a file called'pythonfile' This returns a number using the pythonfile.GetPPMError() method How do I do this: //C# arrays var double x = new double[500] //C# array var double y = new double[500] dynamic par = Python.Runtime.Py.Import("mypackage.pythonfile"); var p = par.GetPeak(x,y) where GetPeak is a python method in the 'pythonfile.py' and p is a class as such for example: class Peak: def __init__(self): self.FileID = "" self.RT = 0 self.Intensity = 0 self.MZ = 0 which can then be converted to a C# object?
answer count: 0
upvote count: 3
tagged with: pythonnet
downvote count: 0
tagged with: python-netifaces
favorite count: 0
type: Question
tagged with: c#
type: UnansweredQuestion

http://stackoverflow.com/comment/82519482
type: QuestionComment
has text: The OP has clearly mentioned he doesn't want to have to visit each URL to figure out whether it is important to him, he wants to skip to the next one which will be useful.
score: 0
comment on: http://stackoverflow.com/q/47779071
type: Comment

http://stackoverflow.com/q/47800655
linked to: http://stackoverflow.com/q/37888620
has comment: http://stackoverflow.com/comment/82562465
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82562387
tagged with: python
duplicate of: http://stackoverflow.com/q/37888620
has body: This is pretty bizarre...I take user input from the command line and execute parts of my script depending on what that input is. I used ast.literal_eval() in order to determine whether or not the user is inputting an int, a bool, etc. I was having some trouble executing some parts of it, and that lead me to this: I have a program: value = True print(type(value)) print(isinstance(value, bool)) print(isinstance(value, int)) print(isinstance(value, float)) print(isinstance(value, str)) that returns: &lt;class 'bool'&gt; True True False False Any idea why isinstance(value, int) is returning True when value is a bool?
has title: Why does isinstance(value, int) return True when value = True?
score: 0
answer count: 0

http://stackoverflow.com/comment/82452542
type: Comment
type: QuestionComment
has text: have you checked the content of your `read` variable? Is it in `list` format?
score: 0
comment on: http://stackoverflow.com/q/47746222

http://stackoverflow.com/comment/84643691
comment on: http://stackoverflow.com/q/47835896
score: 0
type: Comment
type: QuestionComment
has text: What makes this different is the list-of-tuples is unordered, or sparse viz. `OccupancyIdentifier` only appears in the third item, and it appears there twice, so that isn't a simple list of (value,key), we have to concatenate multiple adjacent subvalues

http://stackoverflow.com/q/47782111
tagged with: python
has title: How to use python to press the "load more" in imdb
has answer: http://stackoverflow.com/a/47782259
tagged with: web-crawler
tagged with: nlp
type: Question
score: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/82525771
has comment: http://stackoverflow.com/comment/82526443
downvote count: 2
answer count: 1
has body: I am creating a web crawler now and I want to scrape the user reviews from imdb. It's easy to directly get the 10 reviews and rate from the origin page. For example http://www.imdb.com/title/tt1392170/reviews The problem is to get all reviews, I need to press the "load more" so that more reviews will be shown while the url address doesn't change! So I don't know how can I get all the reviews in Python3. What I use now are requests, bs4. My code now: from urllib.request import urlopen, urlretrieve from bs4 import BeautifulSoup url_link='http://www.imdb.com/title/tt0371746/reviews?ref_=tt_urv' html=urlopen(url_link) content_bs=BeautifulSoup(html) for b in content_bs.find_all('div',class_='text'): print(b) for rate_score in content_bs.find_all('span',class_='rating-other-user-rating'): print(rate_score)
tagged with: python-requests
favorite count: 0
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47782259

http://stackoverflow.com/q/47844381
has comment: http://stackoverflow.com/comment/82659506
favorite count: 0
type: Question
tagged with: tkinter
answer count: 0
type: UnansweredQuestion
tagged with: user-interface
downvote count: 0
upvote count: 1
tagged with: tkinter-layout
has comment: http://stackoverflow.com/comment/82659475
has comment: http://stackoverflow.com/comment/82659918
tagged with: python-2.7
has body: from Tkinter import * root = Tk() def printt(self): repair = Tk() repairwindow = Frame(repair, bg='white', width=800, height=800) repairwindow.pack(expand=True, fill='both', side='right') repair.mainloop() mainarea = Frame(root, bg='grey', width=1200, height=1000) mainarea.pack(expand=True, fill='both', side='right') label1 = Label( mainarea, width=40, height = 5 , text="New Quotation", relief=GROOVE ) label1.place(relx=.5, rely=.5, anchor="center") label1.bind("&lt;Button-1&gt;",printt) label2 = Label( mainarea, width=15, height = 3 , text="Update", relief=GROOVE ) label2.place(relx=.45, rely=.6, anchor="center") label2.bind("&lt;Button-1&gt;",printt) label3 = Label( mainarea, width=15, height = 3 , text="Report", relief=GROOVE ) label3.place(relx=.55, rely=.6, anchor="center") label3.bind("&lt;Button-1&gt;",printt) label4 = Label( mainarea, width=40, height = 5 , text="Data Base", relief=GROOVE ) label4.place(relx=.5, rely=.7, anchor="center") label4.bind("&lt;Button-1&gt;",printt) root.attributes('-alpha', 0.98) root.mainloop() I need to add a clicking effect for the label her and also want to change the colour of window and if possible its size!! This code is in tkinter and i dnt have much idea about the gui desiging using tkinter. Is it good for deaktop application. Referance Pic
score: 1
tagged with: python
has title: How to change the window border colour in tkinter in windows

http://stackoverflow.com/q/47765021
type: Question
tagged with: python-3.x
has title: How to get combinations of list with values from another list?
has answer: http://stackoverflow.com/a/47765073
tagged with: python
possible better answer: http://stackoverflow.com/a/47765259
type: AnsweredQuestion
score: 0
answer count: 2
accepted answer: http://stackoverflow.com/a/47765073
has body: I have a list of 3 values, two of which are string. And another list with values to replace the string: li = [1, 'a', 'b'] li2 = [2, 3, 4] What I thought was that I can just replace the string with the second list and call itertools.combinations() on it: li = [li2 if isinstance(x, str) else x for x in li] li = [1, [2, 3, 4], [2, 3, 4]] combo = list(itertools.combinations(li, 3) But it just gives me a tuple of the same list back. What I wanted was something like [1, 2, 3], [1, 2, 4], [1, 3, 4]. I tried permutations also but it didn't help. How can I get all combinations of values from two lists, keeping value from first list in place?
has answer: http://stackoverflow.com/a/47765259

http://stackoverflow.com/comment/82447611
comment on: http://stackoverflow.com/q/47743704
type: Comment
type: QuestionComment
score: 0
has text: so can you give more examples? what happens if you have "1333" is that 01:03:33 or 13:03:03 ?

http://stackoverflow.com/a/47784051
has body: You can try this: import itertools class Table: def __init__(self, data): self.lst = data self.headers = headers = list(set(itertools.chain(*self.lst))) self.new_count = {i:[b.count(i) for b in self.lst] for i in self.headers} def __getitem__(self, row): if isinstance(row, int): return [d[row] for c, d in sorted(self.new_count.items(), key=lambda x:x[0])] return self.new_count[row] def __repr__(self): return ' '.join(sorted(self.new_count.keys()))+'\n'+'\n'.join('{}. {}'.format(i, ' '.join(map(str, d))) for i, d in enumerate(zip(*[e[-1] for e in sorted(self.new_count.items(), key=lambda x:x[0])]))) lst = [('apple','banana','carrots'),('apple',),('banana','carrots',)] t = Table(lst) print(t) Output: apple banana carrots 0. 1 1 1 1. 1 0 0 2. 0 1 1
score: 0
type: Answer
answers question: http://stackoverflow.com/q/47783833

http://stackoverflow.com/q/47829312
has comment: http://stackoverflow.com/comment/82625658
has comment: http://stackoverflow.com/comment/82625327
tagged with: synchronization
favorite count: 0
type: Question
upvote count: 2
has title: How do I know when a child process died in python3 on windows platform?
type: UnansweredQuestion
has body: In linux I use subprocess.Popen to create a child process, and define a signal handler for SIGCHLD. When the child process died, parent process recieves SIGCHLD signal and the handler will do sth. But on Windows there's no SIGCHLD signal, how can I know when the child process exited?
tagged with: process
answer count: 1
tagged with: python
has answer: http://stackoverflow.com/a/47838946
has comment: http://stackoverflow.com/comment/82632258
score: 2
tagged with: subprocess
downvote count: 0

http://stackoverflow.com/a/47793707
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82548448
accepted answer of: http://stackoverflow.com/q/47793488
has body: Get the first occurance of those indices with all() reduction alongwith argmax() and then slice each 2D slice off the 3D array - In [106]: idx = (arr_3d == [0,0,0]).all(-1).argmax(-1) # Output as list of arrays In [107]: [a[:i] for a,i in zip(arr_3d,idx)] Out[107]: [array([[1, 2, 3], [4, 5, 6]]), array([[3, 2, 1]]), array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])] # Output as list of lists In [108]: [a[:i].tolist() for a,i in zip(arr_3d,idx)] Out[108]: [[[1, 2, 3], [4, 5, 6]], [[3, 2, 1]], [[1, 2, 3], [4, 5, 6], [7, 8, 9]]]
type: Answer
answers question: http://stackoverflow.com/q/47793488
has comment: http://stackoverflow.com/comment/82548494
score: 2
upvote count: 2

http://stackoverflow.com/a/47834583
score: 4
answers question: http://stackoverflow.com/q/47777585
downvote count: 0
has body: This has many good answers already, none accepted though. I tried something bit different, so thought of posting it even if the question is old. At least someone else might find this useful. This works only if there's nice uniform background as in the sample image. detect interest points (try different interest point detectors. I used FAST) find the minimum-enclosing-triangle of these points find the largest (is it?) angle of this triangle This will give you a rough estimate. For the sample image, the code gives 90.868604 42.180990 46.950407 Code is in c++. You can easily port it if you find this useful. // helper function: // finds a cosine of angle between vectors // from pt0-&gt;pt1 and from pt0-&gt;pt2 static double angle( Point2f pt1, Point2f pt2, Point2f pt0 ) { double dx1 = pt1.x - pt0.x; double dy1 = pt1.y - pt0.y; double dx2 = pt2.x - pt0.x; double dy2 = pt2.y - pt0.y; return (dx1*dx2 + dy1*dy2)/sqrt((dx1*dx1 + dy1*dy1)*(dx2*dx2 + dy2*dy2) + 1e-10); } int _tmain(int argc, _TCHAR* argv[]) { Mat rgb = imread("GmHqQ.jpg"); Mat im; cvtColor(rgb, im, CV_BGR2GRAY); Ptr&lt;FeatureDetector&gt; detector = FastFeatureDetector::create(); vector&lt;KeyPoint&gt; keypoints; detector-&gt;detect(im, keypoints); drawKeypoints(im, keypoints, rgb, Scalar(0, 0, 255)); vector&lt;Point2f&gt; points; for (KeyPoint&amp; kp: keypoints) { points.push_back(kp.pt); } vector&lt;Point2f&gt; triangle(3); minEnclosingTriangle(points, triangle); for (size_t i = 0; i &lt; triangle.size(); i++) { line(rgb, triangle[i], triangle[(i + 1) % triangle.size()], Scalar(255, 0, 0), 2); printf("%f\n", acosf( angle(triangle[i], triangle[(i + 1) % triangle.size()], triangle[(i + 2) % triangle.size()]) ) * 180 / CV_PI); } return 0; }
has comment: http://stackoverflow.com/comment/82737183
has comment: http://stackoverflow.com/comment/82705327
type: Answer
upvote count: 4

http://stackoverflow.com/comment/82513973
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47775591
has text: True, but I guess I have to use your solution, even when inaccuracies like `e-16` are very small. Although it happens very rarely sometimes I get a positive inaccuracy, like a sum of 1 + some `e-16`. This error can not be corrected with `min(0, array)`, since the values only have a sum > 1.0, but are always < 1.0 themselves.
score: 1

http://stackoverflow.com/comment/82355751
comment on: http://stackoverflow.com/q/47697945
type: Comment
type: QuestionComment
score: 2
has text: if you want to keep state, use a `Class`

eval
tag name: eval
tags question: http://stackoverflow.com/q/47844946
type: Tag
tags question: http://stackoverflow.com/q/47743798

http://stackoverflow.com/a/47746719
type: Answer
answers question: http://stackoverflow.com/q/47746583
accepted answer of: http://stackoverflow.com/q/47746583
score: 0
type: AcceptedAnswer
has body: When you have an instance and call one of its methods, the instance gets automatically passed as the first argument, self. So if you have a class MyClass and an instance my_instance and you call its handle_event method, it's the same as calling MyClass.handle_event(my_instance). In your program you never create an instance of the player class and so you're passing the screen as the self argument directly to the class (the screen is actually a pygame.Surface). That means the self in the handle_event method actually refers to the screen surface and since surfaces don't have an image_down attribute, Python raises an error when the self.image_down.get_rect() part is reached. To fix this problem, you have to create an instance (also called object) of the player class and must not pass an argument to handle_event (unless you add more parameters to the method): player_instance = player(x_position, y_position) Then use the instance inside of the while and event loops: while True: player_instance.handle_event() You also have to create an instance of the room1 class instead of using the class directly. Here's a complete example with some comments about other problems: import pygame pygame.init() WINDOWWIDTH = 900 WINDOWHEIGHT = 400 screen = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT)) FPS = 40 clock = pygame.time.Clock() # Load images once globally and reuse them in the program. background = pygame.image.load("bedroom.jpg").convert() background = pygame.transform.scale(background, (WINDOWWIDTH, WINDOWHEIGHT)) temp_image = pygame.image.load("stand_down.png").convert_alpha() image_down = pygame.transform.scale(temp_image, (100, 200)) temp_image = pygame.image.load("standleft.png").convert_alpha() image_left = pygame.transform.scale(temp_image, (100, 200)) temp_image = pygame.image.load("standright.png").convert_alpha() image_right = pygame.transform.scale(temp_image, (100, 200)) class player(pygame.sprite.Sprite): def __init__(self, x, y): super(player, self).__init__()…
has comment: http://stackoverflow.com/comment/82453885

http://stackoverflow.com/q/47763778
has answer: http://stackoverflow.com/a/48044764
accepted answer: http://stackoverflow.com/a/48044764
has comment: http://stackoverflow.com/comment/82562713
has comment: http://stackoverflow.com/comment/82525598
has comment: http://stackoverflow.com/comment/82489078
tagged with: python
tagged with: shared-libraries
tagged with: git
has comment: http://stackoverflow.com/comment/82526869
type: AnsweredQuestion
upvote count: 3
has body: This might be a novice question, so please excuse. We have a small python development team and our repo is organized as indicated below. We have a custom library that is shared across multiple scripts (wrappers) and then libraries specific to each wrapper. The below structure is maintained under Git. This has worked so far for development. Now we would like to release the wrappers, but individually. As in, we need to release wrapper1 targeting a separate audience (different timelines and needs) and at a later time wrapper2. Both need to contain the shared_library and only their specific library. What is the best way to do this? repo/: wrapper1.py wrapper2.py shared_library/: module1.py module2.py wrapper1_specific_lib/: wrapper1_module1.py wrapper1_module2.py wrapper2_specific_lib/: wrapper2_module1.py wrapper2_module2.py We have considered the following solutions: Re-org as three separate repos: wrapper1, wrapper2 and shared_library and release separately. Have two separate repos for wrapper1 and wrapper2 and periodically sync the shared library (!!?!!) Leave it like this but explore if it is possible to use Git in some way to release selected files, folders specific to each wrapper. Seeking you help on python code-organization for better release management using Git. Thanks in advance!!
score: 3
tagged with: release
answer count: 1
tagged with: code-structure
has comment: http://stackoverflow.com/comment/82525568
downvote count: 0
has comment: http://stackoverflow.com/comment/82491688
has title: Git and shared python library
has comment: http://stackoverflow.com/comment/82528562
favorite count: 0
type: Question

http://stackoverflow.com/q/47826357
duplicate of: http://stackoverflow.com/q/4869770
tagged with: python
linked to: http://stackoverflow.com/q/4869770
has title: Python: Initialize a variable into if
has comment: http://stackoverflow.com/comment/82615201
has comment: http://stackoverflow.com/comment/82615051
upvote count: 2
score: 2
downvote count: 0
type: UnansweredQuestion
has body: Is there a way to do this in python?: def exist(path_image): if path.isfile(path_image): return path_image else: return False path_image = '/home/user/image.jpg' if (image = exist(path_image)): print(image) Other languages like PHP and Javascript, I can initialize a variable inside 'IF' Thanks
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/82615603
has answer: http://stackoverflow.com/a/47826595
type: Question

http://stackoverflow.com/comment/82425706
type: Comment
comment on: http://stackoverflow.com/q/47732531
type: QuestionComment
has text: you should see [this tutorial](https://www.tutorialspoint.com/python/python_functions.htm)
score: 0

http://stackoverflow.com/a/47735671
has comment: http://stackoverflow.com/comment/82431879
has body: When working with a list of objects, it is generally seen as more readable to query the given model directly. So you could instead use: def average_measurement(self): return Measurement.objects.filter(location__area = self).aggregate(Avg('value'))['value__avg'] You could also adopt this approach in your second example: avg = 0 sum = 0 counter = 0 for m in Measurement.objects.filter(location__area = self): sum += m.value counter += 1 if counter != 0: avg = sum / counter return avg
has comment: http://stackoverflow.com/comment/82432017
type: Answer
has comment: http://stackoverflow.com/comment/82431925
has comment: http://stackoverflow.com/comment/82431903
score: 2
answers question: http://stackoverflow.com/q/47735635
has comment: http://stackoverflow.com/comment/82431985
upvote count: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47735635

http://stackoverflow.com/a/47856742
upvote count: 1
answers question: http://stackoverflow.com/q/47851895
score: 1
type: Answer
has body: As a high level programming language, Python is not particularly close to the processor that supports atomic operations like CAS. In fact, the Python global interpreter lock prevents your threads from running at the same time. This doesn't obviate the need for atomic operations of course (another thread could still be scheduled between the check and set) , but it does make Python look pretty unattractive for the CPU intensive applications that make atomic operations valuable. There's perhaps one way to do it; Python can integrate with c library files. So you could write C to perform CAS operations, maybe. I think it would still be subject to the GIL . I usually use Python threads to handle concurrent blocking operations like parallelization of API calls. In these cases other inter thread communication mechanisms make more sense than atomic operations on shared variables. They're simpler to implement, easier to reason about, and, given the performance characteristics of Python, are fast enough.
downvote count: 0

http://stackoverflow.com/comment/82513406
has text: Are `keyword`, `Random strings` and `Random chars` in separate lines? And can you post a more specific example, instead of using `Random strings`, `Random chars`?
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47776066
type: Comment

http://stackoverflow.com/comment/82651509
score: 0
has text: https://wiki.python.org/moin/WhileLoop
type: QuestionComment
comment on: http://stackoverflow.com/q/47843535
type: Comment

http://stackoverflow.com/comment/82885262
has text: I've edited based on your comments. Not too sure why the first approach didn't work. Note that SQLite is not recommended for use in production, even if your code works. Better to use Postgres or MySQL.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47862761
type: Comment

http://stackoverflow.com/comment/82433527
type: Comment
comment on: http://stackoverflow.com/a/47730402
type: AnswerComment
score: 0
has text: i had edited my code but it generate an error this function iwont to added to xml button object

http://stackoverflow.com/comment/82430511
comment on: http://stackoverflow.com/q/47735037
has text: What numbers did you see being printed? What numbers did you expect instead?
score: 3
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47746646
score: 5
type: UnansweredQuestion
tagged with: multiplication
answer count: 1
downvote count: 0
has title: Where is `*` documented in tensorflow?
tagged with: tensorflow
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47755111
upvote count: 5
tagged with: python
has body: I don't find where * is documented. It seems that it can be equivalent to either tf.multiply or tf.scalar_mul. Is it so?
tagged with: python-3.x

http://stackoverflow.com/q/47749622
tagged with: mysql
has comment: http://stackoverflow.com/comment/82461491
favorite count: 0
type: Question
has title: Django and MySQL save multiple data
has comment: http://stackoverflow.com/comment/82459919
has comment: http://stackoverflow.com/comment/82459536
has comment: http://stackoverflow.com/comment/82460217
upvote count: 0
score: -2
downvote count: 2
has comment: http://stackoverflow.com/comment/82461623
tagged with: django
tagged with: python
accepted answer: http://stackoverflow.com/a/47750799
has comment: http://stackoverflow.com/comment/82459534
has answer: http://stackoverflow.com/a/47750799
has body: I am trying to save multiple fields of data. I've also changed the database connection from the default sqlite3 to MySQL. And I don't know how to do this Here's my views.py def customerview(request): if request.POST: form = CustomerForm(request.POST) if form.is_valid(): if form.save(): return redirect('sales') else: return redirect('index') else: return redirect('index') else: form = CustomerForm return render(request, 'customer.html', {'form':form}) def salesview(request): if request.POST: form = SalesForm(request.POST) if form.is_valid(): if form.save(): return redirect('index') else: return redirect('index') else: return redirect('index') else: form = SalesForm data = Customer.objects.latest('id') return render(request, 'sales.html', {'form':form, 'range':range(data.number_of_transactions)}) Here's my models.py class Customer(models.Model): customer_name = models.CharField(max_length=200) number_of_transactions = models.IntegerField() class Sales(models.Model): product_type = models.CharField(max_length=100) product_code = models.CharField(max_length=100) product_size = models.CharField(max_length=100) product_quantity = models.IntegerField() Here's my brands.html {% csrf_token %} {% for i in range %} Product Type Product Code {% endfor %} The idea is to get the customer details and number of transactions to be performed then that determines the number of fields to be displayed in the sales view. And that works fine. The problem is to get each of the transactions to be saved in the database. When I submit and check my database tables, only one transaction is saved.
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82461456
has comment: http://stackoverflow.com/comment/82462302
has comment: http://stackoverflow.com/comment/82459951
answer count: 1

http://stackoverflow.com/q/47778321
has comment: http://stackoverflow.com/comment/82518539
has comment: http://stackoverflow.com/comment/82517783
type: AnsweredQuestion
has body: I have the following string representing a UTC timestamp: 2017-12-03T20:38:00.971261Z I would like to convert it into Posix timestamp (IE: seconds since the epoch) Using this online converter (https://www.epochconverter.com/) I know the answer is 1512333480 But when I do the following code, the result is off by 1800 seconds -- 30 minutes: &gt;&gt;&gt; temp_time1 = datetime.datetime.strptime('2017-12-03T20:38:00.971261Z', '%Y-%m-%dT%H:%M:%S.%fZ') &gt;&gt;&gt; ctime = int(datetime.datetime(temp_time1.year, temp_time1.month, temp_time1.day, temp_time1.hour, temp_time1.minute, temp_time1.second, temp_time1.microsecond, pytz.timezone('Europe/London')).strftime('%s')) &gt;&gt;&gt; print ctime 1512351480 Anyone know what I'm missing here??
has title: Why is converting this datetime to Epoch off by 30 minutes?
answer count: 1
downvote count: 3
accepted answer: http://stackoverflow.com/a/47778392
favorite count: 0
has answer: http://stackoverflow.com/a/47778392
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/82518781
tagged with: epoch
has comment: http://stackoverflow.com/comment/82518600
tagged with: datetime
linked to: http://stackoverflow.com/q/7065164
has comment: http://stackoverflow.com/comment/82518625
has comment: http://stackoverflow.com/comment/82517815
tagged with: python
score: -1

http://stackoverflow.com/a/47837886
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
has body: Check this solution, I have added the proper headers import requests import json session = requests.Session() loginUrl = "https://wedgfl.aquahawk.us/login" loginHeaders = { "Host": "wedgfl.aquahawk.us", "Connection": "keep-alive", "Accept": "application/json", "Origin": "https://wedgfl.aquahawk.us", "X-Requested-With": "XMLHttpRequest", "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.108 Safari/537.36", "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8", "Referer": "https://wedgfl.aquahawk.us/login", "Accept-Encoding": "gzip, deflate, br", "Accept-Language": "en-US,en;q=0.9", } loginData = { "username":"myemail@domain.tld", "password":"MySecretPassword" } #Data is posted as Json Data using json.dumps loginResponse = session.post(loginUrl, data=json.dumps(loginData), headers=loginHeaders) #If the above does not work try without json.dumps loginResponse = session.post(loginUrl, data=loginData, headers=loginHeaders) print(loginResponse) #should print 200 #check if logged in verify = session.get("https://wedgfl.aquahawk.us/") print(verify.text)
answers question: http://stackoverflow.com/q/47837771
has comment: http://stackoverflow.com/comment/82657474
accepted answer of: http://stackoverflow.com/q/47837771
has comment: http://stackoverflow.com/comment/82662282
type: Answer

http://stackoverflow.com/comment/82487826
comment on: http://stackoverflow.com/q/47761458
score: 0
type: Comment
type: QuestionComment
has text: I can print out with `print distro_date` after setting up the variable `distro_date = int(time.time())` after importing time, but the variable comes out empty when I use it in a key pair ``distributed_on': distro_date`` even though it prints ok. any ideas?

http://stackoverflow.com/comment/82448052
comment on: http://stackoverflow.com/a/47743231
type: Comment
score: 0
type: AnswerComment
has text: When it comes to give any suggestion about installing stuff, my head spins. You can google to find any solution as to how you can get `bs4` working. Btw, the above piece of code is worth trying for. Thanks.

http://stackoverflow.com/q/47819266
favorite count: 0
tagged with: keyerror
answer count: 2
has answer: http://stackoverflow.com/a/47819860
has comment: http://stackoverflow.com/comment/82600855
downvote count: 0
upvote count: 1
type: UnansweredQuestion
score: 1
tagged with: beautifulsoup
has answer: http://stackoverflow.com/a/47820019
type: Question
has body: I'm trying to scrape a website. I learned to scrape from two resources: one used tag.get('href') to get the href from an a tag, and one used tag['href'] to get the same. As far as I understand it, they both do the same thing. But when I tried this code: link_list = [l.get('href') for l in soup.find_all('a')] it worked with the .get method, but not with the dictionary access way. link_list = [l['href'] for l in soup.find_all('a')] This throws a KeyError. I'm very new to scraping, so please pardon if this is a silly one. Edit - Both of the methods worked for the find method instead of find_all.
tagged with: python
has title: Getting href using beautiful soup with different methods

http://stackoverflow.com/q/47705856
tagged with: matrix
has body: I am trying to impute missing values in the matrix by calling different functions from fancyimpute.py. NuclearNormMinimization runs fine for some of the matrices but fails for the example below. NuclearNormMinimization(verbose=False).complete(matrix) where ``` matrix = [[3.64625, 7.34375, 15.0], [5.00000, 12.50000, NaN], [15.00000,11.25000, NaN]] The error message is: TypeError: Expected NuclearNormMinimization.solve() to return NumPy array but got class 'NoneType'. I am using this approach for bigger sparse matrices, but once in a while I get a small matrix with a few missing values, and my code fails. Can somebody help me to understand why this is happening? What are assumptions for NuclearNormMinimization imputation techniques?
has comment: http://stackoverflow.com/comment/82371955
tagged with: fancyimpute
type: Question
type: UnansweredQuestion
tagged with: missing-data
tagged with: python
has comment: http://stackoverflow.com/comment/82372161
has comment: http://stackoverflow.com/comment/82372014
score: 0
answer count: 0
has title: Matrix Imputation with NuclearNormMinimization fails with TypeError

http://stackoverflow.com/comment/82382518
type: Comment
type: QuestionComment
has text: in no way is `np.matrix('1 2 2;2 3 1')` the same as `numpy.matrix('x ; y ; z')`, that's why one works and the other doesn't
comment on: http://stackoverflow.com/q/47711255
score: 0

http://stackoverflow.com/q/47745260
favorite count: 0
type: Question
has body: I am using Python 2.7 and Reportlab to create .pdf files for display/print in my app engine system. I am using ndb.Model to store the data if that matters. I am able to produce the equivalent of a bank statement for a single client on-line. That is; the user clicks the on-screen 'pdf' button and the .pdf statement appears on screen in a new tab, exactly as it should. I am using the following code to save .pdf files to Google Cloud Storage successfully buffer = StringIO.StringIO() self.p = canvas.Canvas(buffer, pagesize=portrait(A4)) self.p.setLineWidth(0.5) try: # create .pdf of .csv data here finally: self.p.save() pdfout = buffer.getvalue() buffer.close() filename = getgcsbucket() + '/InvestorStatement.pdf' write_retry_params = gcs.RetryParams(backoff_factor=1.1) try: gcs_file = gcs.open(filename, 'w', content_type='application/pdf', retry_params=write_retry_params) gcs_file.write(pdfout) except: logging.error(traceback.format_exc()) finally: gcs_file.close() I am using the following code to create a list of all files for display on-screen, it shows all the files stored above. allfiles = [] bucket_name = getgcsbucket() rfiles = gcs.listbucket(bucket_name) for rfile in rfiles: allfiles.append(rfile.filename) return allfiles My screen (html) shows rows of ([Delete] and Filename). When the user clicks the [Delete] button, the following delete code snippet works (filename is /bucket/filename, complete) filename = self.request.get('filename') try: gcs.delete(filename) except gcs.NotFoundError: pass My question - given I have a list of files on-screen, I want the user to click on the filename and for that file to be downloaded to the user's computer. In Google's Chrome Browser, this would result in the file being downloaded, with it's name displayed on the bottom left of the screen. One other point, the above example is for .pdf files. I will also have to show .csv files in the list and would like them to be downloaded as well. I only want the files to be downloaded, no…
has answer: http://stackoverflow.com/a/47758263
tagged with: http://stackoverflow.com/tag/pdf
has title: App Engine - download files from Cloud Storage
accepted answer: http://stackoverflow.com/a/47758263
possible better answer: http://stackoverflow.com/a/47752237
score: 2
upvote count: 2
type: AnsweredQuestion
tagged with: google-app-engine
has answer: http://stackoverflow.com/a/47752237
answer count: 2
downvote count: 0
tagged with: python

http://stackoverflow.com/comment/82580275
type: QuestionComment
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47809511
has text: I m confused. Not clear to me.

http://stackoverflow.com/a/47730852
type: AcceptedAnswer
has body: Just creating a tf.Session() doesn't make it a default. This is basically the difference between tf.Session and tf.InteractiveSession: sess = tf.InteractiveSession() print(tf.get_default_session()) # this is not None! Unlike tf.InteractiveSession, a tf.Session becomes a default only inside with block (it's a context manager): sess = tf.Session() with sess: print(tf.get_default_session()) # this is not None!
answers question: http://stackoverflow.com/q/47721792
type: Answer
score: 17
upvote count: 17
has comment: http://stackoverflow.com/comment/122788896
accepted answer of: http://stackoverflow.com/q/47721792
downvote count: 0

http://stackoverflow.com/q/47714423
has answer: http://stackoverflow.com/a/47714552
has answer: http://stackoverflow.com/a/47714596
favorite count: 0
type: Question
upvote count: 4
has answer: http://stackoverflow.com/a/47714555
has title: Python Iterating over lists in lists with map()
answer count: 5
has body: So my intention is to iterate over lists in lists with map, filter and lambda e.g.: [ [33,3,3,0] , [34,1,0,4] ] should result in [ [33,3,3] , [34,1,4] ] def no_zeros(lst): a=map(filter(lambda x:(y==0 for y in x) ,lst),lst) print (list(a)) #(says that filter is not callable) I know that this code won't work but i do not know what exactly i do wrong since i'm still kind of new to lambda,etc.I already tried different stuff , like moving the filter after the lambda,but that did not seem to work either . Im gratefull for any kind of tipps or help.
accepted answer: http://stackoverflow.com/a/47714521
tagged with: python
has answer: http://stackoverflow.com/a/47714527
score: 4
tagged with: lambda
possible better answer: http://stackoverflow.com/a/47714555
type: AnsweredQuestion
tagged with: filter
downvote count: 0
has answer: http://stackoverflow.com/a/47714521

http://stackoverflow.com/q/47703639
answer count: 1
has title: Why am I getting this (apparently) unusual AttributeError: 'bytes' object has no attribute '_all_strings'? Is there a way to get around it?
downvote count: 0
accepted answer: http://stackoverflow.com/a/47703853
favorite count: 0
tagged with: beautifulsoup
type: Question
has body: I've been searching for a solution to this AttributeError I keep getting, and no solution I've been able to find deals with '_all_strings'. I want to code a web-crawler, but there's a lot of nonsense at the top and bottom of the page, so I'm trying to clean up the HTML code as a precursor to excluding the unwanted noise at the top and bottom of the webpage. When I run the code below, specifically, the last line of it, I get an AttributeError: from __future__ import division from urllib.request import urlopen from bs4 import BeautifulSoup textSource = 'http://celt.ucc.ie/irlpage.html' html = urlopen(textSource).read() raw = BeautifulSoup.get_text(html) This is the full Traceback I get: Traceback (most recent call last): File "...Crawler_Celt_Namelink_Test.py", line 7, in &lt;module&gt; raw = BeautifulSoup.get_text(html) File "...Python\Python35\lib\site-packages\bs4\element.py", line 950, in get_text return separator.join([s for s in self._all_strings( AttributeError: 'bytes' object has no attribute '_all_strings' Has anybody encountered this error before? Or can anyone suggest how I can overcome it, please?
tagged with: attributeerror
tagged with: http://stackoverflow.com/tag/html
tagged with: python
tagged with: web-crawler
has answer: http://stackoverflow.com/a/47703853
type: AnsweredQuestion
score: 2
upvote count: 2

http://stackoverflow.com/a/47705576
answers question: http://stackoverflow.com/q/47705412
type: Answer
has body: There are a few things wrong with the code provided. Here's a working version with inline comments to explain what's going on. While loops allow you to check the input data before moving on. def main(): capitals = {'AL': 'Montgomery', 'AK': 'Juneau', 'AZ': 'Phoenix', 'AR': 'Little Rock', 'CA': 'Sacramento', 'CO': 'Denver', 'CT': 'Hartford', 'FL': 'Tallahassee', 'GA': 'Atlanta', 'HI': 'Honolulu', 'ID': 'Boise', 'IL': 'Springfield', 'IN': 'Indianapolis', 'IA': 'Des Moines', 'KS': 'Topeka'} # initialize variables used in while loops choice = '' guess = '' print("Choose a state from the list: {0}".format(' '.join(capitals.keys()))) # as long as choice is not in the list of capitals, keep asking while choice not in capitals.keys(): choice = input('Which state would you like to guess? : ') # get the correct answer for the chosen state answer = capitals[choice] # as long as the guess doesn't contain any non-whitespace characters, keep asking while guess.strip() == '': guess = input('Guess the capital of the state chosen : ') # if the cleaned up, case-insensitive guess matches the answer, you win if guess.strip().lower() == answer.lower(): print("Yay! You're CORRECT!") # otherwise, you lose else: print("Sorry, You're INCORRECT!") main()
score: 0

http://stackoverflow.com/comment/82486840
type: Comment
comment on: http://stackoverflow.com/q/47762325
has text: (btw, it's not bash that's being broken, but the terminal; when you run `cat somefile.txt`, bash is responsible for actually starting up `/bin/cat`, giving it `somefile.txt` as an argument, and waiting until after that process exited before printing a prompt again; but doesn't know or care what the output of `cat` was -- it's your terminal emulator that receives and handles that data).
score: 1
type: QuestionComment

http://stackoverflow.com/q/47833044
upvote count: 1
type: UnansweredQuestion
score: -4
answer count: 1
has comment: http://stackoverflow.com/comment/82628947
has comment: http://stackoverflow.com/comment/82628988
has answer: http://stackoverflow.com/a/47833489
has comment: http://stackoverflow.com/comment/82628923
favorite count: 0
linked to: http://stackoverflow.com/q/46547168
has comment: http://stackoverflow.com/comment/82629031
tagged with: pandas
downvote count: 5
tagged with: dataframe
tagged with: python
has body: Problem formulation Currently, df['B'] has values ranging from 0 to 16. I would like them replaced with as follows: S where df['B'] &lt;= 2 M where 2 &lt; df['B'] &lt;= 6 L where df['B'] &gt;= 6 DataFrame A B 5180 2 5784 0 5784 16 7269 4 7268 12 Desired output A B 5180 S 5784 S 5784 L 7269 M 7268 L Is there pandas function to do that?
type: Question
has title: I need to replace the values in the columns in my DataFrame with some groups

http://stackoverflow.com/comment/82680824
score: 0
type: QuestionComment
type: Comment
has text: Try running your application through the terminal this will show any errors. Also could you please mention what platform you are working on.
comment on: http://stackoverflow.com/q/47853468

http://stackoverflow.com/comment/82441620
has text: I just assumed someone would be able to spot my error, sorry?
score: 0
comment on: http://stackoverflow.com/q/47740692
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82671286
comment on: http://stackoverflow.com/q/47853378
has text: Thank You. I moved the tests folder under `Tools`, and added the following: `sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))`.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/47719189
score: 1
answers question: http://stackoverflow.com/q/47718590
upvote count: 1
has body: Is it possible for you to create a third table, matching the Table A Bank values to their corresponding Table B Bank values? Because without some sort of linking table specifying the relationship, the SQL server has no way of knowing that 'Barclays' = 'aa', 'tesco' = 'bb', etc. There has to be some sort of unique relationship, and you don't have that in the two tables provided. LinkTable: Code Bank aa Barclays bb tesco cc HSBC dd LLyods e MBNA You can then do: Select A.*, B.* FROM TableA A JOIN LinkTable LB ON (A.Bank = LB.Bank) JOIN TableB B ON (LB.ID = B.Bank);
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/82398811

http://stackoverflow.com/comment/82545678
type: AnswerComment
has text: @pshep123 Fair point. Okay, I tried this: `pd.merge_asof(df1, df2, on='A', tolerance=pd.Timedelta(days=5))` but it just echoes `df1` without doing anything. See if I'm doing something wrong?
comment on: http://stackoverflow.com/a/47788878
type: Comment
score: 0

keyword-argument
tags question: http://stackoverflow.com/q/47721726
type: Tag
tag name: keyword-argument
tags question: http://stackoverflow.com/q/47773427
tags question: http://stackoverflow.com/q/47833287

http://stackoverflow.com/comment/122075855
score: 1
type: Comment
has text: Please provide additional details in your answer. As it's currently written, it's hard to understand your solution.
comment on: http://stackoverflow.com/a/69071150
type: AnswerComment

http://stackoverflow.com/comment/83641253
has text: i remove content type and paste link without any encode . still the same error (
type: Comment
comment on: http://stackoverflow.com/a/48094536
score: 0
type: AnswerComment

http://stackoverflow.com/q/47810226
has comment: http://stackoverflow.com/comment/82585192
score: 7
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/67494374
tagged with: tkinter
upvote count: 8
linked to: http://stackoverflow.com/q/2969870
type: Question
tagged with: toplevel
has body: Is it possible to display the icon for my toplevel and root window after removing the minimize and maximize buttons? I tried using -toolwindow but the icon can't be displayed afterwards. Is there another way I can remove the min and max size buttons from window while still displaying the icon? from tkinter import * def top(): tp = Toplevel() tp.geometry("300x300") tp.attributes("-toolwindow", 1) tp.iconbitmap("My icon.ico") root = Tk() root.geometry("400x400") b = Button(root, text="open window with icon", command=top).pack() root.mainloop()
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82587154
has comment: http://stackoverflow.com/comment/82699634
has answer: http://stackoverflow.com/a/47867275
has answer: http://stackoverflow.com/a/69544844
has title: How to remove minimize/maximize buttons while preserving the icon?
answer count: 3

http://stackoverflow.com/q/47720439
tagged with: multiprocess
has answer: http://stackoverflow.com/a/47724499
type: AnsweredQuestion
tagged with: tkinter
has comment: http://stackoverflow.com/comment/82401485
score: 1
answer count: 1
has body: I am quite beginner with the multiprocessing module. In my code I am trying to build a dictionary with images from a given path. I wrote the following code: from multiprocessing import Pool from PIL import Image, ImageTk import glob def process(path): print path im=ImageTk.PhotoImage(Image.open(path).resize((600, 600), Image.ANTIALIAS)) name = (path.split('/')[1]).split('.')[0] return (name, im) p = Pool(4) input = glob.glob('./*.jpg') image_list = dict(p.map(process, input)) If the code works correctly I would expect something like the following: {'-22': PIL.ImageTk.PhotoImage object at 0x7f6b66507150, '-23': PIL.ImageTk.PhotoImage object at 0x7f6b66507190, ... and so on} ... but instead I get the following error: `multiprocessing.pool.MaybeEncodingError: Error sending result:` `'[('-51', PIL.ImageTk.PhotoImage object at 0x7f6b664f6990),` `('-47', PIL.ImageTk.PhotoImage object at 0x7f6b664f6fd0),` `('-54', PIL.ImageTk.PhotoImage object at 0x7f6b66507050),` `('-13', PIL.ImageTk.PhotoImage object at 0x7f6b665070d0),` `('-45', PIL.ImageTk.PhotoImage object at 0x7f6b66507110),` `('-49', PIL.ImageTk.PhotoImage object at 0x7f6b66507150),` `('-48', PIL.ImageTk.PhotoImage object at 0x7f6b66507190),` `('-26', PIL.ImageTk.PhotoImage object at 0x7f6b665071d0),` `('-10', PIL.ImageTk.PhotoImage object at 0x7f6b66507210)]'.` `Reason: 'UnpickleableError(tkapp object at 0x7f6b67c88e30,)'` How can I solve this?
has title: Python building a dictionary with multiprocessing
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82401433
upvote count: 2
linked to: http://stackoverflow.com/q/21173582
accepted answer: http://stackoverflow.com/a/47724499
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/82401468

http://stackoverflow.com/a/47855290
accepted answer of: http://stackoverflow.com/q/47854436
upvote count: 2
has comment: http://stackoverflow.com/comment/82679285
downvote count: 0
answers question: http://stackoverflow.com/q/47854436
type: AcceptedAnswer
score: 2
has comment: http://stackoverflow.com/comment/82679004
has body: I'm going to answer a specific question you asked: how to use ultimate-api. First make sure that you have python3 and virtualenv installed on your machine: $ type -a python3 $ type -a virtualenv If either of these commands does not return anything you have to install a given program first. Now go to the directory where you cloned ultimate-api repository and run: $ virtualenv -p python3 venv $ source venv/bin/activate $ pip install -r requirements.txt You don't need to be root user to do that. Now start the server: $ python3 run.py * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) * Restarting with stat * Debugger is active! * Debugger PIN: 122-615-257 Go to http://127.0.0.1:5000 in your favorite web browser, it should say hi. Now as the documentation of ultimate-api says you have to use: A full (including protocol) url for an ultimate-guitar.com tab. with /tab method. Example: http://127.0.0.1:5000/tab?url=https://tabs.ultimate-guitar.com/tab/_chk_chk_chk/intensify_bass_934215 http://127.0.0.1:5000/tab?url=https://tabs.ultimate-guitar.com/tab/_chk_chk_chk/me_and_giuliani_down_by_the_schoolyard_a_true_story_bass_512135 Update Say, to get URLs for 100 top tabs: $ wget -U firefox https://www.ultimate-guitar.com/top/tabs -O - 2&gt;/dev/null | grep -F 'https://tabs.ultimate-guitar.com/tab/' | grep -E -o '&lt;a href=.+"' | sed -E 's,^&lt;a href=",,' | sed 's,"$,,' Now you can use this URLs with ultimate-api server.
type: Answer
has comment: http://stackoverflow.com/comment/82679123
has comment: http://stackoverflow.com/comment/82679062

http://stackoverflow.com/q/47717043
score: 1
has body: I am continuing my progress with python and pygames. I am trying to count the number of mouse clicks when the color changes. For some reason, it is only counting 0 or 1, but nothing more. if mouseClicked: #I want to count the number of clicks when the color changes if event.button == 1: countMouseClick = countMouseClick + 1 #Change the window or screen display to a random integer mapped to the list. displayScreen.fill(otherColors[random.randint(0,3)]) Here's my code: #Mouse click color changer. import pygame, random, sys from pygame.locals import * pygame.time.wait(1000) # 1000 ms = 1 sec. #Initializing variables #RGB = R G B white = (255, 255, 255) black = (0, 0, 0) red = (255, 0, 0) green = (0, 255, 0) blue = (0, 0, 255) otherColors = [black, red, green, blue] bgcolor = otherColors[random.randint(0,3)] width = 640 height = 480 fps = 30 #Create a function and call it main(). def main(): pygame.init() pygame.mixer.init() fpsClock = pygame.time.Clock() displayScreen = pygame.display.set_mode((width, height)) pygame.display.set_caption('Mouse Click Color Changer') colorBoard = getRandomizedColor(otherColors) #Game Loop while True: #Process Input (Events)Step mouseClicked = False countMouseClick = 0 for event in pygame.event.get(): if event.type == QUIT or (event.type == KEYUP and event.key == K_ESCAPE): print(countMouseClick) pygame.quit() sys.exit() elif event.type == MOUSEBUTTONDOWN: mouseClicked = True #Update Step if mouseClicked: if event.button == 1: countMouseClick = countMouseClick + 1 displayScreen.fill(otherColors[random.randint(0,3)]) #Render (Draw) Step #Use cases for .update() &amp; .flip() (https://www.pygame.org/docs/tut/newbieguide.html) pygame.display.update() fpsClock.tick(fps) def getRandomizedColor(changeColor): backgroundColor = [] for color in otherColors: backgroundColor.append(color) changeColor = random.shuffle(backgroundColor) return changeColor if __name__ == '__main__': main() Any help is much appreciated even an explanation on what I am do…
tagged with: python
tagged with: pygame
accepted answer: http://stackoverflow.com/a/47717389
type: AnsweredQuestion
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47717389
answer count: 1
has title: Pygame - Count Mouse Clicks
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82394379
has comment: http://stackoverflow.com/comment/82394922
has comment: http://stackoverflow.com/comment/82394975
has comment: http://stackoverflow.com/comment/82394927

http://stackoverflow.com/comment/82611035
comment on: http://stackoverflow.com/q/47824211
type: Comment
type: QuestionComment
has text: You could pickle the variable or use a database?
score: 0

http://stackoverflow.com/q/47828209
type: AnsweredQuestion
score: 3
tagged with: list
has body: I am trying to divide all the elements of a list filled with integers by another integer (functionality like in numpy arrays) by list comprehension, like so: results = 300 * [0] for i in range(100): for j in range(300): results[j] += random.randrange(0,300) average_results = [results[x] / 100 for x in results] However, if I run this in Python, it throws an IndexError: list index out of range I have worked around this by using a regular for loop: average_results = [] for x in results: average_results.append(x/100) which works like a charm. However, in my mind the two approaches should yield the same results, so I am totally stunted as to why it does not work. Can someone point me in the right direction?
answer count: 5
tagged with: index-error
has answer: http://stackoverflow.com/a/47828424
tagged with: python
has answer: http://stackoverflow.com/a/47828298
tagged with: list-comprehension
has answer: http://stackoverflow.com/a/47828300
type: Question
accepted answer: http://stackoverflow.com/a/47828284
upvote count: 3
has answer: http://stackoverflow.com/a/47828284
downvote count: 0
possible better answer: http://stackoverflow.com/a/47828279
has title: Divide elements of a list by integer with list comprehension: index out of range
has answer: http://stackoverflow.com/a/47828279
favorite count: 0

http://stackoverflow.com/q/47801335
type: Question
tagged with: python-3.x
answer count: 2
has title: Inherit same function name from several classes
downvote count: 0
tagged with: python
tagged with: inheritance
tagged with: class
has comment: http://stackoverflow.com/comment/82564092
has comment: http://stackoverflow.com/comment/82563922
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47801465
score: 3
possible better answer: http://stackoverflow.com/a/73164576
upvote count: 3
has comment: http://stackoverflow.com/comment/82563877
has body: I was reading on this thread on stackoverflow but it looked like the solution was wrong according to a user and most important, it couldnt solve my question and I dont know if its because the answer is in python 2 or whatnow. However, lets say i have this code class A: def say_hello(self): print("Hi") class B: def say_hello(self): print("Hello") class C(A, B): def say_hello(self): super().say_hello() print("Hey") welcome = C() welcome.say_hello() How can i call both class A and B from class C without changing the names of the functions? As i read in the other thread you could do something like super(B, self).say_hello() but that does not seem to work, I dont know why though.
has answer: http://stackoverflow.com/a/47801465
linked to: http://stackoverflow.com/q/6849519
has answer: http://stackoverflow.com/a/73164576
favorite count: 0

http://stackoverflow.com/comment/82625780
comment on: http://stackoverflow.com/q/47829647
score: 0
type: Comment
type: QuestionComment
has text: I see that if the cmd does not exist, it gives a FileNotFound exception in Python 3 and an OSError in Python 2. Why not using a "try... except" clause?

http://stackoverflow.com/q/47826874
has answer: http://stackoverflow.com/a/47827355
tagged with: arrays
tagged with: python
has body: I have: &gt;&gt;&gt; a array([[1, 2], [3, 4]]) &gt;&gt;&gt; type(l), l # list of scalers (&lt;type 'list'&gt;, [0, 1]) &gt;&gt;&gt; type(i), i # a numpy array (&lt;type 'numpy.ndarray'&gt;, array([0, 1])) &gt;&gt;&gt; type(j), j # list of numpy arrays (&lt;type 'list'&gt;, [array([0, 1]), array([0, 1])]) When I do &gt;&gt;&gt; a[l] # Case 1, l is a list of scalers I get array([[1, 2], [3, 4]]) which means indexing happened only on 0th axis. But when I do &gt;&gt;&gt; a[j] # Case 2, j is a list of numpy arrays I get array([1, 4]) which means indexing happened along axis 0 and axis 1. Q1: When used for indexing, why is there a difference in treatment of list of scalers and list of numpy arrays ? (Case 1 vs Case 2). In Case 2, I was hoping to see indexing happen only along axis 0 and get array( [[[1,2], [3,4]], [[1,2], [3,4]]]) Now, when using numpy array of arrays instead &gt;&gt;&gt; j1 = np.array(j) # numpy array of arrays The result below indicates that indexing happened only along axis 0 (as expected) &gt;&gt;&gt; a[j1] Case 3, j1 is a numpy array of numpy arrays array([[[1, 2], [3, 4]], [[1, 2], [3, 4]]]) Q2: When used for indexing, why is there a difference in treatment of list of numpy arrays and numpy array of numpy arrays? (Case 2 vs Case 3)
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/47827355
linked to: http://stackoverflow.com/q/46116568
has comment: http://stackoverflow.com/comment/82616305
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/47827714
accepted answer: http://stackoverflow.com/a/47827714
upvote count: 7
score: 7
has comment: http://stackoverflow.com/comment/82616380
favorite count: 0
type: Question
tagged with: numpy
has title: numpy array indexing with lists and arrays

http://stackoverflow.com/comment/82522222
type: QuestionComment
has text: What value do you try to input?
comment on: http://stackoverflow.com/q/47780268
score: 0
type: Comment

http://stackoverflow.com/a/47744696
answers question: http://stackoverflow.com/q/47741602
type: Answer
accepted answer of: http://stackoverflow.com/q/47741602
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
has body: Did you follow these steps from the docs? Don’t forget to point AUTH_USER_MODEL to it. Do this before creating any migrations or running manage.py migrate for the first time. Also, register the model in the app’s admin.py: from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .models import User admin.site.register(User, UserAdmin)

http://stackoverflow.com/q/47739057
type: AnsweredQuestion
score: 1
tagged with: django-models
has body: I'm a beginner with Django, and first time askig :) I'm following a simple tutorial on generating a slug for a string (let's say a slug for a blog post generated from its title). Perhaps I'm following an outdated guide, perhaps I'm missing a basic thing, I have no idea. Django 2.0 Python 3.6 I am trying to do a very simple task of slugifying a simple string, so: User enters a string in a simple form When hitting 'save', the title goes through slugify and creates the slug Save. models.py from django.db import models class Testmodel(models.Model): title = models.CharField(max_length=220) slug = models.SlugField(unique=True, null=True) def __str__(self): return self.title views.py from django.views.generic.edit import CreateView class TestCreate(CreateView): model = Testmodel fields = '__all__' forms.py from django.forms import ModelForm from .models import Testmodel class TestCreateForm(ModelForm): class Meta: model = Testmodel fields = '__all__' Up until here everythig works, if I enter the slug manualy. In order to do it automaticaly, I have tried: Overriding the save() method withing my ModelForm class. Overriding the form_valid() method within the CreateView Overriding the save() method within the model itself. Tried to connect a pre_save signal to the model. In all of these 4 tries, I had the same results: When generating the form with the slug field, I couldn't do anything because it was required. When generating the form without the slug field, nothing happens when I hit save. The only way I have found to dodge this issue is to set the slug field to blank = True as well. I am not sure how secure it is, though? Thank you!
tagged with: django-forms
accepted answer: http://stackoverflow.com/a/47739176
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47739176
answer count: 1
downvote count: 0
tagged with: django
upvote count: 1
tagged with: python
has title: Cannot modify a model field on save()

http://stackoverflow.com/q/47831944
has comment: http://stackoverflow.com/comment/82627250
score: 0
has comment: http://stackoverflow.com/comment/82627000
tagged with: pandas
answer count: 0
tagged with: multiprocessing
type: Question
has body: I have 6 csv files average 10G size I run 6 processes (xargs) through shell 1 for each file merchants () { echo -n merchant_1 merchant_2 merchant_2 merchant_4 merchnat_5 merchant_6 } merchants | xargs -L1 -P6 -d' ' -I{} bash -c \"python main.py '{}' || true\ My code has the following flow. (for 1 file) Initiate a pool of 2 process # (so for 6 files = 12 processes) Read csv in chunk (pandas) (200,000) rows. # 1 chunk avg = 2gb (so for 12 processes = 24gb) pass this chunk to a pool.async(process, (df, transformer, output_filename)) The process function takes the dataframe, create a transformer object (transformer is a class which has 12 - 15 methods. Each method is responsible to perform a transformation (e.g remove certain blacklist words, rename columns, lowercase, etc) and then return the transformed dataframe. Then write the dataframe to a new csv file. So in result i get mutiple new csv files (200,000 rows each) Now the problem is the memory usage. As per above calculation 24gb (already with a bit of buffer) should be used. The machine has 64 gb of memory and 32 processors. Since i run multiprocessing i see process running varying from 10-20 through htop. But it gradually increases the memory and it reaches the whole 60GB memory and every thing get killed. There are two possible reasons which can lead to this high memory use. My code has some problem in the transformation logic (which i don't see until now) The mechanism how i am using the multi processing is not correct. Here is the related code transformer = globals()[merchant['transformer']] # i take the class name from configuration file pool = Pool(processes=merchant['num_of_process']) # 2 chunk_index = 1 for df in pd.read_csv(downloaded_file, chunksize=chunksize, compression='gzip', skipinitialspace=True, encoding='utf-8'): output_file_name = output_path + \ merchant['output_file_format'].format( file_index, chunk_index) pool.apply_async(process, (df, transformer, output_file_name)) chunk_index += 1 Process…
has title: Python multiprocessing with pandas taking full memory and killed
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
tagged with: python-multiprocessing

http://stackoverflow.com/q/47705172
has body: string = 'woraaadaaaa'; If I want to find if there is 'word' in string: for x in string: if 'word' in string: print(word) But I want to print it just when letters are next to each other, so for instance in string 'aaawordaaa' there is 'word', but in 'aaworad' not. How to do this? This is what I am looking help in
type: AnsweredQuestion
has title: how to search for letters which are next to each other?
upvote count: 0
answer count: 1
downvote count: 3
has comment: http://stackoverflow.com/comment/82370745
tagged with: string
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82370485
score: -3
tagged with: python
accepted answer: http://stackoverflow.com/a/47705262
has comment: http://stackoverflow.com/comment/82370505
has answer: http://stackoverflow.com/a/47705262

http://stackoverflow.com/q/47832880
has comment: http://stackoverflow.com/comment/82628801
has title: Why is getting this list index out of range?
has answer: http://stackoverflow.com/a/47834474
tagged with: list
answer count: 3
has body: I have a 'test.txt' file like example that contains: -- a -- b -- c and my Python code: x = ['a','b','c'] i=1 with open("test.txt", "r") as fin: with open("result.log", "w") as fout: for line in fin: if line.startswith(' --'): fout.write(line.replace(' --','use {}'.format(str(x[i-1])))) i+=i else: fout.write(line) But the result is: fout.write(line.replace(' --','use {}'.format(str(x[i-1])))) IndexError: list index out of range Should be working ... anyone can help me? I'd like to have the result: use a a use b b use c c
linked to: http://stackoverflow.com/q/47814761
downvote count: 3
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82628615
has answer: http://stackoverflow.com/a/47833029
type: UnansweredQuestion
score: -2
has comment: http://stackoverflow.com/comment/82630292
tagged with: index-error
tagged with: python
has answer: http://stackoverflow.com/a/47833597

http://stackoverflow.com/q/47834017
tagged with: tkinter
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/47834240
tagged with: simpledialog
has body: I have trouble using the simpledialog widget within a toplevel widget. The code extract below results in an empty pop-up window (entitled "Blocked fields"), a second pop-up window with the correct simpledialog (also working fine) and the main game window (not featured here in the code). I want to get rid of the second obsolete window, and I reckon it must be a simple thing, but I am stuck (complete python newbie, if you can't tell already). Any hints highly appreciated! import tkinter as tk from tkinter import simpledialog root = tk.Tk() root.geometry("580x400+300+200") root.title("Pah Tum") #Popup window block_request_top = tk.Toplevel() block_request_top.title("Blocked fields") entry_block = simpledialog.askinteger("Blocked fields", \ "Please enter a number of fields to be blocked. Choose an \ uneven number between 5,13]", parent=block_request_top, minvalue=5, \ maxvalue=13)
has title: Tkinter: Put simpledialog.askinteger in a toplevel box
score: 0
has answer: http://stackoverflow.com/a/47836771
answer count: 2
tagged with: toplevel
has comment: http://stackoverflow.com/comment/82631730
type: Question

iostream
tags question: http://stackoverflow.com/q/47735139
tag name: iostream
type: Tag

http://stackoverflow.com/q/47752723
type: Question
linked to: http://stackoverflow.com/q/26578799
possible better answer: http://stackoverflow.com/a/57911466
has answer: http://stackoverflow.com/a/57911466
tagged with: python
accepted answer: http://stackoverflow.com/a/47752936
has answer: http://stackoverflow.com/a/47752936
has title: Break pyinotify notifier loop
linked to: http://stackoverflow.com/q/974189
type: AnsweredQuestion
answer count: 2
linked to: http://stackoverflow.com/q/27356837
downvote count: 0
upvote count: 1
score: 1
has body: I'm using pyinotify.notifier to keep track of changes in a text file. When I get an specific change in it, I want to break the notifier loop. By using notifier.stop() seems to not work. Here is what I'm trying to do: class ModHandler(pyinotify.ProcessEvent): def process_IN_MODIFY(self, evt): #... Do Stuff if "Expected change": #break notifier loop if __name__ == "__main__": handler = ModHandler() wm = pyinotify.WatchManager() notifier = pyinotify.Notifier(wm, handler) wdd = wm.add_watch('example.file', pyinotify.IN_MODIFY) notifier.loop() #when finished the loop, do more stuff How can break the thread loop and return to the main program?
favorite count: 0
tagged with: pyinotify
linked to: http://stackoverflow.com/q/30925198

http://stackoverflow.com/comment/82422516
type: Comment
type: QuestionComment
has text: Please don't post multi-line Python code in comments. It's almost useless because the indentation gets lost.
score: 1
comment on: http://stackoverflow.com/q/47730861

http://stackoverflow.com/q/47733773
favorite count: 0
has answer: http://stackoverflow.com/a/47733852
type: Question
score: 1
has title: Python: reading integers in a file and adding them to a list
tagged with: python
has answer: http://stackoverflow.com/a/47733827
has answer: http://stackoverflow.com/a/47733872
has answer: http://stackoverflow.com/a/47733826
upvote count: 2
has answer: http://stackoverflow.com/a/47733834
has body: I am trying to create a function that takes an open file as an argument, reads the integers in the file which are all on their own line, then creates a list of those integers. The function should stop reading the file when there is an empty line. This is what I am stuck on. def load_ints(file): lst = [] x = 1 while x == 1: for line in file: if len(line.strip()) != 0: load = line.split() load = [int(i) for i in load] lst = lst + load else: x = 2 x = 2 return lst the file I am testing it with looks like this: 1 0 -12 53 1078 Should not be read by load_ints! len(line.strip()) != 0: is not working, it currently gives me a ValueError: invalid literal for int() with base 10: 'Should'
has answer: http://stackoverflow.com/a/47739420
type: UnansweredQuestion
downvote count: 1
answer count: 6

http://stackoverflow.com/comment/82494583
score: 0
type: AnswerComment
has text: ... (which are not only 0 or 1) is that you only have the two possible thresholds. 1) Everything with a score above ore equal to one is assumed to be the positive class. 2) Everything with a score above or equal to 0 is taken.
comment on: http://stackoverflow.com/a/47743253
type: Comment

http://stackoverflow.com/comment/82596275
type: AnswerComment
has text: It would help if you edited the question to include a full example showing the CSV input and your expected output for it.
score: 0
comment on: http://stackoverflow.com/a/47816419
type: Comment

http://stackoverflow.com/q/47744644
score: 0
has body: After groupByKey(), I got my RDD is only one line, such as (0, [a list of name]) The use-case: write the list of name to an file on s3. because this RDD is only one line, I directly use foreach() code is: def write_to_s3(keyValue): lines = keyValue[1] tmp_file = ... with open(tmp_file, w+) as f: for line in lines: f.write(line + '\n') # upload tmp_file to s3 # remove tmp_file myRDD.foreach(write_to_s3) My question is in the function write_to_s3(), lines = keyValue[1], is it possible to cause memory blow up since lines(the list) is too large?
tagged with: python
tagged with: foreach
has title: Spark foreach(keyValue), whether value cause memory blow up?
tagged with: apache-spark
answer count: 1
has answer: http://stackoverflow.com/a/47745577
tagged with: rdd
type: Question
tagged with: out-of-memory
type: UnansweredQuestion

http://stackoverflow.com/comment/82393863
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47716768
has text: @mroman `_` and `__` want to have a word with you.
type: Comment

http://stackoverflow.com/q/47780550
linked to: http://stackoverflow.com/q/11222440
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/47780631
duplicate of: http://stackoverflow.com/q/11222440
type: Question
has body: Is it possible to store a variable inside another variable? x = 5 a = x This would return 5 if I were to print(a) it. I want to make it so that when I say (after a = x) a = 4 I would actually be changing the value of x . For context, I am selecting a random variable from an existing list, checking to see if it isn't 0, then changing it to 2. If it is zero, I want to select a new variable and repeat. Thank you, all help is appreciated.
has comment: http://stackoverflow.com/comment/82522756
has comment: http://stackoverflow.com/comment/82522437
has comment: http://stackoverflow.com/comment/82522410
has title: Can I store a variable inside another variable?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82522412
tagged with: python
tagged with: variables
has comment: http://stackoverflow.com/comment/82522482
has comment: http://stackoverflow.com/comment/82522399

http://stackoverflow.com/comment/82491164
comment on: http://stackoverflow.com/a/47738654
score: 0
type: Comment
has text: Your response works as posted. I was using the wrong text file... Silly mistake on my part. Thanks for the answer though!
type: AnswerComment

http://stackoverflow.com/q/47807902
has body: Following is the file structure all are in same folder: __init__.py gnewsclient.py test.py 1) __init__.py: from .gnewsclient import gnewsclient 2) gnewsclient.py class gnewsclient: //Some methods Now I want to import methods from gnewsclient class of gnewsclient.py file inside test.py I tried from gnewsclient import * but it says parent module not loaded '' cannot perform relative import.
accepted answer: http://stackoverflow.com/a/47809171
has comment: http://stackoverflow.com/comment/82577892
has title: How to use class methods from another .py file?
has comment: http://stackoverflow.com/comment/82577489
answer count: 1
has answer: http://stackoverflow.com/a/47809171
downvote count: 0
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/82577641
has comment: http://stackoverflow.com/comment/82579072
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82577834
has comment: http://stackoverflow.com/comment/82578419
has comment: http://stackoverflow.com/comment/82577545
score: 1
linked to: http://stackoverflow.com/q/16981921
has comment: http://stackoverflow.com/comment/82578715
has comment: http://stackoverflow.com/comment/82578745
tagged with: import
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82578315
has comment: http://stackoverflow.com/comment/82579107

http://stackoverflow.com/comment/82613201
score: 1
type: QuestionComment
has text: Hi Todd, that was a typo. I'm using the right data frame name but not getting the required result.
comment on: http://stackoverflow.com/q/47822300
type: Comment

http://stackoverflow.com/comment/82637878
score: 0
comment on: http://stackoverflow.com/a/47836618
type: Comment
type: AnswerComment
has text: That is interesting... numpy is (marginally) slower. Did you have a different idea in mind?`min_val = np.argmax(data['TX']) # 10000 loops, best of 3: 51 µs per loop` versus `min_val = data.TX.idxmax() # 10000 loops, best of 3: 48.7 µs per loop`

http://stackoverflow.com/a/47802207
has body: Try pip3 install quandl. If you have python2 installed, there may be a mismatch in symlinks related to pip.
score: 0
has comment: http://stackoverflow.com/comment/82582704
answers question: http://stackoverflow.com/q/47781460
type: Answer

http://stackoverflow.com/comment/82388455
has text: If one of the numbers is a subset of the other, AND will result to the smaller of the two. It'd be similar to do `c & d == min(c, d)`, not that it matters a lot.
comment on: http://stackoverflow.com/a/47714287
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/a/47807370
has comment: http://stackoverflow.com/comment/82576766
type: Answer
has comment: http://stackoverflow.com/comment/82576873
score: 2
has comment: http://stackoverflow.com/comment/82576503
has comment: http://stackoverflow.com/comment/82576801
upvote count: 3
has comment: http://stackoverflow.com/comment/82577981
has comment: http://stackoverflow.com/comment/82576701
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82576816
downvote count: 1
has comment: http://stackoverflow.com/comment/82579059
answers question: http://stackoverflow.com/q/47806699
has comment: http://stackoverflow.com/comment/82576474
has comment: http://stackoverflow.com/comment/82576937
has body: I'd recommend appending strings to a dictionary of lists. You'll understand why. First, here's a high level approach to solving this problem - Iterate over each string Split the string into its content and list of IDs For each ID, add the string to the appropriate dict key. from collections import defaultdict import re d = defaultdict(list) for i in data: x, y = i.split('-&gt;') for z in map(int, re.findall('\d+', y)): d[z].append(x.strip()) # for performance, move the `strip` call outside the loop print(d) { "0": [ "And user clicks on the link \"Statement and letter preferences\"", "And user waits for 10 seconds", "Then page is successfully launched", "@TestRun", "And user set text \"#Surname\" on textbox name \"surname\"", "And user click on \"menu open user preferences\" label" ], "1": [ "Then page is successfully launched", "@TestRun", "And user set text \"#Surname\" on textbox name \"surname\"" ], "2": [ "And user clicks on the link \"Statement and letter preferences\"", "And user waits for 10 seconds", "Then page is successfully launched", "@TestRun", "And user set text \"#Surname\" on textbox name \"surname\"", "And user click on \"menu open user preferences\" label" ] } You can find all strings related to ID i by querying d[i]. This is much cleaner than initialising separate lists.
accepted answer of: http://stackoverflow.com/q/47806699

http://stackoverflow.com/q/47790687
has comment: http://stackoverflow.com/comment/82542700
possible better answer: http://stackoverflow.com/a/47791222
has answer: http://stackoverflow.com/a/47791222
has answer: http://stackoverflow.com/a/47791381
has comment: http://stackoverflow.com/comment/82542614
has body: I am running a method which returns a dictionary which is formed like the following : { "intents": [ { "name": "goodbye", "created": "2017-08-18T18:09:36.155Z", "updated": "2017-08-18T18:09:41.755Z", "description": null }, { "name": "hello", "created": "2017-08-18T18:05:48.153Z", "updated": "2017-08-18T18:06:06.004Z", "description": null } ], "pagination": { "refresh_url": "/v1/workspaces/9978a49e-ea89-4493-b33d-82298d3db20d/intents?version=2017-08-21" } } This is all saved in a variable called response, which contains the dictionary for over 200 values. If I print just "response", it prints all of the above, including "created/updated/description". I just want to print out the name value...and I cannot figure out how to do it. I have read some posts here and tried the following - for value in response: print(value['intent']) but similarly, this prints out everything (including description/update date etc). How can I make it only print out the name? And for a bonus, how can I add the list of names into an array which I can then iterate over?
tagged with: python
tagged with: dictionary
has title: Printing from a dictionary in Python
has comment: http://stackoverflow.com/comment/82542854
has comment: http://stackoverflow.com/comment/82542580
has comment: http://stackoverflow.com/comment/82543181
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/82543372
accepted answer: http://stackoverflow.com/a/47791221
answer count: 3
has comment: http://stackoverflow.com/comment/82543049
has comment: http://stackoverflow.com/comment/82542770
linked to: http://stackoverflow.com/q/18795253
has comment: http://stackoverflow.com/comment/82544389
has answer: http://stackoverflow.com/a/47791221
has comment: http://stackoverflow.com/comment/82542806
type: Question
tagged with: python-3.x

http://stackoverflow.com/comment/82449417
has text: @spikespaz - do not import from children back to their parents (in package structure) do it other way around, as expected by Python.
comment on: http://stackoverflow.com/q/47744580
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/138812895
type: AnswerComment
score: 0
has text: @rjurney it is not marked as the correct answer, it's marked as the *accepted* answer. On StackOverflow, the closest you get to what is the "correct" answer is the vote count. I'm not saying this is ideal, just explaining that that is how SO works.
type: Comment
comment on: http://stackoverflow.com/a/47724159

http://stackoverflow.com/comment/82574336
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47805216
has text: You can use window functions on non-streaming rdds/dataframes.

http://stackoverflow.com/comment/82386337
has text: can you explain in more detail, how the input and output file should look like? Between "210 célébrités ou évènements ont été trouvés pour la date du 1er janvier." and "Afficher le..." every textline thats end with \n or \n\r has to be in the output file?
comment on: http://stackoverflow.com/a/47711458
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/82550086
score: 4
type: QuestionComment
has text: Your second example appears to be JavaScript, which is a different language to Python. No, you can't use non-existent identifiers as keys in Python dictionaries; if you want string keys, you need the quotes.
type: Comment
comment on: http://stackoverflow.com/q/47794595

http://stackoverflow.com/comment/82561277
score: 0
has text: What confuses me here is that error message says about `X_1`, not `X`. Which hints there's one more `X` somewhere
type: QuestionComment
comment on: http://stackoverflow.com/q/47796453
type: Comment

http://stackoverflow.com/a/47842851
has comment: http://stackoverflow.com/comment/82656252
score: 2
answers question: http://stackoverflow.com/q/47842743
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/82649765
has body: If all you want to do is sum the savings amount entered, why not use a variable external to the while loop? savings_list = [] total_savings = 0 # Define out here while True: bank = input('Enter the name of the bank:') savings_amount = float(input('Enter the amount saved:')) savings_list.append({ "name": bank, "saved_this_month": savings_amount }) total_savings += savings_amount # just a simple sum cont = input('Want to add another? (Y/N)') if cont == 'N': break; print(savings_list) print(total_savings) If, however, you want to be fancy and calculate the sum after you have loaded the savings_list, you will need to convert the list of dicts into a list of something that sum knows how to handle. Try a list comprehension (EDIT: or, even better, a generator statement): total_savings = sum(x["saved_this_month"] for x in savings_list) Unrolling the list comprehension: a = [] for x in savings_list: a.append(x["saved_this_month"]) total_savings = sum(a)
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/47842743

http://stackoverflow.com/comment/82490445
has text: It's really hard to help you troubleshoot the problem without more details. Have you checked your system logs and monitored your processes? Alternatively, try a different install mechanism, such as via the command line.
comment on: http://stackoverflow.com/q/47764527
type: Comment
type: QuestionComment
score: 2

scipy
tags question: http://stackoverflow.com/q/47804883
tags question: http://stackoverflow.com/q/47706005
tags question: http://stackoverflow.com/q/47770906
tags question: http://stackoverflow.com/q/47730385
tags question: http://stackoverflow.com/q/47785237
tags question: http://stackoverflow.com/q/47723921
tags question: http://stackoverflow.com/q/47854967
tags question: http://stackoverflow.com/q/47778117
tags question: http://stackoverflow.com/q/47824229
tags question: http://stackoverflow.com/q/47743164
tags question: http://stackoverflow.com/q/47731375
tags question: http://stackoverflow.com/q/47782104
tags question: http://stackoverflow.com/q/47804632
tags question: http://stackoverflow.com/q/47737034
tags question: http://stackoverflow.com/q/47824817
tags question: http://stackoverflow.com/q/47729486
tags question: http://stackoverflow.com/q/47811757
tags question: http://stackoverflow.com/q/47707016
tags question: http://stackoverflow.com/q/47704158
tags question: http://stackoverflow.com/q/47717012
tags question: http://stackoverflow.com/q/47712058
tags question: http://stackoverflow.com/q/47850890
tags question: http://stackoverflow.com/q/47823060
tags question: http://stackoverflow.com/q/47775763
tags question: http://stackoverflow.com/q/47734122
type: Tag
tags question: http://stackoverflow.com/q/47791765
tags question: http://stackoverflow.com/q/47850760
tags question: http://stackoverflow.com/q/47698022
tags question: http://stackoverflow.com/q/47845327
tag name: scipy
tags question: http://stackoverflow.com/q/47729215
tags question: http://stackoverflow.com/q/47805978
tags question: http://stackoverflow.com/q/47755704
tags question: http://stackoverflow.com/q/47706487
tags question: http://stackoverflow.com/q/47791974
tags question: http://stackoverflow.com/q/47710333
tags question: http://stackoverflow.com/q/47808162
tags question: http://stackoverflow.com/q/47739744
tags question: http://stackoverflow.com/q/47841933
tags question: http://stackoverflow.com/q/47763534
tags question: http://stackoverflow.com/q/47812367
tags question: http://stackoverflow.com/q/47847548
tags question: http://stackoverflow.com/q/47852335
tags question: http://stackoverflow.com/q/47830386
tags question: http://stackoverflow.com/q/47843086
tags question: http://stackoverflow.com/q/47775621
tags question: http://stackoverflow.com/q/47699132
tags question: http://stackoverflow.com/q/47828185
tags question: http://stackoverflow.com/q/47739416
tags question: http://stackoverflow.com/q/47759577
tags question: http://stackoverflow.com/q/47836266
tags question: http://stackoverflow.com/q/47746500
tags question: http://stackoverflow.com/q/47833610
tags question: http://stackoverflow.com/q/47770651
tags question: http://stackoverflow.com/q/47821346
tags question: http://stackoverflow.com/q/47804754
tags question: http://stackoverflow.com/q/47727389
tags question: http://stackoverflow.com/q/47712804
tags question: http://stackoverflow.com/q/47775591
tags question: http://stackoverflow.com/q/47816761
tags question: http://stackoverflow.com/q/47770891
tags question: http://stackoverflow.com/q/47801096
tags question: http://stackoverflow.com/q/47773178
tags question: http://stackoverflow.com/q/47729060

http://stackoverflow.com/a/47701181
upvote count: 1
answers question: http://stackoverflow.com/q/47700778
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/82411213
has comment: http://stackoverflow.com/comment/82409771
has body: Not sure why you want to do that or if using a class is the better way for your purpose but, to answer your question, you can read the class variables using: params.__dict__.items() this gives you dict_items([('__module__', '__main__'), ('maxresources', []), ('functions', []), ('terminals', []), ('numvars', []), ('initpoptype', []), ('__dict__', &lt;attribute '__dict__' of 'params' objects&gt;), ('__weakref__', &lt;attribute '__weakref__' of 'params' objects&gt;), ('__doc__', None)]) and from here you can iterate with the different vatiables like: params.__dict__['maxresources'] or just iterate the tuples in dict_items list(params.__dict__.items()) gives: [('__module__', '__main__'), ('maxresources', []), ('functions', []), ('terminals', []), ('numvars', []), ('initpoptype', []), ('__dict__', &lt;attribute '__dict__' of 'params' objects&gt;), ('__weakref__', &lt;attribute '__weakref__' of 'params' objects&gt;), ('__doc__', None)] so you can check the object (second member in each tuple) corresponding to the names without underscores
accepted answer of: http://stackoverflow.com/q/47700778
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/q/47749796
tagged with: python
type: Question
accepted answer: http://stackoverflow.com/a/47749847
answer count: 1
tagged with: arrays
has body: I am scrapping a website full of JSON arrays. I'm trying to concatenate them and add a unique key to every array (see the code below): For each iteration, the bot calls the function test and if I print get_text, I have this: {"status":{"code":0,"message":"Ok","user":{"isBanned":false,"isNotConfirmed":false}},"payload":{"vat":0,"price":{"201":{"100":{"batchsize_id":60916,"quantity":100,"product_price":14.12,"shipment_price":8.98,"country_id":"DE"},"200":{"batchsize_id":60922,"quantity":200,"product_price":19.13,"shipment_price":9.06,"country_id":"DE"},"300":{"batchsize_id":60928,"quantity":300,"product_price":23.64,"shipment_price":9.14,"country_id":"DE"},"400":{"batchsize_id":60934,"quantity":400,"product_price":28.4,"shipment_price":9.23,"country_id":"DE"},"500":{"batchsize_id":60940,"quantity":500,"product_price":32.93,"shipment_price":9.32,"country_id":"DE"},"600":{"batchsize_id":60946,"quantity":600,"product_price":37.08,"shipment_price":9.4,"country_id":"DE"},"700":{"batchsize_id":60952,"quantity":700,"product_price":41,"shipment_price":9.48,"country_id":"DE"},"800":{"batchsize_id":60958,"quantity":800,"product_price":44.72,"shipment_price":9.63,"country_id":"DE"},"900":{"batchsize_id":60964,"quantity":900,"product_price":48.24,"shipment_price":9.71,"country_id":"DE"},"1000":{"batchsize_id":60970,"quantity":1000,"product_price":51.59,"shipment_price":9.79,"country_id":"DE"},"minDeliveryDays":5,"maxDeliveryDays":8}},"productionCountry":["DE"],"minDeliveryDays":5,"maxDeliveryDays":8},"pager":{"total":null,"count":null,"current":1}} And my code below try to concatenate every iteration and add a unique key for each array. def test(url_final): get_url = requests.get(url_final) #get_dict = json.loads(get_url.text) get_text = get_url.text print(get_text) dictionary['a' + str(uuid.uuid4())[:8]] = get_text print(dictionary) printit() My only issue, is that "print dictionary" returns me this: {'a6a465b1a': '{"status":{"code":0,"message":"Ok","user":{"isBanned":false,"isN…
tagged with: web-scraping
has comment: http://stackoverflow.com/comment/82460914
type: AnsweredQuestion
score: 0
has title: Concatenate json array; issue when adding a unique key
has comment: http://stackoverflow.com/comment/82459845
has answer: http://stackoverflow.com/a/47749847
has comment: http://stackoverflow.com/comment/82459881
tagged with: http://stackoverflow.com/tag/json

http://stackoverflow.com/a/47822679
has body: Here's one way of laying things out. Note that I avoid code duplication as much as possible, and take advantage of recursion to "re-ask" when the input is invalid def get_score(name): score = int(input('Enter score for Judge {}: '.format(name))) if score not in range(11): # Note that we can't assign input to a variable and check that variable at the same time print('Please enter an integer score 0-10') return get_score(name) return score def judge_score_input(): judges = {} for judge in ('A', 'B', 'C', 'D', 'E'): judges[judge] = get_score(judge) return judges judge_score_input will return a dictionary mapping the letters A-E to scores. In your original implementation, the local variables would have been discarded at the end of the function call.
has comment: http://stackoverflow.com/comment/82608312
score: 0
has comment: http://stackoverflow.com/comment/82608108
has comment: http://stackoverflow.com/comment/82608280
has comment: http://stackoverflow.com/comment/82608384
type: Answer
answers question: http://stackoverflow.com/q/47822397

http://stackoverflow.com/comment/82656953
has text: Now, this will result in another error, because not all key-value pairs have dicts with a lat key. Please take another look at your JSON and figure out _where_ you want to extract coordinates form. `location`?
type: QuestionComment
comment on: http://stackoverflow.com/q/47846457
score: 0
type: Comment

http://stackoverflow.com/q/47795792
type: Question
has comment: http://stackoverflow.com/comment/82553096
has title: How to deep join a tuple into a string
has comment: http://stackoverflow.com/comment/82552939
has answer: http://stackoverflow.com/a/47797715
upvote count: 8
has comment: http://stackoverflow.com/comment/82552798
type: UnansweredQuestion
downvote count: 0
answer count: 1
has body: I want to convert a tuple to a semicolon-separated string. Easy. tup = (1,2) ';'.join(map(str,tup)) Output: '1;2' If one of the tuple entries is itself a tuple, however, I get something like this: '1;(2, 3)' I don't want that comma, I want a semicolon, and also I'd like to select the parentheses characters as well. I want this: '1;{2;3}' Is there an easy way to deep-join a tuple of tuples nested to any depth, specifying both the separator (';' in the example) and the parenthes ('{' and '}' in the example above)? Note that I do not want this, which this question was marked as a duplicate of: '1,2,3' I also need to handle strings with commas in them, so i can't use replace: flatten((1,('2,3',4))) '1;{2,3;4}'
tagged with: python
has comment: http://stackoverflow.com/comment/82553258
has comment: http://stackoverflow.com/comment/82552738
has comment: http://stackoverflow.com/comment/82552417
has comment: http://stackoverflow.com/comment/82553049
score: 8
favorite count: 0
linked to: http://stackoverflow.com/q/2158395

http://stackoverflow.com/comment/82653904
type: QuestionComment
score: 0
has text: i have updated the question , thanks @tripleee
comment on: http://stackoverflow.com/q/47844760
type: Comment

http://stackoverflow.com/q/47851402
has answer: http://stackoverflow.com/a/47851478
has answer: http://stackoverflow.com/a/47851411
tagged with: python
has comment: http://stackoverflow.com/comment/82667349
has comment: http://stackoverflow.com/comment/82667272
has answer: http://stackoverflow.com/a/47852820
has comment: http://stackoverflow.com/comment/82667337
favorite count: 0
has comment: http://stackoverflow.com/comment/82667234
has comment: http://stackoverflow.com/comment/82667283
type: Question
score: 2
has comment: http://stackoverflow.com/comment/82667317
has title: assigning print function to variable
has comment: http://stackoverflow.com/comment/82667335
type: UnansweredQuestion
downvote count: 1
has comment: http://stackoverflow.com/comment/82667233
has body: For the following code, it seems to me that we are assigning the print function to the variable, spam. spam = print('Hello!') I'm wondering why doesn't calling spam, print out "Hello!"?
has comment: http://stackoverflow.com/comment/82667433
has comment: http://stackoverflow.com/comment/82667352
answer count: 3
has comment: http://stackoverflow.com/comment/82667330
upvote count: 3

http://stackoverflow.com/a/74309857
has body: A possible solution goes like this: filelist_unsorted=glob.glob(r"*/filen*", recursive=True) for i, file in enumerate(filelist_unsorted): df=pd.read_csv(file) #some modifications df.drop(columns=['b','c'],inplace=True) #optional: add a new column that will serve as an index df['new']=round(values[i]) if i>=1: df_stack = pd.concat([df_stack, df], axis=0) #NOTE axis=0 is vertical concatenation else: df_stack=df pd.MultiIndex.from_frame(df_stack) #optional: set the index df_stack.set_index(['new'], inplace=True) I imported the single files ad DataFrame, after the concatenation I forced the new df to be a MultiIndex and at the end I set the relevant index(es). the for loop concatenates and provides some manipulation (columns dropping, NaN correction, padding, etc.) if needed.
type: Answer
answers question: http://stackoverflow.com/q/47801393
score: 0

http://stackoverflow.com/q/47739636
downvote count: 0
has title: How to load instagram on Firefox 17 through selenium on pythonanywhere?
has body: I want to use a python script on pythonanywhere and make some tests on Instagram with Selenium. I know that pythonanywhere has Firefox 17 and there is no possibility to upgrade it. Everything works, I have no problems with Selenium, the problem is Instagram on Firefox 17. Whe I try to go on http://www.instagram.com the page is simply white apparently without content. I tried to reproduce the error on my computer installing firefox 17, and I've tried to load the page without style. And then I saw this: And of course my script gave me an exception because it couldn't find the log in button. Somebody know how to ho over it?
has comment: http://stackoverflow.com/comment/82439861
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82441379
tagged with: instagram
has comment: http://stackoverflow.com/comment/82439756
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82440049
linked to: http://stackoverflow.com/q/29916054
tagged with: python
tagged with: pythonanywhere
has comment: http://stackoverflow.com/comment/82441033
score: 2
has comment: http://stackoverflow.com/comment/82439833
answer count: 0
has comment: http://stackoverflow.com/comment/82440981
upvote count: 2
has comment: http://stackoverflow.com/comment/82439963
has comment: http://stackoverflow.com/comment/82440265
tagged with: firefox
tagged with: selenium

http://stackoverflow.com/q/47738672
type: UnansweredQuestion
score: 1
duplicate of: http://stackoverflow.com/q/39983695
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82437548
has comment: http://stackoverflow.com/comment/82437539
tagged with: python
has title: Python while loop - without condition?
linked to: http://stackoverflow.com/q/39983695
has body: I understand this code: c = 5 while c != 0: print(c) c -= 1 Output will be: 5 4 3 2 1 But eventually the code below: c = 5 while c: print(c) c -= 1 Gave me the same result. I've read something about conversion into bool automatically? Does compiler knows if c > 0 then it would be true for the while loop, and if c = 0 then it would be false?
answer count: 0

odo
tag name: odo
type: Tag
tags question: http://stackoverflow.com/q/47718488

http://stackoverflow.com/q/47836266
favorite count: 0
tagged with: lapack
type: Question
accepted answer: http://stackoverflow.com/a/47973210
has comment: http://stackoverflow.com/comment/82636212
upvote count: 2
has answer: http://stackoverflow.com/a/47973210
tagged with: python
has title: Error when diagonalising large matrices using anaconda scipy
has comment: http://stackoverflow.com/comment/82636320
has comment: http://stackoverflow.com/comment/82777700
type: AnsweredQuestion
has body: I have recently switched from using homebrew python on mac OS X to using anaconda, and I have started getting an error when diagonalising large(ish) matrices. Calling scipy.linalg.eigvalsh(A) with matrices above about 3000x3000 entries gives an error: $HOME/anaconda2/lib/python2.7/site-packages/scipy/linalg/decomp.pyc in eigvalsh(a, b, lower, overwrite_a, overwrite_b, turbo, eigvals, type, check_finite) 762 overwrite_a=overwrite_a, overwrite_b=overwrite_b, 763 turbo=turbo, eigvals=eigvals, type=type, --&gt; 764 check_finite=check_finite) 765 766 $HOME/anaconda2/lib/python2.7/site-packages/scipy/linalg/decomp.pyc in eigh(a, b, lower, eigvals_only, overwrite_a, overwrite_b, turbo, eigvals, type, check_finite) 385 if eigvals is None: 386 w, v, info = evr(a1, uplo=uplo, jobz=_job, range="A", il=1, --&gt; 387 iu=a1.shape[0], overwrite_a=overwrite_a) 388 else: 389 (lo, hi) = eigvals ValueError: On entry to ZHBRDB parameter number 12 had an illegal value The final error message seems similar to this old scipy issue: scipy/issues/5401, but the matrices I'm having problems with are much smaller. Running print np.__config__.show() gives: lapack_opt_info: libraries = ['mkl_rt', 'pthread'] library_dirs = ['$HOME/anaconda2/lib'] define_macros = [('SCIPY_MKL_H', None), ('HAVE_CBLAS', None)] include_dirs = ['$HOME/anaconda2/include'] blas_opt_info: libraries = ['mkl_rt', 'pthread'] library_dirs = ['$HOME/anaconda2/lib'] define_macros = [('SCIPY_MKL_H', None), ('HAVE_CBLAS', None)] include_dirs = ['$HOME/anaconda2/include'] lapack_mkl_info: libraries = ['mkl_rt', 'pthread'] library_dirs = ['$HOME/anaconda2/lib'] define_macros = [('SCIPY_MKL_H', None), ('HAVE_CBLAS', None)] include_dirs = ['$HOME/anaconda2/include'] blas_mkl_info: libraries = ['mkl_rt', 'pthread'] library_dirs = ['$HOME/anaconda2/lib'] define_macros = [('SCIPY_MKL_H', None), ('HAVE_CBLAS', None)] include_dirs = ['$HOME/anaconda2/include'] None
has comment: http://stackoverflow.com/comment/82800695
tagged with: anaconda
score: 2
has comment: http://stackoverflow.com/comment/82636140
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/82636213
tagged with: scipy
has comment: http://stackoverflow.com/comment/82643059

http://stackoverflow.com/q/47775811
favorite count: 0
has answer: http://stackoverflow.com/a/47776735
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47776150
tagged with: python
possible better answer: http://stackoverflow.com/a/47776150
has title: Find Latest Folder in a Path that starts with a Certain word
type: AnsweredQuestion
answer count: 2
score: 1
has body: I want to ask if it's possible to find the latest folder in a path that starts with a pattern. Example, let's say we are in this path: C:\Users\user There are 4 folders (and many other that we don't care about) that have names: folder13, folder15, folder17, folder20 How can I return that the latest folder's number is 20 with Python?
downvote count: 0
upvote count: 1
accepted answer: http://stackoverflow.com/a/47776735

http://stackoverflow.com/a/47851756
has comment: http://stackoverflow.com/comment/83149646
score: 4
upvote count: 4
has body: Even though reply_count is documented to be available on the Tweet object, it is, unfortunately, a part of the premium API: That field is only offered in the premium and enterprise API tiers and we need to do better at documenting this restriction. (reference)
downvote count: 0
answers question: http://stackoverflow.com/q/47851662
type: Answer

http://stackoverflow.com/q/47778403
has comment: http://stackoverflow.com/comment/82530369
tagged with: machine-learning
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/82537187
has answer: http://stackoverflow.com/a/57437066
downvote count: 1
score: 19
favorite count: 0
has title: Computing TF-IDF on the whole dataset or only on training data?
tagged with: tf-idf
type: AnsweredQuestion
answer count: 3
accepted answer: http://stackoverflow.com/a/47781492
has comment: http://stackoverflow.com/comment/82535495
has body: In the chapter seven of this book "TensorFlow Machine Learning Cookbook" the author in pre-processing data uses fit_transform function of scikit-learn to get the tfidf features of text for training. The author gives all text data to the function before separating it into train and test. Is it a true action or we must separate data first and then perform fit_transform on train and transform on test?
tagged with: python
has answer: http://stackoverflow.com/a/55300936
possible better answer: http://stackoverflow.com/a/55300936
tagged with: nlp
type: Question
upvote count: 20
has answer: http://stackoverflow.com/a/47781492

http://stackoverflow.com/q/47714993
has comment: http://stackoverflow.com/comment/82466488
upvote count: 3
score: 3
tagged with: setuptools
answer count: 1
has comment: http://stackoverflow.com/comment/82487699
has title: Pip install from zip file on private server not installing requirements and when requirements met it does not find the package
favorite count: 0
has comment: http://stackoverflow.com/comment/82448477
type: Question
has body: I made a command line tool to manage some actions on the server-side, and I want to easily distribute it for my coworkers using pip install from a private server we have for internal tools, and to provide them with updates on it, so we don't have to walk around with a thumbstick and doing boring pip install . -r requirements.txt for every workstation they have. I'd try to keep this short, but I think I have to include the project and packaging details to find the problem. I suspect a bad configuration of the setup.py file. The server It is a simple NGINX pointing to a folder with basic auth .htpass. Inside the folder I have the zipped project (maybe this is my first mistake?). To download and install using pip (Python 3.5+), I simply run pip install http://username:password@pip.myserver.io/tools/mypackage.zip The setup.py The requirements in the setup.py below are not downloaded. import os from setuptools import setup from mypackage import __version__, project_name # Utility function to read the README file. # Used for the long_description. It's nice, because now 1) we have a top level # README file and 2) it's easier to type in the README file than to put a raw # string in below ... def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name=project_name, version=__version__, description='Command line client for maintenance and odd jobs on the server', long_description=read('README.md'), classifiers=[ "Development Status :: 2 - Alpha", "Topic :: Utilities :: Rest", "Framework :: Click", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.5", ], keywords='cli rest client admin', author="Myself", author_email='lucas@email.com', packages=['mypackage'], zip_safe=True, install_requires=[ 'certifi==2017.7.27.1', 'chardet==3.0.4', 'click==6.7', 'idna==2.6', 'requests==2.18.4', 'urllib3==1.22', 'terminaltables==3.1.0', 'tqdm==4.19.4', 'aiohttp==2.3.3', 'aiodns==1.1.1', 'cchardet==2.1.1', 'async-timeout==2.0.0', ],…
downvote count: 0
tagged with: pip
has comment: http://stackoverflow.com/comment/82420504
tagged with: python
has comment: http://stackoverflow.com/comment/82486950
accepted answer: http://stackoverflow.com/a/47782372
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82487056
has comment: http://stackoverflow.com/comment/82448572
has answer: http://stackoverflow.com/a/47782372

http://stackoverflow.com/comment/82664851
score: 0
type: AnswerComment
has text: The easiest way to make things conditionally required is to check for co-occurrence after parsing. As it is `parse_args` does all the `required` checks as the last step. Subparsers is the only builtin tool for conditionally required arguments.
type: Comment
comment on: http://stackoverflow.com/a/47849707

http://stackoverflow.com/comment/82500404
has text: Maybe see also https://stackoverflow.com/questions/1419046/python-normal-arguments-vs-keyword-arguments
score: 0
comment on: http://stackoverflow.com/a/47768068
type: AnswerComment
type: Comment

oauth-2.0
type: Tag
tag name: oauth-2.0
tags question: http://stackoverflow.com/q/47830305
tags question: http://stackoverflow.com/q/47782592
tags question: http://stackoverflow.com/q/47854620
tags question: http://stackoverflow.com/q/47780712
tags question: http://stackoverflow.com/q/47700129

relationship
tag name: relationship
type: Tag
tags question: http://stackoverflow.com/q/47854505

http://stackoverflow.com/q/47722509
downvote count: 1
tagged with: calendar
tagged with: string
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: function
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/47722652
upvote count: 0
tagged with: list
answer count: 2
has title: How to change value in list for calendar?
has answer: http://stackoverflow.com/a/47722593
has body: The goal of my function is to book a slot in that calendar corresponding to the parameters day and time - booking is done by changing the value in the calendar to “X” (to indicate that day/time is booked). Here is the code I have so far: def find_index(val, seq): for index in range(len(seq)): place = seq[index] if place == val: return index else: return int("-1") def init_nested_list(size_outer, size_inner): cal = [] for outer_index in range(size_outer): nested_list = [] for inner_index in range(size_inner): nested_list.append("-") cal.append(nested_list) return cal def book_slot(cal,days_labels, times_labels, day, time): pos1 = find_index(day, days_labels) desired_day = cal[pos1] pos2 = find_index(time, times_labels) desired_time = desired_day[pos2] if desired_day == "X": print("We are sorry - that time is not available. Please try again.") else: print("Appointment is booked.") days_labels = ["Wednesday","Thursday","Friday"] times_labels = ["9","10","11"] cal = init_nested_list(len(days_labels), len(times_labels)) print("before" , cal) book_slot(cal, days_labels, times_labels, "Friday", "10") print("after" , cal) This is the output I'm getting: before [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']] Appointment is booked. after [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']] This is the output I should be getting: before [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']] Appointment is booked. after [['-', '-', '-'], ['-', '-', '-'], ['-', 'X', '-']] We are sorry - that time is not available. Please try again. As you can see, the correct output books the second element in the nested list(Friday at 10), but for my code it is not. I know desired_day is the day in cal that the user wants to book, but I'm just unsure of how to properly obtain that, and assign it to the string "X" when it is booked by the user. I also know that there is a coding error in the book_slot function that is causing this, but once again, I'm just unsure what it is...help please?

http://stackoverflow.com/a/47819457
has comment: http://stackoverflow.com/comment/82602127
downvote count: 0
has comment: http://stackoverflow.com/comment/82601845
answers question: http://stackoverflow.com/q/47818984
has body: I think you are looking for merge instead of concat. If each csv is turned into a dataframe you can do the following: new_df = df2.merge(df1, on=['Date','Time'], how='inner') new_df['Common'] = new_df['Common_x'] + new_df['Common_y'] new_df'Date', 'Time','Unique1', 'Unique2' ,'Common' #output Date Time Unique1 Unique2 Common 0 blah blah 55 12 117 You can also try this one liner: one_line = df2.merge(df1, on=['Date','Time'], how='inner').\ set_index(['Date', 'Time','Unique1', 'Unique2']).sum(axis=1).reset_index().\ rename(columns = {0:'Common'}) #output Date Time Unique1 Unique2 Common 0 blah blah 55 12 117
upvote count: 1
score: 1
type: Answer

http://stackoverflow.com/comment/82609707
has text: @usdq777: I have updated my answer to make info about restarting less confusing.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47823318

http://stackoverflow.com/comment/82510168
type: Comment
type: QuestionComment
score: 0
has text: Sorry, I meant a = subprocess.Popen
comment on: http://stackoverflow.com/q/47774530

http://stackoverflow.com/a/47754708
type: AcceptedAnswer
has body: You make some mistakes calculating the ARI in your code -- you calculate a and b too often because you loop over your table twice instead of just once. Also, you pass n as a parameter, but apparently it is set to 10 (that is how I get your result). It would be easier to just pass the table and then calculate n from there. I fixed your code a bit: def ARI(table): index = 0 sum_a = 0 sum_b = 0 n = sum([sum(subrow) for subrow in table]) #all items summed for i in range(len(table)): b_row = 0#this is to hold the col sums for j in range(len(table)): index += choose(table[i][j], 2) b_row += table[j][i] #outside of j-loop b.c. we want to use a=rowsums, b=colsums sum_a += choose(sum(table[i]), 2) sum_b += choose(b_row, 2) expected_index = (sum_a*sum_b) expected_index = expected_index/choose(n,2) max_index = (sum_a+sum_b) max_index = max_index/2 return (index - expected_index)/(max_index-expected_index) or if you pass on the table with row- and column sums: def ARI(table): index = 0 sum_a = 0 sum_b = 0 n = sum(table[len(table)-1]) + sum([table[i][len(table)-1] for i in range(len(table)-1)]) for i in range(len(table)-1): sum_a += choose(table[i][len(table)-1],2) sum_b += choose(table[len(table)-1][i],2) for j in range(len(table)-1): index += choose(table[i][j],2) expected_index = (sum_a*sum_b) expected_index = expected_index/choose(n,2) max_index = (sum_a+sum_b) max_index = max_index/2 return (index - expected_index)/(max_index-expected_index) then def choose(n,r): f = math.factorial if (n-r)&gt;=0: return f(n) // f(r) // f(n-r) else: return 0 table = [[1, 0, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 0, 1], [0, 0, 0, 1, 0, 0, 0, 1], [0, 1, 0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 1, 1, 2], [1, 0, 1, 0, 1, 0, 0, 3], [0, 0, 0, 0, 0, 0, 1, 1], [3, 1, 1, 1, 1, 1, 2, 0]] ARI(table) ARI(table) Out[56]: -0.0604008667388949 The correct result!
score: 0
has comment: http://stackoverflow.com/comment/82474965
type: Answer
accepted answer of: http://stackoverflow.com/q/47733231
has comment: http://stackoverflow.com/comment/82475906
answers question: http://stackoverflow.com/q/47733231

http://stackoverflow.com/comment/82430996
has text: `bytes(string_to_convert, "utf-8")`
score: 0
comment on: http://stackoverflow.com/q/47735214
type: QuestionComment
type: Comment

http://stackoverflow.com/q/47705294
has answer: http://stackoverflow.com/a/47705689
score: 1
upvote count: 1
has title: Fastest way to perform calculation between two dataframe colums?
has body: I have a pandas dataframe with 6 million rows. The columns are: ['x', 'y'] I need to apply a simple calculation between x an y, and append it to the dataframe. This is what I've tried: ''' Calculates the height of a pressure level in feet ''' def pressure_to_elevation(P, T = None): sea_level_pressure = 1013.25 if T is not None: # https://www.omnicalculator.com/physics/air-pressure-at-altitude P0 = sea_level_pressure g = 9.80665 M = 0.0289644 R0 = 8.31447 m = (np.log(P/P0)*T) / -(g*M/R0) f = 3.28084 * m return f b = 0.190284 c = 145366.45 return (1-math.pow((P/sea_level_pressure), b)) * c test_df['result'] = test_fd.apply(lambda row: pressure_to_elevation(row['x'], row['y']),axis=1) Unfortunately, this takes a ridiculous amount of time... in fact, I've yet to see it complete. Is there a faster way to do this?
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82371166
has answer: http://stackoverflow.com/a/47705508
accepted answer: http://stackoverflow.com/a/47705508
has comment: http://stackoverflow.com/comment/82370961
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/82371009
possible better answer: http://stackoverflow.com/a/47705689
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82370656
answer count: 2
downvote count: 0
tagged with: pandas

http://stackoverflow.com/a/47762196
has comment: http://stackoverflow.com/comment/82498176
upvote count: 0
answers question: http://stackoverflow.com/q/47760035
downvote count: 1
has body: Unfortunately, the normal tools aren't really able to modify or read the formatting form existing Excel files. I can think of a few solutions, though none of them are pretty. Make all of the formatted sheets in your excel file live formulas referencing hidden sheets with unformatted data, so you can just generate the .csv with python and paste the raw data into excel. The downside is that this isn't fully automated. You could read every sheet of the workbook and then re-save it with your additions. The downside is you're only reading the data, not the formatting. You would have to hard-code your formatting with the xlsxwriter package, which is extremely tedious and inflexible. You can use the win32com api to open and manipulate Excel programmatically python. You would basically open your workbook in excel and then use commands from that package (that look suspiciously like VBA) to modify the workbook. This is also tedious - in particular, it doesn't integrate with pd.DataFrame.to_excel, so you have to feed it your data by iterating through dataframes. The easiest thing would probably be to write a VBA script to open the .csv and integrate it into the workbook, and then call that script from within python after you generate the .csv.
type: Answer
score: -1

http://stackoverflow.com/comment/95933648
type: AnswerComment
has text: how can I work with Neo4J in Gremlin and Python then? I've tried to find but there aren't any guides on this topic. After starting an instance running Neo4J, how can I run Gremlin queries on it in Python?
comment on: http://stackoverflow.com/a/47856088
type: Comment
score: 0

http://stackoverflow.com/q/47727796
type: UnansweredQuestion
tagged with: python
has body: i have a column called 'str' in a Panda Dataframe. As i intend to delete all rows from it which contain no numerical values [0-9] or literal [a-z], the following statement did not work: data[data['str'].str.contains(r"[a-zA-z0-9]") == True] After the execution I analysed the column values. There are still values in it like: ("[[", "^") and it deletes values (which is in this case not desired): ("1", "2016", "20160715") Is there are anyone who could help me? Best Regards
has answer: http://stackoverflow.com/a/47728955
type: Question
has answer: http://stackoverflow.com/a/47727859
score: 0
has title: Remove rows from Pandas Dataframe which contain no numbers and no literal
answer count: 2
tagged with: pandas

http://stackoverflow.com/comment/82650178
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47843036
has text: How are you exactly trying to use print ? It works perfectly on python2 & python3 !!
score: 0

http://stackoverflow.com/comment/82522532
type: AnswerComment
has text: Did you test this? I suggest you do that ASAP before you get some very buggy code.
comment on: http://stackoverflow.com/a/47780631
score: 3
type: Comment

http://stackoverflow.com/comment/82472818
comment on: http://stackoverflow.com/q/47755800
type: Comment
type: QuestionComment
has text: But CrossValidaded?
score: 0

http://stackoverflow.com/q/47732734
accepted answer: http://stackoverflow.com/a/47732781
has body: Hi, Im struggling with strange for me error, so I want to have buttons in cascade menu, and each of them should trigger function, passing they name to it. The code is as follows: from tkinter import * def say_hi(name): print(name) root = Tk() menu = Menu(root) root.config(menu=menu) subjects_menu = Menu(menu) menu.add_cascade(label="Subjects", menu=subjects_menu) d = ["name1", "name2"] for name in d: subjects_menu.add_command(label=name, command=lambda:say_hi(name)) ''' this is also not working name = "Math" subjects_menu.add_command(label=name, command=lambda:say_hi(name)) name = "Physics" subjects_menu.add_command(label=name, command=lambda:say_hi(name)) ''' root.mainloop() So I want to print name of clicked button in console, and add buttons by iteration, not one by one (I cannot predict number of them) After running program I get no errors, and window shows. Whichever button I click, console prints "name2". I did add few more names - it always prints name of the last option. Thanks in advance
type: AnsweredQuestion
score: 0
upvote count: 1
has title: Tkinter: clicking buttons in menu is triggering function with wrong argument
tagged with: user-interface
downvote count: 1
has answer: http://stackoverflow.com/a/47732828
possible better answer: http://stackoverflow.com/a/47732828
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47732781
tagged with: python-3.x
tagged with: tkinter
answer count: 2
tagged with: python

http://stackoverflow.com/comment/83599134
score: 0
has text: Even the official repo does not cache packages. This is a surprising. I was expecting to find the cache path there.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47824544

http://stackoverflow.com/comment/82472524
type: QuestionComment
score: 1
type: Comment
has text: `print("\n".join(row))`
comment on: http://stackoverflow.com/q/47755835

http://stackoverflow.com/comment/82695933
comment on: http://stackoverflow.com/q/47842931
type: Comment
type: QuestionComment
has text: Is there any reason you have the `encoder_model = Model(inputTensor,encoded_data)`, `decoder_model = Model(encoded_input,decoded_data)`, .. lines? It looks a lot like you've tried to follow the example [here](https://blog.keras.io/building-autoencoders-in-keras.html), which doesn't include those lines, and works.
score: 0

http://stackoverflow.com/a/47706776
has body: Two step approach using str.partition and str.rpartition (could also be accomplished by a str.split and str.rsplit with a maxsplit=1 parameter each time): line = 'GET https://example.com/hello?ageSelections=0&amp;category=6000&amp;productPeriodType=3&amp;resourcePlace=resourcePlace AND 5089=5089-- PStU&amp;twoCategory=6200 HTTP/1.1' method, _, rest = line.partition(' ') url, _, protocol = rest.rpartition(' ') parsed_line = [method, url, protocol]
answers question: http://stackoverflow.com/q/47706721
upvote count: 2
type: AcceptedAnswer
downvote count: 0
score: 2
type: Answer
accepted answer of: http://stackoverflow.com/q/47706721

http://stackoverflow.com/comment/82532028
type: AnswerComment
score: 1
has text: @cᴏʟᴅsᴘᴇᴇᴅ https://github.com/python/cpython/blob/master/Objects/listobject.c#L50
comment on: http://stackoverflow.com/a/47785259
type: Comment

http://stackoverflow.com/a/47818199
downvote count: 1
answers question: http://stackoverflow.com/q/47818157
has body: Python comes with Tkinter... Try &gt;&gt;&gt; import Tkinter in the python interpreter. Edit: Proof (raw build of python 2.6) Python 2.6.6 (r266:84297, Aug 24 2010, 18:13:38) [MSC v.1500 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import Tkinter &gt;&gt;&gt; Tkinter &lt;module 'Tkinter' from 'C:\Python26\lib\lib-tk\Tkinter.pyc'&gt; &gt;&gt;&gt;
has comment: http://stackoverflow.com/comment/82598599
type: Answer
score: -1
accepted answer of: http://stackoverflow.com/q/47818157
upvote count: 0
has comment: http://stackoverflow.com/comment/82598906
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82598272

http://stackoverflow.com/comment/85921872
type: AnswerComment
has text: `sudo python script` runs the system's Python, that is correctly built against fontconfig and truetype. I'm afraid that I cannot upvote your answer...
type: Comment
comment on: http://stackoverflow.com/a/49416725
score: 0

http://stackoverflow.com/comment/82401713
type: Comment
has text: it does redirect, however In case I return HttpResponse it doesn't display the object :( at least on a right path now :)
type: AnswerComment
comment on: http://stackoverflow.com/a/47719775
score: 0

http://stackoverflow.com/comment/82434915
score: 0
has text: It seems like the filter the PDF is using for images is not supported by the library `PyPDF2` you are using. I am not aware of any other PDF readers which do include this filter, but they might well be out there, I am not an expert.
comment on: http://stackoverflow.com/q/47730944
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47724115
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82409963
has title: Remove row from pandas dataframe if it has 2 strings
has comment: http://stackoverflow.com/comment/82409828
tagged with: pandas
answer count: 1
downvote count: 3
has comment: http://stackoverflow.com/comment/82410057
tagged with: python
has comment: http://stackoverflow.com/comment/82409854
accepted answer: http://stackoverflow.com/a/47724652
has comment: http://stackoverflow.com/comment/82409864
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82409972
has answer: http://stackoverflow.com/a/47724652
upvote count: 0
has comment: http://stackoverflow.com/comment/82409918
has comment: http://stackoverflow.com/comment/82409005
has body: Im looking for a way to remove a row from a pandas data frame if it contains both of the 2 strings. I can do it if it has one, but havent been able to get both to work. Below is the code i used to remove records based on 1 string, looking to change that to include another keyword code: Vikings_dataframe_cleaned2=Vikings_dataframe_cleaned[Vikings_dataframe_cleaned.TweetText.str.contains("RT") == False] Strings to be excluded: I want to check to text to make sure that it doesnt contain both @teddyb_h20 and @casekeenum7. Example: ['@teddyb_h2o test test','@casekeenum7 and @teddyb_h2o are test','@casekeenum7 is the best right now'] The code should then produce a dataframe that looks like this: ['@teddyb_h2o test test','@casekeenum7 is the best right now']
score: -3
linked to: http://stackoverflow.com/q/11350770
has comment: http://stackoverflow.com/comment/82409946
has comment: http://stackoverflow.com/comment/82409255
tagged with: string
has comment: http://stackoverflow.com/comment/82409730

http://stackoverflow.com/q/47777497
possible better answer: http://stackoverflow.com/a/47777606
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/82516656
has title: Find values close to multiples in NumPy array
accepted answer: http://stackoverflow.com/a/47777841
tagged with: arrays
tagged with: python
has comment: http://stackoverflow.com/comment/82516175
has answer: http://stackoverflow.com/a/47777606
type: AnsweredQuestion
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/47777841
has body: I have a numpy array as follows: array([ 90., 180., 270., 360., 450., 540., 630., 720., 810., 900., 990., 1080., 1170., 1260., 1350., 1440., 1530., 1620., 1710., 1800., 1890., 1980., 2070., 2160., 2250., 2340., 2430., 2520., 2610., 2700., 2790., 2880., 2970., 3060., 3150., 3240., 3330., 3420., 3510., 3600., 3690., 3780., 3870., 3960., 4050., 4140., 4230., 4320., 4410., 4500., 4590., 4680., 4770., 4860., 4950., 5040., 5130., 5220., 5310., 5400., 5490., 5580., 5670., 5760., 5850., 5940., 6030., 6120., 6210., 6300., 6390., 6480., 6570., 6660., 6750., 6840., 6930., 7020., 7110., 7200., 7290., 7380., 7470., 7560., 7650., 7740., 7830., 7920., 8010., 8100., 8190., 8280., 8370., 8460., 8550., 8640., 8730., 8820., 8910., 9000., 9090., 9180., 9270., 9360., 9450., 9540., 9630., 9720., 9810., 9900., 9990., 10080., 10170., 10260., 10350., 10440., 10530., 10620., 10710., 10800.]) I am trying to match values that come the closest to 4300 or multiple of 4300. So the condition statement would return TRUE for the value of 4320 and 8640 in the array above and FALSE for all other values. How can I accomplish that? TIA Edit 1: After looking at the answer, I need to clarify. I was looking for the closest value within +-20% of the multiple to return TRUE.

http://stackoverflow.com/q/47814463
upvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47815866
tagged with: firebase-realtime-database
tagged with: python
has title: Pyrebase updating fields vanishes the other fields
accepted answer: http://stackoverflow.com/a/47815866
tagged with: firebase
type: AnsweredQuestion
has body: I am using Pyrabase(python wrapper for the Firebase API). I am trying to update a child's only one field like following, when I run the below code it vanishes, "anotherField"s do you guys any idea how to to it without touching "anotherField"s? My firebase db is like: { "weather":{ "Los Angeles":{ "anotherField":"something", "isSunny":false }, "istanbul":{ "anotherField":"something", "isSunny":false } } } I am trying to do update with the following data: dict = { "Los Angeles":{ "isSunny":true }, "istanbul":{ "isSunny":true } } db.child("weather").update(dict)
score: 1
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/82524475
type: AnswerComment
comment on: http://stackoverflow.com/a/47781486
type: Comment
score: 0
has text: Unless it does something with the Python script's output buffering for some reason, it's going to yield the same result as the `os.system` code.

http://stackoverflow.com/comment/82410151
comment on: http://stackoverflow.com/q/47724525
score: 1
type: Comment
type: QuestionComment
has text: What exactly does your homework ask you to do?

http://stackoverflow.com/comment/82367386
comment on: http://stackoverflow.com/q/47703471
type: Comment
type: QuestionComment
has text: `df = pd.read_csv(csv_file, sep=r'\s+', dtype={'D': np.bool})`??
score: 0

http://stackoverflow.com/comment/82643280
has text: Yeah I noticed that! :) Thanks for your help.
comment on: http://stackoverflow.com/a/47839637
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/82545614
score: 0
type: Comment
type: QuestionComment
has text: >>> chain(Build.objects.using('ob').all(), Build.objects.using('sb').all()) <itertools.chain object at 0x92e834c>
comment on: http://stackoverflow.com/q/47750439

http://stackoverflow.com/q/47741801
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/82573547
favorite count: 0
tagged with: android-asynctask
type: Question
has title: dask : How to read CSV files into a DataFrame from Microsoft Azure Blob
tagged with: dask
type: UnansweredQuestion
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/82447789
has answer: http://stackoverflow.com/a/47818673
score: 3
has body: S3Fs is a Pythonic file interface to S3, does DASK have any Pythonic interface to Azure Storage Blob. Python SDK's for Azure Storage Blob provide ways to read and write to blob, but the interface requires the file to be downloaded to the local machine from cloud. I am looking for solutions that which read the blob to support DASK parallel read as either stream or string without persisting to local disk.
tagged with: pandas
tagged with: azure

http://stackoverflow.com/comment/82475188
type: AnswerComment
has text: Was this meant to be a self-answered question all along? No worries if so - it's handy to know, but you do know that `import Image from PIL` is not valid? You're also not showing the import of the `base64` or `io` module...
comment on: http://stackoverflow.com/a/47756930
type: Comment
score: 0

http://stackoverflow.com/comment/82433328
has text: Are you sure this is part isn't correct? `SERVER=localhost;PORT:1433`. The port should be have an equal sign, no?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47731633

http://stackoverflow.com/comment/82382055
type: Comment
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/47710726
has text: This does it. Learned not to double JSON the data... :)

http://stackoverflow.com/q/47835657
accepted answer: http://stackoverflow.com/a/47836144
has answer: http://stackoverflow.com/a/47836144
type: AnsweredQuestion
has title: Human datetime diffs with Pendulum
answer count: 1
downvote count: 0
score: 1
upvote count: 1
tagged with: pendulum
favorite count: 0
type: Question
has body: I've recently stumbled upon this awesome pendulum "datetimes made easy" library. It has a very nice feature of displaying "human like" diffs between datetimes: In [1]: import pendulum In [2]: now = pendulum.now() In [3]: future = now.add(years=10) In [4]: future.diff_for_humans() Out[4]: '10 years from now' But, is it possible to make it work for a more complicated difference - say "years" and "weeks"? In [5]: future = now.add(years=10, weeks=5) In [6]: future.diff_for_humans() Out[6]: '10 years from now' I would expect it to output 10 years and 5 weeks from now.
tagged with: datetime
tagged with: python

http://stackoverflow.com/comment/82438960
type: AnswerComment
has text: @Pumi Happy to help! You're welcome :) Let me know if you get stuck somewhere again ^_^
type: Comment
comment on: http://stackoverflow.com/a/47739176
score: 0

http://stackoverflow.com/a/47724319
score: 3
has comment: http://stackoverflow.com/comment/82409416
answers question: http://stackoverflow.com/q/47724289
upvote count: 3
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/47724289
has body: To keep the 3rd element, include it in the list comprehension: &gt;&gt;&gt; [ [x - 1 for x in stack[0:2]] + stack[2:] for stack in nested ] [[0, 0, 1], [1, 1, 2], [2, 2, 3]] The above works for stack of any length. Or, if stack always has exactly three elements: &gt;&gt;&gt; [[x-1, y-1, z] for x, y, z in nested] [[0, 0, 1], [1, 1, 2], [2, 2, 3]] Or, you can make the changes in place: &gt;&gt;&gt; for stack in nested: stack[0]-=1; stack[1]-=1 ... &gt;&gt;&gt; nested [[0, 0, 1], [1, 1, 2], [2, 2, 3]]

http://stackoverflow.com/comment/82556847
has text: sound like combination of , groupby+reindex +fillna
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47797955

http://stackoverflow.com/comment/82779070
type: QuestionComment
comment on: http://stackoverflow.com/q/47854129
has text: @Guy I've included my error code.
score: 0
type: Comment

http://stackoverflow.com/comment/82650249
has text: set `count=0` and it should exit `while` loop. You run code in function so you can use `return` to exit function
comment on: http://stackoverflow.com/q/47842701
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/47839224
tagged with: return-value
accepted answer: http://stackoverflow.com/a/47839310
has body: When I was embedding some python code into my C++ program and trying to import a python module and get a pointer to it, I here have two options: Passing an empty pointer as an argument: void importPyModule(PyObject * modPtr, const char *modName){ modPtr = PyImport_ImportModule(modName); if(modPtr == nullptr){ std::cout &lt;&lt; "python module: " &lt;&lt; modName &lt;&lt; " import failed\npython message: "; PyErr_Print(); std::exit(1); } } Or returning a pointer: PyObject *importPyModule(const char *modName){ PyObject *modPtr = PyImport_ImportModule(modName); if(modPtr == nullptr){ std::cout &lt;&lt; "python module: " &lt;&lt; modName &lt;&lt; " import failed\npython message: "; PyErr_Print(); std::exit(1); } } For completeness, This is where I am calling my function: #include "Python.h" #include &lt;stdint.h&gt; #include &lt;stdlib.h&gt; #include &lt;stdio.h&gt; #include &lt;iostream&gt; #include &lt;iomanip&gt; int main(){ initPython(); // initialize the interpreter and set appropriate paths PyObject *aws_tools, *boto, *imp, *sdb; // Option 1: return pointer aws_tools = importPyModule("aws_tools"); // Or option 2: pass a pointer importPyModule(aws_tools, "aws_tools"); /* Some other code */ return 0; } When I pass the pointer as an argument, I get a pointer that points to: &lt;unknown at [some address]&gt; But when I the pointer a return value from the function, I get: &lt;module at [some address]&gt; The pointer to module will work properly while the pointer to unknown will crash the program. My question is: Are there better ways of doing this job (than using pointers?) What is causing the difference in behavior here? I am using g++ with c++11 standard and python2.6
answer count: 1
has answer: http://stackoverflow.com/a/47839310
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82642749
has comment: http://stackoverflow.com/comment/82642480
upvote count: 1
tagged with: python
tagged with: parameter-passing
has title: pointer parameter vs pointer return value
tagged with: pointers
tagged with: c++
type: AnsweredQuestion
score: 0

http://stackoverflow.com/q/47847803
has answer: http://stackoverflow.com/a/47847867
accepted answer: http://stackoverflow.com/a/47847867
has comment: http://stackoverflow.com/comment/82659972
favorite count: 0
has title: Replacing for loop with while loop python
type: Question
upvote count: 0
answer count: 2
tagged with: for-loop
downvote count: 2
score: -2
tagged with: python
possible better answer: http://stackoverflow.com/a/47847901
has body: I have a dynamic range of rows in this api i am calling. I have looked at some prior use of while loops but I cant seem to figure out how to swap the for loop in this script out for a while loop. header = ["fanduel", "fd_first_name", "fd_last_name", "fd_player_salary", "draftkings", "dk_first_name", "dk_last_name", "dk_player_salary"] headers = { "Authorization": "Basic " + base64.b64encode('{}:{}'.format(USERNAME,PASSWORD)\ .encode('utf-8')).decode('ascii') } with open("dailydfs.csv", 'w', newline='') as f: writer = csv.writer(f) writer.writerow(header) for fordate in range(20171215,20171216): #ENTER DATE'S req = requests.get(url="https://api.mysportsfeeds.com/v1.1/pull/nhl/2017-2018-regular/daily_dfs.json?fordate=" + str(fordate) , headers=headers) req.raise_for_status() data = req.json() daily_dfs = data['dailydfs'] fanduel = daily_dfs['dfsEntries'][0]['dfsType'] draftkings = daily_dfs['dfsEntries'][1]['dfsType'] for i in range(20): fd_player = daily_dfs['dfsEntries'][0]['dfsRows'][i]['player'] salary_fd = daily_dfs['dfsEntries'][0]['dfsRows'][i] fd_last_name = fd_player['LastName'] fd_first_name = fd_player['FirstName'] fd_player_salary = salary_fd['salary'] dk_player = daily_dfs['dfsEntries'][1]['dfsRows'][i]['player'] salary_dk = daily_dfs['dfsEntries'][1]['dfsRows'][i] dk_last_name = dk_player['LastName'] dk_first_name = dk_player['FirstName'] dk_player_salary = salary_dk['salary'] writer.writerow([fanduel, fd_first_name, fd_last_name, fd_player_salary, draftkings, dk_first_name, dk_last_name, dk_player_salary]) print(fanduel, fd_first_name, fd_last_name, fd_player_salary, draftkings, dk_first_name, dk_last_name, dk_player_salary) OUTPUT: FanDuel Jonathan Quick 8800 DraftKings Martin Jones 8400 FanDuel Henrik Lundqvist 8600 DraftKings Aaron Dell 8300 FanDuel Frederik Andersen 8500 DraftKings Frederik Andersen 8200 FanDuel Martin Jones 8500 DraftKings Curtis McElhinney 8100 FanDuel Ben Bishop 8500 DraftKings Cory Schneider 7900 FanDuel Cory Schneider 8200 Draf…
has answer: http://stackoverflow.com/a/47847901
has comment: http://stackoverflow.com/comment/82659827
type: AnsweredQuestion
tagged with: while-loop

http://stackoverflow.com/a/47836166
type: AcceptedAnswer
downvote count: 1
accepted answer of: http://stackoverflow.com/q/47832281
score: 3
has body: To scroll through the webpage untill the url is mydealz.de/?page=3 you can use the following block of code : from selenium import webdriver driver = webdriver.PhantomJS(executable_path=r'C:\\Utility\\phantomjs-2.1.1-windows\\bin\\phantomjs.exe') driver.set_window_size(1400,1000) driver.get("https://www.mydealz.de") while ("3" not in driver.current_url) : driver.execute_script("window.scrollTo(0, document.body.scrollHeight);") print(driver.current_url) driver.quit() Console Output : https://www.mydealz.de/?page=3
type: Answer
has comment: http://stackoverflow.com/comment/82702725
upvote count: 4
answers question: http://stackoverflow.com/q/47832281

http://stackoverflow.com/a/54052876
answers question: http://stackoverflow.com/q/47804627
type: AcceptedAnswer
downvote count: 0
score: 7
upvote count: 7
has body: I have been in a similar situation. Unsolvable pylint issue class A: pass There are many warnings in pylint for the code above, but I want to talk about old-style-class. In Python 2.7, you will get an old-style-class error. Of course, you can change your code like this: class A(object): pass However, you will receive a useless-object-inheritance warning in Python 3. If you are writing a package compatible with python 2.7 and 3 and using pylint, then you are down. Unavoidable bad-option-value Yes, if it is accepted to disable either of old-style-class or useless-object-inheritance in a comment, you can go further. In Python 2.7: # pylint: disable=old-style-class class A: pass In Python 3: # pylint: disable=useless-object-inheritance class A(object): pass Eventually, you will get a bad-option-value, just the same as this question. Disable bad-option-value I have tried, but bad-option-value can not be disabled locally in this case. I have to disable bad-option-value in a pylint configuration file, like .pylintrc. [TYPECHECK] disable=bad-option-value Note: My pylint version is 1.9.4 in python 2.7, 2.2.2 in python 3.
type: Answer
accepted answer of: http://stackoverflow.com/q/47804627

selenium2library
tags question: http://stackoverflow.com/q/47831039
type: Tag
tag name: selenium2library

http://stackoverflow.com/comment/82535699
comment on: http://stackoverflow.com/a/47777546
score: 0
type: Comment
has text: Can you give some explanation how missing_keys affected?
type: AnswerComment

http://stackoverflow.com/a/47760684
has comment: http://stackoverflow.com/comment/94601664
downvote count: 0
score: 10
upvote count: 10
has body: I just find one solution. But I do not know if there is any better ones. m = tf.constant([[0, 2, 1],[2, 0, 1]]) # matrix y = tf.constant([1,2]) # values whose indices should be found y = tf.reshape(y, (y.shape[0], 1)) # [[1], [2]] cols = tf.where(tf.equal(m, y))[:,-1] # [2,0] init = tf.global_variables_initializer() with tf.Session() as sess: init.run() print(sess.run(cols)) The above outputs: [2, 0]
answers question: http://stackoverflow.com/q/47759777
type: Answer

http://stackoverflow.com/comment/91251608
score: 1
has text: This works, but running a dummy forward pass looks yucky to say the least :\ not your fault, but TF's
comment on: http://stackoverflow.com/a/48033863
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47736059
has answer: http://stackoverflow.com/a/47741481
favorite count: 0
type: Question
type: AnsweredQuestion
tagged with: python
has title: Flask config not being loaded using FLASK_APP and App Factory
score: 2
has body: I have an application set up, trying to configure it with a .env file, using python-dotenv to load it and a Config class to get the variables. If I set the FLASK_APP, for example: export FLASK_APP=pg.py, and do flask run, the app runs, but the config isn't loaded. I know the environmental variables are being loaded from my .env file, and after lots of tinkering, I realized that the app is being created with no context (I think), but I'm not sure how to get it do so. If I add app.run() to the end of pg.py, it works, but I know that is not what I'm supposed to do. I've read this page: http://flask.pocoo.org/docs/0.12/cli/ several times, and I can't quite follow it to get what I'm after. I tried export FLASK_CONFIG=development as my last attempt, to see if that would work correctly, and it did not. So my question is, how do I use flask run, and get it to run my app correctly as opposed to running 'python pg.py' Edit: I notice everything works properly, except the configuration. Not sure what I am missing. I feel like, based on what I've read, that FLASK_CONFIG=development should work. It's almost as if the app gets created with 'app = Flask(name)', skips the config loading, and goes to the Blueprint registration. Why? I know I can export all my sensitive information before running, and do it that way, but now I am stuck on trying to figure out a problem, and won't be able to let it go until I understand :/ Edit 2: Actually, the context is created properly and the configuration is applied. It just doesn't read from the environment. DEBUG=True doesn't work, but other configurations do. Perhaps the app instance is created before the environment is loaded with variables from .env. I will leave this here, and update with a solution when I find it. app/__init__.py from flask import Flask from flask_sqlalchemy import SQLAlchemy from config import config db = SQLAlchemy() def create_app(config_name): app = Flask(__name__) app.config.from_object(config[config_name]) config[conf…
has comment: http://stackoverflow.com/comment/123337238
upvote count: 2
linked to: http://stackoverflow.com/q/55078512
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/47741481
tagged with: flask

http://stackoverflow.com/comment/82583367
score: 0
type: QuestionComment
has text: BTW: to close frame use `self.destroy()` (but it will not close window). If you use Python 3 then you can use `super().__init__()` instead of `tk.Frame.__init__(self)`
comment on: http://stackoverflow.com/q/47810514
type: Comment

http://stackoverflow.com/comment/82581311
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47805161
has text: If I exclude modules the executable is no longer standalone, can I exclude the parts of eg numpy that I dont use?
type: AnswerComment

http://stackoverflow.com/q/47853468
score: 5
upvote count: 5
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82686524
downvote count: 0
has body: My program is working in anaconda spyder. however, after freezing it all widgets that use the tkinter module work except for the widget with xgboost and pandas. No error showed, the build worked but the button is not working and not showing the widget. I've tried importing and including xgboost in my setup.py file but all other widgets with tkinter didn't work altogether. No error still though. have anyone experienced or solved this issue? Here's the closest thing that worked. This is my setup.py, when the other widgets worked with tkinter but not the one with xgboost and pandas. from cx_Freeze import setup, Executable import sys import os includes = [] include_files = [r"C:/Users/USER/Anaconda3/DLLs/tcl86t.dll", r"C:/Users/USER/Anaconda3/DLLs/tk86t.dll", r"C:/Users/USER/SAMPLE/xgboost_USE.model", r"C:/Users/USER/SAMPLE/P1.ico"] os.environ['TCL_LIBRARY'] = "C:/Users/USER/Anaconda3/tcl/tcl8.6" os.environ['TK_LIBRARY'] = "C:/Users/USER/Anaconda3/tcl/tk8.6" base = 'Win32GUI' if sys.platform == 'win32' else None setup(name=application_title, version='1.0', description='SAMPLE', options={"build_exe": {"includes": includes, "include_files": include_files}},executables= [Executable(r'C:/Users/USER/SAMPLE/sample.py', base=base)]) Please help.
tagged with: python
has comment: http://stackoverflow.com/comment/82680824
tagged with: xgboost
favorite count: 0
tagged with: cx-freeze
tagged with: widget
answer count: 1
has title: cxfreeze widget with tkinter xgboost not showing but no error
has answer: http://stackoverflow.com/a/47861748
type: Question
tagged with: tkinter

http://stackoverflow.com/q/47703751
tagged with: pandas
tagged with: openpyxl
tagged with: xlsxwriter
downvote count: 0
has body: I have a 140MB Excel file I need to analyze using pandas. The problem is that if I open this file as xlsx it takes python 5 minutes simply to read it. I tried to manually save this file as csv and then it takes Python about a second to open and read it! There are different 2012-2014 solutions that why Python 3 don't really work on my end. Can somebody suggest how to convert very quickly file 'C:\master_file.xlsx' to 'C:\master_file.csv'?
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47710363
has answer: http://stackoverflow.com/a/55286944
type: UnansweredQuestion
upvote count: 5
has comment: http://stackoverflow.com/comment/82367880
tagged with: python
has answer: http://stackoverflow.com/a/47703801
has answer: http://stackoverflow.com/a/47704239
answer count: 4
has title: how can I quickly convert in python an xlsx file into a csv file?
score: 5
tagged with: xlrd

http://stackoverflow.com/q/47754103
possible better answer: http://stackoverflow.com/a/47754531
favorite count: 0
has comment: http://stackoverflow.com/comment/82469756
tagged with: namedtuple
type: Question
tagged with: memory-management
has answer: http://stackoverflow.com/a/47754531
answer count: 2
upvote count: 0
accepted answer: http://stackoverflow.com/a/47754199
downvote count: 2
tagged with: python
has answer: http://stackoverflow.com/a/47754199
tagged with: dictionary
tagged with: class
has body: So, I have a large 30k line program I've been writing for a year. It basically gathers non-normalized and non-standardized data from multiple sources and matches everything up after standardizing the sources. I've written most everything with ordered dictionaries. This allowed me to keep the columns ordered, named and mutable, which made processing easier as values can be assigned/fixed throughout the entire mess of code. However, I'm currently running out of RAM from all these dictionaries. I've since learned that switching to namedtuples will fix this, the only problem is that these aren't mutable, so that brings up one issue in doing the conversion. I believe I could use a class to eliminate the immutability, but will may RAM savings be the same? Another option would be to use namedtuples and reassign them to new namedtouples every time a value needs to change (i.e. NewTup=Tup(oldTup.odj1, oldTup.odj2, "something new"). But I think I'd need an explicit way to destroy the old one afterwords or space could become an issue again. The bottom line is my input files are about 6GB on disk (lots of data). I'm forced to process this data on a server with 16GB RAM and 4 GB swap. I originally programmed all the rows of these various I/O data sets with dictionaries, which is eating too much RAM... but the mutable nature and named referencing was a huge help in faster development, how do I cut my addition to dictionaries so that I can utilize the cost savings of other objects without rewriting the entire application do to the immutable nature of tuples. SAMPLE CODE: for tan_programs_row in f_tan_programs: #stats not included due to urgent need tan_id = tan_programs_row["Computer ID"].strip() #The Tanium ID by which to reference all other tanium files (i.e. primary key) if("NO RESULT" not in tan_id.upper()): tan_programs_name = tan_programs_row["Name"].strip() #The Program Name tan_programs_publisher = tan_programs_row["Publisher"].strip() #The Program Vendor tan_programs_vers…
type: AnsweredQuestion
score: -2
has title: How to cut my addiction to Python dictionaries

http://stackoverflow.com/comment/82566038
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47801935
type: AnswerComment
has text: Thanks it worked now if i want to retrieve only most frequent classes what i will add e.g most frequent is P1 and P2 only

http://stackoverflow.com/a/59057841
type: Answer
has comment: http://stackoverflow.com/comment/104355219
score: 0
answers question: http://stackoverflow.com/q/47795001
has body: You need to be careful with this solution. It does not account for crossing the primary index. For instance, import pandas as pd import datetime ticker_date = [ ('US',datetime.date.today()-datetime.timedelta(3)), ('US',datetime.date.today()-datetime.timedelta(2)), ('US',datetime.date.today()-datetime.timedelta(1)), ('EU',datetime.date.today()-datetime.timedelta(2)), ('EU',datetime.date.today()-datetime.timedelta(1))] index_df = pd.MultiIndex.from_tuples(ticker_date) example = pd.DataFrame([12.2,12.5,12.6,15.1,15],index_df,['value']) idx = pd.MultiIndex.from_product(( example.index.get_level_values(0).unique(), example.index.get_level_values(1).unique())) example = example.reindex(idx).ffill() print(example) produces: value US 2019-11-23 12.2 2019-11-24 12.5 2019-11-25 12.6 EU 2019-11-23 12.6 &lt;== 2019-11-24 15.1 2019-11-25 15.0

http://stackoverflow.com/q/47831916
type: UnansweredQuestion
has title: Print as you type in Ajax using python
has comment: http://stackoverflow.com/comment/82638888
tagged with: django
tagged with: ajax
score: 0
tagged with: django-views
has comment: http://stackoverflow.com/comment/82627035
has comment: http://stackoverflow.com/comment/82628861
tagged with: ajaxform
has comment: http://stackoverflow.com/comment/82638319
has comment: http://stackoverflow.com/comment/82626833
tagged with: python
has body: Problem Statement: As we type in the text box it has to display exactly the same text that is entered in the text field in the index.html file without clicking submit button using Ajax To do this I have coded in this way shown below: Index.html Submit after typing finished Printing... XViews.py #!C:/Users/user/AppData/Local/Programs/Python/Python36/python.exe import cgi import cgitb cgitb.enable() def print_header(): print("""Content-type: text/html\n """) def print_close(): print (""" """) def display_error(): print_header() print (" An Error occurred parsing the parameters passed to this script. ") print_close() def main(): form = cgi.FieldStorage() search = form.getvalue('search-input') query = request.GET.get('q') if query is not None and query != '' and request.is_ajax(): print (" This is from query ") if search is not None and search != '' and request.is_ajax(): print (" This is from search ") # if "search" in form: # print_header() # print(" Entered Text %s %s " % (search)) # print_close() # else: # display_error() main() Output Result: But whenever I type any text characters it displays Could Not Print than the expected result?
type: Question
answer count: 0
has comment: http://stackoverflow.com/comment/82626889

http://stackoverflow.com/comment/82602358
has text: To be honest I just want to keep the best_solutions somewhere, and thought I could do that. How should I go about it?
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47819301

http://stackoverflow.com/a/47710504
has comment: http://stackoverflow.com/comment/82380801
has body: Here is a solution that has the benefit of doing every sum only once. It is also quite short: import operator def sort_lol(lol): srtd, sums = zip(*sorted((sort_lol(el) if isinstance(el, list) else (el, el) for el in lol), key=operator.itemgetter(1))) return list(srtd), sum(sums) lst = [[2,1,3],4,[2,3],7,1,[9,[4,2],5]] print(sort_lol(lst)) # ([1, 4, [2, 3], [1, 2, 3], 7, [5, [2, 4], 9]], 43) # note that the function returns the sorted list and the total (43 here)
type: Answer
answers question: http://stackoverflow.com/q/47710068
has comment: http://stackoverflow.com/comment/82380971
score: 0

http://stackoverflow.com/a/47751671
score: 0
answers question: http://stackoverflow.com/q/47738406
type: AcceptedAnswer
has body: Because you've used the association object pattern with extra_data the automap relationship detection will not recognize Country_Region_Mapping as a secondary table of a many to many: If the table contains two and exactly two ForeignKeyConstraint objects, and all columns within this table are members of these two ForeignKeyConstraint objects, the table is assumed to be a “secondary” table, and will not be mapped directly. Put another way: not all columns within Country_Region_Mapping are members of the foreign key constraints, so the table is not a secondary, so no many to many relationship is created. Another thing you've overlooked is the naming scheme. If you had a working secondary table, then the created relationship would be named regions_collection by default (because of the plural table name). What does happen is that the many to one / one to many relationships between regions and Country_Region_Mapping, and countries and Country_Region_Mapping are created: In [22]: table_countries.country_region_mapping_collection Out[22]: &lt;sqlalchemy.orm.attributes.InstrumentedAttribute at 0x7f2d600fb258&gt; In [23]: table_regions.country_region_mapping_collection Out[23]: &lt;sqlalchemy.orm.attributes.InstrumentedAttribute at 0x7f2d600fbaf0&gt; In [28]: table_country_region_mapping.countries Out[28]: &lt;sqlalchemy.orm.attributes.InstrumentedAttribute at 0x7f2d535a2990&gt; In [29]: table_country_region_mapping.regions Out[29]: &lt;sqlalchemy.orm.attributes.InstrumentedAttribute at 0x7f2d535a2938&gt; Note that due to plural table naming the scalar relationship attributes on Country_Region_Mapping also have plural naming. With these in mind you'd add a new association like so: In [36]: c.country_region_mapping_collection.append( ...: Base.classes.Country_Region_Mapping(countries=c, regions=r))
type: Answer
accepted answer of: http://stackoverflow.com/q/47738406

http://stackoverflow.com/comment/82511328
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47706343
has text: Try `celery.config_from_object(app.config, force=True)` and see if it helps?
score: 0

http://stackoverflow.com/a/47735421
has body: All paths need to lead to a return statement of your own for you not to get None. For example, here you didn't return a value. else: print("Enter Hours between 0 and 24") get_hours() # return None # this is implicit Suggestion: Use a proper loop, not recursion, but if you do, you should return the recursed result. else: print("Enter Hours between 0 and 24") return get_hours() # this is explicit
upvote count: 1
answers question: http://stackoverflow.com/q/47735381
downvote count: 0
score: 1
type: Answer

http://stackoverflow.com/comment/82586475
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47811761
has text: yes if you want to display email or number then you have to type it. What is wrong with this approach ?
type: Comment

http://stackoverflow.com/comment/82359932
comment on: http://stackoverflow.com/q/47699695
type: QuestionComment
score: 0
has text: Actually, maybe I wasn't clear in my question. The reason is because there's one key, but possibly hundreds of languages. So I wanted to say "choose the key, then stick everything else in the langs", like unpacking might do with an unknown-length array. I also want to not have to specify each language itself by name. But really that may just be hammering a nail with a sausage. Just wanted something short and elegant
type: Comment

http://stackoverflow.com/q/47782185
tagged with: styling
has comment: http://stackoverflow.com/comment/82554755
has comment: http://stackoverflow.com/comment/82530174
favorite count: 0
type: Question
score: 3
has answer: http://stackoverflow.com/a/47803063
upvote count: 5
tagged with: matplotlib
tagged with: python
linked to: http://stackoverflow.com/q/12444716
has comment: http://stackoverflow.com/comment/82538810
has body: I am looking to increment the plot title font size, by bumping it from e.g. medium to large. My plots are getting their base font size as well as modifiers from a matplotlibrc .conf file. This is commonly expressed like so: font.size : 8 axes.titlesize : medium Now, for one of my plots, I would like to increment the title font size, specifically. Were this a number (as it is for e.g. the linewidth), I could do something like: from matplotlib import rcParams newsize = rcParams['lines.linewidth']*2 But this won't work as easily as that. I could, of course, use a dictionary or a series of elif statements - but I am thinking matplotlib, knowing how to interpret these strings, perhaps also has some function to increment them. Do you know of such a thing? EDIT: Someone has suggested this would be a duplicate of some other question. This question specifically inquires about incrementing the "string font size" (as I have written in the title of the question). This means that setting the font size manually to some integer is not an option (unless there is a way to convert matplotlibrc's small or medium to integers - which would also be unique to this question).
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47803063
downvote count: 2
has title: Increment matplotlib string font size
tagged with: rc
answer count: 1
has comment: http://stackoverflow.com/comment/82527853

http://stackoverflow.com/comment/82522987
has text: You need to post the contents of `PDF_Merge_Script.py` in order for anyone here to know what's going on, but luckily for you my psychic powers are telling me you need to read ["What does `if __name__ == “__main__”:` do?"](https://stackoverflow.com/q/419163/744178).
score: 2
type: Comment
comment on: http://stackoverflow.com/q/47780722
type: QuestionComment

http://stackoverflow.com/comment/82417661
has text: always put full error message (Traceback) in question (as text, not screenshot). There are other useful informations.
type: Comment
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/47728631

http://stackoverflow.com/comment/82547710
comment on: http://stackoverflow.com/q/47793192
score: 1
type: QuestionComment
has text: try `C:\\pickle\\ `
type: Comment

least-squares
tags question: http://stackoverflow.com/q/47780845
tags question: http://stackoverflow.com/q/47738471
tags question: http://stackoverflow.com/q/47752210
tags question: http://stackoverflow.com/q/47733367
tag name: least-squares
type: Tag
tags question: http://stackoverflow.com/q/47712804

http://stackoverflow.com/comment/82422981
has text: @Mathi: That's something I cannot solve for you. Check your column names, whether the import is correct etc. It is a standard function, if it does not work, something is wrong with you data (as written above, your column name is probably not `x,` but e.g. `time`).
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47723651

http://stackoverflow.com/q/47748542
has comment: http://stackoverflow.com/comment/82528726
has comment: http://stackoverflow.com/comment/82496377
tagged with: python
tagged with: kivy
type: Question
score: 2
answer count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/82488918
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82481081
downvote count: 0
has body: I tested application with using OpenGl and always were problems with Mesh parametr fmt, which is used for mapping list vertices. At finding the solution of problem I used more simple example. For my question here I edited original code from Kivy manual. To code is added switch between originall and mz modified variant of code. I tested next variants of parameter fmt with these results: vertex_format = [('v_pos', 3, 'float')] -> Exception: expected byte, found str vertex_format = [(b'v_pos', 3, 'float')] -> no picture of scene on the screen I don't use parameter fmt -> picture of scene has incorrect geometry Cann You explain me using of parametr fmt? Thank You for Your interest! from kivy.uix.button import Button from kivy.uix.widget import Widget from kivy.uix.boxlayout import BoxLayout from kivy.app import App from kivy.graphics import Mesh from functools import partial from math import cos, sin, pi class MeshTestApp(App): def change_mode(self, mode, *largs): self.mesh.mode = mode def build_mesh(self): #switch between original and alteration code # switch = False #original switch = True #alteration """ returns a Mesh of a rough circle. """ vertices = [] indices = [] step = 10 istep = (pi * 2) / float(step) # my alteration # mask for mapping list of vertices # where is problem with format? vertex_format = [(b'v_pos', 2,"float")] for i in range(step): x = 300 + cos(istep * i) * 100 y = 300 + sin(istep * i) * 100 if switch == False: # originall code vertices.extend([x, y, 0, 0]) else: # my alteration vertices.extend([x, y]) indices.append(i) if switch == False: # originall code return Mesh(vertices=vertices, indices=indices) else: # my alteration return Mesh(vertices=vertices, indices=indices, fmt = vertex_format ) def build(self): wid = Widget() with wid.canvas: self.mesh = self.build_mesh() layout = BoxLayout(size_hint=(1, None), height=50) for mode in ('points', 'line_strip', 'line_loop', 'lines', 'triangle_strip', 'triangle_fan'): button = Button(text=mode) button…
has title: KIvy: mapping list of vertices for using class Mash
favorite count: 0
has comment: http://stackoverflow.com/comment/82489000

http://stackoverflow.com/a/58286391
score: 2
answers question: http://stackoverflow.com/q/47740535
downvote count: 0
upvote count: 2
type: Answer
has body: I did a dirty workaround which somehow works. I edited sublimerepl.py like: if view.name() == view_id: found = view old_rv = self.repl_view(found) if old_rv: old_rv.on_close() window.focus_view(found) break Also I changed the on_close function from self.repl.close() to self.repl.kill() Now, the amount of Python instances stays the same. There are still some inconsistencies. When I use this code to talk to an Arduino, I'll get a PermissionError every other time. Adding time.sleep(1) didn't change this. I'm open to suggestions. EDIT: After using my "solution" for a while, I got annoyed by ***Repl Killed*** appearing everytime I executed code. Therefore, I decided to close the current REPL view and just start a new one. This way, I don't get an unnecessary amount of tabs, the background Python shell is closed and I start a fresh view every time I execute my code. The new code for sublimerepl.py is: for view in window.views(): if view.name() == view_id: view.close() break view = window.new_file() close() still has to be replaced by kill() for some reason.

http://stackoverflow.com/a/47832293
downvote count: 0
score: 6
has comment: http://stackoverflow.com/comment/82629629
accepted answer of: http://stackoverflow.com/q/47832205
has comment: http://stackoverflow.com/comment/82630834
has comment: http://stackoverflow.com/comment/82628531
type: Answer
answers question: http://stackoverflow.com/q/47832205
has comment: http://stackoverflow.com/comment/82630186
upvote count: 6
has comment: http://stackoverflow.com/comment/82627746
has comment: http://stackoverflow.com/comment/82630305
has comment: http://stackoverflow.com/comment/82627347
type: AcceptedAnswer
has body: It as simple as follow: objective_ouput_set = {item[1] for item in id}

http://stackoverflow.com/q/47835564
has answer: http://stackoverflow.com/a/47835618
tagged with: function-calls
has title: Python: How do I wrap function calls, not the functions themselves?
accepted answer: http://stackoverflow.com/a/47836318
answer count: 5
tagged with: python
has answer: http://stackoverflow.com/a/47835707
possible better answer: http://stackoverflow.com/a/47835609
has answer: http://stackoverflow.com/a/47835609
score: 2
type: AnsweredQuestion
upvote count: 3
has body: For example, I've got functions, funcA(), funcB(), funcC(). I'd like to call each of these functions, but after each one, perform a series of other functions, like func1(), func2(), func3(), func4(). I know that I could: funcA() func1() func2() func3() func4() funcB() .... Or that I could: def funcCombined(): func1() func2() func3() func4() funcA() funcCombined() funcB() funcCombined() ... But is there a better way? I tried putting them in a list, like: funcs = [funcA(), funcB(), funcC()] for func in funcs: x = func func1() func2() func3() func4() But it seems to be executing all of the functions in the list and then executing them in the for loop. What's the best way to do this?
tagged with: for-loop
has answer: http://stackoverflow.com/a/47837211
has answer: http://stackoverflow.com/a/47836318
downvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/a/47744393
accepted answer of: http://stackoverflow.com/q/47719890
score: 1
upvote count: 1
type: Answer
has body: Turns out there were two things I needed to do: Dump the data with --natural-primary, --natural-foreign, and -e contenttypes Have loaddata ignore post_save signals It still takes a very long time to load the data, but it works.
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47719890
downvote count: 0

http://stackoverflow.com/comment/82467535
type: Comment
has text: @martineau Actually, looks like the decorator syntax you mention is very similar to AOP.
type: AnswerComment
comment on: http://stackoverflow.com/a/47742575
score: 0

http://stackoverflow.com/comment/82430807
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47735090
has text: @RoadRunner last time I tried I ran into dependency issues. But even if it's gotten completely trivial, I don't think it's worth installing the whole thing just for `numpy.sum`. Just my opinion, there are reasonable arguments for installing it anyway.

http://stackoverflow.com/q/47737277
accepted answer: http://stackoverflow.com/a/47737599
has title: Pandas using loc for assignment in a Multi Index DataFrame
has answer: http://stackoverflow.com/a/63610060
has comment: http://stackoverflow.com/comment/82435533
tagged with: dataframe
tagged with: python
type: AnsweredQuestion
tagged with: python-2.7
answer count: 3
tagged with: pandas
upvote count: 3
has answer: http://stackoverflow.com/a/47737599
has answer: http://stackoverflow.com/a/47737368
downvote count: 0
has body: I have initialised a dataframe like this: df = pd.DataFrame(columns=["stockname","timestamp","price","volume"]) df.timestamp = pd.to_datetime(df.timestamp, format = "%Y-%m-%d %H:%M:%S:%f") df.set_index(['stockname', 'timestamp'], inplace = True) Now I get stream of data from somewhere but for the sake of program let me write it like this: filehandle = open("datasource") for line in filehandle: line = line.rstrip() data = line.split(",") stockname = data[4] price = float(data[3]) timestamp = pd.to_datetime(data[0], format = "%Y-%m-%d %H:%M:%S:%f") volume = int(data[6]) df.loc[stockname, timestamp] = [price, volume] filehandle.close() print df but this is giving error: ValueError: cannot set using a multi-index selection indexer with a different length than the value
has comment: http://stackoverflow.com/comment/82435493
favorite count: 0
type: Question
tagged with: indexing
possible better answer: http://stackoverflow.com/a/63610060
score: 3

http://stackoverflow.com/comment/82699100
type: AnswerComment
comment on: http://stackoverflow.com/a/47845074
has text: @IskyMathews: Make it work for a fixed number, then generalize. You can take inspiration (maybe even some of the code) from the itertools implementation.
score: 0
type: Comment

http://stackoverflow.com/comment/82515459
comment on: http://stackoverflow.com/q/47776516
has text: Read this blog for better understanding - https://www.dataquest.io/blog/settingwithcopywarning/
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47701545
tagged with: python-3.x
answer count: 2
type: UnansweredQuestion
tagged with: python
tagged with: dictionary
tagged with: list
score: 0
has title: accessing list in python 3
has answer: http://stackoverflow.com/a/47701626
has body: I'm storing key and value in a dictionary called campaign_name, then access the value using randvalue. That works fine. But when I try to access certain element in the randvalue, let's say randvalue[0] or randvalue[1] it would throw an error. I can print(randvalue) perfectly and the value would show like this [[16949.070963, 2694507, 76606]]. But I can't print just 16949.070963. My complete section of code is as follows: Thanks for the help. def startchecking(): storepast() # loading file into opepyxl ref_workbook = openpyxl.load_workbook(path) # Grab all the sheet name in the workbook workbook_tab = ref_workbook.get_sheet_names() for i in workbook_tab: ws = ref_workbook[i] randvalue=campaign_name.get(str(ws['B4'].value)) print(randvalue) temptext = "Starting Check" + str(ws) textoutput(temptext) checkdaily(45, 52)
has comment: http://stackoverflow.com/comment/82364699
has answer: http://stackoverflow.com/a/47701590
type: Question

http://stackoverflow.com/a/47711052
type: Answer
answers question: http://stackoverflow.com/q/47710333
upvote count: 4
accepted answer of: http://stackoverflow.com/q/47710333
has body: The short answer is: floc (and fscale for that matter) are used to specify that the location parameter (and scale parameter respectively) are to be kept fixed at the specified value. loc and scale merely give starting values for the fit. sp.stats.weibull_min inherits the fit method from scipy.stat.rv_continuous. The documentation of scipy.stats.rv_continuous.fit specifies the fact, that floc and fscale keep said parameters fixed. loc, scale and other keyword arguments that are recognized by derived distributions are simply used as starting values. So if you want to fit keeping the location fixed, you should use floc=0 if you only want to provide a starting parameter, you should use loc=0.
type: AcceptedAnswer
downvote count: 0
score: 4
has comment: http://stackoverflow.com/comment/82395888

http://stackoverflow.com/comment/82409011
has text: I hate to ask if it might just be a simple answer, but how would you go about doing that. That seems to be the problem I'm having, I've been searching through the documentation but can't find it.
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47724073

http://stackoverflow.com/comment/82518373
score: 0
type: Comment
has text: "List index out of range" means that you are trying to access element N of some list, but that list has fewer than N elements. You will probably find the error pretty quickly if you `print(len(var_list), x)` in both loops in the last section of your code.
type: QuestionComment
comment on: http://stackoverflow.com/q/47778543

http://stackoverflow.com/comment/82490275
type: QuestionComment
has text: Give some test cases where `unwrap` does not work as you expect.
type: Comment
comment on: http://stackoverflow.com/q/47764452
score: 0

http://stackoverflow.com/a/47738475
answers question: http://stackoverflow.com/q/47738145
downvote count: 0
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/82437324
has comment: http://stackoverflow.com/comment/82437163
has body: As others have pointed out, you could check for the existence of the variables using locals(), but the question remains why you would want to do that. A reason I can imagine is that you want to ensure that the memory for a large object that is no longer needed is released. To do that, you can simply assign None to the variable. try: a = VeryLargeObject() b = AnotherVeryLargeObject() ... finally: a = b = None However, if this code is encapsulated in a function, the memory is released anyway as soon as the function returns. That being said, I would not clutter my code with manual "memory management" unless you run into actual memory issues. Edit: after @JonClements comment, I want to clarify: assigning None to a name, just like del, doesn't actually remove the object referenced by a name, it just removes the reference. In this example, the object a referred to would not be released, because there is still referenced from the global list: global_list = [] try: a = VeryLargeObject() global_list.append(a) b = AnotherVeryLargeObject() ... finally: a = b = None
has comment: http://stackoverflow.com/comment/82437291
upvote count: 2

http://stackoverflow.com/a/47823904
type: AcceptedAnswer
has body: an alternative solution: ... &lt;ListButton&gt;: height: self.texture_size[1] on_release: self.parent.parent.parent.parent.parent.ChangeScreen(self.index) ... but just do this for the events like on_press, on_release never for on_parent because they have no parent when this last event is call for the explanation all you have to know is that self.parent.parent.parent is your ListView I hope this helps
accepted answer of: http://stackoverflow.com/q/47821478
answers question: http://stackoverflow.com/q/47821478
score: 1
upvote count: 1
type: Answer
downvote count: 0

http://stackoverflow.com/a/47827600
answers question: http://stackoverflow.com/q/47827424
score: 0
has body: In the first program return the value needed and save it in a text file and in the second program open the file and use the value from the imported file as an input to your second program.
type: Answer

http://stackoverflow.com/comment/97665803
type: AnswerComment
score: 0
has text: I am developing a complex project. currently i have many apps, each apps is highly dependent on each others' models. so is it okay to have a 'core' app to keep all the models (centralize models) to avoid migrations dependency in the future? example: the app_a/views.py and app_b/views.py will import core.a_model and core. b_model respectively. @brunodesthuilliers
type: Comment
comment on: http://stackoverflow.com/a/47797730

c++
tags question: http://stackoverflow.com/q/47766364
tags question: http://stackoverflow.com/q/47848525
tags question: http://stackoverflow.com/q/47848123
tags question: http://stackoverflow.com/q/47762543
tags question: http://stackoverflow.com/q/47777315
tags question: http://stackoverflow.com/q/47806199
tags question: http://stackoverflow.com/q/47735139
tags question: http://stackoverflow.com/q/47839224
tags question: http://stackoverflow.com/q/47768372
tags question: http://stackoverflow.com/q/47793096
tags question: http://stackoverflow.com/q/47796460
tags question: http://stackoverflow.com/q/47754260
type: Tag
tags question: http://stackoverflow.com/q/47724911
tags question: http://stackoverflow.com/q/47752670
tags question: http://stackoverflow.com/q/47796013
tags question: http://stackoverflow.com/q/47797759
tag name: c++
tags question: http://stackoverflow.com/q/47768868
tags question: http://stackoverflow.com/q/47761090
tags question: http://stackoverflow.com/q/47849366
tags question: http://stackoverflow.com/q/47817448

http://stackoverflow.com/q/47744433
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82449046
has answer: http://stackoverflow.com/a/47744829
linked to: http://stackoverflow.com/q/17348548
has title: Get values from a histogram without using plt
score: 5
type: UnansweredQuestion
answer count: 1
downvote count: 0
tagged with: histogram
has comment: http://stackoverflow.com/comment/82449758
has body: Is there any way to get the values in "x" and "y" of a histogram without graphing** it? I use the function below many times (in each loop) in my code, and I noticed that my code gets slower and slower in each loop. ** I am not sure if what it does internally is to graph but I know that the slowness in my code is related to the function "plt.hist" despite using plt.close(). Thank you. # a is a list def function_hist(a, ini, final): # 12 bins bins = np.linspace(ini, final, 13) weightsa = np.ones_like(a)/float(len(a)) y, x, _ = plt.hist(a, bins, weights = weightsa) plt.close()
upvote count: 5
tagged with: python

http://stackoverflow.com/a/47765235
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47764343
type: Answer
accepted answer of: http://stackoverflow.com/q/47764343
has body: Referring the link: https://www.tensorflow.org/api_docs/python/tf/nn/conv3d the filter should be a tensor, to be specific a variable (trainable), so change the filter=[5, 5, 5, 3, 8] to filter=tf.get_variable(shape=[5, 5, 5, 3, 8], dtype=tf.float64, name='filter') then run it and should work.
score: 0

http://stackoverflow.com/comment/82551840
type: QuestionComment
has text: I don't understand the question. Are `index` and `index2` defined or do you want the values of undefined variables as keys?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47794595

http://stackoverflow.com/a/47883775
has body: I think You can use the default class in django to a achieve the same result. As far as i understood i got the scenario like this we have two django forms and we need it to be used in same template if that is the scenario we can use the LoginView from django.contrib.auth.views which has several customizable option like you can give the additional form like this class LoginUserView(LoginView): authentication_form = LoginForm extra_context = {"register_form": RegistrationForm} template_name = 'accounts/index.html' it will be using the get context data method to update the form which you will be able to get in the template and use accordingly .If you are not wishing to use the code like this you can still use it like this class MyEmailUpdateView(LoginRequiredMixin, EmailView): form_class = EmailForm template_name = 'account/account_settings' success_url = reverse_lazy('settings') def get_context_data(self, **kwargs): context = super(MyEmailUpdateView, self).get_context_data(**kwargs) context['password_reset_form'] = ResetPasswordForm return context def form_valid(self, form): return super(MyEmailUpdateView, self).form_valid(form) Then you can handle your post in the form valid accordingly as your requirement. Hope that helps get back if you need any additional requirement.
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47789661
upvote count: 2
answers question: http://stackoverflow.com/q/47789661
type: Answer
score: 2

http://stackoverflow.com/q/47824723
tagged with: ssl-certificate
tagged with: twill
score: 3
tagged with: python-2.7
upvote count: 3
has title: Debug Twill Exception Error
answer count: 1
downvote count: 0
favorite count: 0
type: Question
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47844536
tagged with: ssl
has body: I have been failing to go to a URL usign twill and I couldn't find a way to debug the issue further. I have enabled debug levels in twill for "http","equiv-refresh" and "commands", still twill is not giving any details about the error. Here is the output from twill-sh: $ twill-sh -= Welcome to twill! =- current page: *empty page* &gt;&gt; debug equiv-refresh 1 DEBUG: setting equiv-refresh debugging to level 1 current page: *empty page* &gt;&gt; debug http 1 DEBUG: setting http debugging to level 1 current page: *empty page* &gt;&gt; debug commands 1 DEBUG: setting commands debugging to level 1 current page: *empty page* &gt;&gt; go https://auth.nbnco.net.au/okta/login ERROR: cannot go to 'https://auth.nbnco.net.au/okta/login' current page: *empty page* And here is the output from the python script: $ ./test.py Traceback (most recent call last): File "./test.py", line 13, in &lt;module&gt; go("https://auth.nbnco.net.au/okta/login") File "/usr/lib/python2.7/site-packages/twill/commands.py", line 109, in go browser.go(url) File "/usr/lib/python2.7/site-packages/twill/browser.py", line 91, in go raise TwillException("cannot go to '%s'" % (url,)) twill.errors.TwillException: cannot go to 'https://auth.nbnco.net.au/okta/login'
tagged with: python

http://stackoverflow.com/comment/82778524
comment on: http://stackoverflow.com/a/47898836
type: Comment
score: 0
type: AnswerComment
has text: The attrs suggestion is relevant but I don't find this an extremely un pythonic request, why not have decorators that implement customary hiding of certain members in serialization? Anyway, you're the only runner up for this bounty so far.

http://stackoverflow.com/comment/82637735
has text: You're welcome! When you apply an aggregation function on a single variable, you get a `Series` as output. It's only one vector, so it doesn't get referenced by name, the way you would in a multi-column data frame. It's still called `Time`, though, as you can see in the output. You can also check this with `divstack.name` (you'll see that's equal to `'Time'`).
type: Comment
comment on: http://stackoverflow.com/a/47836874
type: AnswerComment
score: 0

http://stackoverflow.com/comment/82534040
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47786518
has text: Where is the template?
score: 0

http://stackoverflow.com/comment/82577892
type: QuestionComment
comment on: http://stackoverflow.com/q/47807902
has text: @You'reawesome Does not work
score: 0
type: Comment

http://stackoverflow.com/comment/82646552
score: 0
has text: ..and `from coverage.misc import CoverageException` from the command prompt (from the same directory) works and imports the CoverageException class.
type: QuestionComment
comment on: http://stackoverflow.com/q/47840155
type: Comment

http://stackoverflow.com/q/47759323
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/47760879
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/104950533
upvote count: 2
has body: My program is in Python and my configuration file is in yaml. I would like to use variables and some math expressions in my yaml file. (eg: $var + $offset) It seems like Ansible supports both, but I am not familiar with Ansible and not sure whether I can only import the part which handles yaml configuration. Any help will be appreciated. Reference: Ansible - Can I use arithmetic when setting a variable value? Update: Ideally, I would like to use playbook feature from Ansible as a library. Something like described here: http://oriolrius.cat/blog/2015/01/21/using-ansible-like-library-programming-in-python/ But I couldn't make it work seems like the instruction is outdated.
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/41620674
has title: Python: can I use variables and simple expression in yaml configuration file with the help of Ansible?
has answer: http://stackoverflow.com/a/47759641
linked to: http://stackoverflow.com/q/33505521
tagged with: ansible
score: 1
tagged with: yaml

http://stackoverflow.com/q/47698771
score: 1
has comment: http://stackoverflow.com/comment/82378171
accepted answer: http://stackoverflow.com/a/47699619
downvote count: 1
has comment: http://stackoverflow.com/comment/82378074
has comment: http://stackoverflow.com/comment/82357807
favorite count: 0
has title: Python Trig Functions Return Complex Numbers?
has comment: http://stackoverflow.com/comment/82358420
has comment: http://stackoverflow.com/comment/82359294
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/82358815
has comment: http://stackoverflow.com/comment/82357837
has comment: http://stackoverflow.com/comment/82358935
has comment: http://stackoverflow.com/comment/82358961
tagged with: python
has body: I am writing code that accepts the degree by which a motor turns and uses that data to calculate the distance covered by the wheels (using distance = no. of rotations * distance covered per rotation). It then makes an error adjustment (taking into consideration environmental factors such as friction). Finally, using trigonometry, it calculates the distance moved along the x-axis and y-axis. All the above is done by the function straight contained within the class CoordinateManager. This function is called by an instance of another class. class CoordinateManager: goalcord = [20, 0] def __init__(self): self.curcord = [0, 0] self.theta = 0 def get_compass_angle(self): compass = Sensor(address='in2') return compass.value(0) def turn(self, iangle, fangle): self.theta = self.theta + (fangle-iangle) def straight(self, turnangle): d = turnangle*2*3.14*2/360 d = 1.8120132*(d**0.8938054) thetarad = radians(self.theta) dx = d*sin(thetarad) dy = d*cos(thetarad) self.curcord[0] += dx self.curcord[1] += dy Printing both d and self.theta shows that they contain correct values. This must mean that the array self.curcord has valid values too. However, this has not been the case. Printing the two elements of self.curcord outputs complex numbers (some big float + another big floatj). I can think of no logical explanation for this other than that the trigonometric functions must be returning complex numbers. However, I think the chances that a python built-in lib function returns wrong values are extraordinarily slim. Is there any logical error that I may be overlooking? Edit: I just tried changing the last two lines to: self.curcord[0] += dx self.curcord[1] += dy I just tried using .real when displaying the values. Even though the values are real now, they are still wrong. I will look further into whether this is caused by some calculation error.
answer count: 1
has comment: http://stackoverflow.com/comment/82358130
has comment: http://stackoverflow.com/comment/82357718
has answer: http://stackoverflow.com/a/47699619
has comment: http://stackoverflow.com/comment/82358689
type: AnsweredQuestion
tagged with: math
tagged with: trigonometry
tagged with: complex-numbers
has comment: http://stackoverflow.com/comment/82357798
has comment: http://stackoverflow.com/comment/82359095

http://stackoverflow.com/q/47762190
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/82486355
has title: Process ends before expected Python
downvote count: 0
has comment: http://stackoverflow.com/comment/82486459
score: 1
upvote count: 1
tagged with: process
answer count: 1
has comment: http://stackoverflow.com/comment/82485866
has comment: http://stackoverflow.com/comment/82486143
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47762496
tagged with: mongodb
has body: I am writing a simple Python program in Pycharm that imports a csv database to a Mongodb, shows a progress bar while importing and, after being imported all documents, run some other functions... Since I use a subprocess instruction to run mongoimport command I must do some waiting for the other functions not to be executed before the mongimport. Here comes the issue: if I use subprocess.wait() the progress bar stops updating until the mongoimport ends, else if I use sleep() the same happens... So I tried to run mongoimport subprocess and the functions that updates the progress bar in the same process. Then I use an "empty" while loop checking if process.is_alive() so the main program does nothin, while the process is importing and updating the progress bar... BUT it exits the loop before expected! Long before the mongoimport neither the progress bar function end. Here is the code: def mainFunction(self): process1 = Process(target=self.execc()) process1.start() while process1.is_alive(): print("IM IN PROCESS 1") # THIS IS PRINTED BEFORE "execc()" ENDS print("IM OUT!") # other functions self.toISO() self.createFrec() self.sort() def execc(self): p = subprocess.Popen(['mongoimport', '-d', 'tfg', '-c', 'myCol', '--type', 'csv', '--file', './myFile.csv', '--headerline'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) # shows and updates the progress bar while mongoimpor self.showProgress() # RECURSIVE FUNCTION # updates the progress bar every 200ms def showProgress(self): bytes = self.db.command('collStats', self.coll_name.get()) self.pBar['value'] = bytes['size'] if bytes['size'] &lt; self.maxbytes: self.pBar.after(200, self.showProgress)

http://stackoverflow.com/a/66958931
answers question: http://stackoverflow.com/q/47704895
has body: I do not know whether it is relevant with your case but since we assigning the file path in string type like cv2.imread("filepathHere"), if arguments like "\b" or "\r" occurs in the file path it causes program to pop an error such as this. When I encountered such an error before, I changed the file name from file / brick.png to ibrick.png and the problem was resolved.
score: 1
upvote count: 1
type: Answer
downvote count: 0

http://stackoverflow.com/a/47765144
has comment: http://stackoverflow.com/comment/82492353
has comment: http://stackoverflow.com/comment/82491874
answers question: http://stackoverflow.com/q/47764825
score: 0
has comment: http://stackoverflow.com/comment/82492072
has body: This should give you the desired result: import datetime as dt import numpy as np import matplotlib.pyplot as plt fig = plt.figure(1).clf() ax = plt.subplot(111) data1 = np.arange(30) time = dt.datetime(2004,1,1,0,0,0) + dt.timedelta(days=1)*data1 data2 = data1*data1 ax.plot(time, data1) major = slice(2,None,7) ax.set_xticks(time, minor=True) ax.set_xticks(time[major]) ax.set_xticklabels([t.strftime('%Y %m %d') + '\nSquare is ' + str(d2) for (t,d2) in zip(time,data2)][major])
has comment: http://stackoverflow.com/comment/82494777
type: Answer

http://stackoverflow.com/comment/82609099
type: Comment
type: AnswerComment
has text: Unfortunatelly this not working, Im trying to render form to base template, from which few more will be extended, so render is not suitable here. The most weird staff is that absolutely same code worked fine for other project, the only difference was that here form is not connected with model.
comment on: http://stackoverflow.com/a/47817815
score: 0

http://stackoverflow.com/comment/82527096
has text: (flask) [felixc@diamond flask]$ ipython Python 2.7.13 (default, Jun 22 2017, 13:33:06) IPython 5.5.0 -- An enhanced Interactive Python. In [1]: edit IPython will make a temporary file named: /tmp/ipython_edit_pUodOs/ipython_edit_WWATn8.py Editing... done. Executing edited code... Out[1]: "import logging\nlogging.basicConfig(level=logging.DEBUG, format = '%(asctime)s [%(process)d %(name)s] %(levelname)s %(message)s')\n" In [2]: logging.debug('test') **2017-12-12 14:51:06,042 [14863 root] DEBUG test**
comment on: http://stackoverflow.com/q/47782789
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82359725
score: 0
type: QuestionComment
has text: look into groupby
type: Comment
comment on: http://stackoverflow.com/q/47699891

http://stackoverflow.com/comment/82650664
comment on: http://stackoverflow.com/a/47843304
has text: Can't comment yet, Bill :/
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/47762803
tagged with: sql-server
type: Question
tagged with: pypyodbc
has comment: http://stackoverflow.com/comment/82487213
has comment: http://stackoverflow.com/comment/82522148
has body: I am trying to execute a simple INSERT query to MSSQL Server using the pypyodbc library in python. If I try to execute SELECT Country, City, Street, House, Zipcode, Date FROM postal_test_db.dbo.addresses from the Microsoft SQL Management Studio it executes correctly as well as if I execute it from my python code: import pypyodbc connection_string ='Driver={SQL Server};Server=PC\TEW_SQLEXPRESS;Uid=py_test_user;Pwd=1q2w3e4r5t!A;' connection = pypyodbc.connect(connection_string) SQL = "SELECT Country, City, Street, House, Zipcode, Date FROM postal_test_db.dbo.addresses" cur = connection.cursor() result = cur.execute(SQL) print(result.fetchone()) cur.close() connection.close() But if I try to execute next code from the Microsoft SQL Management Studio: INSERT INTO postal_test_db.dbo.addresses (Country, City, Street, House, Zipcode) `VALUES ('Россия', 'Ульяновск', 'Варейкиса', '25', '432035')` then it still works well from the management studio but the python code which is supposed to do the same fails to execute import pypyodbc connection_string ='Driver={SQL Server};Server=PC\TEW_SQLEXPRESS;Uid=py_test_user;Pwd=1q2w3e4r5t!A;' connection = pypyodbc.connect(connection_string) SQL = "INSERT INTO postal_test_db.dbo.addresses (Country, City, Street, House, Zipcode) VALUES ('Россия', 'Ульяновск', 'Варейкиса', '25', '432035')" cur = connection.cursor() result = cur.execute(SQL) print(result.fetchone()) cur.close() connection.close() throwing the next error: pypyodbc.ProgrammingError: ('24000', '[24000] [Microsoft][ODBC SQL Server Driver ]Invalid cursor state') the visual representation of the CMD window with the corresponding error message What am I doing wrong? I a logging to MSSQL as the same user both in Management studio and in python listing and the user has all the necessary permissions (if he didn't had - he would not be able to execute the same code from the Management studio - it is logical for me).
favorite count: 0
has title: INSERT query is not executing from the python listing but executes pretty fine from MSSQL Management studio
downvote count: 0
upvote count: 1
tagged with: python
type: UnansweredQuestion
score: 1
answer count: 1
has answer: http://stackoverflow.com/a/47762995

http://stackoverflow.com/a/50436702
type: Answer
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/87932655
has comment: http://stackoverflow.com/comment/87888630
has body: I had the same issue, this is what I used: import numpy as np matrix = np.random.random((15,15)) for x in range(15): for y in range(15): matrix[x][y] = int(matrix[x][y]*10) I needed integers between 0 and 10, but you get the idea...
has comment: http://stackoverflow.com/comment/92824138
answers question: http://stackoverflow.com/q/47834140

http://stackoverflow.com/a/47786015
has body: def getNumberInRange(x,y): while True: a=int(input("Enter Number")) if not x &lt; a &lt; y: print("Invalid") else: return a Try this. This function will prompt the user to enter an integer. If the number is lower than low or higher than high, it will output an error message to the user and then prompt again. Hope this helps :)
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/82533165
has comment: http://stackoverflow.com/comment/82534695
answers question: http://stackoverflow.com/q/47785858

http://stackoverflow.com/comment/82480524
type: AnswerComment
comment on: http://stackoverflow.com/a/47745261
has text: @uzdisral - I don't see why not, provided you extract the proper field from that bitcoin value tracking site.
type: Comment
score: 0

http://stackoverflow.com/comment/82519303
type: QuestionComment
has text: I doubt there is a clean solution, `numpy`/`pandas` isn't designed around having list-objects a values
comment on: http://stackoverflow.com/q/47778895
score: 0
type: Comment

http://stackoverflow.com/comment/82575235
score: 0
has text: `QuizApp` isn't even a method. It's a _class_. Also it's not safe to run graphical apps in threads.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47806824

http://stackoverflow.com/comment/82583962
score: 0
comment on: http://stackoverflow.com/q/47811129
type: Comment
has text: if there are some problems on network then it can loose connection. If you would know file size before donwloading then you would know if you have to repeat downloading. You should have file size in header `content-size`
type: QuestionComment

http://stackoverflow.com/a/47935773
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47790517
has body: Try this: class EmployeeChangeForm(UserChangeForm): class Meta: model = Employee fields = '__all__' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if self.instance.pk: self.fields['manager'].queryset = Employee.objects.exclude( pk=self.instance.pk, ) Don't forget to use the form in your ModelAdmin by adding form = EmployeeChangeForm.
answers question: http://stackoverflow.com/q/47790517
type: Answer
score: 1

http://stackoverflow.com/comment/99348852
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/56373327
score: 1
has text: While this may help OP, it's better to add more details, explanation, examples, etc. Please [provide answers that don't require clarification from the asker.](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead)

http://stackoverflow.com/comment/82529613
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47784099
type: AnswerComment
has text: Sorry but i try and throw me an error, TypeError: '<' not supported between instances of 'numpy.ndarray' and 'tuple'

http://stackoverflow.com/q/47757464
tagged with: python
tagged with: mapreduce
has body: I'm trying to write a mapper/reducer set of code for hadoop to count words in tweets, but I'm running into a bit of a problem. The file I input is a JSON file of collected tweet information. I start by setting my default encoding the utf-8, but when running my code I receive the following error: Traceback (most recent call last): File "./mapperworks2.py", line 211, in my_json_dict = json.loads(line) File "/usr/lib/python2.6/json/init.py", line 307, in loads return _default_decoder.decode(s) File "/usr/lib/python2.6/json/decoder.py", line 319, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/usr/lib/python2.6/json/decoder.py", line 338, in raw_decode raise ValueError("No JSON object could be decoded") ValueError: No JSON object could be decoded Where the code for the program is #!/usr/bin/python import sys import json import string reload(sys) sys.setdefaultencoding('utf8') stop_words = ['a', 'about', 'above', 'after', 'again', 'against', 'all', 'am', 'an', 'and', 'any', 'are', "aren't", 'as', 'at', 'be', 'because', 'been', 'before', 'being', 'below', 'between', 'both', 'but', 'by', "can't", 'cannot', 'could', "couldn't", 'did', "didn't", 'do', 'does', "doesn't", 'yourselves'] numbers = ["0","1","2","3","4","5","6","7","8","9"] def clean_word(word): for c in string.punctuation: word = word.replace(c,"") for c in numbers: word = word.replace(c,"") return word def dont_stop(word): if word in stop_words or word == "": return False else: return True # input comes from STDIN (standard input) for line in sys.stdin: ############ ############ ############ ############ my_json_dict = json.loads(line) line = my_json_dict['text'].lower() ############ ############ ############ ############ # remove leading and trailing whitespace line = line.strip() # split the line into words words = line.split() # increase counters for word in words: ################## ################## word = clean_word(word) ################## ################## # write the results to STDO…
tagged with: ascii
tagged with: hadoop
has title: ValueError("No JSON object could be decoded") using Python 2.6 and utf-8
score: 2
upvote count: 2
type: UnansweredQuestion
answer count: 1
has answer: http://stackoverflow.com/a/47762664
downvote count: 0
linked to: http://stackoverflow.com/q/492483
favorite count: 0
type: Question
tagged with: http://stackoverflow.com/tag/json

http://stackoverflow.com/comment/82446612
type: QuestionComment
comment on: http://stackoverflow.com/q/47743100
has text: Have you tried setting the environment variable explicitly before starting the server?
score: 0
type: Comment

http://stackoverflow.com/comment/82669883
score: 0
type: Comment
type: QuestionComment
has text: It was my edit mistake. Updated code.
comment on: http://stackoverflow.com/q/47851054

http://stackoverflow.com/q/47854028
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47854119
has answer: http://stackoverflow.com/a/47854119
upvote count: 0
score: -3
answer count: 1
tagged with: python
has title: split list of tuples into a list of strings in python/django
has comment: http://stackoverflow.com/comment/82672238
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82672096
has body: My original list of tuples was list1 and I wanted to split the tuple into a list of strings: list = [Apple, Orange, Grapes] list1= [(u"[u'Apple', u'Orange', u'Grapes']",)] I converted it into list2 list2 = ("[u'Apple', u'Orange', u'Grapes']",) using string_tuple_list = [tuple(map(str, eachTuple)) for eachTuple in list1] but I want to convert this into a list like this: list = [Apple, Orange, Grapes] How can I do this?
downvote count: 3

http://stackoverflow.com/q/47760017
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82523575
tagged with: tkinter
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82481620
downvote count: 0
has answer: http://stackoverflow.com/a/47768796
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/82481324
has body: Working with Tkinter, and I'm having some trouble getting the OptionMenu to work properly. I'm creating a new window inside a function, with an OptionMenu and a label. Simple enough. But, it seems that I can't select an option from the OptionMenu. If I put it outside the function, it works fine. But, I need to be able to create the window on a function call. Here's the function: def ask_a_question(): question = Tk() question.geometry('300x100') qs = ['test0', 'test1', 'test2'] q = StringVar() q.set(None) Label(question, text = "placeholder").grid(row = 0, column = 0, padx = 10, pady = 10) questions = OptionMenu(question, q, *qs) questions.grid(row = 1, column = 0, padx = 10, pady = 10) question.mainloop() The code above executes as a command on a button. In the window that it creates, I can see all the widgets, but selecting any of the options in the OptionMenu does not update it. I had a similar problem with button images when creating a window in the main code and creating a button in a function. Does tkinter not play well with functions? Or is there a trick to get it to work properly?
answer count: 1
has title: tkinter optionmenu not working
score: 1
has comment: http://stackoverflow.com/comment/82482330

http://stackoverflow.com/comment/82479018
comment on: http://stackoverflow.com/a/47745261
score: 0
type: Comment
type: AnswerComment
has text: So I was also wondering if thats something I could use for this? [Here] (https://stackoverflow.com/questions/47724574/beautifulsoup-scraping-bitcoin-price-issue) is my Bitcoin scraping, Could I use the same loop to print for example,: Price is too high, or Price is too low, depending on how the value changes?

http://stackoverflow.com/q/47786968
has answer: http://stackoverflow.com/a/47788293
linked to: http://stackoverflow.com/q/40860457
type: Question
has comment: http://stackoverflow.com/comment/82535054
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/82535331
has comment: http://stackoverflow.com/comment/82558024
answer count: 3
tagged with: python
score: 1
possible better answer: http://stackoverflow.com/a/47787427
favorite count: 0
has answer: http://stackoverflow.com/a/47787427
has comment: http://stackoverflow.com/comment/82535135
has title: How to subset a pandas dataframe based on iterating through all row values of another df?
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47787581
has comment: http://stackoverflow.com/comment/82535463
has body: I have two pandas dataframes: key_df and value_df key_dict = {"coordinates": ["AB1", "AC1", "AD1", "EF1", ... ], "start": [762, 1274, 1587, 1991, ...], "end": [2481, 1789, 1689, 2211, ...] } key_df = pd.DataFrame(key_dict) coordinates start end 0 AB1 762 2481 1 AC1 1274 1789 2 AD1 1587 1689 3 EF1 1991 2211 ... ... ... ... value_dict = {"coordinates": ["AD1", "AB1"], "meta_data": [101, 010]} value_df = pd.DataFrame(value_dict) coordinates meta_data 0 AD1 101 1 AB1 110 ... ... ... The coordinates column for key_df only contains unique values---there are no repeats. Similarly for value_df. I would like to iterate through value_df on coordinates, checking each value of coordinates in value_df for the value of coordinates in key_df. I would then like to return start and end for these values. My thought to subset the dataframe and grab the start and end values would be to create a function: def parse(x, df): ### 'x' is each row of value_df$coordinates df = df[df.coordinates == x] return (df.start, df.end) ## return as a tuple and I would call the function be parse(x, df=key_df) However, I'm not sure how to iterate over value_df. .iterrows() is quick but it doesn't preserve the row dtype, which may be a problem.
accepted answer: http://stackoverflow.com/a/47788293
downvote count: 0
has comment: http://stackoverflow.com/comment/82535082
upvote count: 1

http://stackoverflow.com/q/47841565
favorite count: 0
has answer: http://stackoverflow.com/a/58981854
type: Question
has title: Screenshot Map using Selenium and Google Maps API
tagged with: google-api
type: UnansweredQuestion
tagged with: python
has body: I am trying to use Selenium, PhantomJS, and GoogleMaps API to automatically screenshot / save down maps. The url i request is a local html file with javascript to generate the map. When I open the local file, I am able to view the map, however, when I run the following code and attempt to screenshot the map, only a blank picture is saved. I have explored the Google Static Maps API, but my maps have hundreds of markers, exceeding the URL length limit. I am trying to screenshot hundreds of maps that will change over time and need to be a set size. I believe this is the best way to go about it. As reference, here is some test html that brings up a Google API map (note: will require API key): https://developers.google.com/maps/documentation/javascript/earthquakes Here is my code: from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC def maps(): driver = webdriver.PhantomJS() driver.set_window_size(640,640) driver.implicitly_wait(5) driver.get("file:///U:/ABC%20Comps/test.html") element = driver.find_element_by_id('map') driver.save_screenshot('test.png') driver.quit() ` Can someone point me in the right direction?
has comment: http://stackoverflow.com/comment/82649869
tagged with: phantomjs
linked to: http://stackoverflow.com/q/18067021
tagged with: screenshot
score: 1
answer count: 1
downvote count: 0
tagged with: selenium
upvote count: 1

http://stackoverflow.com/q/47803270
favorite count: 0
type: Question
tagged with: tkinter
type: UnansweredQuestion
has body: The Tkinter Variable subclasses such as StringVar or IntVar allow for a tk Frame widget as the first argument. What is this argument used for?
tagged with: python
score: 3
upvote count: 3
downvote count: 0
answer count: 1
has title: What is the Tkinter Variable class first argument used for?
has answer: http://stackoverflow.com/a/47803302

http://stackoverflow.com/a/47782683
has body: The third example fails because func exists but ex.func does not. ex.func looks up "func" in the attributes of Example class and fails. You could call func in procedural style, passing ex as first argument: func(ex) which is equivalent to: ex.simple_av() (the 2 first examples use a call to a defined method, so it works)
accepted answer of: http://stackoverflow.com/q/47782596
type: Answer
answers question: http://stackoverflow.com/q/47782596
upvote count: 2
score: 2
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/a/47783285
upvote count: 2
accepted answer of: http://stackoverflow.com/q/47774552
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82535271
answers question: http://stackoverflow.com/q/47774552
has comment: http://stackoverflow.com/comment/82541691
has body: Yes, your interpretation is right. From the Keras documentation: If the model has multiple outputs, you can use a different loss on each output by passing a dictionary or a list of losses. The loss value that will be minimized by the model will then be the sum of all individual losses.
has comment: http://stackoverflow.com/comment/82540720
has comment: http://stackoverflow.com/comment/82539877
has comment: http://stackoverflow.com/comment/82541225
type: Answer
has comment: http://stackoverflow.com/comment/82541014
score: 2

http://stackoverflow.com/comment/82634477
type: QuestionComment
comment on: http://stackoverflow.com/q/47835138
score: 0
has text: I believe my edits help with the content of your post. I've highlighted the functions to be in code syntax. It makes it easier to read. Also `cv::Scharr` is part of the C++ definition but you're using Python. That's why I've converted it to `cv2.Scharr()` instead. Please consider keeping my edits.
type: Comment

http://stackoverflow.com/q/47725725
answer count: 2
has body: I have the dataframe below in pandas currently | x | ID | Num |-----|------|----- | 1 | 100 | 35 | 2 | 100 | 50 | 3 | 150 | 34 | 4 | 150 | 25 | 5 | 150 | 46 | 6 | 200 | 13 | 7 | 200 | 75 | 8 | 100 | 37 | 9 | 150 | 61 I'm trying to create a multi-line graph where the 'x' column is the index and on the x-axis, while the ID and Num columns form the lines. I tried to do a single line version with just x and ID with the following code, but it returns nothing, and I'm not sure how to upgrade to a two line graph. s1 = df_iter.resample('LowestAcceptedValue') s2 = df_iter.resample('SwapsValue') df = pd.concat([s1, s2], axis=1) df.plot()
tagged with: pandas
has answer: http://stackoverflow.com/a/47728156
upvote count: 0
has answer: http://stackoverflow.com/a/47725775
downvote count: 1
favorite count: 0
type: Question
type: UnansweredQuestion
has title: Plot line from pandas dataframe in Python
tagged with: matplotlib
tagged with: python
score: -1

http://stackoverflow.com/comment/82570245
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/47804339
has text: this is not what I was asking for
type: Comment

http://stackoverflow.com/a/47851573
has body: Use this regular expression instead: RHS \d+.?\d?x\d+.?\d?x\d+.?\d?(?!x) Or a compact version of it: RHS (\d+.?\d?){3}(?!x)
score: 0
type: Answer
answers question: http://stackoverflow.com/q/47850705

http://stackoverflow.com/q/47772501
type: Question
has title: nGram frequency using Pandas Dataframe
tagged with: pandas
has body: So I have some items in MongoDB with a field named title (and many others) but we'll focus on this one. I want to retrieve the most used words overall time, for example, the expected result would be { "christmas 2017": 30, "foo bar": 4, "apple iphone": 10, ... } So I can then render a bar plot and see things, with my code I can 'do this' but it also gives me ngrams with just 1 frequency, which I don't want, because they're not used more than once, so useless info. The point of this, is to get the most common words within titles, I think a good ngram range would be 2-3 words, because 1 is not enough and more than 3 is too specific. This is my code, which is working but I need a way to get ride of the non repeated things (and maybe also a better way to achieve this) vector = CountVectorizer(ngram_range=(2,2), analyzer='word') n_gram = vectorizer.fit_transform(df[text_field]) frequencies = n_gram.toarray().sum(axis=0) results = pd.DataFrame(frequencies, index=vectorizer.get_feature_names(), columns=['frequency']) results.plot.bar() Needless to say that the drawn bar, has a huge amount of irrelevant info (things with just 1 frequency) And this code, I'll be using it to parse long text fields, such as description, so I need to get a clean list of the most used things. As a bonus, if I could just tell the script the minimum repeating frequency, that'll be awesome, so it can fit any need in the future.
tagged with: python
score: 0
tagged with: data-mining
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47773096
answer count: 1

http://stackoverflow.com/a/50349148
score: 0
answers question: http://stackoverflow.com/q/47821756
type: Answer
has body: From: https://groups.google.com/forum/#!topic/pyglet-users/ah2I54BSrZg You can install FFmpeg for your platform by following the instructions found in the FFmpeg download page. For Mac OS and Linux, the library is usually installed system-wide. For Windows users, it’s not recommended to install the library in one of the windows sub-folders. Instead we recommend to use the pyglet.options search_local_libs: import pyglet pyglet.options['search_local_libs'] = True This will allow pyglet to find the FFmpeg binaries in the lib folder located in your running script folder.

http://stackoverflow.com/q/47826097
tagged with: python
has title: Django and Flask on same nginx server
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47826562
upvote count: 3
downvote count: 0
answer count: 1
tagged with: flask
favorite count: 0
type: Question
score: 3
has answer: http://stackoverflow.com/a/47826562
tagged with: nginx
has body: I currently have a Djago app running on my main site when I visit mysite.com. However, I'd like mysite.com/flaskapp to run a separate Flask application. I'm able to set up two nginx site-enabled config files and run each app on a different port but, for various reasons, I'd like to run them all on the same port (if possible). When I configure my flaskapp/ location in my nginx server file I get a 404 error. Here's my supervisor config file: [program:MYSITE] command=/var/www/html/MYSITE/prodenv/bin/gunicorn --workers 3 --bind unix:/var/www/html/MYSITE/public_html/MYSITE.sock MYSITE.wsgi directory=/var/www/html/MYSITE/public_html autostart=true autorestart=true stderr_logfile=/var/log/MYSITE.err.log stdout_logfile=/var/log/MYSITE.out.log [program:FLASKAPP] directory=/var/www/html/MYSITE/public_html/FLASKAPP/api command=/var/www/html/MYSITE/public_html/FLASKAPP/venv/bin/gunicorn --workers 3 --bind unix:/var/www/html/MYSITE/public_html/FLASKAPP/api/FLASKAPP.sock FLASKAPP:app autostart=true autorestart=true stderr_logfile=/var/log/FLASKAPP.err.log stdout_logfile=/var/log/FLASKAPP.out.log And my nginx site-enabled file: server { listen 80; listen [::]:80; server_name MYSITE; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /var/www/html/MYSITE/public_html; expires 30d; } location / { include proxy_params; proxy_pass http://unix:/var/www/html/MYSITE/public_html/MYSITE.sock; } location /FLASKAPP/ { include proxy_params; proxy_pass http://unix:/var/www/html/MYSITE/public_html/FLASKAPP/api/FLASKAPP.sock; } } I wrote a function to check the request url @app.errorhandler(404) def page_not_found(error): return 'This route does not exist {}'.format(request.url), 404 Which returns: This route does not exist http://MYSITE/FLASKAPP The Flask app is clearly working, but the routing is screwed up. How can I fix this?
has comment: http://stackoverflow.com/comment/82615021

http://stackoverflow.com/comment/82391560
type: Comment
has text: Can you show your attempt that got closest to what you're looking for?
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/47715666

http://stackoverflow.com/q/47819405
tagged with: python-3.x
type: Question
tagged with: python
has title: Server in gevent and other greenlets in the same app
accepted answer: http://stackoverflow.com/a/47819769
has answer: http://stackoverflow.com/a/47819769
tagged with: greenlets
type: AnsweredQuestion
tagged with: tcp
downvote count: 0
score: 1
upvote count: 1
tagged with: gevent
has body: I'm searching how to run server in gevent and other greenlets in one program. So I want to have server (multiple connections) and one or two other greenlets. Is this possible? If yes, then how? Best regards, Matt.
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/104373730
has text: I noticed that in windows, I can do `facecolor=''`, but on Linux I have to enter as by the answer `facecolor='none'`
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47847586

http://stackoverflow.com/comment/82485173
score: 1
type: Comment
has text: https://stackoverflow.com/questions/47703634/pandas-group-by-and-assign-a-group-id-then-ungroup/47703735#47703735, multiple ways to achieve this
type: QuestionComment
comment on: http://stackoverflow.com/q/47761762

http://stackoverflow.com/comment/82590204
score: 0
type: Comment
type: QuestionComment
has text: This may also be useful: https://stackoverflow.com/questions/19412462/getting-distance-between-two-points-based-on-latitude-longitude
comment on: http://stackoverflow.com/q/47812006

http://stackoverflow.com/a/63220890
upvote count: 4
has body: I had the same error with Django 3.0.8 (july 2020) when trying to run the server, and in my case no need for the DJANGO_SETTINGS_MODULE environment variable. The solution is to use another form to run the server: cd &lt;directory containing manage.py&gt; python3 manage.py runserver It works to run Django shell too : python3 manage.py shell
downvote count: 0
answers question: http://stackoverflow.com/q/47700347
type: Answer
score: 4

http://stackoverflow.com/comment/82619170
has text: "is not working" is not a useful description of your problem. Please explain what result you get (including the exact error message and full traceback if you have an exception).
comment on: http://stackoverflow.com/q/47828090
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82358689
comment on: http://stackoverflow.com/q/47698771
type: Comment
has text: "I can think of no logical explanation for this other than that the trigonometric functions must be returning complex numbers." That's a good theory, but as I said earlier the `math` module doesn't handle complex numbers, although `cmath` does. But you still haven't told us where you're importing your trig functions from.
score: 0
type: QuestionComment

http://stackoverflow.com/comment/82420086
comment on: http://stackoverflow.com/a/47729757
score: 0
type: AnswerComment
type: Comment
has text: Hi Ahmed, I executed your script, but the OUTPUT.txt file is empty

http://stackoverflow.com/comment/82628861
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47831916
type: QuestionComment
has text: Forget that, you do have two line breaks. But what makes you think your condition `if 'search' in form` would ever evaluate to true? The only parameter you send in your Ajax request is `q`.

http://stackoverflow.com/a/47744895
has comment: http://stackoverflow.com/comment/82449948
downvote count: 1
answers question: http://stackoverflow.com/q/47744506
has comment: http://stackoverflow.com/comment/82449981
score: -1
accepted answer of: http://stackoverflow.com/q/47744506
has body: Solution: Python's install path was overridden by Visual Studio to it's "shared" location (more like pain-in-the-ass location) located at: C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\ Changing both system variables(Path and PYTHONPATH ) to this location resolved this issue. Thank you to all who commented/responded. EDIT: Apparently it is bad practice to manually set PYTHONPATH, as it is automatically set by Python.
upvote count: 0
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/comment/82377452
comment on: http://stackoverflow.com/a/47708521
score: 0
type: AnswerComment
has text: Without more detail no one can help.Can't create instance or create instance with blank imagen?
type: Comment

http://stackoverflow.com/comment/82411418
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47725332
has text: `teams = row.split(None, 3)[4] IndexError: list index out of range`

http://stackoverflow.com/q/47816090
tagged with: python-3.x
tagged with: field
has title: Django - Null value in column "imageLink" violates not-null constraint
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/47816311
accepted answer: http://stackoverflow.com/a/47816311
type: AnsweredQuestion
score: 0
answer count: 1
tagged with: forms
has body: I've been trying to setup an upload possibility for a form (with the intent to upload pictures) to a database, which is linked to other data in the list but every time I try to run it, it won't ignore the null that is suppose to be the picture. I've been reading up and trying to get this fixed for a solid day and a half but there isn't a lot of documentation to be found on this subject. Am I missing a place where the file needs to be uploaded to and/or is there a way to ignore the null if there hasn't been a photo added to the list? Error message: IntegrityError at /createproduct/ null value in column "imageLink" violates not-null constraint DETAIL: Failing row contains (81, Comedy, Comic, DC, 5, Engels, 5, Henk, haHAA, null, 808, 2000-04-02). Form snippet 1: class PRegistrationForm(ModelForm): ProductsEntry = Products(prodNum=products.id, prodName=products.prodName, prodPrice=products.prodPrice, prodStock=products.prodStock) ProductsEntry.save() ProdData = ProductDetails(prodNum=products(prodNum=products.id), genre=products.genre, type=products.type, publisher=products.publisher, totalPages=products.totalPages, language=products.language, rating=products.rating, author=products.author, desc=products.desc, imageLink=products.imageLink, pubDatum=products.pubDatum) ProdData.save() if commit: products.save() return products Form snippet 2: class ProductDetails(forms.Form): products_prodName = forms.CharField(required=True, max_length=200) products_prodPrice = forms.DecimalField(required=True, max_digits=5, decimal_places=2) products_prodStock = forms.IntegerField(required=True, max_value=5000, min_value=1) products_genre = forms.CharField(required=False, max_length=15) products_type = forms.CharField(required=False, max_length=15) products_publisher = forms.CharField(required=True, max_length=30) products_totalPages = forms.IntegerField(required=True, max_value=2000, min_value=1) products_language = forms.CharField(required=False, max_length=25) products_rating = forms…
type: Question

http://stackoverflow.com/q/47812597
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47812749
answer count: 2
accepted answer: http://stackoverflow.com/a/47812685
has comment: http://stackoverflow.com/comment/82586639
upvote count: 0
has comment: http://stackoverflow.com/comment/82586495
has answer: http://stackoverflow.com/a/47812685
tagged with: python
possible better answer: http://stackoverflow.com/a/47812749
linked to: http://stackoverflow.com/q/2407398
has body: I am trying to get the value of 2 python lists. list1 = ['a','b','c'] list1 = ['1','2','3'] the output ['a','1'] ['b','2'] ['c','3'] I am still beginner with python Any help will be apperciate
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82586456
has title: How to get the equivalent index of each case in 2 python lists
duplicate of: http://stackoverflow.com/q/2407398
has comment: http://stackoverflow.com/comment/82586888
downvote count: 1
score: -1

http://stackoverflow.com/a/47851982
type: Answer
accepted answer of: http://stackoverflow.com/q/47851966
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47851966
has body: Python doesn't have a (single) standard placeholder value for parameterized queries. SQLite uses ?, but MySQL and Postgresql drivers use %s (for all data types, not just strings): cur.execute("INSERT INTO description VALUES(%s,%s,%s,%s,%s,%s)", (a + b))

http://stackoverflow.com/q/47829603
has body: All the answers I keep finding are for python 2.X, but I use python 3.X. They also keep talking about not working with .exe installed programs. I need a way to be able to get a list of installed programs, both .exe and .msi (and any other method of installation as well), along side their respective installation paths. At the moment, this is what I'm using to find things: import os, string from os.path import join, getsize availableDrives = ['%s:' % d for d in string.ascii_uppercase if os.path.exists('%s:' % d)] for i in range(len(availableDrives)): for root, dirs, files in os.walk(availableDrives[i]): print(root) if "ds.py" in files: print('yes') else: print("No") For those that don't want to read it, it searches through all folder on every drive. I'm in the middle of making it slightly more fficient, but it is still time consuming and I was wondering if after 6 years (yes, that was when the questions were asked), theres finally a way to get this information? If so, how? And if possible, could you give me the code for it but explain it as I need it as a small part of a school project. Cheers all, Luke EDIT: I've seen some other resources using cmd to create a text file containing the necessary information. I wouldn't mid using this method if someone could tell me how to do it
score: 0
has answer: http://stackoverflow.com/a/47830588
tagged with: windows
answer count: 1
tagged with: file
has title: How can i get a list (file, list, whatever) of all installed programs using python?
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82622161
tagged with: python

http://stackoverflow.com/a/47750242
accepted answer of: http://stackoverflow.com/q/47749685
has body: When you add Executable setting, it must be an executable, this means that is has to be either .exe or .dll. If you look at the picture in the instructions, you will see an executable there (python.exe). If you don't provide path to an executable, error that specified executable must be .dll or .exe will pop up. Make sure you are referring to an executable there and it should be fine then.
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/47749685
has comment: http://stackoverflow.com/comment/82462818
has comment: http://stackoverflow.com/comment/82461588
has comment: http://stackoverflow.com/comment/119770981
has comment: http://stackoverflow.com/comment/82461629
score: 2
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/47710136
answers question: http://stackoverflow.com/q/47709192
downvote count: 0
type: Answer
has body: Does this ok? convert to gray threshold findContours boundingRect
has comment: http://stackoverflow.com/comment/82387956
has comment: http://stackoverflow.com/comment/82390365
accepted answer of: http://stackoverflow.com/q/47709192
has comment: http://stackoverflow.com/comment/82619609
score: 1
type: AcceptedAnswer
upvote count: 1

http://stackoverflow.com/q/47842352
downvote count: 4
has comment: http://stackoverflow.com/comment/82649212
score: 1
answer count: 1
tagged with: iterable-unpacking
has title: Iterable Unpacking Evaluation Order
duplicate of: http://stackoverflow.com/q/68152730
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/47841934
has comment: http://stackoverflow.com/comment/82649194
upvote count: 5
has comment: http://stackoverflow.com/comment/82648979
tagged with: variable-assignment
tagged with: python
has body: I recently answered a question where a user was having trouble because they were appending a multi-dimensional array to another array, and it was brought to my attention in my answer that it is possible to use iterable unpacking to populate an x and y value and assign to board[x][y] on the same line. I had expected this to throw an error as x and y had at the time not been defined, as, even in the iterable-unpacking tag it reads: elements of an iterable are simultaneously assigned to multiple values This can be seen as working in the following example: &gt;&gt;&gt; board = [[0, 0], [0, 0]] &gt;&gt;&gt; move = [0, 1, 2] &gt;&gt;&gt; x, y, board[x][y] = move &gt;&gt;&gt; board [[0, 2], [0, 0]] Which is the same as: &gt;&gt;&gt; board = [[0, 0], [0, 0]] &gt;&gt;&gt; move = [0, 1, 2] &gt;&gt;&gt; x = move[0] &gt;&gt;&gt; y = move[1] &gt;&gt;&gt; board[x][y] = move[2] &gt;&gt;&gt; board [[0, 2], [0, 0]] And yet when calculating the Fibonacci sequence using: a, b = b, a + b It doesn't evaluate as: a = b b = a + b And when swapping values with: a, b = b, a It doesn't evaluate as: a = b b = a So why does this work in the first example?
accepted answer: http://stackoverflow.com/a/47842433
has answer: http://stackoverflow.com/a/47842433
type: AnsweredQuestion

http://stackoverflow.com/comment/82660182
type: QuestionComment
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47847891
has text: html.parser is what I've been using

http://stackoverflow.com/a/47893387
answers question: http://stackoverflow.com/q/47802521
score: 0
type: AcceptedAnswer
has body: It seems praw does not want to crawl subreddits like questioned. praw provides several "get subreddit" methods to receive specific ones or get "popular" or "gold"-categorized ones. I'm now working with scrapy to receive the needed data from specific subreddits.
accepted answer of: http://stackoverflow.com/q/47802521
type: Answer

http://stackoverflow.com/a/47792449
accepted answer of: http://stackoverflow.com/q/47792373
has comment: http://stackoverflow.com/comment/82556636
has comment: http://stackoverflow.com/comment/82550557
answers question: http://stackoverflow.com/q/47792373
type: Answer
has comment: http://stackoverflow.com/comment/82556490
has body: You have to load the tag library before you use it in the template: {% load template_filters %} Or you can load the specific filter: {% load get_item from template_filters %} See the docs on custom template tags and the {% load %} tag for more info.
score: 2
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/139705196
type: AcceptedAnswer

http://stackoverflow.com/q/47699006
tagged with: selenium
has title: Dynamic ID - selenium, python. How to match start with and contains?
favorite count: 0
type: Question
duplicate of: http://stackoverflow.com/q/26217002
type: UnansweredQuestion
downvote count: 2
answer count: 1
upvote count: 1
tagged with: python
score: -1
linked to: http://stackoverflow.com/q/26217002
has body: I've got id="phone_123456_option". There's no fully static part in code to find the element in other way. I can't also use only start-with, for sure I need also refer to option. So I guess I need to match start-with and contains (or ends-with?) in one line of code using xpath. Does anybody know how to do it properly? In python and selenium now I can use: driver.find_element_by_id("phone_123456_option").click() I need to create a python, not xml, xpath: //*[@id="phone_123456_option"] - How to properly remove dynamic number and refer to phone and option?
has answer: http://stackoverflow.com/a/47699650

http://stackoverflow.com/q/47698836
tagged with: admin
has answer: http://stackoverflow.com/a/47699924
accepted answer: http://stackoverflow.com/a/47699924
type: Question
upvote count: 3
downvote count: 0
answer count: 1
tagged with: django
tagged with: python
tagged with: m2m
favorite count: 0
type: AnsweredQuestion
score: 3
has body: when deleting users with schedule_files I got this: IntegrityError at /admin/auth/user/166/delete/ (1451, 'Cannot delete or update a parent row: a foreign key constraint fails (vacation.vacations_schedulefile, CONSTRAINT vacations_schedulefile_user_id_e85fa52f_fk_auth_user_id FOREIGN KEY (user_id) REFERENCES auth_user (id))') My models are: class ScheduleFile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) added = models.DateTimeField(default=django.utils.timezone.now) def __str__(self): return '[User ID: {}] {}'.format(str(self.user.id), self.user.username) And class VacationEvent(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) schedule_type = models.CharField(choices=SCHEDULE_TYPES, default=STRICT_TIME, max_length=3) exclude_fba_from_chatzos = models.BooleanField(default=False) schedule_file = models.ForeignKey(ScheduleFile, on_delete=models.CASCADE, null=True) status = models.CharField(verbose_name="status event", choices=EVENT_STATUSES, max_length=3, default=CREATED) And User(AbstractUser) I decided to create pre_delete signal and delete relative objects of schedule model: @receiver(pre_delete, dispatch_uid='User') def user_del(sender, instance, **kwargs): i = instance events = VacationEvent.objects.filter(user_id=166) schedule = prefetch_related_objects(events, 'schedule_file__user') schedule.delete() # instance.user.schedulefile_set.clear() # qs = VacationEvent.objects.filter(user_id=166).prefetch_related_('schedule_file') # qs.delete() # b = ScheduleFile.objects.filter(user_id=166) # e = VacationEvent.objects.filter(user_id=166) # e.schedule_file.remove(b) But it returns 'NoneType' object has no attribute 'delete'. How can I do it right? Thanks for any help.
has title: IntegrityError: (1451, 'Cannot delete or update a parent row: a foreign key constraint fails (..))

http://stackoverflow.com/a/60606618
has body: I was having the same issue with RstDocuments in a ScrollView. The problem arises because RstDocuments have their own scrolling and 'intercept' the scroll command because it thinks you're trying to scroll inside the RstDocument. If you're fine with non-scrolling RstDocuments, you can set do_scroll_y: False for RstDocument, and scrolling will then work fine in the ScrollView regardless of mousing over an RstDocument.
type: Answer
answers question: http://stackoverflow.com/q/47726858
score: 0

http://stackoverflow.com/q/47792217
tagged with: parsing
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82552586
has body: Anybody have this problem before? Any suggestion about the reason? The script creates the files containing the genome sequences but it appears at the end of the process. Line in my script File "scripts/list_ncbi_download_genome_vs_02.py", line 97, in &lt;module&gt; SeqIO.write(SeqIO.parse(genbank_file, "genbank"), genome_file, "fasta") Warnings that appear: File "/usr/lib/python2.7/dist-packages/Bio/SeqIO/__init__.py", line 481, in write count = writer_class(fp).write_file(sequences) File "/usr/lib/python2.7/dist-packages/Bio/SeqIO/Interfaces.py", line 209, in write_file count = self.write_records(records) File "/usr/lib/python2.7/dist-packages/Bio/SeqIO/Interfaces.py", line 193, in write_records for record in records: File "/usr/lib/python2.7/dist-packages/Bio/SeqIO/__init__.py", line 600, in parse for r in i: File "/usr/lib/python2.7/dist-packages/Bio/GenBank/Scanner.py", line 478, in parse_records record = self.parse(handle, do_features) File "/usr/lib/python2.7/dist-packages/Bio/GenBank/Scanner.py", line 462, in parse if self.feed(handle, consumer, do_features): File "/usr/lib/python2.7/dist-packages/Bio/GenBank/Scanner.py", line 434, in feed self._feed_feature_table(consumer, self.parse_features(skip=False)) File "/usr/lib/python2.7/dist-packages/Bio/GenBank/Scanner.py", line 159, in parse_features raise ValueError("Premature end of line during features table") I can live with this but it is not so beautiful to finish a process and it appears after. The file is available for download at https://github.com/felipelira/files_to_test/blob/master/GCF_000302915.1_Pav631_1.0_genomic.gbff the block in my script that calls the command is: ## rename and move files to the output directory created in the command line: genome_dict = {} genome_list = [] for genbank_file in list_uncompressed: organism = genbank_file.split('/')[0] file_name = genbank_file.split('/')[-1] genome_file = organism +'_'+ file_name.split('_')[0] +'_'+ file_name.split('_')[1]+'.fna' genome_list.append…
score: 0
has comment: http://stackoverflow.com/comment/82549351
answer count: 1
has answer: http://stackoverflow.com/a/47809888
has title: SeqIO.parse python: Premature end of line during features table
type: Question
tagged with: bioinformatics
accepted answer: http://stackoverflow.com/a/47809888
has comment: http://stackoverflow.com/comment/82548851
tagged with: python

http://stackoverflow.com/a/47808919
has comment: http://stackoverflow.com/comment/82580359
answers question: http://stackoverflow.com/q/47808181
type: Answer
has body: First point: in your example, bar() is not a proper view - it returns a unicode string (result of rendering a template), not an HttpResponse, so you can not use it as a view. Second point: as I mentionned above, what bar() returns is just a plain unicode string. If you have a function foo() which renders another template and returns the result (another unicode string), you can of course concatenate those two strings - actually, the fact you used templates to build those two strings is totally irrelevant. Now wether concatenating those two strings will yield valid html (assuming you use the templates to generate html) is another question. Both templates are rendered separately and chances are both were designed to generate a full html document, so you will probably end up with the concatenation of two html documents, which does not result in a valid html document. So to answer your questions: Is this possible? Yes, obviously. Am I doing it the right way? Obviously not. Actually, the very first sentence of your question: I'm trying to display 2 views on the same page shows a lack of understanding of what Django views are. A Django view is a callable that takes a request (HttpRequest) as input and returns a response (HttpResponse) as output. So "displaying two view on a page" just doesn't make sense - actually even "displaying a view" don't make sense in itself, you don't "display" a view (the http client can eventually "display" the http response itself, but the http response is not the view). As to "what would be the right way to solve your problem", well the only sensible answer is "it depends" - first we don't have enough details (but "enough" might actually be "too much for a SO question"), and then there are probably more than one "correct" solution, each with it's pros and cons.
score: 0
has comment: http://stackoverflow.com/comment/82580133
has comment: http://stackoverflow.com/comment/82579892

http://stackoverflow.com/a/47779570
answers question: http://stackoverflow.com/q/47779344
score: 0
has comment: http://stackoverflow.com/comment/82520305
has body: The code you displayed is not really python. Matlab and python are totally different animals. Numpy and Matplotlib, which are python extensions used frequently in the scientific realm, share a lot of concepts with matlab, but the underlying syntax is distintly pythonic. I would start with https://learnpythonthehardway.org/python3/index.html for a quick and dirty introduction to Python (Its free as of the time of my writing: you can ignore the solicitations for a purchase, although if you did buy, i believe its money well spent). In addition, these official documentation pages should always be handy when coding in python Python Language Reference: https://docs.python.org/3/reference/index.html#reference-index Python Standard Library: https://docs.python.org/3/library/index.html#library-index
type: Answer

http://stackoverflow.com/comment/82376463
type: Comment
has text: What is the data type of the property?
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47707293

http://stackoverflow.com/q/47835929
type: AnsweredQuestion
upvote count: 2
tagged with: pyqt
answer count: 1
downvote count: 0
has body: I'm trying to make two scroll bars for a QGroupBox but I only succeed having one (the vertical one) I'm not sure what I need to do. here is a short example of my code: from PyQt5.QtGui import * from PyQt5.QtCore import * from PyQt5.QtWidgets import * import sys class SurfViewer(QMainWindow): def __init__(self, parent=None): super(SurfViewer, self).__init__() self.parent = parent self.centralTabs= QTabWidget() self.setCentralWidget(self.centralTabs) self.setFixedWidth(200) self.setFixedHeight(200) #tab Model selection self.tab_ModelSelect = QWidget() self.centralTabs.addTab(self.tab_ModelSelect,"Label") self.groupscrolllayouttest = QHBoxLayout() self.groupscrollbartest = QGroupBox() self.mainHBOX_param_scene = QVBoxLayout() for i in range(10): Label = QLabel('BlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBla') Label.setFixedWidth(200) self.mainHBOX_param_scene.addWidget(Label) # scroll = QScrollArea() scroll.setWidget(self.groupscrollbartest) scroll.setWidgetResizable(True) scroll.setFixedWidth(20) scroll.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded) scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded) self.groupscrollbartest.setLayout(self.mainHBOX_param_scene) self.groupscrolllayouttest.addWidget(self.groupscrollbartest) self.groupscrolllayouttest.addWidget(scroll) self.tab_ModelSelect.setLayout(self.groupscrolllayouttest) def main(): app = QApplication(sys.argv) ex = SurfViewer(app) ex.setWindowTitle('window') # ex.showMaximized() ex.show() sys.exit(app.exec_( )) if __name__ == '__main__': main() and here is the result: In my more complex code I used QTabWidget, that why I included it in this example. What I would like to do is having a horizontal scrollbar to the bottom which allows me to shift the text left and right. Obviously I want keep the other one to shift the text up and down. I also try to add a second scroll bar to the first one (groupscrolllayouttest) from PyQt5.QtGui import * from PyQt5.QtCore import * from PyQt5.QtWidgets import * import…
tagged with: pyqt5
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47836096
has title: How set two scroll bars (vertical and horizontal) to the same widget in PyQt environment?
has answer: http://stackoverflow.com/a/47836096
tagged with: python
tagged with: qscrollarea
score: 2

http://stackoverflow.com/comment/82433696
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47734446
has text: How are you compiling your C code? You haven't told us this vital piece of information. Also, how is Python being compiled? Are there any optimisations enabled in Python which aren't in your code?
score: 0

http://stackoverflow.com/comment/82516308
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47776568
has text: I try your code and no warning, so I guess problem is in lines of code above.
score: 1

http://stackoverflow.com/comment/82516055
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47777043
has text: @maniramreddy If keys O and P are missing, then what will the dictionary know to show?

http://stackoverflow.com/q/47708375
tagged with: python
has body: I'm using compute_gradients() and apply_gradients() functions of Tensorflow for back-prop. By printing the gradient values I do see that gradients are getting calculated, but I do not see any change in weights after call to apply_gradients() function. I also do not see that value of global_step variable changing. Am I doing something wrong? I'm running the below code in a session and I do see gradient values returned from compute_gradients() function getting printed. But when I pass the list of (gradient, weights variables) tuple to apply_gradients() function I do not see the weights value changing and global_step value does not get updated. global_step = tf.Variable(0, trainable=False, dtype=tf.int32) images = tf.placeholder(dtype=tf.float32, shape=[batch_size, None, None, 3]) out_locs = tf.placeholder(dtype=tf.float32, shape=[None, 2]) org_gt_coords = tf.placeholder(dtype=tf.float32, shape=[batch_size, 2]) res_aux = inference(images,out_locs,org_gt_coords) ret_dict = train(res_aux, global_step) init = tf.global_variables_initializer() with tf.Session() as sess: writer = tf.summary.FileWriter('./graphs', sess.graph) sess.run(init) for epoch in xrange(max_steps): start_time = time.time() anno_file_batch_rows = getImageMetaRecords() print('epoch: ', epoch) for batch in xrange(len(anno_file_batch_rows)/batch_size): distorted_images, meta = cdhd_input.distorted_inputs(stats_dict, batch_size, \ anno_file_batch_rows[batch * batch_size : (batch * batch_size) + batch_size]) out_dict = sess.run(ret_dict, feed_dict= {images: distorted_images, out_locs: meta['out_locs'], org_gt_coords: meta['org_gt_coords']}) def inference(images,out_locs,org_gt_coords): # conv1 with tf.variable_scope('conv1') as scope: kernel = _variable_with_weight_decay('weights', shape=[3, 3, 3, 32], stddev=1, #check if this is right wd=0.0) kernel = tf.multiply(kernel, 0.2722) #line 321-325 in warpTrainCNNCDHDCentroidChainGridPredSharedRevFastExp3 conv = tf.nn.conv2d(images, kernel, [1, 2, 2, 1], padding…
score: 4
has title: apply_gradients() function in tensorflow does not update the weight and bias variables
type: Question
upvote count: 4
tagged with: deep-learning
type: UnansweredQuestion
answer count: 1
downvote count: 0
tagged with: neural-network
tagged with: machine-learning
has answer: http://stackoverflow.com/a/47710743
tagged with: tensorflow
favorite count: 0

http://stackoverflow.com/comment/82510285
type: Comment
type: QuestionComment
has text: No @AshwiniChaudhary, this is a pandas solution, that I currently don't it (I only use numpy for this project).
comment on: http://stackoverflow.com/q/47774660
score: 0

http://stackoverflow.com/comment/82480854
type: Comment
comment on: http://stackoverflow.com/q/47759603
type: QuestionComment
has text: @AmitTripathi I looked at that answer but I still don't see how I can apply to my current problem. And yes I'm starting to realize that threading is a bit of an issue in python.
score: 0

http://stackoverflow.com/a/47847878
has body: First of all, shadowing a built-in name like list may lead to all sorts of troubles - choose your variable names carefully. You don't actually need a regular expression here - there is a built-in isalpha() string method: Return true if all characters in the string are alphabetic and there is at least one character, false otherwise. In [1]: l = [['hello', 'mr.', 'smith', ',', 'how', 'are', 'you', 'doing', 'today', '?'], ['the', 'wea ...: ther', 'is', 'great', ',', 'and', 'python', 'is', 'awesome', '.'], ['the', 'sky', 'is', 'pink ...: ish-blue', '.'], ['you', 'should', "n't", 'eat', 'cardboard', '.']] In [2]: [[item for item in sublist if item.isalpha()] for sublist in l] Out[2]: [['hello', 'smith', 'how', 'are', 'you', 'doing', 'today'], ['the', 'weather', 'is', 'great', 'and', 'python', 'is', 'awesome'], ['the', 'sky', 'is'], ['you', 'should', 'eat', 'cardboard']] Here is how you can apply the same filtering logic but using map and filter (you would need the help of functools.partial() as well): In [4]: from functools import partial In [5]: for item in map(partial(filter, str.isalpha), l): ...: print(list(item)) ['hello', 'smith', 'how', 'are', 'you', 'doing', 'today'] ['the', 'weather', 'is', 'great', 'and', 'python', 'is', 'awesome'] ['the', 'sky', 'is'] ['you', 'should', 'eat', 'cardboard']
upvote count: 1
answers question: http://stackoverflow.com/q/47847807
has comment: http://stackoverflow.com/comment/82660910
downvote count: 0
score: 1
type: Answer

http://stackoverflow.com/q/47852373
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47852502
has answer: http://stackoverflow.com/a/47852502
tagged with: http://stackoverflow.com/tag/html
tagged with: python
tagged with: twitter
possible better answer: http://stackoverflow.com/a/47852499
favorite count: 0
type: Question
answer count: 2
upvote count: 2
has body: I am getting some odd behavior that I do not quite understand. I am hoping someone can explain what is going on. Consider this metadata: &lt;meta property="og:title" content="This is the Tesla Semi truck"&gt; &lt;meta name="twitter:title" content="This is the Tesla Semi truck"&gt; This line successfully finds ALL "og" properties and returns a list. opengraphs = doc.html.head.findAll(property=re.compile(r'^og')) However, this line fails to do the same thing for the twitter cards. twitterCards = doc.html.head.findAll(name=re.compile(r'^twitter')) Why does the first line successfully find all the "og" (opengraph cards), but fail to find the twitter cards?
downvote count: 0
tagged with: web-scraping
has title: Python Beautiful Soup Extracting HTML Meta Data
tagged with: beautifulsoup
has answer: http://stackoverflow.com/a/47852499
score: 2

http://stackoverflow.com/comment/82526417
type: Comment
has text: So, what should I do? (I want to run python package of med2image in a python script)
score: 0
comment on: http://stackoverflow.com/q/47782522
type: QuestionComment

http://stackoverflow.com/q/47698035
upvote count: 4
has answer: http://stackoverflow.com/a/47698311
type: AnsweredQuestion
tagged with: python-2.7
has answer: http://stackoverflow.com/a/47700195
answer count: 2
has body: While creating a character device on a Linux system, I interacted with it using Python and its basic file operations. After experiencing several crashes, I started printing debug messages and noticed a strange behavior: it seems that Python "optimizes" file operations in a weird sense. Let's peek at an example; here's a basic code and output of an interaction: Kernel module // Several includes and kernel module initialization static ssize_t dev_read(struct file *filep, char *buffer, size_t len, long long *offset){ printk(KERN_INFO "[DEBUGGER] - dev_read with len: %d, offset: 0x%llx.\n", len, offset[0]); return len; } static ssize_t dev_write(struct file *filep, const char *buffer, size_t len, long long *offset){ printk(KERN_INFO "[DEBUGGER] - dev_write with len: %d, offset: 0x%llx.\n", len, offset[0]); return len; } static long long dev_llseek(struct file *filep, long long offset, int orig){ printk(KERN_INFO "[DEBUGGER] - dev_llseek with offset: 0x%llx, orig: %d\n", offset, orig); return offset; } static int dev_release(struct inode *inodep, struct file *filep){ return 0; // Success } static int dev_open(struct inode *inodep, struct file *filep){ return 0; // Success } static struct file_operations fops = { .open = dev_open, .read = dev_read, .write = dev_write, .release = dev_release, .llseek = dev_llseek, }; int init_module(void){ // Code to create character device return 0; } void cleanup_module(void){ // Code to delete character device } Python with open("/dev/chardevice", "r+b") as character: character.seek(1) character.read(4) character.seek(0x7f123456) character.read(20) character.write("\xff" * 4) Output # seek(1) [DEBUGGER] - dev_llseek with offset: 0x0, orig: 0 [DEBUGGER] - dev_read with len: 1, offset: 0x0. [DEBUGGER] - dev_llseek with offset: 0x1, orig: 0 # read(4) [DEBUGGER] - dev_read with len: 4, offset: 0x0. # seek(0x7f123456) [DEBUGGER] - dev_llseek with offset: 0x7f123000, orig: 0 [DEBUGGER] - dev_read with len: 1110, offset: 0x0. # read(20) [DEBUG…
downvote count: 0
possible better answer: http://stackoverflow.com/a/47698311
has comment: http://stackoverflow.com/comment/82360000
favorite count: 0
type: Question
tagged with: linux
has title: Python read/write/seek operations under the hood
tagged with: python
tagged with: http://stackoverflow.com/tag/c
score: 4
tagged with: linux-device-driver
accepted answer: http://stackoverflow.com/a/47700195

http://stackoverflow.com/comment/82499188
type: AnswerComment
comment on: http://stackoverflow.com/a/47763008
has text: i was referring to ppl using aws resource mock
type: Comment
score: 0

http://stackoverflow.com/q/47726778
has comment: http://stackoverflow.com/comment/83767120
tagged with: pytest
answer count: 1
has answer: http://stackoverflow.com/a/47731333
score: 7
has title: PyTest : Allow Failure Rate
favorite count: 0
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82630248
downvote count: 0
tagged with: python
upvote count: 7
has body: I am currently working on a project where we are running a large suite of parameterized tests (>1M). The tests are randomly generated use-cases and in this large test space, it is expected that in each run certain edge cases will fail, ~1-2%. Is there a implementation for Pytest where you can pass a failure-rate argument, or handle this behavior?

http://stackoverflow.com/q/47818984
type: UnansweredQuestion
has title: Combine two pandas dataframes adding corresponding values pt2
has comment: http://stackoverflow.com/comment/82600049
has comment: http://stackoverflow.com/comment/82599960
linked to: http://stackoverflow.com/q/9108855
has answer: http://stackoverflow.com/a/47819457
tagged with: python
has answer: http://stackoverflow.com/a/47820074
tagged with: merge
type: Question
score: 0
answer count: 2
tagged with: concatenation
has body: So i have these CSV files I want to combine as follows: file1.csv Date,Time,Unique1,Common blah,blah,55,92 file2.csv Date,Time,Unique2,Common blah,blah,12,25 I want a pandas dataframe where... Date,Time,Unique1,Unique2,Common (order of columns doesn't matter) blah,blah,55,12,117 .. where 92+25 is the 117. I found a post with the exact same title as this one that has the following code sample: each_df = (pd.read_csv(f) for f in all_files) full_df = pd.concat(each_df).groupby(level=0).sum() This does what I need, except that it doesn't carry forward the Date and Time columns. I suppose that's because the sum() doesn't know what to do with it. I instead get... Unique1,Unique2,Common &lt;values as expected&gt; Please help me to pass through the Date and Time columns. They're supposed to be the exact same in each file so I'm ok to index the data by 'Date' and 'Time' columns. Thanks in advance.
tagged with: pandas
tagged with: join

http://stackoverflow.com/a/52019275
has body: This bug has been fixed (don't know in which version though) and it works as expected in the latest version- 0.13.3.
type: Answer
answers question: http://stackoverflow.com/q/47817168
score: 0

http://stackoverflow.com/q/47716814
downvote count: 0
answer count: 1
tagged with: selenium
has body: I want to click block. I tried this: alert = browser.switch_to_alert() alert.dismiss(); However it says that there is no alert open. I think it's not considered as an alert?
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47717362
type: UnansweredQuestion
tagged with: python
score: 4
upvote count: 4
has title: How can I close the microphone/camera popup in Python / Selenium?

http://stackoverflow.com/q/47758858
tagged with: string
has answer: http://stackoverflow.com/a/47759650
type: Question
has body: i am trying to perform sentence chunking in my corpus.firstly i loaded my tagged data and then i was trying to perform chunking in that tagged corpus.here is my code. def load_corpus(): corpus_root = os.path.abspath('../nlp1/dumpfiles') mycorpus = nltk.corpus.reader.TaggedCorpusReader(corpus_root,'.*') return mycorpus.tagged_sents() def sents_chunks(tagg_sents, pos_tag_pattern): chunk_freq_dict = defaultdict(int) chunker = nltk.RegexpParser(pos_tag_pattern) for sent in tagg_sents: if not all(sent): print("NoneType object in \"{}\": {}".format(sent.label(),sent)) sent = cast_to_tree_function(filter(bool, sent)) for chk in chunker.parse(sent).subtrees(): if str(chk).startswith('(NP'): phrase = chk.__unicode__()[4:-1] #print(phrase) if '\n' in phrase: phrase = ' '.join(phrase.split()) #print(phrase) chunk_freq_dict[phrase] += 1 #print(chunk_freq_dict) return chunk_freq_dict i am getting error somewhere in my corpus ,where and why i dont know.does anyone know what is the issue and how can i solve it? this is the error: Traceback (most recent call last): File "multiwords1.py", line 184, in &lt;module&gt; candidates = main(domain_corpus, PATTERN,MIN_FREQ,MIN_CVAL) File "multiwords1.py", line 156, in main chunks_freqs = sents_chunks(domain_sents, pos_tag_pattern) File "multiwords1.py", line 23, in sents_chunks for chk in chunker.parse(sent).subtrees(): File "/usr/local/lib/python3.5/dist-packages/nltk/chunk/regexp.py", line 1208, in parse chunk_struct = parser.parse(chunk_struct, trace=trace) File "/usr/local/lib/python3.5/dist-packages/nltk/chunk/regexp.py", line 1023, in parse chunkstr = ChunkString(chunk_struct) File "/usr/local/lib/python3.5/dist-packages/nltk/chunk/regexp.py", line 98, in __init__ self._str = '&lt;' + '&gt;&lt;'.join(tags) + '&gt;' TypeError: sequence item 352: expected str instance, NoneType found
type: UnansweredQuestion
tagged with: python
tagged with: list
score: 0
answer count: 1
has title: TypeError: sequence item 352: expected str instance, NoneType found

http://stackoverflow.com/a/47835713
answers question: http://stackoverflow.com/q/47835269
score: 1
type: Answer
downvote count: 0
upvote count: 1
has body: One can also use system commands to work on files. For example in Linux: import os os.system("cat test.txt | sed 's/^(.*$//' &gt; results.txt") cat reads out the infile, | is to pipe the output to sed which replaces lines starting with ( to blank and finally &gt; redirects output to outfile.

oauth
tags question: http://stackoverflow.com/q/47780712
tag name: oauth
tags question: http://stackoverflow.com/q/47778277
type: Tag
tags question: http://stackoverflow.com/q/47777288
tags question: http://stackoverflow.com/q/47817606

http://stackoverflow.com/comment/82583551
type: Comment
type: QuestionComment
has text: Can you show the data before and teh data after so we can see what is happening?
score: 0
comment on: http://stackoverflow.com/q/47810367

http://stackoverflow.com/a/47792756
has body: Everything is possible Maybe what you're looking for has already been implemented. You may have to exchange your own messages between the two programs. You could do AMQP, HTTP, XMPP... to send your messages over Your messages could be any format such as XML-RPC, JSON-RPC, JSON, your own format, ... Then... On Python side, you transform from/to your format from 5 and dict. On Java side, you transform from/to your format from 5 and some Java container Good luck.
score: 0
answers question: http://stackoverflow.com/q/47792530
type: Answer

http://stackoverflow.com/comment/82558357
has text: How did you make your python3 virtual env? I would try `python3 -m venv myvirtualenv` to make sure you are creating it with a python3 interpreter
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47798698

http://stackoverflow.com/q/47810665
has comment: http://stackoverflow.com/comment/82582656
tagged with: python
score: -1
has body: I need to take number of row(x) and column(y) as user input separated by comma etc. and create a 2D array out of it. where array[x][y]=x*j This is what i am trying: userInput = raw_input("Enter values for row and column number:\t").split(",") for x in range(userInput): for y in range(userInput[x]): userInput[x][y]=x*y print(userInput[x][y])
has comment: http://stackoverflow.com/comment/82583156
type: Question
has comment: http://stackoverflow.com/comment/82583104
downvote count: 2
answer count: 2
has comment: http://stackoverflow.com/comment/82582553
upvote count: 1
has comment: http://stackoverflow.com/comment/82582604
has comment: http://stackoverflow.com/comment/82582505
has answer: http://stackoverflow.com/a/47811195
has title: create a program which takes 2 digits, X,Y as input and generates a 2-dimensional array
accepted answer: http://stackoverflow.com/a/47811195
has comment: http://stackoverflow.com/comment/82582622
has comment: http://stackoverflow.com/comment/82582957
favorite count: 0
has comment: http://stackoverflow.com/comment/82582663
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82582593
has comment: http://stackoverflow.com/comment/82582536
has comment: http://stackoverflow.com/comment/82582490
has answer: http://stackoverflow.com/a/47810951
possible better answer: http://stackoverflow.com/a/47810951

http://stackoverflow.com/comment/82449132
comment on: http://stackoverflow.com/a/47744264
has text: actually can just do `df.val.diff()`
type: AnswerComment
score: 1
type: Comment

http://stackoverflow.com/comment/82432600
has text: @xaav, decode did not work either. Here is the traceback:
comment on: http://stackoverflow.com/q/47735949
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/a/47844500
type: Answer
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47824229
has body: This is a very incomplete answer since I haven't profiled or timed anything or even checked that it gives the same answer. However here are some suggestions that reduce the amount of Python code that Cython generates: Add the @cython.cdivision(True) compilation directive. This means that a ZeroDivisionError won't be raised on float division and you'll get a NaN value instead. (Only do this if you don't want the error to be raised). Change p_s = np.sqrt(...) to p_s = sqrt(...). This removes a numpy call that only operates on a single value. You seem to have done this elsewhere so I don't know why you missed this line. Where possible use fixed size C arrays instead of numpy arrays: cdef double beta[3] # ... beta[0] = X[1]/X[5] beta[1] = X[3]/X[5] beta[2] = p_s/X[5] You can do this when the size is known at compile time (and fairly small) and when you don't want to return it. This avoids a call to np.zeros and some subsequent type-checking to assign it the the typed numpy array. I think beta is the only place you can do this. np.angle( complex(x/r, y/r) ) can be replaced by atan2(y/r, x/r) (using atan2 from libc.math. You can also lose the division by r cdef int i helps make your for loop faster in getEMField (Cython is often good at automatically picking up the types of loop variables but seems to have failed here) I suspect it's quicker to assign E element-by-element than as a whole array: E[0] = k2*x/0.045 + k10*rn**9*cos(9*arg) E[1] = -k2*y/0.045 -k10*rn**9*sin(9*arg) There isn't much value in specifying types like list and tuple and it may actually make the code slightly slower (because it will waste time checking the types). A bigger change would be to pass E and B into GetEMField as pointers rather than using allocating them np.zeros. This would let you allocate them as static C arrays in equations (cdef double E[3]). The downside is that GetEMField would have to be cdef so no longer callable from Python (but you could make a Python callable wrapper function too…
accepted answer of: http://stackoverflow.com/q/47824229
score: 1

http://stackoverflow.com/comment/82651558
has text: How would you determine which values to show on the x axis then? Maybe you want something like [a broken axis](https://matplotlib.org/examples/pylab_examples/broken_axis.html)?
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47842156

http://stackoverflow.com/q/47801821
type: UnansweredQuestion
has title: Plotting multiple lines in one graph with pandas and matplotlib, using climate data
tagged with: python
has body: I'm trying to create a graph that shows whether or not average temperatures in my city are increasing. I'm using data provided by NOAA and have a DataFrame that looks like this: DATE TAVG MONTH YEAR 0 1939-07 86.0 07 1939 1 1939-08 84.8 08 1939 2 1939-09 82.2 09 1939 3 1939-10 68.0 10 1939 4 1939-11 53.1 11 1939 5 1939-12 52.5 12 1939 This is saved in a variable called "avgs", and I then use groupby and plot functions like so: avgs.groupby(["YEAR"]).plot(kind='line',x='MONTH', y='TAVG') This produces a line graph (see below for example) for each year that shows the average temperature for each month. That's great stuff, but I'd like to be able to put all of the yearly line graphs into one graph, for the purposes of visual comparison (to see if the monthly averages are increasing). Example output I'm a total noob with matplotlib and pandas, so I don't know the best way to do this. Am I going wrong somewhere and just don't realize it? And if I'm on the right track, where should I go from here?
has answer: http://stackoverflow.com/a/47802114
score: 0
answer count: 2
tagged with: anaconda
tagged with: pandas
tagged with: matplotlib
has answer: http://stackoverflow.com/a/47802502
type: Question

http://stackoverflow.com/a/47798047
type: Answer
has body: As a guess, one of the following things happened: pip install enum -- a different enum package than the stdlib version which is shadowing the stdlib version enum.py file -- you have created an enum.py file which is shadowing the stdlib version you have somehow deleted the enum.py that comes with the stdlib
answers question: http://stackoverflow.com/q/47797275
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/a/47800599
has comment: http://stackoverflow.com/comment/82565954
answers question: http://stackoverflow.com/q/47800256
score: 0
has comment: http://stackoverflow.com/comment/82562720
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82562769
has body: I would use the XML format which is the most machine-readable and will have the most support. In the past I've used the XML parsing library called lxml with BeautifulSoup to pull out the data I needed. Both of these have lots of documentation.
has comment: http://stackoverflow.com/comment/82562413
accepted answer of: http://stackoverflow.com/q/47800256
has comment: http://stackoverflow.com/comment/82565928
type: Answer
has comment: http://stackoverflow.com/comment/82597323

http://stackoverflow.com/comment/82576338
type: Comment
has text: jaccard values are coming as NaN, how shall i fix it ?
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47785817

http://stackoverflow.com/a/47842689
has body: Some options: fill in the missing data with the average value of that month ignore the months with partial information change your frequency to every 2 weeks
type: Answer
score: -1
answers question: http://stackoverflow.com/q/47842534
upvote count: 0
downvote count: 1

http://stackoverflow.com/a/47698686
has comment: http://stackoverflow.com/comment/82357322
has comment: http://stackoverflow.com/comment/82357278
answers question: http://stackoverflow.com/q/47698571
has comment: http://stackoverflow.com/comment/82357614
score: 0
has body: Try this d = {0b1: 'a', 0b10: 'b', 0b100: 'c'} for i in range(0b1000): s = '' for k, v in d.items(): if i &amp; k: s += v print s Edit: Some explination So you're trying to associate 'a', 'b', 'c' to 1, 2 and 4 respectively. To do this I used the dictionary above (using binary literals for clarity). Then, looping through all 0 &lt;= i &lt; 8, you can see if there is a 1 at the relevant position using the &amp; operator. e.g. is there a 1 at the second position from the right: 0b00 &amp; 0b10 == 0b01 &amp; 0b10 == 0 is false, whereas 0b10 &amp; 0b10 == 0b11 &amp; 0b10 != 0is true.
type: Answer

http://stackoverflow.com/q/47782681
tagged with: printing
has comment: http://stackoverflow.com/comment/82526832
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/82528725
accepted answer: http://stackoverflow.com/a/47783603
has comment: http://stackoverflow.com/comment/82528010
has comment: http://stackoverflow.com/comment/82526723
tagged with: floating-point
upvote count: 1
has comment: http://stackoverflow.com/comment/82528095
has answer: http://stackoverflow.com/a/47783603
tagged with: precision
favorite count: 0
type: Question
score: 1
has title: Dynamically change floating point precision in Python
linked to: http://stackoverflow.com/q/783897
tagged with: python
has comment: http://stackoverflow.com/comment/82526819
has body: I'm trying to write a program that calculates pi with different accuracies and prints out the number and the time elapsed. I want to print the result with the current accuracy each time. I used print('pi = %*f'%(i, pi)) where i is my current floating point accuracy. This made the program round up the number to the i decimal digit. I'm attaching a picture showing my results running the same algorithm but changing output from: print (" pi = ", pi, " =with ", i-1, " decimal points accuracy= in: ", (-1)*t, "sec") to: print (" pi = %.*f"%(i, pi), " =with ", i-1, " decimal points accuracy= in: ", (-1)*t, "sec") This is my full code: import time accuracy = 4 for i in range(1,accuracy + 1): pi = 0 prevPi = 1 x = 0 t = time.time() while abs((pi * 4) - prevPi) &gt; 10**((-1)*(i+1)): #while x &lt; lim: prevPi = pi * 4 pi += (((-1)**(x))/(1+(2*x))) #print(abs((pi * 4) - prevPi)) x += 1 pi *= 4 t -= time.time() print (" pi = %.*f"%(i, pi), " =with ", i-1, " decimal points accuracy= in: ", (-1)*t, "sec") How do I print the number with i decimal digits WITHOUT rounding?
type: AnsweredQuestion

http://stackoverflow.com/q/47723873
has answer: http://stackoverflow.com/a/47723984
upvote count: 6
score: 6
tagged with: machine-learning
linked to: http://stackoverflow.com/q/35678883
possible better answer: http://stackoverflow.com/a/47731647
tagged with: tensorflow
favorite count: 0
has answer: http://stackoverflow.com/a/47730776
has answer: http://stackoverflow.com/a/47731647
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47730776
has title: Modifying the weights and biases of a restored CNN model in TensorFlow
tagged with: python
has answer: http://stackoverflow.com/a/71603741
answer count: 4
has body: I have recently started using TensorFlow (TF), and I have come across a problem that I need some help with. Basically, I've restored a pre-trained model, and I need to modify the weights and biases of one of its layers before I retest its accuracy. Now, my problem is the following: how can I change the weights and biases using the assign method in TF? Is modifying the weights of a restored modeled even possible in TF? Here is my code: import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data # Imports the MINST dataset # Data Set: # --------- mnist = input_data.read_data_sets("/home/frr/MNIST_data", one_hot=True)# An object where data is stored ImVecDim = 784# The number of elements in a an image vector (flattening a 28x28 2D image) NumOfClasses = 10 g = tf.get_default_graph() with tf.Session() as sess: LoadMod = tf.train.import_meta_graph('simple_mnist.ckpt.meta') # This object loads the model LoadMod.restore(sess, tf.train.latest_checkpoint('./'))# Loading weights and biases and other stuff to the model # ( Here I'd like to modify the weights and biases of layer 1, set them to one for example, before I go ahead and test the accuracy ) # # Testing the acuracy of the model: X = g.get_tensor_by_name('ImageIn:0') Y = g.get_tensor_by_name('LabelIn:0') KP = g.get_tensor_by_name('KeepProb:0') Accuracy = g.get_tensor_by_name('NetAccuracy:0') feed_dict = { X: mnist.test.images[:256], Y: mnist.test.labels[:256], KP: 1.0 } print( 'Model Accuracy = ' ) print( sess.run( Accuracy, feed_dict ) )
type: Question
tagged with: deep-learning
downvote count: 0

http://stackoverflow.com/q/47723377
has comment: http://stackoverflow.com/comment/82407598
has title: How to get a script to read and write a file?
accepted answer: http://stackoverflow.com/a/47723447
has comment: http://stackoverflow.com/comment/82407525
tagged with: python
has comment: http://stackoverflow.com/comment/82407796
has answer: http://stackoverflow.com/a/47723447
has comment: http://stackoverflow.com/comment/82407789
type: Question
has body: I'm completing exercise 16 from Learn Python the Hard Way and it's asking this question: Write a script similar to the last exercise that uses read and argv to read the file you just created. I'm attempting to use the 'read' function in order to have the script automatically run and display the text file that the script creates. But nothing shows up when I run everything, it's just an extra blank space before "close it". How do I get it to display anything? from sys import argv script, filename = argv txt = open(filename) print "Erase %r" % filename print "hit CTRL-C (^C)." print "hit RETURN." raw_input("?") print "Opening the file..." target = open(filename, 'w') print "Truncating the file." target.truncate() print "Need 3 lines." line1 = raw_input("line 1: ") line2 = raw_input("line 2: ") line3 = raw_input("line 3: ") print "Write these to a file" target.write("{0}\n{1}\n{2}\n".format(line1, line2, line3)) print txt.read() print "Close it." target.close()
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/82407626
has comment: http://stackoverflow.com/comment/82407810
has comment: http://stackoverflow.com/comment/82407493
type: AnsweredQuestion

http://stackoverflow.com/a/47841495
upvote count: 3
score: 3
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47840056
type: Answer
has body: This lib uses numpy's random-module, more specific: this part. Just use it like that: import numpy as np bh_sne(X, random_state=np.random.RandomState(0)) # init with integer 0 This can be seen with a simple source-search for random (see picture below), which also shows some unit-test! An integer (0 above) is just some source of entropy, which results in some state of the internal random-number generator. Without analyzing the PRNG there are no guarantees how a seed-number of 0 behaves compared to 1 or 40. It does not need to be different (but often is)! There is only one guarantee: determinism! Grabbing random-numbers from a PRNG initialized with number seed=my_integer, returns the same path / the same numbers each time this is done with this exact seed (first x numbers are equal each time; x arbitrary). But the intro-page probably gives a more important notice (which was my first question when i saw what lib you are using while working in python): Note: Scikit-learn v0.17 includes TSNE algorithms and you should probably be using them instead of this.
accepted answer of: http://stackoverflow.com/q/47840056

http://stackoverflow.com/a/47743986
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/47743819
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82481723
downvote count: 0
has body: Your test function was never executed. The default for pytest is that your test functions must be named test_&lt;something&gt; in order to be automatically discovered and executed by pytest. Here are details how to alter the default behaviour: https://docs.pytest.org/en/latest/example/pythoncollection.html
accepted answer of: http://stackoverflow.com/q/47743819
type: Answer

http://stackoverflow.com/q/47742900
tagged with: jupyter
score: 1
upvote count: 1
favorite count: 0
type: Question
has body: Is there a simple way to make a diff of the latest version of the Jupyter notebook with its previous version using the nbdime tool's nbdiff-web command. http://nbdime.readthedocs.io/en/latest/cli.html#nbdiff-web
tagged with: python
tagged with: git
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48333320
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/48333320
has title: How to make a diff using nbdiff-web of a Jupyter notebook stored on git?

http://stackoverflow.com/q/47724077
tagged with: keras
type: AnsweredQuestion
upvote count: 3
has body: I'm using Keras with Tensorflow on Windows 10. I'm trying to create a maschine learning model for the Adult dataset (https://archive.ics.uci.edu/ml/datasets/Adult). First I am doing One Hot Encoding and then I'm trying to train my model but i get: "ValueError: could not broadcast input array from shape (14,1) into shape (14)" Even if I change the input_dim to something else than 14, I still get the same error with the same shapes. What am I doing wrong? df = pd.read_csv("adult_data.csv",header=None) X = df.iloc[:,0:14] Y = df.iloc[:,14] encoder = LabelEncoder() #X for i in [1,3,5,6,7,8,9,13]: column = X[i] encoder.fit(column) encoded_C = encoder.transform(column) X[i] = np_utils.to_categorical(encoded_C) print(X.shape) #Y encoder.fit(Y) en_Y = encoder.transform(Y) Y = np_utils.to_categorical(en_Y) #model model = Sequential() model.add(Dense(21, input_dim=14, activation="relu")) model.add(Dense(2, activation="softmax")) #compile model.compile(loss="categorical_crossentropy",optimizer="adam",metrics= ["accuracy"]) #train model.fit(X,Y, epochs=50, batch_size=100) score = model.evaluate(X,Y) print("Accuracy: {}%".format(score[0])) FULL ERROR: Traceback (most recent call last): File "main.py", line 36, in &lt;module&gt; model.fit(X,Y, epochs=50, batch_size=100) File "C:\Users\K\AppData\Local\Programs\Python\Python36\lib\site-packages\keras\models.py", line 960, in fit validation_steps=validation_steps) File "C:\Users\K\AppData\Local\Programs\Python\Python36\lib\site-packages\keras\engine\training.py", line 1574, in fit batch_size=batch_size) File "C:\Users\K\AppData\Local\Programs\Python\Python36\lib\site-packages\keras\engine\training.py", line 1407, in _standardize_user_data exception_prefix='input') File "C:\Users\K\AppData\Local\Programs\Python\Python36\lib\site-packages\keras\engine\training.py", line 128, in _standardize_input_data arrays[i] = array ValueError: could not broadcast input array from shape (14,1) into shape (14)
score: 3
answer count: 1
has comment: http://stackoverflow.com/comment/110388712
downvote count: 0
accepted answer: http://stackoverflow.com/a/47724464
has title: Keras: could not broadcast input array from shape (14,1) into shape (14)
tagged with: tensorflow
has answer: http://stackoverflow.com/a/47724464
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82409582
has comment: http://stackoverflow.com/comment/82409129
has comment: http://stackoverflow.com/comment/82409644
tagged with: machine-learning
tagged with: python

http://stackoverflow.com/q/47823935
type: UnansweredQuestion
tagged with: python
score: 0
has body: I have a project of this structure: src/ __init__.py folder_A/ __init__.py foo.py folder_B/ __init__.py bar.py In my src/folder_A/__init__.py I import some instance variables from foo.py from .foo import variable_a as A Now I want to use that variable in my bar.py file so I do the import: from src.folder_A import A But that doesn't work, though if I do: from src.folder_A.foo import variable_a What am I doing wrong?
answer count: 1
has answer: http://stackoverflow.com/a/47823973
has title: Why can my import not be found?
type: Question
tagged with: importerror

http://stackoverflow.com/comment/82395581
score: 0
comment on: http://stackoverflow.com/q/47715070
type: Comment
has text: @zwer The user must upon entering the file. Or, in the example above, the "wrong" query found must somehow throw an error, i.e. "Error: there's no B index"
type: QuestionComment

http://stackoverflow.com/q/47750056
downvote count: 0
possible better answer: http://stackoverflow.com/a/47750298
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47750298
type: AnsweredQuestion
score: 3
has title: python struct unpack length error
has comment: http://stackoverflow.com/comment/116945115
accepted answer: http://stackoverflow.com/a/47750278
has answer: http://stackoverflow.com/a/47750278
tagged with: python
has answer: http://stackoverflow.com/a/47750269
type: Question
has body: I've a bytes object with length 41. I tried to unpack it with: struct.unpack('2B2B32sBi',data) But I got a error that: struct.error: unpack requires a bytes object of length 44 I think the length of 2B2B32sBi should be 2*1+2*1+32*1+1+4=41 after check the python document. Why am I wrong?
answer count: 3
upvote count: 3

http://stackoverflow.com/q/47705344
upvote count: 0
tagged with: google-api
type: UnansweredQuestion
tagged with: flask
has title: Flask app can't find google module
has body: I'm using a virtual environment to run a flask app. When I run pip freeze, I get the following: google-api-core==0.1.1 google-auth==1.2.1 google-cloud-core==0.28.0 google-cloud-speech==0.30.0 google-gax==0.15.16 googleapis-common-protos==1.5.3 However, during run time, I get the following error: from google.cloud import speech ModuleNotFoundError: No module named 'google' I'm using the google speech APIs. They work just fine when I run them locally. I don't understand why the app can't find the modules even though they're listed as installed. Can someone suggest a fix? I've tried doing pip install google, and it downloaded a bunch of other stuff, but still no fix.
downvote count: 1
has answer: http://stackoverflow.com/a/47706685
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82372450
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/47707551
has answer: http://stackoverflow.com/a/62763338
answer count: 3

http://stackoverflow.com/q/47762325
answer count: 1
has title: Python-Bash: unicode strings break bash; safe way to fix?
linked to: http://stackoverflow.com/q/816285
tagged with: string
has comment: http://stackoverflow.com/comment/82486966
tagged with: unicode
has comment: http://stackoverflow.com/comment/82486813
type: Question
has comment: http://stackoverflow.com/comment/82486443
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47762697
score: 0
has comment: http://stackoverflow.com/comment/82486910
has comment: http://stackoverflow.com/comment/82486840
has comment: http://stackoverflow.com/comment/82486498
has answer: http://stackoverflow.com/a/47762697
has comment: http://stackoverflow.com/comment/82487186
has comment: http://stackoverflow.com/comment/82487215
tagged with: python
has comment: http://stackoverflow.com/comment/82486243
has comment: http://stackoverflow.com/comment/82486859
has comment: http://stackoverflow.com/comment/82487021
has body: I have a set of strings in unicode. When I print these out to a file and cat it, this can break my bash terminal: after catting the file, I will get "symbol salad" where everything is just random gibberish (including my command prompt). I understand that this is probably related to the fact that the strings are unicode strings. Currently, I am encoding them as ascii strings as follows: my_string.encode('ascii','ignore') However, this deprecates a lot of data from the strings. Ideally, I would have some way to safely preserve all the unicode data in a file such that the user's terminal does not break when the file is catted. What is the proper way to do this?
has comment: http://stackoverflow.com/comment/82486299
tagged with: bash

http://stackoverflow.com/a/47786621
has comment: http://stackoverflow.com/comment/92739520
type: AcceptedAnswer
downvote count: 0
score: 6
answers question: http://stackoverflow.com/q/47769348
accepted answer of: http://stackoverflow.com/q/47769348
type: Answer
upvote count: 6
has body: i tried so many different things. i updated pip for this project's virtualenvironment and updated the pytest and pytest-flask. but none did work. I was able to pass the tests by: removed the pytest and pytest-flask from virtualenvironment. removed my system-wide installations of them. strangely, i had a package named flask-pytest i removed it(in the env) installed them again system-wide. installed them again on virtualenvironment. i don't know how this had anything with the tests, but it worked. the only thing different is that i didn't installed the said flask-pytest thing.

http://stackoverflow.com/q/47712425
answer count: 0
has body: I am trying to run unit test case of selenium webdriver in python on Pycharm, in which I am stuck on the problem. I have two scripts i.e. goodsRegister.py and Register.py. Now there is a function i.e.test_Test2 in goodsRegister.py and I need that only and only that function to be executed in Register.py, not test_Test1. Check the code goodsRegister.py is as: from selenium import webdriver import os import unittest import time from selenium.webdriver.support.select import Select from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import * from selenium.webdriver.common.by import By from selenium.webdriver.common.action_chains import ActionChains EmailEntry = input("Please Enter Email Address: ") password='12345678' class goodsweb(unittest.TestCase): def setUp(self): driverlocation ="/Users/new/Documents/Learning/Drivers/selenium-2.53.1/py/selenium/webdriver/chromedriver" os.environ["webdriver.chrome.driver"] = driverlocation self.driver = webdriver.Chrome(driverlocation) def test_Test1(self): driver = self.driver url = "https://goods.theentertainerme.com/" driver.get(url) driver.maximize_window() driver.implicitly_wait(10) self.RegisterButton = driver.find_element_by_xpath("//*[@id='logs']/li[2]//a[text()='Sign up']") self.FirstName = driver.find_element_by_id("registrationform-firstname") self.Lastname = driver.find_element_by_id("registrationform-lastname") self.EmailAddress = driver.find_element_by_id("registrationform-email") self.CountryofResidence = driver.find_element_by_xpath("//*[@id='register-form']//div[1]/div[4]//span") self.SelectCountry = driver.find_element_by_xpath("//*[@id='registrationform-country_of_residence']") self.DateofBirth = driver.find_element_by_id("registrationform-date_of_birth") self.Gender = driver.find_element_by_xpath("//*[@id='register-form']//div[1]/div[6]//div") self.Password = driver.find_element_by_id("registrationform-password")…
has comment: http://stackoverflow.com/comment/82386319
tagged with: python-unittest
tagged with: selenium
has comment: http://stackoverflow.com/comment/82385805
type: Question
tagged with: python-3.x
type: UnansweredQuestion
has title: How to call function of one script to another script in webdriver selenium Python
tagged with: python
tagged with: selenium-webdriver
score: 0

http://stackoverflow.com/comment/82538772
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47788448
has text: @jezrael Sorry for delay, been doing some more testing. Type in in ctrl f: Adelaide United and you'll see exact issue I talk about and that Adelaide United v Newcastle jets is in Betfair and Centrebet
score: 0

http://stackoverflow.com/a/47783160
accepted answer of: http://stackoverflow.com/q/47783106
type: AcceptedAnswer
upvote count: 5
type: Answer
has comment: http://stackoverflow.com/comment/82528072
has comment: http://stackoverflow.com/comment/82528435
downvote count: 0
answers question: http://stackoverflow.com/q/47783106
has comment: http://stackoverflow.com/comment/82528347
has comment: http://stackoverflow.com/comment/82529446
has comment: http://stackoverflow.com/comment/82528336
has body: we can using MonthEnd from pandas.tseries.offsets import MonthEnd df.Date=(pd.to_datetime(df.Date,format='%Y%m')+MonthEnd(1)).dt.strftime('%m/%d/%Y') df Out[1336]: Id Name Date Number 0 1 A 01/31/2016 5 1 2 B 02/29/2016 6 2 3 C 03/31/2016 4
score: 5

http://stackoverflow.com/q/47732263
has comment: http://stackoverflow.com/comment/82425395
has comment: http://stackoverflow.com/comment/82425083
accepted answer: http://stackoverflow.com/a/47732320
has answer: http://stackoverflow.com/a/47732382
has answer: http://stackoverflow.com/a/47732320
has comment: http://stackoverflow.com/comment/82425276
has answer: http://stackoverflow.com/a/47732492
has comment: http://stackoverflow.com/comment/82425210
type: AnsweredQuestion
score: -5
has body: How can I find the smallest odd number in a list of integers, if the problem statement says that I can't use for and if?
answer count: 3
tagged with: algorithm
has comment: http://stackoverflow.com/comment/82425545
possible better answer: http://stackoverflow.com/a/47732382
downvote count: 5
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/82425202
type: Question
has comment: http://stackoverflow.com/comment/82425217
has comment: http://stackoverflow.com/comment/82425180
tagged with: functional-programming
upvote count: 0
has title: Functional programming in Python: find smallest odd number in list

http://stackoverflow.com/a/47735259
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47735075
score: 1
type: Answer
has body: You can use map to "push sum down one level of list nesting"; for example: map(sum, subsequences(foo, 4)) # [10, 14, 18, 22, 26, 30, 34, 38, 42, 46, 50, 54, 58, 62, 66, 70, ... A more efficient way is to compute the cumulative sum first and then take pairwise differences at a suitable offset. You appear to be on python 2 which is a pity because python 3 has an accumulate function. On python 2 we need to build our own: def partialsums(a): def runner(a): runner.tot += a return runner.tot runner.tot = 0 return [0] + [runner(i) for i in a] ps = partialsums(foo) Now you can simply do: [r-l for r, l in zip(ps[4:], ps[:-4])] # [10, 14, 18, 22, 26, 30, 34, 38, 42, 46, 50, 54, 58, 62, 66, 70, ... [r-l for r, l in zip(ps[100:], ps[:-100])] # [5050, 5150, 5250, 5350, 5450, 5550, 5650, 5750, 5850, 5950, 6050, ... This last example takes a bit below 10,000 arithmetic operations with the direct method compared to just 300 with the difference method and of these 300, 200 need only be done once and can be reused for other window lengths.

http://stackoverflow.com/comment/85899887
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47772868
has text: I had the same problem and your solution worked good! Thanks so much!

http://stackoverflow.com/q/47757499
downvote count: 0
tagged with: django
upvote count: 1
tagged with: python
answer count: 1
accepted answer: http://stackoverflow.com/a/47757519
has title: Cannot use extra_option with path django
has answer: http://stackoverflow.com/a/47757519
type: Question
has body: I don't understand why I cannot use the path() method as documented here: https://docs.djangoproject.com/en/2.0/topics/http/urls/#passing-extra-options-to-view-functions in my apps urls.py. Here is the code I have: from django.conf.urls import url, include from django.contrib import admin from django.urls import path from . import views as AliasViews from permissions import views as PermissionsViews urlpatterns = [ ... path(r'^user/(?P&lt;alias_id&gt;\d{1,})/members/?$', AliasViews.UserAliasMember.as_view(), name='useralias_member', {'alias_type':'UserAlias'}), ... ] I get this error: SyntaxError: non-keyword arg after keyword arg.
score: 1
favorite count: 0
type: AnsweredQuestion

http://stackoverflow.com/comment/82377300
comment on: http://stackoverflow.com/q/47706979
type: Comment
type: QuestionComment
has text: The fact that you are seeing `MALFORMED_CATEGORY_LABEL` indicates that you are using a version of Bokeh too old for this example (before the recent work to improve categorical support). But your data does not seem appropriate for a joyplot in any case. Joyplots are multiple series, each associated with a different category. You don't appear to have any categoricals for the y-axis at all.
score: 0

http://stackoverflow.com/q/47704639
answer count: 1
type: Question
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82369494
has body: I've been working on a function which will update two dictionaries (similar authors, and awards they've won) from an open text file. The text file looks something like this: Brabudy, Ray Hugo Award Nebula Award Saturn Award Ellison, Harlan Heinlein, Robert Asimov, Isaac Clarke, Arthur Ellison, Harlan Nebula Award Hugo Award Locus Award Stephenson, Neil Vonnegut, Kurt Morgan, Richard Adams, Douglas And so on. The first name is an authors name (last name first, first name last), followed by awards they may have won, and then authors who are similar to them. This is what I've got so far: def load_author_dicts(text_file, similar_authors, awards_authors): name_of_author = True awards = False similar = False for line in text_file: if name_of_author: author = line.split(', ') nameA = author[1].strip() + ' ' + author[0].strip() name_of_author = False awards = True continue if awards: if ',' in line: awards = False similar = True else: if nameA in awards_authors: listawards = awards_authors[nameA] listawards.append(line.strip()) else: listawards = [] listawards.append(line.strip() awards_authors[nameA] = listawards if similar: if line == '\n': similar = False name_of_author = True else: sim_author = line.split(', ') nameS = sim_author[1].strip() + ' ' + sim_author[0].strip() if nameA in similar_authors: similar_list = similar_authors[nameA] similar_list.append(nameS) else: similar_list = [] similar_list.append(nameS) similar_authors[nameA] = similar_list continue This works great! However, if the text file contains an entry with just a name (i.e. no awards, and no similar authors), it screws the whole thing up, generating an IndexError: list index out of range at this part Zname = sim_author[1].strip()+" "+sim_author[0].strip() ) How can I fix this? Maybe with a 'try, except function' in that area? Also, I wouldn't mind getting rid of those continue functions, I wasn't sure how else to keep it going. I'm still pretty new to this, so any help would be much appreciated! I keep…
tagged with: python
score: 0
has title: Error when creating dictionaries from text files
has answer: http://stackoverflow.com/a/47705041

http://stackoverflow.com/q/47742557
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/47742800
possible better answer: http://stackoverflow.com/a/47742800
type: Question
has answer: http://stackoverflow.com/a/47742737
accepted answer: http://stackoverflow.com/a/47742737
answer count: 2
has body: I have problems while I am building a simple like button. I have done everything as I have read in different tutorial but when I click on the Like button, it does not do anything. Look: models.py class Comentario (models.Model): titulo = models.CharField(max_length=50) texto = models.CharField(max_length=200) autor = models.ForeignKey (Perfil, null=True, blank=True, on_delete=models.CASCADE) likes = models.IntegerField(default=0) views.py def like (request): com_id = None if request.method == 'GET': com_id = request.GET.get('comentario_id') likes = 0 if com_id: com = Comentario.objects.get(id=int(com_id)) if com: likes = com.likes + 1 com.likes = likes com.save() return HttpResponse(likes) urls.py urlpatterns = [ url(r'^like/$', login_required(views.like), name='like'), ] .html {% extends 'base/base.html' %} {% for comentario in objects %} ... {% if user.is_authenticated %} Like|{{ comentario.likes }} {% endif %} {% endfor %} js/ajax.js $('#likes').click(function(){ var comid; comid = $(this).attr("data-comid"); $.get('/home/like/', {comentario_id: comid}, function(data){ $('#like_count').html(data); $('#likes').hide(); }); }); And in base.html I have import all the .js base.html The issue is that when I push the button nothing happens. It is a simple code but somethin crashes. In the inspection do not show any error or something missing. When I enter into .../home/like/ it appears a 0. I will appreciate your help. Thank you so much.
has title: Ajax + Django Like button
tagged with: django
tagged with: javascript
tagged with: python
tagged with: jquery
tagged with: ajax

http://stackoverflow.com/a/47745261
has comment: http://stackoverflow.com/comment/82480524
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47745106
has comment: http://stackoverflow.com/comment/82479018
answers question: http://stackoverflow.com/q/47745106
has comment: http://stackoverflow.com/comment/82481668
has body: First of all, you're collecting the whole &lt;span&gt; tag even tho you're only interested in the value presented, so to get the temperature value (and convert it to an actual integer) do: current_temp = int(soup.find("div", {"class": "current-temp"}).find( "span", {"class": "wu-value wu-value-to"}).getText()) Second, your current_temp will never change once obtained, what you want instead is to periodically pick up the latest temperature value and then, based on its value, print whatever you want. Something like: # !/usr/bin/python import requests from BeautifulSoup import BeautifulSoup import time degree = u'\N{DEGREE SIGN}' url = 'https://www.wunderground.com/weather/us/ca/san-diego/KCASANDI355' def weather(): while (True): # get the current temperature response = requests.get(url) soup = BeautifulSoup(response.content) current_temp = int(soup.find("div", {"class": "current-temp"}).find( "span", {"class": "wu-value wu-value-to"}).getText()) # now print it out and add our comment print(u"San Diego Feels Like: {}{}F".format(current_temp, degree)) if current_temp &gt; 100: print("You Dead") elif 100 &gt;= current_temp &gt; 80: print("It's hot af") elif 80 &gt;= current_temp &gt; 70: print("It's just right") elif 70 &gt;= current_temp &gt; 50: print("It's kinda cool") else: print("It's cold af") # finally, wait 5 minutes (300 seconds) before updating again time.sleep(300) if __name__ == "__main__": weather()
type: Answer
has comment: http://stackoverflow.com/comment/82482484
has comment: http://stackoverflow.com/comment/82450614
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/comment/82455729
type: Comment
type: QuestionComment
score: 0
has text: @abccd Thanks alot
comment on: http://stackoverflow.com/q/47747503

http://stackoverflow.com/comment/82372366
has text: I'm glad that you were able to get your answer. Please do note that the proper way to thank someone on Stack Overflow isn't actually by writing "Thank You," but rather by accepting the answer.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47705999
type: Comment

http://stackoverflow.com/comment/82542293
type: QuestionComment
has text: do you need a string or an integer? you cannot have integers starting with zero. It's invalid. do you mean `MyVar="018904837646"`. What do you want to achieve?
score: 0
comment on: http://stackoverflow.com/q/47790591
type: Comment

http://stackoverflow.com/q/47802801
has answer: http://stackoverflow.com/a/47802868
type: UnansweredQuestion
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/82567084
has answer: http://stackoverflow.com/a/47802861
has comment: http://stackoverflow.com/comment/82567037
tagged with: class
upvote count: 0
answer count: 2
has title: Using the value of a variable as the name of an object
downvote count: 1
favorite count: 0
type: Question
has body: How can I use the value of a variable as the object in a class? e.g. I have a class called 'a', and I want to be able to assign the value of a variable 'b' to be the name of an object in class a class a(): __init__(self): b = "foo" How can I make it so that b = a() Would be the same as foo = a() ?

http://stackoverflow.com/comment/82578824
type: Comment
has text: e.g.: https://www.reddit.com/r/leagueoflegends/ has a vast amount of submissions, i would like to gather all submission id's of this (or another subreddit), if you follow the link and go to an undfined comment section of a submission you will find e.g.: https://redd.it/7jnfw5, as described i'm already able to crawl all comments recursively there, but to fully automate the crawler i need to find all these submission id's of the subreddit .../r/leagueoflegends
type: QuestionComment
comment on: http://stackoverflow.com/q/47802521
score: 0

http://stackoverflow.com/comment/82524782
type: Comment
comment on: http://stackoverflow.com/a/47781373
score: 0
type: AnswerComment
has text: I just ran your code. Out of range is not from matrix, it's from temp_a = re.findall(r"\'(.+?)\'",line)[0]. It can't find anything.

http://stackoverflow.com/comment/82541647
comment on: http://stackoverflow.com/q/47790088
has text: Do you mind providing a data sample that accurately reproduces your problem? You could also try updating to the latest stable release - 0.21.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/47809075
downvote count: 0
has body: Setup I had to make up data because you didn't provide any. df = pd.DataFrame(dict( Date=pd.date_range(end=pd.to_datetime('now'), periods=100, freq='H'), Proto=np.random.choice('UDP TCP ICMP'.split(), 100, p=(.3, .5, .2)) )) Solution Use pd.crosstab then plot pd.crosstab(df.Date.dt.date, df.Proto).plot.bar(stacked=True)
upvote count: 1
has comment: http://stackoverflow.com/comment/82621365
score: 1
answers question: http://stackoverflow.com/q/47807693
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47807693
type: Answer

http://stackoverflow.com/a/47701626
score: 0
answers question: http://stackoverflow.com/q/47701545
type: Answer
has body: It looks like that randvalue is a list in list. So try to print print(randvalue[0][0]) so it will print 16949.070963

http://stackoverflow.com/comment/82576746
score: 0
type: Comment
type: QuestionComment
has text: add it, I will modify it with a suitable format.
comment on: http://stackoverflow.com/q/47800755

http://stackoverflow.com/a/47851938
accepted answer of: http://stackoverflow.com/q/47851848
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82668260
answers question: http://stackoverflow.com/q/47851848
score: 1
type: Answer
has body: the problem is with your cli command, not your code. you have dashes (or some sort of unicode) instead of hyphens $ python test.py –f import_dbs –c 1 None None $ python test.py -f import_dbs –c 1 import_dbs None $ python test.py -f import_dbs -c 1 import_dbs 1 $ echo "python test.py –f import_dbs –c 1" | od -c 0000000 p y t h o n t e s t . p y – 0000020 ** ** f i m p o r t _ d b s – 0000040 ** ** c 1 \n 0000046 $ echo "python test.py -f import_dbs -c 1" | od -c 0000000 p y t h o n t e s t . p y - 0000020 f i m p o r t _ d b s - c 0000040 1 \n 0000042 probably caused by cutting and pasting or weird keyboard mapping.
has comment: http://stackoverflow.com/comment/82668225
upvote count: 1

http://stackoverflow.com/q/47700462
type: AnsweredQuestion
score: 0
tagged with: tkinter
has comment: http://stackoverflow.com/comment/82361412
has comment: http://stackoverflow.com/comment/82361190
answer count: 1
has title: Creating and Moving Shapes On Click with TKINTER and canvas
accepted answer: http://stackoverflow.com/a/47701211
has comment: http://stackoverflow.com/comment/82361553
type: Question
has answer: http://stackoverflow.com/a/47701211
tagged with: canvas
tagged with: python
has comment: http://stackoverflow.com/comment/82361645
has body: I hope this isn't too stupid for you guys Am kinda stuck in this project first time working with canvas and tkinter all I know is the basic tutorial. what I want is how to create an on click event after precision of the shape I want with buttons and move the form (updating the positing) from tkinter import * from tkinter import messagebox def Click(event) : can.coords(cercle, event.x, event.y, event.x+10, event.y+10) def Rectangle() : can.create_rectangle(10, 10, 70, 70, fill='white', outline='blue', width=3) def Delete() : msg = messagebox.askyesnocancel('Info','Delete canevas ?') if msg == None : return elif msg == True : can.delete(ALL) def Line(): can.create_line(200,200,100,100,fill='red', width=5) def Cercle(): can.create_oval(10, 10, 70, 70, fill='orange', outline='blue') fenetre = Tk() fenetre.title('Dessin des objets') fenetre.resizable(width=False,height=False) fenetre.geometry('400x200+100+50') fenetre.configure(bg = 'light green') can = Canvas(fenetre, bg='white', height=300, width=300) can.pack(side = RIGHT) btnLine = Button(fenetre,text='Line',width=30,command=Line) btnLine.pack() btnRectangle = Button(fenetre,text='Rectangle',width=30,command=Rectangle) btnRectangle.pack() btnDelete = Button(fenetre, text='Effacer', width=30,command=Effacer) btnDelete.pack() btnCercle = Button(fenetre,text='Cercle',width=30,command=Cercle) btnCercle.pack() can.bind("&lt;Button-1&gt;", Click) can.pack(side = RIGHT) cercle = can.create_oval(10, 10, 10+10, 10+10, fill = 'orange', outline = 'gold') fenetre.mainloop() Am looking for a way to create shapes on click after click on a button, and I started to realise I went off road with this code. here is a pic of what I did thanks in advance
has comment: http://stackoverflow.com/comment/82362139

decode
tag name: decode
tags question: http://stackoverflow.com/q/47737021
tags question: http://stackoverflow.com/q/47839776
type: Tag

build
tag name: build
tags question: http://stackoverflow.com/q/47792600
type: Tag
tags question: http://stackoverflow.com/q/47769998

http://stackoverflow.com/comment/107754797
comment on: http://stackoverflow.com/a/60903525
score: 1
type: Comment
has text: Can't edit because it's too few characters so I'm not allowed. But you should add a newline for your code to be correctly formatted :)
type: AnswerComment

http://stackoverflow.com/q/47829141
has title: Plotting data from a Pandas Dataframe with distinct curves based on column values
type: Question
upvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/47829163
tagged with: python
downvote count: 1
tagged with: plot
favorite count: 0
type: AnsweredQuestion
has body: I have a Pandas dataframe which looks like this: City timestamp HUMI year Beijing 10100 43.0 2010 Chengdu 10100 81.2 2010 Beijing 10101 47.0 2010 Chengdu 10101 86.99 2010 Beijing 10102 43.0 2010 Chengdu 10102 86.99 2010 Beijing 10103 55.0 2010 Chengdu 10103 86.89 2010 Beijing 10104 51.0 2010 Chengdu 10104 86.79 2010 Beijing 10105 47.0 2010 Chengdu 10105 93.13 2010 I would like to plot HUMI as a function of timestamp, and have a curve per city. Is there a one-line command which would allow me to do this? I have already checked the Pandas visualization page and didn't see it (or miss it). Thanks in advance.
accepted answer: http://stackoverflow.com/a/47829163
tagged with: pandas
score: -1

http://stackoverflow.com/a/47850480
score: 1
downvote count: 0
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/47850352
has body: The key point here is Advanced indexing always returns a copy of the data In your second example you're not using the index to return anything. You're only using the index to modify the values. So the object that you're modifying is the original object. Not the copy.

http://stackoverflow.com/comment/82656863
score: 0
has text: Done! Thanks for the feedback.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47846256

http://stackoverflow.com/q/47709795
tagged with: python
has comment: http://stackoverflow.com/comment/82380039
possible better answer: http://stackoverflow.com/a/47710296
has answer: http://stackoverflow.com/a/47710296
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/82379311
has title: How to make a string interpreted as a condition with Python?
has comment: http://stackoverflow.com/comment/82380193
has comment: http://stackoverflow.com/comment/82379397
has comment: http://stackoverflow.com/comment/82379721
has comment: http://stackoverflow.com/comment/82384835
has body: I need to use the following syntax to filter the list operations: a = [ope for ope in operations if ope[0] == 1] The if statement condition is variable and may contain multiple conditions: a = [ope for ope in operations if ope[0] == 1 and ope[1] == "test"] I use a function to build the condition and return it as a string: &gt;&gt;&gt;&gt; c = makeCondition(**{"id": 1, "title": 'test'}) &gt;&gt;&gt;&gt; c "ope[0] == 1 and ope[1] == 'test'" Is there a way to integrate the c variable into the list filtering? Something like this (of course, the c variable is evaluated as a string in the below example): a = [ope for ope in operations if c] Thanks for help!
tagged with: python-3.x
tagged with: conditional-statements
accepted answer: http://stackoverflow.com/a/47710198
type: Question
tagged with: if-statement
answer count: 2
has answer: http://stackoverflow.com/a/47710198
linked to: http://stackoverflow.com/q/47769705

http://stackoverflow.com/q/47733928
type: Question
answer count: 2
type: UnansweredQuestion
tagged with: multithreading
tagged with: python
has answer: http://stackoverflow.com/a/47734030
has body: Using the threading library, I am attempting to pass down a variety of args/keyword args into the threading function. There are three different situations. Each one consists of a function ran prior to the threading function, which passes down the options to the threading function to tell it what function to call for the threading, and the arguments. In some situations, there will be keyword arguments, in some arguments, and in some, none. Here is the sample code of the threading function: def create_some_threads(my_target, *my_args, **my_keyword_args): for DeviceName in Devices: device_ip = Devices[DeviceName]['mgmt_ip'] my_thread = threading.Thread(target=my_target, args=(device_ip, DeviceName, *my_args, **my_keyword_args)) my_thread.start() Unfortunately, I get the error: my_thread = threading.Thread(target=my_target, args=(device_ip, DeviceName, *args, **kwargs)) ^ SyntaxError: invalid syntax Here is the function where I call in the *my_args: pingable_devices = {} unpingable_devices = {} with open(os.devnull, "wb") as limbo: print("\n[+] Progress:\n") pbar = tqdm(total=100) my_args = (pingable_devices, unpingable_devices, pbar, limbo) my_target = ping_em_all create_some_threads(my_target, *my_args) The problem is, for each function I use prior to calling the threading function, there are a different set of arguments/keyword arguments that I will call. I attempted to make this a function on its own, but if I can't run it something like this, then I may have to explore other avenues. Edit: This first problem was solved by unutbu, but now I have encountered a second problem. It seems the function called by the threading function is not recognizing the variables passed into threading, my_args. Error is below: Exception in thread Thread-4: Traceback (most recent call last): File "/usr/lib/python2.7/threading.py", line 801, in __bootstrap_inner self.run() File "/usr/lib/python2.7/threading.py", line 754, in run self.__target(*self.__args, **self.__kwargs) File "Automat…
has title: Passing *args or **kwargs into threading.Thread()
linked to: http://stackoverflow.com/q/291978
has answer: http://stackoverflow.com/a/58783653
score: 0

http://stackoverflow.com/comment/82396570
comment on: http://stackoverflow.com/q/47718013
type: Comment
score: 0
type: QuestionComment
has text: What do you want to avoid exactly? You want to avoid the legend avoiding something?

http://stackoverflow.com/comment/82530860
type: QuestionComment
comment on: http://stackoverflow.com/q/47784721
has text: Please post a [MCVE].
score: 0
type: Comment

http://stackoverflow.com/q/47698744
has title: Python pandas to excel UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 11
favorite count: 0
tagged with: encoding
has comment: http://stackoverflow.com/comment/82359006
has comment: http://stackoverflow.com/comment/82459749
has answer: http://stackoverflow.com/a/50255022
possible better answer: http://stackoverflow.com/a/51980885
accepted answer: http://stackoverflow.com/a/47803619
has answer: http://stackoverflow.com/a/51980885
type: Question
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/82499398
answer count: 3
has comment: http://stackoverflow.com/comment/82358156
downvote count: 1
tagged with: dataframe
tagged with: python
has body: After the web scraping of an e-commerce web site I have saved all the data into a pandas dataframe. Well, when I'm trying to save my pandas dataframe to an excel file but I get the following error: Traceback (most recent call last): File "&lt;ipython-input-7-3dafdf6b87bd&gt;", line 2, in &lt;module&gt; sheet_name='Dolci', encoding='iso-8859-1') File "C:\ProgramData\Anaconda2\lib\site-packages\pandas\core\frame.py", line 1466, in to_excel excel_writer.save() File "C:\ProgramData\Anaconda2\lib\site-packages\pandas\io\excel.py", line 1502, in save return self.book.close() File "C:\ProgramData\Anaconda2\lib\site-packages\xlsxwriter\workbook.py", line 299, in close self._store_workbook() File "C:\ProgramData\Anaconda2\lib\site-packages\xlsxwriter\workbook.py", line 607, in _store_workbook xml_files = packager._create_package() File "C:\ProgramData\Anaconda2\lib\site-packages\xlsxwriter\packager.py", line 139, in _create_package self._write_shared_strings_file() File "C:\ProgramData\Anaconda2\lib\site-packages\xlsxwriter\packager.py", line 286, in _write_shared_strings_file sst._assemble_xml_file() File "C:\ProgramData\Anaconda2\lib\site- packages\xlsxwriter\sharedstrings.py", line 53, in _assemble_xml_file self._write_sst_strings() File "C:\ProgramData\Anaconda2\lib\site- packages\xlsxwriter\sharedstrings.py", line 83, in _write_sst_strings self._write_si(string) File "C:\ProgramData\Anaconda2\lib\site- packages\xlsxwriter\sharedstrings.py", line 110, in _write_si self._xml_si_element(string, attributes) File "C:\ProgramData\Anaconda2\lib\site-packages\xlsxwriter\xmlwriter.py", line 122, in _xml_si_element self.fh.write("""&lt;si&gt;&lt;t%s&gt;%s&lt;/t&gt;&lt;/si&gt;""" % (attr, string)) File "C:\ProgramData\Anaconda2\lib\codecs.py", line 706, in write return self.writer.write(data) File "C:\ProgramData\Anaconda2\lib\codecs.py", line 369, in write data, consumed = self.encode(object, self.errors) UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 11: or…
tagged with: utf-8
upvote count: 4
has answer: http://stackoverflow.com/a/47803619

http://stackoverflow.com/comment/82392045
score: 0
comment on: http://stackoverflow.com/q/47715337
type: Comment
type: QuestionComment
has text: @MattR thanks for raising this as well. What would be your advice to tackle this problem?

http://stackoverflow.com/a/47762496
has comment: http://stackoverflow.com/comment/82486682
has comment: http://stackoverflow.com/comment/82488085
score: 0
type: Answer
has body: I don't think you need a multiprocessing approach to handle this case. Instead you can simply use Popen.poll to check whether the subprocess has terminated. I think something like this should work p = subprocess.Popen(['mongoimport', '-d', 'tfg', '-c', 'myCol', '--type', 'csv', '--file', './myFile.csv', '--headerline'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) while p.poll() is None: # shows and updates the progress bar while mongoimpor self.showProgress() if p.returncode != 0: raise Exception("mongoimport terminated with exit code {}".format(p.returncode))
answers question: http://stackoverflow.com/q/47762190

http://stackoverflow.com/q/47771698
score: 0
tagged with: form-submit
has body: I am tryping to scrape data from "https://pagesjaunes.fr". I on order to scrape the data from pagesjaunes: E-mail, adress etc I have first to submit the data in When I search in the network chrome debuger to see the form data that is sent i can see a bunch of data that is probably generated on the fly by javascript. and here is my python code for the spider: import scrapy from scrapy_splash import SplashRequest class PagesJaunes(scrapy.Spider): name="pagesjaunes" allowed_domains = [".fr", ".com"] start_urls = ["https://www.pagesjaunes.fr"] def parse(self, response): return scrapy.FormRequest.from_response(response, formdata = { "quoiqui": "macon", "ou":"bordeaux" }, callback = self.parse_page2) def parse_page2(self, response): self.logger.info("%s page visited", response.url) But it shows me this error: 2017-12-12 13:33:11 [scrapy.utils.log] INFO: Scrapy 1.4.0 started (bot: scrapybot) 2017-12-12 13:33:11 [scrapy.utils.log] INFO: Overridden settings: {'EDITOR': '/usr/bin/nano', 'SPIDER_LOADER_WARN_ONLY': True} 2017-12-12 13:33:11 [scrapy.middleware] INFO: Enabled extensions: ['scrapy.extensions.corestats.CoreStats', 'scrapy.extensions.telnet.TelnetConsole', 'scrapy.extensions.memusage.MemoryUsage', 'scrapy.extensions.logstats.LogStats'] 2017-12-12 13:33:11 [scrapy.middleware] INFO: Enabled downloader middlewares: ['scrapy.downloadermiddlewares.httpauth.HttpAuthMiddleware', 'scrapy.downloadermiddlewares.downloadtimeout.DownloadTimeoutMiddleware', 'scrapy.downloadermiddlewares.defaultheaders.DefaultHeadersMiddleware', 'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware', 'scrapy.downloadermiddlewares.retry.RetryMiddleware', 'scrapy.downloadermiddlewares.redirect.MetaRefreshMiddleware', 'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware', 'scrapy.downloadermiddlewares.redirect.RedirectMiddleware', 'scrapy.downloadermiddlewares.cookies.CookiesMiddleware', 'scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware', 'scrapy.downloadermiddlewa…
has title: Scrapy FormRequest.from_response error
answer count: 1
has comment: http://stackoverflow.com/comment/82509238
tagged with: web-scraping
has comment: http://stackoverflow.com/comment/82509330
tagged with: scrapy
has comment: http://stackoverflow.com/comment/82507379
type: Question
has comment: http://stackoverflow.com/comment/82509174
tagged with: javascript
tagged with: python
has comment: http://stackoverflow.com/comment/82507439
has comment: http://stackoverflow.com/comment/82508074
has answer: http://stackoverflow.com/a/47774713
accepted answer: http://stackoverflow.com/a/47774713
type: AnsweredQuestion

http://stackoverflow.com/q/47831826
downvote count: 0
upvote count: 1
score: 1
answer count: 1
favorite count: 0
has title: Reading attributes of .msg file
type: Question
tagged with: msg
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47832738
has comment: http://stackoverflow.com/comment/82627968
has comment: http://stackoverflow.com/comment/82628192
has body: I am trying to read a .msg file to get the sender, recipients, and title. I'm making this script for my workplace where I'm only allowed to install default python libraries so I want to use the email module to do this. On the python website I found some examples of using the email module. https://docs.python.org/3/library/email.examples.html Near the end of the page it talks about getting the sender, subject and recipient. I've tried using this code like this: # Import the email modules we'll need from email import policy from email.parser import BytesParser with open('test_email.msg', 'rb') as fp: msg = BytesParser(policy=policy.default).parse(fp) # Now the header items can be accessed as a dictionary, and any non-ASCII will # be converted to unicode: print('To:', msg['to']) print('From:', msg['from']) print('Subject:', msg['subject']) This results in an output: To: None From: None Subject: None I checked the file test_email.msg, it is a valid email. When I add a line of code print(msg) I get an output of a garbled email the same as if I opened the .msg file in notepad. Can anybody suggest why the email module isn't finding the sender/recipient/subject correctly?
has comment: http://stackoverflow.com/comment/82627507
has comment: http://stackoverflow.com/comment/82627567
has comment: http://stackoverflow.com/comment/82627963
tagged with: email
has comment: http://stackoverflow.com/comment/82627652

http://stackoverflow.com/q/47770891
tagged with: yocto
has comment: http://stackoverflow.com/comment/82551250
has comment: http://stackoverflow.com/comment/82508992
tagged with: scipy
has answer: http://stackoverflow.com/a/47869912
has comment: http://stackoverflow.com/comment/82695447
favorite count: 0
type: Question
tagged with: openembedded
tagged with: bitbake
has comment: http://stackoverflow.com/comment/85606677
has body: I'm currently trying to corss-compile scipy for open-embedded but the bitbake build failed with the error NOTE: Executing SetScene Tasks NOTE: Executing RunQueue Tasks ERROR: python-scipy-1.0.0-r0 do_compile: python setup.py build execution failed. ERROR: python-scipy-1.0.0-r0 do_compile: Function failed: do_compile (log file is located at /home/somewhere_in_my_home_folder/build_dir/tmp/work/core2-64-idp-linux/python-scipy/1.0.0-r0/temp/log.do_compile.2788) ERROR: Logfile of failure stored in: /home/somewhere_in_my_home_folder/build_dir/tmp/work/core2-64-idp-linux/python-scipy/1.0.0-r0/temp/log.do_compile.2788 Log data follows: | DEBUG: Executing shell function do_compile | Traceback (most recent call last): | File "setup.py", line 418, in &lt;module&gt; | setup_package() | File "setup.py", line 398, in setup_package | from numpy.distutils.core import setup | ImportError: No module named numpy.distutils.core | ERROR: python setup.py build execution failed. | WARNING: exit code 1 from a shell command. | ERROR: Function failed: do_compile (log file is located at /home/somewhere_in_my_home_folder/build_dir/tmp/work/core2-64-idp-linux/python-scipy/1.0.0-r0/temp/log.do_compile.2788) ERROR: Task (/home/somewhere_in_my_home_folder/recipes-ros/python-scipy/python-scipy_1.0.0.bb:do_compile) failed with exit code '1' I already spend searching several hours for recipe which works, but without any success. The only thing I found about this error was here. My recipe looks like this DESCRIPTION = "SciPy" SECTION = "devel/python" LICENSE = "CLOSED" PYPI_PACKAGE = "scipy" inherit pypi setuptools distutils DEPENDS_${PN} = "python-numpy python-setuptools python-distutils" RDEPENDS_${PN} = "python-numpy python-setuptools python-distutils" S = "${WORKDIR}/scipy-1.0.0" SRC_URI[md5sum] = "53fa34bd3733a9a4216842b6000f7316" SRC_URI[sha256sum] = "87ea1f11a0e9ec08c264dc64551d501fa307289460705f6fccd84cbfc7926d10" Any ideas on how to crosscompile scipy oder on how to fix this error? edit 1: my…
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85607613
tagged with: python
has comment: http://stackoverflow.com/comment/85607874
has comment: http://stackoverflow.com/comment/82579730
downvote count: 0
has title: Cross compiling scipy for open-embedded
score: 1
upvote count: 1
answer count: 1

http://stackoverflow.com/q/47851566
has body: I would like to darken one image based on the mask of an edge-detected second image. Image 1: Original (greyscale) image Image 2: Edge detected (to be used as mask) Image 3: Failed example showing cv2.subtract processing In my failed example (Image 3), I subtracted the white pixels (255) from the original image but what I want to do is DARKEN the original image based on a mask of the edge detected image. In this article: How to fast change image brightness with python + OpenCV?, Bill Gates describes how he converts the image to HSV, splits out then modifies Value, and then finally merges back. This seems like a reasonable approach but I only want to modify the Value where the mask is white i.e. the edge exists. Ultimately, I am trying to enhance the edge of a low resolution thermal video stream in a similar way to the FLIR One VividIR technology. I believe that I've made it really far as a complete novice to image processing, OpenCV and Python but after days now of trying just about every function OpenCV offers, I've got myself stuck.
linked to: http://stackoverflow.com/q/32609098
has comment: http://stackoverflow.com/comment/82670186
tagged with: opencv
type: AnsweredQuestion
upvote count: 2
score: 1
has comment: http://stackoverflow.com/comment/82694150
answer count: 1
tagged with: image-processing
has answer: http://stackoverflow.com/a/47851810
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82667837
accepted answer: http://stackoverflow.com/a/47851810
has title: OpenCV & Python: How to decrease brightness using binary mask?
tagged with: python

http://stackoverflow.com/comment/82429228
comment on: http://stackoverflow.com/q/47734342
has text: You could give your ContextManager an attribute that it checks in its `__enter__` method. So `with context(condition):`, then don't run any of the `__enter__` logic if `condition` is `False`. (A bit hacky!)
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/a/47775293
downvote count: 1
score: 19
answers question: http://stackoverflow.com/q/47775220
accepted answer of: http://stackoverflow.com/q/47775220
type: Answer
has body: Pandas.DataFrame.plot() per default uses index for plotting X axis, all other numeric columns will be used as Y values. So setting year column as index will do the trick: total_year.set_index('year').plot(figsize=(10,5), grid=True)
upvote count: 20
type: AcceptedAnswer

http://stackoverflow.com/comment/82638712
type: Comment
has text: Thanks alot! thats indeed a very good option, but this method is really good for minimum and maximum values in a dataframe, but cant be used for other values, right?
type: AnswerComment
comment on: http://stackoverflow.com/a/47836618
score: 0

http://stackoverflow.com/q/47788079
type: UnansweredQuestion
tagged with: python
tagged with: python-os
has title: How to get a filtered list of files in a folder
has answer: http://stackoverflow.com/a/47789575
downvote count: 0
answer count: 1
has body: I am trying to get a filtered (or patterned though I barely touch the pattern content) file list in a folder. My initial approach was with glob: list_files2 = os.listdir(accordingto) movable = set() n = 0 for f in list_files2: name, ext = os.path.splitext(f) name = name.rsplit("_", 1)[0] movable.add(name) for m in movable: family = glob("{}{}*".format(dir, m)) for f in family: # f is absolute path and needs to be relative shutil.move(f, target+f) # &lt;- problem is here n += 1 which works nearly as I expected except for the fact that it returns an absolute path while I wanted a relative one (only the filename that is) to append it to the destination folder. To make it more clear I have a folder with various images grouped in "families" which derive from the same original image. E.g. family: 71_157,23_850 images: 71_157,23_850_1.jpg, 71_157,23_850_1.png, 71_157,23_850_3.jpg etc I know I can process every item returned by glob but it seems a bit circular as approach. My second approach was with os.scandir: x = [f.name for f in os.scandir('images') if f.name.startswith(family in movable)] which of course does not work at all though it works for a specific "family" of images e.g. for 51_332,-5_545 family x = [f.name for f in os.scandir('images') if f.name.startswith('51_332,-5_545')] and I could concatenate the results in a loop for example. So, my question(s) are: Is there a way to return a relative path with glob? Or I am stuck with absolute paths? How can I get a filtered list of files with os.scandir in a "pythonic" manner?
score: 1
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/82537263
type: Question
tagged with: python-3.x

http://stackoverflow.com/q/47817665
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82655080
tagged with: python
has title: Python Selenium Chrome Disable Pop Up Blocker
has body: For some reason I can not figure out how to disable the pop up blocker (to allow pop up windows to work). This use to work, so I am guessing it has something to do with the new version of Chrome/Chromedriver? Below is some sample code, that I know use to work, but now when a pop up happens, I do not even see the icon in the top right, where you can allow the pop up or not. I did also try using the prefs found here to disable the pop up blocker, but that did not work ether. If anyone has a solution, it would be much appreciated! from selenium import webdriver from selenium.webdriver.chrome.options import Options request_url = 'https://www.example.com' chrome_options = Options() chrome_options.add_argument("--disable-popup-blocking") driver = webdriver.Chrome(chrome_options=chrome_options) driver.get(request_url)
tagged with: selenium-chromedriver
downvote count: 0
tagged with: selenium
has comment: http://stackoverflow.com/comment/82658849
score: 7
upvote count: 7
tagged with: google-chrome
favorite count: 0
type: Question
tagged with: python-3.x

http://stackoverflow.com/q/47850504
tagged with: python
upvote count: 6
tagged with: tradingview-api
answer count: 0
tagged with: pyqt
downvote count: 0
has title: How can i integrate tradingview chart with pyqt?
score: 6
tagged with: integration
has body: i want to integrate https://www.tradingview.com/widget/advanced-chart/ with my application. Primarily i just want to be able to display the chart and be able to click the buttons etc inside a pyqt app normally but i would probably then also want to know which rate i am clicking on for python to see. Perhaps even add a new function to the chart so that i can click on for example a 'BUY' button, drag a slider to the right price and then send that information to qt/python so that i can then process it in python, maybe send info from python too and run a javascript function... What is the best way to go about this? Edit: Iv'e tried integrating a webengineview in my app and pointing to the code, but unfortunately this crashes the whole system(i think the graphics card locks up). I think this might have something to do with my nouveu drivers(linux). Anyone know how to fix this?
favorite count: 0
type: Question
tagged with: qt
type: UnansweredQuestion

unity-game-engine
tags question: http://stackoverflow.com/q/47855380
type: Tag
tag name: unity-game-engine
tags question: http://stackoverflow.com/q/47772806

http://stackoverflow.com/a/47812521
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47812420
has comment: http://stackoverflow.com/comment/82596104
upvote count: 5
score: 5
type: Answer
has body: There are python-daemon and python-service packages that you may use to create python-based daemons and/or services. Though I suppose it might be enough just to use nohup python path/to/script.py &amp;.
accepted answer of: http://stackoverflow.com/q/47812420

http://stackoverflow.com/a/47839333
accepted answer of: http://stackoverflow.com/q/47828486
score: 0
has body: here is what is said in the documentation for QuerySelectedField : The data property actually will store/keep an ORM model instance, not the ID. Now I understand your problem change your view like this : @auth.route('/register', methods=['GET', 'POST']) def register(): """ Handle requests to the /register route Add an employee to the database through the registration form """ form = RegistrationForm() if form.validate_on_submit(): employee = Employee( emp_number=form.emp_number.data, email=form.email.data, username=form.username.data, emp_name=form.emp_name.data, password=form.password.data) project=form.project.data #an instance of Project Class subproject=form.subproject.data #an instance of SubProject Class project.pro_subproject.append(subproject) project.pro_employee.append(employee) # add employee to the database db.session.add(employee) db.session.add(subproject) db.session.add(project) db.session.commit() flash('You have registered successfully. You can now log in.') Here is an explanation of that : A one to many relationships places a foreign key on the child table referencing the parent. relationship() is then specified on the parent, as referencing a collection of items represented by the child: This means in your project table the field pro_employees and pro_subproject are lists of employee (n) and sub_project(n).
answers question: http://stackoverflow.com/q/47828486
has comment: http://stackoverflow.com/comment/82678208
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82662646
type: Answer

http://stackoverflow.com/q/47731611
has body: I am desperately trying to perform a simple search operation on elasticsearch, but fail since hours. This is my code: res = es.search(index="people", doc_type="test", body={"query":{"match":{"name": "john"}}}) I saw this many times on the internet, but I get always an error and have no clue what is wrong with my code snippet. Traceback (most recent call last): File "./es_request.py", line 14, in &lt;module&gt; res = es.search(index="people", doc_type="test", body={"query":{"match":{"name": "john"}}}) File "/usr/local/lib/python3.4/dist-packages/pyelasticsearch/client.py", line 93, in decorate return func(*args, query_params=query_params, **kwargs) TypeError: search() missing 1 required positional argument: 'query' Where do I have to write the required 'query'? I am trying to perform the search for name and last name.
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: elasticsearch
tagged with: python
tagged with: elasticsearch-py
has title: Elasticsearch Python API results in "search() missing 1 required positional argument" on a simple query
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47731908
accepted answer: http://stackoverflow.com/a/47731908
tagged with: pyelasticsearch
downvote count: 0
score: 1
upvote count: 1
answer count: 1

http://stackoverflow.com/a/47797074
answers question: http://stackoverflow.com/q/47796488
has body: Try: PyMuPDF Python recipe: PDF TEXT EXTRACTION USING FITZ / MUPDF (PYMUPDF): #!/usr/bin/env python """ Created on Wed Jul 29 07:00:00 2015 @author: Jorj McKie Copyright (c) 2015 Jorj X. McKie The license of this program is governed by the GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007. See the "COPYING" file of this repository. This is an example for using the Python binding PyMuPDF of MuPDF. This program extracts the text of an input PDF and writes it in a text file. The input file name is provided as a parameter to this script (sys.argv[1]) The output file name is input-filename appended with ".txt". Encoding of the text in the PDF is assumed to be UTF-8. Change the ENCODING variable as required. ------------------------------------------------------------------------------- """ import fitz # this is PyMuPDF import sys, json ENCODING = "UTF-8" def SortBlocks(blocks): ''' Sort the blocks of a TextPage in ascending vertical pixel order, then in ascending horizontal pixel order. This should sequence the text in a more readable form, at least by convention of the Western hemisphere: from top-left to bottom-right. If you need something else, change the sortkey variable accordingly ... ''' sblocks = [] for b in blocks: x0 = str(int(b["bbox"][0]+0.99999)).rjust(4,"0") # x coord in pixels y0 = str(int(b["bbox"][1]+0.99999)).rjust(4,"0") # y coord in pixels sortkey = y0 + x0 # = "yx" sblocks.append([sortkey, b]) sblocks.sort() return [b[1] for b in sblocks] # return sorted list of blocks def SortLines(lines): ''' Sort the lines of a block in ascending vertical direction. See comment in SortBlocks function. ''' slines = [] for l in lines: y0 = str(int(l["bbox"][1] + 0.99999)).rjust(4,"0") slines.append([y0, l]) slines.sort() return [l[1] for l in slines] def SortSpans(spans): ''' Sort the spans of a line in ascending horizontal direction. See comment in SortBlocks function. ''' sspans = [] for s in spans: x0 = str(int(s["bbox"][0] + 0.99999)).rjust(4,"0") sspans.append…
type: Answer
upvote count: 4
score: 4
accepted answer of: http://stackoverflow.com/q/47796488
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/82664947
has text: Thank you for your response, it is much appreciated! Here is the latest. See below the issue: <><><><><><><><><><><><><><><><><><> C:\Users\ths>activate tensorflow36 (tensorflow36) C:\Users\ths>pip install --ignore-installed --upgrade tensorflow Collecting tensorflow Could not find a version that satisfies the requirement tensorflow (from versions: ) No matching distribution found for tensorflow (tensorflow36) C:\Users\ths> <><><><><><>?><><><><><><><><><><><><><><><><><><><><> BTW, this is MS Windows 10 environment.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47802151

http://stackoverflow.com/comment/82612007
has text: `Open Door` should work, and doesn't require knowledge of the hostname.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47824608

http://stackoverflow.com/comment/133893031
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47741568
type: Comment
has text: For example, the [standard library defines a whole bunch of stuff directly in the `__init__.py` of the `collections` package](https://github.com/python/cpython/blob/main/Lib/collections/__init__.py). This is a simple way of working with the fact that `collections` was a simple module originally, before `collections.abc` was added. Similarly, [`json`](https://github.com/python/cpython/blob/main/Lib/json/__init__.py) defines the main function-based interface in `__init__.py`, while shuffling the support classes off to separate files.

http://stackoverflow.com/a/47853184
answers question: http://stackoverflow.com/q/47853134
has comment: http://stackoverflow.com/comment/82677508
has comment: http://stackoverflow.com/comment/82671285
downvote count: 2
type: Answer
has body: Solution: put a '^' character in front of '(' like this: os.system('test^(1).exe')
upvote count: 3
has comment: http://stackoverflow.com/comment/82672363
has comment: http://stackoverflow.com/comment/82677686
score: 1

http://stackoverflow.com/a/66813409
answers question: http://stackoverflow.com/q/47769348
upvote count: 2
has body: I just had the same issue. The solution was: pip uninstall pytest-flask
type: Answer
score: 2
downvote count: 0

http://stackoverflow.com/comment/82460860
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47749744
has text: I edited your question to give you a working example, since the post has been closed. But it got rejected :P

http://stackoverflow.com/a/47730486
has comment: http://stackoverflow.com/comment/82424203
upvote count: 8
type: Answer
has comment: http://stackoverflow.com/comment/82423075
has comment: http://stackoverflow.com/comment/82422339
answers question: http://stackoverflow.com/q/47730259
has body: urllib is a standard python library (built-in) so you don't have to install it. just import it if you need to use request by: import urllib.request if it's not work maybe you compiled python in wrong way, so be kind and give us more details.
has comment: http://stackoverflow.com/comment/82422485
score: 7
downvote count: 1

http://stackoverflow.com/comment/82582242
type: Comment
has text: @tobias_k Well then make it *prettier* instead :-). If you followed the documentation, you'd use `repeat(x, n)`. And since you're willing to create a list, you could simply use `[x] * n`.
comment on: http://stackoverflow.com/a/47803195
score: 0
type: AnswerComment

http://stackoverflow.com/comment/82488795
has text: Yes. I got that problem several times whenever I try to merge it's not a big deal just annoying.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47763572
score: 0

http://stackoverflow.com/comment/82639950
type: QuestionComment
has text: Well, if your goal is to hide and show in live time, Javascript (AJAX) is not an option, it is in fact mandatory. I don't see any way with built-in Django features for you to acheive that.
comment on: http://stackoverflow.com/q/47838059
score: 0
type: Comment

http://stackoverflow.com/comment/82675574
has text: @DanielPryden: indeed. However, I am mostly interested about whether a such concept exists in any language. Also, python has type annotations, and typescript adds similar functionality to javascript, so something similar could be achieved
score: 0
comment on: http://stackoverflow.com/q/47855082
type: QuestionComment
type: Comment

http://stackoverflow.com/q/47723231
upvote count: 9
has comment: http://stackoverflow.com/comment/82633458
tagged with: http://stackoverflow.com/tag/json
has answer: http://stackoverflow.com/a/47748892
tagged with: python
possible better answer: http://stackoverflow.com/a/47805332
has comment: http://stackoverflow.com/comment/82643510
score: 9
answer count: 2
has title: django rest framework list query customize json array result response because of date formatting
accepted answer: http://stackoverflow.com/a/47748892
has body: I have this Django REST API that I want to customize the list query result for the json response. The reason is because of date formatting and potentially other formatting as well. This is the Rest API, the issue is created_at I want it to formatted like this: ('%Y-%m-%d %H:%M'). The following code doesn't have any formatting, it will just list and create a json on the result. @api_view(['POST']) def employee_get_list_by_page(request): val_params = ["id", "username","first_name","last_name","created_at"] employee_list = Employee.objects.all().values(*val_params).order_by('id') page = request.GET.get('page', request.POST['page']) paginator = Paginator(employee_list, request.POST['page_limit']) try: employees = paginator.page(page) except PageNotAnInteger: employees = paginator.page(request.POST['page']) except EmptyPage: employees = paginator.page(paginator.num_pages) return Response(list(employees), status=status.HTTP_200_OK) This is the model. Notice I have .as_dict() function. For individual record like using emp = Employee.objects.get(id=6), I can do like this emp.as_dict() and the result will have the formatted date in created_at. class Employee(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='employee') company = models.ForeignKey(Company) username = models.CharField(max_length=30, blank=False) first_name = models.CharField(max_length=30, blank=False) last_name = models.CharField(max_length=30, blank=False) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.user.username def as_dict(self): return {"id": "%d" % self.id, "username": self.username if self.username else "", "first_name": self.first_name if self.first_name else "", "last_name": self.last_name if self.last_name else "", "created_at":self.created_at.strftime('%Y-%m-%d %H:%M')} This is the json response result of the list. Notice the date is not formatted. [ { "id": 7, "username": "mick", "first_name": "zack", "last_name": "ray", …
downvote count: 0
tagged with: django
tagged with: django-rest-framework
favorite count: 0
has comment: http://stackoverflow.com/comment/82457267
type: Question
has answer: http://stackoverflow.com/a/47805332
type: AnsweredQuestion
tagged with: rest

http://stackoverflow.com/q/47716948
linked to: http://stackoverflow.com/q/1912434
has comment: http://stackoverflow.com/comment/82395805
score: 1
has answer: http://stackoverflow.com/a/47718031
has comment: http://stackoverflow.com/comment/82394861
has comment: http://stackoverflow.com/comment/82396038
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/82396228
has comment: http://stackoverflow.com/comment/82396324
has answer: http://stackoverflow.com/a/47717156
accepted answer: http://stackoverflow.com/a/47717156
type: Question
upvote count: 2
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/47717408
has comment: http://stackoverflow.com/comment/82395872
has comment: http://stackoverflow.com/comment/82394907
has answer: http://stackoverflow.com/a/47717408
downvote count: 1
has body: Is there a way in regex to find a string if it occurs twice in given structures (i.e. like in XML parsing)? This code obviously does not work as it finds the first tag and then the last closing tag: re.findall(r'<(.+)>([\s\S]*)</(.+)>', s) So is there a way to tell regex that the third match should be the same as the first? Full code: import re s = ''' 1 52 Abc 21 ''' matches = re.findall(r'<(.+)>([\s\S]*)</(.+)>', s) for match in matches: print(match) Result should be all the tags with the contents: [('a1', '\n \n 1\n \n \n 52\n \n \n \n Abc\n \n \n'), ('a2', '\n 1\n '), ...] Note: I am not looking for a complete xml parsing package. The question is specificly about solving the given problem with regex.
favorite count: 0
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/1732348
has title: Finding two matches with the same string in regex
answer count: 3

http://stackoverflow.com/q/47742417
tagged with: python
has comment: http://stackoverflow.com/comment/82445238
accepted answer: http://stackoverflow.com/a/47742539
has title: How do I execute code that is taken as user input?
has comment: http://stackoverflow.com/comment/82445896
type: AnsweredQuestion
downvote count: 4
upvote count: 0
has comment: http://stackoverflow.com/comment/82444914
score: -4
answer count: 1
has answer: http://stackoverflow.com/a/47742539
has comment: http://stackoverflow.com/comment/82445314
favorite count: 0
type: Question
has body: Is there a way to actually take a well formatted input and execute it at an appropriate time? Something like: num = 5 command = input() # do something with command Now, if i enter "print(num)" as input, it should output 5
has comment: http://stackoverflow.com/comment/82444911
tagged with: input

http://stackoverflow.com/q/47831969
tagged with: python
score: -1
has body: My ndarray matrix is X with dimensions (2536,72) is an object type. I want to change the type to float 64, but before I have to delete rows containing ?. I have used this code but it doesn't work--> import numpy as np X1=np.delete(X,'?',axis=0) __main__:2: DeprecationWarning: using a non-integer array as obj in delete will result in an error in the future Traceback (most recent call last): File "&lt;ipython-input-89-34091147b19c&gt;", line 2, in &lt;module&gt; X1=np.delete(X,'?',axis=0) File "/anaconda3/envs/py36/lib/python3.6/site-packages/numpy/lib/function_base.py", line 4865, in delete obj = obj.astype(intp) ValueError: invalid literal for int() with base 10: '?' Any suggestion for that please??
answer count: 3
upvote count: 0
has answer: http://stackoverflow.com/a/47832454
has answer: http://stackoverflow.com/a/47833260
has answer: http://stackoverflow.com/a/47832490
downvote count: 1
favorite count: 0
type: Question
tagged with: numpy
has title: How to delete rows from a ndarray object when values inside are equal to?
type: UnansweredQuestion

http://stackoverflow.com/a/48407725
score: 0
has body: Telegram servers periodically send you 504 (gateway timeout) error on longpooling. Use webhook, instead longpooling.
type: Answer
answers question: http://stackoverflow.com/q/47850118

http://stackoverflow.com/comment/82481679
comment on: http://stackoverflow.com/a/47759641
type: Comment
type: AnswerComment
has text: Alex, there's a python API for ansible, you may want to give it a go: http://docs.ansible.com/ansible/latest/dev_guide/developing_api.html
score: 0

http://stackoverflow.com/comment/82536749
comment on: http://stackoverflow.com/q/47787214
has text: you are resetting my_data to empty list every time in the loop.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/82491252
type: Comment
comment on: http://stackoverflow.com/a/47726711
type: AnswerComment
score: 0
has text: yea sure! I'll put it on Github. Never actually used that before, but I'll keep you posted. I think you def deserve some credit for helping solve one of the most oddly challenging issues i've come across in my project aha

http://stackoverflow.com/q/47783833
has answer: http://stackoverflow.com/a/47789213
accepted answer: http://stackoverflow.com/a/47789213
has answer: http://stackoverflow.com/a/47784659
tagged with: dataframe
tagged with: python
tagged with: data-structures
type: AnsweredQuestion
has body: I have a list of transactions/tuples in Python with varying number or elements, like this: lst = [('apple','banana','carrots'),('apple',),('banana','carrots',)] I would like to store this list in a tabular form (preferably in a pd.DataFrame) such as this: apple banana carrots 0 1 1 1 1 1 0 0 2 0 1 1 But if try to convert directly using pd.DataFrame, I get his instead: pd.DataFrame(lst) 0 1 2 0 apple banana carrots 1 apple None None 2 banana carrots None How can I convert this type of list into a binary table?
tagged with: list
downvote count: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/47784080
possible better answer: http://stackoverflow.com/a/47784659
has answer: http://stackoverflow.com/a/47787051
answer count: 7
has answer: http://stackoverflow.com/a/47784051
has answer: http://stackoverflow.com/a/47784018
upvote count: 8
favorite count: 0
score: 8
type: Question
has answer: http://stackoverflow.com/a/47784827
has title: List of tuples into a binary table?

http://stackoverflow.com/comment/82445902
score: 0
type: Comment
has text: Thank you so much. Just to assure; 1. the first solution is to change the ajax.js $('#likes').ready(function(){ var comid; comid = $(this).attr("data-comid"); $.get('/home/like/', {comentario_id: comid}, function(data){ $('#like_count').html(data); $('#likes').hide(); }); }); 2. The second; add in .html onclick="functionToBind(event)", I have just copy and paste and the inspection tells me "Uncaught ReferenceError: functionToBind isn't definedat HTMLButtonElement.onclick". Is it I have to add something more?
type: AnswerComment
comment on: http://stackoverflow.com/a/47742737

http://stackoverflow.com/comment/82634757
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47829925
score: 0
has text: If you want to run multiple test suites, just pass them all to pybot (eg: `pybot suite1.robot suite2.robot ...` or, if they are all in a folder, you can do `pybot folder_with_tests`)

http://stackoverflow.com/a/47763311
accepted answer of: http://stackoverflow.com/q/47761883
has comment: http://stackoverflow.com/comment/82503476
downvote count: 0
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/47761883
has body: Here is an example showing a way of recursively checking if there is a oneOf property in the json supplied. You'll need to check the parent property if you specifically want to only check the 'schema' portion of the json. #!/usr/bin/env python import json def objectHasKey(object_,key_): _result = False if (type(object_)==dict): for _key in object_.keys(): print _key if (type(object_[_key])==dict): _dict = object_[_key] _result = objectHasKey(_dict,key_) if _key == key_: _result = True if _result: break return _result firstJSONText = ''' { "definitions": { "schema": { "type": "object", "properties": { "name": { "type": [ "string", "null" ] } } } } } ''' first = json.loads(firstJSONText) secondJSONText = ''' { "definitions": { "schema": { "oneOf": [ { "type": [ "null" ] }, { "type": [ "string" ], "enum": [ "NONE" ] } ] } } } ''' second = json.loads(secondJSONText) target = first if objectHasKey(target,'oneOf'): print "Handle oneOf with first" else: print "Handle default with first" target = second if objectHasKey(target,'oneOf'): print "Handle oneOf with second" else: print "Handle default with second" Example call with output csmu-macbook-pro-2:detect-if-a-json-schema-has-a-oneof-type-schema admin$ ./test-for-schema.py definitions schema type properties name type Handle default with first definitions schema oneOf Handle oneOf with second
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/q/47777683
type: Question
type: UnansweredQuestion
tagged with: python
tagged with: audit
has comment: http://stackoverflow.com/comment/82517920
score: 0
answer count: 0
has title: Python virtualenv unlinking python and module pyc files
has comment: http://stackoverflow.com/comment/82516652
tagged with: virtualenv
has body: I setup a python virtualenv. The folder is protected from writing by non-root users. When in the virtualenv I get some odd behavior. If I just start python, the system audit log way have an entry showing I attempted to unlink the virtualenv python site.pyc file. If I then run something like "import numpy", I will then get a slew of audit messages saying I tried to unlink all the .pyc files in the virtualenv python site-packages folder related to numpy. If I run the native python (not in the virutalenv) I do not get any of these audit messages. The really strange thing is that I have two "identical" systems. Same redhat package set, same virtualenv folder, same audit rules. However on the other system, I don't get the unlink messages in the audit. I'd appreciate any advice on how I might track down the cause of this

http://stackoverflow.com/q/47822318
tagged with: python-imageio
type: Question
tagged with: python
accepted answer: http://stackoverflow.com/a/47824983
possible better answer: http://stackoverflow.com/a/51174329
has answer: http://stackoverflow.com/a/47824983
has title: Cannot reshape array using imageio. Why?
has answer: http://stackoverflow.com/a/51174329
score: 2
upvote count: 2
type: AnsweredQuestion
answer count: 2
downvote count: 0
has body: I'm trying to mimic what this line of code does, using imageio : img_array = scipy.misc.imread('/Users/user/Desktop/IMG_5.png', flatten=True) img_data = 255.0 - img_array.reshape(784)` However when using imageio I get: img = imageio.imread('/Users/user/Desktop/IMG_5.png') img.flatten() Output: Image([212, 211, 209, ..., 192, 190, 191], dtype=uint8) img.reshape(1, 784) ValueError: cannot reshape array of size 2352 into shape (1,784) Can someone explain what is going on here, why is my image size 2352? I resized the image to 28x28 pixels before importing it.
favorite count: 0

http://stackoverflow.com/comment/82401711
has text: I can emphasize that it's the _second_ code section in my question that worked in ipython, and not the first. I wanted to reuse the same Mocker across several methods, but I see where the mistake is now. Thanks
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47717618
type: AnswerComment

http://stackoverflow.com/comment/82530021
has text: What is your opinion? Do you have some code that you have been working on? I'd suggest a generator.
score: 0
comment on: http://stackoverflow.com/q/47784159
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82510816
comment on: http://stackoverflow.com/q/47774699
has text: @gmas80 Looks pretty cythonised to me: https://ibb.co/jwhdAG
type: Comment
score: 1
type: QuestionComment

http://stackoverflow.com/comment/82566903
has text: For yellow, it would be all, but to find red, it would just the be the r value. And for green, the g value.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47802480

http://stackoverflow.com/q/47843388
has title: assign into multiple variable in same line in python
has answer: http://stackoverflow.com/a/47843448
type: AnsweredQuestion
answer count: 2
score: 1
downvote count: 0
upvote count: 1
duplicate of: http://stackoverflow.com/q/32127908
has body: I am using Jupyter Notebook for Python and also using Numpy Lib. Here is what i have tried import numpy as np arr = np.arange(10, 21) print(arr) slice_arr = arr[:5]= 6 print(slice_arr) print(arr) Output is : [10 11 12 13 14 15 16 17 18 19] 6 [ 6 6 6 6 6 15 16 17 18 19] But I thought slice_arr would be [ 6 6 6 6 6] as i am getting first 5 element from arr and assigning 6 to all 5 elements and then assigning to slice_arr How this statements would executed and How slice_arr value is 6? Does 6 is assigned separately to arr[:5] and slice_arr? If the assignment if from right to left then slice_arr should be [ 6 6 6 6 6] Thanks in advance
favorite count: 0
tagged with: jupyter-notebook
type: Question
tagged with: numpy
accepted answer: http://stackoverflow.com/a/47843698
has answer: http://stackoverflow.com/a/47843698
tagged with: python
possible better answer: http://stackoverflow.com/a/47843448

http://stackoverflow.com/comment/119420819
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47700674
has text: What if you are just querying a database? I don't have a 'mysite' other then the REST I am querying

http://stackoverflow.com/comment/82653751
type: AnswerComment
has text: pymongo only use **pure** mongo commands , mongoose is not pure mongo, as i know its from npm and for nodeJS
type: Comment
comment on: http://stackoverflow.com/a/47843970
score: 0

http://stackoverflow.com/comment/82668225
type: AnswerComment
has text: Thanks! i'm using ConEmu console, i test with windows cmd and it's works!
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47851938

http://stackoverflow.com/comment/82483678
score: 0
comment on: http://stackoverflow.com/q/47760496
has text: @albert I do call the script from within the same root dir.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47760634
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/47761937
answer count: 1
has comment: http://stackoverflow.com/comment/82482607
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82482839
has comment: http://stackoverflow.com/comment/82483523
accepted answer: http://stackoverflow.com/a/47761937
downvote count: 0
score: 1
upvote count: 1
tagged with: django-rest-framework
favorite count: 0
has title: DRF - Nested serializer disappears after parent is_valid() call
type: Question
has body: TLDR; (full description below) Valid field with nested serializer is dropped upon validation of parent serializer. I read some StackOverflow posts about similar cases, but there the field was dropped because of being read_only=True which is not my case. After POSTing valid object to CreateParentView(generics.CreateAPIView) I get Http 400 Bad request error. I ended up debugging the create() method. # parsed_data is a QueryDict prepared from request.POST and request.FILES # to fit the nested serializers format. -&gt; serializer.is_valid(raise_exception=True) (Pdb) parsed_data.keys() odict_keys(['parent_field_1', 'parent_field_2', 'parent_field_3', 'child']) (Pdb) from .serializers import CreateChildSerializer; ch = parsed_data.get('child'); new_child = CreateChildSerializer(data = ch); (Pdb) new_child.is_valid() True (Pdb) new_child.errors {} # the parent serializer is invalid and drops the 'child' key (Pdb) serializer.is_valid(); False (Pdb) serializer.data.keys() odict_keys(['parent_field_1', 'parent_field_2', 'parent_field_3']) The response is 400 (Bad Request), "{"child":["This field is required."]}" Dafuq, I just provided you with that, and you, sir, dropped it :-( End Of TLDR; Okay, lets have a look on the View, the Serializer and the Model. I'm using a toy model, my real one is too verbose to reproduce here. Lets start with the models.py - the Child and Parent models are OneToOneField relationship. # models.py class Parent(models.Model): objects = ParentManager() user = models.ForeignKey('auth.User', on_delete=models.CASCADE) parent_field_1 = models.BooleanField() parent_field_2 = models.CharField(max_length=10) parent_field_3 = models.CharField(max_length=10) class Child(models.Model): objects = ChildManager() parent = models.OneToOneField('Parent', on_delete=models.CASCADE) child_field_1 = ... The serializers are basically the DRF guide approach for nested serializers. # serializers.py class CreateParentSerializer(serializers.ModelSerializer): child = CreateC…
has comment: http://stackoverflow.com/comment/82482682

http://stackoverflow.com/comment/82486910
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47762325
has text: @CharlesDuffy I am interpreting the incoming data as latin-1 from stdin, then printing strings for which I get an error to a log file. My understanding is that latin-1 should still work. However, it seems as if there is something called `punycode` that I should be using...

http://stackoverflow.com/q/47821633
has comment: http://stackoverflow.com/comment/82606153
type: Question
has title: python pdfminer - KeyError 'AcroForm'
has comment: http://stackoverflow.com/comment/83045414
score: 3
has answer: http://stackoverflow.com/a/63066448
type: UnansweredQuestion
tagged with: pdfminer
has body: I have a script that is getting the attachment filename and if the ext indicates a pdf file, it runs it through the following code. However I'm receiving the KeyError below. I cannot find any information on how to correct or troubleshoot. I have successfully run PDF forms through this script previously, not sure why this is not functioning as expect. if ext == '.PDF' or ext == '.pdf': item_field_list = [] item_number = str(random.randint(1000000, 9999999)) #try: with tempfile.NamedTemporaryFile() as tmp: verify_item = 0 tmp.write(part.get_payload(decode=True)) parser = PDFParser(tmp) doc = PDFDocument(parser) fields = resolve1(doc.catalog['AcroForm'])['Fields'] Here is the traceback: Traceback (most recent call last): File "distributionitemimport.py", line 87, in &lt;module&gt; fields = resolve1(doc.catalog['AcroForm'])['Fields'] KeyError: 'AcroForm' When I do a print(doc.catalog) I get the following: {'MarkInfo': {'Marked': True}, 'Lang': b'en-US', 'Type': /'Catalog', 'StructTree Root': &lt;PDFObjRef:162&gt;, 'Pages': &lt;PDFObjRef:2&gt;}
tagged with: python
has comment: http://stackoverflow.com/comment/82605888
has comment: http://stackoverflow.com/comment/82606806
has comment: http://stackoverflow.com/comment/82607327
upvote count: 3
answer count: 1
downvote count: 0
favorite count: 0
tagged with: keyerror

http://stackoverflow.com/q/47851268
type: UnansweredQuestion
score: 0
tagged with: sqlite
answer count: 1
has comment: http://stackoverflow.com/comment/82667309
has comment: http://stackoverflow.com/comment/82668774
has comment: http://stackoverflow.com/comment/82669054
has comment: http://stackoverflow.com/comment/82668779
has body: I am trying to load a JSON dump of my Django Sqlite db into a fresh db, using manage.py loaddata. I am encountering the following django.db.utils.OperationalError, however: Could not load foo.Bar(pk=1): no such table: foo_bar The table is definitely present in the database, and all my migrations are applied, checked using showmigrations. So I am stumped as to what's going on. I would not be surprised if it's something simple, however. Would appreciate any suggestions. N.B: The db I'm trying to load the data into is just an empty file. Might that be the issue? Do I need to create the relevant tables in that fresh db before loading into it from the fixture?
has comment: http://stackoverflow.com/comment/82668967
type: Question
has title: Django - loaddata from JSON dump gives 'no such table' error
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/47851591
has comment: http://stackoverflow.com/comment/82669045
has comment: http://stackoverflow.com/comment/82667739
has comment: http://stackoverflow.com/comment/82668982
has comment: http://stackoverflow.com/comment/82669034
has comment: http://stackoverflow.com/comment/82667129
has comment: http://stackoverflow.com/comment/82667564

http://stackoverflow.com/comment/82566666
comment on: http://stackoverflow.com/q/47802570
type: Comment
type: QuestionComment
score: 0
has text: start with `df['firstcol'] = df['question#'].str[0]`

http://stackoverflow.com/comment/82603188
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47820360
has text: [Series.empty](http://pandas.pydata.org/pandas-docs/version/0.18/generated/pandas.Series.empty.html) tests if the entire Series is empty. If that is not your intent, then please post the desired result.

http://stackoverflow.com/a/47757988
has body: This is a common case among web development, so you need to use a MultiDict object for that, such as the MultiDict under http://werkzeug.pocoo.org/docs/0.13/datastructures/#werkzeug.datastructures.MultiDict Alternatively, you can use a defaultdict with a list, such as:: &gt;&gt;&gt; from collections import defaultdict &gt;&gt;&gt; d = defaultdict(list) &gt;&gt;&gt; d defaultdict(&lt;type 'list'&gt;, {}) &gt;&gt;&gt; d['a'].append(1) &gt;&gt;&gt; d['a'].append(2) &gt;&gt;&gt; d['b'].append(3) &gt;&gt;&gt; d defaultdict(&lt;type 'list'&gt;, {'a': [1, 2], 'b': [3]})
answers question: http://stackoverflow.com/q/47757946
upvote count: 0
downvote count: 1
type: Answer
score: -1

http://stackoverflow.com/q/47702406
type: Question
has title: Spark DataFrame - Get the average of two column combinations
tagged with: pyspark
accepted answer: http://stackoverflow.com/a/47702561
tagged with: python
type: AnsweredQuestion
score: 0
has body: How I get the average of Price for each combination of 2 columns? My DataFrame: relevantTable = df.select(df['Price'], df['B'], df['A']) looks like: +-------+------------+------------------+ | Price| B | A | +-------+------------+------------------+ | 0.2947| i3.xlarge| x| | 0.105| c4.large| x| | 0.2179| m4.xlarge| x| | 2.2534| m4.10xlarge| x| | 2.1801| m4.10xlarge| x| | 0.108| r4.large| x| | 0.108| r4.large| x| | 0.0213| i3.large| y| | 0.5572| i2.4xlarge| y| | 0.1542| c4.4xlarge| y| | 0.3624| m4.10xlarge| y| | 0.3596| m4.10xlarge| y| | 0.11| m4.large| x| | 0.4436| m4.2xlarge| x| | 0.1458| m4.2xlarge| y| ... and so on real huge set What would be a simple and scalable solution to get the average for all combinations of A and B?
tagged with: apache-spark
has comment: http://stackoverflow.com/comment/82365004
answer count: 1
has answer: http://stackoverflow.com/a/47702561

http://stackoverflow.com/q/47787413
tagged with: pycharm
answer count: 1
has comment: http://stackoverflow.com/comment/82536234
accepted answer: http://stackoverflow.com/a/47787770
has comment: http://stackoverflow.com/comment/82536072
has title: I am unable to import apiai on pycharm?
type: AnsweredQuestion
score: 0
upvote count: 1
downvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/47787770
has body: I tried import apiai on pycharm, but it didn't work so I ran pip install apiai then freezed to the requirements.txt it still didn't work on pycharm. I went and tested my code in the prompt after i ran it in the env environment and it worked just fine. My question is how can i make it work on pycharm too ?
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82535987

http://stackoverflow.com/comment/82366126
type: AnswerComment
type: Comment
has text: I'm not clear on how that solves the problem. Also, if I separately have a unique index value where I'm trying to fill the end date, I think that will throw an error.
comment on: http://stackoverflow.com/a/47701906
score: 0

http://stackoverflow.com/q/47832114
downvote count: 0
tagged with: python
has answer: http://stackoverflow.com/a/47832202
possible better answer: http://stackoverflow.com/a/47832202
has answer: http://stackoverflow.com/a/47832154
accepted answer: http://stackoverflow.com/a/47832154
has body: Given the example dataset below, I would like to return one row per group that shows the obsnum of the first row with a score less than 0.4. import pandas as pd import numpy as np np.random.seed(42) df = pd.DataFrame({'group': ['a', 'a', 'a', 'a', 'b', 'b', 'b', 'b', 'c', 'c', 'c', 'c'], 'obsnum': [1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4], 'score' : np.random.rand(12)}) The dataframe looks like this: df group obsnum score 0 a 1 0.374540 1 a 2 0.950714 2 a 3 0.731994 3 a 4 0.598658 4 b 1 0.156019 5 b 2 0.155995 6 b 3 0.058084 7 b 4 0.866176 8 c 1 0.601115 9 c 2 0.708073 10 c 3 0.020584 11 c 4 0.969910 The returned result should be like this and stored in another dataframe. group obsnum score a 1 0.374540 b 1 0.156019 c 3 0.020584 I have tried this df.groupby('group').apply(lambda x: x['score'] &lt;= 0.4) and this df.groupby('group')['obsnum', 'score'].min() but neither are what I am after.
upvote count: 2
type: AnsweredQuestion
score: 2
tagged with: pandas-groupby
tagged with: pandas
favorite count: 0
type: Question
has title: pandas groupby - return the first row in a group that mets a condition
answer count: 2

http://stackoverflow.com/q/47771854
tagged with: list
has title: Check continuity of integers and return uniques
tagged with: pandas
score: 2
upvote count: 2
accepted answer: http://stackoverflow.com/a/47771938
type: AnsweredQuestion
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/47771938
possible better answer: http://stackoverflow.com/a/47771936
favorite count: 0
has comment: http://stackoverflow.com/comment/82504550
has answer: http://stackoverflow.com/a/47771936
type: Question
tagged with: python
has body: Suppose i have a list like this: [1.0, 1.0, -1.0, -1.0, -1.0, -1.0, -1.0, 1.0, -1.0, -1.0, -1.0, -1.0, -1.0, 1.0, -1.0, -1.0, 1.0, -1.0, -1.0, 1.0, -1.0, -1.0, -1.0, 1.0, 1.0, 1.0, -1.0, -1.0, 1.0, -1.0, 1.0, -1.0, 1.0, 1.0, 1.0, 1.0, -1.0, -1.0, 1.0, 1.0, 1.0, 1.0, 1.0, -1.0, -1.0, -1.0, -1.0, 1.0, -1.0, 1.0, -1.0, 1.0, -1.0, 0.0, 1.0, 1.0, -1.0, 1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0] I want to check the continuity of the 1's and -1's. Expected output: [(1.0, 1.0), (-1.0, -1.0, -1.0, -1.0, -1.0), (1.0), (-1.0, -1.0, -1.0, -1.0, -1.0),....,(1.0), (0,0), (1.0, 1.0),( -1.0, 1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0)] [1,-1,1,-1,....,1,0,1,-1] for consecutive positive and negative values, it will return only ones. It's a little bit confusing for me. Can anybody help or suggest me the correct way to do it. Any help would be appreciated.

strftime
type: Tag
tag name: strftime
tags question: http://stackoverflow.com/q/47782463

http://stackoverflow.com/comment/82531036
comment on: http://stackoverflow.com/a/47784659
type: AnswerComment
has text: Haha maybe, felt like using it
type: Comment
score: 0

http://stackoverflow.com/comment/82558981
score: 0
type: Comment
has text: Possible duplicate of [setting up environment in virtaulenv using python3 stuck on setuptools, pip, wheel](https://stackoverflow.com/questions/45674311/setting-up-environment-in-virtaulenv-using-python3-stuck-on-setuptools-pip-whe)
type: QuestionComment
comment on: http://stackoverflow.com/q/47798698

http://stackoverflow.com/q/47718163
score: 0
has title: How to paginate once number of pages has been scraped? (Scrapy)
answer count: 1
tagged with: web-scraping
accepted answer: http://stackoverflow.com/a/47721321
tagged with: scrapy
has comment: http://stackoverflow.com/comment/82402285
type: Question
has body: I'm trying to paginate through a review site that doesn't have hyperlinked pagination buttons. I've written logic to paginate and hardcoded the number of pages for each link. However, I'm wondering if it's possible to use information that I scrape as the number of pages for a given link in start_requests. Spider code here (with 2 links to paginate through): class TareviewsSpider(scrapy.Spider): name = 'tareviews' allowed_domains = ['tripadvisor.com'] # start_urls = [] def start_requests(self): for page in range(0,395,5): yield self.make_requests_from_url('https://www.tripadvisor.com/Hotel_Review-g60795-d102542-Reviews-or{}-Courtyard_Philadelphia_Airport-Philadelphia_Pennsylvania.html'.format(page)) for page in range(0,1645,5): yield self.make_requests_from_url('https://www.tripadvisor.com/Hotel_Review-g60795-d122332-Reviews-or{}-The_Ritz_Carlton_Philadelphia-Philadelphia_Pennsylvania.html'.format(page)) def parse(self, response): for idx,review in enumerate(response.css('div.review-container')): item = { 'num_reviews': response.css('span.reviews_header_count::text')[0].re(r'\d{0,3}\,?\d{1,3}'), 'hotel_name': response.css('h1.heading_title::text').extract_first(), 'review_title': review.css('span.noQuotes::text').extract_first(), 'review_body': review.css('p.partial_entry::text').extract_first(), 'review_date': review.xpath('//*[@class="ratingDate relativeDate"]/@title')[idx].extract(), 'num_reviews_reviewer': review.css('span.badgetext::text').extract_first(), 'reviewer_name': review.css('span.scrname::text').extract(), 'bubble_rating': review.xpath("//div[contains(@class, 'reviewItemInline')]//span[contains(@class, 'ui_bubble_rating')]/@class")[idx].re(r'(?&lt;=ui_bubble_rating bubble_).+?(?=0)') } yield item 'num_reviews' is the value for the number of the last page for each link. In the for loop in start_requests it is 395 and 1645. Is this possible? I'd like to avoid a headless browser if possible. Thanks!
has comment: http://stackoverflow.com/comment/82402139
has comment: http://stackoverflow.com/comment/82398917
tagged with: pagination
tagged with: python
has answer: http://stackoverflow.com/a/47721321
type: AnsweredQuestion

http://stackoverflow.com/a/47746533
type: Answer
has body: The system does not like your call to Date.now(). You have not done a proper import for your Date.now() command. You need to import the module where you think the command is coming from. Maybe you meant to type: import datetime : : 'Date': datetime.datetime.now(), or 'Date': datetime.date.today(), There are many date and time options, so I'm not sure which one you're trying to use.
score: 0
answers question: http://stackoverflow.com/q/47746470
has comment: http://stackoverflow.com/comment/82473656

http://stackoverflow.com/a/47855020
accepted answer of: http://stackoverflow.com/q/47854983
upvote count: 2
has comment: http://stackoverflow.com/comment/82674193
answers question: http://stackoverflow.com/q/47854983
type: AcceptedAnswer
downvote count: 0
has body: That error means that lists in python can't be used as dictionary keys. What you want is to access the dictionary values for each element of that list, so try to use a list comprehension. score = sum(cards[c] for c in p.values())
type: Answer
score: 2

http://stackoverflow.com/a/47797470
upvote count: 3
downvote count: 0
score: 3
type: Answer
has body: This is pretty simple, as long as your timestamp only has the hour and minute components. Split, operate, and then combine - y = df.Time_string.str.split(':') i, j = y.str[0], y.str[1] df['Time_float'] = i.astype(int) + (j.astype(float) / 60) df Time_string Count Time_float 0 23:10 2400 23.166667 1 02:55 760 2.916667
answers question: http://stackoverflow.com/q/47797290

http://stackoverflow.com/a/47853030
upvote count: 7
accepted answer of: http://stackoverflow.com/q/47852950
score: 7
type: Answer
has comment: http://stackoverflow.com/comment/82670439
has body: The tldextract package should do the heavy lifting for you, based on the public suffix list. It isn't bullet proof, but should work for all the reasonable usecases: import tldextract def rm(text): return tldextract.extract(text).registered_domain
has comment: http://stackoverflow.com/comment/82670463
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47852950
downvote count: 0

http://stackoverflow.com/comment/82528210
has text: I'd also see, [Why would we use a variable class?](https://stackoverflow.com/q/47334885/7032856).
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47781604

http://stackoverflow.com/a/47720115
has body: If you know what h2 you want based on order, you simply need to use that as an index to the return of .findAll method: from bs4 import BeautifulSoup soup = BeautifulSoup(''' Video Instructions For Making Soft Idlis Recipe For Making Soft Idlis ''', "html.parser") >>> soup.findAll("h2")[1] Recipe For Making Soft Idlis
type: Answer
has comment: http://stackoverflow.com/comment/82481154
upvote count: 1
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/82456998
answers question: http://stackoverflow.com/q/47719165

http://stackoverflow.com/comment/82415268
type: Comment
has text: Yes zwer, I know which column to check
score: 0
comment on: http://stackoverflow.com/q/47727236
type: QuestionComment

http://stackoverflow.com/q/47823174
has comment: http://stackoverflow.com/comment/82646604
tagged with: python
tagged with: numpy
type: AnsweredQuestion
score: 0
has title: How to preserve encoded numpy array on disk?
accepted answer: http://stackoverflow.com/a/47823267
answer count: 1
has answer: http://stackoverflow.com/a/47823267
type: Question
has body: I have a numpy array of numbers as follows: array([[ 0.00365172, -0.01862929, 0.00739219, ..., -0.05520727, -0.00388453, -0.00591132], [ 0.00084692, -0.0177305 , 0.00618157, ..., -0.05275924, -0.00323982, -0.00107789], [ 0.01276451, -0.00361472, 0.0008607 , ..., 0.00464235, 0.00075972, 0.00700309]], dtype=float32) What is the most efficient way to store this on disk such that each array item is encoded in some text label as follows: array(['LabelA' 'LabelB', 'LabelC']) In other words, LabelA, LabelB and LabelC are string representations of the corresponding number vectors. My goal is to store this kind of array in a human readable format and I don't really care about reading the numerical values, yet preserving their one-to-one relationship with the corresponding unique labels. Is something like this possible? Thanks.
has comment: http://stackoverflow.com/comment/82641739

http://stackoverflow.com/a/47842039
accepted answer of: http://stackoverflow.com/q/47838558
upvote count: 3
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82649158
answers question: http://stackoverflow.com/q/47838558
score: 3
has comment: http://stackoverflow.com/comment/82649526
type: Answer
has body: You don't need to get the details of the job that created the view. There's a much easier way. Simply get the Table object and examine its view_query property. Code [..] client = bigquery.Client('grey-sort-challenge') dataset = client.dataset('apps_script_scheduler') tables = list(client.list_dataset_tables(dataset)) for t in tables: table = client.get_table(t) print 'Table type: %s, SQL: %s' % (table.table_type, table.view_query) [..] Output (for my dataset that contains 2 native tables and a view) Table type: TABLE, SQL: None Table type: TABLE, SQL: None Table type: VIEW, SQL: SELECT SUM(views) AS total_views, title, LANGUAGE FROM `bigquery-samples.wikipedia_benchmark.Wiki1M` WHERE title LIKE '%Melbourne%' GROUP BY title, LANGUAGE ORDER BY total_views DESC; Docs --> https://googlecloudplatform.github.io/google-cloud-python/latest/bigquery/reference.html#google.cloud.bigquery.table.Table.view_query

http://stackoverflow.com/comment/82593543
comment on: http://stackoverflow.com/a/47779143
has text: I tried and it works almost perfectly, i've edited the code just a bit, and I have a small problem...he is the code at the end: ` if 'Experiment Details: Error' in page: pagesSTREAK = pagesSTREAK+1 if pagesSTREAK == 2: indices = next_skip(indices,2) lettersSTREAK = lettersSTREAK+1 pagesSTREAK = 0 if lettersSTREAK == 2: indices = next_skip(indices,1) numbersSTREAK = numbersSTREAK+1` (part 1)
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/82382491
has text: problem can be python uses some most popular decoding to read file - it can be ie. `Latin-1`, `Utf-8`, `ASCII` - but your file has data in different encoding and you have to set corect when you read it. Different functions may need different solutions. Use Google to see in what encoding can be 0x8f.
comment on: http://stackoverflow.com/q/47711149
type: Comment
score: 1
type: QuestionComment

http://stackoverflow.com/comment/82667201
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47851237
has text: I believe that if you change your if test in printList() to `if current == None:`, it will work.

http://stackoverflow.com/comment/82563941
has text: @Shlomi and you're *sure* your Python path that corresponds to pip is the same as the one used by PyCharm in the settings? I.e. the actual Python binary is in the Scripts folder and is pointed to as the SDK and the packages for *that* Python instance contain the dependency? No alternate system version in root of C:\ or anything....
comment on: http://stackoverflow.com/a/47762126
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/47723919
type: Question
has answer: http://stackoverflow.com/a/47725481
has body: I have a dataframe that has two columns, Hospital name and Address, and I want to iterate through each address to find the latitude and longitude. My code seems to be taking the first row in the dataframe and I can't seem to select the address to find the coordinates. import pandas from geopy.geocoders import Nominatim geolocator = Nominatim() for index, item in df.iterrows(): location = geolocator.geocode(item) df["Latitude"].append(location.latitude) df["Longitude"].append(location.longitude) Here is the code I used to scrape the website. Copy and run this and you'll have the data set. import requests from bs4 import BeautifulSoup import pandas import numpy as np r=requests.get("https://www.privatehealth.co.uk/hospitals-and- clinics/orthopaedic-surgery/?offset=300") c=r.content soup=BeautifulSoup(c,"html.parser") all=soup.find_all(["div"],{"class":"col-9"}) names = [] for item in all: d={} d["Hospital Name"] = item.find(["h3"],{"class":"mb6"}).text.replace("\n","") d["Address"] = item.find(["p"],{"class":"mb6"}).text.replace("\n","") names.append(d) df=pandas.DataFrame(names) df = df'Hospital Name','Address' df Currently the data looks like (one hospital example): Hospital Name |Address Fulwood Hospital|Preston, PR2 9SZ The final output that I'm trying to achieve looks like. Hospital Name |Address | Latitude | Longitude Fulwood Hospital|Preston, PR2 9SZ|53.7589938|-2.7051618
has comment: http://stackoverflow.com/comment/82408691
tagged with: python
type: AnsweredQuestion
tagged with: geopy
tagged with: pandas
score: 1
answer count: 1
downvote count: 0
tagged with: loops
upvote count: 1
has title: Iterate geolocation over pandas dataframe
accepted answer: http://stackoverflow.com/a/47725481
favorite count: 0

http://stackoverflow.com/comment/82677073
score: 0
has text: @FujiAple, I am sorry. I should check my question before post it.
comment on: http://stackoverflow.com/q/47855892
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47743704
has title: Convert a column of integers to time in python
has comment: http://stackoverflow.com/comment/82447611
type: Question
has body: I have a column of data with 'int' format I want to change it to date time format, my time is like 94320 that should be 9:43:20 or another example: 143020 should be 14:30:20. I use quote['SellTime'] = pd.to_datetime(quote['SellTime'], unit = 's') but it add 1970-01-01 to the beginning of time that I don't need it.
type: UnansweredQuestion
tagged with: datetime
tagged with: python
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/47743828
has answer: http://stackoverflow.com/a/47743797
has comment: http://stackoverflow.com/comment/82447645

http://stackoverflow.com/comment/82486938
type: QuestionComment
has text: So, where's your attempt? Why do you want variables of the form `xxx1`, `xxx2`, etc? That's always a bad idea. Instead, you should have just a list `xxx_list`, where `xxx1` is equivalent to `xxx_list[0]`.
type: Comment
score: 2
comment on: http://stackoverflow.com/q/47762735

http://stackoverflow.com/comment/82605478
comment on: http://stackoverflow.com/a/47821268
has text: @sypher5 Please accept (grey --> green tick next to answer) then as it works!
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/a/47855011
answers question: http://stackoverflow.com/q/47854941
has comment: http://stackoverflow.com/comment/82674211
accepted answer of: http://stackoverflow.com/q/47854941
score: 2
has body: Use this approach. from sqlalchemy.orm import sessionmaker Session = sessionmaker(bind=engine) session = Session() # it will send the connection back to the pool of connections in the engine, but it will not close the connection instead it will make the connection idle session.close() # to close the engine having pool of connections will close all the idle connections in the pool engine.dispose()() # for directing close the connection on session.close, use this code # Disabling pooling using NullPool: from sqlalchemy.pool import NullPool engine = create_engine( 'postgresql+psycopg2://scott:tiger@localhost/test', poolclass=NullPool) session.close()
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82674033
has comment: http://stackoverflow.com/comment/82674336
type: Answer

http://stackoverflow.com/q/47737602
type: UnansweredQuestion
tagged with: arrays
duplicate of: http://stackoverflow.com/q/9296658
has comment: http://stackoverflow.com/comment/82443875
downvote count: 0
upvote count: 1
score: 1
tagged with: python
has title: Numpy filtering array by True/False
linked to: http://stackoverflow.com/q/9296658
favorite count: 0
has body: I have a 2-dim numpy array where I want to delete lines where in a scond array is a a "False": Input: a = np.array[[0, 0, 1] [5, 2, 7] [3, 12, 0]] b = np.array[True, False, True] Result: c = np.array[[0, 0, 1] [3, 12, 0]] I have searched a lot and didn't find a way so far. Many thanks for some hints Tom
type: Question
tagged with: numpy
answer count: 0

bullet
tags question: http://stackoverflow.com/q/47771351
tag name: bullet
type: Tag

http://stackoverflow.com/comment/82633138
has text: Please be more clear about the context of your question and identify that you are referring to TensorFlow: https://www.tensorflow.org/ Otherwise your readers may be confused about the context. You should also specify the target platform.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47834768
score: 0

http://stackoverflow.com/a/51945256
type: Answer
has comment: http://stackoverflow.com/comment/104014620
answers question: http://stackoverflow.com/q/47843265
type: AcceptedAnswer
downvote count: 0
score: 29
has comment: http://stackoverflow.com/comment/121058794
upvote count: 29
accepted answer of: http://stackoverflow.com/q/47843265
has comment: http://stackoverflow.com/comment/98060900
has comment: http://stackoverflow.com/comment/122963905
has body: Unfortunately it seems that Keras hasn't implemented the possibility of loading the history directly from a loaded model. Instead you have to set it up in advance. This is how I solved it using CSVLogger (it's actually very convenient storing the entire training history in a separate file. This way you can always come back later and plot whatever history you want instead of being dependent on a variable you can easily lose stored in the RAM): First we have to set up the logger before initiating the training. from keras.callbacks import CSVLogger csv_logger = CSVLogger('training.log', separator=',', append=False) model.fit(X_train, Y_train, callbacks=[csv_logger]) The entire log history will now be stored in the file 'training.log' (the same information you would get, by in your case, calling H.history). When the training is finished, the next step would simply be to load the data stored in this file. You can do that with pandas read_csv: import pandas as pd log_data = pd.read_csv('training.log', sep=',', engine='python') From here on you can treat the data stored in log_data just as you would by loading it from K.history. More information in Keras callbacks docs.
has comment: http://stackoverflow.com/comment/121059013

http://stackoverflow.com/comment/82374264
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47705710
has text: the logic was suppose to be that if there's a quote there match until the next quote. if there's no quote match until the next space. looking at it again, I think you're right something is wrong when there's no quotes. funny how it seems to work sometimes.

http://stackoverflow.com/a/61699417
has comment: http://stackoverflow.com/comment/133397429
upvote count: 16
has comment: http://stackoverflow.com/comment/110360829
has comment: http://stackoverflow.com/comment/138433299
has comment: http://stackoverflow.com/comment/110277928
has comment: http://stackoverflow.com/comment/110360819
has comment: http://stackoverflow.com/comment/116452114
downvote count: 0
has body: Thank you for your useful question. I tried the two ways proposed above to handle my problem. For feather, I faced this issue: pyarrow.lib.ArrowInvalid: Not a Feather V1 or Arrow IPC file For rpy2, as mentioned by @Orange: "pandas2ri.ri2py_dataframe does not seem to exist any longer in rpy2 version 3.0.3" or later. I searched for another workaround and found pyreadr useful for me and maybe for those who are facing the same problems as I am: https://github.com/ofajardo/pyreadr Usage: https://gist.github.com/LeiG/8094753a6cc7907c716f#gistcomment-2795790 pip install pyreadr import pyreadr result = pyreadr.read_r('/path/to/file.RData') # also works for Rds, rda # done! let's see what we got # result is a dictionary where keys are the name of objects and the values python # objects print(result.keys()) # let's check what objects we got df1 = result["df1"] # extract the pandas data frame for object df1
score: 16
has comment: http://stackoverflow.com/comment/110247914
answers question: http://stackoverflow.com/q/47833692
type: Answer

http://stackoverflow.com/comment/82435040
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47737350
has text: Sure. I have updated this in the answer section.
score: 0

http://stackoverflow.com/q/47709010
has comment: http://stackoverflow.com/comment/82378213
has title: Read and plot real time live self updating csv file
score: 0
has comment: http://stackoverflow.com/comment/82377851
tagged with: real-time
tagged with: pandas
has comment: http://stackoverflow.com/comment/82378009
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47779907
answer count: 1
has body: So, I have a .csv file which updates itself. I would like to do some things with it and am not sure how to approach it, hope you can help me. The data in the csv looks like this: There is no headers. I can join the date and time to be in same column without a delimiter too. 07/12/2017,23:50,113.179,113.182,113.168,113.180,113.187,113.189,113.176,113.186,144 07/12/2017,23:51,113.180,113.190,113.180,113.187,113.186,113.196,113.186,113.193,175 07/12/2017,23:52,113.187,113.188,113.174,113.186,113.193,113.194,113.181,113.192,340 07/12/2017,23:53,113.186,113.192,113.175,113.181,113.192,113.199,113.182,113.188,282 07/12/2017,23:54,113.181,113.183,113.170,113.171,113.188,113.188,113.176,113.179,74 07/12/2017,23:55,113.171,113.181,113.170,113.179,113.179,113.188,113.176,113.186,329 07/12/2017,23:56,113.179,113.189,113.174,113.181,113.186,113.195,113.181,113.187,148 07/12/2017,23:57,113.181,113.181,113.169,113.169,113.187,113.187,113.175,113.175,55 07/12/2017,23:58,113.169,113.183,113.169,113.182,113.175,113.188,113.175,113.187,246 07/12/2017,23:59,113.182,113.210,113.175,113.203,113.187,113.215,113.181,113.209,378 08/12/2017,00:00,113.203,113.213,113.180,113.183,113.209,113.220,113.187,113.190,651 08/12/2017,00:01,113.183,113.190,113.164,113.167,113.190,113.196,113.171,113.174,333 08/12/2017,00:02,113.167,113.182,113.156,113.156,113.174,113.188,113.162,113.163,265 08/12/2017,00:03,113.156,113.165,113.151,113.163,113.163,113.172,113.158,113.170,222 08/12/2017,00:04,113.163,113.163,113.154,113.159,113.170,113.170,113.159,113.166,148 08/12/2017,00:05,113.159,113.163,113.153,113.154,113.166,113.168,113.159,113.162,162 For starters I would be interested in using just the first two (or 3 if date and time are separate) columns for this exercise. So for example: 07/12/2017,21:54,113.098 07/12/2017,21:55,113.096 07/12/2017,21:56,113.087 07/12/2017,21:57,113.075 07/12/2017,21:58,113.087 07/12/2017,21:59,113.079 New rows are being added with more recent date time every second or so. I …
tagged with: pyqtgraph
has comment: http://stackoverflow.com/comment/82378228
tagged with: plot
type: Question
has comment: http://stackoverflow.com/comment/82378070
tagged with: python

http://stackoverflow.com/tag/html
tags question: http://stackoverflow.com/q/47733013
tags question: http://stackoverflow.com/q/47744697
tags question: http://stackoverflow.com/q/47708331
tags question: http://stackoverflow.com/q/47794678
tags question: http://stackoverflow.com/q/47741702
tags question: http://stackoverflow.com/q/47787289
tags question: http://stackoverflow.com/q/47752716
tags question: http://stackoverflow.com/q/47808181
tags question: http://stackoverflow.com/q/47716063
tags question: http://stackoverflow.com/q/47855500
tags question: http://stackoverflow.com/q/47840862
tags question: http://stackoverflow.com/q/47726766
tags question: http://stackoverflow.com/q/47763282
tags question: http://stackoverflow.com/q/47809732
tags question: http://stackoverflow.com/q/47779454
tags question: http://stackoverflow.com/q/47776460
tags question: http://stackoverflow.com/q/47734706
tags question: http://stackoverflow.com/q/47761361
tags question: http://stackoverflow.com/q/47820431
tags question: http://stackoverflow.com/q/47833910
tags question: http://stackoverflow.com/q/47739105
tags question: http://stackoverflow.com/q/47724241
tags question: http://stackoverflow.com/q/47828926
tags question: http://stackoverflow.com/q/47840270
tags question: http://stackoverflow.com/q/47761033
tags question: http://stackoverflow.com/q/47824519
tags question: http://stackoverflow.com/q/47729643
tags question: http://stackoverflow.com/q/47716699
tags question: http://stackoverflow.com/q/47736600
tags question: http://stackoverflow.com/q/47704441
tags question: http://stackoverflow.com/q/47739065
tags question: http://stackoverflow.com/q/47852373
tags question: http://stackoverflow.com/q/47761481
tags question: http://stackoverflow.com/q/47799418
tags question: http://stackoverflow.com/q/47766150
tags question: http://stackoverflow.com/q/47799931
tags question: http://stackoverflow.com/q/47851288
tags question: http://stackoverflow.com/q/47827827
tags question: http://stackoverflow.com/q/47762717
tags question: http://stackoverflow.com/q/47804924
tags question: http://stackoverflow.com/q/47818858
tags question: http://stackoverflow.com/q/47800567
type: Tag
tags question: http://stackoverflow.com/q/47841163
tags question: http://stackoverflow.com/q/47774510
tag name: html
tags question: http://stackoverflow.com/q/47840010
tags question: http://stackoverflow.com/q/47838115
tags question: http://stackoverflow.com/q/47725669
tags question: http://stackoverflow.com/q/47720832
tags question: http://stackoverflow.com/q/47711880
tags question: http://stackoverflow.com/q/47836276
tags question: http://stackoverflow.com/q/47727390
tags question: http://stackoverflow.com/q/47734979
tags question: http://stackoverflow.com/q/47723301
tags question: http://stackoverflow.com/q/47759269
tags question: http://stackoverflow.com/q/47819696
tags question: http://stackoverflow.com/q/47760436
tags question: http://stackoverflow.com/q/47703639
tags question: http://stackoverflow.com/q/47781711
tags question: http://stackoverflow.com/q/47770144
tags question: http://stackoverflow.com/q/47780198
tags question: http://stackoverflow.com/q/47776762
tags question: http://stackoverflow.com/q/47731682
tags question: http://stackoverflow.com/q/47817800
tags question: http://stackoverflow.com/q/47751002
tags question: http://stackoverflow.com/q/47742823
tags question: http://stackoverflow.com/q/47735413
tags question: http://stackoverflow.com/q/47825131

http://stackoverflow.com/comment/82660619
comment on: http://stackoverflow.com/q/47816188
type: QuestionComment
type: Comment
has text: Ok but why the first tf.get_variable() generate a collection_def that contains a list of nodes (just one node in this case) while the second tf.get_variable() generate e collection_def that contains a bytes_list representing a string ? It is the same method call that generate a tf.Variable in both cases. I know is a very specific question but it help me understand why that difference.
score: 0

http://stackoverflow.com/q/47740078
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47740434
answer count: 1
upvote count: 1
tagged with: python
has title: Grouping days based on relative position
type: AnsweredQuestion
score: 0
has body: import datetime dates_list = ['2015-03-28 10:15:36.560000', '2015-03-28 11:35:17.820000', '2015-03-29 13:34:54.380000', '2015-03-29 14:10:41.900000', '2015-03-31 16:55:43.680000', '2015-03-31 16:57:58.320000', '2015-04-02 18:54:31.480000', '2015-04-02 19:46:46.580000', '2015-04-03 20:58:27.940000', '2015-04-03 21:30:05.600000'] df = pd.DataFrame(data=[1,2,3,np.nan,5,6,np.nan,np.nan,8,9],columns=['value'],index=[datetime.datetime.strptime(date, '%Y-%m-%d %H:%M:%S.%f') for date in dates_list]) df Out[18]: value 2015-03-28 10:15:36.560 1.0 2015-03-28 11:35:17.820 2.0 2015-03-29 13:34:54.380 3.0 2015-03-29 14:10:41.900 NaN 2015-03-31 16:55:43.680 5.0 2015-03-31 16:57:58.320 6.0 2015-04-02 18:54:31.480 NaN 2015-04-02 19:46:46.580 NaN 2015-04-03 20:58:27.940 8.0 2015-04-03 21:30:05.600 9.0 I would like to compute 2 means: 1) groupin of the days in even positions [2015-03-28, 2015-03-31, 2015-04-03] and 2) grouping the days in even position [2015-03-29 2015-04-02]. In this case df2 = df.groupby(df.index.day % 2).agg(np.mean) won't work because the days are not consecutive and I am interested in the position of the days.
tagged with: pandas
tagged with: datetime
tagged with: dataframe
downvote count: 1
accepted answer: http://stackoverflow.com/a/47740434

rx-py
tag name: rx-py
type: Tag
tags question: http://stackoverflow.com/q/47770914

http://stackoverflow.com/comment/82529084
type: Comment
has text: What if I only wanna pad one axis?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47765030

http://stackoverflow.com/comment/82603385
has text: Well forget the list then, just print on each iteration where `best_solution` changes. Don't do both... What you have posted is impossible. Are you sure the code and results you have there is **exactly** what you have in your editor. Because my bet is you are returning `solution`, not `best_solution`.
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47819301

http://stackoverflow.com/comment/82669200
has text: I know (or expect) what they want. But you seem to be new to ML and should grab those basic data-formats first before asking things like that. Try to bring your expected output into MATRIX-form. That's all coo_matrix can give you. If your expected output is not a matrix (2-d!) like your expected output, there is no way you can do this. You are probably asking for one_hot_encoding or some other preprocessings. But that has not much to do with scipy's sparse-matrices.The format is quite standard,you will learn a lot from scikit-learn's documentation. Visit it and read the preprocessing tutorial.
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/47852335

http://stackoverflow.com/comment/82556490
comment on: http://stackoverflow.com/a/47792449
has text: It worked after I've created a directory named `templatetags` in my app and moved `template_filters.py` in that directory. Also I had to create a `__init__.py` in that directory.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/47767042
upvote count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/47767535
has comment: http://stackoverflow.com/comment/82496048
favorite count: 0
type: Question
has body: Me and my partner, we need to create a game in python. We are total beginners, so sorry if we ask questions that possibly sound very imprudent for Python-Pro´s. Here is our code to create a field with a range from 7x7: import string class board: def __init__(self, width): self.w = width self.board = [[[] for i in range(width)] for b in range(width)] def __setitem__(self, coords, val): self.board[coords[0]][coords[-1]] = [val] def __repr__(self): return ' '+' '.join(list(string.ascii_lowercase[:self.w]))+"\n"+'\n'.join(string.ascii_lowercase[a]+' '.join(str(i) for i in b) for a, b in enumerate(self.board)) board = board(7) board[(3, 3)] = 'X' Until now, it works (not perfect, but good enough to go on with it). I have now several questions. If you don´t mind, you can just answer one of them. We would be very thankful. The title of the columns and lines are letters (a-g), how do i invert them into numbers? What needs to be done, to get the content of a specific 'cell'? e.G. if the cell in 3,3 has the content 'X', how do i get just the 'X'? Thank you very much guys!
accepted answer: http://stackoverflow.com/a/47767454
tagged with: field
has answer: http://stackoverflow.com/a/47767454
has title: Python: How to retrieve the content of a cell in our game-field?
possible better answer: http://stackoverflow.com/a/47767535
tagged with: python
tagged with: class
type: AnsweredQuestion
answer count: 2
score: 0

http://stackoverflow.com/a/50176945
score: 3
upvote count: 3
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47800903
has body: It is not clear from the tool documentation, but based on a thread: https://github.com/dsoprea/PyEasyArchive/issues/16 I set another environment variable to the place where the underlying c library could be found. In my case, it was put there by homebrew on my mac. os.environ['LA_LIBRARY_FILEPATH']='/usr/local/opt/libarchive/lib/libarchive.dylib' import libarchive.public worked for me.
answers question: http://stackoverflow.com/q/47800903
type: Answer

http://stackoverflow.com/a/55284575
answers question: http://stackoverflow.com/q/47786463
upvote count: 5
type: Answer
has body: This is likely Windows specific behavior and how they manage sockets. On Windows, you can have multiple processes bind to the same port for listening. This was found to cause a lot of security issues, so Windows released updates that can prevent a port from being hi-jacked by another process via the SO_EXCLUSIVEADDRUSE socket flag. You can read more about it at https://learn.microsoft.com/en-us/windows/desktop/winsock/so-exclusiveaddruse From what I can see by reading through the flask development server code, there is no way for a user to set the SO_EXCLUSIVEADDRUSE flag.
score: 5
downvote count: 0

http://stackoverflow.com/comment/82572410
has text: Is there a way to disable DevTools listening on ws:// as well or is this ingrained into cmd?
comment on: http://stackoverflow.com/a/47798657
type: Comment
score: 0
type: AnswerComment

string
tags question: http://stackoverflow.com/q/47758858
type: Tag
tags question: http://stackoverflow.com/q/47798578
tags question: http://stackoverflow.com/q/47790591
tags question: http://stackoverflow.com/q/47758810
tags question: http://stackoverflow.com/q/47813099
tags question: http://stackoverflow.com/q/47838733
tags question: http://stackoverflow.com/q/47803928
tags question: http://stackoverflow.com/q/47825061
tags question: http://stackoverflow.com/q/47793516
tags question: http://stackoverflow.com/q/47762325
tags question: http://stackoverflow.com/q/47750711
tags question: http://stackoverflow.com/q/47704547
tags question: http://stackoverflow.com/q/47705172
tags question: http://stackoverflow.com/q/47702285
tags question: http://stackoverflow.com/q/47837733
tags question: http://stackoverflow.com/q/47780229
tags question: http://stackoverflow.com/q/47853171
tags question: http://stackoverflow.com/q/47795262
tags question: http://stackoverflow.com/q/47708020
tags question: http://stackoverflow.com/q/47724521
tags question: http://stackoverflow.com/q/47819144
tags question: http://stackoverflow.com/q/47749297
tags question: http://stackoverflow.com/q/47848182
tags question: http://stackoverflow.com/q/47745359
tags question: http://stackoverflow.com/q/47722509
tags question: http://stackoverflow.com/q/47824853
tags question: http://stackoverflow.com/q/47808037
tags question: http://stackoverflow.com/q/47715392
tags question: http://stackoverflow.com/q/47807426
tags question: http://stackoverflow.com/q/47803203
tags question: http://stackoverflow.com/q/47803865
tags question: http://stackoverflow.com/q/47725484
tags question: http://stackoverflow.com/q/47806393
tags question: http://stackoverflow.com/q/47832354
tags question: http://stackoverflow.com/q/47737021
tags question: http://stackoverflow.com/q/47706418
tags question: http://stackoverflow.com/q/47824510
tags question: http://stackoverflow.com/q/47724115
tags question: http://stackoverflow.com/q/47706673
tags question: http://stackoverflow.com/q/47742001
tags question: http://stackoverflow.com/q/47708239
tags question: http://stackoverflow.com/q/47761343
tags question: http://stackoverflow.com/q/47717860
tags question: http://stackoverflow.com/q/47721315
tags question: http://stackoverflow.com/q/47783326
tags question: http://stackoverflow.com/q/47851698
tags question: http://stackoverflow.com/q/47802324
tags question: http://stackoverflow.com/q/47803871
tags question: http://stackoverflow.com/q/47826694
tag name: string
tags question: http://stackoverflow.com/q/47712263
tags question: http://stackoverflow.com/q/47796104
tags question: http://stackoverflow.com/q/47735764
tags question: http://stackoverflow.com/q/47847807
tags question: http://stackoverflow.com/q/47740671
tags question: http://stackoverflow.com/q/47797790
tags question: http://stackoverflow.com/q/47711595
tags question: http://stackoverflow.com/q/47780227
tags question: http://stackoverflow.com/q/47773262
tags question: http://stackoverflow.com/q/47711255
tags question: http://stackoverflow.com/q/47723737
tags question: http://stackoverflow.com/q/47751102
tags question: http://stackoverflow.com/q/47734068

http://stackoverflow.com/q/47706820
linked to: http://stackoverflow.com/q/2627002
type: Question
has comment: http://stackoverflow.com/comment/82373859
has comment: http://stackoverflow.com/comment/82373981
tagged with: oop
has body: I was reading this link about using getters in Python, quote: The Pythonic way is to not use them. If you must have them then hide them behind a property. That same page includes various examples, but my question is, if getters are not the Python way, how would I indicate to someone reading my code that a variable should be read-only after construction. Suppose I have the following class: class Car: def __init__(self, ID, name, tire, engine): self.ID = ID self.name = name self.tire = tire self.engine = engine def __str__(self): return "ID: {0} Name:{1} Tire: {2} Engine: {3}".format(self.ID, self.name, self.tire, self.engine) If I wanted to indicate to another developer that self.engine is read-only after being set in the constructor, how would I do so? In orders words, if clients violate the rule, and attempt to set it, it's there problem if the implementation of self.engine changes(for example, from object of the class Engine to Dictionary).
has answer: http://stackoverflow.com/a/47706875
accepted answer: http://stackoverflow.com/a/47706875
has comment: http://stackoverflow.com/comment/82373754
linked to: http://stackoverflow.com/q/1301346
has comment: http://stackoverflow.com/comment/82373775
has comment: http://stackoverflow.com/comment/82373833
tagged with: python
has comment: http://stackoverflow.com/comment/82373974
has comment: http://stackoverflow.com/comment/82373881
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/82373841
has comment: http://stackoverflow.com/comment/82373890
has title: Read-Only properties without getters
has comment: http://stackoverflow.com/comment/82373814
has comment: http://stackoverflow.com/comment/82373918
answer count: 1
has comment: http://stackoverflow.com/comment/82373770

http://stackoverflow.com/a/47852168
has body: &lt;img src="imagename.jpeg"&gt; This works great in markdown cells. Please let me know if you have any other questions!
has comment: http://stackoverflow.com/comment/136407756
answers question: http://stackoverflow.com/q/47843222
type: AcceptedAnswer
score: 6
has comment: http://stackoverflow.com/comment/136407781
type: Answer
upvote count: 6
has comment: http://stackoverflow.com/comment/136094626
accepted answer of: http://stackoverflow.com/q/47843222
has comment: http://stackoverflow.com/comment/82668773
downvote count: 0

undo
type: Tag
tag name: undo
tags question: http://stackoverflow.com/q/47841934

http://stackoverflow.com/q/47703974
has comment: http://stackoverflow.com/comment/82368177
answer count: 1
type: Question
has body: This is my model: class CalEvents(models.Model): user = models.ForeignKey(User) activity_name = models.CharField(max_length=256, unique=False, blank=True) activity_type = models.CharField(max_length=30, unique=False, blank=True) activity_code = models.CharField(max_length=30, unique=False, blank=True) def __str__(self): return "Activity: '{}' - @{}".format(self.activity_name, self.user.username) This is my forms.py (with my attempted solutions to define the labels): from django.forms import ModelForm from gCalData.models import CalEvents from accounts.models import User class CalEventsForm(ModelForm): class Meta: model = CalEvents fields = ['activity_name','activity_type','activity_code'] labels = {"actiity_name": "Activity name", "activity_type": "Activity type", "activity_code": "Activity code"} def __init__(self, *args, **kwargs): super(CalEventsForm, self).__init__(*args, **kwargs) self.fields['activity_name'].label = "Activity name" self.fields['activity_type'].label = "Activity type" self.fields['activity_code'].label = "Activity code" This is the part of my template where I put the form: &lt;tr&gt; &lt;form method="POST"&gt; {% csrf_token %} {% for field in form %} &lt;td&gt;{{ field }}&lt;/td&gt; {% endfor %} &lt;td&gt;&lt;input type="submit" name="new_record" class="btn btn-primary" value="Add Activity"&gt;&lt;/td&gt; &lt;/form&gt; &lt;/tr&gt; What am I doing wrong?
has comment: http://stackoverflow.com/comment/82368087
has comment: http://stackoverflow.com/comment/82368186
tagged with: django
tagged with: python
accepted answer: http://stackoverflow.com/a/47704074
tagged with: forms
has answer: http://stackoverflow.com/a/47704074
has comment: http://stackoverflow.com/comment/82368244
type: AnsweredQuestion
score: 0
has title: I can't set labels in Django forms fields

http://stackoverflow.com/q/47698571
favorite count: 0
has answer: http://stackoverflow.com/a/47698858
type: Question
has comment: http://stackoverflow.com/comment/82357190
has answer: http://stackoverflow.com/a/47698739
has comment: http://stackoverflow.com/comment/82357159
score: 1
has body: I am trying to create a powerset by multiplying binary counter with array to get Value of Counter Subset 000 -&gt; Empty set 001 -&gt; a 010 -&gt; b 011 -&gt; ab 100 -&gt; c 101 -&gt; ac 110 -&gt; bc 111 -&gt; abc My code: A = ['a','b','c'] n = len(A) for i in range(2**n): print format(i,'b') and A I get all the outputs as ['a','b','c'] . Is there a different way to do the print statement to get the required result.
downvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/47698686
upvote count: 2
answer count: 3
has comment: http://stackoverflow.com/comment/82357164
type: UnansweredQuestion
tagged with: bit-manipulation
has title: Multiply list with binary

http://stackoverflow.com/comment/82580450
score: 0
comment on: http://stackoverflow.com/q/47809646
type: QuestionComment
has text: Please show the code leading to this error.
type: Comment

http://stackoverflow.com/a/47699930
upvote count: 14
type: Answer
downvote count: 1
answers question: http://stackoverflow.com/q/47699872
has comment: http://stackoverflow.com/comment/92113758
has body: Use openpyxl.cell.cell.Cell.value as, wb = load_workbook(file_name, read_only=True) test_sheet = wb["Test"] row = 1 column = 1 print(test_sheet.cell(row, column).value)
score: 13

http://stackoverflow.com/q/47704461
has comment: http://stackoverflow.com/comment/82369052
has comment: http://stackoverflow.com/comment/82401521
tagged with: int
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47704515
tagged with: list
has body: I have this function that creates an empty 2D list. getal X getal wide and high. Though when i execute the code i get this error Traceback (most recent call last): line 49, in bord = rooster(5, "&lt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;") line 38, in rooster r = r + 1 TypeError: can only concatenate list (not "int") to list r is a counter in this code that stands for rows of the board. k is also a counter that stands for columns of the board. reeks is a string that gets split into characters. The goal of the code is to make the board getal X getal wide and then inserting all characters from 'reeks' into their own separate slot. def rooster(getal, reeks): #vierkant = [['']*getal]* getal vierkant = [[0 for r in range(getal)] for k in range(getal)] r = 0 k = 0 reekslist = list(reeks) while r &lt; getal: k = 0 while k &lt; getal: vierkant[r][k] = reekslist[k + r*getal] k += 1 for r in vierkant: print(r) r = r + 1 bord = rooster(5, "&lt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;")
has answer: http://stackoverflow.com/a/47704515
has comment: http://stackoverflow.com/comment/82370259
answer count: 1
has comment: http://stackoverflow.com/comment/82400855
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82369087
tagged with: for-loop
has title: r = r + 1 not working concatenate list while its an int?
has comment: http://stackoverflow.com/comment/82369115
upvote count: 0
tagged with: python
score: -1

http://stackoverflow.com/comment/82509310
has text: @AlessandroPetric it is not complicated at all, it does the same that Arne told you to do, with the exception that this Node class automatically sets visited to true when you lookup the data "attribute" and sets it to false when you set the data attribute. So you dont have to worry about when to set visited to true. Each time you visit (i.e. use the data of the node) it will set its own visited attribute to True.
score: 0
comment on: http://stackoverflow.com/a/47773755
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/82591272
score: 2
type: Comment
comment on: http://stackoverflow.com/q/47814968
has text: Homework is meant for you to solve... unless you're willing to share the A+ you get when you turn in our solution ;)
type: QuestionComment

http://stackoverflow.com/a/47708171
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82420765
downvote count: 0
answers question: http://stackoverflow.com/q/47706005
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47706005
has comment: http://stackoverflow.com/comment/82424138
type: Answer
score: 1
has body: LRU Cache This is implementing Paul Panzer's suggestion, it relies on @lru_cache which is a Python 3 feature. We cannot directly apply this decorator to the objective function, because it receives a NumPy array, which is mutable and therefore not hashable. So we need two functions: func_with_cons computes the objective and constraint, given scalar arguments. f calls func_with_cons and returns either objective or constraint, based on returncons argument. Note that we need consargs parameter in the call to fmin_cobyla, because without it the same extra arguments args will be passed to the constraint function. from scipy.optimize import fmin_cobyla as mini from functools import lru_cache @lru_cache(maxsize=32) def func_with_cons(x0, x1): return (x0 - 2)**2 + 4 * (x1 -x0**2)**2, x0 - x1 def f(x, returncons=True): value, cons = func_with_cons(x[0], x[1]) return cons if returncons else value func_with_cons.cache_clear() x_opt = mini(f, (1., 1.), cons=f, args=(False,), consargs=()) print(x_opt) print(func_with_cons.cache_info()) Output: [ 1.14491021 1.14491021] CacheInfo(hits=41, misses=32, maxsize=32, currsize=32) So, the cache works. I changed the constraint from x1-x0 to x0-x1 to show that it also works (the original constraint x1-x0 is satisfied by the global minimum of this function, so it would have no effect on the result). Cache size can be much smaller: with maxsize=2 we would have 40 hits (vs 41 with the above size). Global variable This is implementing Jakob Lovern's suggestion. The function f stores the constraint in a global variable, from which the function cons retrieves it. The use of a global has obvious drawbacks, but then again, this works in Python 2.7. def f(x): global stored_cons stored_cons = x[0] - x[1] return (x[0] - 2)**2 + 4 * (x[1] -x[0]**2)**2 def cons(x): return stored_cons x0 = [1., 1.] f(x0) # called to initialize stored_cons x_opt = mini(f, x0, cons=cons) This returns [ 1.14491021, 1.14491021] since the global minimum [2, 4] is disallowed b…

http://stackoverflow.com/q/47740206
has answer: http://stackoverflow.com/a/47741851
downvote count: 1
has comment: http://stackoverflow.com/comment/82441613
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47740650
type: UnansweredQuestion
has body: I just started to study OpenCV with Python and was trying to build my first game bot. My thought is: capture the game window frame by frame and analyze the pixels in some specific locations, if the color of those pixels has changed, then press a key to do some automatic operations. This game needs quick reactions so the FPS is quite important, I have tried the mss and PIL, but the fps in both methods are not enough (30+ with mss and 10+ with PIL's ImageGrab), so I'm wondering if there is any better way to deal with pixels in real-time. Thanks!
has title: Dealing with pixels in real-time using OpenCV
tagged with: python
score: -1
upvote count: 0
answer count: 2

http://stackoverflow.com/comment/82525753
type: QuestionComment
comment on: http://stackoverflow.com/q/47778594
score: 0
type: Comment
has text: @Dan But I already try the code 'df = pd.concat(tp, ignore_index=True)' and that costs over 10 seconds for the csv file over 1 million rows.

http://stackoverflow.com/comment/82766030
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47861748
has text: Not finding xgboost would definitely be a problem while trying to freeze it. as for pandas I think so long as you have pandas and the numpy related things I added in like addtional_mods = ['numpy.core._methods', 'numpy.lib.format'] and packages = ['numpy', 'numpy.core._methods', 'pandas'] it should work.

http://stackoverflow.com/comment/82409996
score: 0
type: AnswerComment
has text: this solution creates a new dictionary
comment on: http://stackoverflow.com/a/47724418
type: Comment

http://stackoverflow.com/q/47766146
has answer: http://stackoverflow.com/a/47766464
answer count: 2
tagged with: django
linked to: http://stackoverflow.com/q/29311354
linked to: http://stackoverflow.com/q/35884639
type: Question
linked to: http://stackoverflow.com/q/35829024
possible better answer: http://stackoverflow.com/a/47766889
tagged with: postgresql
has answer: http://stackoverflow.com/a/47766889
tagged with: datetime
tagged with: python
has body: I am adding timestamp in my payload and storing it in the database for every record. Suppose say a part of my payload is {"content":[{"timestamp":"2017-12-12 08:05:30"}] This is how I process it. content['timestamp'] = parser.parse(content['timestamp'],dayfirst=True) My model has timestamp field as : timestamp = models.DateTimeField(null=True) When I check in my database it stores timestamp field as : 2017-12-12 13:35:30 Which should be stored as it is as per my requirement. 2017-12-12 08:05:30 i.e it stores the timestamp field + my local timezone(+5:30) hours. I want it to store the timestamp field as it is. I tried other posts where they suggest using del os.environ['TZ']. Any idea what I may have done which causes this or what could I do to avoid this. Any help is appreciated.
has title: Django automatically converting datetime string to local timezone
accepted answer: http://stackoverflow.com/a/47766464
type: AnsweredQuestion
score: 0

http://stackoverflow.com/comment/82598536
has text: I thought I might be able to store it as a temp variable or something. Do you have any idea how I may do it with a list then?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47817969
score: 0

http://stackoverflow.com/comment/82705834
comment on: http://stackoverflow.com/q/47782716
score: 0
type: Comment
type: QuestionComment
has text: Thank you, guys. I haven't tried any of the options you proposed. I will keep it in my for the future cases

http://stackoverflow.com/a/47722101
answers question: http://stackoverflow.com/q/47721982
score: 0
has body: The algorithm is known as Binary Search Alorithm. It works on sorted list to find an element in O(logn) (normally finding an element in a list requires O(n) to iterate over all elements). The magic behind it is as follows: Suppose you have a sorted array from 1 to 1000. you want to check whether 247 is exist or not, one way is iterate over all elements but the the other is using BST i.e. check the median value, if it is greater than 247, It means that if 247 exist on this array it should be placed somewhere in the first have of the array and in this way you simply ignore the second half and so on.
type: Answer

http://stackoverflow.com/comment/82504975
score: 0
has text: It is quite memory consuming. I run it on one node with 28 cores, and I think somehow the memory doesn't empty for the next process after finishing one. This is just my guess.
type: Comment
comment on: http://stackoverflow.com/q/47769748
type: QuestionComment

http://stackoverflow.com/comment/82597145
comment on: http://stackoverflow.com/q/47817448
type: Comment
score: 0
has text: You run some process (which happens to be a python script) from c++, using OS specific means to get a handle to its stdin. Then you stream text to its stdin through that handle. The python code is irrelevant -- it is just any process that takes input from stdin.
type: QuestionComment

parallel-processing
tags question: http://stackoverflow.com/q/47850890
tags question: http://stackoverflow.com/q/47735074
type: Tag
tag name: parallel-processing
tags question: http://stackoverflow.com/q/47721524
tags question: http://stackoverflow.com/q/47823063
tags question: http://stackoverflow.com/q/47718428
tags question: http://stackoverflow.com/q/47749619
tags question: http://stackoverflow.com/q/47804241
tags question: http://stackoverflow.com/q/47847389
tags question: http://stackoverflow.com/q/47728862
tags question: http://stackoverflow.com/q/47842829
tags question: http://stackoverflow.com/q/47725932

http://stackoverflow.com/a/47738834
accepted answer of: http://stackoverflow.com/q/47738537
answers question: http://stackoverflow.com/q/47738537
has comment: http://stackoverflow.com/comment/82441292
has comment: http://stackoverflow.com/comment/102480112
has comment: http://stackoverflow.com/comment/102440605
score: 10
type: Answer
has comment: http://stackoverflow.com/comment/82442313
upvote count: 10
has comment: http://stackoverflow.com/comment/82441119
has comment: http://stackoverflow.com/comment/102478379
has body: This is a bit of an iPython headshot that comes with Spyder. I've fallen foul of this when copy/pasting random bits of code from SO to test only to find really odd behaviour several days later - variables defined in the iPython console will also be in the script's global namespace indefinitely. There's two things you can do: A hard restart of the Kernel (ctrl + .) Follow up on this feature request thread where it's now possible to clear the namespace automatically every time you run a script.
has comment: http://stackoverflow.com/comment/82441208
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/82467584
comment on: http://stackoverflow.com/a/47753203
type: Comment
type: AnswerComment
has text: The last line invokes the rest of parent method. Therefore you don't need to repeat all logic but just add customization you need.
score: 0

http://stackoverflow.com/comment/120644215
has text: This gives me /usr/lib/cnf-update-db: not found
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/55518436

http://stackoverflow.com/comment/82609296
score: 0
comment on: http://stackoverflow.com/q/47823060
has text: Are you using [sklean.preprocessing.normalize](http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.normalize.html)? What is the type and dimension of `allsounds`?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82657391
comment on: http://stackoverflow.com/q/47846686
type: QuestionComment
has text: Because each call you copy the list, and copying happens in *O(n)*.
type: Comment
score: 0

http://stackoverflow.com/q/47745226
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82452468
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/47747119
has answer: http://stackoverflow.com/a/47746312
has title: Select radio button behind a label
tagged with: selenium-webdriver
upvote count: 0
answer count: 3
has body: I am having trouble selecting a particular radio button (Male or female) I have looked at several other posts to no avail. I get the error message: selenium.common.exceptions.ElementNotVisibleException: Message: element not visible (Session info: chrome=62.0.3202.94) (Driver info: chromedriver=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f),platform=Windows NT 10.0.16299 x86_64) HTML: Male Female My Code
has answer: http://stackoverflow.com/a/47746735
downvote count: 1
tagged with: selenium
has comment: http://stackoverflow.com/comment/82450556
favorite count: 0
type: Question
tagged with: python-3.x

http://stackoverflow.com/comment/82664403
comment on: http://stackoverflow.com/q/47849523
has text: @JordanBonitatis - post is edited. Classes are hidden because they don't matter here.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82529593
type: Comment
type: AnswerComment
has text: @tobias_k thanks i'm looking at the bable parse_decimal and how to determine what locale the number is.
score: 0
comment on: http://stackoverflow.com/a/47782748

http://stackoverflow.com/comment/82409570
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47724187
score: 0
has text: Oh, im sorry, I was just not looking close enough, i just looked at the first few characters and didnt see it changes later on. Thanks!

http://stackoverflow.com/q/47850993
downvote count: 1
has comment: http://stackoverflow.com/comment/82666395
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82667419
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82666471
tagged with: math
has comment: http://stackoverflow.com/comment/82666431
has answer: http://stackoverflow.com/a/47862709
tagged with: python
has title: How to put an integral in a function in python/matplotlib
score: 2
upvote count: 3
answer count: 2
has answer: http://stackoverflow.com/a/47851788
tagged with: sympy
has comment: http://stackoverflow.com/comment/82667646
has comment: http://stackoverflow.com/comment/82680347
has body: So pretty much, I am aiming to achieve a function f(x) My problem is that my function has an integral in it, and I only know how to construct definite integrals, so my question is how does one create an indefinite integral in a function (or there may be some other method I am currently unaware of) My function is defined as : (G is gravitational constant, although you can leave G out of your answer for simplicity, I'll add it in my code) Here is the starting point, but I don't know how to do the integral portion import numpy as np def f(x): rho = 5*(1/(1+((x**2)/(3**2)))) function_result = rho * 4 * np.pi * x**2 return function_result Please let me know if I need to elaborate on something. EDIT----------------------------------------------------- I made some major progress, but I still have one little error. Pretty much, I did this: from sympy import * x = Symbol('x') rho = p0()*(1/(1+((x**2)/(rc()**2))))* 4 * np.pi * x**2 fooply = integrate(rho,x) def f(rx): function_result = fooply.subs({x:rx}) return function_result Which works fine when I plug in one number for f; however, when I plug in an array (as I need to later), I get the error: raise SympifyError(a) sympy.core.sympify.SympifyError: SympifyError: [3, 3, 3, 3, 3] (Here, I did print(f([3,3,3,3,3]))). Usually, the function returns an array of values. So if I did f([3,2]) it should return [f(3),f(2)]. Yet, for some reason, it doesn't for my function.... Thanks in advance

http://stackoverflow.com/q/47742111
has title: Python, histogram from a dataframe
answer count: 0
has comment: http://stackoverflow.com/comment/82445662
tagged with: histogram
has body: Good time of the day, I am writting a function in python (I am using Spyder 3.6), which takes as inputs as dataframe and a label of the particular column. The function should return a histogram of that one column. def plot_dist(daily_returns,asset_name): daily_returns[asset_name].plot.hist(bins=20) plt.show() The dataframe daily_returns consists of 3 stocks' returns and an index date. The function is very simple, but I get the following mistake TypeError: unsupported operand type(s) for /: 'list' and 'int' It is worth mentioning that it works for a simple plot: def plot_dist(daily_returns,asset_name): daily_returns[asset_name].plot() plt.show() However, if I run the following function to build a histogram def plot_dist(daily_returns,asset_name): ax = daily_returns.ix[:,[asset_name]] ax.plot.hist(bins=20) plt.show() it works. I do not like to create an extra dataframe ax and the usage of df.ix[] looks to bulky. I would appreciate if someone could help me to understand why my first function does not work. Thanks in advance
type: Question
has comment: http://stackoverflow.com/comment/82483361
type: UnansweredQuestion
tagged with: dataframe
tagged with: python
score: 0

http://stackoverflow.com/comment/82413261
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47726325
score: 0
has text: Thank you! I appreciate the Notes as well, very helpful you new coders!

http://stackoverflow.com/comment/82356505
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47697880
type: QuestionComment
has text: Is the word dude, for instance, in the lexicon of the original training set?

http://stackoverflow.com/comment/82584520
score: 0
has text: Make sure you have saved and changes to files and restarted your server.
comment on: http://stackoverflow.com/q/47811629
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/82612347
score: 0
has text: @ewizard it will work with `json.loads` however you will find that the resulting dictionary will have more json strings in it such as the value for `"res"` being a json string.
type: Comment
comment on: http://stackoverflow.com/q/47824853
type: QuestionComment

m2m
tags question: http://stackoverflow.com/q/47698836
type: Tag
tag name: m2m

http://stackoverflow.com/a/47703560
has comment: http://stackoverflow.com/comment/82367430
type: Answer
has comment: http://stackoverflow.com/comment/82369509
has body: I'd use pandas import pandas as pd col_test = [1L, 2L, 3L, 4L, 5L] data = pd.read_excel('workbook.xlsx', 'INPUT') # Write to specific column name start_row = 5 for i, val in enumerate(col_test): data.iloc[start_row + i, 'COL_NAME'] = val writer = pd.ExcelWriter('output.xlsx') data.to_excel(writer, 'NewSheet') Assigning values to particular cell read_excel to_excel
score: 0
has comment: http://stackoverflow.com/comment/82367584
has comment: http://stackoverflow.com/comment/82368750
has comment: http://stackoverflow.com/comment/82367551
answers question: http://stackoverflow.com/q/47703314

http://stackoverflow.com/comment/82558858
type: QuestionComment
has text: check EDIT 1@COLDSPEED
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47798708

http://stackoverflow.com/a/47794962
score: 0
answers question: http://stackoverflow.com/q/47794918
type: Answer
has body: pack generates a side-effect and returns None, maybe try: sbcount = Spinbox(tab1, from_ = 1, to = 20, textvariable = countmin) sbcount.pack()

http://stackoverflow.com/comment/114742247
type: QuestionComment
comment on: http://stackoverflow.com/q/47837443
type: Comment
has text: Anyone resolve this? I am struggling with the same issue two years later ...
score: 0

http://stackoverflow.com/comment/82366896
score: 1
comment on: http://stackoverflow.com/q/47699542
type: Comment
type: QuestionComment
has text: Related: https://stackoverflow.com/questions/16776761/color-each-errorbar-with-different-color

http://stackoverflow.com/q/47746899
has comment: http://stackoverflow.com/comment/82454039
duplicate of: http://stackoverflow.com/q/3470215
tagged with: python-2.7
score: 0
has title: How to pass data(Args,parameter,list ..etc) from python2 to python3 in memory?
answer count: 1
has body: Owing to some reason,I must use "win32com" this module to output my Dataframe from another appication (But this module seems to be only in python2). However , I want to do some calculate in python3 with this Dataframe(output by python2). How can I send the Dataframe from python2 to python3 in memory? (Except to output the data to the file) Supplementary explanation 1: My os is Win10 64bit (both contain python2 and python3) In short , I want to know how can I pass the Data(produced by python2) to python3. Supplementary explanation 2: I have a A python script and it need to run in python2. A python script will generated some data(maybe json , dataframe ..) And then I want pass this data to B python script B python script must run in python3. My os is win10 64bits(both have python2 and 3). I am a new to python , I have tried "out the data to the file ,then B.py read the file". However this I/O way is too slow , so I want pass data in memory , how can I do that? (My English is not very good, please entertain me )
type: Question
has comment: http://stackoverflow.com/comment/82464763
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47747387
linked to: http://stackoverflow.com/q/3470215
has comment: http://stackoverflow.com/comment/82458119
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/82530239
has text: @JakobLovern https://wiki.python.org/moin/PythonSpeed#Use_the_best_algorithms_and_fastest_tools
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47784317

http://stackoverflow.com/a/47836931
type: Answer
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47836837
has body: OptionMenu(master=UI.window,variable=standard_move,*list(UI.party[UI.control.get()].normal_moves)) When you mix keyword arguments and packed positional arguments like this, the *list gets bound to the positional parameters first, putting the first element of the list for master, the second for variable, and the remainder for the option items. Then the keyword arguments try to bind themselves to master and variable, but a TypeError occurs because those names already have a value. Consider this simpler example: def f(a,b,c): print(a,b,c) f(a=23, *[42,99]) #TypeError: f() got multiple values for argument 'a' Try passing in the first two arguments without using their names. standard_moves=tkinter.OptionMenu(UI.window,standard_move,*list(UI.party[UI.control.get()].normal_moves))
accepted answer of: http://stackoverflow.com/q/47836837

http://stackoverflow.com/comment/83029763
type: AnswerComment
has text: Yes, but things like "context" are still fuzzy for me. I think this is incorrect: '{{ Table1.form.as_p }}' but this is correct: '{% render_table table1 %}'
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47895926

http://stackoverflow.com/comment/82591964
has text: `print([i for i in ["abc", "xyz"] if not i.startswith('a')])`
comment on: http://stackoverflow.com/q/47815291
score: 3
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47772976
has title: Python sympy.Plot - OverflowError: int too large to convert to float
answer count: 1
downvote count: 0
upvote count: 1
score: 1
has body: So i want to display the g function as a graph but whenever i run it, it returns the OverflowError in the title and i can't figure out why. Can anyone help? %matplotlib inline import sympy as sym def g(x): return 1 - (sym.factorial(365) / ((365 ** x) * sym.factorial(365 - x))) sym.plot(f(x), (x, 0, 100), ylim=(0, 1))
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82507026
tagged with: sympy
has answer: http://stackoverflow.com/a/47785587
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82517332
tagged with: python

http://stackoverflow.com/a/47742137
has comment: http://stackoverflow.com/comment/82444731
downvote count: 0
has body: or you can not use regex in this case, which is maintainable and readable: line = "[RUN #1 3%, 2 secs] 2 threads: 6673 ops, 3511 (avg: 3333) ops/sec, 3.60MB/sec (avg: 3.42MB/sec), 0.56 (avg: 0.59) msec latency" answer = line.split() print answer[9], answer[16]
has comment: http://stackoverflow.com/comment/82444531
type: Answer
score: 4
upvote count: 4
answers question: http://stackoverflow.com/q/47742001

http://stackoverflow.com/a/47800806
type: Answer
answers question: http://stackoverflow.com/q/47799925
downvote count: 0
upvote count: 1
has body: I don't know of a really clean solution to this, but one way to approach it manually is as follows: import pandas as pd import numpy as np df = pd.read_csv('tmp.csv', skip_blank_lines=False) # add a blank row at the end df = df.reindex(np.arange(len(df.index) + 1)) # add an index of the third dimension indices = df[df.isnull().all(1)].index df['level'] = pd.Series(range(len(indices)), index=indices) df['level'].fillna(method='bfill', inplace=True) # reset indices within each "group" df = df.groupby('level').apply(lambda x: x.reset_index()) df = df.drop(['level', 'index'], axis=1).dropna(how='all') The result is a multiply-indexed dataframe representing your 3D data.
score: 1

http://stackoverflow.com/q/47757888
downvote count: 0
favorite count: 0
type: Question
upvote count: 3
score: 3
has body: I am following the popular NER example of Spacy: https://github.com/explosion/spaCy/blob/master/examples/training/train_ner.py They use create_pipe and add_pipe to build the pipeline: def main(model=None, output_dir=None, n_iter=100): """Load the model, set up the pipeline and train the entity recognizer.""" if model is not None: nlp = spacy.load(model) # load existing spaCy model print("Loaded model '%s'" % model) else: nlp = spacy.blank('en') # create blank Language class print("Created blank 'en' model") # create the built-in pipeline components and add them to the pipeline # nlp.create_pipe works for built-ins that are registered with spaCy if 'ner' not in nlp.pipe_names: ner = nlp.create_pipe('ner') nlp.add_pipe(ner, last=True) # otherwise, get it so we can add labels else: ner = nlp.get_pipe('ner') # add labels for _, annotations in TRAIN_DATA: for ent in annotations.get('entities'): ner.add_label(ent[2]) # get names of other pipes to disable them during training other_pipes = [pipe for pipe in nlp.pipe_names if pipe != 'ner'] with nlp.disable_pipes(*other_pipes): # only train NER optimizer = nlp.begin_training() for itn in range(n_iter): random.shuffle(TRAIN_DATA) losses = {} for text, annotations in TRAIN_DATA: nlp.update( [text], # batch of texts [annotations], # batch of annotations drop=0.5, # dropout - make it harder to memorise data sgd=optimizer, # callable to update weights losses=losses) print(losses) I would like to set n_threads, as it is documented for nlp.pipe here. However, following their example there does not seem to be the possibility to specify the number of threads if nlp.pipe is not explicitly called. Am I missing something or do I need to rebuild using nlp.pipe?
tagged with: python
answer count: 0
tagged with: spacy
has title: Python spaCy: how to set n_threads with create_pipe and add_pipe
type: UnansweredQuestion
tagged with: multithreading

http://stackoverflow.com/a/47846540
score: 2
has comment: http://stackoverflow.com/comment/82657395
has body: json_data['results'][0]['geometry'] is a _dict_. This means that, for x in json_data['results'][0]['geometry'] will result in iteration over the keys, where x is a loop variable that is assigned a key (string). Here's an example - d = {'a' : 'b', 'c' : 'd'} for each in d: print(x) a c Since each is a string, each['lat'] would be an invalid operation (since you can't index a string with anything besides an integer). Observe the structure of your JSON file - { "location_type": "GEOMETRIC_CENTER", ... "location": { "lng": 103.8529918, "lat": 1.3097033 } } Carefully observe that only location has a dict with lat and lng keys associated with it. If all you want are these values, then just index them directly. A loop is not needed. x = json_data['results'][0]['geometry']['location'] lat, lng = x['lat'], x['lng']
answers question: http://stackoverflow.com/q/47846457
upvote count: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47846457
has comment: http://stackoverflow.com/comment/82657419
type: Answer

http://stackoverflow.com/comment/82643287
score: 1
type: Comment
comment on: http://stackoverflow.com/q/47838519
type: QuestionComment
has text: in `DevTool` I use tab `Network` and select `XHR` to see only javascript requests. And I see url `http://members.tsetmc.com/tsev2/data/InstTradeHistory.aspx?i=9211775239375291&Top=999999&A=0` and it sends data like `20171213@901.00@863.00@893.00@901.00@901.00@859.00@411324010096.00@460750068@...` and there are values `901.00`, `863.00`, etc. which I see in table on the page.

http://stackoverflow.com/comment/82489813
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47749257
has text: Thank you, but client I verify true, verifySignature I create only check it works from android. The data I sign both java side and python side is "haha". h.hexdigest() in python and sha256(data).getBytes() return same value.

http://stackoverflow.com/comment/108795297
score: 1
comment on: http://stackoverflow.com/a/47785513
has text: This solution also works for MacOS, just need to change the executable path.
type: Comment
type: AnswerComment

http://stackoverflow.com/a/47705495
has comment: http://stackoverflow.com/comment/84392883
has comment: http://stackoverflow.com/comment/84514749
score: 8
has comment: http://stackoverflow.com/comment/84420972
has comment: http://stackoverflow.com/comment/84443283
has comment: http://stackoverflow.com/comment/124927284
has comment: http://stackoverflow.com/comment/84410104
upvote count: 8
has comment: http://stackoverflow.com/comment/84513176
has comment: http://stackoverflow.com/comment/84442210
type: Answer
has comment: http://stackoverflow.com/comment/84514232
has comment: http://stackoverflow.com/comment/84404897
has comment: http://stackoverflow.com/comment/84408519
has comment: http://stackoverflow.com/comment/84442814
has comment: http://stackoverflow.com/comment/84444185
has comment: http://stackoverflow.com/comment/84496405
has comment: http://stackoverflow.com/comment/84444129
answers question: http://stackoverflow.com/q/47704008
has body: Bresenham may be smart but I'm pretty sure brute force vectorization is faster. I've written two variants - the first is easier to read, the second is faster (80 us vs 50 us). Update Fixed a bug (thanks @Varlor) and added an nd variant. import numpy as np from timeit import timeit def connect(ends): d0, d1 = np.abs(np.diff(ends, axis=0))[0] if d0 &gt; d1: return np.c_[np.linspace(ends[0, 0], ends[1, 0], d0+1, dtype=np.int32), np.round(np.linspace(ends[0, 1], ends[1, 1], d0+1)) .astype(np.int32)] else: return np.c_[np.round(np.linspace(ends[0, 0], ends[1, 0], d1+1)) .astype(np.int32), np.linspace(ends[0, 1], ends[1, 1], d1+1, dtype=np.int32)] def connect2(ends): d0, d1 = np.diff(ends, axis=0)[0] if np.abs(d0) &gt; np.abs(d1): return np.c_[np.arange(ends[0, 0], ends[1,0] + np.sign(d0), np.sign(d0), dtype=np.int32), np.arange(ends[0, 1] * np.abs(d0) + np.abs(d0)//2, ends[0, 1] * np.abs(d0) + np.abs(d0)//2 + (np.abs(d0)+1) * d1, d1, dtype=np.int32) // np.abs(d0)] else: return np.c_[np.arange(ends[0, 0] * np.abs(d1) + np.abs(d1)//2, ends[0, 0] * np.abs(d1) + np.abs(d1)//2 + (np.abs(d1)+1) * d0, d0, dtype=np.int32) // np.abs(d1), np.arange(ends[0, 1], ends[1,1] + np.sign(d1), np.sign(d1), dtype=np.int32)] def connect_nd(ends): d = np.diff(ends, axis=0)[0] j = np.argmax(np.abs(d)) D = d[j] aD = np.abs(D) return ends[0] + (np.outer(np.arange(aD + 1), d) + (aD//2)) // aD ends = np.array([[ 1520, -1140], [ 1412, -73]]) ends_4d = np.array([[ 100, -302, 101, -49], [ -100, -45, 112, 100]]) print(connect(ends)) print(connect_nd(ends_4d)) assert np.all(connect(ends)==connect2(ends)) assert np.all(connect(ends)==connect_nd(ends)) assert np.all(connect(ends)==connect(ends[:, ::-1])[:, ::-1]) assert np.all(connect(ends)==connect(ends[::-1])[::-1]) print(timeit('f(ends)', globals={'f': connect, 'ends': ends}, number=10000)*100, 'us') print(timeit('f(ends)', globals={'f': connect2, 'ends': ends}, number=10000)*100, 'us') print(timeit('f(ends)', globals={'f': connect_nd, 'ends': ends}, …
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47704008

http://stackoverflow.com/a/47782958
answers question: http://stackoverflow.com/q/47782878
type: AcceptedAnswer
has body: One option for single-pass replacement is re.sub: x = re.sub(r'\bVAR(\d+)\b', lambda m: rndvar[int(m.group(1)) - 1], x) You could also use a simple zip loop to replace in passes: for placeholder, replacement in enumerate(('VAR1', 'VAR2'), rndvar): x = x.replace(placeholder, replacement)
upvote count: 2
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/47782878
has comment: http://stackoverflow.com/comment/82527728
score: 2

http://stackoverflow.com/comment/82444877
type: Comment
score: 0
type: AnswerComment
has text: and in that case, I'm required to do that through a class. I will be more than happy if you can explain a little bit more about this case. thanks @Ben Darnell.
comment on: http://stackoverflow.com/a/47739848

http://stackoverflow.com/q/47802766
has body: I am using python 2.7 to control a Newport 1936-R power meter which uses custom .dll. It is not VISA (Virtual Instrument Software Architecture) compatible so I can't use pyvisa. I have installed the USB driver which contains the dll named usbdll.dll. I copied the dll to a system folder so that it is visible. When using Python.Net I can AddReference but when I import the dll I get the error No module named usbdll. My Python.Net version is 2.3.0
tagged with: python
has answer: http://stackoverflow.com/a/47823523
score: 2
tagged with: python.net
tagged with: python-2.7
has title: Python.Net cannot import dll
answer count: 2
upvote count: 2
downvote count: 0
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47806817
tagged with: dll
type: UnansweredQuestion

http://stackoverflow.com/a/48412773
score: -5
upvote count: 0
type: Answer
downvote count: 5
has body: Here is a work around - start cmd shell . Run - activate . Check - conda env list . Start powershell - powershell .
answers question: http://stackoverflow.com/q/47800794

http://stackoverflow.com/comment/82668512
has text: I am trying to solve the travelling salesman problem. The nested list is the distance matrix for 4 different cities. So choosing zeros would not make sense. So I replaced all the zeros by a very high number and now the next problem I am stuck is about not repeating the indexes.
score: 0
comment on: http://stackoverflow.com/q/47851935
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47729808
type: Answer
score: 0
has body: According to official documentation the the token key should be Authentication and the token should be should be trailing Token and a white space. In your code change token {} to Token {}. If the problem persists try to print request headers in you view by printing request.META to check the key.
answers question: http://stackoverflow.com/q/47729164

http://stackoverflow.com/q/47739358
has title: How to insert (change values) matrix in matrix? Python (numpy)
has answer: http://stackoverflow.com/a/47739471
tagged with: python
has answer: http://stackoverflow.com/a/47739418
possible better answer: http://stackoverflow.com/a/47739418
has comment: http://stackoverflow.com/comment/82439099
has comment: http://stackoverflow.com/comment/82438962
type: AnsweredQuestion
score: 0
has body: For example, I have a matrix: [ [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] ] I want to insert [ [-1 -1 -1], [0 5 0] ] in some position, like: [ [1 2 3 4 5], [6 7 8 9 10], [11 -1 -1 -1 15], [16 0 5 0 20], [21 22 23 24 25] ]
answer count: 3
upvote count: 1
tagged with: matrix
has comment: http://stackoverflow.com/comment/82439028
downvote count: 1
has answer: http://stackoverflow.com/a/47739683
accepted answer: http://stackoverflow.com/a/47739683
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82439494
tagged with: numpy

http://stackoverflow.com/q/47716536
tagged with: linux
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82394694
tagged with: pyqt4
has title: How upgrade FigureCanvas programmed on pyQT4 for pyQT5
tagged with: python
has comment: http://stackoverflow.com/comment/82396115
tagged with: python-2.7
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/82396830
tagged with: pyqt5
type: Question
has body: This is a part of a code that show a figure. I was using this with pyqt4 on windows, but on linux I use anaconda, so just have pyqt5 and when I update this code dont work. Anyone knows how install pyqt4 on linux or how update this code to pyqt5? (Python 2.7) from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar def showfig(self): self.main_frame = QWidget() self.figure = plt.figure() self.ax = self.figure.add_subplot(111) # this is the Canvas Widget that displays the `figure` # it takes the `figure` instance as a parameter to __init__ self.canvas = FigureCanvas(self, self.figure) self.canvas.setParent(self.main_frame) self.kpress = self.figure.canvas.mpl_connect('key_press_event', self.flip) self.mpress = self.figure.canvas.mpl_connect('button_press_event', self.on_press) self.mrelea = self.figure.canvas.mpl_connect('button_release_event', self.on_release) self.kmove = self.figure.canvas.mpl_connect('motion_notify_event', self.on_motion) self.canvas.setFocusPolicy( Qt.ClickFocus ) self.canvas.setFocus() EDIT: This is the error that appear overlay loaded Traceback (most recent call last): File "editor.py", line 1006, in newover self.overset = Overset(parent=self) File "editor.py", line 650, in __init__ self.showfig() File "editor.py", line 746, in showfig self.canvas = FigureCanvas(self, self.figure) TypeError: __init__() takes exactly2 arguments (3 given)

http://stackoverflow.com/q/47821383
has answer: http://stackoverflow.com/a/47823744
has title: Cannot plot my function : return array(a, dtype, copy=False, order=order) TypeError: float() argument must be a string or a number
tagged with: plot
has comment: http://stackoverflow.com/comment/82609286
has comment: http://stackoverflow.com/comment/82605917
has comment: http://stackoverflow.com/comment/82610155
has body: I'm trying to plot a function that gives the arctan of the angle of several scatterplots (it's a physics experiment): Here is my code: import numpy as np import matplotlib.pyplot as plt filename='rawPhaseDataf2f_17h_15m.dat' datatype=np.dtype( [('Shotnumber',np.dtype('&gt;f8')),('A1',np.dtype('&gt;f8')), ('A2',np.dtype('&gt;f8')), ('f2f',np.dtype('&gt;f8')), ('intensity',np.dtype('&gt;f8'))]) data=np.fromfile(filename,dtype=datatype) #time=data['Shotnumber']/9900 # reprate is 9900 Hz -&gt; time in seconds A1=data['A1'] A2=data['A2'] #np.sort() i=range(1,209773) def x(i) : return arctan((A1.item(i)/A2.item(i))*(i/209772)) def y(i) : return i*2*pi/209772 plot(x,y) plt.figure('Scatterplot') plt.plot(A1,A2,',') #Scatterplot plt.xlabel('A1') plt.ylabel('A2') plt.figure('2D Histogram') plt.hist2d(A1,A2,100) # 2D Histogram plt.xlabel('A1') plt.ylabel('A2') plt.show() My error is: Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/lib/python2.7/dist-packages/spyderlib/widgets/externalshell /sitecustomize.py", line 540, in runfile execfile(filename, namespace) File "/home/nelly/Bureau/ Téléchargements/Kr4 Experiment/read_rawPhaseData.py", line 21, in &lt;module&gt; plot(x,y) File "/usr/lib/pymodules/python2.7/matplotlib/pyplot.py", line 2987, in plot ret = ax.plot(*args, **kwargs) File "/usr/lib/pymodules/python2.7/matplotlib/axes.py", line 4138, in plot self.add_line(line) File "/usr/lib/pymodules/python2.7/matplotlib/axes.py", line 1497, in add_line self._update_line_limits(line) File "/usr/lib/pymodules/python2.7/matplotlib/axes.py", line 1508, in _update_line_limits path = line.get_path() File "/usr/lib/pymodules/python2.7/matplotlib/lines.py", line 743, in get_path self.recache() File "/usr/lib/pymodules/python2.7/matplotlib/lines.py", line 420, in recache x = np.asarray(xconv, np.float_) File "/usr/lib/python2.7/dist-packages/numpy/core/numeric.py", line 460, in asarray return array(a, dtype, copy=False, order=order) TypeError…
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82605859
score: 0
has comment: http://stackoverflow.com/comment/82606135
tagged with: matrix
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/82609524
has comment: http://stackoverflow.com/comment/82605380
tagged with: python
accepted answer: http://stackoverflow.com/a/47823744
type: Question
has comment: http://stackoverflow.com/comment/82609759
has comment: http://stackoverflow.com/comment/82605726
has comment: http://stackoverflow.com/comment/82605620
has comment: http://stackoverflow.com/comment/82610079
has comment: http://stackoverflow.com/comment/82605304
has comment: http://stackoverflow.com/comment/82606816
tagged with: function
answer count: 1
has comment: http://stackoverflow.com/comment/82609411

http://stackoverflow.com/a/47933103
downvote count: 0
has body: What you're trying to do is perfectly possible and will probably involve writing your own request iterator object that can be given responses as they arrive rather than using a simple generator as your request iterator. Perhaps something like class MySmarterRequestIterator(object): def __init__(self): self._lock = threading.Lock() self._responses_so_far = [] def __iter__(self): return self def _next(self): # some logic that depends upon what responses have been seen # before returning the next request message return &lt;your message value&gt; def __next__(self): # Python 3 return self._next() def next(self): # Python 2 return self._next() def add_response(self, response): with self._lock: self._responses.append(response) that you then use like my_smarter_request_iterator = MySmarterRequestIterator() responses = stub.MyEventStream(my_smarter_request_iterator) for response in responses: my_smarter_request_iterator.add_response(response) . There will probably be locking and blocking in your _next implementation to handle the situation of gRPC Python asking your object for the next request that it wants to send and your responding (in effect) "wait, hold on, I don't know what request I want to send until after I've seen how the next response turned out".
score: 13
upvote count: 13
has comment: http://stackoverflow.com/comment/84546322
accepted answer of: http://stackoverflow.com/q/47831895
type: Answer
has comment: http://stackoverflow.com/comment/82837667
has comment: http://stackoverflow.com/comment/82963949
answers question: http://stackoverflow.com/q/47831895
type: AcceptedAnswer

http://stackoverflow.com/q/47814042
has answer: http://stackoverflow.com/a/47821984
accepted answer: http://stackoverflow.com/a/47821984
tagged with: sqlite
answer count: 1
type: Question
has title: Appending and Retrieving Lists from SqlLite3 using Python
has body: In my example i need to store a list of ints and a list of strings int a database. I'm currently just converting the entire list of ints and list of strings into a single int. I was wondering if this was an ideal workflow or if anyone had some alternative recommendations on how i could handle this. My concern with storing it as a string is how would i late then retrieve that information properly as a pythonic list of ints and strings? import sqlite3 import hashlib database = 'test.db' def create_table(): connection = sqlite3.connect(database) cursor = connection.cursor() cursor.execute("CREATE TABLE IF NOT EXISTS assets(url BLOB UNIQUE, colors BLOB, tags BLOB)") connection.commit() cursor.close() connection.close() def kill_table(): connection = sqlite3.connect(database) cursor = connection.cursor() cursor.execute('''DROP TABLE IF EXISTS assets''') connection.commit() def read_from_db(): connection = sqlite3.connect(database) cursor = connection.cursor() cursor.execute('SELECT * FROM assets') data = cursor.fetchall() print(len(data)) for row in data: print(row) cursor.close() connection.close() def get_data_entry(url=''): connection = sqlite3.connect(database) cursor = connection.cursor() url = hashlib.md5(url).hexdigest() cursor.execute('SELECT * FROM assets WHERE url=?', (url,)) data = cursor.fetchall() if len(data) == 1: return data[0] else: print 'Found multiple entry instances' return False def append_data_entries(url, colors, tags): ''' Args: url (str): name of image item colors (list): list of dominant image colors tags (list): list of tags ''' if not url or not colors or not tags: return False url = hashlib.md5(url).hexdigest() colors = str(colors) tags = str(tags) # updates or inserts cursor.execute("REPLACE INTO assets(url, colors, tags) VALUES (?, ?, ?)", (url, colors, tags)) return True if __name__ == '__main__': 'Example' kill_table() create_table() # add test data to database connection = sqlite3.connect(database) cursor = connection.cursor() for i in …
tagged with: python
type: AnsweredQuestion
score: 0

http://stackoverflow.com/q/47728499
tagged with: python
tagged with: php
has body: I have got the following HTML form with several complicated input elements: &lt;input type="text" name="images[1]"&gt; &lt;input type="text" name="images[2]"&gt; &lt;input type="text" name="video[1]"&gt; &lt;input type="text" name="video[2]"&gt; When I talk about cimplicated inputs I mean sophisticated name of elements: name="images[1]" Where images is indicate group of input and [1] number or identificator of input. Using PHP approach of handling form It can be achieved like: if(isset($_POST['images'])) { foreach($_POST['images'] as $index) { // $key echo $_POST['images'][$index]; // or key } } How to reproduce this in Python?
has answer: http://stackoverflow.com/a/47728569
linked to: http://stackoverflow.com/q/6881221
tagged with: python-2.7
score: 2
upvote count: 2
type: AnsweredQuestion
answer count: 2
accepted answer: http://stackoverflow.com/a/47728658
downvote count: 0
duplicate of: http://stackoverflow.com/q/6881221
has comment: http://stackoverflow.com/comment/82418993
has answer: http://stackoverflow.com/a/47728658
favorite count: 0
has title: How to handle complicated input form in Python according PHP approach?
type: Question
linked to: http://stackoverflow.com/q/464040
possible better answer: http://stackoverflow.com/a/47728569

http://stackoverflow.com/q/47839705
has body: I have an array, I need to return the index of an element if the target matches, without using the index(). For example we have a=[12,31,45,67,100,101]. If the target is 101, we will return 5, otherwise -1. What I did is: def target_meet(a,t): for i in range(len(a)): if a[i]==t: return i else: return -1 It gives me the wrong output. Kindly help. Thanks.
has answer: http://stackoverflow.com/a/47839753
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82643492
has comment: http://stackoverflow.com/comment/82643867
tagged with: python
has answer: http://stackoverflow.com/a/47839741
score: -1
has title: Returning an index of an element in python if an element matches
downvote count: 2
answer count: 3
has comment: http://stackoverflow.com/comment/82643650
has comment: http://stackoverflow.com/comment/82649403
has answer: http://stackoverflow.com/a/47842615
has comment: http://stackoverflow.com/comment/82643508
favorite count: 0
type: Question
upvote count: 1

http://stackoverflow.com/a/47886145
downvote count: 1
accepted answer of: http://stackoverflow.com/q/47850064
type: Answer
score: 40
has comment: http://stackoverflow.com/comment/120948537
has comment: http://stackoverflow.com/comment/130962016
has body: A repository on GitHub helped me to find a solution to my question. I've used the shutil module and .spec file to add extra data files (in my case, a config-sample.ini file) to dist folder using the PyInstaller --onefile option. Make a .spec file for PyInstaller First of all, I've created a makespec file with the options I needed: pyi-makespec --onefile --windowed --name exefilename scriptname.py This command creates an exefilename.spec file to use with PyInstaller. Modify exefilename.spec, adding shutil.copyfile Now I've edited the exefilename.spec, adding the following code at the end of the file. import shutil shutil.copyfile('config-sample.ini', '{0}/config-sample.ini'.format(DISTPATH)) shutil.copyfile('whateveryouwant.ext', '{0}/whateveryouwant.ext'.format(DISTPATH)) This code copies the data files needed at the end of the compile process. You could use all the methods available in the shutil package. Run PyInstaller The final step is to run the compile process pyinstaller --clean exefilename.spec The result is that in the dist folder you should have the compiled .exe file together with the data files copied. Consideration In the official documentation of PyInstaller I didn't find an option to get this result. I think it could be considered as a workaround... that works.
upvote count: 41
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47850064

http://stackoverflow.com/q/47782650
has answer: http://stackoverflow.com/a/47785513
downvote count: 0
tagged with: selenium
possible better answer: http://stackoverflow.com/a/47784565
has comment: http://stackoverflow.com/comment/82532671
answer count: 7
has answer: http://stackoverflow.com/a/54460199
favorite count: 0
has answer: http://stackoverflow.com/a/53462171
has comment: http://stackoverflow.com/comment/82559056
upvote count: 40
score: 40
type: Question
linked to: http://stackoverflow.com/q/47073748
has body: I must have some versions here that don't match up since I can't get Selenium with Python to fire up a Firefox web browser. I'm using an older version of Firefox because other people in here have the same old version of Python and for them the old version of Firefox works best. Code: from selenium import webdriver from selenium import common from selenium.webdriver import ActionChains 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 from selenium.common.exceptions import NoSuchElementException from selenium.webdriver.common.desired_capabilities import DesiredCapabilities driver=webdriver.Firefox(capabilities=DesiredCapabilities.FIREFOX) Error: Traceback (most recent call last): File "scrapeCommunitySelenium.py", line 13, in &lt;module&gt; driver=webdriver.Firefox(capabilities=DesiredCapabilities.FIREFOX) File "/Library/Python/2.7/site-packages/selenium/webdriver/firefox/webdriver.py", line 158, in __init__ keep_alive=True) File "/Library/Python/2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 154, in __init__ self.start_session(desired_capabilities, browser_profile) File "/Library/Python/2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 243, in start_session response = self.execute(Command.NEW_SESSION, parameters) File "/Library/Python/2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 311, in execute self.error_handler.check_response(response) File "/Library/Python/2.7/site-packages/selenium/webdriver/remote/errorhandler.py", line 237, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.SessionNotCreatedException: Message: Unable to find a matching set of capabilities Version info: Python 2.7.10 Selenium 3.8.0 Firefox 46.0 GeckoDriver 0.19.1 (It's in a folder which is in my PATH environment variable) MacOS 10.12…
tagged with: firefox
tagged with: geckodriver
has answer: http://stackoverflow.com/a/59999320
linked to: http://stackoverflow.com/q/45510338
tagged with: python
linked to: http://stackoverflow.com/q/45329528
has answer: http://stackoverflow.com/a/47784565
has answer: http://stackoverflow.com/a/59015416
tagged with: selenium-webdriver
linked to: http://stackoverflow.com/q/49947694
has answer: http://stackoverflow.com/a/62353442
accepted answer: http://stackoverflow.com/a/47785513
type: AnsweredQuestion
has title: selenium.common.exceptions.SessionNotCreatedException: Message: Unable to find a matching set of capabilities with Firefox 46 through Selenium

http://stackoverflow.com/q/47844328
score: -2
tagged with: http://stackoverflow.com/tag/csv
has title: CSV file writing by using python?
downvote count: 2
tagged with: python
has answer: http://stackoverflow.com/a/47846427
type: AnsweredQuestion
upvote count: 0
has comment: http://stackoverflow.com/comment/82652795
answer count: 1
accepted answer: http://stackoverflow.com/a/47846427
has comment: http://stackoverflow.com/comment/82653224
has body: "ABC - PQR - ""$6,000 PY"" - 02/23/17 - 01/31/18" "LMN - OPQ, XYZ - ""A: 432 XYZ, LMN, PQR"" I have above strings. str=["ABC - PQR - ""$6,000 PY"" - 02/23/17 - 01/31/18", "LMN - OPQ, XYZ - ""A: 432 XYZ, LMN, PQR""] with open('abc.csv', 'wb') as file: for str1 in str: file.write('\"' + str1 + '\"\n') file.close() I have to write these strings in csv file by using python. I am getting these strings in seperate columns. How can I get these string in one column?
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82653063

http://stackoverflow.com/comment/82525164
type: Comment
comment on: http://stackoverflow.com/a/47781893
has text: Well, the original match is also not capturing anything, so that makes sense
type: AnswerComment
score: 1

http://stackoverflow.com/comment/82422595
comment on: http://stackoverflow.com/a/47730866
score: 0
type: Comment
has text: It's a long time since I used a Mac on Linux you put it in /usr/local/bin/ is it the same on a Mac?
type: AnswerComment

http://stackoverflow.com/a/65275738
answers question: http://stackoverflow.com/q/47759491
has body: I have written a download method for zip file download. this could be helpful. after clicking on download button this method will be called and waiting until the download complete def downloader() : print("File Download Started.......") sleep(60) while True: file = glob.glob(BASE_FILE_DIR+'*.zip.part') if file: print("Download Pending.......") sleep(60) continue else: print('File Downloaded') break
type: Answer
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/comment/84821822
comment on: http://stackoverflow.com/a/48875676
type: Comment
score: 0
type: AnswerComment
has text: The reason I asked if you would not post to Github is because Dr.'s Finlayson, et. al., have students who must implement the code as part of their coursework. I think I'm going to ask again if I can submit a pull request to OpenCV to add their algorithm to the library, making sure to give them credit. I don't believe there is anything legally preventing us from posting to GitHub as Python is open source, but I'm simply doing it out of honor. Let me see if I can get in touch with them again. Again, @Shawn Mathew thank you so much and good luck!

http://stackoverflow.com/comment/82452461
comment on: http://stackoverflow.com/q/47746039
type: Comment
has text: what name? variable name ? use dictionary to keep buttons.
score: 0
type: QuestionComment

http://stackoverflow.com/comment/82538327
type: QuestionComment
has text: Is possible see your file data, e.g. upload files or send them to my email?
comment on: http://stackoverflow.com/q/47788448
score: 0
type: Comment

http://stackoverflow.com/a/47774712
has comment: http://stackoverflow.com/comment/82512650
score: 0
answers question: http://stackoverflow.com/q/47768406
has comment: http://stackoverflow.com/comment/82513586
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82512634
accepted answer of: http://stackoverflow.com/q/47768406
has comment: http://stackoverflow.com/comment/82513606
has body: Starting with - df = pd.DataFrame(...) # your data df A B C 0 1 2 PRODUCT_1 1 3 2 PRODUCT_2 2 3 2 PRODUCT_4 3 3 2 PRODUCT_5 4 5 2 PRODUCT_1 5 3 2 PRODUCT_3 Find uniques first, using uniques = df.C.unique() uniques array(['PRODUCT_1', 'PRODUCT_2', 'PRODUCT_4', 'PRODUCT_5', 'PRODUCT_3'], dtype=object) To get all rows from a particular product, I'd do this using groupby (so, you actually don't need uniques here) - acc = {} for i, g in df.groupby('C'): X, y = g['A'], g['B'] p = model.predict(X, y) acc[i] = (p == y).sum() / len(y) Basically, for each group, call model.predict and append a key-value pair to the acc dict.
type: Answer

http://stackoverflow.com/comment/82450171
score: 0
has text: Thanks for your help so far. Have tried the updated SQL and am getting the following error: Traceback (most recent call last): File "smartoysters_06122017_V1.py", line 165, in <module> calldb(conn, sql_cmd) File "smartoysters_06122017_V1.py", line 27, in calldb cur.execute(sql_cmd) psycopg2.ProgrammingError: syntax error at or near "%" LINE 7: SELECT %s AS MyJSON ^
type: AnswerComment
comment on: http://stackoverflow.com/a/47744840
type: Comment

http://stackoverflow.com/a/47814300
answers question: http://stackoverflow.com/q/47814258
type: Answer
score: 2
downvote count: 0
has body: Use bash -c command: find . -type f -exec bash -c 'mv "$1" $(urlencode "$1")' _ {} \;
upvote count: 2

http://stackoverflow.com/q/47712374
has comment: http://stackoverflow.com/comment/85298932
has comment: http://stackoverflow.com/comment/85274282
tagged with: svm
type: Question
has title: misclassification on SGDclassifier using loss='hinge' for SVM
answer count: 0
type: UnansweredQuestion
has body: I have a huge dataset around 5-8 million data and 70-80 classes, till now in future data and classes will increase. I used hashingvectorizer() for feature selection because I am building incremental learning model(I am not using CountVectorizer(),Tfidf() because i have heard they don't support for Incremental learning) so I have multiclass classification problem and I have used SDClassifier with SVM using partial_fit method. but while in testing it is producing misclassification. 1) Is it because of I am doing something wrong in feature selection 2) Is Unbalanced data the problem? 3) Parameter tuning? 4) How to decide no of iteration? Any method? (data is increasing) 5) Any other feedbacks are welcome. please provide some example with your answer it will be helpful
tagged with: machine-learning
tagged with: python
score: 0

http://stackoverflow.com/comment/82400088
type: Comment
score: 0
has text: However, the instructor had originally wanted show frequencies for only the first 5 items in each line.but you were doing for 10?
comment on: http://stackoverflow.com/q/47719686
type: QuestionComment

http://stackoverflow.com/q/47749321
type: Question
has title: Python Pandas Check if Value in Dataframe
type: UnansweredQuestion
tagged with: dataframe
tagged with: python
has body: For anybody that has any experience with Python and Pandas, I am trying to compare two dataframes (not equal indices) and see if one value from a column (studentIDs) is in another dataframe with the same column name. If it is not, I need to add it to a separate dataframe. Does anyone know how to do this?
has comment: http://stackoverflow.com/comment/82469988
score: 0
tagged with: pandas
answer count: 0
has comment: http://stackoverflow.com/comment/82482260
linked to: http://stackoverflow.com/q/29464234
duplicate of: http://stackoverflow.com/q/29464234

http://stackoverflow.com/a/47851074
type: AcceptedAnswer
score: 0
has body: Problem was single_questions.clear(). It removes elements but it keeps reference to the same place in memory, so both questions was using the same place. I use single_questions = [] to create new empty list (and it doesn't have to be global list) import tkinter as tk # clear all the entries or Text def clear_entries(event=None): for entry in all_entries: entry.delete(1.0, 'end') # saves single questions, call add_to_all_question and clears screen. def save_next(event=None): # create new empty list new_questions = [] for entry in all_entries: new_questions.append(entry.get(1.0,'end').strip()) print("appending:", new_questions) all_questions.append(new_questions) # clear entries clear_entries() quest_entry.focus() # first method of button check confirm def check_confirm(event=None): ''' should disappear after initiation and set back to n=0''' global n print("Confirm btn pressed") save_next.configure(state="disabled") confirm_btn.grid_forget() confirm.grid(column=2, row=4, padx=x, pady=y) n = 0 clear_entries() incrementer() # Increment then display the following questions def incrementer(event=None): global n root.update_idletasks() if n &lt; len(all_questions): quest_entry.insert(1.0, all_questions[n][0]) ans_entry.insert(1.0, all_questions[n][1]) hint_entry.insert(1.0, all_questions[n][2]) confirm.configure(text="Save Entry #{}".format(n)) else: quest_entry.insert(1.0, "No more Entries Click \ Main to close course or back to return to options.") save_next.configure(state="normal") confirm.configure(state="disabled") # confirm what's being displayed and save new changes def save_new_confirm(event=None): global n print("currently editing list index:", n) display_list("before list") # create empty list for new values new_single = [] for entry in all_entries: new_single.append(entry.get(1.0,'end').strip()) print("new single:", new_single) all_questions[n] = new_single print("now list has:", all_questions) display_list("\nafter list") n += 1 clear_entries() incrementer() …
accepted answer of: http://stackoverflow.com/q/47847071
type: Answer
has comment: http://stackoverflow.com/comment/82668864
answers question: http://stackoverflow.com/q/47847071

twill
type: Tag
tags question: http://stackoverflow.com/q/47824723
tag name: twill

import
tags question: http://stackoverflow.com/q/47773765
type: Tag
tags question: http://stackoverflow.com/q/47712024
tags question: http://stackoverflow.com/q/47742587
tags question: http://stackoverflow.com/q/47807902
tags question: http://stackoverflow.com/q/47744580
tags question: http://stackoverflow.com/q/47732461
tags question: http://stackoverflow.com/q/47836025
tags question: http://stackoverflow.com/q/47730966
tag name: import
tags question: http://stackoverflow.com/q/47781157
tags question: http://stackoverflow.com/q/47852889
tags question: http://stackoverflow.com/q/47822324
tags question: http://stackoverflow.com/q/47740456
tags question: http://stackoverflow.com/q/47742374
tags question: http://stackoverflow.com/q/47849523

http://stackoverflow.com/q/47849342
tagged with: python
tagged with: date
has body: I've recently stumbled upon a new awesome pendulum library for easier work with datetimes. In pandas, there is this handy to_datetime() method allowing to convert series and other objects to datetimes: raw_data['Mycol'] = pd.to_datetime(raw_data['Mycol'], format='%d%b%Y:%H:%M:%S.%f') What would be the canonical way to create a custom to_&lt;something&gt; method - in this case to_pendulum() method which would be able to convert Series of date strings directly to Pendulum objects? This may lead to Series having various interesting capabilities like, for instance, converting a series of date strings to a series of "offsets from now" - human datetime diffs.
has comment: http://stackoverflow.com/comment/82663187
has comment: http://stackoverflow.com/comment/82663701
type: Question
has comment: http://stackoverflow.com/comment/82663270
has comment: http://stackoverflow.com/comment/82663982
linked to: http://stackoverflow.com/q/54028325
answer count: 1
accepted answer: http://stackoverflow.com/a/47849609
tagged with: pendulum
score: 15
downvote count: 1
upvote count: 16
has comment: http://stackoverflow.com/comment/82663385
favorite count: 0
has answer: http://stackoverflow.com/a/47849609
has comment: http://stackoverflow.com/comment/82663730
has title: Making Pandas work with Pendulum
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82663118
tagged with: pandas
has comment: http://stackoverflow.com/comment/82663153
tagged with: datetime

http://stackoverflow.com/a/47778900
answers question: http://stackoverflow.com/q/47720239
score: 0
type: Answer
has body: Kind of a solution..... After trying different approaches in my code, even tried the script below... #!/usr/bin/python import serial serialport = serial.Serial("/dev/ttyUSB0", 115200, timeout=None,rtscts=True,dsrdtr=True) while True: serialport.flush() command = serialport.readline() print str(command).encode('hex') I was able to get a desired behavior by changing the XBee MR parameter (Mesh unicast retries - The maximum number of network packet delivery attempts) to the maximum (0x7), none of my packages are lost, even for a delay of 0s (zero) between the transmission of each package. Probably, as said by tomlogic, if I run my code on a faster PC, I believe, I'll get my packages. When I do this test, i'll post the results here. Thanks.

http://stackoverflow.com/a/47825111
has comment: http://stackoverflow.com/comment/82619665
upvote count: 2
answers question: http://stackoverflow.com/q/47823141
has comment: http://stackoverflow.com/comment/82661842
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/47823141
has body: With the numbers you are quoting and reasonable hardware (8GB ram) the mapping can be done in less than a second. The bad news is that getting the data out of the original dicts of objects takes 60 x longer at least with the mock objects I created. # extract 29.2821946144104 map 0.4702422618865967 But maybe you can find some way of bulk querying your nodes and tets? Code: import numpy as np from time import time def mock_data(nn, nt, idf): nid = np.cumsum(np.random.randint(1, 2*idf, (nn,))) nodes = np.random.random((nn, 3)) import collections node = collections.namedtuple('node', 'nid xyz') tet4 = collections.namedtuple('tet4', 'nodes') nodes = dict(zip(nid, map(node, nid, nodes))) eid = np.cumsum(np.random.randint(1, 2*idf, (nt,))) tet4s = nid[np.random.randint(0, nn, (nt, 4))] tet4s = dict(zip(eid, map(tet4, map(lambda t: [nodes[ti] for ti in t], tet4s)))) return nodes, tet4s def f_extract(nodes, tet4s, limit=15*10**7): nid = np.array(list(nodes.keys())) from operator import attrgetter ncoords = np.array(list(map(attrgetter('xyz'), nodes.values()))) tid = np.array(list(tet4s.keys())) tnodes = np.array([[n.nid for n in v.nodes] for v in tet4s.values()]) return nid, ncoords, tid, tnodes, limit def f_lookup(nid, ncoords, tid, tnodes, limit): nmx = nid.max() if nmx &lt; limit: nlookup = np.empty((nmx+1,), dtype=np.uint32) nlookup[nid] = np.arange(len(nid), dtype=np.uint32) tnodes = nlookup[tnodes] del nlookup else: nidx = np.argsort(nid) nid = nid[nidx] ncoords = ncoords[nidx] tnodes = nid.searchsorted(tnodes) tmx = tid.max() if tmx &lt; limit: tlookup = np.empty((tmx+1,), dtype=np.uint32) tlookup[tid] = np.arange(len(tid), dtype=np.uint32) else: tidx = np.argsort(tid) tid = tid[tidx] tnodes = tnodes[tidx] return nid, ncoords, tid, tnodes data = mock_data(1_600_000, 6_500_000, 16) t0 = time() data = f_extract(*data) t1 = time() f_lookup(*data) t2 = time() print('extract', t1-t0, 'map', t2-t1)
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/82619715

http://stackoverflow.com/q/47790767
tagged with: python
has answer: http://stackoverflow.com/a/47792148
score: 0
has comment: http://stackoverflow.com/comment/82545312
answer count: 1
tagged with: sqlalchemy
type: Question
tagged with: postgresql
has title: KeyError when creating a view
type: UnansweredQuestion
has body: I want to use SQLAlchemy to create a view in my PostgreSQL database. I'm using the CreateView compiler from sqlalchemy-views. I'm using the answer to this question as a reference: How to create an SQL View with SQLAlchemy? My code for creating the view looks like this: def create_view(self, myparameter): mytable = Table('mytable', metadata, autoload=True) myview = Table('myview', metadata) engine.execute(CreateView(myview, mytable.select().where(mytable.c.mycolumn==myparameter))) However, when I attempt to run this query, the following exception is thrown: KeyError: 'mycolumn_1' Looking at the compiled query, it seems that a placeholder for my parameter value is not being replaced: '\nCREATE VIEW myview AS SELECT mytable.mycolumn \nFROM mytable \nWHERE mytable.mycolumn = %(mycolumn_1)s\n\n' Since the placeholder is not being replaced, the query obviously fails. However, I do not understand why the replacement does not happen, since my code does not differ much from the example. My first suspicion was that maybe the type of the parameter and the column were incompatible. Currently, the parameter comes in as a unicode string, which should be mapped to a text column in my database. I have also tried mapping the parameter as a long to a bigint column with the same (failed) result. Does anyone have another suggestion?
linked to: http://stackoverflow.com/q/9766940

http://stackoverflow.com/q/47783480
has title: Python program printing on a new line when it shouldn't
tagged with: printing
type: Question
has comment: http://stackoverflow.com/comment/82528430
type: AnsweredQuestion
downvote count: 3
tagged with: file
has body: I have a text file with random letters,numbers and characters in it. I have to remove the special characters and only end up with alphanumeric ones, while printing the process. For some reason my program is printing: Line read' ,,s.8,ymsw5w-86 ' ' ,,s.8,ymsw5w-86 '-&gt;' s8ymsw5w86 ' When the text should go on only 2 lines, instead of 4. Like this: Line read' ,,s.8,ymsw5w-86' ' ,,s.8,ymsw5w-86' -&gt; 's8ymsw5w86' I don't understand what's wrong. This is my code: file1=open(textfile1,"r") for line in file1: line2="".join(filter(str.isalnum,line)) print("Line read","'",str(line),"'") print("'",str(line),"'-&gt;'",line2,"'") Thank you.
favorite count: 0
has comment: http://stackoverflow.com/comment/82528391
upvote count: 0
accepted answer: http://stackoverflow.com/a/47783578
tagged with: newline
has comment: http://stackoverflow.com/comment/82528427
has answer: http://stackoverflow.com/a/47783578
tagged with: python
score: -3
answer count: 1
tagged with: line

http://stackoverflow.com/comment/82562919
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47800252
has text: The answer to what you asked is because of bad logic. You decide isAssigned immediately on the first language match, again for each language match, regardless of other criteria. You could also greatly improve readability by using python for loops and the "in" operator, and good variable names. If it's complicated, re-write it with good function names hiding complicated details, then work on those functions.

http://stackoverflow.com/comment/82460021
type: Comment
score: 0
comment on: http://stackoverflow.com/a/47749681
type: AnswerComment
has text: can we talk in a room so i can explain you better?

http://stackoverflow.com/q/47743402
has comment: http://stackoverflow.com/comment/82447900
has comment: http://stackoverflow.com/comment/82447034
has comment: http://stackoverflow.com/comment/82446951
has comment: http://stackoverflow.com/comment/82448763
answer count: 0
has comment: http://stackoverflow.com/comment/82446987
score: 7
upvote count: 7
has comment: http://stackoverflow.com/comment/82447029
favorite count: 0
has comment: http://stackoverflow.com/comment/82446966
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82446963
tagged with: crash
tagged with: tkinter
has comment: http://stackoverflow.com/comment/82447004
has comment: http://stackoverflow.com/comment/82446991
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82447039
downvote count: 0
has body: I am trying to make an applet for my code that simulates the Enigma. When I run the code, the window pops up and everything is fine. I can use it on my laptop monitor and everything works. When I move the window to an external monitor (higher resolution) and touch on one of the comboboxes the whole thing crashes. I am using Python and Tkinter. Here the code: import tkinter as tk from tkinter import ttk class EnigmaIApp(tk.Tk): def __init__(self, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) tk.Tk.wm_title(self, "Enigma I") tk.Tk.wm_resizable(self,0,0) tk.Tk.grid_propagate(self,0) container = ttk.Frame(self, padding="3 3 12 12") container.pack(side="top", fill="both", expand = True) container.grid_rowconfigure(0, weight=1) container.grid_columnconfigure(0, weight=1) self.frames = {} frame = Emulator(container, self) self.frames[Emulator] = frame frame.grid(row=0, column=0, sticky="nsew") self.show_frame(Emulator) def show_frame(self, cont): frame = self.frames[cont] frame.tkraise() class Emulator(ttk.Frame): def __init__(self, parent, controller): ttk.Frame.__init__(self, parent) self.columnconfigure(0, weight = 1) self.columnconfigure(1, weight = 1) self.columnconfigure(2, weight = 1) self.sl1, self.sl2, self.sl3 = tk.StringVar(), tk.StringVar(), tk.StringVar() Scrambler1_SL = ttk.Combobox(self, textvariable=self.sl1, width=10, values = ('I', 'II', 'III', 'IV', 'V'), state="readonly") Scrambler1_SL.grid(column=0, row=3, columnspan=12, sticky='w', padx='5') Scrambler1_SL.current(2) Scrambler2_SL = ttk.Combobox(self, textvariable=self.sl2, width=10, values = ('I', 'II', 'III', 'IV', 'V'), state="readonly") Scrambler2_SL.grid(column=1, row=3, columnspan=12, sticky='w', padx='5') Scrambler2_SL.current(3) Scrambler3_SL = ttk.Combobox(self, textvariable=self.sl3, width=10, values = ('I', 'II', 'III', 'IV', 'V'), state="readonly") Scrambler3_SL.grid(column=2, row=3, columnspan=12, sticky='w', padx='5') Scrambler3_SL.current(4) app = EnigmaIApp() app.geometry("500…
tagged with: python
has comment: http://stackoverflow.com/comment/134066431
has title: Moving tk window to another monitor causes Python to crash

http://stackoverflow.com/q/47738835
has title: could not convert string to float 12 + 13
duplicate of: http://stackoverflow.com/q/2371436
type: Question
accepted answer: http://stackoverflow.com/a/47738871
has comment: http://stackoverflow.com/comment/82438082
tagged with: python
tagged with: valueerror
has body: I am trying to write a very simple code which I will feed it two numbers (with the input function) and it'll give me a result based on these numbers. When the numbers are just numbers (e.g., 12 or 15) everything works fine, but when instead of a number is, for example, an addition (i.e., 6 + 6) then I get an error saying "could not convert string to float: '6 + 6'. Please see below a reproducible example: def calc_sal(number1, number2): return number1 * 4.5 + number2 number1 = float(input("Give number1 ")) number2 = float(input("Give number2 ")) print(calc_sal(number1, number2)) and this is the error: Give number1 6 + 6 Traceback (most recent call last): File "SalaryCalc.py", line 4, in &lt;module&gt; number1 = float(input("Give number1 ")) ValueError: could not convert string to float: '6 + 6' It appears to me that I cannot perform an addition through the input function, instead it thinks that it's a string "6 + 6". However, when I am running the same code line by line in an interactive session, everything works just fine (i.e., when the input is 6 + 6, the output is 12, rather than "6 + 6"). So do you why is this happening only when I am running the programme through the terminal and not interactively? And how to resolve this? Thank you.
has comment: http://stackoverflow.com/comment/82437956
linked to: http://stackoverflow.com/q/15197673
linked to: http://stackoverflow.com/q/20748202
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/2371436
has answer: http://stackoverflow.com/a/47738871
has comment: http://stackoverflow.com/comment/82438044
downvote count: 0
has comment: http://stackoverflow.com/comment/82438206
score: 1
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/82438085
favorite count: 0

http://stackoverflow.com/a/47710524
has comment: http://stackoverflow.com/comment/82381134
answers question: http://stackoverflow.com/q/47710379
has comment: http://stackoverflow.com/comment/82383168
has comment: http://stackoverflow.com/comment/82380925
has comment: http://stackoverflow.com/comment/82383486
type: Answer
has body: Case 1: The code presented here is exactly what you have Comp_urls = ['https://www.indeed.com/jobs?q=Dell&amp;rbc=DELL&amp;jcid=0918a251e6902f97', 'https://www.indeed.com/jobs?q=Harman&amp;rbc=Harman&amp;jcid=4faf342d2307e9ed','https://www.indeed.com/jobs?q=johnson+%26+johnson&amp;rbc=Johnson+%26+Johnson+Family+of+Companies&amp;jcid=08849387e791ebc6','https://www.indeed.com/jobs?q=nova&amp;rbc=Nova+Biomedical&amp;jcid=051380d3bdd5b915'] for url in Comp_urls: target = Soup(urllib.request.urlopen(url), "lxml") targetElements = target.findAll('div', class_ =' row result') for elem in targetElements: The problem here is targetElements changes with every iteration in the first for loop. To avoid this, indent the second for loop inside the first like so: for url in Comp_urls: target = Soup(urllib.request.urlopen(url), "lxml") targetElements = target.findAll('div', class_ =' row result') for elem in targetElements: Case 2: Your the bug is not a result of improper indentation (i.e. not like what is in your original post) If it is the case that your code is properly idented , then it may be the case that targetElements is an empty list. This means target.findAll('div', class_ =' row result') does not return anything. In that case, visit the sites, check out the dom, then modify your scraping program.
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/a/47779255
has comment: http://stackoverflow.com/comment/82539590
downvote count: 0
has comment: http://stackoverflow.com/comment/82553675
has body: Seems that Hough transform for the second image should give two strong vertical (in Theta-Rho space) clusters, that correspond to the bundles of parallel lines. So you can determine main directions. Here is result of my quick test using the second image and OpenCV function HoughLines Then I counted lines with all directions(rounded to integer degrees) in range 0..180 and printed results with count&gt;1. We apparently can see larger counts at 86-87 and 175-176 degrees (note almost 90-degrees difference) line angle : count 84: 3 85: 3 86: 8 87: 12 88: 3 102: 3 135: 3 140: 2 141: 2 165: 2 171: 4 172: 2 173: 2 175: 7 176: 17 177: 3 Note: I've used arbitrary Delphi example of HoughLines function usage and added direction counting. You can get this Python example and build histogram for theta values
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/47777585

http://stackoverflow.com/q/47731211
has body: I'm trying to build a translator using deepl for subtitles but it isn't running perfectly. I managed to translate the subtitles and most of the part I'm having problems replacing the lines. I can see that the lines are translated because it prints them but it doesn't replace them. Whenever I run the program it is the same as the original file. This is the code responsible for: def translate(input, output, languagef, languaget): file = open(input, 'r').read() fileresp = open(output,'r+') subs = list(srt.parse(file)) for sub in subs: try: linefromsub = sub.content translationSentence = pydeepl.translate(linefromsub, languaget.upper(), languagef.upper()) print(str(sub.index) + ' ' + translationSentence) for line in fileresp.readlines(): newline = fileresp.write(line.replace(linefromsub,translationSentence)) except IndexError: print("Error parsing data from deepl") This is the how the file looks: 1 00:00:02,470 --&gt; 00:00:04,570 - Yes, I do. - (laughs) 2 00:00:04,605 --&gt; 00:00:07,906 My mom doesn't want to babysit everyday 3 00:00:07,942 --&gt; 00:00:09,274 or any day. 4 00:00:09,310 --&gt; 00:00:11,977 But I need my mom's help sometimes. 5 00:00:12,013 --&gt; 00:00:14,046 She's just gonna have to be grandma today. Help will be appreaciated :) Thanks.
upvote count: 3
downvote count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/82423256
type: AnsweredQuestion
score: 3
tagged with: deepl
has title: Python: Having trouble replacing lines from file
accepted answer: http://stackoverflow.com/a/47731304
answer count: 1
has answer: http://stackoverflow.com/a/47731304
favorite count: 0
type: Question
tagged with: python-3.x

http://stackoverflow.com/comment/82524363
score: 0
comment on: http://stackoverflow.com/q/47781157
type: Comment
type: QuestionComment
has text: Probably means that pycharm is not configured properly. Should make sure it is using the right interpreter for the project.

http://stackoverflow.com/a/47782130
upvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/47781711
score: -1
has comment: http://stackoverflow.com/comment/135193984
has body: First use ModelForm instead of Form, then you can use widgets attributes: from django.forms import ModelForm # Mind the name of your form!! class MyModelForm(ModelForm): class Meta: model = MyModel fields = ['color'] widgets = { # Here you define what input type should the field have 'color': Select(attrs = { 'class': 'form-control', }), } You don't "call that form on my index.html". Yo use views to call the form and set the html template to use. Using class based views you got: from django.views.generic import CreateView from .models import MyModel from .forms import MyModelForm class ColourCreateView(CreateView): model = MyModel template_name = 'index.html' form_class = MyModelForm
has comment: http://stackoverflow.com/comment/135190011
downvote count: 1

http://stackoverflow.com/comment/82465157
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47752313
has text: @brunodesthuilliers Right now, I am testing it for dev environment. Also, I am trying to run it via gunicorn but also giving the same issue [Import error].
type: QuestionComment

http://stackoverflow.com/a/47714989
type: Answer
upvote count: 2
type: AcceptedAnswer
score: 1
downvote count: 1
answers question: http://stackoverflow.com/q/47714884
has body: For the immediate problem, you need to call your methods via self - ie self.LongerString() - and they need to accept self as the first argument. But this isn't really how you use classes. You should write an __init__ method that takes the two strings and stores them as instance attributes, then refer to those throughout. (Also note, you should use PEP8 style for your variable names.) class CompareString: def __init__(self, string1, string2): self.string1 = string1 self.string2 = string2 def longer_string(self): if len(self.string1) == len(self.string2): ... def result(self): ... call self.longer_string() etc ... compare = CompareString(string1, string2) print compare.result() (Also also note, your longer_string method could just be return max(len(self.string1), len(self.string2)), and your shorter_string method similarly.) (Also also also note, your result method should not iterate over a range, but just over zip(self.string1, self.string2), so you don't even need either of those other methods.)
accepted answer of: http://stackoverflow.com/q/47714884

http://stackoverflow.com/comment/82474975
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47743125
type: AnswerComment
has text: No, you're creating two models. They will not share weights.

http://stackoverflow.com/comment/82558666
type: QuestionComment
score: 0
has text: I don't even see a "please" in your question. You are not entitled to anyone's help here. Please show your efforts.
comment on: http://stackoverflow.com/q/47798708
type: Comment

http://stackoverflow.com/q/47801267
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/37083058
has comment: http://stackoverflow.com/comment/82564359
has comment: http://stackoverflow.com/comment/82565670
has comment: http://stackoverflow.com/comment/82564623
tagged with: beautifulsoup
has comment: http://stackoverflow.com/comment/82563975
score: 0
has comment: http://stackoverflow.com/comment/82565217
tagged with: google-search
has comment: http://stackoverflow.com/comment/82564745
tagged with: python
has title: Retrieve a list of URLs from google and print to text file in python
tagged with: web-crawler
linked to: http://stackoverflow.com/q/37083058
has body: Ok, so I've got some code I can't get to work. I'm trying to pull the first 10 urls from google for any given search result. I cannot get the results to print to the file, have had errors such as: AtributeError: 'NoneType' object has no attribute from bs4 import BeautifulSoup import requests import re import urllib2 import os jobid='test_01' town='town' KEIF="/home/dream/scripts/Keif/" f = open(KEIF+'wordlists/trades.txt') job = f.readline() DIR="/home/dream/scripts/Keif/output/"+jobid if not os.path.exists(DIR): os.mkdir(DIR) while job: #Create google query jobquery=job.replace(" ", "%20"); jobquery=jobquery.replace("/n ", "") query = jobquery+'%20'+'in%20'+town query= query.split() query='+'.join(query) #Create new text file based on query jobdir=job.replace(" ","_"); jobdir=jobdir.replace("\n", "") textpath=DIR+"/"+jobdir+'.txt' os.system("cat "+textpath) textOut=open(textpath, "a") #Get Results page = requests.get("https://www.google.co.uk/search?q="+query+"&amp;start=10&amp;num=10") soup = BeautifulSoup(page.text, "html.parser") print soup.find('cite').text I am getting the: AtributeError: 'NoneType' object has no atribute on the last line print sou.find('cite').text. Can someone please help keep me from tearing out my hair!
type: Question
answer count: 0

http://stackoverflow.com/q/47824211
has comment: http://stackoverflow.com/comment/82611035
has body: I want to create a debt collector program. I want to be able to save the data so when I close it I don't have to start over. For example, if account = 100 and I make a payment of 20 that then makes the account = 80. I want to save this new variable so that when I run it again it does not start me at 100 again. So far I've tried: def takePayment(): account = 0 take_payment = input("how mych") sum = float(account) + float(take_payment) print("The total now is $", sum) takePayment()
type: Question
has comment: http://stackoverflow.com/comment/82614951
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82612144
tagged with: python
has answer: http://stackoverflow.com/a/47824293
score: 0
has title: saving data so it does not restart when I run the program again
answer count: 1

http://stackoverflow.com/q/47735635
favorite count: 0
type: AnsweredQuestion
has title: Writing nested queries in Django
score: 1
has answer: http://stackoverflow.com/a/47735671
accepted answer: http://stackoverflow.com/a/47735671
tagged with: python
type: Question
has body: I am trying to write a nested query in Django. It is very simple to do in SQL, but with Django I am having some trouble deciding if I am doing it right or not. I have three models. Area, Location, and Measurement. Area class Area(models.Model): name = models.CharField(max_length=200) longitude = models.FloatField() latitude = models.FloatField() Location class Location(models.Model): name = models.CharField(max_length=200) altitude = models.IntegerField() area = models.ForeignKey(Area, on_delete=models.CASCADE) Measurement class Measurement(models.Model): value = models.FloatField() date = models.DateTimeField() location = models.ForeignKey(Location, on_delete=models.CASCADE) Inside Area, I need a function that will return the average of the measurements for this area. So basically, I need the average measurements of all locations for this area. Area can have many locations, but locations can have one area. In the Area Model, I made this function: def average_measurement(self): all_locations = self.location_set.all() return all_locations.measurement_set.all().aggregate(Avg('value')) This is my equivalent to writing a nested query in Django. I get all locations first and then find the average of all their measurements. Am I doing this correctly? On a side question, would this query be equivalent to doing something like this: avg = 0 locations = self.location_set.all() sum = 0 counter = 0 for l in locations: measurement = l.measurement_set.all() if measurement: for m in measurement: sum += m.value counter += 1 if counter != 0: avg = sum / counter return avg
downvote count: 0
upvote count: 1
answer count: 1
tagged with: django

http://stackoverflow.com/q/47781859
accepted answer: http://stackoverflow.com/a/47914280
has comment: http://stackoverflow.com/comment/82525488
answer count: 1
has comment: http://stackoverflow.com/comment/82525558
tagged with: basehttpserver
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47914280
has title: Python BaseHTTPServer, how to redirect multiple hosts to ip/port?
score: 0
has comment: http://stackoverflow.com/comment/82525379
tagged with: python
type: Question
has body: I currently have the following code: from BaseHTTPServer import BaseHTTPRequestHandler from pathlib import Path from random import randint import json import random example = 'logs/example.json' class GetHandler(BaseHTTPRequestHandler): # Slurp data from file def dummy_data(self): json_result = Path(example) if json_result.is_file(): return json.load(open(example)) # Return data or empty def random_selection(self): data = self.dummy_data() try: return random.sample(data, randint(1, len(data)+50)) # Purposefully introduce entropy except ValueError: return '' def do_GET(self): self.send_response(200) self.send_header('Content-Type', 'application/json') self.end_headers() self.wfile.write(json.dumps(self.random_selection())) return if __name__ == '__main__': from BaseHTTPServer import HTTPServer server = HTTPServer(('localhost', 8080), GetHandler) print 'Starting server at http://127.0.0.1:8080' server.serve_forever() I have patched /etc/hosts as follows: server-0001 server-0002 server-0003 server-0004 127.0.0.1 I am looking for a way for servers 0001-4 to redirect to 127.0.0.1:8080 but am not seeing how? Is this something to do with /etc/resolv.conf? I am using OSX but hopefully any *nix solution should work I'm hoping (unless ipfw evidently, since we no longer have it like sane people).

http://stackoverflow.com/q/47788484
has body: I am trying to run dev_appserver.py on this Google App Engine Standard Flask Sample As the instructions say I run: pip install -t lib -r requirements.txt dev_appserver.py app.yaml I should be able to go to http://localhost:8080/form but I get ImportError: No module named msvcrt. I found that using Flask==0.10.1 and Werkzeug==0.12.2 works but nothing newer. Versions: OS: Windows 10 Pro Python 2.7.14 Google Cloud SDK 182.0.0 app-engine-go app-engine-python 1.9.63 app-engine-python-extras 1.9.63 bq 2.0.27 core 2017.12.01 gsutil 4.28
linked to: http://stackoverflow.com/q/41525223
favorite count: 0
type: Question
tagged with: werkzeug
linked to: http://stackoverflow.com/q/25915164
type: UnansweredQuestion
tagged with: google-app-engine
linked to: http://stackoverflow.com/q/47716196
tagged with: python
tagged with: flask
has answer: http://stackoverflow.com/a/47791541
score: 2
has title: Google App Engine Standard dev_appserver.py giving a Import Error
tagged with: google-cloud-platform
upvote count: 2
has comment: http://stackoverflow.com/comment/82538247
answer count: 1
downvote count: 0

http://stackoverflow.com/a/47824472
type: AcceptedAnswer
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/47824378
type: Answer
has body: Note that I have made this a CW post to mark it as answered. I take no credit for this answer and give it all to Patrick Haugh, who answered in comments. Use zip. You need to iterate through both lists at the same time. The zip(list1,list2) function takes two lists of equal size and turns them into a single list by doing something like [(list1[index],list2[index]) for index in range(len(list1))].
accepted answer of: http://stackoverflow.com/q/47824378

http://stackoverflow.com/comment/82405971
type: Comment
has text: have you looked at [`pd.to_datetime()`](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html)?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47722552

http://stackoverflow.com/comment/82424203
type: AnswerComment
score: 0
has text: i have python 3.6.3
type: Comment
comment on: http://stackoverflow.com/a/47730486

permutation
tags question: http://stackoverflow.com/q/47742622
type: Tag
tag name: permutation
tags question: http://stackoverflow.com/q/47740459
tags question: http://stackoverflow.com/q/47762682

http://stackoverflow.com/comment/82446176
comment on: http://stackoverflow.com/q/47742797
type: Comment
has text: Type some code, to understand you better
type: QuestionComment
score: 1

http://stackoverflow.com/comment/82631425
comment on: http://stackoverflow.com/q/47804843
score: 0
has text: If you're just aiming to have the View emit a JSON representation of the activity, I would write a customer function to do this rather than implementing a full Django Serializer.
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/82675938
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47855651
has text: @gaussclb: no, it returns `None` because you implemented a `__getattribute__` method that **always returns `None`**.

http://stackoverflow.com/q/47765824
has title: TKinter not inserting a string to Text widget
has comment: http://stackoverflow.com/comment/82493218
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/82493193
has comment: http://stackoverflow.com/comment/82493180
has comment: http://stackoverflow.com/comment/82493112
tagged with: text
type: AnsweredQuestion
has body: I Apologize in advance for the long code and if I break any rules as this is my first time asking a question on this site. I'm fairly new to Python but I'm currently writing a program for a school project that requests data from the OpenFEC API and then display it in a GUI that I created using TKinter. Everything works well if I print to the console but once I try to insert my data to the Text widget I get an error and not all the data is shown. The error is 'TypeError: must be str, not NoneType', I've tried converting the variable to a string using str(varName) but doesn't work. I've been working on this specific issue for a couple of days now and have searched all over the internet for possible solutions but I haven't found anything that helps me. I appreciate any help that I can receive. import json import urllib.request import urllib.parse import urllib.error from tkinter import * from tkinter import ttk def inputValidation(year): # Ask the user for a year # year = yearEntry.get() # Input validation year = int(year) # Converting input to integer for comparison purposes if year &gt;= 2003 and year &lt;= 2020: message = "Here are the election dates for " + str(year) + ':' + '\n' else: message = "Please enter a valid year." # Clear out any existing text from entry window data.config(state=NORMAL) data.delete(0.0, END) # Set the data window data.insert(1.0, message) data.config(state=DISABLED) # Convert the year back to a string year = str(year) return year # Function to get API data def apiCall(event, year, pageNumber): """ Requests data from OpenFEC API by constructing a url using predetermined values. """ apiKey = 'rdudHBjgS5srIohVWYyyUL64AOsqVfRkGZD4gvMU' perPage = '90' # Number of items to print per page electionYear = year nullHide = 'true' nullOnly = 'true' sort = sortNum.get() if sort == 1: sort = '-election_state' if sort == 2: sort = '-election_date' if sort == 3: sort = 'office_sought' url = ('https://api.open.fec.gov/v1/election-dates/?per_page=' + perPa…
has comment: http://stackoverflow.com/comment/82493316
upvote count: 0
has comment: http://stackoverflow.com/comment/82493254
has comment: http://stackoverflow.com/comment/82493369
answer count: 2
accepted answer: http://stackoverflow.com/a/47766262
tagged with: widget
has comment: http://stackoverflow.com/comment/82493149
has comment: http://stackoverflow.com/comment/82493146
downvote count: 1
has comment: http://stackoverflow.com/comment/82493557
favorite count: 0
has answer: http://stackoverflow.com/a/47766095
possible better answer: http://stackoverflow.com/a/47766095
type: Question
tagged with: tkinter
has answer: http://stackoverflow.com/a/47766262
has comment: http://stackoverflow.com/comment/82493473
tagged with: nonetype

http://stackoverflow.com/a/47705025
has body: You could just ping the connection first, instead of after the query, as that should reconnect if necessary. Setup: conn = pymysql.connect(host= "server", user="user", passwd="pw", db="db", charset='utf8') and every second: query = "UPDATE missionFilesDelDro SET landLat = '%s', landLon='%s',landHea='%s' WHERE displayName='%s'" % (lat, lon, heading, mission) conn.ping() x = conn.cursor() x.execute(query) Ref https://github.com/PyMySQL/PyMySQL/blob/master/pymysql/connections.py#L872 It's still possible that the connection could drop after the ping() but before the execute(), which would then fail. For handling that you would need to trap the error, something similar to from time import sleep MAX_ATTEMPTS = 10 # every second: query = "UPDATE missionFilesDelDro SET landLat = '%s', landLon='%s',landHea='%s' WHERE displayName='%s'" % (lat, lon, heading, mission) inserted = False attempts = 0 while (not inserted) and attempts &lt; MAX_ATTEMPTS: attempts += 1 try: conn.ping() x = conn.cursor() x.execute(query) inserted = True except StandardError: # it would be better to use the specific error, not StandardError sleep(10) # however long is appropriate between tries # you could also do a whole re-connection here if you wanted if not inserted: # do something #raise RuntimeError("Couldn't insert the record after {} attempts.".format(MAX_ATTEMPTS)) pass
score: 2
has comment: http://stackoverflow.com/comment/82388602
accepted answer of: http://stackoverflow.com/q/47704358
upvote count: 2
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47704358
has comment: http://stackoverflow.com/comment/82386160
type: Answer

http://stackoverflow.com/comment/82480214
comment on: http://stackoverflow.com/q/47758292
has text: I think my approach here would be to do `pip install <package name> -U` for each package that can't be found, re-run `pip freeze > requirements.txt` and then try to deploy on Heroku.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82482223
comment on: http://stackoverflow.com/q/47760436
type: Comment
type: QuestionComment
score: 0
has text: I'd suggest checking out [this page](http://regexr.com) for regex help & experimentation.

http://stackoverflow.com/comment/82771759
type: Comment
has text: I overwrite the function `def to_representation(self,instance):` of `serializers.ModelSerializer`，and so I can add the infomation that I want.
type: AnswerComment
comment on: http://stackoverflow.com/a/47808158
score: 0

http://stackoverflow.com/q/47698407
tagged with: tkinter
has comment: http://stackoverflow.com/comment/82357173
has answer: http://stackoverflow.com/a/47699222
type: AnsweredQuestion
upvote count: 0
has answer: http://stackoverflow.com/a/47698960
answer count: 2
downvote count: 3
has comment: http://stackoverflow.com/comment/82358563
favorite count: 0
has body: How is it possible to check the entries for login and password and if they are correct, new tabs will open. If the entries are incorrect, an error message will be displayed. The user should also be able to register for an account from tkinter import * import sqlite3 import tkinter import time root = Tk() root.title("Sale System") root.geometry("500x500") root.configure(background='grey') Label(root, text="Checkout System", background='grey').grid(row=0, column=1) Label(root, text="Time:", background='grey').grid(row=1, column=1) def clock(): t=time.strftime('%I:%M:%S',time.localtime()) if t!='': labeltime.config(text=t) root.after(100,clock) labeltime=Label(root, text="Current System Time", background='grey') labeltime.grid(row=1, column=1) time1 = clock() def new_winF(): #Opens registration confirmation window newwin = Toplevel(root) display = Label(newwin, text="Your account has been created. Please log in with your new details. This window may be closed.") display.pack() Label(root, text="Username:", background='grey').grid(row=3, column=0, sticky=W) Label(root, text="Password:", background='grey').grid(row=4, column=0, sticky=W) e1 = Entry(root) e1.grid(row=3, column=1) if e1 == 'yes': command =new_winF e2 = Entry(root) e2.grid(row=4, column=1) LoginButton = Button(root, text="Login", width=10) LoginButton.grid(row=5, column=1) RegisterButton = Button(root, text ="Register", command =new_winF, width=10) RegisterButton.grid(row=6, column=1) root.mainloop()
has title: User login system including username and password
accepted answer: http://stackoverflow.com/a/47698960
has comment: http://stackoverflow.com/comment/82357051
linked to: http://stackoverflow.com/q/7546050
type: Question
tagged with: python
score: -3
possible better answer: http://stackoverflow.com/a/47699222

http://stackoverflow.com/q/47731479
tagged with: python
has comment: http://stackoverflow.com/comment/82424103
has comment: http://stackoverflow.com/comment/82439022
score: 0
has comment: http://stackoverflow.com/comment/82423994
has body: i'm trying to solve Laplace's equation with a particular geometry (two circular conductors), here's what i've done in python : from __future__ import division from pylab import * from scipy import * from numpy import * from matplotlib import * N1=50 # number of points along x and y N=2*N1+1 # number of points in total # in cm. xc1=4 xc2=9 yc1=0 yc2=0 R1=1.75 R2=9 ecart = 1 a, b = linspace(-1, 19, N), linspace(-10, 10, N) xa, ya = meshgrid(a, b) V = zeros_like(xa) for i in range(N): for j in range(N): x, y = xa[i,j], ya[i,j] if (((x-xc1)**2/(R1**2))+((y-yc1)**2/(R1**2)))&lt;=1 : # potential in the central conductor V[i,j] = 30 if (((x-xc2)**2/(R2**2))+((y-yc2)**2/(R2**2)))&gt;=1 : # potential in the outer conductor V[i,j] =0 #draws the potential along X along the axis of symmetry. Vnew = V.copy() while ecart &gt; 5*10**-2: for i in range(1,N-1): for j in range(1,N-1): Vnew[i,j] = 0.25*(V[i-1,j] + V[i+1,j] + V [i,j-1] + V[i,j+1]) # convergence criterion ecart = np.max(np.abs(V - (Vnew))/np.max(V)) print(ecart) # save in the grid V of the calculated grid for i in range(N): for j in range(N): x, y = xa[i,j], ya[i,j] if (((x-xc1)**2/(R1**2))+((y-yc1)**2/(R1**2))) &gt; 1 and (((x-xc2)**2/(R2**2))+((y-yc2)**2/(R2**2))) &lt; 1 : V[i,j] = Vnew[i,j] it actually works with ecart&gt;5*10**-2, but I would like to do it with ecart&gt;10**-3 and here is the problem, it takes too much time ,actually it never ends... Does someone have any idea in order to improve the program ? Thank you in advance !
has comment: http://stackoverflow.com/comment/82439071
tagged with: physics
tagged with: equation
has title: Solving Laplace's equation
has comment: http://stackoverflow.com/comment/82424155
type: Question
has comment: http://stackoverflow.com/comment/82424057
answer count: 0
has comment: http://stackoverflow.com/comment/82428094
type: UnansweredQuestion

http://stackoverflow.com/comment/82457481
comment on: http://stackoverflow.com/q/47747894
type: Comment
has text: not `webbrowser.open()` but `f = open( , "r", encoding=...)`
score: 0
type: QuestionComment

http://stackoverflow.com/comment/82467903
comment on: http://stackoverflow.com/a/47742575
score: 2
type: Comment
type: AnswerComment
has text: I'm sure concepts (and terminology) in the different design methodologies overlap. Maybe the way to reconcile things in this case is to say that there's this other class whose single responsibility is to deal with using these two other classes together in the desired way.

http://stackoverflow.com/comment/82391465
type: Comment
type: QuestionComment
has text: Might be worth opening a GitHub issue: https://github.com/yaml/pyyaml/issues It's not just you, I was able to reproduce this.
score: 1
comment on: http://stackoverflow.com/q/47715566

http://stackoverflow.com/q/47795836
type: Question
tagged with: python-3.x
has body: I'm trying to make my program run faster, using threads but it takes too many time. The code must compute two kinds of matrices (word_level where I compare every two words of the query and a document, sequence_level: where I compare the query to different sequences on the document. Here are the principal functions: import threading from threading import Thread def sim_QxD_word(query, document, model, alpha, outOfVocab, lock): #word_level sim_w = {} for q in set(query.split()): sim_w[q] = {} qE = [] if q in model.vocab: qE = model[q] elif q in outOfVocab: qE = outOfVocab[q] else: qE = numpy.random.rand(model.layer1_size) # random vector lock.acquire() outOfVocab[q] = qE lock.release() for d in set(document.split()): dE = [] if d in model.vocab: dE = model[d] elif d in outOfVocab: dE = outOfVocab[d] else: dE = numpy.random.rand(model.layer1_size) # random vector lock.acquire() outOfVocab[d] = dE lock.release() sim_w[q][d] = sim(qE,dE,alpha) return (sim_w, outOfVocab) def sim_QxD_sequences(query, document, model, outOfVocab, alpha, lock): #sequence_level # 1. extract document sequences document_sequences = [] for i in range(len(document.split())-len(query.split())): document_sequences.append(" ".join(document.split()[i:i+len(query.split())])) # 2. compute similarities with a query sentence lock.acquire() query_vec, outOfVocab = avg_sequenceToVec(query, model, outOfVocab, lock) lock.release() sim_QxD = {} for s in document_sequences: lock.acquire() s_vec, outOfVocab = avg_sequenceToVec(s, model, outOfVocab, lock) lock.release() sim_QxD[s] = sim(query_vec, s_vec, alpha) return (sim_QxD, outOfVocab) def word_level(q_clean, d_text, model, alpha, outOfVocab, out_w, q, ext_id, lock): #print("in word_level") sim_w, outOfVocab = sim_QxD_word(q_clean, d_text, model, alpha, outOfVocab, lock) numpy.save(join(out_w, str(q)+ext_id+"word_interactions.npy"), sim_w) def sequence_level(q_clean, d_text, model, outOfVocab, alpha, out_s, q, ext_id, lock): #print("in sequence_level") sim_s…
linked to: http://stackoverflow.com/q/10154487
type: UnansweredQuestion
tagged with: multithreading
has comment: http://stackoverflow.com/comment/82553372
has answer: http://stackoverflow.com/a/47796143
tagged with: python
tagged with: optimization
has title: Why my multi-threading program is slow?
downvote count: 0
upvote count: 1
score: 1
answer count: 1
has comment: http://stackoverflow.com/comment/82552614
duplicate of: http://stackoverflow.com/q/10154487
favorite count: 0

http://stackoverflow.com/comment/82593562
score: 0
comment on: http://stackoverflow.com/q/47805088
type: Comment
type: QuestionComment
has text: last night i was working on a mac and the Popen was also blocking. today i am on windows and i changed the windows code to a Popen call `subprocess.Popen([win_python_bin, win_script_file])` and the subprocess is still blocking (stuck waiting for process to end). am I using the subprocess.Popen() correctly? looking at the docs, it seems like i am.

http://stackoverflow.com/comment/82488255
type: Comment
comment on: http://stackoverflow.com/a/47763353
score: 0
type: AnswerComment
has text: @Julien True.. I didn't even look at the 2nd part. I leave those edits to OP.

dictvectorizer
tags question: http://stackoverflow.com/q/47765017
type: Tag
tag name: dictvectorizer

http://stackoverflow.com/a/47726367
has comment: http://stackoverflow.com/comment/82429687
has comment: http://stackoverflow.com/comment/82429526
has comment: http://stackoverflow.com/comment/82441556
score: 0
has comment: http://stackoverflow.com/comment/82419518
has comment: http://stackoverflow.com/comment/82428695
has body: I think os.walk can be tricky. It's easy to lose track of where you are. On top of it, .h5 with pandas can also be tricky whether you read from pd.HDFStore or use pd.read_hdf. Figuring out dataset names within an h5 file is even more ridiculous. This to say, lots of things can go wrong. import pandas as pd import numpy as np import h5py import os dfs = [] for path, dirs, filenames in os.walk(os.curdir): if path != os.curdir: print(path, dirs, filenames) for file in filenames: file_path = os.path.join(path, file) h5_store = h5py.File(file_path, mode='r') dataset_names = list(h5_store.keys()) for dataset in dataset_names: df = pd.DataFrame(h5_store[dataset].value) print(file, df.shape) dfs.append(df) h5_store.close() final = pd.concat(dfs, ignore_index=True).reset_index() print(final.shape) My directory looks something like: dir1 arr0.h5 dir4 arr0.h5 arr1.h5 arr2.h5 arr3.h5 dir2 arr0.h5 arr1.h5 dir3 arr0.h5 arr1.h5 arr2.h5 dir5 arr0.h5 dir6 arr0.h5 arr1.h5 arr2.h5 arr3.h5 dir7 arr0.h5 arr1.h5 arr2.h5 arr3.h5 That df = pd.DataFrame(h5_store[dataset].value) part is key though. That might not work. It depends on the type of data that is. You might try pd.read_hdf(...) if that doesn't work. It also depends on if you have multiple datasets in each .h5 file.
has comment: http://stackoverflow.com/comment/82427771
has comment: http://stackoverflow.com/comment/82425041
has comment: http://stackoverflow.com/comment/82419913
has comment: http://stackoverflow.com/comment/82428333
type: Answer
has comment: http://stackoverflow.com/comment/82423326
has comment: http://stackoverflow.com/comment/82429859
answers question: http://stackoverflow.com/q/47720252

http://stackoverflow.com/q/47732254
has answer: http://stackoverflow.com/a/47732357
accepted answer: http://stackoverflow.com/a/47732357
score: 2
upvote count: 2
type: AnsweredQuestion
has title: Setting up GUI with Tkinter for Image and Text inputs
answer count: 2
tagged with: tkinter
downvote count: 0
tagged with: user-interface
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/47732372
has body: Im using python 2.7 to build a satellite tracker for a cubesat project at my university. Now I've got the whole thing running as I want it to. I produce 4 images and a load of text based on the ISS's orbit parameters as our cubesat is not yet flying. The 4 pictures are: 1) Satellite's current position on a globe based on its TLE straight from celestrak. 2) Satellite's current position on a mercator(flat) map. 3) Its current lat/lon position translated to a google earth view to physically interpret where it is. 4) Its current lat/lon position based on current weather maps, for whether or not there are clouds in the region, obscuring the satellites remote sensing imaging capabilities. (Reason why the picture looks ugly and purple, is because this region had no current weather data at the time of retrieving data) Then I need to implement a text box with information on altitude, velocity, spatial resolution etc. It's all nice and dandy. But I cant for the love of god figure out how to get this Tkinter GUI to play nice! I'm a geoscientist, not a computer scientist and python programming is very new to me :D Anyway I did a quick layout in photoshop as of how I want the finished data to be produced in a Tkinter GUI. See the primitive image below: Now here is my shameful code below: import Tkinter as tk from PIL import ImageTk, Image #This creates the main window of an application window = tk.Tk() window.title("Satellite Control Center") window.geometry("1000x800") window.configure(background='grey') #Imports the pictures. pic1 = "Globeview.png" pic2 = "MercatorView.png" pic3 = "currentweathercroppedsmall.png" pic4 = "GECurrentcroppedsmall.png" #Creates a Tkinter-compatible photo image, which can be used everywhere Tkinter expects an image object. img1 = ImageTk.PhotoImage(Image.open(pic1)) img2 = ImageTk.PhotoImage(Image.open(pic2)) img3 = ImageTk.PhotoImage(Image.open(pic3)) img4 = ImageTk.PhotoImage(Image.open(pic4)) #The Label widget is a standard Tkinter widget used to…
has answer: http://stackoverflow.com/a/47732372
tagged with: python
has comment: http://stackoverflow.com/comment/82425835

http://stackoverflow.com/comment/82404345
score: 0
has text: Which version of Python are you using?
comment on: http://stackoverflow.com/q/47721867
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47703918
answer count: 1
tagged with: cmake
favorite count: 0
tagged with: visual-studio
has answer: http://stackoverflow.com/a/47704687
accepted answer: http://stackoverflow.com/a/47704687
type: AnsweredQuestion
tagged with: batch-file
score: 1
has title: How to call CMake from a python script using the environment set up by vcvarsall.bat?
tagged with: python
has body: I have a python script for a C++ project that uses CMake as the build system. I want to use the CMake Ninja generator instead of the Visual Studio generator. However, the Ninja generator expects the environment to be set up as performed by the vcvarsall.bat batch file provided with the Visual Studio installation. It's easy if you do everything manually because you can just call the vcvarsall.bat file, get a command prompt with the correct environment set up and then you can fire the cmake -G Ninja command from there. Things become more difficult when trying to use a python script that has not been started in such an environment. How do I call the vcvarsall.bat file programmatically from python, followed by a cmake call in that environment? I assume that the only way is to just fire one subprocess from python. But I cannot come up with a parameter list that would do the job.
type: Question
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/47706170
has body: This program I am trying to build needs to check if the user's input corresponds to values in a list. Here is the code I have: def find_val(val, seq): for ele in seq: if val == ele: return True return False def get_input(possible_vals, day_or_time_string): if day_or_time_string == "day": answer = input("What day would you like your appointment? ") else: answer = input("What time would you like your appointment? ") answer = answer.strip() valid_entry = find_val(answer, possible_vals) if valid_entry == True: count = 0 while False: second_answer = input("Invalid entry. Please enter a valid day: ") count = count + 1 if count == 3: print("This is getting silly - still not a valid entry") if second_answer in possible_vals: return second_answer else: return answer day_list = ["Monday", "Tuesday", "Wednesday"] res = get_input( day_list, "day" ) print("The funtion returned", res) This is the type of output I should be getting: What day would you like your appointment? saturday Invaild entry. Please enter a valid day: Monday The funtion returned Monday However, it seems that no matter what I input, the function returns it, and doesn't check if the input matches a string in the list: What day would you like your appointment? akw The function returned akw What is wrong with my code that isn't allowing the user's input to be checked whether or not it is in the list day_list?
has answer: http://stackoverflow.com/a/47706206
has comment: http://stackoverflow.com/comment/82372562
type: UnansweredQuestion
tagged with: input
tagged with: python
has title: Code not checking values in list?
score: 0
tagged with: list
has comment: http://stackoverflow.com/comment/82372520
tagged with: function
answer count: 1
type: Question

http://stackoverflow.com/comment/82669106
comment on: http://stackoverflow.com/q/47852335
type: Comment
type: QuestionComment
score: 0
has text: @RoadRunner Pls see edit

http://stackoverflow.com/comment/84980316
has text: @BenWhitehead then you aren't generating every possible word containing 20 characters. Did you look at the time required above? Can you point out where it's wrong if you're program is correct?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47744431
type: Comment

http://stackoverflow.com/comment/82695928
type: QuestionComment
has text: did my answer help you or do you need anything else ?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47855766

http://stackoverflow.com/q/47702536
has comment: http://stackoverflow.com/comment/82365203
has comment: http://stackoverflow.com/comment/82367141
has comment: http://stackoverflow.com/comment/82366635
has comment: http://stackoverflow.com/comment/82367428
has answer: http://stackoverflow.com/a/47704553
has comment: http://stackoverflow.com/comment/82366683
answer count: 1
has comment: http://stackoverflow.com/comment/82365270
has comment: http://stackoverflow.com/comment/82365663
has comment: http://stackoverflow.com/comment/82367680
has comment: http://stackoverflow.com/comment/82365827
has comment: http://stackoverflow.com/comment/82366828
has comment: http://stackoverflow.com/comment/82368061
type: Question
has comment: http://stackoverflow.com/comment/82367197
has title: Python - loop through subfolders and files in a directory without ignoring the subfolder
has comment: http://stackoverflow.com/comment/82365651
has body: I have read all the stack exchange help files on looping through subfolders, as as well as the os documentation, but I am still stuck. I am trying to loop over files in subfolders, open each file, extract the first number in the first line, copy the file to a different subfolder(with the same name but in the output directory) and rename the file copy with the number as a suffix. import os import re outputpath = "C:/Users/Heather/Dropbox/T_Files/Raw_FRUS_Data/Wisconsin_Copies_With_PageNumbers" inputpath = "C:/Users/Heather/Dropbox/T_Files/Raw_FRUS_Data/FRUS_Wisconsin" suffix=".txt" for root, dirs, files in os.walk(inputpath): for file in files: file_path = os.path.join(root, file) foldername=os.path.split(os.path.dirname(file_path))[1] filebname=os.path.splitext(file)[0] filename=filebname + "_" f=open(os.path.join(root,file),'r') data=f.readlines() if data is None: f.close() else: with open(os.path.join(root,file),'r') as f: for line in f: s=re.search(r'\d+',line) if s: pagenum=(s.group()) break with open(os.path.join(outputpath, foldername,filename+pagenum+suffix), 'w') as f1: with open(os.path.join(root,file),'r') as f: for line in f: f1.write(line) I expect the result to be copies of the files in the input directory placed in the corresponding subfolder in the output directory, renamed with a suffix, such as "005_2", where 005 is the original file name, and 2 is the number the python code extracted from it. The error I get seems to indicates that I am not looping through files correctly. I know the code for extracting the first number and renaming the file works because I tested it on a single file. But using os.walk to loop through multiple subfolders is not working, and I can't figure out what I am doing wrong. Here is the error: File "&lt;ipython-input-1-614e2851f16a&gt;", line 23, in &lt;module&gt; with open(os.path.join(outputpath, foldername,filename+pagenum+suffix), 'w') as f1: IOError: [Errno 2] No such file or directory: 'C:/Users/Heather/Dropbox/T_Files…
has comment: http://stackoverflow.com/comment/82366477
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82365711
has comment: http://stackoverflow.com/comment/82365126
has comment: http://stackoverflow.com/comment/82365314
has comment: http://stackoverflow.com/comment/82366548
tagged with: python
has comment: http://stackoverflow.com/comment/82366627
linked to: http://stackoverflow.com/q/19932130
tagged with: subdirectory
has comment: http://stackoverflow.com/comment/82366777
has comment: http://stackoverflow.com/comment/82366872
has comment: http://stackoverflow.com/comment/82365192
score: 0

http://stackoverflow.com/a/47836771
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/82654723
score: 1
type: Answer
has body: You shouldn't need the Toplevel() window at all. askinteger() is a dialogbox and does not require a container widget. Just skip the block_request_top window code. import tkinter as tk from tkinter import simpledialog root = tk.Tk() root.geometry("580x400+300+200") root.title("Pah Tum") # Popup window #block_request_top = tk.Toplevel() #block_request_top.title("Blocked fields") entry_block = simpledialog.askinteger("Blocked fields", "Please enter a number of fields to be blocked. Choose an \ uneven number between 5,13]", parent=root, minvalue=5, # parent changed... maxvalue=13) print('Okay, I will block %d fields.' % entry_block) # new, to see value # set up the rest of your GUI root.mainloop() # You need this for the GUI to remain alive. The value of parent was updated to root, to reflect the Toplevel window going away. You also need the root.mainloop() call at the end, to keep the GUI active and running. Once your program gets here, the Tkinter system essentially just waits for "events" to happen, like the user clicking a button or typing into a field. You still have to tie all this together with all the buttons you have to draw. There are a few people posting about this same problem.
answers question: http://stackoverflow.com/q/47834017

http://stackoverflow.com/comment/82660949
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47848342
has text: Which version of python are you using ?
type: Comment

http://stackoverflow.com/comment/82651331
score: 0
type: QuestionComment
type: Comment
has text: especially in discrete wavelet transform. thanks
comment on: http://stackoverflow.com/q/47843671

http://stackoverflow.com/comment/82482264
type: Comment
type: QuestionComment
has text: Could you show me what you mean by the 4th loop being nested in the 3rd and why (trying to understand). Also, for the zip items, I was under the impression if I am going to put several urls to run this loop, it's a good idea to zip the items.
score: 0
comment on: http://stackoverflow.com/q/47760220

http://stackoverflow.com/q/47708655
has body: I want to load a pretrained model and continue training with this model. Standard code snippet to save a model (pretrain.py): tf.reset_default_graph() # tf Graph input X = tf.placeholder("float", [None, n_input]) Y = tf.placeholder("float", [None, n_classes]) mlp_layer_name = ['h1', 'b1', 'h2', 'b2', 'h3', 'b3', 'w_o', 'b_o'] logits = multilayer_perceptron(X, n_input, n_classes, mlp_layer_name) loss_op = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=Y), name='loss_op') optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate) train_op = optimizer.minimize(loss_op, name='train_op') saver = tf.train.Saver() with tf.Session() as sess: sess.run(tf.global_variables_initializer()) # Training cycle for epoch in range(training_epochs): avg_cost = 0. # Loop over all batches for i in range(total_batch): batch_x, batch_y = next(train_generator) # Run optimization op (backprop) and cost op (to get loss value) _, c = sess.run([train_op, loss_op], feed_dict={X: batch_x, Y: batch_y}) # Compute average loss avg_cost += c / total_batch print("Epoch: {:3d}, cost = {:.6f}".format(epoch+1, avg_cost)) print("Optimization Finished!") saver.save(sess, 'model') print("Model saved") Now load the pretrained model and continue training with it (continue.py). # tf Graph input X = tf.placeholder("float", [None, n_input]) Y = tf.placeholder("float", [None, n_classes]) mlp_layer_name = ['h1', 'b1', 'h2', 'b2', 'h3', 'b3', 'w_o', 'b_o'] logits = multilayer_perceptron(X, n_input, n_classes, mlp_layer_name) loss_op = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=Y), name='loss_op') optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate) train_op = optimizer.minimize(loss_op, name='train_op') with tf.Session() as sess: saver = tf.train.import_meta_graph('model.meta') saver.restore(sess, tf.train.latest_checkpoint('./')) # search for checkpoint file graph = tf.get_default_graph() for epoch in range(training_epochs): avg_cost =…
tagged with: python
accepted answer: http://stackoverflow.com/a/47709570
score: 8
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47709570
downvote count: 0
answer count: 1
has title: how to load a tensorflow model and continue training
tagged with: tensorflow
favorite count: 0
type: Question
upvote count: 8

http://stackoverflow.com/comment/82398269
has text: @Adelin Better?
comment on: http://stackoverflow.com/a/47711815
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/47712122
type: UnansweredQuestion
has body: I'm using SQLAlchemy in a Pyramid system. I use a transaction manager (zope) and add a request_method called 'db_session', so request.session can be used to do queries. This is fine in views, but for functions on my SQLAlchemy objects themselves I'm using inspect(self).session to get the session. This is fairly common as far as I can tell. Now I want to be able to access my zope transaction session from classmethods on my SQLAlchemy objects. After trying various things, I realize I have to set my metaclass Base.query to Session.query_property() inside the includeme() function in init.py. Basically this:- def includeme(config): settings = config.get_settings() # use pyramid_tm to hook the transaction lifecycle to the request config.include('pyramid_tm') session_factory = get_session_factory(get_engine(settings)) factory = scoped_session(session_factory) config.registry['dbsession_factory'] = factory Base.query = factory.query_property() # make request.dbsession available for use in Pyramid config.add_request_method( # r.tm is the transaction manager used by pyramid_tm lambda r: get_tm_session(session_factory, r.tm), 'dbsession', reify=True ) 'Base' here is my metaclass. This does what I want, but I realize what I'm effectively doing when using this is using a python global variable. I haven't proceeded very far yet, but is this going to cause problems (especially with testability) in future? I'm pretty sure it 'works' for what I want to do (classmethods have inherent access to the current session without having to have it passed to them).
has comment: http://stackoverflow.com/comment/82395819
has comment: http://stackoverflow.com/comment/82393032
tagged with: session
has comment: http://stackoverflow.com/comment/82518057
has comment: http://stackoverflow.com/comment/82469472
tagged with: python
has comment: http://stackoverflow.com/comment/82393604
has title: Implementing class-based query (query_property) in a zope transaction_manager system, is this testable?
score: 0
has comment: http://stackoverflow.com/comment/82407249
answer count: 0
has comment: http://stackoverflow.com/comment/82468646
tagged with: sqlalchemy
has comment: http://stackoverflow.com/comment/82492766
type: Question
has comment: http://stackoverflow.com/comment/82571171
tagged with: pyramid
has comment: http://stackoverflow.com/comment/82487743

http://stackoverflow.com/a/47755439
has body: You should install pytho-resize-image package. One example from PIL import Image from resizeimage import resizeimage with open('acajeb-image.jpeg', 'r+b') as f: with Image.open(f) as image: cover = resizeimage.resize_cover(image, [200, 200]) cover.save('test-image-cover.jpeg', image.format) You can install package with pip install python-resize-image
score: 0
answers question: http://stackoverflow.com/q/47755312
has comment: http://stackoverflow.com/comment/82471716
type: Answer

http://stackoverflow.com/a/47715381
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47715164
type: Answer
answers question: http://stackoverflow.com/q/47715164
has body: If you're using exec in this way, you're doing something very wrong. The simple solution is to add widgets to a list or dictionary. Though, in this specific case you don't need that because you're never referencing the label anywhere but in the button command. Here's a working example: from tkinter import * root = Tk() def newWindow(): global labels window = Toplevel() labels = {} for i in range(int(textbox.get())): label = Label(window, text='0') button = Button(window, text='Add', command = lambda l=label: setText(l)) label.grid(row=0, column=i) button.grid(row=1, column=i) # this allows you to access any label later with something # like labels[3].configure(...) labels[i] = label def setText(label): label.config(text = str(int(label.cget("text")) + 1)) textbox = Entry(root) textbox.grid(row = 0) submitButton = Button(root, text = "Submit", command = newWindow) submitButton.grid(row = 0, column = 1) root.mainloop() If you wanted to make use of labels, you could have your button pass in the index, and let setText get the widget from the dictionary: def setText(i): label = labels[i] label.configure(...) ... button = Button(..., command=lambda i=i: setText(i))

http://stackoverflow.com/comment/110894450
has text: Does this answer your question? [Python3 correct way to import relative or absolute?](https://stackoverflow.com/questions/28400690/python3-correct-way-to-import-relative-or-absolute)
comment on: http://stackoverflow.com/q/47745447
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82424188
type: AnswerComment
has text: @ArthurTacca thank you very much man! it's working with your edit.
type: Comment
comment on: http://stackoverflow.com/a/47730280
score: 0

http://stackoverflow.com/comment/82592160
has text: `y, z = x.split(':')` split will return a list `['hello', 'world']`, and `x, y =` will unpack it
type: Comment
comment on: http://stackoverflow.com/q/47815322
type: QuestionComment
score: 0

http://stackoverflow.com/comment/82396863
type: Comment
comment on: http://stackoverflow.com/a/47710320
type: AnswerComment
has text: thanks for your response. I have added the original image.
score: 0

http://stackoverflow.com/comment/82516316
has text: why do we need `abs()` here?
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47777606
type: Comment

http://stackoverflow.com/comment/82372482
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47705710
has text: Is there a specific reason that you dont want the quote char in the capturing group? May be easier to strip the quote char after the regex as a post process than to do what you want with the regex
score: 0

http://stackoverflow.com/comment/82666471
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47850993
has text: Oh, thank you. I'm currently installing sympy so hopefully it'll work. Also, I'm asking about similar problems

http://stackoverflow.com/comment/82781744
type: AnswerComment
has text: And, incidentally, I do not need the path, just the distance, so even more to the point.
score: 0
comment on: http://stackoverflow.com/a/47895062
type: Comment

http://stackoverflow.com/q/47778579
downvote count: 0
accepted answer: http://stackoverflow.com/a/47783352
has answer: http://stackoverflow.com/a/47783352
type: AnsweredQuestion
tagged with: python-2.7
tagged with: bz2
has title: How to read lines from arbitrary BZ2 streams for CSV?
has answer: http://stackoverflow.com/a/64665481
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has body: The bz2 module provides a standard open() method from which one can call readline(). However, my situation is one where I have a stream (pointing to a large amount of data) that I want to decompress lines from on the fly. My current implementation is as follows but I know there must be a more succinct way to do this. import bz2 import csv BZ2_BUFFER = '' BZ2_DECOMPRESSOR = None BZ2_FILE = None BZ2_READ_SIZE = 100 * 1024 def bz2_csv_rows(fp): global BZ2_BUFFER, BZ2_DECOMPRESSOR, BZ2_FILE, BZ2_READ_SIZE BZ2_BUFFER = '' BZ2_DECOMPRESSOR = bz2.BZ2Decompressor() BZ2_FILE = fp for row in csv.reader(iter(bz2_line_reader, b'')): yield row def bz2_line_reader(): global BZ2_BUFFER, BZ2_DECOMPRESSOR, BZ2_FILE, BZ2_READ_SIZE if BZ2_BUFFER is None: return None while '\n' not in BZ2_BUFFER: bindata = BZ2_FILE.read(BZ2_READ_SIZE) try: data = BZ2_DECOMPRESSOR.decompress(bindata) except EOFError: break except IOError: pass BZ2_BUFFER += data if len(data) &lt; BZ2_READ_SIZE: BZ2_FILE = None break i = BZ2_BUFFER.find('\n') if i is None or i &lt; 0: line = BZ2_BUFFER BZ2_BUFFER = None return line line = BZ2_BUFFER[:i] BZ2_BUFFER = BZ2_BUFFER[i + 1:] return line Thoughts?
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/64665481
has comment: http://stackoverflow.com/comment/82519213
answer count: 2
score: 5
has comment: http://stackoverflow.com/comment/82518806
upvote count: 5

http://stackoverflow.com/comment/82523967
has text: @Coal_ good point. Edited and removed those examples.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47778970
type: AnswerComment

http://stackoverflow.com/comment/82652114
score: 0
type: Comment
has text: This is the error message that I am getting
type: QuestionComment
comment on: http://stackoverflow.com/q/47843889

http://stackoverflow.com/q/47785763
has title: If I use async workers workers with Gunicorn does my app been to be thread safe?
accepted answer: http://stackoverflow.com/a/47850707
has answer: http://stackoverflow.com/a/47850707
type: Question
tagged with: gunicorn
has body: I am correct in understand that if I use the default worker type (sync) then if the app blocks for any reason, say while waiting fo the result of a database query, the aaociated worker process will not be able to handle any further requests during this time? I am looking for a model which doesn't require too much special coding in my app code. I understand there are two async worker types, gevent and gthread, which can solve this problem. What is the difference between these two and and does my app need to be thread safe to use these? UPDATE - I did some reading on gevent it seems it works by monkey patching std library functions so I would think that in the case of a database query in general it probably wouldn't patch whatever db library I am using so if I would need to program my app to cooperatively yield control when I waiting on the database. Is this correct?
tagged with: python
type: AnsweredQuestion
score: 0
answer count: 1

http://stackoverflow.com/a/47716344
has comment: http://stackoverflow.com/comment/82392952
downvote count: 0
has comment: http://stackoverflow.com/comment/82394590
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/82393235
has comment: http://stackoverflow.com/comment/82395272
accepted answer of: http://stackoverflow.com/q/47713947
has comment: http://stackoverflow.com/comment/82393511
score: 1
has comment: http://stackoverflow.com/comment/82393724
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47713947
has body: This should work: import pandas as pd import numpy as np df = pd.read_excel("C:\\13\\13\\13.xlsx") def highlight_vals(val, min=-1111, max=1, color='green'): if min &lt;= val &lt;= max: return 'background-color: %s' % color else: return '' style_1 = df.style.applymap(highlight_vals, subset=['C']) def highlight_vals(val, min=0, max=0.5, color='yellow'): if min &lt;= val &lt;= max: return 'background-color: %s' % color else: return '' style_2 = df.style.applymap(highlight_vals, subset=['C']) style_1.use(style_2.export()) writer = pd.ExcelWriter("C:\\13\\13\\zz.xlsx") style_1.to_excel(writer, startrow=0, startcol=0, index = False) writer.save() I kept both Styler objects, applied one on another and saved the resulting one to Excel instead of a dataframe. Also note that I fixed your conditions. Otherwise, you won't get yellow color because of min &lt; val
has comment: http://stackoverflow.com/comment/82395347
has comment: http://stackoverflow.com/comment/82393301
has comment: http://stackoverflow.com/comment/82393106
has comment: http://stackoverflow.com/comment/82409525
has comment: http://stackoverflow.com/comment/82393747

http://stackoverflow.com/a/47698374
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82356818
accepted answer of: http://stackoverflow.com/q/47697995
has comment: http://stackoverflow.com/comment/82357116
type: Answer
has comment: http://stackoverflow.com/comment/82357991
score: 2
answers question: http://stackoverflow.com/q/47697995
upvote count: 2
has body: gridfs.GridFS.find_one allows to find a file that was saved to GridFS using a filename. This method returns an instance grid_file.GridOut that can be read. file = fs.find_one({'filename': 'foo'}) image = file.read()

http://stackoverflow.com/comment/82626339
type: Comment
type: QuestionComment
has text: Now that you mention that, no, I haven't, I will check that out, thank you
score: 0
comment on: http://stackoverflow.com/q/47831444

http://stackoverflow.com/a/47739908
upvote count: 2
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/82441385
score: 2
answers question: http://stackoverflow.com/q/47735929
type: AcceptedAnswer
has body: Use the mean squared error function for regression tasks. For classification tasks, one usually uses a softmax layer as output and optimizes the cross-entry cost function.
accepted answer of: http://stackoverflow.com/q/47735929
has comment: http://stackoverflow.com/comment/82442732

http://stackoverflow.com/comment/82516555
type: Comment
comment on: http://stackoverflow.com/a/47775499
has text: I didn't visite FB for 2 months - there is too much informations to read. And it displays Python code without indentions and colors.
score: 0
type: AnswerComment

http://stackoverflow.com/a/47821861
score: 0
has comment: http://stackoverflow.com/comment/82607963
answers question: http://stackoverflow.com/q/47820002
type: Answer
has body: In the below answer, I have tried using pandas.to_datetime, to convert the epoch time into date time. I'm reading data from csv like below: import pandas as pd df = pd.read_csv(path) print(df) Timestamp 0 1.512580e+12 1 1.512420e+12 2 1.512420e+12 df.Timestamp = pd.to_datetime(df['Timestamp'], unit='ms') print(df) Timestamp 0 2017-12-06 17:06:40 1 2017-12-04 20:40:00 2 2017-12-04 20:40:00 df.applymap(type) Timestamp 0 &lt;class 'pandas._libs.tslib.Timestamp'&gt; 1 &lt;class 'pandas._libs.tslib.Timestamp'&gt; 2 &lt;class 'pandas._libs.tslib.Timestamp'&gt;
has comment: http://stackoverflow.com/comment/82607088

http://stackoverflow.com/comment/83504149
score: 0
comment on: http://stackoverflow.com/a/47745740
has text: Yes, i saw it Jay, when you chose the V1 and then chose V2, the list is updated and we can see that there is only East US. Thank you for your help =)
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/82415383
type: Comment
type: QuestionComment
has text: is 'page' a method? What 'another url' are you referring to?
score: 0
comment on: http://stackoverflow.com/q/47725714

http://stackoverflow.com/comment/82424716
type: QuestionComment
score: 0
has text: don't load image in `draw()` again and again - it slows down program - do it only once in `__init__`
comment on: http://stackoverflow.com/q/47730829
type: Comment

http://stackoverflow.com/a/47783429
answers question: http://stackoverflow.com/q/47782361
score: 1
has body: Also another possibility by using sort_values and drop_duplicates: data.melt(id_vars=["field1", "field2"], var_name="date", value_name="obs")\ .dropna(subset=['obs'])\ .sort_values(['field1', 'date'], ascending=[True, False])\ .drop_duplicates('field1', keep='first') which gives you field1 field2 date obs 21 a 0.0 2017 4.0 8 b 5.0 2015 7.0 9 c 10.0 2015 12.0 10 d 15.0 2015 17.0 4 e 20.0 2014 21.0 26 f 25.0 2017 29.0 27 g 30.0 2017 34.0
type: Answer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/82530491

http://stackoverflow.com/q/47735037
has body: I've tried time.sleep(), but its accuracy is total garbage. Consider this loop, for instance: for i in range(10000000): print(i) sleep(.334) Watch the numbers it prints. If it's anything like my computer, it's not even remotely regular. Is this function supposed to be accurate? Have I found a bug somewhere in my system? If this function is not supposed to be accurate, what function would be more accurate?
downvote count: 2
answer count: 3
has answer: http://stackoverflow.com/a/47735147
tagged with: real-time
linked to: http://stackoverflow.com/q/47735431
upvote count: 1
has title: An accurate python sleep function
has comment: http://stackoverflow.com/comment/82430548
has comment: http://stackoverflow.com/comment/82431352
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82430512
has comment: http://stackoverflow.com/comment/82430593
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82430511
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/82430838
has answer: http://stackoverflow.com/a/47735937
has answer: http://stackoverflow.com/a/47744798

http://stackoverflow.com/a/47811348
score: 8
has body: I would use the PermissionRequiredMixin. With this you can specify specific permissions users need to have or override the has_permission method. from django.contrib.auth.mixins import PermissionRequiredMixin class RecruitView(PermissionRequiredMixin, generic.DetailView): ... login_url = '/login/' permission_denied_message = 'you did not confirmed yet. please check your email.' def has_permission(self): return self.request.user.email_confirmed This will redirect users without the email_confirmed to the login_url where you can display the error message. In order to use the index.html template instead you might need to override the handle_no_permission method.
downvote count: 0
has comment: http://stackoverflow.com/comment/82584401
type: AcceptedAnswer
upvote count: 8
accepted answer of: http://stackoverflow.com/q/47811179
has comment: http://stackoverflow.com/comment/82585044
answers question: http://stackoverflow.com/q/47811179
type: Answer

http://stackoverflow.com/a/47760486
score: 2
accepted answer of: http://stackoverflow.com/q/47758248
type: AcceptedAnswer
downvote count: 0
has body: You can use state variables (True/False) to control which element to display and you can change those varibles using button. In example I have display_text = True display_button_1 = True display_button_2 = False to control when display text and two buttons. First button change values and it hides text and first button, and it shows second button. There is one problem - your button function is ugly and it use get_buttons() so when I hold pressed button and I remove one button and put another in the same place then it automatically click second button. You should use event.type == MOUSEBUTTONUP (as suggest @Hilea) to fix this. import pygame import sys # every import in separated line # --- constants --- display_width = 800 display_height = 600 black = (0,0,0) white = (255,255,255) red = (200,0,0) green = (0,200,0) bright_red = (255,0,0) bright_green = (0,255,0) block_color = (53,115,255) # --- functions --- def text_objects(text, font): textSurface = font.render(text, True, black) return textSurface, textSurface.get_rect() def button(msg,x,y,w,h,ic,ac,action=None): mouse = pygame.mouse.get_pos() click = pygame.mouse.get_pressed() if x+w &gt; mouse[0] &gt; x and y+h &gt; mouse[1] &gt; y: pygame.draw.rect(gameDisplay, ac,(x,y,w,h)) if click[0] == 1 and action != None: pygame.mixer.music.stop() action() else: pygame.draw.rect(gameDisplay, ic,(x,y,w,h)) smallText = pygame.font.SysFont("comicsansms",20) textSurf, textRect = text_objects(msg, smallText) textRect.center = ( (x+(w/2)), (y+(h/2)) ) gameDisplay.blit(textSurf, textRect) def quitgame(): pygame.quit() sys.exit() quit() def hide_text(): global display_text global display_button_1 global display_button_2 display_text = False display_button_1 = False display_button_2 = True def game_loop(): global display_text global display_button_1 global display_button_2 gameExit = False display_text = True display_button_1 = True display_button_2 = False meie_font = pygame.font.SysFont("Arial", 36) tekst = "This game will go as f…
answers question: http://stackoverflow.com/q/47758248
upvote count: 2
type: Answer

apache-spark
tags question: http://stackoverflow.com/q/47828907
tags question: http://stackoverflow.com/q/47791878
tags question: http://stackoverflow.com/q/47770674
tags question: http://stackoverflow.com/q/47829201
tags question: http://stackoverflow.com/q/47764902
tags question: http://stackoverflow.com/q/47774601
tags question: http://stackoverflow.com/q/47847285
tags question: http://stackoverflow.com/q/47722948
tags question: http://stackoverflow.com/q/47780567
tags question: http://stackoverflow.com/q/47726552
tags question: http://stackoverflow.com/q/47829089
tags question: http://stackoverflow.com/q/47844999
tags question: http://stackoverflow.com/q/47702406
tags question: http://stackoverflow.com/q/47719089
tags question: http://stackoverflow.com/q/47736702
tags question: http://stackoverflow.com/q/47723547
tags question: http://stackoverflow.com/q/47709253
tags question: http://stackoverflow.com/q/47765716
tags question: http://stackoverflow.com/q/47844496
tags question: http://stackoverflow.com/q/47805216
tags question: http://stackoverflow.com/q/47721453
tags question: http://stackoverflow.com/q/47705919
tags question: http://stackoverflow.com/q/47766256
tags question: http://stackoverflow.com/q/47744644
tags question: http://stackoverflow.com/q/47807845
tags question: http://stackoverflow.com/q/47787075
type: Tag
tags question: http://stackoverflow.com/q/47779919
tags question: http://stackoverflow.com/q/47707405
tag name: apache-spark
tags question: http://stackoverflow.com/q/47801317
tags question: http://stackoverflow.com/q/47755665
tags question: http://stackoverflow.com/q/47730265
tags question: http://stackoverflow.com/q/47701769
tags question: http://stackoverflow.com/q/47832817
tags question: http://stackoverflow.com/q/47842829
tags question: http://stackoverflow.com/q/47699922

http://stackoverflow.com/comment/82484176
comment on: http://stackoverflow.com/q/47761343
has text: No you can't. In the same way that you can not format a string with `round()`
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/82359666
type: Comment
type: QuestionComment
score: 0
has text: Ok so you're trying to build a nested dictionary? Something like `[{'t_key':'wanna_play_a_game','langs':{'english':'Wanna play a game?','spanish':'¿Quiero jugar a un juego?'},...]`
comment on: http://stackoverflow.com/q/47699695

http://stackoverflow.com/comment/82599861
score: 0
comment on: http://stackoverflow.com/q/47817419
type: Comment
has text: maybe it helps: [scrapy: Populate nested items with itemLoader](https://stackoverflow.com/questions/41333735/scrapy-populate-nested-items-with-itemloader)
type: QuestionComment

http://stackoverflow.com/comment/82641426
has text: Actually I don't think this gives what I need, the shape is still (33388, 104), shouldn't it be smaller after the multiplication?
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47838630

http://stackoverflow.com/comment/82482892
type: Comment
score: 1
has text: What does "center each row of the legend" mean exactly? What is the required output?
type: QuestionComment
comment on: http://stackoverflow.com/q/47760805

http://stackoverflow.com/comment/82650586
type: QuestionComment
has text: The user's first click on the canvas starts appending (x,y) points into a list. Every subsequent click adds another (x,y) point to the list, until some user action indicates the curve is complete and can be automatically closed. For feedback in a GUI, the first click draws a point on the canvas and subsequent points draw a point and a line from the last point. For extra swank, draw a "rubberband" line from the last point to the current cursor position and also implement an "undo/redo" mechanism. Actually **how** to do this depends on the GUI platform you are using, if any.
type: Comment
comment on: http://stackoverflow.com/q/47843278
score: 1

http://stackoverflow.com/comment/82466437
score: 0
comment on: http://stackoverflow.com/a/47735899
type: Comment
has text: issues with anaconda too, see https://stackoverflow.com/questions/47743619/fresh-windows-10-fresh-anaconda-error-404
type: AnswerComment

http://stackoverflow.com/q/47763061
tagged with: numpy
score: 0
answer count: 1
tagged with: arrays
has answer: http://stackoverflow.com/a/47764199
linked to: http://stackoverflow.com/q/2777907
has body: I am trying to re-center a set of image-like data where I know the appropriate offset in the x- and y- dimensions. Similarly to this question I want to do something like a "roll" but instead of assuming periodic boundary conditions I want to fill in the "empty" positions in the array with zeros. My question is more general than the one that I have linked because I would like to shift an array in arbitrary directions. In the accepted solution, one must always know what direction the image is being rolled, in order to cut off the appropriate edge. In particular, here is the accepted solution which involves shifting the array x by 1. import numpy as np x = np.array([[1, 2, 3],[4, 5, 6]]) print np.pad(x,((0,0),(1,0)), mode='constant')[:, :-1] However to do the reverse operation, one would have to hard code the following change: import numpy as np x = np.array([[1, 2, 3],[4, 5, 6]]) print np.pad(x,((0,0),(0,1)), mode='constant')[:, 1:] // changed argument of pad // and array indices Is there a simple way to implement both at once?
type: Question
has title: python numpy roll with padding in arbitrary direction
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/82637334
comment on: http://stackoverflow.com/a/47836471
score: 0
type: AnswerComment
has text: Thanks! Question: I know we're using idxmin and loc, but is it possible to remove the index while using them?
type: Comment

http://stackoverflow.com/q/47847370
tagged with: node.js
has comment: http://stackoverflow.com/comment/82659644
score: 2
type: AnsweredQuestion
has body: Background Story I have a python project which uses setuptools for building the source distribution. Pylint is integrated for running tests. And I come from a heavy NodeJs background. Problem After doing changes to the code, I have several steps which should be run before distributing the application. Run tests Run pylint Clean build/dist directories Build source distribution using setuptools and distutils etc etc etc And some other requirements like, Install packages using pip install -r requirements.txt Activate virtualenv Trigger pre-commit &amp; pre-push git hooks (Not yet implemented) In NodeJs projects, I can write a set of shell commands with pre and post subscripts in the package.json file which does the job in a real nice way. Currently for the python project, I am using a shell script which executes the required steps in required order. One other option I thought of was having a package.json just for the sake of handling the dev environment. But it doesn't sound pythonic! How can I automate these steps in an elegant pythonic way?
answer count: 2
tagged with: setuptools
downvote count: 0
accepted answer: http://stackoverflow.com/a/47848544
has title: How to setup a developer environment for a python project similar to NodeJs
has answer: http://stackoverflow.com/a/47852066
favorite count: 0
tagged with: git
type: Question
has answer: http://stackoverflow.com/a/47848544
tagged with: setup.py
has comment: http://stackoverflow.com/comment/82659520
upvote count: 2
possible better answer: http://stackoverflow.com/a/47852066
tagged with: python

http://stackoverflow.com/comment/82642345
type: Comment
comment on: http://stackoverflow.com/a/47817357
score: 0
type: AnswerComment
has text: in your join on=expression, try adding an alias: .join((exp1... exp2).alias('price'))

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

http://stackoverflow.com/comment/82525451
comment on: http://stackoverflow.com/a/47775650
score: 0
type: AnswerComment
has text: @Topto: that link doesn't actually lead anywhere, I'm afraid.
type: Comment

http://stackoverflow.com/comment/82478083
score: 2
comment on: http://stackoverflow.com/q/47758410
type: Comment
type: QuestionComment
has text: When you say "back to base-10", you're talking about converting from a base-32 string representation of an integer to a Python `int`, right? (Python `int`s aren't stored in base 10, so the "base-10" part is a bit misleading.)

http://stackoverflow.com/q/47827424
has answer: http://stackoverflow.com/a/47827587
favorite count: 0
tagged with: python-3.x
has title: How I can link the output of the 1st program as an input for the 2nd program using python?
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/47827600
type: UnansweredQuestion
tagged with: python
has body: I have a program written in Python and need to use the output values of this program as an input values to my second program of same python folder. May I know is it possible to do; if so can you please tell me which module is used and would be great if I can get a small example. For example below is the first program and from this how I can take the output value 'x' to plot in my second program. from functools import partial import numpy import scipy.optimize import matplotlib.pyplot as pp def z(x, y): return x * y - 30 x_window = 0, 15 y_window = 0, 5 xs = [] ys = [] for x in numpy.linspace(*x_window, num=200): try: # A more efficient technique would use the last-found-y-value as a # starting point y = scipy.optimize.brentq(partial(z, x), *y_window) except ValueError: # Should we not be able to find a solution in this window. pass else: xs.append(x) ys.append(y) pp.plot(xs, ys) pp.xlim(*x_window) pp.ylim(*y_window) pp.show()
has answer: http://stackoverflow.com/a/47827524
score: 2
answer count: 3
downvote count: 0

http://stackoverflow.com/q/47849292
type: Question
tagged with: fft
has title: python-FFT and PSD calculating
has body: I have a set of data that consists of 36002 items and I want to do FFT and PSD of it to know which frequency it includes and corresponding power density of the frequency. My code is: from __future__ import division import numpy import matplotlib.pyplot as plt #read in the pressure p_dot and time t, they are [36002,] vector nSteps=36002 p_dot=numpy.genfromtxt((r'E:\p_dot.dat'), delimiter=' ')[:,2] t=numpy.genfromtxt((r'E:\t.dat'), delimiter=' ')[:,0] T=(t[-1]-t[0])/nSteps # the interval between two data points N=len(p_dot)//2+1 # FFT is symmetrical, so plot one half Y=numpy.fft.fft(p_dot) # to compare with Yhann hann=numpy.hanning(len(p_dot)) Yhann=numpy.fft.fft(hann*p_dot) fa=1.0/T # scan frequency X=numpy.linspace(0, fa/2, N, endpoint=True) # Nyquest frequency=fa/2 plt.close() plt.subplot(2,1,1) plt.plot(x,y) plt.subplot(2,1,2) plt.plot(X, 2.0*abs(Yhann[:N])/N) plt.tight_layout() plt.show() But the results turned out incorrect, at least I think so. Apparently my data is periodical, but the FFT only has a spike at 0 Hz. See the result of first 1000 items. result 1000 And the result of 36002 result 36002 So what's the problem? Thanks a lot. Btw, can anyone explain how to use overlap window in python? And when should we use it? Since when I search the solution of my problem, I always see these methods and no idea how to use it. Thanks!
tagged with: python
has answer: http://stackoverflow.com/a/47849518
has comment: http://stackoverflow.com/comment/82888066
type: UnansweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/82663449
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0

http://stackoverflow.com/q/47825335
downvote count: 0
tagged with: mysql
upvote count: 1
has answer: http://stackoverflow.com/a/47825460
score: 1
favorite count: 0
type: Question
has title: mysql connector in python not working
tagged with: python
has body: i wrote the code as below import mysql.connector mysql.connector.connect (host='localhost',database='test2',user='root',password='1234') and saved the file as databas.py. When i execute the below code from command prompt i am getting error as shown in command_prompt_error. But when i execute the same set of commands in python command line link to data base s getting created successfully.(shown in working.png) please let me know what is the source of the issue
has comment: http://stackoverflow.com/comment/82613302
has comment: http://stackoverflow.com/comment/82613140
has comment: http://stackoverflow.com/comment/82613180
type: UnansweredQuestion
answer count: 1

http://stackoverflow.com/a/47777359
score: 0
type: Answer
answers question: http://stackoverflow.com/q/47777358
accepted answer of: http://stackoverflow.com/q/47777358
type: AcceptedAnswer
has body: This kind of a problem usually occurs when Spyder gets upgraded. Turns out there was some bug in Spyder 3.1 version and there was an auto upgrade which caused the import to stop working. I just downgraded to version 3.0 from Anaconda Navigator and things seem to be working fine. This link discusses the same in sufficient detail.

http://stackoverflow.com/comment/82418074
has text: Can't you just use something like: `stats = [n.text for n in soup.select('ul.inline-stats.section li strong')]` ?
type: QuestionComment
comment on: http://stackoverflow.com/q/47728631
score: 0
type: Comment

http://stackoverflow.com/comment/82647271
type: QuestionComment
has text: @DanielRoseman ah the second version work there is an error because I use `UserProfile` in other model above `FavoriteAd`. I didn't change it to the string version.
comment on: http://stackoverflow.com/q/47834997
score: 0
type: Comment

http://stackoverflow.com/comment/82404102
score: 0
has text: I am suspecting a certain type of timeout of some sort. Maybe saving is taking too long and workers and timing out ?
type: QuestionComment
comment on: http://stackoverflow.com/q/47720893
type: Comment

http://stackoverflow.com/comment/82418736
has text: it shows 'urllib3 1.16 <pip>' and 'urllib3 1.22 <pip>'
score: 0
comment on: http://stackoverflow.com/q/47728299
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82481282
type: Comment
score: 0
type: AnswerComment
has text: adding `to_csv()` at the end
comment on: http://stackoverflow.com/a/47759784

api
tags question: http://stackoverflow.com/q/47719280
tag name: api
tags question: http://stackoverflow.com/q/47761876
tags question: http://stackoverflow.com/q/47789696
tags question: http://stackoverflow.com/q/47838831
tags question: http://stackoverflow.com/q/47803592
tags question: http://stackoverflow.com/q/47836641
tags question: http://stackoverflow.com/q/47828222
tags question: http://stackoverflow.com/q/47844064
tags question: http://stackoverflow.com/q/47849057
tags question: http://stackoverflow.com/q/47824793
tags question: http://stackoverflow.com/q/47777908
tags question: http://stackoverflow.com/q/47775993
tags question: http://stackoverflow.com/q/47849077
tags question: http://stackoverflow.com/q/47828090
tags question: http://stackoverflow.com/q/47767969
type: Tag
tags question: http://stackoverflow.com/q/47729872
tags question: http://stackoverflow.com/q/47847408

http://stackoverflow.com/comment/82632920
comment on: http://stackoverflow.com/q/47834140
has text: @MaxU What about copyright?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/47716695
has comment: http://stackoverflow.com/comment/82402165
has comment: http://stackoverflow.com/comment/82403392
upvote count: 2
has body: We have a python program that needs to send logs to splunk. Our splunk admins have created a service collector HTTP endpoint to publish logs to with the following: index token hostname URI We can't find where to input the URI in the splunk python SDK client. For example: import splunklib.client as client import splunklib.results as results_util HOST="splunkcollector.hostname.com" URI="services/collector/raw" TOKEN="ABCDEFG-8A55-4ABB-HIJK-1A7E6637LMNO" PORT=443 # Create a Service instance and log in service = client.connect( host=HOST, port=PORT, token=TOKEN) # Retrieve the index for the data myindex = service.indexes["cloud_custodian"] # Submit an event over HTTP myindex.submit("Dummy test python client log") As you can see I never use the URI variable. The above code results in: Traceback (most recent call last): File "splunk_log.py", line 15, in &lt;module&gt; myindex = service.indexes["cloud_custodian"] File "/usr/local/lib/python2.7/site-packages/splunklib/client.py", line 1230, in __getitem__ raise KeyError(key) KeyError: UrlEncoded('cloud_custodian')
possible better answer: http://stackoverflow.com/a/47741688
downvote count: 0
tagged with: splunk
has comment: http://stackoverflow.com/comment/82401407
has comment: http://stackoverflow.com/comment/82401647
has answer: http://stackoverflow.com/a/47741688
has comment: http://stackoverflow.com/comment/82401682
tagged with: splunk-sdk
type: AnsweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/82401525
has title: write log entry to splunk via HTTP in python
has answer: http://stackoverflow.com/a/47756716
tagged with: python
favorite count: 0
accepted answer: http://stackoverflow.com/a/47756716
type: Question
has comment: http://stackoverflow.com/comment/82394378
answer count: 2

http://stackoverflow.com/comment/130152614
comment on: http://stackoverflow.com/a/47766308
has text: This does not answer the question. Extract will completely remove the contents too, so instead of having 4 "paragraph1" strings you will get only 3.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/82567902
type: Comment
comment on: http://stackoverflow.com/a/47803229
type: AnswerComment
has text: Holy hell that's sneaky.
score: 1

http://stackoverflow.com/comment/82462616
comment on: http://stackoverflow.com/q/47750639
type: Comment
type: QuestionComment
has text: @ImportanceOfBeingErnest Thank you I will take a look at it. The shown solution would lead me to rewrite the code (which is not from me), so I wanted to know if there was a more direct way. Thank you again
score: 0

http://stackoverflow.com/comment/82540692
has text: Your second part raises an error: AttributeError: module 'numpy' has no attribute 'moveaxis' But your first part works perfectly. I just removed **cb** variable to remove the colorbar.
type: AnswerComment
comment on: http://stackoverflow.com/a/47778106
score: 0
type: Comment

http://stackoverflow.com/comment/103413679
type: AnswerComment
has text: @GhoulFool If a MEL command is multiple lines, all but the last line need a semicolon. The last line is delimited by the end of file.
comment on: http://stackoverflow.com/a/47790315
type: Comment
score: 0

http://stackoverflow.com/q/47731793
has body: I am getting input value and save it in the variable. and the error message occurs as this. Here is my code: input_id = input("your id please") members = ['egoing', 'k8805'] for member in members: if member == input_id: print("hellop"+member) and here is the error message /Python_Workspace/PycharmProjects/Practice/venv/bin/python /Python_Workspace/PycharmProjects/Practice/Container_Loop/4.py your id pleaseegoing Traceback (most recent call last): File "/Python_Workspace/PycharmProjects/Practice/Container_Loop/4.py", line 1, in &lt;module&gt; input_id = input("your id please") File "&lt;string&gt;", line 1, in &lt;module&gt; NameError: name 'egoing' is not defined Process finished with exit code 1 Many others asked similar questions and many answers highlighted raw_input and input function and its role after version change. I just started python and currently using pycharm 2017.3 and didnot individually install python in my mac. Any advice why this error is happening?
tagged with: pycharm
tagged with: python
type: AnsweredQuestion
score: 0
has title: Pycharm 2017.3 and input function
answer count: 1
has comment: http://stackoverflow.com/comment/82424165
accepted answer: http://stackoverflow.com/a/47731930
has answer: http://stackoverflow.com/a/47731930
type: Question

http://stackoverflow.com/q/47705215
has body: I've deployed my Python app on Heroku and have connected it to a clearDB database. This works perfectly when run locally, however when running on Heroku my INSERT statements don't seem to be committing properly (sometimes they do, sometimes they don't). It's running through gunicorn. This is my MySQL setup: APP_ROOT = os.path.join(os.path.dirname(__file__), '..') dotenv_path = os.path.join(APP_ROOT, '.env') load_dotenv(dotenv_path) db_user = os.getenv('DB_USER2') db_pass = os.getenv('DB_PASSWORD2') db_database = os.getenv('DB_DATABASE2') db_host = os.getenv('DB_HOST2') app.config['MYSQL_DATABASE_USER'] = db_user app.config['MYSQL_DATABASE_PASSWORD'] = db_pass app.config['MYSQL_DATABASE_DB'] = db_database app.config['MYSQL_DATABASE_HOST'] = db_host mysql.init_app(app) These variables are coming from a .env file. But they are also added as environmental variables on Heroku. So connection to the server is same both locally and on Heroku. It's completely random whether it works or not. Fetch statements work perfectly fine, but inserting or updating seems to cause me a lot of issues. Again, this works perfectly with no issues locally, but doesn't on Heroku. (When run locally, it seems to take a bit of time to save the data, which is fine. But it doesn't take much time at all on Heroku so I'm assuming it's somehow skipping the commit). There are no errors in the logs either. It just seems to bypass the statement sometimes and not commit. Doing a hard refresh sometimes brings up the data, but then it disappears again. Most of the times the data isn't saved at all. I have one cursor open throughout the app and I'm using conn.ping(True) before every SQL statement, and conn.commit() after fetching the data. Any help would be appreciated, thank you!
has comment: http://stackoverflow.com/comment/82370894
score: 0
tagged with: mysql
has answer: http://stackoverflow.com/a/49995806
has comment: http://stackoverflow.com/comment/82370989
has comment: http://stackoverflow.com/comment/82370781
type: Question
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/82371107
answer count: 1
tagged with: cleardb
tagged with: git
tagged with: heroku
has title: Flask/Heroku ClearDB not updating

http://stackoverflow.com/q/47760319
favorite count: 0
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82482151
accepted answer: http://stackoverflow.com/a/47760649
answer count: 3
has body: I'm trying to write simple GUI game in python using tkinter library. I want to generate random numbers and after each generation i want to delete this number. I put my function into a for loop so i want to call it 3 times, but it works just when i call it first. It generates the number then delete it and do not generate a new number again. Could you please explain what is the problem, i am really new to python. from tkinter import * from random import* def blink(): number.config(text=randint(1,10)) number.after(2000, lambda: number.config(text=' ')) root = Tk() number = Label(root,width=20,height=10) number.pack() for i in range(3): blink() root.mainloop()
score: 1
has answer: http://stackoverflow.com/a/47760649
tagged with: python
has answer: http://stackoverflow.com/a/47761118
has comment: http://stackoverflow.com/comment/82482026
has comment: http://stackoverflow.com/comment/82482456
has comment: http://stackoverflow.com/comment/82482097
type: Question
has answer: http://stackoverflow.com/a/47760712
has title: Multiple calling of same function in python
tagged with: tkinter
tagged with: function
possible better answer: http://stackoverflow.com/a/47761118
downvote count: 0
has comment: http://stackoverflow.com/comment/82482219
upvote count: 1

http://stackoverflow.com/a/47736147
score: 0
has body: env: python3.5 + pyqt5.9 I use a timer to update the CPU info like that: #!/usr/bin/python3 # 2017.12.10 13:20:11 CST # 显示 CPU import sys from PyQt5 import QtCore, QtWidgets import psutil class CPU(QtWidgets.QProgressBar): def __init__(self, parent=None): super().__init__(parent) self.setWindowTitle("CPU Info") self.timer = QtCore.QTimer(self) self.timer.timeout.connect(lambda : self.setValue(psutil.cpu_percent())) self.timer.start(1000) if __name__ == '__main__': app = QtWidgets.QApplication(sys.argv) win = CPU() win.show() app.exec_()
answers question: http://stackoverflow.com/q/47735664
downvote count: 1
type: Answer
upvote count: 1

http://stackoverflow.com/comment/82585681
comment on: http://stackoverflow.com/a/47812118
score: 0
has text: If you want only one value then you first need to filter the query to fetch only one object - e.g., `Htmlfiles.objects.get(... some filter here...).values('htmlfile')`. But you need to know which object you want first.
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/82547791
comment on: http://stackoverflow.com/a/47793101
has text: @JohnDoe `data.loc[j[j == j[i].value_counts().idxmax()].index[-1], 'date']`
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/47851337
type: Question
has title: Why does my code keep printing None?
has comment: http://stackoverflow.com/comment/82667096
accepted answer: http://stackoverflow.com/a/47851539
has body: I'm practicing binary_search. I want to return 'ban' but my code keeps returning None. I don't know why None is returned although 'ban' is existing. *'ban' is variable. My code is def binary_search(ls,num): #print ls fir=ls[0] last=ls[-1] ban=(fir+last)/2 print ban,num if ban &gt; num: binary_search(range(fir,ban+1),num) elif num &gt; ban: binary_search(range(ban,last+1),num) elif num==ban: print ls,ban return ban ls=range(1,22) print binary_search(ls,10)
upvote count: 1
tagged with: python
score: -1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82667280
has answer: http://stackoverflow.com/a/47851539
downvote count: 2
answer count: 1
has comment: http://stackoverflow.com/comment/82667278
favorite count: 0

http://stackoverflow.com/comment/82515523
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47775640
has text: The error is because "it is a fatal error to call start_response without the exc_info argument if start_response has already been called" (https://www.python.org/dev/peps/pep-3333/#the-start-response-callable). I am not sure WSGI supports what you want.

http://stackoverflow.com/comment/82412570
score: 1
type: Comment
type: QuestionComment
has text: See https://stackoverflow.com/questions/34187130/fast-random-weighted-selection-across-all-rows-of-a-stochastic-matrix
comment on: http://stackoverflow.com/q/47722005

http://stackoverflow.com/a/47724371
has body: df['Yourcol']=df.groupby('Year Type',sort=False)['Good Year'].apply(lambda x : x.shift().cumsum()) df Out[283]: Good Year Year Year Type Yourcol 0 1 2000 X NaN 1 0 2001 Y NaN 2 1 2002 Z NaN 3 0 2003 Z 1.0 4 0 2004 Z 1.0 5 1 2005 X 1.0 6 1 2006 Y 0.0 7 1 2007 Z 1.0 8 0 2008 Z 2.0
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/136347804
score: 3
type: Answer
answers question: http://stackoverflow.com/q/47723875

http://stackoverflow.com/comment/82406219
has text: This is really close to what I'm looking for, though I'm not trying to get my value to be 8601, just if it is ISO 8601, it should convert to a python datetime object properly, editing my question with what I've worked out so far...
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47718075

http://stackoverflow.com/comment/82671470
comment on: http://stackoverflow.com/q/47852944
has text: A solution without additionals libraries: [How do I change the color of a specific printed letter in python?](https://stackoverflow.com/questions/47670946/how-do-i-change-the-color-of-a-specific-printed-letter-in-python)
type: Comment
score: 1
type: QuestionComment

http://stackoverflow.com/a/47806488
accepted answer of: http://stackoverflow.com/q/47805784
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47805784
has body: You need to add the path to your environment variables: Control Panel>System and Security>System>Advanced System Settings>Environment Variables Select edit PATH and append: C:\Users\lenovo\AppData\Local\Programs\Python\Python36 to the path. Hit apply and ok. After closing and reopening the shell you should be able to type "python" and be in the python shell.
type: Answer
score: 15
upvote count: 15

http://stackoverflow.com/comment/82655901
type: AnswerComment
comment on: http://stackoverflow.com/a/47835500
has text: I have seen that there is a problem in my code, that when I choose a second option, the first one is eliminated, is that what you mean?
type: Comment
score: 0

http://stackoverflow.com/a/47856088
downvote count: 1
has body: You can not connect gremlin-python to Neo4j Server. gremlin-python contains drivers that connect to Gremlin Server so you must have that installed for gremlin-python to work. Given that you need Gremlin Server you must choose one of the following options all of which are just Gremlin Server configurations: Configure Neo4j in embedded mode within Gremlin Server. An example of this is here where that file points to a Neo4j configuration file. Note that these files are packaged in the Gremlin Server distribution as samples so you can run them directly quite easily. Modify the aforementioned Neo4j configuration file to run Neo4j in HA mode effectively turning Gremlin Server into a node in the Neo4j cluster. Configure a neo4j-gremlin-bolt instance which will use the Neo4j Bolt protocol to connect to the running Neo4j Server. While I"m not completely familiar with this implementation, I can see that you would change the gremlin.graph to com.steelbridgelabs.oss.neo4j.structure.Neo4JGraph and that you would discern Bolt configuration options from this class (which instantiates that graph instance). Once you've chosen one of those configuration options you can then use gremlin-python to work with Neo4j.
has comment: http://stackoverflow.com/comment/96314037
has comment: http://stackoverflow.com/comment/96314704
score: 5
has comment: http://stackoverflow.com/comment/95933648
upvote count: 6
type: Answer
answers question: http://stackoverflow.com/q/47843862
has comment: http://stackoverflow.com/comment/102863447
has comment: http://stackoverflow.com/comment/95943323

http://stackoverflow.com/a/47724514
has comment: http://stackoverflow.com/comment/82409843
answers question: http://stackoverflow.com/q/47724459
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/82409926
has body: To understand how the solution process works, try the following: # get all combinations of n items from given list def getCombinations(items, n): if len(items) &lt; n: return [] # need more items than are remaining if n == 0: return [''] # need no more items, return the combination of no items [fst, *rst] = items # all combinations including the first item in the list including = [fst + comb for comb in getCombinations(rst, n-1)] # all combinations excluding the first item in the list excluding = getCombinations(rst, n) both = including + excluding return both x = ['a','b','c','d','e'] n = 3 print(getCombinations(x, n)) # ['abc', 'abd', 'abe', 'acd', 'ace', 'ade', 'bcd', 'bce', 'bde', 'cde']

http://stackoverflow.com/comment/82464218
comment on: http://stackoverflow.com/a/47730960
score: 0
type: AnswerComment
has text: Thank you for your respond. I have the longitude and latitude in my database. It's now possible through a Ajax search to get the names from the database. The Problem is that i don't know how to get coordinates from the view search_duik_locaties(request) in index view so I can use it to place the markers that correspondent with the locaties that is searched for.
type: Comment

http://stackoverflow.com/comment/82517783
type: QuestionComment
score: 3
comment on: http://stackoverflow.com/q/47778321
has text: So why are you using the Europe/London timezone if this is supposed to be a UTC timestamp?
type: Comment

http://stackoverflow.com/comment/82548494
comment on: http://stackoverflow.com/a/47793707
type: AnswerComment
score: 0
type: Comment
has text: @cᴏʟᴅsᴘᴇᴇᴅ Not really similar (so you could have kept it), but I guess `argmax` would be faster though.

http://stackoverflow.com/q/47855577
score: 1
upvote count: 1
accepted answer: http://stackoverflow.com/a/47855632
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47855798
tagged with: python
possible better answer: http://stackoverflow.com/a/47855798
has title: Class Attributes VALUES to a list
linked to: http://stackoverflow.com/q/141545
type: AnsweredQuestion
tagged with: python-2.7
has answer: http://stackoverflow.com/a/47855632
answer count: 2
has body: I have a simple python class that consists of some attributes and some methods.What i need is to make a list out of the class attributes ( only ! ) Class A(): def __init__(self, a=50, b="ship"): a = a b = b def method1(): ..... I want to have a list : [50, "ship"]
downvote count: 0
has comment: http://stackoverflow.com/comment/82675177

http://stackoverflow.com/a/47734030
has comment: http://stackoverflow.com/comment/82438150
score: 2
has body: The target is called with: self._target(*self._args, **self._kwargs) Therefore, you could use: def create_some_threads(my_target, *my_args, **my_keyword_args): for DeviceName in Devices: device_ip = Devices[DeviceName]['mgmt_ip'] my_args = (device_ip, DeviceName,) + my_args my_thread = threading.Thread(target=my_target, args=my_args, kwargs=my_keyword_args)) my_thread.start() When you define you define a function with *my_args or **my_keyword_args in its call signature, note that my_args becomes a tuple inside the body of that function, and my_keyword_args becomes a dict. my_args = (device_ip, DeviceName,) + my_args simply concatenates two more values to the front of the my_args tuple. The error message NameError: global name 'device_ip' is not defined is saying that the variable name device_ip has not been defined in a scope that is accessible at the point where the NameError occurred. A look at the ping_em_all function shows that that's true: def ping_em_all(*my_args, **my_keyword_args): """.rstrip is needed for the ip as .readline adds a \n to the lines' text""" if "Linux" in platform.system(): ping_reply = subprocess.Popen(['ping', '-c', '2', '-w', '2', '-q', device_ip.rstrip('\n')],stdout=limbo, stderr=limbo).wait() ... device_ip is the first value in my_args: my_args = (device_ip, DeviceName,) + my_args Therefore, change ping_em_all to def ping_em_all(*my_args, **my_keyword_args): """.rstrip is needed for the ip as .readline adds a \n to the lines' text""" device_ip, DeviceName, my_args = my_args #&lt;-- This defines device_ip if "Linux" in platform.system(): ping_reply = subprocess.Popen(['ping', '-c', '2', '-w', '2', '-q', device_ip.rstrip('\n')],stdout=limbo, stderr=limbo).wait() ... to unpack values from the my_args tuple and give them variable names.
type: Answer
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/47733928

http://stackoverflow.com/comment/82627048
type: QuestionComment
has text: I probably shouldn't have linked to [that example](https://docs.djangoproject.com/en/2.0/topics/auth/customizing/#a-full-example), I've removed it from my answer now. That example is using `AbstractBaseUser`, not `BaseUser`, so more code is required. See [this other](https://stackoverflow.com/a/43209322/113962) answer from the question @N.Ivanov linked to.
comment on: http://stackoverflow.com/q/47831501
score: 1
type: Comment

http://stackoverflow.com/comment/82567018
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47802722
has text: I really like this solution. OP: FYI, this won't work if the `n` is uppercased

http://stackoverflow.com/a/47797455
has comment: http://stackoverflow.com/comment/82555946
type: Answer
has body: You should read the open file textopen before you can print it. For example: textopen = open('/Users/Don/Desktop/TextAuto/'+proto) print(testopen.readlines()) resource: Methods of File Objects
has comment: http://stackoverflow.com/comment/82556133
answers question: http://stackoverflow.com/q/47796636
score: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/47854186
has answer: http://stackoverflow.com/a/47854338
has comment: http://stackoverflow.com/comment/82672490
score: -2
has comment: http://stackoverflow.com/comment/82672485
has comment: http://stackoverflow.com/comment/82672504
tagged with: python
accepted answer: http://stackoverflow.com/a/47854338
tagged with: ranking
type: AnsweredQuestion
has body: I have a dataset history of temperature/weather by city like this: {"city": "Barcelona", "date": "2016-10-16", "temperature": "13", "weather": "cloudy"} {"city": "Berlin", "date": "2016-10-16", "temperature": "-1", "weather": "sunny"} {"city": "Pekin", "date": "2016-10-16", "temperature": "19", "weather": "cloudy"} {"city": "Paris", "date": "2016-10-16", "temperature": "-8", "weather": "sunny"} And I would like to create a top 5, order by best average temperature.In this result I would like to know the number of day by weather type(sunny cloudy rainy) Example: Rank - City - Average Temperature - Cloudy days - Sunny days - Rainy Days 1 - Barcelona - 20 - 93 - 298 - 29 How can doing this in Python? Thanks Matt
answer count: 1
downvote count: 3
tagged with: dataset
upvote count: 1
has title: Python order dataset weather
favorite count: 0
type: Question

http://stackoverflow.com/a/47836504
has comment: http://stackoverflow.com/comment/82636855
has comment: http://stackoverflow.com/comment/82636757
answers question: http://stackoverflow.com/q/47836276
type: Answer
downvote count: 0
has body: So it looks like you're using requests to try and get data generated by JS. Well this isn't going to work, unless you know some magic a lot of people don't. Requests can't deal with the JS, so it never runs. You should be able to get the data using selenium or something to automate a browser. Otherwise, I don't think you're going to be able to scrape it like this. But if someone knows a way to get JS generated data with requests, please post it.
upvote count: 1
score: 1

http://stackoverflow.com/comment/82566872
score: 2
has text: I think this is correct, but from the question it seems they want the `'n'` included in the tuple.
type: AnswerComment
comment on: http://stackoverflow.com/a/47802722
type: Comment

http://stackoverflow.com/q/47716668
has answer: http://stackoverflow.com/a/47716754
has comment: http://stackoverflow.com/comment/82393628
has answer: http://stackoverflow.com/a/47716953
tagged with: python
has body: My teacher solved this question "Write a function which takes a n digits number as an input and return True if the biggest digit in this number is divisible by 3" like this: def is_divisable(n): a = str(n) b = 0 for i in a: if int(i)&gt;b: b = int(i) if b % 3 == 0: return "True" print is_divisable(67479) I have thought of it in another way but my code is not working and I am getting an error says: "TypeError: 'int' object is not iterable" def is_dvo(n): if max(n) % 3 == 0: return True print is_dvo(67479)
has comment: http://stackoverflow.com/comment/82393889
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82393668
score: 0
has title: I am using `max()` to get the highest value from n digits?
answer count: 3
possible better answer: http://stackoverflow.com/a/47716785
accepted answer: http://stackoverflow.com/a/47716754
type: Question
has answer: http://stackoverflow.com/a/47716785

http://stackoverflow.com/a/47839932
type: Answer
accepted answer of: http://stackoverflow.com/q/47839877
upvote count: 2
score: 2
answers question: http://stackoverflow.com/q/47839877
type: AcceptedAnswer
downvote count: 0
has body: Your print statement and its argument are on separate lines. Do print line, instead.
has comment: http://stackoverflow.com/comment/82643961

http://stackoverflow.com/comment/82378524
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47708963
has text: Also there is pygogo which wraps the python logger, making it even easier https://pypi.python.org/pypi/pygogo
score: 0

tweets
tags question: http://stackoverflow.com/q/47841431
tags question: http://stackoverflow.com/q/47733763
tags question: http://stackoverflow.com/q/47739967
tag name: tweets
type: Tag
tags question: http://stackoverflow.com/q/47726484

http://stackoverflow.com/q/47720941
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82561617
tagged with: visual-studio-code
has comment: http://stackoverflow.com/comment/82606149
answer count: 0
has body: I have a new clean installation of VSCode on Linux Mint 18.2. I've installed Python 0.8.0, Python Extension Pack 1.0.1, Python for VSCode 0.2.3 and MagicPython 1.0.12 I can debug code in the integrated console but not in an external console. Since I'm writing code that must be run as a super user, that means I can't debug the code (the integrated terminal will not run sudo code). When I try and debug, the debug console throws 'Error: spawn ENODIR'. The launch.json section is as follows: "name": "Python: Terminal (external)", "type": "python", "request": "launch", "stopOnEntry": true, "pythonPath": "/usr/bin/python3.5m", "program": "${file}", "cwd": "/home/jsb/development/diskHealth/health.py", "console": "externalTerminal", "env": {}, "envFile": "${workspaceRoot}/.env", "debugOptions": [ "WaitOnAbnormalExit", "WaitOnNormalExit", "Sudo" ] Thanks for any insight.
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82568376
score: 0
has comment: http://stackoverflow.com/comment/82643752
tagged with: python
has title: VSCode python debugger crashes
type: Question

http://stackoverflow.com/comment/82554933
score: 0
type: Comment
has text: @zwer Refusing to comply to absurdity is decency. I will rephrase my answer to reflect your concerns though.
comment on: http://stackoverflow.com/a/47796976
type: AnswerComment

http://stackoverflow.com/a/47764728
has comment: http://stackoverflow.com/comment/82490781
has body: so you need something like this ? x.groupby('person').rating.apply(lambda x : (sum(x&lt;=4)-sum(x==4))/len(x)) Out[7]: person a 0.4 b 0.8 Name: rating, dtype: float64 Or transform ? x.groupby('person').rating.transform(lambda x : (sum(x&lt;=4)-sum(x==4))/len(x)) Out[8]: 0 0.4 1 0.8 2 0.4 3 0.8 4 0.4 5 0.8 6 0.4 7 0.8 8 0.4 9 0.8 Name: rating, dtype: float64 EDIT : x=x.sort_values('person') x['ref']=x.groupby('person').rating.apply(lambda y : [(sum(y&lt;=x)-sum(y==x))/len(y) for x in y]).apply(pd.Series).stack().values x Out[25]: person rating ref 0 a 1 0.0 2 a 4 0.4 4 a 4 0.4 6 a 3 0.2 8 a 5 0.8 1 b 3 0.4 3 b 2 0.0 5 b 2 0.0 7 b 4 0.8 9 b 3 0.4 Since you are using python 2.7 x['map']=x.person.map(x.groupby('person').rating.apply(list)) x.apply(lambda x : sum(x['rating']&lt;np.array(x['map']))/len(x['map']),1 )
type: Answer
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/82490969
downvote count: 0
answers question: http://stackoverflow.com/q/47764095
has comment: http://stackoverflow.com/comment/82491213
has comment: http://stackoverflow.com/comment/82490955
has comment: http://stackoverflow.com/comment/82491116

http://stackoverflow.com/q/47766453
tagged with: pandas
type: AnsweredQuestion
answer count: 1
downvote count: 0
score: 1
upvote count: 1
favorite count: 0
has title: spliting a data frame and then saving them into two separate dfs in python
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/47766576
type: Question
has body: I have a pandas dataframe with columns as id,program,name,add Some of the records don't have any values for the name and add columns (i.e. contains NaN values). I want to split this dataframe into two in such a way that the first df1 contains all the values under id,program,name,add i.e. no null values (only those records that contain values under each column); and the second df2 contains only those records wherein there's no value under both the name and add column. If either of name and add has any value then it should go into df1, df2 should contain only those records wherein both the columns have NaN values. The question may seem stupid to some, but I've just started using python, so still a newbie. the sample data looks like this: id, program,name,add 142, FOO, Sherlock, Baker street 934, FOOFOO, Harry, Hogwards 229, ABC,NaN,NaN 420, XYZ,NaN,USA 619, DEF,NaN,NaN desired output should be something like this: df1: id,program,name,add 142, FOO, Sherlock, Baker street 934, FOOFOO, Harry, Hogwards 420, XYZ,NaN,USA df2: id,program,name,add 229, ABC,NaN,NaN 619, DEF,NaN,NaN Thanks in advance.
has answer: http://stackoverflow.com/a/47766576
tagged with: dataframe
tagged with: python

http://stackoverflow.com/q/47802322
answer count: 3
tagged with: matrix
score: 1
has answer: http://stackoverflow.com/a/47802891
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/47802667
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47802805
has title: Converting into an appropriate distance matrix (for TSP)
tagged with: distance-matrix
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/82566780
tagged with: traveling-salesman
has body: I currently have a matrix like this: [[2, 6, 8, 9, 8, 6, 3], [4, 8, 10, 10, 7, 5], [5, 6, 8, 8, 9], [4, 6, 7, 8], [3, 5, 9], [3, 6], [4]] such that the first array is distances from city 1 to 2,3,4,5,6,7,8 the second is distances from city 2 to 3,4,5,6,7,8 ... the 7th array is the distance from city 7 to city 8. I need to convert it into a proper distance matrix. So far, I've inserted 0's to make it size 7 and it becomes: [[2, 6, 8, 9, 8, 6, 3], [0, 4, 8, 10, 10, 7, 5], [0, 0, 5, 6, 8, 8, 9], [0, 0, 0, 4, 6, 7, 8], [0, 0, 0, 0, 3, 5, 9], [0, 0, 0, 0, 0, 3, 6], [0, 0, 0, 0, 0, 0, 4]] I then did for i,j if distance==0 then distances[i][j]=distances[j][i] and it becomes: [[2, 6, 8, 9, 8, 6, 3], [6, 4, 8, 10, 10, 7, 5], [8, 8, 5, 6, 8, 8, 9], [9, 10, 6, 4, 6, 7, 8], [8, 10, 8, 6, 3, 5, 9], [6, 7, 8, 7, 5, 3, 6], [3, 5, 9, 8, 9, 6, 4]] I then inserted 0's to include the distance from city to same city: [[0, 2, 6, 8, 9, 8, 6, 3], [6, 0, 4, 8, 10, 10, 7, 5], [8, 8, 0, 5, 6, 8, 8, 9], [9, 10, 6, 0, 4, 6, 7, 8], [8, 10, 8, 6, 0, 3, 5, 9], [6, 7, 8, 7, 5, 0, 3, 6], [3, 5, 9, 8, 9, 6, 0, 4]] and finally added on the final city's distances: [[0, 2, 6, 8, 9, 8, 6, 3], [6, 0, 4, 8, 10, 10, 7, 5], [8, 8, 0, 5, 6, 8, 8, 9], [9, 10, 6, 0, 4, 6, 7, 8], [8, 10, 8, 6, 0, 3, 5, 9], [6, 7, 8, 7, 5, 0, 3, 6], [3, 5, 9, 8, 9, 6, 0, 4], [3, 5, 9, 8, 9, 6, 4, 0]] but I appear to have gone wrong somewhere, as I have not produced the correct distance matrix. I believe it may be the distances[i][j]=[j][i] bit, but I'm not entirely sure.

http://stackoverflow.com/comment/121285096
type: AnswerComment
comment on: http://stackoverflow.com/a/68590274
type: Comment
has text: this seemed to resolve the same issue with the Python plugin for IntelliJ 2021.2 also
score: 0

http://stackoverflow.com/q/47769170
downvote count: 2
has title: Identify duplicate - csv dict reader
answer count: 1
has comment: http://stackoverflow.com/comment/82500582
has comment: http://stackoverflow.com/comment/82502093
favorite count: 0
type: Question
type: UnansweredQuestion
score: -2
tagged with: http://stackoverflow.com/tag/csv
has body: I am iterating over rows of one csv file, I want to skip the row from processing if it is duplicate from any of earlier processed row. Below is my code: import csv csv_contents = request.vars['file'].value.decode('utf-8') file = csv_contents.splitlines() file_data = [row for row in csv.DictReader(file)] for data in file_data: #if duplicate, continue. skip the row How to identify if a row is duplicate in a file.
tagged with: duplicates
tagged with: python
has answer: http://stackoverflow.com/a/47769428
upvote count: 0

http://stackoverflow.com/comment/82506619
type: Comment
has text: Hmmm, I guess if you want to pass `progdata = ` it should be something else, probably a `prog_data` structure you initialized previously. Sorry for the red herring. But this is just tangential commentary; focus on the previous comment if you are still struggling.
score: 0
comment on: http://stackoverflow.com/a/47768068
type: AnswerComment

http://stackoverflow.com/comment/82583104
type: Comment
score: 0
has text: was just goin through certain python questions and found this one. and trying to get the desired result. Plus i am new on stackoverflow thus inconvenience regretted about how to state my questions properly. still getting the hang of it.
comment on: http://stackoverflow.com/q/47810665
type: QuestionComment

http://stackoverflow.com/comment/82488377
type: Comment
comment on: http://stackoverflow.com/q/47763326
score: 0
type: QuestionComment
has text: Makes sense. Anyway, I went ahead and just added an answer. Note, Python is a rather dynamic language, and it's object model is a bit different than your typical statically-typed OOP language. For example, `self.stateDescriptions` will first check the instance namespace, and if it doesn't find it, it will check the class-namespace, and all the name-spaces in the MRO. But, you can actually *shadow* class-variables with instance variables. So, say you had a mix of *both* your original definition and the modified one, then you essentially create a useless class-variable that always gets shadowed

scroll
type: Tag
tags question: http://stackoverflow.com/q/47761696
tag name: scroll

http://stackoverflow.com/q/47787803
type: Question
has title: Using HOG to get image descriptors but hog.compute always returns 0.0
type: UnansweredQuestion
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
tagged with: opencv
score: 1
has body: 64x64 image Trying to use OpenCV to do something simple in Python. Using HOG to get the feature vector. But I get all 0.0. I've tried a few images same result. import cv2 image = cv2.imread("D:\\skhan\\research\\data\\face\\test.jpg",cv2.IMREAD_COLOR) image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) winSize = (64,64) blockSize = (16,16) blockStride = (8,8) cellSize = (8,8) nbins = 9 derivAperture = 1 winSigma = 4.0 histogramNormType = 0 L2HysThreshold = 2.0000000000000001e-01 gammaCorrection = 0 nlevels = 64 hog = cv2.HOGDescriptor(winSize,blockSize,blockStride,cellSize,nbins,derivAperture,winSigma,histogramNormType,L2HysThreshold,gammaCorrection,nlevels) winStride = (8,8) padding = (8,8) locations = ((10,20),) hist = hog.compute(image,winStride,padding,locations)
tagged with: python
has answer: http://stackoverflow.com/a/48192374

http://stackoverflow.com/comment/82359074
has text: I believe I clarified it again in my first edit, but thank you. This works for functions.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47699220
type: Comment

http://stackoverflow.com/comment/82388435
has text: Yeah, changed it to `all` already. It usually takes me some time to remember python builtins and I start out doing everything by hand. To the `gte` in favor of what I did, I think I prefer my way, but yours is as good. And shorter of course.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47714153
type: AnswerComment

http://stackoverflow.com/a/47723392
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47722733
accepted answer of: http://stackoverflow.com/q/47722733
type: Answer
has body: Assuming that you're decided to use cp rather than native Python operations -- This code will be much more reliable if you write it to not invoke any shell whatsoever. To avoid the need for /* on the source (and the side effects of this -- ie. refusal to copy directories whose names exceed the ARG_MAX combined environment and command-line size storage limit), use . as the last element of the name of the directory whose contents are to be copied, instead of passing a wildcard that needs to be expanded by a shell. subprocess.check_call(["cp", "-R", "--", '%s/.' % src, dest]) The use of cp -R rather than cp -rv is on account of -R, but not -r, being POSIX-standardized (and thus portable across all compliant UNIXlike platforms). Demonstrating In Action (copy/pasteable code) tempdir=$(mktemp -d -t testdir.XXXXXX) trap 'rm -rf "$tempdir"' EXIT cd "$tempdir" mkdir -p ./src/CopyPasteIntoBuildDir/subdir-1 ./build-root/src/ touch ./src/CopyPasteIntoBuildDir/file-1 touch ./src/CopyPasteIntoBuildDir/subdir-1/file-2 script=' import sys, shutil, subprocess src = sys.argv[1] dest = sys.argv[2] subprocess.check_call(["cp", "-R", "--", "%s/." % src, dest]) ' python -c "$script" ./src/CopyPasteIntoBuildDir ./build-root/src/ find ./build-root -type f -print rm -rf "$tempdir" ...emits output akin to: ./build-root/src/file-1 ./build-root/src/subdir-1/file-2 ...showing that content was correctly recursively copied with no prefix.
score: 1

http://stackoverflow.com/comment/82440568
type: Comment
type: QuestionComment
has text: @PatrickArtner Do you know if there is a way that I can scrap live stock prices? Perhaps from another source? thank you
comment on: http://stackoverflow.com/q/47740151
score: 0

http://stackoverflow.com/comment/82495243
type: AnswerComment
comment on: http://stackoverflow.com/a/47766604
has text: @Everett if you presented the output that you get, then everything should be fine. Probably you get error, and you should check for `r.status_code`, for not 2xx status response.
type: Comment
score: 0

http://stackoverflow.com/comment/82373212
comment on: http://stackoverflow.com/q/47706246
score: 0
type: Comment
type: QuestionComment
has text: @furas there is no error

http://stackoverflow.com/comment/82447215
type: Comment
has text: @Carcigenicate Yeah i noticed that too but according to the original poster of the code that is what is supposed to happen.
type: QuestionComment
comment on: http://stackoverflow.com/q/47742887
score: 0

http://stackoverflow.com/comment/82927412
type: Comment
has text: @DeepakKumar: Yes, there is an implementation difference. But it is not wrong. In Spark you are required to do the normalization yourself as stated in the answer. Does the numbers not match after you have done the mean normalization?
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47785727

http://stackoverflow.com/q/47795361
tagged with: datetime
has comment: http://stackoverflow.com/comment/82551775
tagged with: python
accepted answer: http://stackoverflow.com/a/47795529
type: AnsweredQuestion
answer count: 2
has answer: http://stackoverflow.com/a/47795529
tagged with: pandas
has title: how to convert a column of integer to standard hour time in python?
upvote count: 3
downvote count: 0
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/47795715
score: 3
has body: I have a data frame like this: BuyTime ID SellTime 94650 1 94651 94717 1 94817 120458 2 114119 the buy time and sell time type are integer but i want to convert them to standard time date. I already used quote['SellTime'] = pd.to_datetime(quote['SellTime'], unit = 's') but it gives a start year like 1970-01-01 to time which is not needed. my data should be like this: BuyTime Id SellTime 09:46:50 1 09:46:51 09:47:17 1 09:48:17 12:04:58 2 11:41:19 EDIT: also using this function regard to size of my data is not efficient: def format_time(value): t2 = str(value) if len(t2) == 5: return "0%s:%s:%s" % (t2[0], t2[1:3], t2[3:5]) return "%s:%s:%s" % (t2[0:2], t2[2:4], t2[4:6])
has answer: http://stackoverflow.com/a/47795715

http://stackoverflow.com/comment/82609277
has text: But messages will only appear if you render a template with them in. And you're not, because once again **you're always redirecting**.
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47817209

http://stackoverflow.com/q/47842930
tagged with: mysql
has comment: http://stackoverflow.com/comment/82652829
has comment: http://stackoverflow.com/comment/82656488
favorite count: 0
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82651244
has body: I wanna plot a graph for data present in the database of temperature and dates. the data dates is of string type. I tried to convert the string type into matplot date using date2num() function. But, while at the time of plotting graphs I observed that the dates are being shown in the form of time. Why this is being happened and what should I do to make dates of format(YYYY-MM-DD) on X-axis? import MySQLdb import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import matplotlib.dates as mdates from dateutil import parser from matplotlib import style import datetime def graph_data(): con =MySQLdb.connect("***.***.*.**","monitor", "password","temp") cursor=con.cursor() style.use('fivethirtyeight') cursor.execute('select tdate,ttime,temperature from temptb') rows=cursor.fetchall() timenow=[] temperature=[] for eachRow in rows: temperature.append(eachRow[2]) timenow.append(eachRow[0]) #dates=[mdates.date2num(t) for t in timenow] fig=plt.figure() ax1=fig.add_subplot(111) ax1.set_title("Temperature Analysis") ax1.set_ylabel("Temperature") ax1.set_xlabel("Time") #ax1.plot_date(dates, temperature, '-', label="tempurature", color='r') ax1.plot_date(timenow, temperature, '-', label="tempurature", color='r') fig.autofmt_xdate(rotation=60) fig.tight_layout() ax1.grid(True) ax1.legend(loc='best', framealpha=0.5) plt.savefig("figure.png") graph_data() The data fetched from database: 2017-12-14 16 2017-12-14 17 2017-12-13 18 2017-12-14 18 2017-12-14 21 2017-12-13 22 2017-12-14 23 2017-12-13 25 2017-12-14 26 output: edit 1: There is no change in output though using timenow in the place of date in ax1.plot_date(dates, temperature, '-', label="tempurature", color='r')
has answer: http://stackoverflow.com/a/47843042
upvote count: 1
tagged with: python
tagged with: date
tagged with: matplotlib.mlab
has title: How to converting string dates(YYYY-MM-DD) from SQL database to matplotlib dates in python?
score: 1
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/82656473
downvote count: 0
answer count: 1

http://stackoverflow.com/comment/82548512
type: Comment
type: QuestionComment
has text: [`Here`](http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.GridSearchCV.html) it is. Have a look and then be more specific.
comment on: http://stackoverflow.com/q/47793569
score: 0

http://stackoverflow.com/a/47822096
answers question: http://stackoverflow.com/q/47821864
type: Answer
has body: You have to somehow pass the user object in: class NoteQuerySet(models.query.QuerySet): def authenticated(self, user): return self.filter(user=user) I think it's much clearer if you just directly use filter: Note.objects.filter(user=self.request.user).search(query)
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47821864
has comment: http://stackoverflow.com/comment/82613916

http://stackoverflow.com/a/47782533
downvote count: 0
answers question: http://stackoverflow.com/q/47782361
type: Answer
has body: last_valid_index + agg('last') A=data.iloc[:,2:].apply(lambda x : x.last_valid_index(),1) B=data.groupby(['value'] * data.shape[1], 1).agg('last') data['date']=A data['obs']=B data Out[1326]: field1 field2 2014 2015 2016 2017 date obs 0 a 0.0 1.0 2.0 3.0 4.0 2017 4.0 1 b 5.0 6.0 7.0 NaN NaN 2015 7.0 2 c 10.0 11.0 12.0 NaN NaN 2015 12.0 3 d 15.0 16.0 17.0 NaN NaN 2015 17.0 4 e 20.0 21.0 NaN NaN NaN 2014 21.0 5 f 25.0 26.0 27.0 28.0 29.0 2017 29.0 6 g 30.0 31.0 32.0 33.0 34.0 2017 34.0 By using assign we can push them into one line as blow data.assign(date=data.iloc[:,2:].apply(lambda x : x.last_valid_index(),1),obs=data.groupby(['value'] * data.shape[1], 1).agg('last')) Out[1340]: field1 field2 2014 2015 2016 2017 date obs 0 a 0.0 1.0 2.0 3.0 4.0 2017 4.0 1 b 5.0 6.0 7.0 NaN NaN 2015 7.0 2 c 10.0 11.0 12.0 NaN NaN 2015 12.0 3 d 15.0 16.0 17.0 NaN NaN 2015 17.0 4 e 20.0 21.0 NaN NaN NaN 2014 21.0 5 f 25.0 26.0 27.0 28.0 29.0 2017 29.0 6 g 30.0 31.0 32.0 33.0 34.0 2017 34.0
upvote count: 2
score: 2

http://stackoverflow.com/comment/82558677
comment on: http://stackoverflow.com/a/47798652
type: AnswerComment
score: 5
has text: These pandas func names sounds like some pyscho movie actions - explode, melt, cut ;)
type: Comment

http://stackoverflow.com/comment/82398561
has text: using eval is almost always the wrong solution. Here the problem can certainly be solved using lambdas instead
type: AnswerComment
comment on: http://stackoverflow.com/a/47710198
score: 0
type: Comment

http://stackoverflow.com/comment/82542468
score: 0
type: Comment
type: QuestionComment
has text: yes because it's one purchase.
comment on: http://stackoverflow.com/q/47790564

http://stackoverflow.com/comment/82611179
comment on: http://stackoverflow.com/q/47824080
score: 0
has text: Yes James and others have been able to run your 3 lines of code locally just fine.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82422762
has text: Oh, I forgot that the `interpolation` default is different in older matplotlib versions. Sure, that makes sense.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47718341

http://stackoverflow.com/a/47789475
answers question: http://stackoverflow.com/q/47778527
downvote count: 0
score: 1
upvote count: 1
has body: Potentially this has nothing to do with kivy. As can be seen the axes limits are small and outside the range where the data resides. It makes sense to update the limits once data is changed. The easiest way would be to use self.ax.autoscale() inside the updating function.
type: Answer

http://stackoverflow.com/q/47827943
tagged with: validation
upvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/47828526
downvote count: 1
favorite count: 0
has body: I have file that contains set data of temperatures, of 12 months: and I have this code: if n &lt;= 0: #validate the size raise ValueError("Invalid data set size value.") for i in range(n): line = infile.readline() #read a data set if line != "": raise RuntimeError("more data sets than expected") #check if there is more lines than expected when I run the program the output is Error:more data sets than expected
has title: More data than expected
type: Question
has comment: http://stackoverflow.com/comment/82618322
tagged with: exception
has comment: http://stackoverflow.com/comment/82618153
has comment: http://stackoverflow.com/comment/82618835
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/47828526
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82618756
has comment: http://stackoverflow.com/comment/82618174
has comment: http://stackoverflow.com/comment/82618130
has comment: http://stackoverflow.com/comment/82618716

http://stackoverflow.com/q/47838324
answer count: 4
has comment: http://stackoverflow.com/comment/82640450
type: AnsweredQuestion
score: 0
has body: I want add a variable to some of the items in mylist = ['A', 'B', 'C', 'D', 'E']. I tried something like this example... for direction in ['Up', 'Down']: mylist = ['A{}', 'B', 'C{}', 'D', 'E'].format(direction) for x in mylist: print x I want the output to be the following... AUp B CUp D E ADown B CDown D E However, this isn't working. Is there a best way to add a variable in a list?
tagged with: list
has answer: http://stackoverflow.com/a/47842678
has comment: http://stackoverflow.com/comment/82640401
has title: Add a variable into a list with Python
has comment: http://stackoverflow.com/comment/82640410
upvote count: 1
has answer: http://stackoverflow.com/a/47838569
downvote count: 1
possible better answer: http://stackoverflow.com/a/47838397
favorite count: 0
type: Question
tagged with: format
has answer: http://stackoverflow.com/a/47838397
accepted answer: http://stackoverflow.com/a/47838472
tagged with: python
has answer: http://stackoverflow.com/a/47838472

http://stackoverflow.com/comment/82486876
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47762695
has text: use `mystirng = '{"1" : "a", "2" : "b", "3" : "c", "4" : "d"}'` and it will work as expected. If you start a string with `"` the next `"` will end the string, this is why your `mystring` is not valid. **Voting to close this as it is a simple type-o**.
type: QuestionComment

http://stackoverflow.com/q/47780897
has body: This import datetime datetime.datetime.fromtimestamp(1501545600).isoformat() should output 2017-08-01T00:00:00Z or 2017-08-01T00:00:00 but I get 2017-08-01T02:00:00 instead, probably because of local timezone. How to make .isoformat() output an UTC time instead, i.e. 2017-08-01T00:00:00? If possible I'd like to use only datetime, and no other third party library like arrow or dateutils.
downvote count: 0
has answer: http://stackoverflow.com/a/47780939
accepted answer: http://stackoverflow.com/a/47780939
has title: Timestamp to UTC ISO 8601 date
favorite count: 0
type: Question
answer count: 2
tagged with: utc
tagged with: datetime
tagged with: iso8601
tagged with: python
tagged with: date
has answer: http://stackoverflow.com/a/47780950
possible better answer: http://stackoverflow.com/a/47780950
score: 2
upvote count: 2
type: AnsweredQuestion

http://stackoverflow.com/comment/82441613
type: QuestionComment
comment on: http://stackoverflow.com/q/47740206
score: 0
has text: As jacub said going with GPU is a good option, but another good factor is the language that you're using, I should suggest you use C or C++ as they are somewhat faster languages, but on the other hand, it'll take you more effort to do it with those as it's not as easy as writing `from PIL import *` as it is in python.
type: Comment

http://stackoverflow.com/comment/82677004
type: Comment
comment on: http://stackoverflow.com/q/47844773
type: QuestionComment
has text: In python, the standard module language for odoo
score: 0

templates
tags question: http://stackoverflow.com/q/47716841
tag name: templates
tags question: http://stackoverflow.com/q/47704643
tags question: http://stackoverflow.com/q/47714772
type: Tag

timer
tag name: timer
tags question: http://stackoverflow.com/q/47756075
type: Tag
tags question: http://stackoverflow.com/q/47833369

http://stackoverflow.com/q/47741873
has answer: http://stackoverflow.com/a/56637437
has comment: http://stackoverflow.com/comment/82458087
has title: Unable to install Numpy on AWS EC2 Python 3.6
favorite count: 0
type: Question
tagged with: numpy
downvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82446779
tagged with: amazon-ec2
has answer: http://stackoverflow.com/a/47741956
has body: I have an Amazon EC2 instance running Amazon Linux and a virtual environment with python 3.6. I can't seem to install Numpy : (testenv) [ec2-user@ip-xxx-xx-xx-xx venv]$ pip3 install numpy Collecting numpy Using cached numpy-1.13.3-cp36-cp36m-manylinux1_x86_64.whl Installing collected packages: numpy Successfully installed numpy-1.13.3 (testenv) [ec2-user@ip-xxx-xx-xx-xx venv]$ python Python 3.6.2 (default, Nov 2 2017, 19:34:31) [GCC 4.8.5 20150623 (Red Hat 4.8.5-11)] on linux Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import numpy Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ModuleNotFoundError: No module named 'numpy' I also did a sudo python36 -m pip install numpy it did not work.
tagged with: python
answer count: 3
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/47742362

http://stackoverflow.com/q/47837548
tagged with: python
tagged with: dictionary
linked to: http://stackoverflow.com/q/23233617
tagged with: python-2.7
duplicate of: http://stackoverflow.com/q/1373164
linked to: http://stackoverflow.com/q/16099557
answer count: 0
score: 0
has comment: http://stackoverflow.com/comment/82638941
has comment: http://stackoverflow.com/comment/82639653
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
has title: Python how to split a dict with nested values given presence of specific values
tagged with: split
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/1373164
has comment: http://stackoverflow.com/comment/82638919
has body: I am using Python 2.7 and trying to split a dict containing nested values into multiple dicts containing specific values. My initial dict is as follows: d = {'V1': [['10', 'AND', '2'], 'OR', ['5', 'AND', '1']], 'V2': ['4', 'OR', '1'], 'V3': ['4', 'AND', '4'], 'V4': ['100']} I am trying to get: d1 = {'V1': [['10', 'AND', '2'], 'OR', ['5', 'AND', '1']]} #nested key:values containing OR, AND operators d2 = {'V2': ['4', 'OR', '1']} #key:values containing only OR operator d3 = {'V3': ['4', 'AND', '4']} #key:values containing only AND operator d4 = {'V4': ['100']} #key:values containing no linking OR, AND operators I have tried list comprehension but get stuck with separating the nested values containing both AND, OR operators. For example: OR_dict = {k:v for k, v in d.items() if 'OR' in v} # {'V1': [['10', 'AND', '2'], 'OR', ['5', 'AND', '1']], 'V2': ['4', 'OR', '1']} For separating key:values containing only AND operator I have tried the following and have had some success: AND_dict = {k:v for k, v in d.items() for i in v if i=='AND'} # {'V3': [['4', 'AND', '4']} I have looked at related questions: python split dict by value and python split dict by key but haven't been able to solve my problem. Any help would be appreciated.

http://stackoverflow.com/q/47706487
upvote count: 1
accepted answer: http://stackoverflow.com/a/47712053
downvote count: 1
tagged with: scipy
has comment: http://stackoverflow.com/comment/82373293
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47712053
has comment: http://stackoverflow.com/comment/82373242
tagged with: curve-fitting
tagged with: python
type: AnsweredQuestion
score: 0
has body: I am trying to curve fit my data with scipy.optimize.curve_fit. For some reason it doesn't like my equation. If I plot the equation using plausible numbers it looks right. So I trust my equation. If I try to fit to a simpler equation, it works, so I trust my code in general. Any advice as to why it doesn't work? The specific error return is "Residuals are not finite in the initial point." Changing p0 to anything reasonable is also unhelpful import matplotlib.pyplot as plt from scipy.optimize import curve_fit import numpy as np Y=np.array([0.00001,1.421828697,2.553970883,3.340262844,3.931459808, 4.640896164,5.084293887,5.379892368,5.557251457,5.705050698, 5.823290091,5.911969636,5.971089332,6.059768876,6.118888573,6.178008269, 6.266687814]) X=np.array([0,2500,5000,7500,10000,15000,20000,25000, 30000,35000,40000,45000,50000,55000,60000,65000,70000]) plt.plot(X,Y,'g^') def func(X,J,g): u=6.720*10**-5 k=1.380*(10**-16) T=2 N=1 x=g*J*u*(X)/(k*T) return N*g*J*(((2*J+1)/(2*J))*(1/(np.tanh((2*J+1)*x/(2*J))))-(1/(2*J))* (1/(np.tanh(x/(2*J))))) plt.figure(1) popt, pcov = curve_fit(func, X,Y,p0=[3.5,2],bounds=([0.25,0.001],[10,4])) plt.plot(X, func(X, *popt), 'r--', label='fit-with-bounds') print(" J is %s " %(popt[0]),"\n","g is %s" %(popt[1]))
has title: Curve fit in python using scipy.optimize.curve_fit
answer count: 1

http://stackoverflow.com/comment/82525488
type: QuestionComment
comment on: http://stackoverflow.com/q/47781859
has text: @MauroBaraldi agreed but `/etc/hosts` does not handle port forwarding
score: 0
type: Comment

http://stackoverflow.com/comment/82675057
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47851245
score: 0
has text: Ok thanks. I presume then you have no idea what's wrong?

http://stackoverflow.com/comment/82408664
comment on: http://stackoverflow.com/q/47723967
score: 1
type: Comment
type: QuestionComment
has text: what about `e.message`

http://stackoverflow.com/q/47821602
tagged with: python
has title: Where to find jwt_key_id for box python SDK
tagged with: box
score: 5
has body: I am not able to find jwt_key_id. Can anybody guide me to the right direction ? auth = JWTAuth( client_id='got it from app configuration page', client_secret='got it from app configuration page', enterprise_id='got it from app configuration page', jwt_key_id='????', rsa_private_key_file_sys_path='got it from app configuration page', rsa_private_key_passphrase="got it from app configuration page" #store_tokens=your_store_tokens_callback_method, ) Thank you.
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/48396456
favorite count: 0
type: Question
tagged with: sdk
type: UnansweredQuestion
upvote count: 5

http://stackoverflow.com/q/47824131
tagged with: anaconda
answer count: 3
has comment: http://stackoverflow.com/comment/83876831
downvote count: 0
linked to: http://stackoverflow.com/q/28831854
tagged with: jupyter
has body: I've spent a few days now trying to make Spark work with my Jupyter Notebook and Anaconda. Here's what my .bash_profile looks like: PATH="/my/path/to/anaconda3/bin:$PATH" export JAVA_HOME="/my/path/to/jdk" export PYTHON_PATH="/my/path/to/anaconda3/bin/python" export PYSPARK_PYTHON="/my/path/to/anaconda3/bin/python" export PATH=$PATH:/my/path/to/spark-2.1.0-bin-hadoop2.7/bin export PYSPARK_DRIVER_PYTHON=jupyter export PYSPARK_DRIVER_PYTHON_OPTS="notebook" pyspark export SPARK_HOME=/my/path/to/spark-2.1.0-bin-hadoop2.7 alias pyspark="pyspark --conf spark.local.dir=/home/puifais --num-executors 30 --driver-memory 128g --executor-memory 6g --packages com.databricks:spark-csv_2.11:1.5.0" When I type /my/path/to/spark-2.1.0-bin-hadoop2.7/bin/spark-shell, I can launch Spark just fine in my command line shell. And the output sc is not empty. It seems to work fine. When I type pyspark, it launches my Jupyter Notebook fine. When I create a new Python3 notebook, this error appears: [IPKernelApp] WARNING | Unknown error in handling PYTHONSTARTUP file /my/path/to/spark-2.1.0-bin-hadoop2.7/python/pyspark/shell.py: And sc in my Jupyter Notebook is empty. Can anyone help solve this situation? Just want to clarify: There is nothing after the colon at the end of the error. I also tried to create my own start-up file using this post and I quote here so you don't have to go look there: I created a short initialization script init_spark.py as follows: from pyspark import SparkConf, SparkContext conf = SparkConf().setMaster("yarn-client") sc = SparkContext(conf = conf) and placed it in the ~/.ipython/profile_default/startup/ directory When I did this, the error then became: [IPKernelApp] WARNING | Unknown error in handling PYTHONSTARTUP file /my/path/to/spark-2.1.0-bin-hadoop2.7/python/pyspark/shell.py: [IPKernelApp] WARNING | Unknown error in handling startup files:
linked to: http://stackoverflow.com/q/46772280
tagged with: jupyter-notebook
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47873725
upvote count: 15
has comment: http://stackoverflow.com/comment/82611375
has title: Configuring Spark to work with Jupyter Notebook and Anaconda
has answer: http://stackoverflow.com/a/55134593
linked to: http://stackoverflow.com/q/43500744
possible better answer: http://stackoverflow.com/a/47870277
tagged with: pyspark
tagged with: python
linked to: http://stackoverflow.com/q/33908156
has answer: http://stackoverflow.com/a/47870277
has comment: http://stackoverflow.com/comment/82612048
accepted answer: http://stackoverflow.com/a/47873725
score: 15
has comment: http://stackoverflow.com/comment/82637674
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82611192

http://stackoverflow.com/comment/82460201
has text: 'MESS_DATUM' is the date in the x-axis and 'sum_meal' should be the value for the y-axis
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47748989
type: QuestionComment

http://stackoverflow.com/a/60731288
has body: In the geopy version 1.21.0 and using the import from geopy.geocoders import Nominatim I couldn't use the location.raw["address"]. An example of location.raw is as follows: {'place_id': 3330757, 'licence': 'Data © OpenStreetMap contributors, ODbL 1.0. https://osm.org/copyright', 'osm_type': 'node', 'osm_id': 368381231, 'boundingbox': ['39.6634459', '39.6934459', '-75.6213155', '-75.5913155'], 'lat': '39.6784459', 'lon': '-75.6063155', 'display_name': 'New Castle County Airport, South Hollow Road, Manor Park, New Castle County, Delaware, 19721, United States of America', 'class': 'aeroway', 'type': 'aerodrome', 'importance': 0.6780150946188139, 'icon': 'https://nominatim.openstreetmap.org/images/mapicons/transport_airport2.p.20.png'} Instead I used location.address.split(",")[-2] which worked for me.
score: 2
upvote count: 2
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/47824915

http://stackoverflow.com/comment/82377058
score: 0
type: Comment
has text: You could check [\[SO\]: Print all xml child node using python](https://stackoverflow.com/questions/42699430/print-all-xml-child-node-using-python/42701630#42701630). You need to know the structure of the _xml_ in order to extract relevant data. So which node text would you like to have extracted?
type: QuestionComment
comment on: http://stackoverflow.com/q/47708233

http://stackoverflow.com/comment/82538419
has text: Make the ajax request type a `GET` since you're not mutating the resource
type: Comment
comment on: http://stackoverflow.com/q/47786139
type: QuestionComment
score: 0

http://stackoverflow.com/comment/82602911
comment on: http://stackoverflow.com/q/47820259
type: Comment
type: QuestionComment
has text: `[x['total']==y['total'] for x,y in zip(list_1,list_2)]` but that completely drops the other keys. If they're the same for both list that'll work, but your data is strange.
score: 0

http://stackoverflow.com/comment/82563299
type: Comment
has text: what is the aim/purpose with the renaming? How do you want that to work?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47800913

http://stackoverflow.com/comment/82432472
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47736016
has text: I can't get your code to work. When I run it I get "TypeError: '>' not supported between instances of 'str' and 'int' ". Like I said, I get get Pandas to believe that that's an na.
score: 0

http://stackoverflow.com/comment/82393100
type: AnswerComment
comment on: http://stackoverflow.com/a/47716315
type: Comment
has text: `print(r.url)` will print the url, not the repose from that url. Try `print(r.text)`. Also, just for giggles, include the protocol in the url: `r = requests.get('http://example.com')` (I'm not sure if it is mandatory; but I'n finicky).
score: 0

http://stackoverflow.com/comment/82540897
type: QuestionComment
comment on: http://stackoverflow.com/q/47775652
score: 0
has text: I am only interested in the combination of the X_arrays (the projection of the data from the original X matrix on the joint latent space for both CCA and PLSCA), then their combination with the kernelPCA projection of the X_matrix. I do not need the Y projections on the joint space.
type: Comment

http://stackoverflow.com/a/47851713
score: 0
answers question: http://stackoverflow.com/q/47850817
has comment: http://stackoverflow.com/comment/82686637
has comment: http://stackoverflow.com/comment/82686599
has body: I have rewritten the code to replace current window, but i am not sure if that is what you ask for. pls try it out, it does replace the window for each function call, but still retain one root window. #%% from tkinter import * def adminLogin(): global AnameEL global ApwordEL # More globals :D global ArootA AnameL = Label(f2, text='Username: ') # More labels ApwordL = Label(f2, text='Password: ') # ^ AnameL.grid(row=1, sticky=W) ApwordL.grid(row=2, sticky=W) AnameEL = Entry(f2) # The entry input ApwordEL = Entry(f2, show='*') AnameEL.grid(row=1, column=1) ApwordEL.grid(row=2, column=1) AloginB = Button(f2, text='Login', command=CheckAdmin) # This makes the login button, which will go to the CheckLogin def. AloginB.grid(columnspan=2, sticky=W) def CheckAdmin(): if AnameEL.get() == "test" and ApwordEL.get() == "123" : # Checks to see if you entered the correct data. f2.destroy() #r = Tk() # Opens new window loginL = Label(f3, text = 'Success!!!') loginC = Button(f3, text='Add new login', command=Signup) loginL.grid(row = 2, column=0, sticky=W) loginC.grid(columnspan=2, sticky=E) #r.mainloop() else: f2.destroy() #r = Tk() # Opens new window loginL2 = Label(f3, text = 'Error!!') ribl = Label(f3, text='\n[!] Invalid Login') loginL2.grid(row = 2, column=0, sticky=W) ribl.grid(row = 3, column=0, sticky=W) #.mainloop() def Signup(): # This is the signup definition, global pwordE # These globals just make the variables global to the entire script, meaning any definition can use them global nameE global roots f3.destroy() #r = Tk() # Opens new window loginL3 = Label(f4, text = 'Signup!!!') # This renames the title of said window to 'signup' loginL3.grid(row = 0, column=50, sticky=W) intruction = Label(f4, text='Please Enter new Credidentials\n') # This puts a label, so just a piece of text saying 'please enter blah' intruction.grid(row=2, column=0, sticky=E) # This just puts it in the window, on row 0, col 0. If you want to learn more look up a tkinter tutorial :) nameL = Labe…
has comment: http://stackoverflow.com/comment/82672630
type: Answer

http://stackoverflow.com/q/47758409
score: 1
tagged with: email
tagged with: python
tagged with: forms
has answer: http://stackoverflow.com/a/47758619
has body: I made a website and whenever someone sends a form (e.g. inquire about my work) I get an email so I'm trying to automate this I have got as far as to download relevant emails and cut out irrelevant data but I'm stuck on how to import the .txt file and export it into a spreadsheet (.csv file) this is the .txt file I'm trying to extract the data from: ` Name: someone Email: someone@gmail.com Site: someone.com Remote IP: 192.168.0.1 ----------------------------------------------------------------------- Name: someone51 Email: someone1@gmail.com Site: someone1.com Remote IP: 192.168.0.2 ----------------------------------------------------------------------- Name: someone Email: someone52@gmail.com Site: someone.com Remote IP: 192.168.0.5 ----------------------------------------------------------------------- Name: someone51 Email: someone52532222@gmail.com Site: someone1.com Remote IP: 192.168.0.76 ----------------------------------------------------------------------- Name: someone123 Email: someone123@gmail.com Site: someone.com Remote IP: 192.168.0.21 ----------------------------------------------------------------------- Name: someone51 Email: someone1@gmail.com Site: someone1.com Remote IP: 192.168.0.2 ----------------------------------------------------------------------- ` obviously, I had to change the exact data but this is the layout I have got it too. So I am asking about how I can change this .txt file and put it systematically into a spreadsheet Thank you in advance
has comment: http://stackoverflow.com/comment/82478171
type: UnansweredQuestion
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/82478075
upvote count: 1
has title: how to read a text file in python and output variables into a csv
favorite count: 0
type: Question
tagged with: http://stackoverflow.com/tag/csv

http://stackoverflow.com/comment/82356523
type: QuestionComment
type: Comment
has text: What's the error/problem? What _Python_ version are you using? `encode`/`decode` are inverse counterparts meaning that each does the exact opposite of the other (`s == decode(encode(s))`). So, in order to have the same result at both ends, you should call each function in one of the ends. I'm not sure what the _PS_ code does (encodes/decodes), but I feel (might be wrong) that on _Python_ side you should decode.
score: 0
comment on: http://stackoverflow.com/q/47698003

http://stackoverflow.com/a/47740661
answers question: http://stackoverflow.com/q/47740456
score: 0
has body: this code solves the problem. import csv with open('name.csv', 'r') as f: reader = csv.reader(f) my_list = list(reader) print(my_list) def remove_cruft(s): return s[:-1] new_list=[remove_cruft(s) for s in my_list[0]] print(new_list) output :- 'robić', 'marudzić', 'biegać' ['robi', 'marudzi', 'biega'] Actually , the output your code produces is :- 'robić', 'marudzić', 'biegać' 'robić', 'marudzić' you need pass strings to remove_cruft() , which can be done by traversing my_list[0]
type: Answer

http://stackoverflow.com/a/47813550
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/82590085
upvote count: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47807463
answers question: http://stackoverflow.com/q/47807463
has body: OK, here is what people in the comments are trying to tell you: X_test is not a single datapoint, but the whole of your test set. How many samples does it include? X_test.shape # (360, 64) So, it includes 360 samples; hence, your pred variable must also contain predictions for all these 360 samples. Indeed: pred.shape # (360,) You want to check the prediction for your first sample in X_test? pred[0] # 8 And what is the ground truth for this prediction? y_test[0] # 8 It seems you got a correct prediction for your first test sample indeed. You want to plot this sample (X_test[0])? You should first reshape it back into (8,8), since the train_test_split load_digits() function flattens the original 8x8 images to 1D arrays of length 64: plt.imshow(X_test[0].reshape(8,8), cmap=plt.cm.gray_r, interpolation='nearest') plt.show() Well, it looks like an 8 (kind of)...

http://stackoverflow.com/a/47711458
answers question: http://stackoverflow.com/q/47711111
upvote count: 5
type: Answer
has comment: http://stackoverflow.com/comment/82386337
has body: In this statement: nm1 = re.search(nmx,line, re.M) you get an NoneType object (nm1 = None), because no matches were found. So make more investigation on the nmx attribute, why you get no matches in the regex. By the way if it´s possible to get a NoneType object, you can avoid this by preventing a NoneType: If nm1 is not None: out.write(str(nm1.group("ename")).rstrip('\r\n')) else: #handle your NoneType case
downvote count: 0
has comment: http://stackoverflow.com/comment/82387624
has comment: http://stackoverflow.com/comment/82383617
score: 5

http://stackoverflow.com/comment/82479516
has text: Ok now you added my solution +1 :)
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47759047

http://stackoverflow.com/comment/82632569
has text: **use `netifaces` module** life is short ! @frankopt
comment on: http://stackoverflow.com/q/47833705
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82594793
comment on: http://stackoverflow.com/a/47816581
type: Comment
score: 0
type: AnswerComment
has text: You came just in time. I literally was in the process of fixing my code. I'll take your advice in bug fixing! Thank you!

http://stackoverflow.com/q/47776914
type: UnansweredQuestion
tagged with: python
tagged with: kivy
has answer: http://stackoverflow.com/a/47777181
has title: How do I change settings of a custom widget in kivy?
has body: I have this code where I want a button to trigger a change in a custom button. My solution only changes the color of all the custom buttons when they have been pressed. What would be the proper way to change the buttons? python class B_SettingScreen(Screen): def change_color(self): Factory.MainButton.background_normal = "z_MainButtonColorRed.jpg" kivy &lt;MainButton@Button&gt;: font_size: 18 markup: True size_hint: 0.25,0.06 color: 0,0,0,1 background_normal: "z_MainButtonColor.jpg" &lt;B_SettingScreen&gt;: MainButton: text: "[b][font=Arial]Change Color[/b][/font]" pos_hint: {"center_x":0.25, "y":0.5} on_release: root.change_color()
tagged with: kivy-language
score: 0
answer count: 1
type: Question

http://stackoverflow.com/q/47716746
favorite count: 0
type: Question
upvote count: 2
has body: I was trying to extract text from a receipt image uploaded as image1 and image2. After scaling and removing noise from the second image, the tesseract is able to extract text pretty well, whereas after applying the same transformations to the first image also there is no improvement in the text output. I tried binarization, blurr function, sharpening also in first image. Still there is no improvement. Is there any way to extract text from image1 ? I read about tesseract training, will that help in this scenario. If so how we can do that?
type: UnansweredQuestion
downvote count: 0
tagged with: python
tagged with: tesseract
tagged with: opencv
score: 2
answer count: 0
has title: tesseract 4.0, reading text from a reciept image

http://stackoverflow.com/a/50491370
upvote count: 6
has comment: http://stackoverflow.com/comment/93634133
has comment: http://stackoverflow.com/comment/88000695
has comment: http://stackoverflow.com/comment/93578139
has body: What you are looking for is called stratification. Luckily, sklearn has just that. Just change the line to itrain, itest, utrain, utest, rtrain, rtest = train_test_split( items, users, ratings, train_size=train_ratio, stratify=users) If stratify is not set, data is shuffled randomly. See http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html If [stratify is] not None, data is split in a stratified fashion, using this as the class labels. Update to the updated question: it seems that putting unique instances into the training set is not built into scikit-learn. You could abuse PredefinedSplit, or extend StratifiedShuffleSplit, but this might be more complicated than simply rolling your own.
downvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/88182159
has comment: http://stackoverflow.com/comment/93559510
has comment: http://stackoverflow.com/comment/87996182
has comment: http://stackoverflow.com/comment/88016800
answers question: http://stackoverflow.com/q/47700151
score: 5

http://stackoverflow.com/q/47834140
downvote count: 1
has title: NumPy equivalent of Matlab's magic()
favorite count: 0
score: 13
type: Question
has comment: http://stackoverflow.com/comment/82637474
possible better answer: http://stackoverflow.com/a/47838438
has comment: http://stackoverflow.com/comment/82637740
has comment: http://stackoverflow.com/comment/86765383
has answer: http://stackoverflow.com/a/50436702
has answer: http://stackoverflow.com/a/47838438
has comment: http://stackoverflow.com/comment/82631936
tagged with: python
has comment: http://stackoverflow.com/comment/82638727
has comment: http://stackoverflow.com/comment/82632920
has comment: http://stackoverflow.com/comment/86750758
tagged with: numpy
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82638967
upvote count: 14
answer count: 3
has comment: http://stackoverflow.com/comment/82631538
tagged with: matrix
accepted answer: http://stackoverflow.com/a/47840614
has body: In Ocatave / Matlab, I can use magic() to get a magic square, e.g., magic(4) 16 2 3 13 5 11 10 8 9 7 6 12 4 14 15 1 Definition: A magic square is an N×N grid of numbers in which the entries in each row, column and main diagonal sum to the same number (equal to N(N^2+1)/2). How can I generate the same using NumPy?
tagged with: magic-square
has comment: http://stackoverflow.com/comment/82638791
has answer: http://stackoverflow.com/a/47840614

http://stackoverflow.com/comment/82484288
type: Comment
score: 1
has text: functions inside `__init__` - what a mess.
type: QuestionComment
comment on: http://stackoverflow.com/q/47759657

home-automation
tag name: home-automation
tags question: http://stackoverflow.com/q/47776954
type: Tag

http://stackoverflow.com/comment/82651224
type: Comment
has text: @Solaxun it is obviously a DFS, just look once more at the algorithm, and add traces (for example trace x after when-let). It would also be nice, if you could add some desired input to your question, then it would be easier to reason about the validity of the solution ))
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47790682

http://stackoverflow.com/a/47765435
type: Answer
accepted answer of: http://stackoverflow.com/q/47765236
score: 2
downvote count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/82492230
answers question: http://stackoverflow.com/q/47765236
has body: You can use list.count to get the number of urls that occur three or more times: urls = ['www.hughes-family.org', 'www.bondedsender.com', 'thinkgeek.com', 'www.hughes-family.org', 'www.hughes-family.org', 'lists.sourceforge.net', 'www.hughes-family.org'] new_urls = [url for url in urls if urls.count(url) &gt; 1] if len(new_urls) &gt; 3: pass #condition met
type: AcceptedAnswer

http://stackoverflow.com/q/47737760
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/47737822
has title: How does collections.namedtuple work?
has answer: http://stackoverflow.com/a/47737822
type: Question
has body: I am studying the code of "namedtuple" in Python.(Python 3.6.3). I run the code : from collections import namedtuple,_iskeyword Point = namedtuple('Point', ['x', 'y'],rename=False,verbose=True) p = Point(2,3) print(p) and then the console print such as : from builtins import property as _property, tuple as _tuple from operator import itemgetter as _itemgetter from collections import OrderedDict class Point(tuple): 'Point(x, y)' __slots__ = () _fields = ('x', 'y') def __new__(_cls, x, y): 'Create new instance of Point(x, y)' return _tuple.__new__(_cls, (x, y)) @classmethod def _make(cls, iterable, new=tuple.__new__, len=len): 'Make a new Point object from a sequence or iterable' result = new(cls, iterable) if len(result) != 2: raise TypeError('Expected 2 arguments, got %d' % len(result)) return result def _replace(_self, **kwds): 'Return a new Point object replacing specified fields with new values' result = _self._make(map(kwds.pop, ('x', 'y'), _self)) if kwds: raise ValueError('Got unexpected field names: %r' % list(kwds)) return result def __repr__(self): 'Return a nicely formatted representation string' return self.__class__.__name__ + '(x=%r, y=%r)' % self def _asdict(self): 'Return a new OrderedDict which maps field names to their values.' return OrderedDict(zip(self._fields, self)) def __getnewargs__(self): 'Return self as a plain tuple. Used by copy and pickle.' return tuple(self) x = _property(_itemgetter(0), doc='Alias for field number 0') y = _property(_itemgetter(1), doc='Alias for field number 1') this is the class definition, I am confused with the class's definition: x = _property(_itemgetter(0), doc='Alias for field number 0') At here the property as _property, the fget function of property is _itemgetter(0). My question is: What the return of _itemgetter(0)? How does the _property work in this case?
answer count: 1
tagged with: python
tagged with: namedtuple

http://stackoverflow.com/q/47785950
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47786108
score: 0
has answer: http://stackoverflow.com/a/47786168
upvote count: 1
downvote count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/14426574
has title: Import all modules from a directory into an array
type: Question
answer count: 2
has body: Behold my directory structure exchange.py exchanges/ kraken.py gemini.py bitfinex.py Now in exchange.py I'd like to dynamically load all modules from the exchanges folder so that I can iterate over them and instantiate the classes within programmatically. Pseudocode: exchanges = load_modules('exchanges') for module in exchanges: config = module.CONFIG # a global for class in module: loaded_classes.append(module.class) # add each class in each module to a list Goal is to allow any contributor to create a class that inherits from exchange.py, put it into the exchanges folder and the app will automatically load it and its configuration. I've seen this answer which uses the os module to load all files in a directory but this seems unreasonably hacky to me.

http://stackoverflow.com/a/47809130
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47797170
has body: This command will print the Python version used by WLST : print (sys.version)
score: 5
upvote count: 5
has comment: http://stackoverflow.com/comment/82590319
has comment: http://stackoverflow.com/comment/82593907
type: Answer
accepted answer of: http://stackoverflow.com/q/47797170

http://stackoverflow.com/a/47852650
has comment: http://stackoverflow.com/comment/82680610
downvote count: 0
upvote count: 1
has body: That is not HTML, that is XML. You should find your namespaced elements instead of attempting to access via attribute. This will give you your value: items[i].find('image.title') A full example: for url in soup.find_all('url'): if 'Cassady' in url.find('image:title').text: print(url.find('image:loc').text)
has comment: http://stackoverflow.com/comment/82680533
score: 1
has comment: http://stackoverflow.com/comment/82680796
type: Answer
answers question: http://stackoverflow.com/q/47852596
has comment: http://stackoverflow.com/comment/82680551

http://stackoverflow.com/comment/82435309
score: 2
comment on: http://stackoverflow.com/q/47737470
type: Comment
type: QuestionComment
has text: Also, the example is somewhat broken because you're assigning a new dictionary to the `batman` variable, not changing the old dictionary, but that doesn't really change the outcome.

http://stackoverflow.com/comment/116255430
has text: I have a test case with a similar structure. When I implement your suggestion I get an error saying *fixture 'return code' not found*. Apparently, setting indirect=True requires all parameters inside @pytest.mark.parametrize() to be function fixtures. Do you have an idea how to make @pytest.mark.parametrize() accommodate both function fixtures and parameters?
comment on: http://stackoverflow.com/a/47726125
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/47801233
score: 0
has body: On PyCharm, next to the green "RUN" arrow press the box and then press edit configurations (see image) There you'll have Working Directory - that path is where PyCharm is running that script from (without errors). Try running it from the terminal within that path - that should solve your import errors.
answers question: http://stackoverflow.com/q/47800969
type: Answer

http://stackoverflow.com/comment/82580051
score: 0
type: Comment
has text: Yet, what should I make on stock.move.operation.link? What is the only field of type char?
type: AnswerComment
comment on: http://stackoverflow.com/a/47806950

http://stackoverflow.com/q/47847282
score: -2
tagged with: python
tagged with: dictionary
has body: I have below list of dictionaries: &gt;&gt;&gt; d={} &gt;&gt;&gt; d['primary info']={"name":"Mark","age":22,"Id":1234} &gt;&gt;&gt; d['secondary info']={"location":"Pune"} Now dictionary d has list as following: {'secondary info': {'location': 'Pune'}, 'primary info': {'age': 22, 'Id': 1234, 'name': 'Mark'}} How can I remove age key-value pair from primary info? How can I update value of Id in primary info?
has comment: http://stackoverflow.com/comment/82658687
answer count: 3
has title: Removing key value pair from list of dictionaries in python
downvote count: 3
upvote count: 1
has answer: http://stackoverflow.com/a/47847308
has answer: http://stackoverflow.com/a/47847358
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47847327
type: UnansweredQuestion

http://stackoverflow.com/a/47787770
type: Answer
accepted answer of: http://stackoverflow.com/q/47787413
answers question: http://stackoverflow.com/q/47787413
score: 0
type: AcceptedAnswer
has body: On pycharm go to File > Settings > project interpreter.. Under this add your env as an interpreter.

http://stackoverflow.com/comment/82636576
score: 0
has text: @Wen you can't ignore the fact that the full dataset likely has many different parameters recorded at multiple sites. Averaging e.g., PM2.5 with NOx is meaningless.
comment on: http://stackoverflow.com/q/47835573
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82455548
score: 0
has text: @Nishanth, follow method1 in my answer(django-pyodbc-azure). see the update in the answer.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47741601

http://stackoverflow.com/comment/82536173
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47787270
has text: Glad to help :)

http://stackoverflow.com/comment/82457066
has text: you need to save the team object inside the loop.Please check the edited answer.
type: Comment
comment on: http://stackoverflow.com/a/47748321
type: AnswerComment
score: 0

http://stackoverflow.com/comment/82423206
type: Comment
comment on: http://stackoverflow.com/q/47731064
type: QuestionComment
has text: I think the structure of the `item` dict is inapropriate. Using `QTreeWidgetItem` value as a key would be easier, so a dict like `item = {'Item12': {'ItemEnabled': True}}`. Also, this key can be stored using `Qt.UserRole` instead of `Qt.DisplayRole`
score: 0

http://stackoverflow.com/q/47702999
has comment: http://stackoverflow.com/comment/82366191
linked to: http://stackoverflow.com/q/10079216
favorite count: 0
type: AnsweredQuestion
score: -5
duplicate of: http://stackoverflow.com/q/10079216
has body: Imagine I have a list of balls objects as follows: balls = [container,ball1,ball2,ball3,ball4] I want to do a for loop that will go through ball1, ball2, ball3, ball4 but not the first item container. What is a method for doing it?
has answer: http://stackoverflow.com/a/47703040
tagged with: python
tagged with: loops
type: Question
tagged with: for-loop
accepted answer: http://stackoverflow.com/a/47703040
upvote count: 0
has title: How to do for loop through all items of a list except the first
answer count: 1
downvote count: 5

http://stackoverflow.com/comment/82480610
comment on: http://stackoverflow.com/q/47719291
type: QuestionComment
type: Comment
has text: Yes, you could. This should be significantly faster, but will probably get very messy. I believe it is also possible to inject javascript methods into the page, which might allow you to use JSON to transfer/serialize your form data.
score: 0

http://stackoverflow.com/comment/82488981
type: Comment
type: QuestionComment
has text: Yep, that's definitely a dict-literal... Does it go away when you put it all on one line?
score: 0
comment on: http://stackoverflow.com/q/47763792

http://stackoverflow.com/comment/82570439
has text: SVMs scale badly with many samples and non-linear kernels somewhat forbid alternatives (like SGDRegressor which can be used on huge data for a linear SVM). So no. Nothing you can do in general (although some values of C,nu might be trained faster; depends on your data if those are good or not). Drop kernels or look for another regressor.
score: 2
type: Comment
comment on: http://stackoverflow.com/q/47804326
type: QuestionComment

http://stackoverflow.com/a/47829583
type: Answer
has body: You also need to install the BigchainDB Python driver using pip install bigchaindb_driver. In your Python code, there should be no &gt; at the end of the line from bigchaindb_driver import BigchainDB&gt;, i.e. it should just be: from bigchaindb_driver import BigchainDB More info: BigchainDB Python Driver
answers question: http://stackoverflow.com/q/47818142
score: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/82664045
score: 0
comment on: http://stackoverflow.com/q/47849713
type: QuestionComment
has text: How does your python code output differ from the desired output?
type: Comment

http://stackoverflow.com/q/47747142
tagged with: python
tagged with: kdtree
has comment: http://stackoverflow.com/comment/82455538
upvote count: 2
tagged with: numpy
type: AnsweredQuestion
score: 2
downvote count: 0
has answer: http://stackoverflow.com/a/47755171
accepted answer: http://stackoverflow.com/a/47755171
answer count: 1
has title: vectorize loop for ckdtree search over two arrays
has comment: http://stackoverflow.com/comment/82465683
tagged with: vectorization
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82463531
has comment: http://stackoverflow.com/comment/82455575
has comment: http://stackoverflow.com/comment/82457599
has body: I have a csv file with latitude, longitude and elevation values at random places. I wanted to apply IDW interpolation to generate a regular grid. I used scipy.spatial.cKDTree for nearest neighbor search and find the elevation value at unknown points. The following code works fine when the output grid has dimensions (z &lt; 1000 X1000). If the dimensions increase the code runs really slow. Please help me vectorize the for loop with out removing using cKDTree. Thank you. ## Inverse distance weighted function def idw(p, dist, values): dist_pow = np.power(dist, 2) nominator = np.sum(values/dist_pow) denominator = np.sum(1/dist_pow) if denominator &gt; 0: return nominator/denominator else: return none ## Reading the lat/lon and elevation values from file lat = [] lon = [] ele = [] with open('VSKP_ground_dat.csv') as read: csvreader = csv.DictReader(read) for row in csvreader: lat.append(float(row['LAT'])) lon.append(float(row['LON'])) ele.append(float(row['ALT'])) xycoord = np.c_[lon,lat] ele_arr = np.array(ele) ## ------------- Creating KDTree point_tree = spatial.cKDTree(xycoord, leafsize=25) ## ------------- Creating empty grid matrix with np.zeros xmin, xmax, ymin, ymax = 81.903158, 83.352158, 17.25856, 18.40056 ## --------- Defining resolution xres, yres = 0.01, 0.01 x = np.arange(xmin, xmax, xres) y = np.arange(ymin, ymax, yres) z = np.zeros((x.shape[0], y.shape[0]), dtype=np.float16) for i, val1 in enumerate(x): for j, val2 in enumerate(y): p = np.array([val1, val2]) # points_idx = point_tree.query_ball_point(p, dist_2) distances, points_idx = point_tree.query(p, k=6, eps=0) ele_vals = ele_arr[points_idx] value = idw(p, distances, ele_vals) z[i,j] = value

http://stackoverflow.com/comment/82425765
type: QuestionComment
score: 0
has text: sorry i'll edit my question and post my code
comment on: http://stackoverflow.com/q/47732531
type: Comment

http://stackoverflow.com/comment/82496276
type: QuestionComment
has text: run HTTP in `thread`
comment on: http://stackoverflow.com/q/47767596
score: 0
type: Comment

http://stackoverflow.com/a/47777043
has comment: http://stackoverflow.com/comment/82516017
has comment: http://stackoverflow.com/comment/82515142
has comment: http://stackoverflow.com/comment/82538171
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/47776866
has comment: http://stackoverflow.com/comment/82537208
has comment: http://stackoverflow.com/comment/82515875
has comment: http://stackoverflow.com/comment/82515569
has comment: http://stackoverflow.com/comment/82515203
score: 1
has comment: http://stackoverflow.com/comment/82516055
answers question: http://stackoverflow.com/q/47776866
type: AcceptedAnswer
has body: Here's another alternative - df = pd.DataFrame(list(a.keys()), columns=list('mno')) df['p'] = list(a.values()) df m n o p 0 p l2 6 4 1 p l 6 2 2 p l 3 4 3 p l 5 4 4 p l1 2 5 5 p l1 5 4 6 p l 2 3 (Edit) Getting back a dict post groupby: if you want the result for just p, then call mean on p followed by to_dict - df.groupby(['m', 'n']).p.mean().to_dict() {('p', 'l'): 3.25, ('p', 'l1'): 4.5, ('p', 'l2'): 4.0}
has comment: http://stackoverflow.com/comment/82515169
has comment: http://stackoverflow.com/comment/82515625
upvote count: 1

http://stackoverflow.com/q/47803066
type: Question
tagged with: tflearn
tagged with: python
has title: LSTM/RNN Predicting cosine from sine
has body: I am trying to code a simple LSTM/RNN. Given a sine input, can I predict the cosine signal? While running my code, I can accurately predict next value of sine given historical sine values; but I am unable to accurately predict the next value of cosine given historical sine values. I heavily borrowed from this following code example, which is used to predict the next character from the alphabet. Since I am using a LSTM/RNN, I define windows (of length seq_length) of sequence input data corresponding to an output data point. For example, Input Sequence -&gt; Output Sequence [ 0. , 0.00314198, 0.00628393, 0.00942582, 0.01256761] -&gt; 1.0 In the above sample sequence, sin(0) is 0, and then we have the sine values for the next 4 points. These values have an associated cos(0). Corresponding code, import numpy as np from keras.models import Sequential from keras.layers import Dense from keras.layers import LSTM time_points = np.linspace(0, 8*np.pi, 8000) seq_length = 5 dataX = [] dataY = [] for i in range(0, len(time_points) - seq_length, 1): seq_in = np.sin(time_points)[i:i + seq_length] seq_out = np.cos(time_points)[i] dataX.append([seq_in]) dataY.append(seq_out) X = np.reshape(dataX, (len(dataX), seq_length, 1)) #numpy as np y = np.reshape(dataY, (len(dataY), 1)) LSTM Keras code model = Sequential() model.add(LSTM(16, input_shape=(X.shape[1], X.shape[2]))) model.add(Dense(y.shape[1], activation='linear')) model.compile(loss='mean_squared_error', optimizer='adam') model.fit(X[:6000], y[:6000], epochs=20, batch_size=10, verbose=2, validation_split=0.3) The following figure shows the prediction and the ground truth, when we try to learn cosine from sequential sine data. However, if we were to learn sine using sequential sine data (i.e. have seq_out = np.sin(time_points)[i]), the prediction is accurate as shown below. I was wondering what could be going wrong. Or, how can I get a more accurate prediction?
tagged with: lstm
type: AnsweredQuestion
downvote count: 0
upvote count: 1
score: 1
has answer: http://stackoverflow.com/a/47816831
answer count: 1
accepted answer: http://stackoverflow.com/a/47816831
tagged with: keras
tagged with: tensorflow
favorite count: 0

http://stackoverflow.com/comment/82668488
type: QuestionComment
comment on: http://stackoverflow.com/q/47851895
has text: Is it possible for the interpreter to context switch after the if statement but before visited[node]=True? That would allow another thread to enter the if statement.
score: 0
type: Comment

http://stackoverflow.com/comment/82670405
comment on: http://stackoverflow.com/q/47852944
type: Comment
score: 2
has text: Your question has nothing to do with `pascal` the programming language, so I removed that tag. Please read the tag description before adding.
type: QuestionComment

http://stackoverflow.com/a/47853625
upvote count: 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47853489
type: Answer
score: 2
downvote count: 0
has body: will work if you specify a time unit parameter as dtype='datetime64[s]' on your array creation. here is the working code: trade_type = np.dtype( [ ('id', 'U'), ('timestamp', 'u8'), ('datetime', np.dtype('datetime64[s]')) ] ) array = np.zeros(shape=1, dtype=trade_type) array['datetime'] = np.datetime64('1970-01-01 00:00:00') output: hope i did understand right. reference: Datetimes and Timedeltas
answers question: http://stackoverflow.com/q/47853489

http://stackoverflow.com/comment/131312901
score: 0
has text: I used encoding="utf-8" and errors='ignore' to read sql files generated by ssms
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47722635

http://stackoverflow.com/q/47754210
has comment: http://stackoverflow.com/comment/82469602
linked to: http://stackoverflow.com/q/47699473
tagged with: algorithm
has title: Algorithm for generation of number matrix with specified boundaries
tagged with: python
has answer: http://stackoverflow.com/a/47755357
upvote count: 4
score: 4
accepted answer: http://stackoverflow.com/a/47801339
has comment: http://stackoverflow.com/comment/82469798
has comment: http://stackoverflow.com/comment/82471801
tagged with: optimization
has comment: http://stackoverflow.com/comment/82471175
tagged with: numpy
answer count: 2
has comment: http://stackoverflow.com/comment/82470715
downvote count: 0
has comment: http://stackoverflow.com/comment/82469409
has comment: http://stackoverflow.com/comment/82471950
possible better answer: http://stackoverflow.com/a/47755357
has comment: http://stackoverflow.com/comment/82469517
has answer: http://stackoverflow.com/a/47801339
has body: I am trying to generate a matrix of numbers with 7 rows and 4 columns. Each row must sum to 100 and each column must have an even spread (if permitted) between a min and max range (specified below). Goal: C1 C2 C3 C4 sum range 1 low 100 ^ 2 .. | 3 .. | 4 .. | 5 .. | 6 .. | 7 high _ c1_high = 98 c1_low = 75 c2_high = 15 c2_low = 6 c3_high = 8 c3_low = 2 c4_low = 0.05 c4_high =0.5 In addition to this, i need the spread of each row to be as linear as possible, though a line fitted to the data with a second order polynomial would suffice (with an r^2 value of >0.98). I am currently trying to do this using the following sudocode: generate random number between ranges for c1,c2,c3 and c4. repeat this 7 times check correlation between each generated c1 value and a range of numbers from 1-7. For example: repeat step 3 for c2,c3 and c4. Break loop when step 3 and 4 are successful This has proven to be too burdensome in terms of the number of iterations required and as a result, the solution is never reached. Is there a more efficient way of achieving this solution? So far: import pandas as pd import numpy as np from sklearn.utils import shuffle c1_high = 98 c1_low = 75 c2_high = 15 c2_low = 6 c3_high = 8 c3_low = 2 c4_low = 0.05 c4_high =0.5 def matrix_gen(): #generates matrix within min and max values container =[] d={} offset = np.linspace(0.05,1,9) c1= np.linspace(c1_low, c1_high, 7) c2= np.linspace(c2_low, c2_high, 7) c3= np.linspace(c3_low, c3_high, 7) c4= np.linspace(c4_low, c4_high, 7) for i in np.arange(7): d["row{0}".format(i)]=[item[i] for item in [c1,c2,c3,c4]] df =pd.DataFrame(d) df.loc[4,:] = df.iloc[0,:][::-1].values df1 = df.drop(0) df1.loc[5,:] = df1.sum(axis=0) new_name = df1.index[-1] df1 = df1.rename(index={new_name: 'sum'}) return df1 m = matrix_gen() print(m) out: row0 row1 row2 row3 row4 row5 row6 1 6.00 7.500000 9.000000 10.500 12.000000 13.500000 15.0 2 2.00 3.000000 4.000000 5.000 6.000000 7.000000 8.0 3 0.05 0.125000 0.200000 0.275 0.350000 0.425000…
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82469532
has comment: http://stackoverflow.com/comment/82469886
type: AnsweredQuestion

http://stackoverflow.com/a/58759163
has body: The accepted a[indices].sum() approach copies data and creates a new array, which might cause problem if the array is large. np.sum actually has an argument to mask out colums, you can just do np.sum(a, where=[True, False, True, False]) Which doesn't copy any data. The mask array can be obtained by: mask = np.full(4, False) mask[np.array([0,2])] = True
has comment: http://stackoverflow.com/comment/136410463
score: 14
answers question: http://stackoverflow.com/q/47734392
type: Answer
upvote count: 14
downvote count: 0

http://stackoverflow.com/comment/82488140
score: 2
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47763282
has text: Post the entire error message so we can see some detail. (Do you have your own `urllib2.py` module?)

http://stackoverflow.com/comment/82557858
has text: It is. Show us what you’ve tried first. We’re not a code-writing service.
type: QuestionComment
comment on: http://stackoverflow.com/q/47798471
type: Comment
score: 0

http://stackoverflow.com/comment/82411213
type: AnswerComment
comment on: http://stackoverflow.com/a/47701181
has text: @eXistanCe you cannot rely on the order, it is *quite literally* a `dict`.
type: Comment
score: 0

http://stackoverflow.com/q/47804241
tagged with: pandas
has title: Applying parallelization when updating dictionary values
tagged with: multithreading
answer count: 1
downvote count: 0
has body: datasets = {} datasets['df1'] = df1 datasets['df2'] = df2 datasets['df3'] = df3 datasets['df4'] = df4 def prepare_dataframe(dataframe): return dataframe.apply(lambda x: x.astype(str).str.lower().str.replace('[^\w\s]', '')) for key, value in datasets.items(): datasets[key] = prepare_dataframe(value) I need to prepare the data in some dataframes for further analysis. I would like to parallelize the for loop that updates the dictionary with a prepared dataframe. This code will eventually run on a machine with dozens of cores and thousands of dataframes. On my local machine I do not appear to be using more than a single core in the prepare_dataframe function. I have looked at Numba and Joblib but I cannot find a way to work with dictionary values in either library. Any insight would be very much appreciated!
favorite count: 0
type: AnsweredQuestion
tagged with: python
tagged with: dictionary
type: Question
upvote count: 2
tagged with: parallel-processing
score: 2
has answer: http://stackoverflow.com/a/47876499
accepted answer: http://stackoverflow.com/a/47876499

http://stackoverflow.com/comment/82460928
type: Comment
type: AnswerComment
has text: @A_N Then try to modified the R smaller like that `R = 0.7`
score: 0
comment on: http://stackoverflow.com/a/47710320

http://stackoverflow.com/q/47845900
downvote count: 0
tagged with: file
possible better answer: http://stackoverflow.com/a/47845995
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82655802
has comment: http://stackoverflow.com/comment/82663557
has comment: http://stackoverflow.com/comment/82663621
has comment: http://stackoverflow.com/comment/82660881
has answer: http://stackoverflow.com/a/47845958
tagged with: io
has title: Reading a text file in pandas with separator as linefeed (\n) and line terminator as two linefeeds (\n\n)
tagged with: dataframe
tagged with: python
accepted answer: http://stackoverflow.com/a/47846077
has comment: http://stackoverflow.com/comment/82659694
score: 6
upvote count: 6
has answer: http://stackoverflow.com/a/47846077
has answer: http://stackoverflow.com/a/47845995
has body: I have a text file of the form : data.txt 2 8 4 3 1 9 6 5 7 How to read it into a pandas dataframe 0 1 2 0 2 8 4 1 3 1 9 2 6 5 7
type: AnsweredQuestion
answer count: 3
tagged with: pandas

http://stackoverflow.com/a/47720392
accepted answer of: http://stackoverflow.com/q/47719040
has comment: http://stackoverflow.com/comment/82408048
has comment: http://stackoverflow.com/comment/82408071
answers question: http://stackoverflow.com/q/47719040
has comment: http://stackoverflow.com/comment/82403068
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/82402924
has comment: http://stackoverflow.com/comment/82402239
has body: I broke down the steps, after we get the dd1, we can merge it back to your df1, you can replace NaN by using fillna(0) Newdf=pd.wide_to_long(df1,stubnames=['StartDate','EndDate'],i=['Name','ID1'],j='nnumer') Newdf.StartDate=pd.to_datetime(Newdf.StartDate) Newdf.EndDate=pd.to_datetime(Newdf.EndDate) Newdf['New']=Newdf'StartDate','EndDate'.apply(lambda x : [pd.date_range(x['StartDate'], x['EndDate'],freq='MS').tolist()],1)['StartDate'] Newdf=Newdf.set_index(['StartDate','EndDate'],append=True).New.apply(pd.Series).stack() Newdf=Newdf.to_frame('Date').reset_index() df2.Date=pd.to_datetime(df2.Date) dd=Newdf.merge(df2,on=['ID1','Date']) dd'Id1_num','id2_num'=dd'Id1_num','id2_num'.mask(dd'Id1_num','id2_num'&lt;10) dd1=dd.groupby(['ID1','nnumer','StartDate','EndDate'])['Id1_num','id2_num'].agg(['mean','count']).unstack(1).groupby(level='ID1').ffill().bfill().reset_index(['StartDate','EndDate'],drop=True).drop_duplicates() dd1 Out[626]: Id1_num id2_num mean count mean count nnumer 1 2 1 2 1 2 1 2 ID1 111 11.5 14.0 2.0 2.0 11.333333 12.0 3.0 3.0 112 11.5 11.5 2.0 2.0 19.000000 19.0 1.0 2.0 113 17.0 17.0 2.0 1.0 14.000000 14.0 1.0 1.0 114 13.0 13.0 3.0 3.0 13.000000 13.0 2.0 2.0 115 13.0 NaN 1.0 0.0 19.000000 NaN 1.0 0.0 Updated dd1.columns=dd1.columns.map(''.join) dd1 Out[650]: Id1_nummean1 Id1_nummean2 Id1_numcount1 Id1_numcount2 id2_nummean1 \ ID1 111 11.5 14.0 2.0 2.0 11.333333 112 11.5 11.5 2.0 2.0 19.000000 113 17.0 17.0 2.0 1.0 14.000000 114 13.0 13.0 3.0 3.0 13.000000 115 13.0 NaN 1.0 0.0 19.000000 id2_nummean2 id2_numcount1 id2_numcount2 ID1 111 12.0 3.0 3.0 112 19.0 1.0 2.0 113 14.0 1.0 1.0 114 13.0 2.0 2.0 115 NaN 1.0 0.0
has comment: http://stackoverflow.com/comment/82402439
downvote count: 0
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/82405768
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47722552
has text: `df['date']=pd.Timestamp("2017-01-01")`
score: 0

http://stackoverflow.com/comment/82359399
type: QuestionComment
score: 0
has text: I'm actually keen to see `pearson_def`. The correlation is computed between two series, yet one of them seems to be the numbers 0, 1, 2, ...
comment on: http://stackoverflow.com/q/47699473
type: Comment

http://stackoverflow.com/a/47753616
score: 0
has body: You can't modify the collection you are iterating on. This will do the trick: for element in lst[:] : lst.remove(element)
answers question: http://stackoverflow.com/q/47753532
type: Answer

http://stackoverflow.com/a/47798432
has body: Just change the end of your code as follows: if uChoice == "Rock" and sChoice == 1 or uChoice == "Paper" and sChoice == 2 or uChoice == "Scissors" and sChoice == 3: print("The opponent chose %s" %(sChoicet)) print("The match was a draw.") elif uChoice == "Rock" and sChoice == 2 or uChoice == "Paper" and sChoice == 3 or uChoice == "Scissors" and sChoice == 1: print("The opponent chose %s" %(sChoicet)) print("You lost the match, unlucky.") elif uChoice == "Rock" and sChoice == 3 or uChoice == "Paper" and sChoice == 1 or uChoice == "Scissors" and sChoice == 2: print("The opponent chose %s" %(sChoicet)) print("You won the match!") You were comparing a String with an Integer value, reason why the comparison was never true.
answers question: http://stackoverflow.com/q/47798330
score: 0
type: Answer

http://stackoverflow.com/comment/82600113
type: Comment
type: AnswerComment
has text: Ugh, I found the dumb mistake on my end. I mistakenly left my template href as `{% url my_url %}` instead of changing it to `{{my_url}}` as you described. Works now, and much cleaner. Thanks so much for your help!
comment on: http://stackoverflow.com/a/47806606
score: 1

http://stackoverflow.com/q/47839194
has answer: http://stackoverflow.com/a/47839380
has comment: http://stackoverflow.com/comment/82642431
downvote count: 0
has body: I have a function that can return one of three values: a, b, or c. def f(): return x # a, b, or c I need to execute different statements based on the return value of f(): A, B, or C. The best way to do this, that I know of, is: v = f() if v == a: # Do A elif v == b: # Do B else: # Do C Without introducing this new variable v, is there a different way to evaluate the return value of f()? Something like this, maybe? if f() == a: # Do A elif _value_from_above == b: # Do B else: # Do C
tagged with: python
score: 4
has comment: http://stackoverflow.com/comment/82642400
accepted answer: http://stackoverflow.com/a/47839359
has answer: http://stackoverflow.com/a/47839359
type: AnsweredQuestion
answer count: 3
tagged with: if-statement
possible better answer: http://stackoverflow.com/a/47839281
linked to: http://stackoverflow.com/q/60208
has answer: http://stackoverflow.com/a/47839281
favorite count: 0
has title: python: Piping a value through an if/elif statement
type: Question
upvote count: 4
duplicate of: http://stackoverflow.com/q/60208

http://stackoverflow.com/comment/82444265
type: QuestionComment
comment on: http://stackoverflow.com/q/47741920
has text: `np.where((df.A==1) & (df.B==2),True,False)`
type: Comment
score: 1

http://stackoverflow.com/q/47742001
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47742105
tagged with: string
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82444147
has comment: http://stackoverflow.com/comment/82445026
has body: How can I get specific integers inside a string?: mystring = "[RUN #1 3%, 2 secs] 2 threads: 6673 ops, 3511 (avg: 3333) ops/sec, 3.60MB/sec (avg: 3.42MB/sec), 0.56 (avg: 0.59) msec latency" I want to get in this line the 3511, and 0.56
has title: Get a specific numbers inside a string in python
score: -2
has comment: http://stackoverflow.com/comment/82444166
has answer: http://stackoverflow.com/a/47742102
tagged with: python
tagged with: regex
has answer: http://stackoverflow.com/a/47742137
answer count: 3
downvote count: 3
upvote count: 1

http://stackoverflow.com/comment/82468356
type: QuestionComment
has text: I _think_ you want to know how you can update the printed board after the players make a move. The simple way to do that is to just clear the screen and reprint it. There _are_ ways to modify the stuff that's currently printed, but the details depend on your OS, and it's a bit technical, so it's best to use a library that can handle the messy details. Or forget about doing it in the terminal, and use a GUI to display your board.
comment on: http://stackoverflow.com/q/47753012
score: 0
type: Comment

http://stackoverflow.com/q/47813091
downvote count: 5
tagged with: python
has answer: http://stackoverflow.com/a/47813477
tagged with: dictionary
has body: I have an array like the following: [( 1, b'"C"'), ( 2, b'"C#"'), ( 3, b'"D"'), ( 4, b'"D#"'), ( 5, b'"E"'), ( 6, b'"F"'), ( 7, b'"F#"'), ( 8, b'"G"'), ( 9, b'"G#"'), (10, b'"A"'), (11, b'"A#"'), (12, b'"B"'))] I want to convert this to a dictionary "d" such that when I say d[11] I will get "A#". EDIT: learnt that dict is a reserved word, so I changed it to "d".
answer count: 4
type: AnsweredQuestion
tagged with: numpy
has answer: http://stackoverflow.com/a/67529605
upvote count: 2
has answer: http://stackoverflow.com/a/47813968
tagged with: arrays
has title: converting numpy array into dictionary
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82593970
has comment: http://stackoverflow.com/comment/82587434
has answer: http://stackoverflow.com/a/47813338
possible better answer: http://stackoverflow.com/a/47813968
accepted answer: http://stackoverflow.com/a/47813477
score: -3

http://stackoverflow.com/q/47841051
type: UnansweredQuestion
answer count: 1
has answer: http://stackoverflow.com/a/47930147
type: Question
score: 0
has body: I'm having trouble making an MLP in MxNet learn. It tends to output fairly constant values, only occasionally outputting anything different. I'm using the Pima Indians dataset to do binary classification, but no matter what I do (normalisation, scaling, changing activations, objective functions, number of neurons, batch size, epochs) it wouldn't produce anything useful. The same MLP in Keras works fine. Here's the MxNet code: batch_size=10 train_iter=mx.io.NDArrayIter(mx.nd.array(df_train), mx.nd.array(y_train), batch_size, shuffle=True) val_iter=mx.io.NDArrayIter(mx.nd.array(df_test), mx.nd.array(y_test), batch_size) data=mx.sym.var('data') fc1 = mx.sym.FullyConnected(data=data, num_hidden=12) act1 = mx.sym.Activation(data=fc1, act_type='relu') fc2 = mx.sym.FullyConnected(data=act1, num_hidden=8) act2 = mx.sym.Activation(data=fc2, act_type='relu') fcfinal = mx.sym.FullyConnected(data=act2, num_hidden=2) mlp = mx.sym.SoftmaxOutput(data=fcfinal, name='softmax') mlp_model = mx.mod.Module(symbol=mlp, context=mx.cpu()) mlp_model.fit(train_iter, eval_data=val_iter, optimizer='sgd', eval_metric='ce', num_epoch=150) And the same MLP in Keras: model = Sequential() model.add(Dense(12, input_dim=8, activation='relu')) model.add(Dense(8, activation='relu')) model.add(Dense(1, activation='sigmoid')) model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) model.fit(df_train_res, y_train_res)
tagged with: mxnet
tagged with: python
has title: MxNet neural nets won't learn
tagged with: deep-learning

http://stackoverflow.com/q/47790088
upvote count: 1
has comment: http://stackoverflow.com/comment/82541284
has title: Pandas value_count() 'index must be monotonic', but index already is
favorite count: 0
has comment: http://stackoverflow.com/comment/82630718
type: Question
has comment: http://stackoverflow.com/comment/82543710
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
score: 1
has comment: http://stackoverflow.com/comment/82543849
tagged with: python
has comment: http://stackoverflow.com/comment/82543971
has answer: http://stackoverflow.com/a/48846709
has comment: http://stackoverflow.com/comment/82544724
has comment: http://stackoverflow.com/comment/82541618
has comment: http://stackoverflow.com/comment/82547777
has comment: http://stackoverflow.com/comment/82544353
tagged with: python-3.x
has answer: http://stackoverflow.com/a/61538486
has body: When trying to get a value count for some columns in my data frame, I get this error saying the index must be monotonic, but the is_monotonic property says that the index is already that way. The majority of the columns in the dataframe after importing a csv don't return this error, but a few do. I've tried some of the tactics mentioned here, but can't seem to get it working. Doing this: import pandas as pd data = pd.read_csv('info/train.csv') print('Monotonic?: ', data['net_booking_value_monthly'].index.is_monotonic) print(data['net_booking_value_monthly'].value_counts(dropna=False)[:10]) Gives me this: Monotonic?: True Traceback (most recent call last): File "/Users/person/venvs/science/lib/python3.6/site-packages/pandas/core/indexes/base.py", line 3484, in get_slice_bound return self._searchsorted_monotonic(label, side) File "/Users/person/venvs/science/lib/python3.6/site-packages/pandas/core/indexes/base.py", line 3443, in _searchsorted_monotonic raise ValueError('index must be monotonic increasing or decreasing') ValueError: index must be monotonic increasing or decreasing During handling of the above exception, another exception occurred: etc. etc. It's doing my head in that the is_monotonic property is True, but the value count returns this error. The input CSV file is pretty big and I can't share it, but is there anything I should look for in there that would cause this? Pandas version is 0.20.2.
answer count: 2
has comment: http://stackoverflow.com/comment/82545163
has comment: http://stackoverflow.com/comment/82541647
has comment: http://stackoverflow.com/comment/82543922
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/37982170
downvote count: 0

http://stackoverflow.com/comment/82593093
comment on: http://stackoverflow.com/q/47814767
has text: @BinyaminEven I could probably figure it out if I spent the time to do it, but it's not something I could do easily.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/82596162
type: QuestionComment
score: 0
has text: If the API provides the data you’re after I’d use the API.
comment on: http://stackoverflow.com/q/47817006
type: Comment

http://stackoverflow.com/comment/82607066
type: Comment
has text: What do you mean by `my program won't return`? You closed stdout and stderr. By definition, it _shouldn't_ be returning.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47822021

http://stackoverflow.com/comment/82496222
score: 0
type: AnswerComment
has text: do you remove `df=df['Person']` ?
type: Comment
comment on: http://stackoverflow.com/a/47767362

http://stackoverflow.com/q/47712058
has body: I want to compute the Pearson correlation between two lists of tuples. I know that I can compute the correlation between e.g two lists of numbers, by putting them in a dataframe as columns and then just run df.corr(). However, I have now lists of tuples (2-element tuples) and I want to be able to compute the correlation between these 2 lists without transforming these tuples into anything else that might cause a loss of information. Is it possible to do that in Python (or anywhere else, as far as this is concerned)? An example of the 2 lists can be: list1 = [(1,2),(3,4),(5,6)] list2 = [(10,11),(12,13),(14,15)]
tagged with: stat
answer count: 0
has comment: http://stackoverflow.com/comment/82384504
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/82400465
has comment: http://stackoverflow.com/comment/82384260
has comment: http://stackoverflow.com/comment/82400730
score: 0
has title: Correlation between 2 lists of tuples
upvote count: 1
downvote count: 1
tagged with: scipy
favorite count: 0
tagged with: correlation
type: Question

http://stackoverflow.com/q/47733641
answer count: 0
has comment: http://stackoverflow.com/comment/82431472
has comment: http://stackoverflow.com/comment/82515605
type: Question
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/82427928
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82428547
has title: Can't print out lines of my csv file
tagged with: scraper
has comment: http://stackoverflow.com/comment/82427876
score: 0
has body: I am a novice coder working on a data scraping project. I was able to get my code to scrape the data working properly and I put it into a csv file that is organized as [Name,Price,Shipping,Date]. Now I want to take this data and put it into a list and change the variable types accordingly. something like list = ["name", price(int),shipping(int), date (str)] so I can feed this list into a constructor to make objects of each listing that I scraped. Firstly, I just wanted some clarity. Is the csv file saving each piece of info as a string? I'm not sure on this. The problem I am running into is everytime I try and print out a line of my csv file I keep getting an error. I want to print out the lines, clean up the data a bit then save them into a list. here is my code: import csv with open('Charmander.csv', newline = '') as csv_file: data = csv.reader(csv_file, delimiter = ',') for line in data: print(line[0]) and I keep getting this back Name Traceback (most recent call last): File "C:\Python\Data mon\csv_to_list.py", line 6, in &lt;module&gt; print(line[0]) IndexError: list index out of range I am not very familiar with csv files and im not sure what I am doing wrong, if anyone can teach me and give some insight that would be great, I just want to get some more progress on my project as soon as I can.

http://stackoverflow.com/comment/88993150
type: Comment
has text: @hroncok I guess it is possible to distinguish AssertionError with other types of exception.
type: AnswerComment
comment on: http://stackoverflow.com/a/47731333
score: 0

http://stackoverflow.com/comment/82589976
score: 0
type: Comment
type: QuestionComment
has text: you didn't show code before - now I see you use it in different way than I expected. How it works when you remove all logic which read database and use fake data ? If works without problems then problem can be in logic and we can't say anything more.
comment on: http://stackoverflow.com/q/47811125

http://stackoverflow.com/comment/82664647
type: AnswerComment
has text: It happens at that line because that's when the faulty code is actually executed. When we just look at `def g(f1, f2) : return f1(f2)`, f1 and f2 could be anything, so at that point there's no way to tell if that code going to fail. It is only when the function `g` is called with parameter values `f1 = lambda x: x**2` and `f2 = lambda y: 2*y` that the error occurs, because putting `f2` in `x` leads to running `(lambda y: 2*y) ** 2`, and that causes the error you see
type: Comment
comment on: http://stackoverflow.com/a/47845606
score: 0

http://stackoverflow.com/comment/82565283
comment on: http://stackoverflow.com/q/47801788
score: 0
has text: might be able to copy the cookies over? : https://stackoverflow.com/a/38812576/2026508
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82509865
type: Comment
score: 1
comment on: http://stackoverflow.com/a/47774343
type: AnswerComment
has text: @Zanzag Yes, use `query`. `df.query('CO2 == "AFG"').sum(level=0)` or to do multiple `df.query('CO2 in ["AFG","AGO"]').sum(level=0)`

http://stackoverflow.com/a/47854487
downvote count: 0
has comment: http://stackoverflow.com/comment/82673641
type: Answer
score: 2
has body: results isn't a str, it is a requests.models.Response object. Try invoking it's .json() method, like so: import requests API_KEY = '******' Movie = 'The Matrix' results = requests.get("http://httpbin.org/get", params={'apikey': API_KEY, 't': Movie}) data = results.json() print data
upvote count: 2
answers question: http://stackoverflow.com/q/47854450

http://stackoverflow.com/a/47698816
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47698647
upvote count: 1
has body: As mentioned by CristiFati's comment, you should read the file, close it and then open it for writing: import sys file_in = open(sys.argv[1],'r') content = file_in.read() file_in.close() file_out = open(sys.argv[1],'w') file_out.write(content.replace(';',';\n')) file_out.close() Optionally you can change the output filename to be something different so that you don't overwrite your original file.
type: Answer
answers question: http://stackoverflow.com/q/47698647
score: 1
type: AcceptedAnswer

http://stackoverflow.com/q/47769111
type: AnsweredQuestion
tagged with: list
accepted answer: http://stackoverflow.com/a/47769166
tagged with: pandas
has body: I have this data below, which is a list with 4 elements. These elements are tuple which items are list them self... data = [(['a', 'b', 'c'], [1, 2, 3, 4, 5], ['aa', 'bb'], ['00', '03', '0000', '0006']), (['e', 'f', 'g'], [2, 1, 4, 4, 6], ['qq', 'er'], ['10', '04', '3340', '9009']), (['w', 'd', 'c'], [5, 6, 55, 1, 6], ['rr', 'rr'], ['55', '11', '6788', '7789']), (['l', 'a', 's'], [29, 2, 9, 4, 3], ['yy', 'uu'], ['33', '67', '0000', '0237'])] I want to convert it to dataframe in such a way that each element is broken onto column of the dataframe. For example; df = pd.DataFrame(data) will result into a dataframe with four columns. What I want is for each column to be broken into columns of the dataframe as seen below in red lines... That is to say, above dataframe will have each column sub divided into the number of items that made up the cell.
has answer: http://stackoverflow.com/a/47769166
downvote count: 0
answer count: 1
upvote count: 1
favorite count: 0
type: Question
score: 1
tagged with: dataframe
tagged with: python
has title: Create pandas dataframe from list of tuple of nested lists

http://stackoverflow.com/a/47820174
answers question: http://stackoverflow.com/q/47820152
has comment: http://stackoverflow.com/comment/82605804
has comment: http://stackoverflow.com/comment/82606279
has comment: http://stackoverflow.com/comment/82605865
accepted answer of: http://stackoverflow.com/q/47820152
type: Answer
has comment: http://stackoverflow.com/comment/82606022
has body: This is stack not pivot df.set_index('name').stack() Out[186]: name MathematicsHouseAB X 0.123 Y 0.111 PhysicalScienceHut X 0.124 Y 0.112 PrimaryEducationLO X 0.125 Y 0.113 TertiaryUniversitas X 0.126 Y 0.114 PrincipleofPhysics X 0.127 Y 0.115 ChemicalIndustryA1 X 0.128 Y 0.116 dtype: float64 EDIT: df=df.set_index('name').stack() df.index.names=['name', 'Z'] df Out[263]: 0 name Z MathematicsHouseAB X 0.123 Y 0.111 PhysicalScienceHut X 0.124 Y 0.112 PrimaryEducationLO X 0.125 Y 0.113 TertiaryUniversitas X 0.126 Y 0.114 PrincipleofPhysics X 0.127 Y 0.115 ChemicalIndustryA1 X 0.128 Y 0.116
has comment: http://stackoverflow.com/comment/82605421
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/82604812

http://stackoverflow.com/q/47794752
has body: I am connecting to MS Access using ODBC (Python ODBC module ). There is one part of the code which put some values into DB. Looks similar to this: for item in changes: format_str = """INSERT INTO changes (short_description) VALUES ('{short_description}');""" sql_command = format_str.format(short_description =item.short_description) cursor.execute(sql_command) cursor.commit() The problem is that it returns syttaxt error: pypyodbc.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC Microsoft Access Driver] Syntax error (missing operator) in query expression I found that it is because for one the cases I have short_description like this one: The Service Request status is not changing to \"OPEN', once dispatched to another group the problem is for " ' " after OPEN. to provide you full picture here. Actually the string I see is this: The Service Request status is not changing to "OPEN', once dispatched to another group The string with "\" I get from the API for the application which serves the data. It adds "\" to escape string, but not everywhere. The question is - what will be the simplest way to solve it? Theoretically I could replace\remove unwanted signs, but what in case I want to keep it as it is? For any other cases all works fine.
has title: Python - special characters in SQL statement
has answer: http://stackoverflow.com/a/47794851
tagged with: python
type: AnsweredQuestion
score: 2
upvote count: 2
accepted answer: http://stackoverflow.com/a/47794851
tagged with: pypyodbc
answer count: 1
downvote count: 0
favorite count: 0
type: Question

http://stackoverflow.com/comment/82670632
type: QuestionComment
has text: You need to escape shell special characters / separators if you're going to use `os.system()`. Or, from the documentation of the same function: '_The [`subprocess`](https://docs.python.org/2/library/subprocess.html#module-subprocess) module provides more powerful facilities for spawning new processes and retrieving their results; **using that module is preferable to using this function**. See the [Replacing Older Functions with the subprocess Module](https://docs.python.org/2/library/subprocess.html#subprocess-replacements) section in the subprocess documentation for some helpful recipes._'
score: 5
comment on: http://stackoverflow.com/q/47853134
type: Comment

http://stackoverflow.com/q/47704438
downvote count: 0
accepted answer: http://stackoverflow.com/a/47704471
upvote count: 1
has answer: http://stackoverflow.com/a/47704471
favorite count: 0
type: Question
tagged with: python-3.x
has title: Python Dataframe: operation per row in all dataframe
score: 1
tagged with: python
tagged with: numpy
type: AnsweredQuestion
has body: I have a dataframe in python which looks like the following. The number of column is not fix and increase with a iteration but follows the same pattern (more columns can be added), but to illustrate my issue please take my current df. 0 1 2 0 0.414143 13.898568 17.322851 1 24.348445 0.514046 36.663878 0 0.776340 11.541118 21.312318 0 11.700539 56.442854 22.853285 2 11.599149 12.977594 4.905724 1 22.944083 0.501586 42.553746 0 4.092333 39.273114 23.406309 The idea is to keep the same dataframe dimension and compute the min value per row and set zero to the others values in the same row. The final results should look like this: 0 1 2 0 0.414143 0 0 1 0 0.514046 0 0 0.776340 0 0 0 11.700539 0 0 2 0 0 4.905724 1 0 0.501586 0 0 4.092333 0 0 I set the row and column index with the same format (This indexes are integers in a range between [0-9]. The value which match with the same index, is the value that I'd like to keep it and set others as zeros. Any idea which function could I apply to achieve my goal? Thanks for your help.
tagged with: pandas
answer count: 1

http://stackoverflow.com/a/47855651
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47855617
has comment: http://stackoverflow.com/comment/82675495
has body: The __getattribute__, __setattr__ and __delattr__ methods are called for all attribute access (getting, setting and deleting). __getattr__ on the other hand is only called for missing attributes; it is not normally already implemented, but if it is then __getattribute__ calls it if it could not otherwise locate the attribute, or if an AttributeError was raised by __getattribute__. You replaced the standard implementations of the 3 main methods with methods that do nothing but print and return None (the default in the absence of an explicit return statement). __dict__ is just another attribute access, and your __getattribute__ method returns None, and never itself calls __getattr__ or raises an AttributeError. From the Customizing attribute access documentation: object.__getattr__(self, name) Called when an attribute lookup has not found the attribute in the usual places (i.e. it is not an instance attribute nor is it found in the class tree for self). and object.__getattribute__(self, name) Called unconditionally to implement attribute accesses for instances of the class. If the class also defines __getattr__(), the latter will not be called unless __getattribute__() either calls it explicitly or raises an AttributeError. (Bold emphasis mine). Either call the base implementation (via super().__getattribute__) or raise an AttributeError: &gt;&gt;&gt; class B: ... def __init__(self): ... self.name = '234' ... def __getattribute__(self, name): ... print('getattr') ... return super().__getattribute__(name) ... def __getattr__(self, name): ... print('get') ... def __setattr__(self, name, value): ... print('set') ... def __delattr__(self, name): ... print('del') ... &gt;&gt;&gt; b = B() set &gt;&gt;&gt; b.__dict__ getattr {} &gt;&gt;&gt; b.name getattr get &gt;&gt;&gt; class B: ... def __init__(self): ... self.name = '234' ... def __getattribute__(self, name): ... print('getattr') ... raise AttributeError(name) ... def __getattr__(self, name): ... print('get') ... def __s…
has comment: http://stackoverflow.com/comment/82675938
has comment: http://stackoverflow.com/comment/82675683
upvote count: 5
has comment: http://stackoverflow.com/comment/82675575
has comment: http://stackoverflow.com/comment/82675554
type: Answer
answers question: http://stackoverflow.com/q/47855617
has comment: http://stackoverflow.com/comment/82675960
has comment: http://stackoverflow.com/comment/82675630
has comment: http://stackoverflow.com/comment/82675613
score: 5
has comment: http://stackoverflow.com/comment/82675876
type: AcceptedAnswer

python-packaging
type: Tag
tags question: http://stackoverflow.com/q/47804206
tags question: http://stackoverflow.com/q/47773596
tag name: python-packaging

http://stackoverflow.com/comment/82604812
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47820174
score: 0
has text: Thanks for your reply. Is there a way to perform the 2nd part of the task by relabelling the column of X,Y and the float column (2nd and 3rd columns in all) with the label Z?

http://stackoverflow.com/comment/82508519
type: Comment
comment on: http://stackoverflow.com/a/47773486
has text: then could you post your modified version as an answer, for other people who stumble on the same problem, thanks!
type: AnswerComment
score: 0

pickle
tags question: http://stackoverflow.com/q/47824532
tags question: http://stackoverflow.com/q/47850996
type: Tag
tags question: http://stackoverflow.com/q/47705202
tags question: http://stackoverflow.com/q/47702975
tags question: http://stackoverflow.com/q/47762345
tags question: http://stackoverflow.com/q/47793192
tags question: http://stackoverflow.com/q/47776528
tags question: http://stackoverflow.com/q/47746988
tag name: pickle

http://stackoverflow.com/comment/82603138
has text: Yes I did, this seems to be a problem with the chromedriver. I updated the chromedrive from their website and it resolved this.
score: 1
type: Comment
comment on: http://stackoverflow.com/q/47711009
type: QuestionComment

http://stackoverflow.com/comment/82523465
comment on: http://stackoverflow.com/q/47760220
score: 0
type: Comment
type: QuestionComment
has text: So is your file empty after you run this? I would suggest you to add f.close() in the end of your script. This might help.

http://stackoverflow.com/q/47723751
tagged with: beautifulsoup
tagged with: python-3.x
has body: Trying to scrape a table on one page, grab every link in it, and then scrape a specific section of each link by adding "#Section" to the end. import urllib.request as urllib2 from bs4 import BeautifulSoup import json req = urllib2.Request(url, headers={'User-Agent' : "Magic Browser"}) con = urllib2.urlopen( req ) string = con.read().decode('utf-8') print(string) I'm not sure how to find a specific table, though - this prints a string but I don't know how to parse it, and json.loads(string) gives me an error json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) Also, User_Agent is a workaround because I get a 403 error otherwise
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/82408532
has comment: http://stackoverflow.com/comment/82408311
score: 0
answer count: 0
tagged with: http://stackoverflow.com/tag/json
has title: Scraping tables in Python3 with BeautifulSoup?
has comment: http://stackoverflow.com/comment/82409026
type: Question

http://stackoverflow.com/comment/82515064
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47775186
has text: Read the error message carefully. What does it say to you?

http://stackoverflow.com/a/47834032
has body: Try this; answer = [answer1, answer2]; student_answer= [studentAnswer1, studentAnswer2]; for i in range (len(answer)){ if int(self.answer[i]) == int(self.student_answer[i]): self.score = int(self.score) + 1 self.questionsAsked = self.questionsAsked + 1 self.updateProgressBar() else: self.display = "Sorry the correct answer was " + str(self.answer[i]) self.wrongAnswer() self.correctAnswer = int(self.answer[i]) self.input = int(self.student_answer[i]) self.type = str(self.a) + " multiplied by 1000, to convert KG to Grams" self.insertAnswer() }
answers question: http://stackoverflow.com/q/47833920
type: Answer
score: 0

http://stackoverflow.com/a/47806883
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/119264288
has comment: http://stackoverflow.com/comment/82575263
answers question: http://stackoverflow.com/q/47791878
type: Answer
accepted answer of: http://stackoverflow.com/q/47791878
has body: You can do this is PySpark by using groupby. First group on the id column and merge the products together into a single, sorted list. To get the count of the number of such lists, use groupby again and aggregate by count. from pyspark.sql import functions as F df2 = (df .groupby("id") .agg(F.concat_ws("-", F.sort_array(F.collect_list("product"))).alias("products")) .groupby("products") .agg(F.count("id")).alias("count")) This should give you a dataframe like this: +--------------+-----+ | products|count| +--------------+-----+ | HOME-mobile| 2| | mobile-watch| 1| |cd-music-video| 1| +--------------+-----+
has comment: http://stackoverflow.com/comment/82575582
upvote count: 2
has comment: http://stackoverflow.com/comment/82575108
score: 2
has comment: http://stackoverflow.com/comment/119270849
downvote count: 0
has comment: http://stackoverflow.com/comment/82575218

http://stackoverflow.com/q/47797290
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82555558
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47797470
tagged with: dataframe
tagged with: python
tagged with: pandas
has body: I have a dataframe (first column is in string format):` Time_string Count 23:10 2400 02:55 760 I want to add a third column which is the float of the first column: Time_float 23.166667 2.916667 How do I do this?
score: 1
downvote count: 0
answer count: 1
upvote count: 1
has title: convert hh:mm to float pandas

frame-rate
tags question: http://stackoverflow.com/q/47743246
tags question: http://stackoverflow.com/q/47844353
tag name: frame-rate
type: Tag

http://stackoverflow.com/q/47843875
accepted answer: http://stackoverflow.com/a/47845537
tagged with: python
tagged with: data-science
type: AnsweredQuestion
score: 1
downvote count: 0
answer count: 1
has body: this is the first time i ask question in stackoverflow, thus i might not able to give all details of my problem in a single post. I am trying to apply CNN on activity recognition dataset but current i facing a problem where logits and labels must be same size: logits_size=[1200,7] labels_size=[600,7]. Link of dataset Link to my github file batch_size = 600 # Batch size seq_len = 200 # Number of steps learning_rate = 0.0005 epochs = 200 n_classes = 7 n_channels = 3 inputs_ = tf.placeholder(tf.float32, [None, seq_len, n_channels], name = 'inputs') labels_ = tf.placeholder(tf.float32, [None, n_classes], name = 'labels') keep_prob_ = tf.placeholder(tf.float32, name = 'keep') learning_rate_ = tf.placeholder(tf.float32, name = 'learning_rate') cconv1 = tf.layers.conv1d(inputs=inputs_, filters=18, kernel_size=2, strides=1, padding='same', activation = tf.nn.relu) pool_1 = tf.layers.max_pooling1d(inputs=cconv1, pool_size=4, strides=4, padding='same') cconv2 = tf.layers.conv1d(inputs=pool_1, filters=36, kernel_size=2, strides=1, padding='same', activation = tf.nn.relu) pool_2 = tf.layers.max_pooling1d(inputs=cconv2, pool_size=4, strides=4, padding='same') cconv3 = tf.layers.conv1d(inputs=pool_2, filters=72, kernel_size=2, strides=1, padding='same', activation = tf.nn.relu) pool_3 = tf.layers.max_pooling1d(inputs=cconv3, pool_size=4, strides=4, padding='same') flat = tf.reshape(pool_3, (-1, 2*72)) print(flat.get_shape()) flat = tf.nn.dropout(flat, keep_prob=keep_prob_) print(flat.get_shape()) logits = tf.layers.dense(flat, n_classes) print(logits.get_shape()) # Cost function and optimizer cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=labels_)) # print(cost.get_shape()) optimizer = tf.train.AdamOptimizer(learning_rate_).minimize(cost) tf.summary.scalar("cost",cost) # Accuracy correct_pred = tf.equal(tf.argmax(logits, 1), tf.argmax(labels_, 1)) accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32), name='accuracy') tf.summary.scalar("…
upvote count: 1
has answer: http://stackoverflow.com/a/47845537
has title: logits and labels must be same size: logits_size=[1200,7] labels_size=[600,7]
tagged with: tensorflow
favorite count: 0
type: Question
tagged with: deep-learning

http://stackoverflow.com/comment/82549703
score: 1
comment on: http://stackoverflow.com/q/47793894
type: Comment
type: QuestionComment
has text: See [mcve]. Only if people can reproduce the issue they are likely to come up with a solution.

http://stackoverflow.com/comment/82557351
type: AnswerComment
has text: @Faibbus It also assumes that the question being answered is the one asked and not all possible variations of it.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47797611

http://stackoverflow.com/comment/82661113
comment on: http://stackoverflow.com/a/47843970
score: 0
type: AnswerComment
has text: If I'm sending a nested json data via python to mongodb then how can I replace the json code from string to objectId? Please can you share the code? Thank You, Nozar :)
type: Comment

http://stackoverflow.com/comment/82866967
type: Comment
score: 0
type: AnswerComment
has text: I mean classify a new example once training is complete. For example [1,0,0,0]
comment on: http://stackoverflow.com/a/47941930

http://stackoverflow.com/comment/82405104
comment on: http://stackoverflow.com/q/47722168
type: QuestionComment
has text: I did it @app.route("/user/<username>/set-password", methods=["POST"]) def set_password(username): data=request.get_json() new_password = data["password"] users[username] = {new_password} return "Set password of {} to '()' "\ .format(username, new_password) app.run(debug=True)
score: 0
type: Comment

http://stackoverflow.com/comment/82402739
type: Comment
has text: can you provide the input and expected output , like a small example
type: QuestionComment
comment on: http://stackoverflow.com/q/47721083
score: 1

http://stackoverflow.com/q/47781887
type: Question
type: UnansweredQuestion
tagged with: python
has title: override operations in dask for getitem
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/47781992
tagged with: dask
has body: Is there a way to override certain operations. import dask import numpy as np a = np.zeros((10,10)) a = dask.delayed(lambda x : x*2)(a) I would like a[0] to return a number (instead of having to call a[0].compute()). Is this possible? The context is that I would like to have a series of images (3D array), and run operations like: imgs2 = imgs - 1 imgs3 = imgs*mask and then have an operation like imgs3[0] explicitly run imgs3[0].compute(). However, I see many drawbacks with this method now and I would like to remove this post. For one is this is quite limiting. Indexing things like imgs3[:,:, 10] (all columns) may also have to end up with a computed result.

http://stackoverflow.com/comment/82667735
type: Comment
type: AnswerComment
has text: That's what I ended up to do. Thanks ! Cython is not used for that purpose, but I need this feature inside a Cython module.
comment on: http://stackoverflow.com/a/47827330
score: 1

http://stackoverflow.com/comment/82638568
has text: Thanks Max, I'll try as said :)
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47827650

http://stackoverflow.com/comment/82406893
has text: Have you tried running the script with sudo?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47722559
score: 0

http://stackoverflow.com/a/47714555
type: Answer
answers question: http://stackoverflow.com/q/47714423
upvote count: 2
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/82389045
has body: The thing is that map expects a function/callable as a first argument but you're giving it the result of a filter. You can fix this by applying filter to the sublists iterated by map: def no_zeros(lst): a = map(lambda x: filter(lambda y: y != 0, x), lst) print(list(a)) By the way, you can do the same thing with list comprehensions: def no_zeros(lst): a = [[y for y in x if y != 0] for x in lst] print(a)

http://stackoverflow.com/comment/82387872
type: QuestionComment
type: Comment
score: 0
has text: Yes. ASCII of '00' is empty. How can I print now?
comment on: http://stackoverflow.com/q/47713915

http://stackoverflow.com/comment/82374390
score: 0
type: Comment
has text: Oh. I did not even notice that. That is how the code templet was written at first. I will try tweaking that next. Thank you.
type: QuestionComment
comment on: http://stackoverflow.com/q/47707075

http://stackoverflow.com/a/47727673
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/82416307
answers question: http://stackoverflow.com/q/47727551
score: 1
has comment: http://stackoverflow.com/comment/82416037
type: Answer
accepted answer of: http://stackoverflow.com/q/47727551
has body: It sounds like you want to generate a random number and, if the random number meets certain criteria, enqueue a value, else break the loop. Using your definition of Queue class, the following should perform this operation: import random # We will need this to generate the random number q = Queue() # Initialize the Queue just like you had it names = ["Same", "Peter", "James", "Daniel"] # List of possible names for i in range(0,4): # for loop 4 times rand = random.randint(1, 10) # Choose a random number print("Number Generated:\n" + str(rand)) # Display selected number if rand &gt;= 9: # number is 9 or 10 break # Break out of the loop, you can also add other logic here else: # number is less than 9 q.enqueue(random.choice(names)) # Enqueue a random name Hope this helps with your problem.
has comment: http://stackoverflow.com/comment/82416328
type: AcceptedAnswer

http://stackoverflow.com/comment/82478033
comment on: http://stackoverflow.com/q/47751798
type: QuestionComment
has text: Can you post your myapp.users.app.UserConfig. It is weird that its thinking that serializer is a module and not a class.
score: 1
type: Comment

http://stackoverflow.com/comment/82631388
comment on: http://stackoverflow.com/q/47834164
type: Comment
has text: It appears as though `self.rect.center` is a tuple, not a function.
score: 3
type: QuestionComment

http://stackoverflow.com/comment/82531454
score: 0
comment on: http://stackoverflow.com/q/47784166
type: Comment
has text: Not sure what you mean by .npy file. But yeah, you can store/hold an array as memmap and slice rows and columns out. The whole idea is to behave like a normal numpy-array without the need for all the memory. **But:** access patterns will matter! Slicing block-wise is good, while slicing small blocks / single values in high frequency is bad (in general). I would expect an outer ```np.random.shuffle()``` to be the worst kind of operation you can do. It will work, but you are slowed down by IO.
type: QuestionComment

http://stackoverflow.com/comment/82567207
type: AnswerComment
has text: Modifying `locals()` [doesn't work](https://ideone.com/Hv0Xwu). Please read the [docs](https://docs.python.org/3/library/functions.html#locals) before posting. That applies to answers as well as questions.
comment on: http://stackoverflow.com/a/47802868
type: Comment
score: 0

http://stackoverflow.com/comment/82446779
has text: How about `sudo python -m pip install numpy`? What you posted should make your `python36` executable work, but it's not clear to me that `python` refers to the same one.
score: 0
comment on: http://stackoverflow.com/q/47741873
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47819975
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/82602155
has body: you can use a classmethod as an alternate constructor and return what you want: class ABC: def __init__(self, a): self.a = a @classmethod def with_validation(cls, a): if a &gt; 5: return cls(a) return None a = ABC.with_validation(10) a &lt;__main__.ABC at 0x10ceec288&gt; a = ABC.with_validation(4) a type(a) NoneType
answers question: http://stackoverflow.com/q/47819741
score: 5
upvote count: 5

http://stackoverflow.com/comment/82367616
has text: why not inheriting your shape class instead? yes, you must read more abour OOP. You could also use a factory method to instanciate the proper class.
comment on: http://stackoverflow.com/q/47703730
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/47826740
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82617273
has comment: http://stackoverflow.com/comment/82616336
has answer: http://stackoverflow.com/a/47828750
tagged with: flask
has title: Flask cannot change the hostname
favorite count: 0
has comment: http://stackoverflow.com/comment/82616445
score: 1
tagged with: python
has answer: http://stackoverflow.com/a/47827533
type: Question
has body: I am trying to use flask integrate stripe checkout. It can startup fine for default port and 127.0.0.1/localhost. I try to change server host because localhost does not allow access from the remote server. But it does not work after I change. Would I know how to change it? Thanks a lot! details inform: Flask 0.12.2 Python 2.7.5 (default, May 3 2017, 07:55:04) My change: app = Flask(__name__) app.config['SERVER_NAME'] = '*:5000'
answer count: 2
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/47827901
has comment: http://stackoverflow.com/comment/82618974
answers question: http://stackoverflow.com/q/47827858
has comment: http://stackoverflow.com/comment/82618362
has comment: http://stackoverflow.com/comment/82618793
upvote count: 5
has body: Importing a module executes all module-level statements, including obj=test(). To avoid this, make an instance only when run as the main program, not when imported: class test(object): def __init__(self): print 'INIT of test class' if __name__ == '__main__': obj=test() The problem is not the inheritance but the import. In your case you execute obj=test() when importing: from test import test When you import test, its name __name__ is test. But when you run your program on the command line as main program with python test.py, its name is __main__. So, in the import case, you skip obj=test()if you use: if __name__ == '__main__': obj=test()
type: Answer
has comment: http://stackoverflow.com/comment/82618970
has comment: http://stackoverflow.com/comment/82618490
has comment: http://stackoverflow.com/comment/82618558
score: 5
accepted answer of: http://stackoverflow.com/q/47827858
has comment: http://stackoverflow.com/comment/82618422
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/82640959
has text: You have to "POST" forms, unless i missed something
score: 3
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47838575

http://stackoverflow.com/q/47823974
tagged with: python
type: UnansweredQuestion
has title: identifying valid url in python column pandas
tagged with: python-2.7
tagged with: pandas
has body: I have a dataframe which has URL column The valid URL should contain http://www.validurl.com. All other should be invalid URL I need to add another column which shows that URL is invalid ID URL 1 http://www.validurl.com/sports 2 http://www.validurl.com 3 Nan 4 http://www.invalidurl.com output should be ID URL Error message 1 http://www.validurl.com/sports 2 http://www.validurl.com 3 Nan Invalid 4 http://www.invalidurl.com Invalid
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/47824028
type: Question

http://stackoverflow.com/q/47842958
score: 0
upvote count: 1
has title: BeautifulSoup and if/else statements
has comment: http://stackoverflow.com/comment/82649989
answer count: 1
downvote count: 1
favorite count: 0
tagged with: beautifulsoup
type: Question
linked to: http://stackoverflow.com/q/9835762
type: UnansweredQuestion
has body: A am learning how to use BeautifulSoup and I have run into an issue with double printing in a loop I have written. Any insight would be greatly appreciated! from bs4 import BeautifulSoup import requests import re page = 'https://news.google.com/news/headlines?gl=US&amp;ned=us&amp;hl=en' #main page #url = raw_input("Enter a website to extract the URL's from: ") r = requests.get(page) #requests html document data = r.text #set data = to html text soup = BeautifulSoup(data, "html.parser") #parse data with BS for link in soup.find_all('a'): #if contains /news/ if ('/news/' in link.get('href')): print(link.get('href')) Examples: for link in soup.find_all('a'): #if contains cointelegraph/news/ #if ('https://cointelegraph.com/news/' in link.get('href')): url = link.get('href') #local var store url if '/news/' in url: print(url) print(count) count += 1 if count == 5: break output: https://cointelegraph.com/news/woman-in-denmark-imprisoned-for-hiring-hitman-using-bitcoin 0 https://cointelegraph.com/news/ethereum-price-hits-all-time-high-of-750-following-speed-boost 1 https://cointelegraph.com/news/ethereum-price-hits-all-time-high-of-750-following-speed-boost 2 https://cointelegraph.com/news/senior-vp-says-ebay-seriously-considering-bitcoin-integration 3 https://cointelegraph.com/news/senior-vp-says-ebay-seriously-considering-bitcoin-integration 4 For some reason my code keeps printing out the same url twice...
tagged with: python
has comment: http://stackoverflow.com/comment/82649957
has answer: http://stackoverflow.com/a/47843317
has comment: http://stackoverflow.com/comment/82649882

h2o
tags question: http://stackoverflow.com/q/47829169
tags question: http://stackoverflow.com/q/47747662
tag name: h2o
tags question: http://stackoverflow.com/q/47784467
type: Tag
tags question: http://stackoverflow.com/q/47703196
tags question: http://stackoverflow.com/q/47702323
tags question: http://stackoverflow.com/q/47773338

http://stackoverflow.com/q/47713771
has comment: http://stackoverflow.com/comment/82393012
tagged with: python
linked to: http://stackoverflow.com/q/19324453
has comment: http://stackoverflow.com/comment/82404821
has comment: http://stackoverflow.com/comment/82404672
tagged with: pandas
has body: I have the following dataframe df = pd.DataFrame(data=[np.nan,1.34,np.nan,1,3,np.nan,np.nan,4,5,2,3,4], index=[datetime.date(2015, 3, 31), datetime.date(2015, 3, 31), datetime.date(2015, 3, 31), datetime.date(2015, 3, 31), datetime.date(2015, 4, 1), datetime.date(2015, 4, 1), datetime.date(2015, 4, 1), datetime.date(2015, 4, 3), datetime.date(2015, 4, 3), datetime.date(2015, 4, 5), datetime.date(2015, 4, 5), datetime.date(2015, 4, 5)]) by running np.unique(df.index) I get array([datetime.date(2015, 3, 31), datetime.date(2015, 4, 1), datetime.date(2015, 4, 3), datetime.date(2015, 4, 5)], dtype=object) i.e. the dates datetime.date(2015, 4, 2) datetime.date(2015, 4, 4) are missing how can I shift the dates in order to have continuous dates? I d like to have: df df Out[28]: 0 2015-03-31 NaN 2015-03-31 1.34 2015-03-31 NaN 2015-03-31 1.00 2015-04-01 3.00 2015-04-01 NaN 2015-04-01 NaN 2015-04-02 4.00 2015-04-02 5.00 2015-04-03 2.00 2015-04-03 3.00 2015-04-03 4.00 where 2015-04-03 becomes 2015-04-02 and so on...
has comment: http://stackoverflow.com/comment/82404649
linked to: http://stackoverflow.com/q/47536243
tagged with: datetime
has comment: http://stackoverflow.com/comment/82397356
tagged with: dataframe
has title: shift up datetime dates to make the list of date continuous
type: Question
has comment: http://stackoverflow.com/comment/82387501
has comment: http://stackoverflow.com/comment/82404516
has comment: http://stackoverflow.com/comment/82392848
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82404804
score: 0
has comment: http://stackoverflow.com/comment/82389563

http://stackoverflow.com/q/47759956
has comment: http://stackoverflow.com/comment/82481522
has comment: http://stackoverflow.com/comment/82481334
upvote count: 1
score: 1
has title: How can I pass a jinja2 object to a jquery function as parameter?
tagged with: python
has comment: http://stackoverflow.com/comment/82481424
has comment: http://stackoverflow.com/comment/82481234
has body: In my python script, I have something like this students = getStudent() return render_template('index.html', students = students) students is a list of student, and each student has attributes like name, id, gpa, .... In index.html, I have a selection like this &lt;select class="form-control" onchange="changeStudent"&gt; {% for student in students %} &lt;option&gt;{{student.name}}&lt;/option&gt; {% endfor %} &lt;/select&gt; Now I want to implement a jquery function that can do can for example print out the student information if that student is selected. function changeStudent(student) { alert(student.name) } How can I do that? Thanks in advance.
favorite count: 0
type: Question
type: UnansweredQuestion
answer count: 1
downvote count: 0
tagged with: javascript
tagged with: jquery
has answer: http://stackoverflow.com/a/47760148
tagged with: jinja2
has comment: http://stackoverflow.com/comment/82481306

http://stackoverflow.com/a/47766776
has comment: http://stackoverflow.com/comment/82494653
score: 1
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/47766734
has comment: http://stackoverflow.com/comment/82494807
downvote count: 0
has body: You need remove [] by strip: pd.to_datetime(data['visited_at'].str.strip('[]'), errors = 'coerce') data['visited_at'] = pd.to_datetime(data['visited_at'].str.strip('[]'), errors = 'coerce') print (data) Index id user_id merchant_id \ 0 68989 68990 13277 38 437 2016-04-11 00:00:00 1 403557 403558 195246 179 2218 2017-06-09 00:00:00 2 333381 333382 127359 514 1820 2017-04-24 00:00:00 3 511815 511816 151653 259 1136 2017-08-05 00:00:00 4 167172 167173 51546 32 363 2016-08-05 00:00:00 marketing_email_id start_date end_date email_status \ 0 68989 68990 13277 2016-04-16 00:00:00 1 NaN 1 403557 403558 195246 2017-06-12 00:00:00 0 1.0 2 333381 333382 127359 2017-05-01 00:00:00 0 1.0 3 511815 511816 151653 2017-08-08 00:00:00 0 1.0 4 167172 167173 51546 2016-08-15 00:00:00 1 NaN sms_status created_at visited_at 0 68989 68990 13277 2016-04-11 11:05:31 NaT 1 403557 403558 195246 2017-06-09 06:01:04 NaT 2 333381 333382 127359 2017-04-24 10:00:33 2017-04-24 3 511815 511816 151653 2017-08-05 11:31:19 NaT 4 167172 167173 51546 2016-08-05 12:00:43 NaT Another solution is check if not empty df with select first value by [0] with if-else: def visiter(d,visits): visit = visits[d.start_date:d.end_date] out=visit[(visit['user_id'] == d.user_id)&amp;(visit['merchant_id']==d.merchant_id)].head(1) out = np.nan if out.empty else out.index.date[0] return (out)
has comment: http://stackoverflow.com/comment/82494704

http://stackoverflow.com/comment/82577632
type: Comment
score: 0
type: QuestionComment
has text: does that work if I need to interact with the database in that template?
comment on: http://stackoverflow.com/q/47808181

http://stackoverflow.com/comment/97371451
comment on: http://stackoverflow.com/a/48712298
has text: arcgis still times out after several hundred records. I am a fair newbie at python and would like to know a method to catch this error and keep going
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/47798172
tagged with: kdb+
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/47799145
tagged with: python
has title: PyQ - casting datatypes to empty tables
has body: In PyQ I can create a dictionary and transpose it with flip to get a table... q.set(':alpha', q('!', ["Name", "Ask", "Bid", "Time"], ()).flip) However, as expected, when I load it in q and retrieve the meta data it shows the char type for all of the columns as symbols... &gt;&gt;&gt; q.get(':alpha').show() Name Ask Bid Time --------------------------------------------------------------- "BTC" "16351.0" "16350.0" "2017-12-12T17:32:33.09" "ETH" "589.89999993" "585.25" "2017-12-12T17:32:32.697" "LTC" "297.0" "296.29570358" "2017-12-12T17:32:32.353" "BTC" "16355.0" "16351.0" "2017-12-12T17:32:44.777" "ETH" "589.89999993" "585.25" "2017-12-12T17:32:42.15" "LTC" "297.99940398" "296.29570359" "2017-12-12T17:32:44.433" "BTC" "16359.99999998" "16350.0" "2017-12-12T17:32:53.713" "ETH" "589.89999993" "585.2500001" "2017-12-12T17:32:53.197" "LTC" "297.99940398" "295.0" "2017-12-12T17:32:51.37" "BTC" "16355.0" "16350.0" "2017-12-12T17:33:02.433" "ETH" "585.2500001" "585.25" "2017-12-12T17:33:03.497" "LTC" "297.99940397" "295.0" "2017-12-12T17:33:01.463" &gt;&gt;&gt; q() q)\l alpha `alpha q)meta alpha c | t f a ----| ----- Name| s Ask | s Bid | s Time| s q) Which I believe is what's causing the 'type error to be thrown by the console when I perform the following queries... q)select Name, max Ask, max Bid, Time from alpha 'type q)select max Ask, max Bid, Time by Name from alpha 'type q)select from alpha where Bid=(max;Bid) fby Name 'type q)select from alpha where Name=`BTC Name Ask Bid Time ----------------- I know in q I can issue the following command to achieve this... q)alpha:([]Name:`symbol$(); Ask:`float$(); Bid:`float$(); Time:`datetime$()) q)meta alpha c | t f a ----| ----- Name| s Ask | f Bid | f Time| z q) What is the correct syntax to define the char type for each column in PyQ?
has answer: http://stackoverflow.com/a/47799145
tagged with: pyq
score: 2
accepted answer: http://stackoverflow.com/a/47847416
type: AnsweredQuestion
tagged with: python-3.x
answer count: 2
has answer: http://stackoverflow.com/a/47847416
upvote count: 2
downvote count: 0

http://stackoverflow.com/a/52066332
answers question: http://stackoverflow.com/q/47705573
upvote count: 3
score: 3
downvote count: 0
type: Answer
has body: Using a nested context manager within __enter__ seems magical. Check this out: class Enter(object): def __init__(self, times): self.times = times def __enter__(self): print('entering {}'.format(self.times)) if self.times: with Enter(self.times - 1) as tup: # WRONG print('returning {}'.format(tup)) return tup + (self.times,) print('returning () from times={}'.format(self.times)) return () def __exit__(self, *_): print('exiting {}'.format(self.times)) with Enter(3) as tup: print(tup) Running this prints entering 3 entering 2 entering 1 entering 0 returning () from times=0 returning () exiting 0 returning (1,) exiting 1 returning (1, 2) exiting 2 (1, 2, 3) exiting 3 I think it makes sense on some level. The mental model could be, when you call with Enter(3) ..., that must "finish" the __enter__ method, and "finish" means enter and exit all context managers. def foo(): with Enter(2) as tup: return tup # we expect Enter to exit before we return, so why would it be different when # we rename foo to __enter__? Let's do this explicitly. In [3]: %paste class Enter(object): def __init__(self, times): self.times = times self._ctx = None def __enter__(self): print('entering {}'.format(self.times)) if self.times: self._ctx = Enter(self.times - 1) tup = self._ctx.__enter__() return tup + (self.times,) else: return () def __exit__(self, *_): if self._ctx is not None: self._ctx.__exit__() print('exiting {}'.format(self.times)) In [4]: with Enter(3) as tup: ...: print(tup) ...: entering 3 entering 2 entering 1 entering 0 (1, 2, 3) exiting 0 exiting 1 exiting 2 exiting 3 (Answered with guidance from @jasonharper.)

http://stackoverflow.com/a/75086529
score: 0
answers question: http://stackoverflow.com/q/47777308
type: Answer
has body: Following from a comment by @jordanm, this is likely due to the cache file being created using a different python interpreter version than the one reading it. Make sure you are writing and reading using the same interpreter version. In my case, since the writing code is also the reading code, simply deleting the cache file was enough (thus re-creating it with the correct version).

http://stackoverflow.com/comment/82535350
has text: Please either update your question with more detail or post a question more specific to the problem you're encountering.
comment on: http://stackoverflow.com/q/47786637
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47701246
has comment: http://stackoverflow.com/comment/82362615
has comment: http://stackoverflow.com/comment/82364544
has comment: http://stackoverflow.com/comment/82363721
favorite count: 0
has answer: http://stackoverflow.com/a/47702588
has title: Procedure in if loop not working even though condition is met
type: AnsweredQuestion
tagged with: if-statement
has comment: http://stackoverflow.com/comment/82362463
score: -2
has comment: http://stackoverflow.com/comment/82362760
tagged with: python
has comment: http://stackoverflow.com/comment/82362560
linked to: http://stackoverflow.com/q/20449427
has comment: http://stackoverflow.com/comment/82363612
linked to: http://stackoverflow.com/q/15112125
accepted answer: http://stackoverflow.com/a/47702588
type: Question
has body: I have made this code to emulate a rock paper scissors game. I have a procedure which has the main game, and when I run this by itself without the if loop at the end, it works. However, when I try to validate whether or not the user entry is numerical, it does not print the correct message. Here is the full code: import random def game(choice): number = random.randint(1,3) if choice == 1 and number == 2: print("You lose.") if choice == 1 and number ==3: print("You win.") if choice == 1 and number == 1: print("It is a draw") if choice == 2 and number == 3: print("You lose.") if choice == 2 and number ==1: print("You win.") if choice == 2 and number == 2: print("It is a draw") if choice == 3 and number == 1: print("You lose.") if choice == 3 and number ==2: print("You win.") if choice == 3 and number == 3: print("It is a draw") x = input("Choose 1 (rock), 2 (paper) or 3 (scissors).") digit = x.isdigit() if digit == True: game(x) By the way, there is no error message, the procedure just does not work!
upvote count: 0
duplicate of: http://stackoverflow.com/q/20449427
downvote count: 2
answer count: 1

http://stackoverflow.com/q/47808377
possible better answer: http://stackoverflow.com/a/56445576
has title: How to change checkpoint interval in Yolo 2 (darflow) python?
has answer: http://stackoverflow.com/a/56445576
tagged with: darkflow
tagged with: python
type: AnsweredQuestion
score: 0
answer count: 2
accepted answer: http://stackoverflow.com/a/49393826
has answer: http://stackoverflow.com/a/49393826
has body: I'm Training Yolo2 (darkflow) and want to change the interval (e.g. every 100 steps) to make checkpoints. Train command: python flow --model cfg/yolo.cfg --load bin/yolo.weights --train --annotation train/XML --dataset train/Images Something like this: --set ckpt 100 I could not find the command. Thank you !
type: Question

http://stackoverflow.com/q/47844741
tagged with: pyqt4
tagged with: python
has comment: http://stackoverflow.com/comment/82662572
has answer: http://stackoverflow.com/a/47846790
accepted answer: http://stackoverflow.com/a/47846790
has title: PyQt4: How to color each tab in QTabWidget separately?
type: AnsweredQuestion
score: 0
tagged with: pyqt
has comment: http://stackoverflow.com/comment/82659909
answer count: 1
linked to: http://stackoverflow.com/q/12901095
type: Question
tagged with: python-3.x
has body: I'm working on a project with a GUI, for which I am using Python with PyQt4 module. Here is my demo code: import sys from PyQt4 import QtGui, QtCore class Window(QtGui.QMainWindow): def __init__(self): super(Window, self).__init__() self.setWindowTitle('PyQt4 demo') self.setGeometry(50, 50, 1000, 1000) self.createTabs() self.styleTabs() self.show() def createTabs(self): '''Creates a QTabWidget with 5 tabs, named 1, 2, 3, 4, 5 ''' self.tabs = QtGui.QTabWidget(self) self.tabs.resize(1000, 1000) contents1 = QtGui.QWidget() contents2 = QtGui.QWidget() contents3 = QtGui.QWidget() contents4 = QtGui.QWidget() contents5 = QtGui.QWidget() self.tabs.addTab(contents1, '1') self.tabs.addTab(contents2, '2') self.tabs.addTab(contents3, '3') self.tabs.addTab(contents4, '4') self.tabs.addTab(contents5, '5') def styleTabs(self): #Would like to add some code here which colors #each tab with a different color. pass def run(): app = QtGui.QApplication(sys.argv) GUI = Window() sys.exit(app.exec_()) run() Most objects (including QtabWidget and QTabBar) support styling with CSS using .setStyleSheet(str) method. But with this I could only achieve coloring all tabs with the same color. I've also found a way to color selected, first, last tab, but could never achieve coloring a tab for ex.: with an index of 2. For example: self.tabs.setStyleSheet(''' QTabBar::tab {background-color: green;} QTabBar::tab:selected {background-color: red;} QTabBar::tab:first {background-color: red;} QTabBar::tab:last {background-color: red;} ''') I've also tried applying color to current QTabBar. This works with Qt, but not with PyQt apparently: tab = self.tabs.tabBar() tab.setStyleSheet('background-color: grey;') The PyQt4 coloring methods didn't work either: plt = QtGui.QPalette() clr = QtGui.QColor() clr.setRgb(100, 100, 100) plt.setColor(10, clr) tab.setPalette(plt) I've been searching on web a lot, but haven't found any solutions for this problem. At this point, I'm not even sure an easy solution exists. Is…
tagged with: qtabwidget

http://stackoverflow.com/a/47716279
has comment: http://stackoverflow.com/comment/82780468
has comment: http://stackoverflow.com/comment/82781550
has comment: http://stackoverflow.com/comment/82781659
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82769991
answers question: http://stackoverflow.com/q/47710581
type: Answer
accepted answer of: http://stackoverflow.com/q/47710581
score: 0
has body: try this Replace links = dict((next(count) + 1, e) for e in elements) desc_links = sorted(links.items(), key=operator.itemgetter(1)) for link in desc_links: driver.get(link[1]) print(f'At Page: {link[0]}') With import collections links = dict((next(count) + 1, e) for e in elements) desc_links = collections.OrderedDict(sorted(links.items(), reverse=True)) for key, value in desc_links.items(): driver.get(value) print('At Page: ' + str(key))

http://stackoverflow.com/a/48108114
score: 0
accepted answer of: http://stackoverflow.com/q/47855836
has body: Unfortunately, you cannot patch it to work with timestamps because that is the internal implementation of Google's Apache Beam runner: Dataflow. So you will have to wait until this is fixed by Google (should this be identified as a bug). Please, report it as soon as possible because this is more a limitation of Python's version used rather than a bug. The problem comes from strftime as you can see in the error. The documentation explicitly mentions it won't work with any year prior to 1900. A workaround, on your end though, is to convert the timestamp to a string (you can do this in BigQuery as specified in the documentation). And then in your Beam pipeline you can reconvert it again to some timestamp or whatever suits you best. You also have an example on how to convert a datetimeobject to a string as the template of your error in answer. In the same question there is another answer that explains what has happened with this bug and how has it been solved (in Python) and what you can do. Unfortunately, the solution seems to avoid using strftime at all, and use some alternative instead.
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/47855836

http://stackoverflow.com/a/47791880
type: Answer
answers question: http://stackoverflow.com/q/47791384
has comment: http://stackoverflow.com/comment/82546700
downvote count: 0
upvote count: 1
has body: There are few wrong issues with your approach. Your photo_tag method should be a property method, or eventually cached_property method. For displaying safely HTML code you should use the method format_html provided by Django. Here is how I'd refactor your code: models.py from django.db import models from django.utils.html import format_html from django.utils.functional import cached_property class Photo(models.Model): name = models.CharField(max_length=100, null=False) photo = models.ImageField(upload_to="photos/", null=True) # better use blank=True instead of null=True for ImageField @cached_property def photo_tag(self): if self.photo: return format_html( '&lt;a href="{img}"&gt;&lt;img src="{img}"&gt;&lt;/a&gt;', img=self.photo.url ) return None # or better return '' if you use blank=True photo_tag.short_description = 'Photo of prescription' class Prescription(models.Model): description = models.CharField(max_length=100, null=True) photo = models.ForeignKey(Photo, related_name='related_photo', null=True) def __str__(self): return self.description Now you can use photo_tag as a property of Photo and bind the HTML safe in your admin.
score: 1

http://stackoverflow.com/comment/82778590
type: QuestionComment
comment on: http://stackoverflow.com/q/47854129
score: 0
has text: *I am having issues with the following:* And what is the issue? Your question is not very clear, please rephrase it.
type: Comment

http://stackoverflow.com/a/47798261
has body: The pygame.transform.rotate function returns a new surface and doesn't modify the original image, so you have to assign it to the self.image attribute. Afterwards you have to create a new rect with self.image.get_rect so that the sprite stays centered. The next problem is the rotation speed. The rot attribute is the current angle which you have to update by the rot_speed each frame, e.g. self.rot += self.rot_speed. I'd also move the event handling to the update method and just pass the desired rot_speed to the rotate method. In the update method the self.acc += self.vel * PLAYER_FRICTION and self.image0 = self.image were causing erroneous behavior, so I removed them. Here's a fixed minimal and complete version: import pygame from pygame.math import Vector2 as Vec WIDTH, HEIGHT = 640, 480 PLAYER_FRICTION = .95 PLAYER_ACC = .1 class Player(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) self.image = pygame.Surface((30, 50), pygame.SRCALPHA) self.image.fill(pygame.Color('dodgerblue1')) self.image0 = self.image self.rect = self.image.get_rect() self.pos = Vec(WIDTH / 2, HEIGHT / 2) self.vel = Vec(0, 0) self.acc = Vec(0, 0) self.rot = 0 self.rot_speed = 3 self.last_update = pygame.time.get_ticks() def rotate(self, rot_speed): self.rot += rot_speed # Change `self.rot` (the angle). # Rotate the original image. self.image = pygame.transform.rotate(self.image0, self.rot) # Get a new rect with the center of the old rect. self.rect = self.image.get_rect(center=self.rect.center) def update(self): self.acc = Vec(0, 0) keys = pygame.key.get_pressed() if keys[pygame.K_LEFT]: self.acc.x = -PLAYER_ACC if keys[pygame.K_RIGHT]: self.acc.x = PLAYER_ACC if keys[pygame.K_UP]: self.acc.y = -PLAYER_ACC if keys[pygame.K_DOWN]: self.acc.y = PLAYER_ACC # Call self.rotate with the desired speed. if keys[pygame.K_z]: self.rotate(self.rot_speed) if keys[pygame.K_c]: self.rotate(-self.rot_speed) # apply translations self.vel += self.acc self.vel *= PLAYER_FRICTION s…
type: Answer
accepted answer of: http://stackoverflow.com/q/47797253
answers question: http://stackoverflow.com/q/47797253
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/82561767

http://stackoverflow.com/a/47742317
downvote count: 0
upvote count: 1
type: Answer
has body: Negative lookahead is indispensable if you want to match something not followed by something else. When explaining character classes, this tutorial explained why you cannot use a negated character class to match a q not followed by a u. Negative lookahead provides the solution: q(?!u). The negative lookahead construct is the pair of parentheses, with the opening parenthesis followed by a question mark and an exclamation point. Inside the lookahead, we have the trivial regex u. Positive lookahead works just the same. q(?=u) matches a q that is followed by a u, without making the u part of the match. The positive lookahead construct is a pair of parentheses, with the opening parenthesis followed by a question mark and an equals sign. Regex lookahead, lookbehind and atomic groups
answers question: http://stackoverflow.com/q/47742275
score: 1

http://stackoverflow.com/a/61768005
answers question: http://stackoverflow.com/q/47703486
has body: you can solve this error by doing below network = osm.network_from_bbox(bbox[0], bbox[1], bbox[2], bbox[3]) network=pandana.Network(network[0]["x"],network[0]["y"], network[1]["from"], network[1]["to"], network[1]"distance") lcn = network.low_connectivity_nodes(impedance=1000, count=10, imp_name='distance') network.save_hdf5(net_filename, rm_nodes=lcn) #remove low-connectivity nodes and save to h5
score: 0
type: Answer

http://stackoverflow.com/q/47807426
answer count: 2
accepted answer: http://stackoverflow.com/a/47807497
downvote count: 0
upvote count: 1
tagged with: python
tagged with: string
has comment: http://stackoverflow.com/comment/82576249
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47807497
has comment: http://stackoverflow.com/comment/82576069
tagged with: pandas
score: 1
has title: How to test which cell in a pandas dataframe string column contains a substring of a given reference string?
has comment: http://stackoverflow.com/comment/82576094
has answer: http://stackoverflow.com/a/47809230
tagged with: substring
possible better answer: http://stackoverflow.com/a/47809230
favorite count: 0
type: Question
has body: I am dealing with a pandas dataframe that looks like this: 0 Item Category 1 Hammer A 2 Car A 3 Cardiologist B 4 Park A 5 Parkway A 6 CarparkCar A I need to find all cells in Item that contain a specific sequence of letters, defined as substring of my reference word. I am not interested in cells that contain additional letters not present in my reference word. reference_word = Carpark Desired output: 0 Item Category Contains_substring_of_reference_word 1 Hammer A FALSE 2 Car A TRUE 3 Cardiologist B FALSE 4 Park A TRUE 5 Parkway A FALSE 6 CarparkCar A TRUE How to check which cell of a pandas dataframe column contains a substring of a given word/string?

http://stackoverflow.com/comment/98197939
has text: Anytime, check my post, I tagged you there: https://stackoverflow.com/a/55537459/11050796
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/55316950

http://stackoverflow.com/a/47839019
upvote count: 2
has body: You can just use df = pd.DataFrame({'Access Message': access, 'Number': number}) which yields the desired outcome Access Message Number 0 denied 21 1 Try Again 44 If you actually want to append to an existing dataframe as @Tim mentioned in the comments, you can do for ni, aci in zip(number, access): df = df.append({'Access Message': aci, 'Number': ni}, ignore_index=True) which gives (I just appended to df which I created above) Access Message Number 0 denied 21 1 Try Again 44 2 denied 21 3 Try Again 44 But I guess what would be more efficient for huge lists is to use concat (as also @Wen suggests in the comments): append_me = pd.DataFrame(zip(number, access)).rename(columns={0: 'Number', 1: 'Access Message'}) df = pd.concat([df, append_me]) which gives (I again just appended to the previous dataframe) Access Message Number 0 denied 21 1 Try Again 44 2 denied 21 3 Try Again 44 0 denied 21 1 Try Again 44
downvote count: 0
has comment: http://stackoverflow.com/comment/82642322
has comment: http://stackoverflow.com/comment/82642049
has comment: http://stackoverflow.com/comment/82642103
has comment: http://stackoverflow.com/comment/82642368
type: Answer
answers question: http://stackoverflow.com/q/47838998
has comment: http://stackoverflow.com/comment/82642444
score: 2

http://stackoverflow.com/comment/82641088
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47838440
has text: Thanks for the reply @Wen! When I try that, I get this: <bound method Series.value_counts of Series([], Name: data, dtype: float64)> Seems to be telling me my data is still float64, even though I imported it as a string...?

http://stackoverflow.com/q/47788471
upvote count: 0
tagged with: srcset
answer count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/47788757
favorite count: 0
has body: I'm trying to extract srcset attribute of a img tag using pyquery &amp; python3. &lt;img alt="my-image" srcset="//url/i/need/to/extract"&gt; Extracting alt attribute works like expected, and returns "my-image" (".item-thumb img").attr('alt') But this method doesn't work for the attribute srcset. It returns None (".item-thumb img").attr('srcset') #doesn't work (".item-thumb img").attr.srcset #doesn't work How to solve this? If there is no built-in way, may be a regular expression? Thanks.
type: Question
tagged with: pyquery
type: UnansweredQuestion
tagged with: python
score: -1
has title: Pyquery get value of "srcset" attribute

http://stackoverflow.com/a/47749287
has comment: http://stackoverflow.com/comment/82459263
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82459427
has comment: http://stackoverflow.com/comment/82459305
has comment: http://stackoverflow.com/comment/82458826
type: Answer
accepted answer of: http://stackoverflow.com/q/47749219
has comment: http://stackoverflow.com/comment/82459382
has body: Try (^\s*)?\{\{\s*([A-Za-z_]+)\s*\}\}. The only difference is a single ?. The problem with (^\s*) is that the ^ is not optional.
downvote count: 0
answers question: http://stackoverflow.com/q/47749219
score: 1
upvote count: 1

http://stackoverflow.com/q/47698728
tagged with: python
accepted answer: http://stackoverflow.com/a/47700063
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/47700063
answer count: 1
type: Question
has body: I'm using Fysom to create a finite state machine in Python, and I'm seeing one issue which I don't know why it's happening. I create a MyClass class, and inside that class I create a self.fsm member which is an instance of Fysom. For some reason, the fsm member of my class seems to not exist when the first state of the finite state machine is reached. But when the second state is reached, it does exist. from fysom import Fysom class MyClass(object): def __init__(self): self.fsm = Fysom({ 'initial': 'start', 'events': [ { 'src': 'start', 'name': 'go', 'dst': 'end' } ], 'callbacks': { # States callbacks 'onstart': self.on_start_callback, 'onend': self.on_end_callback, # Events callbacks 'onbeforego': self.show_event } }) def on_start_callback(self, event): print "state: start" print "self attrs: {}".format(self.__dict__) def on_end_callback(self, event): print "state: end" print "self attrs: {}".format(self.__dict__) def show_event(_, event): print "event: {}".format(event.event) def main(): instance = MyClass() instance.fsm.go() if __name__ == "__main__": main() And this is the output: state: start self attrs: {} event: go state: end self attrs: {'fsm': &lt;fysom.Fysom object at 0x7fe948f11510&gt;} Why the fsm member of MyClass doesn't exists when the initial state (start) is reached? Is not supposed to be created and initialized at the class constructor __init__? My guess is that the on_start_callback (which is the callback for the initial state of the finite state machine) is called when the Fysom instance is being created and before it's assigned to the fsm member, therefore it fails when trying to access self.fsm. Is that what actually happens and is that the correct behavior? I have found a workaround for that issue by creating an initial state that does nothing (or at least it doesn't access self at all) and then from the main function I manually trigger the event that transits to the real initial state which does access self (at that point is already defined).
has title: State callback function being called before Fysom initialization from inside a class

http://stackoverflow.com/a/48395538
accepted answer of: http://stackoverflow.com/q/47827812
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/47827812
has body: Ok I finally got the answer to this. below is a picture of the code in context for Odoo 10: No "def" of "for record" needed: the code will not run. I just hope this will be helpful to someone else... Kazu

http://stackoverflow.com/a/47749759
downvote count: 1
score: -1
has body: Your question is a duplicate of How to read/process command line arguments? You can find more details there, or use the following code: import sys def main(): for arg in sys.argv[1:]: print "Given argument is ", arg #_main_ should be __main__ if __name__ == "__main__": main()
upvote count: 0
answers question: http://stackoverflow.com/q/47749674
type: Answer

http://stackoverflow.com/comment/82648595
has text: Need to comment out import as well, in UserProfile model file check my update
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47835294
type: Comment

http://stackoverflow.com/q/47727129
type: UnansweredQuestion
tagged with: imap
tagged with: python
has answer: http://stackoverflow.com/a/47727410
tagged with: imapclient
has body: I am working on my own email client app. And currently, when a user adds a new mailbox, I make them to input IMAP server name manually (say, imap.gmail.com). By I've notices that there are mail client apps that somehow figure out the correct IMAP server name automatically. So the question is, is there any database or something, that would take login as input and return IMAP server name as output? If this is important, I am using Python (Django) and MySQL on the backend.
score: 0
answer count: 1
has title: Automatically determining IMAP server name by email address
type: Question

http://stackoverflow.com/a/47776225
score: 2
has comment: http://stackoverflow.com/comment/82519754
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82513534
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47775763
upvote count: 2
has body: It looks like what you're asking for is a reduction along a particular axis: this can be done using the reduce method of any binary ufunc. For example: &gt;&gt;&gt; x = np.array([[1,1,1], [2,1,3], [2,2,2]], dtype=float) &gt;&gt;&gt; np.divide.reduce(x, axis=1) array([ 1. , 0.66666667, 0.5 ])
answers question: http://stackoverflow.com/q/47775763
type: Answer

http://stackoverflow.com/comment/82531911
type: AnswerComment
score: 0
type: Comment
has text: @spikespaz. No, `__call__` is the decorator. It accepts `func`. Its return value is the decorated function. It can return its input unchanged just like the decorator I described in my answer. A class form decorator has all the same bits as the decorator faactory, just arranged so that there is one less level of nesting.
comment on: http://stackoverflow.com/a/47784164

http://stackoverflow.com/a/48793387
answers question: http://stackoverflow.com/q/47825542
score: 3
upvote count: 3
downvote count: 0
type: Answer
has body: Should do the same thing as above. import mdtraj as md pdbfile='1ABZ.pdb' traj=md.load_pdb(pdbfile) print traj.xyz[0]

http://stackoverflow.com/comment/82645361
type: QuestionComment
score: 0
has text: Well, you can just use `str.strip`, `str.lower` etc directly, no need for lambda. All methods still exist as attributes that are function objects in the class namespace.
comment on: http://stackoverflow.com/q/47840467
type: Comment

http://stackoverflow.com/q/47842368
tagged with: smtp
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82648881
linked to: http://stackoverflow.com/q/26697565
has comment: http://stackoverflow.com/comment/82648879
tagged with: python
has title: SMTPAuthenticationError; Username and Password not accepted
tagged with: gmail
has answer: http://stackoverflow.com/a/60903525
type: UnansweredQuestion
answer count: 1
downvote count: 0
tagged with: django
upvote count: 1
has body: I'm following along with this book and in chapter 18 part of the current assignment involves sending an email via Django. I have a yearly domain I use for testing, and rather than pay an additional 5$ a month I figured I'd just have the emails forwarded to an existing address, using these instructions. I then went ahead and set it up so I could send mail using an alias via the Sending mail from your forwarded email address section However, I'm unable to get it working using the generated app password + alias. When I try to send an email from the page it only works if 2FA is disabled and I use my actual gmail credentials, say for example: EMAIL_HOST_USER = 'bob@gmail.com' EMAIL_HOST_PASSWORD = 'bobswife123' It works as intended. However, lets say I wanted to use my generated app password and alias, something like: EMAIL_HOST_USER = 'alias@bob.com' EMAIL_HOST_PASSWORD = 'bobsmistress123' Then I'll get the following error: Was not able to make any use of the support article from the URL in the above screenshot, but here it is for the sake of convenience: https://support.google.com/mail/?p=BadCredentials Anyways, these are the exact steps I'm taking: From terminal on macOS 10.13.1, I run python manage.py runserver from terminal, and then enter http://localhost:8000/ into Google Chrome. The page displays correctly. I hit enter and try to send the email. Next, it either works, or I get the screenshot shown above. Here's a dpaste of the traceback: http://dpaste.com/2DVFSPK other potentially relevant settings: EMAIL_HOST = 'smtp.gmail.com EMAIL_PORT = 465 EMAIL_USE_SSL = True Any help is greatly appreciated! Regarding the duplication accusation: I have already tried the accepted answer's instructions from the potential duplicate. Once again, I can get this to work by using my normal Gmail credentials -- but I don't want to reveal my personal email address, which is why I setup an alias using these instructions. This should allow me to send emails on behalf of the alias doma…
score: 1

http://stackoverflow.com/comment/82409803
comment on: http://stackoverflow.com/q/47724417
type: Comment
type: QuestionComment
score: 0
has text: i read the python api on turtle graphics... say for example, you are creating a listener() for key events, i used both screen.listen and turtle.listen and both work. wondering if there's a difference...

http://stackoverflow.com/comment/82531326
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47784721
type: Comment
has text: I'm not entirely sure. If you have a suggestion I'm willing to try anything at this point. I tried the for item in descriptionArray: outfile.write(item + '\n') and it came back with an error. unsupported operand type(s) for +: 'int' and 'str'

http://stackoverflow.com/comment/82630001
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47818706
has text: How can we help you if we don't know what you have already tried?
type: Comment

http://stackoverflow.com/q/47732711
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/47835130
tagged with: discord
has title: Find all User's UserID in a server
type: Question
accepted answer: http://stackoverflow.com/a/47835130
answer count: 1
has body: How would I find and store all of the users UserID's in a discord server? @client.event async def on_message(message): if message.content.startswith("##kickrandom"): await client.send_message(message.channel, "Kicking a random user in 30 seconds...")
tagged with: python

http://stackoverflow.com/comment/82601785
type: QuestionComment
comment on: http://stackoverflow.com/q/47819805
type: Comment
has text: Beyond that -- we need a [mcve] before we can provide a canonical and complete answer to your question. Right now, you haven't provided anything we can copy-and-paste to see the error you're experiencing ourselves, so we don't know the details of the problem. Maybe your `IFS` contains a character present in the `SD` variable, maybe `SD` has a hidden/non-printable character and/or a control character that moves the cursor around, maybe there's something else going on -- without a reproducer, all we can do is guess.
score: 1

http://stackoverflow.com/comment/82491086
type: AnswerComment
has text: this is a free-range kind of "get help if you're stuck" type kind of project. Thanks for the help though! I got it working using some of your techniques. And yea, as you were saying, checking for collision has proved very hard. Mainly because the turtle always detects the rect it just created behind it! Anyway, thanks for your help
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47726711

http://stackoverflow.com/comment/82577362
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47801331
has text: You need to add the column for it. But first is shorter so why not. Consider marking this as accepted if it answered the question.

http://stackoverflow.com/q/47851935
has title: Finding lowest element in every row of a nested list
has comment: http://stackoverflow.com/comment/82668288
has comment: http://stackoverflow.com/comment/82668811
has comment: http://stackoverflow.com/comment/82668164
tagged with: python-3.x
favorite count: 0
type: Question
has body: I have a nested list which looks like this. [[0.0, 1.4142135623730951, 2.8284271247461903, 2.23606797749979], [1.4142135623730951, 0.0, 1.4142135623730951, 1.0], [2.8284271247461903, 1.4142135623730951, 0.0, 1.0], [2.23606797749979, 1.0, 1.0, 0.0]] I want to find the minimum element in every sub list. Thanks for the help!
answer count: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/82668321
score: -3
has comment: http://stackoverflow.com/comment/82685251
tagged with: python
downvote count: 5
possible better answer: http://stackoverflow.com/a/47851945
has comment: http://stackoverflow.com/comment/82668447
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47851945
accepted answer: http://stackoverflow.com/a/47851971
has comment: http://stackoverflow.com/comment/82668512
has answer: http://stackoverflow.com/a/47851971
has comment: http://stackoverflow.com/comment/82668834

http://stackoverflow.com/q/47762287
upvote count: 1
score: 1
answer count: 1
tagged with: quantization
tagged with: tensorflow
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: python
has body: I have been using this simple script to dump out a .pb graph to load up in tensorboard for looking at: import sys import os import os.path import tensorflow as tf from tensorflow.python.platform import gfile model_filename = sys.argv[1] output_dirname = sys.argv[2] if not os.path.exists(output_dirname): os.makedirs(output_dirname) with tf.Session() as sess: with gfile.FastGFile(model_filename, 'rb') as f: graph_def = tf.GraphDef() graph_def.ParseFromString(f.read()) _ = tf.import_graph_def(graph_def, name='') writer = tf.summary.FileWriter(output_dirname, tf.get_default_graph()) writer.close() This works great for visualizing what happens in the graph if you use the graph transform tool up through at least TF 1.2. When I recently tried master, I get the following problem (using https://storage.googleapis.com/download.tensorflow.org/models/inception_dec_2015.zip as the graph for example): bazel-bin/tensorflow/tools/graph_transforms/transform_graph \ --in_graph=tensorflow_inception_graph.pb \ --out_graph=inception_v3_quantized.pb \ --inputs="Mul" \ --outputs='softmax' \ --transforms='add_default_attributes strip_unused_nodes(type=float, shape="1,299,299,3") remove_nodes(op=Identity, op=CheckNumerics) fold_constants(ignore_errors=true) fold_batch_norms fold_old_batch_norms quantize_weights quantize_nodes strip_unused_nodes sort_by_execution_order' python dump_for_tensorboard.py inception_v3_quantized.pb /tmp/dump_logdir On Tensorflow 1.2 and earlier, this works fine. I get a directory that I can point tensorboard at. But on master I get this: 2017-12-11 15:56:39.159333: I tensorflow/core/platform/cpu_feature_guard.cc:137] Your CPU supports instructions that this TensorFlow binary was not compiled to use: SSE4.1 SSE4.2 AVX AVX2 FMA Traceback (most recent call last): File "../dump_for_tensorboard.py", line 16, in &lt;module&gt; _ = tf.import_graph_def(graph_def, name='') File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/importer.py", line 369, in i…
has answer: http://stackoverflow.com/a/47932240
downvote count: 0
has title: Tensorflow Graph Transform Tool quantize_nodes references nonexistant "hat" node names?

http://stackoverflow.com/comment/82490752
comment on: http://stackoverflow.com/a/47747466
score: 0
type: Comment
has text: I didn't think of this! I'll try it when I am able to but I'm marking this as solution since I'm pretty sure this is what it is.
type: AnswerComment

http://stackoverflow.com/q/47808277
tagged with: django
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/82577987
has answer: http://stackoverflow.com/a/47808278
has comment: http://stackoverflow.com/comment/82581592
score: 1
answer count: 1
has title: How to set index page with path function in django 2.0?
favorite count: 0
type: Question
tagged with: django-2.0
type: UnansweredQuestion
has body: Django 2.0 has introduced new path function in django.urls. So I m using path function to set my index page but as far as I know it doesn't accept regular expression.I have tried couple of options as follows path('/',views.index,name='index'), and path('/index',views.index,name='index'), but it gives 404 page not found. So my question is how to set index page site using path function?
downvote count: 0

http://stackoverflow.com/q/47806784
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47807054
tagged with: python
tagged with: plot
has answer: http://stackoverflow.com/a/47807112
tagged with: mplot3d
score: 0
tagged with: matplotlib
has title: how to plot a 3d graph in python using matplotlib?
has body: I am new to python and matplotlib, I want to plot a line graph and I have 3 arrays: np.append(self.arraynv,nv) np.append(self.arraysvdb,Svdb) np.append(self.arraykclen,kclen) which I want to be x, y and z axis points respectively the code I wrote: fig = plt.figure() ax = fig.add_subplot(111, projection='3d') Axes3D.plot(self.arraynv,self.arraysvdb, self.arraykclen) ax.show() The error I am getting: 'numpy.ndarray' object has no attribute 'has_data'
type: Question
tagged with: numpy
answer count: 2

http://stackoverflow.com/q/47833991
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/82631922
type: AnsweredQuestion
has title: Django application memory usage
downvote count: 0
has answer: http://stackoverflow.com/a/47834995
accepted answer: http://stackoverflow.com/a/47834995
answer count: 1
has comment: http://stackoverflow.com/comment/82631113
has body: I am running Django application (built on Django Rest Framework) on Digital Ocean server with following characteristics: 4gb RAM 2 CPUs 60 GB drive I am using Gunicorn to run Django app and Celery to manage queue. Database is MySQL. As I can see CPU usage is really low, but memory usage seems to be large. After I deploy I noticed that python3 process uses even more memory (something around 75%). Whenever I deploy I am running after_deploy script, which contains following: service nginx restart service gunicorn restart chmod +x /mnt/myapplication/current/myapplication/setup/restart.sh source /mnt/env/bin/activate cd /mnt/myapplication/current/ pip3 install -r requirements.txt python3 manage.py migrate --noinput &gt;&gt; /mnt/migrations/migrations.log rm -f celerybeat.pid rm -f celeryd.pid celery -A myapplication beat -l info -f /var/log/celery/celery.log --detach celery -A myapplication worker -l info -f /var/log/celery/celery.log --detach Are these numbers expected? And if not, how can I investigate what is going wrong?
favorite count: 0
type: Question
tagged with: gunicorn
score: 6
upvote count: 6

time-complexity
tags question: http://stackoverflow.com/q/47826052
tag name: time-complexity
type: Tag

http://stackoverflow.com/comment/82581643
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47796422
has text: @ParthapratimNeog Yes. Thats the case. In this case you need to think about what you will do in real world case where new unseed data contains something which you have not learnt about. How do you handle them then? Do you then drop those cases or train again on the whole data.
score: 0

http://stackoverflow.com/q/47846256
has body: Given this table: ╔═══╦══════════╦═══════════╦═════════════╗ ║ ║ position ║ amino_var ║ sequence ║ ╠═══╬══════════╬═══════════╬═════════════╣ ║ 0 ║ 3 ║ A ║ MWSWKCLLFWA ║ ║ 1 ║ 4 ║ G ║ MWSWKCLLFWH ║ ║ 2 ║ 6 ║ I ║ MWSWKCLFLVH ║ ║ 3 ║ 3 ║ C ║ MWSWVESFLVH ║ ║ 4 ║ 2 ║ V ║ MWEQAQPWGAH ║ ╚═══╩══════════╩═══════════╩═════════════╝ Or you can construct this dataframe with: uniprots = pd.DataFrame({'position': [3,4,6,3,2], 'amino_var': ['A', 'G', 'I', 'C', 'V'], 'sequence': ['MWSWKCLLFWA', 'MWSWKCLLFWH', 'MWSWKCLFLVH', 'MWSWVESFLVH', 'MWEQAQPWGAH']}) I would like to slice the sequence part between position + 1 and position - 1for example, and then replace the letter in position for the letter in amino_var. I tried this: uniprots.sequence.str[uniprots.position - 1 : uniprots.position + 1] But I get a Series full of NaNs. My expected output would be: ╔═══╦════════╗ ║ ║ output ║ ╠═══╬════════╣ ║ 0 ║ WAW ║ ║ 1 ║ SGK ║ ║ 2 ║ KIL ║ ║ 3 ║ WCW ║ ║ 4 ║ MVE ║ ╚═══╩════════╝
has answer: http://stackoverflow.com/a/47852746
has answer: http://stackoverflow.com/a/47846561
has comment: http://stackoverflow.com/comment/82656863
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82656591
tagged with: python
has comment: http://stackoverflow.com/comment/82656706
accepted answer: http://stackoverflow.com/a/47846561
has title: Slice a Pandas object column using other columns
possible better answer: http://stackoverflow.com/a/47846442
score: 2
upvote count: 2
type: AnsweredQuestion
answer count: 3
downvote count: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/47846442

http://stackoverflow.com/comment/82646562
score: 0
type: Comment
has text: I guess How can I improve my algorithm to prevent this, when run its meant to create a [sierpinski carpet](http://paulbourke.net/fractals/carpet/ifs10000000.gif)
type: QuestionComment
comment on: http://stackoverflow.com/q/47841025

grasshopper
tag name: grasshopper
tags question: http://stackoverflow.com/q/47781418
type: Tag

http://stackoverflow.com/q/47758657
type: Question
has comment: http://stackoverflow.com/comment/82478779
has comment: http://stackoverflow.com/comment/82479517
tagged with: cron
type: UnansweredQuestion
has body: I am trying to put a cronjob inside my docker container, which runs a python script. My Dockerfile: FROM python:3.6.2 RUN apt-get update &amp;&amp; apt-get -y install cron ADD . /dir WORKDIR /dir RUN pip install -r requirements.txt RUN chmod 0644 /dir ADD crontab /dir ENV NAME loader CMD cron -f My crontab file: * * * * * root /loader.py As i run: $ docker run -t -i loader:latest I get nothing even after 10 mins. The script writes out Hello world when it runs. I removed the cron from the docker image and the script works and writes out Hello world As I was trying to simplify things i tried to leave the script out so the cron only writes out something like hi every minute like this: * * * * * root echo "hi" but nothing happens.
tagged with: python
has title: How can I run cron in Docker? (No jobs/output even with simple crontab)
has answer: http://stackoverflow.com/a/47760481
tagged with: docker
score: 0
has comment: http://stackoverflow.com/comment/82478850
answer count: 1
has comment: http://stackoverflow.com/comment/82478819
tagged with: dockerfile
has comment: http://stackoverflow.com/comment/82479798

http://stackoverflow.com/comment/82494957
type: Comment
type: QuestionComment
has text: Did you check TestLink configurations? Docker ports could be good to check also, using cURL example.
comment on: http://stackoverflow.com/q/47763067
score: 0

http://stackoverflow.com/q/47793282
has comment: http://stackoverflow.com/comment/82548213
favorite count: 0
has comment: http://stackoverflow.com/comment/82547509
has answer: http://stackoverflow.com/a/47847144
has comment: http://stackoverflow.com/comment/82547561
tagged with: woocommerce
has comment: http://stackoverflow.com/comment/82547668
has comment: http://stackoverflow.com/comment/82548335
has comment: http://stackoverflow.com/comment/82548921
tagged with: python
has comment: http://stackoverflow.com/comment/82547606
has comment: http://stackoverflow.com/comment/82548080
has answer: http://stackoverflow.com/a/47794238
type: Question
has comment: http://stackoverflow.com/comment/82547666
has body: I have a WooCommerce webhook who sends a POST request to a specific URL (http://po.tic.ch/polls/hello) for every order on my website. This WooCommerce is running on https://vi.tic.ch. For each order, i want to retrieve the informations of the POST like user ID = 12, product ID = 234, price = 50CHF, etc. to save it in my server po.tic.ch. The server po.tic.ch runs Django with Apache2. He have the port 80 open and receives all the POSTS but i don't know how to get the his content. I tried this on my views.py file: from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt import json @csrf_exempt def hello(request): # r = json.loads(request.POST) r = json.loads(request.POST.body) print(r) return HttpResponse(r) def get(self, request, *args, **kwargs): return HttpResponse('This is GET request') def post(self, request, *args, **kwargs): return HttpResponse('This is POST request') the POST request on my Django Thank You!
score: -5
has title: How, with Python, can i retrieve the data content of a POST request?
answer count: 2
has comment: http://stackoverflow.com/comment/82547595
upvote count: 1
has comment: http://stackoverflow.com/comment/82548071
type: UnansweredQuestion
tagged with: django
has comment: http://stackoverflow.com/comment/82547653
downvote count: 6

http://stackoverflow.com/a/47775499
has comment: http://stackoverflow.com/comment/82516091
has comment: http://stackoverflow.com/comment/82515721
has comment: http://stackoverflow.com/comment/82513719
has comment: http://stackoverflow.com/comment/82515826
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82512179
answers question: http://stackoverflow.com/q/47774809
upvote count: 1
has comment: http://stackoverflow.com/comment/82512061
has comment: http://stackoverflow.com/comment/82516263
has comment: http://stackoverflow.com/comment/82514897
has body: You create own OptionMenu with Frame inside but without original tk.OptionMenu import tkinter as tk langMap = {1:"English", 2:"German", 3:"Russian"} class MyOptionMenu1(): # &lt;-- without inheritions it is not widget, # You can't use `menu1.pack()`. # You could use only `menu1.frame.pack()`. # Or you have to create own `def pack(self, **options) # and execute `self.frame.pack()` inside def __init__(self, master, status, *options): self.frame = tk.Frame(master) # &lt;-- tk. self.frame.pack() # &lt;-- self. self.result = tk.StringVar() #self.result.set(status) self.label = tk.Label(self.frame, text=status) self.label.pack() self.dropdown = tk.OptionMenu(self.frame, self.result, *options) self.dropdown.pack() class MyOptionMenu2(tk.Frame): # &lt;-- inherits from Frame def __init__(self, master, status, *options): super().__init__(master) # Frame constructor #self.pack() # &lt;-- without - use `menu1.pack()` to show this frame self.result = tk.StringVar() #self.result.set(status) self.label = tk.Label(self, text=status) # &lt;-- self as parent/master self.label.pack() self.dropdown = tk.OptionMenu(self, self.result, *options) # &lt;-- self as parent/master self.dropdown.pack() def main(): root = tk.Tk() # --- version 1 --- menu1 = MyOptionMenu1(root, "Language", *langMap.keys()) # &lt;-- tk. #menu1.pack() # &lt;--- without, because MyOptionMenu1 is not widget menu1 = MyOptionMenu1(root, "Language", *langMap.values()) # &lt;-- tk. #menu1.pack() # &lt;--- without, because MyOptionMenu1 is not widget # --- version 2 --- menu1 = MyOptionMenu2(root, "Language", *langMap.keys()) # &lt;-- tk. menu1.pack() # &lt;--- with, because MyOptionMenu2 is widget menu1 = MyOptionMenu2(root, "Language", *langMap.values()) # &lt;-- tk. menu1.pack() # &lt;--- without, because MyOptionMenu is not widget root.mainloop() if __name__ == '__main__': main() EDIT: code with layout changes but without some comments import tkinter as tk class MyOptionMenu1(): # &lt;-- not inherits from Frame def __…
has comment: http://stackoverflow.com/comment/82512198
has comment: http://stackoverflow.com/comment/82517569
score: 1
has comment: http://stackoverflow.com/comment/82514710
has comment: http://stackoverflow.com/comment/82516555
has comment: http://stackoverflow.com/comment/82515137
type: Answer
has comment: http://stackoverflow.com/comment/82514441
has comment: http://stackoverflow.com/comment/82516051
has comment: http://stackoverflow.com/comment/82513139
has comment: http://stackoverflow.com/comment/82514090
has comment: http://stackoverflow.com/comment/82514678
has comment: http://stackoverflow.com/comment/82514641
has comment: http://stackoverflow.com/comment/82515873
accepted answer of: http://stackoverflow.com/q/47774809
has comment: http://stackoverflow.com/comment/82515299

http://stackoverflow.com/comment/82614315
comment on: http://stackoverflow.com/q/47825900
score: 0
type: Comment
type: QuestionComment
has text: How can I get the id?

http://stackoverflow.com/a/47822374
type: Answer
has body: Try this: mask = (df.ColX == 'F') &amp; (df.ColY == 'Y') df[~mask] Output: line_date ColX ColY ColZ rating rw 0 2007-03-31 P Y 56 1.000000 56.000000 1 2007-03-10 P Y 67 1.000000 67.000000 3 2007-01-13 2 NaN 83 0.880678 73.096278 4 2006-12-23 2 Y 88 0.793033 69.786942 5 2006-11-09 F NaN 52 0.636655 33.106077 6 2006-10-22 P NaN 66 0.581946 38.408408 Or, because I am a little confused what your output should be. mask = (df.ColX == 'F') | (df.ColY == 'Y') df[~mask] Output: line_date ColX ColY ColZ rating rw 3 2007-01-13 2 NaN 83 0.880678 73.096278 6 2006-10-22 P NaN 66 0.581946 38.408408
upvote count: 2
score: 2
has comment: http://stackoverflow.com/comment/82613572
downvote count: 0
has comment: http://stackoverflow.com/comment/82613590
has comment: http://stackoverflow.com/comment/82614013
answers question: http://stackoverflow.com/q/47822300

http://stackoverflow.com/comment/82403769
type: AnswerComment
comment on: http://stackoverflow.com/a/47721606
has text: Thanks! I prefer scalable solutions, as this was just an MWE.
type: Comment
score: 0

http://stackoverflow.com/comment/82601363
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47807770
has text: well, even with deepcopy, is this a reasonable approach?

http://stackoverflow.com/comment/82664075
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47849523
has text: What does `employees.py` look like?
type: Comment

http://stackoverflow.com/comment/125765742
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47801913
score: 0
has text: @alias51 here is example `p = io.BytesIO(content); pdf = PyPDF2.PdfFileReader(p)` where content is some byte representation of a PDF file. IE the output of img2pdf.convert(jpegimag) for example.

http://stackoverflow.com/q/47790619
has answer: http://stackoverflow.com/a/48649803
tagged with: python
has title: sacred, python - ex.config in one file and ex
accepted answer: http://stackoverflow.com/a/47790713
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47790713
answer count: 2
possible better answer: http://stackoverflow.com/a/48649803
score: 2
upvote count: 2
downvote count: 0
favorite count: 0
type: Question
tagged with: python-sacred
has body: so I've been poking around with sacred a little bit and it seems great. unfortunately I did not find any multiple files use-cases examples like I am trying to implement. so i have this file called configuration.py, it is intended to contain different variables which will (using sacred) be plugged in to the rest of the code (laying in different files): from sacred import Experiment ex = Experiment('Analysis') @ex.config def configure_analysis_default(): """Initializes default """ generic_name = "C:\\basic_config.cfg" # configuration filename message = "This is my generic name: %s!" % generic_name print(message) @ex.automain #automain function needs to be at the end of the file. Otherwise everything below it is not defined yet # when the experiment is run. def my_main(message): print(message) This by itself works great. sacred is working as expected. However, when I'm trying to introduce a second file named Analysis.py: import configuration from sacred import Experiment ex = Experiment('Analysis') @ex.capture def what_is_love(generic_name): message = " I don't know" print(message) print(generic_name) @ex.automain def my_main1(): what_is_love() running Analysis.py yields: Error: TypeError: what_is_love is missing value(s) for ['generic_name'] I expected that the 'import configuration' statement to include the configuration.py file, thus importing everything that was configured in there including configure_analysis_default() alongside its decorator @ex.config and then inject it to what_is_love(generic_name). What am I doing wrong? how can i fix this? Appreciate it!

http://stackoverflow.com/comment/82548153
has text: @cᴏʟᴅsᴘᴇᴇᴅ Updated the question. Thanks!
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47793488

http://stackoverflow.com/comment/82639886
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47838056
has text: `hard_drive = 'D:\\sifreler.txt' , 'E:\\sifreler.txt' , 'F:\\sifreler.txt' , 'G:\\sifreler.txt' , 'H:\\sifreler.txt' , 'I:\\sifreler.txt'` dont work @manoelhc
type: Comment

http://stackoverflow.com/q/47790540
answer count: 1
has body: I have a dataset like this: ID1 ID2 11 22 11 34 22 35 35 9 41 10 52 87 9 65 34 43 I want an output dataset which detects duplicate IDs using ID1 and ID2 assignment as: ID1 ID2 ID3 11 22 ID_11 11 34 ID_11 22 35 ID_11 35 9 ID_11 41 10 ID_10 52 87 ID_87 9 65 ID_11 34 43 ID_1 Since IDs 11,22,35,9,34 are all referring to one another, they are mapped to a single ID say ID_11
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82542378
has answer: http://stackoverflow.com/a/47791831
score: -2
tagged with: duplicates
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82543749
accepted answer: http://stackoverflow.com/a/47791831
has comment: http://stackoverflow.com/comment/82542237
has title: Identifying duplicate IDs using combination of 2 IDs
has comment: http://stackoverflow.com/comment/82542653
upvote count: 0
downvote count: 2

http://stackoverflow.com/comment/82376171
comment on: http://stackoverflow.com/q/47707784
type: QuestionComment
type: Comment
score: 0
has text: @Turksarama yo that totally worked thanks man

http://stackoverflow.com/q/47717012
accepted answer: http://stackoverflow.com/a/47717327
downvote count: 0
upvote count: 1
answer count: 1
has title: linprog in scipy.optimize - checking solution
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47717327
type: AnsweredQuestion
score: 1
tagged with: python
tagged with: linear-programming
has body: I tried to solve linear system with constraints using linprog from scipy.optimize, but got answer contradicting some inequalities. Here is my set up: import numpy as np from scipy.optimize import linprog c = np.array([1,0,0,0,0,0,0]) A_ub = np.identity(7)*(-1) b_ub = np.array([[-2],[-2],[-2],[-2],[-2],[-2],[-2]]) A_eq = np.array([[1,1,1,1,1,1,0],[0.3,1.3,0.9,0,0,0,-1],[0.3,0,0,0,0,0,-2/3], [0,0.65,0,0,0,0,-1/15],[0,0,0.3,0,0,0,-1/15]]) b_eq = np.array([[100],[0],[0],[0],[0]]) res = linprog(c = c, A_ub=A_ub, b_ub=b_ub, A_eq = A_eq, b_eq = b_eq) Here is the answer: fun: -0.0 message: 'Optimization terminated successfully.' nit: 15 slack: array([ -2., -2., -2., 94., 0., 0., -2.]) status: 0 success: True x: array([ 0.00000000e+00, -8.88178420e-16, -1.77635684e-15, 9.60000000e+01, 2.00000000e+00, 2.00000000e+00, -7.10542736e-15]) As you can see x_2 =&gt; 8.88178420e-16 is not smaller than -2. Can somebody clarify why it happens? Here is link to documentation: linprog
tagged with: scipy

http://stackoverflow.com/q/47759474
has comment: http://stackoverflow.com/comment/82480414
score: 0
tagged with: pandas
upvote count: 1
answer count: 1
downvote count: 1
linked to: http://stackoverflow.com/q/21254472
has body: I would like to have a time series plot with years on the x axis and counties/ unemployment rate on the y axis. The problem is similar to the one suggested duplicate and that is the method I would like to use. The primary difference is that I cannot figure out how to wrangle the data correctly. The data appears as such name employment_2007 employment_2008 employment_2009 Napa 200 230 215 Lake 140 130 150 Sample of what I'm going for screenshot of code and error Note in the image I've isolated out one county to make the problem simpler, I plan to add all the counties once I've worked this out. This is probably more of a data transformation problem, so I should note I'm using a Pandas dataframe to store everything.
has comment: http://stackoverflow.com/comment/82480307
has comment: http://stackoverflow.com/comment/82480407
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47760023
has title: Plot multiple lines on matplotlib graph for time series plot
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82480559
tagged with: matplotlib
tagged with: python

http://stackoverflow.com/q/47810445
accepted answer: http://stackoverflow.com/a/47845085
has answer: http://stackoverflow.com/a/47845085
tagged with: python
has title: How can I validate a field depending on the lenght of another field with Cerberus?
possible better answer: http://stackoverflow.com/a/47815599
type: Question
has body: Is there a way to validate document where existence of one field depends of length of other field? My try: import cerberus schema = { 'field_2': { 'type': 'integer', 'dependencies': { 'field_1': {'maxlength': 1} } }, 'field_1': { 'type': 'list', } } v = cerberus.Validator(schema) doc = { 'field_1': [1, ], 'field_2': 77 } if not v.validate(doc): print(v.errors) else: print(True) output: {'field_2': ["depends on these values: {'field_1': {'maxlength': 1}}"]} expected output is True
answer count: 2
has answer: http://stackoverflow.com/a/47815599
type: AnsweredQuestion
score: 0
tagged with: cerberus

http://stackoverflow.com/comment/82377964
has text: are you mixing dict2 and dict1?
comment on: http://stackoverflow.com/q/47709058
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/47708365
answers question: http://stackoverflow.com/q/47708239
has body: You had the right idea with the Collections module. Use a Counter, it's their purpose: from collections import Counter s = 'pooiiiuuuuyyyyyttttttrrrrrrreeeeeeeewwwwwwwwwqqqqqqqqqq' c = Counter(s) c Counter({'q': 10, 'w': 9, 'e': 8, 'r': 7, 't': 6, 'y': 5, 'u': 4, 'i': 3, 'o': 2, 'p': 1}) It's already ordered by most frequent. If you need the results as an ordered tuple: c.most_common() [('q', 10), ('w', 9), ('e', 8), ('r', 7), ('t', 6), ('y', 5), ('u', 4), ('i', 3), ('o', 2), ('p', 1)]
upvote count: 2
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/82376763
has comment: http://stackoverflow.com/comment/82377065
has comment: http://stackoverflow.com/comment/82376618
score: 2
has comment: http://stackoverflow.com/comment/82376882

http://stackoverflow.com/a/47738117
has comment: http://stackoverflow.com/comment/82436897
has comment: http://stackoverflow.com/comment/82436786
answers question: http://stackoverflow.com/q/47737141
score: 0
has comment: http://stackoverflow.com/comment/82436961
type: Answer
has body: You've wrote a good code just missed some lines here and there. I've marked lines that you've missed with # country = [] info = [] dic = {} # def countryFinder(fileName,info): infile = open(fileName, "r") line = infile.readline() infile = open(fileName, "r").readlines() # for line in infile: line.strip() fields = line.split(":") fields = fields[1:3] # country = fields[0] country = country.strip() # info = fields[1] info = float(info.strip("\n")) # dic[country] = info # return dic.copy() # country = input("Please enter a country (\"q to quit\"): ") life = countryFinder("life.txt",info) gini = countryFinder("gini.txt",info) while country != "q": info = life # if country in info: info = country # print (" Life Expectancy is ",life[info]," years at birth") else: print (" No Life Expectancy Data") info = gini # if country in info: info = country # print (" Gini Value is ",gini[info]) else: print (" No Gini Data") country = input("Please enter a country (\"q to quit\"): ")
has comment: http://stackoverflow.com/comment/82436882
accepted answer of: http://stackoverflow.com/q/47737141
has comment: http://stackoverflow.com/comment/82436725
type: AcceptedAnswer

http://stackoverflow.com/a/48726944
has body: Hi if this is still relevant, you would have to convert it to a Bokeh figure and then utilize Bokeh functions like this. from bokeh.io import output_notebook, show from bokeh.models.tickers import FixedTicker import holoviews as hv import numpy as np hv.extension('bokeh') renderer = hv.renderer('bokeh') %opts Curve [xticks=[0, 1.5, 9] show_grid=True] points = [(0.1 * i, np.sin(0.1 * i)) for i in range(100)] plot = hv.Curve(points) p = renderer.get_plot(plot).state p.xgrid[0].ticker=FixedTicker(ticks=[1.5, 9]) show(p) Specific Tick Locations
answers question: http://stackoverflow.com/q/47840204
downvote count: 0
upvote count: 1
score: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47840204
has comment: http://stackoverflow.com/comment/84719574
type: Answer

http://stackoverflow.com/a/47734190
type: Answer
accepted answer of: http://stackoverflow.com/q/47733953
downvote count: 1
score: 12
answers question: http://stackoverflow.com/q/47733953
has comment: http://stackoverflow.com/comment/82428976
type: AcceptedAnswer
upvote count: 13
has body: Edit: Note that the solution in this answer will not work in bokeh server due to a known bug. This answer below will work and is more pythonic. You have to assign an instance of Title to p.title. Since, we are able to investigate the types of things in python using the function type, it is fairly simple to figure out these sorts of things. &gt; type(p.title) bokeh.models.annotations.Title Here's a complete example in a jupyter notebook: from bokeh.models.annotations import Title from bokeh.plotting import figure, show import numpy as np from bokeh.io import output_notebook output_notebook() x = np.arange(0, 2*np.pi, np.pi/100) y = np.sin(x) p = figure() p.circle(x, y) t = Title() t.text = 'new title' p.title = t show(p) outputs the following chart with the title set to new title:

http://stackoverflow.com/a/47700850
score: 1
accepted answer of: http://stackoverflow.com/q/47700690
type: Answer
has body: You already have a NumPy array. Therefore, you can subtract the integer directly: for key, value in dic.items(): dic[key] = value - dark_val
answers question: http://stackoverflow.com/q/47700690
type: AcceptedAnswer
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/82386830
type: AnswerComment
score: 0
type: Comment
has text: @AlexPoca, i would suggest to open a new question and provide there a reproducible data set, so we could test solutions
comment on: http://stackoverflow.com/a/47703756

http://stackoverflow.com/a/47778477
has comment: http://stackoverflow.com/comment/82522475
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: That happens because the subprocess call isn't asynchronous and blocks the mainloop and the user interface as a consequence. So, the approach is not correct. The clicked signal requires a button to be pressed and released but you have other signals that you can use, eg. button-press-event and button-release-event. The callback prototypes vary from the clicked one and you'll have access to the event, if needed. The answer to your question would be, set a callback to the button press event, BUT this will not solve your problem! The call should be async and to achieve that you can use GLib spawn async method.
accepted answer of: http://stackoverflow.com/q/47773468
has comment: http://stackoverflow.com/comment/82524591
type: Answer
answers question: http://stackoverflow.com/q/47773468

http://stackoverflow.com/a/47734746
type: Answer
answers question: http://stackoverflow.com/q/47733520
has body: The method numpy.einsum is convenient for this: np.einsum('ij,kli-&gt;klj', A, B) The notation says: multiply A[i, j] by B[k, l, i] and sum over i; place the result in the cell [k, l, j]. Example: A = np.array([(255, 0, 0), (0, 255, 0), (0, 0, 255)]) B = np.array([[[0.2, 0.6, 0.20], [0.2, 0.2, 0.60]], [[0.4, 0.4, 0.2], [0.3, 0.3, 0.4]]]) Y = np.einsum('ij,kli-&gt;klj', A, B) Then Y is array([[[ 51. , 153. , 51. ], [ 51. , 51. , 153. ]], [[ 102. , 102. , 51. ], [ 76.5, 76.5, 102. ]]])
score: 3
upvote count: 3
downvote count: 0

http://stackoverflow.com/comment/82552717
has text: I've updated the question with the expected output I am trying to achieve.
score: 0
comment on: http://stackoverflow.com/q/47793591
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47817360
has answer: http://stackoverflow.com/a/47838342
upvote count: 0
type: UnansweredQuestion
has title: Large scrollable figure in matplotlib is extremely slow
has answer: http://stackoverflow.com/a/47817515
downvote count: 1
has body: I created a tkinter window with a scrollable figure using the method from this post. Basically, I load in a relatively large image which i want to be resizeable using a tk.Scale, but I want the window which contains the figure to stay a constant size. The problem is that once my figure reaches ~16x16 inches, the program gets unbearably slow. Any ideas would be greatly appreciated. The particularly slowing line is figure.set_size_inches([factor * s for s in oldSize]) Here's the whole code for the window: import matplotlib matplotlib.use("TkAgg") from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg from matplotlib.figure import Figure import tkinter as tk from tkinter import ttk class MacroWindow(tk.Tk): def __init__(self, controller, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) #initialize regular Tk stuff #set properties for main window tk.Tk.wm_title(self, "Macro View") tk.Tk.geometry(self, newGeometry = '600x700+200+200') #define container for what's in the window self.controller = controller self.figSize_inches = [8,8] self.addScrollingFigure() frame_buttons = ttk.Frame(self) frame_buttons.grid(row = 1, column = 0, sticky = 'nsew') button_loadMacroImage = ttk.Button(frame_buttons,text = "Load Test Macro Image", command = lambda: self.loadMacroImage()) button_loadMacroImage.grid(row = 0, column = 0, padx = 10, pady = 10, sticky = 'nw') self.scale_zoom = tk.Scale(self, orient = tk.VERTICAL) self.scale_zoom.grid(row = 2, column = 0, sticky = 'ew') self.scale_zoom.config(command = self.changeSize, from_=.1, to=5, resolution = .1) def addScrollingFigure(self): self.frame_canvas = ttk.Frame(self) self.frame_canvas.grid(row = 0, column = 0, sticky = 'nsew') # set up canvas with scrollbars canvas = tk.Canvas(self.frame_canvas) canvas.grid(row = 0, column = 0, sticky = 'nsew') xScrollbar = tk.Scrollbar(self.frame_canvas, orient = tk.HORIZONTAL) yScrollbar = tk.Scrollbar(self.frame_canvas, orient = tk.VERTICAL) xScrollbar.grid(row = 1, column = 0, sti…
type: Question
linked to: http://stackoverflow.com/q/13197469
tagged with: matplotlib
tagged with: python
favorite count: 0
score: -1
answer count: 2

http://stackoverflow.com/comment/82625658
score: 0
type: QuestionComment
has text: @dsgdfg The child process may cost a long time before exited, so I need a non-blocking method. If using communicate(), my main process will be blocked...
type: Comment
comment on: http://stackoverflow.com/q/47829312

http://stackoverflow.com/a/47807751
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/82612793
downvote count: 0
has body: If db1.Members and db3.Members have the same definition, you do not have to redeclare the Members class separately for each database. Models.py ... class Members(models.Model): # Only declared once ever! .... then, from Models import Members context['db1_data'] = Members.objects.using('db1').filter... context['db3_data'] = Members.objects.using('db3').filter... ... # continue processing Shouldn't from ..models.db1 and from ..models.db2 be clear enough for django to spot the difference between the two models? Django Models are not database-specific, more like schema-specific, so if you have the same table in two different databases, one class extending model.Models suffices. Then, when you attempt to retrieve the objects, either specify the database with using(), or using routers, which you can read about in the Django docs https://docs.djangoproject.com/en/2.0/topics/db/multi-db/#an-example
has comment: http://stackoverflow.com/comment/82702184
has comment: http://stackoverflow.com/comment/82588505
answers question: http://stackoverflow.com/q/47750439
upvote count: 1

http://stackoverflow.com/q/47844513
upvote count: 1
has comment: http://stackoverflow.com/comment/82699217
score: 1
tagged with: complex-numbers
has comment: http://stackoverflow.com/comment/82654384
favorite count: 0
has comment: http://stackoverflow.com/comment/82654041
type: Question
tagged with: numpy
has body: I am trying to fuse two images using Kekres wavelet transform in python. I have used DFT (size 32*32) as base matrix to generate wavelet matrix (size 1024*1024). Same program is written in MATLAB, it shows fused result correctly. But this python program is not showing fused image. I am not able to understand the reason. Sample images are here MR Image Registered CT Image Expected Fused Image import cv2 import numpy as np from WaveletMatrix import GenerateWaveletMatrix import matplotlib.pyplot as plt import scipy as sp def dftmatrix(N): return sp.fft(sp.eye(N)) TranformSize=32 WaveletSize= TranformSize*TranformSize dftm=dftmatrix(TranformSize); WaveletMat=GenerateWaveletMatrix(dftm,TranformSize) FixedImageR = cv2.imread('D:\MyTransforms_HP\DataSet3\MR_LumbarSpineT2Cube00001.jpg',0) MovingImageR = cv2.imread('D:\MyTransforms_HP\DataSet3\R.jpg',0) SizeFixedImage=FixedImageR.shape SizeMovingImage=MovingImageR.shape if SizeFixedImage!=SizeMovingImage: print("Images must be of same size") exit() FixedImageR=FixedImageR.astype(np.double) MovingImageR=MovingImageR.astype(np.double) FixedImage = cv2.resize(FixedImageR,(WaveletSize,WaveletSize),0,0) MovingImage= cv2.resize(MovingImageR,(WaveletSize,WaveletSize),0,0) FixedImage=np.ceil(FixedImage) MovingImage=np.ceil(MovingImage) #WaveletImage1= np.zeros(shape=(WaveletSize,WaveletSize),dtype=np.double) #WaveletImage2= np.zeros(shape=(WaveletSize,WaveletSize),dtype=np.double) WaveletT=WaveletMat.T WaveletImage1=np.zeros(shape=(WaveletSize,WaveletSize),dtype=np.complex) WaveletImage2=np.zeros(shape=(WaveletSize,WaveletSize),dtype=np.complex) WaveletImage1=WaveletMat.dot(FixedImage).dot(WaveletT) WaveletImage2=WaveletMat.dot(MovingImage).dot(WaveletT) plt.figure(1) plt.imshow(np.uint8(WaveletImage1),cmap='gray') plt.show() plt.figure(2) plt.imshow(np.uint8(WaveletImage2),cmap='gray') plt.show() FusedImage1=np.zeros(shape=(WaveletSize,WaveletSize),dtype=np.complex) FusedImage1=(WaveletImage1 + WaveletImage2) / 2 newimg=np.zeros(sh…
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82655968
has comment: http://stackoverflow.com/comment/82847866
tagged with: python
has comment: http://stackoverflow.com/comment/82683870
has comment: http://stackoverflow.com/comment/82654010
has comment: http://stackoverflow.com/comment/82653334
has title: In Python, I am trying to obtain fusion of two images, but I am getting unexpected result
downvote count: 0

http://stackoverflow.com/a/47715809
type: Answer
downvote count: 0
upvote count: 1
score: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47715733
has body: I think you want to just print the class instance and receive a formatted output. For this you need to implement this method in the class: def __repr__(self): return '{} {} \n{} {} {}'.format(john._firstname, john._surname, john.d, john.m, john.y) Then you can just print the class instance: print(john) So this would be the complete code: class Person: def __init__(self, _firstname, _surname, d, m, y): self._firstname = _firstname self._surname = _surname self.d = d self.m = m self.y = y def __repr__(self): return '{} {} \n{} {} {}'.format(john._firstname, john._surname, john.d, john.m, john.y) john = Person('John','Lennon','8','10','1940') paul = Person('Paul','McCartney','7','7','1940') john._firstname = 'John' john._surname = 'Lennon' john.d = '8th' john.m = 'October' john.y = '1940' paul._firstname = 'Paul' paul._surname = 'McCartney' paul._day = '18' paul._month = '6' paul._year = '1943' print('{} {} \n{} {} {}'.format(john._firstname, john._surname, john.d, john.m, john.y)) print(john)
answers question: http://stackoverflow.com/q/47715733

http://stackoverflow.com/q/47854175
tagged with: python
has answer: http://stackoverflow.com/a/71705728
tagged with: django-rest-framework
has answer: http://stackoverflow.com/a/47854629
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82672572
answer count: 3
has title: Use one class based view for both List and Retrieve Rest API
possible better answer: http://stackoverflow.com/a/71705728
upvote count: 5
has comment: http://stackoverflow.com/comment/82672460
accepted answer: http://stackoverflow.com/a/47854407
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47854407
score: 5
has body: I currently have two different class based views for detailing a specific object and for listing all objects: class StatusList(ListAPIView): permission_classes = (IsAuthenticated,) serializer_class = serializers.StatusSerializer def get_queryset(self): queryset = helperfunctions.getObjects(self.request.user, models.Status) return queryset class StatusDetail(RetrieveAPIView): permission_classes = (IsAuthenticated,) serializer_class = serializers.StatusSerializer def get_queryset(self): queryset = helperfunctions.getObjects(self.request.user, models.Status) return queryset Note that helperfunctions.getObjects() simply returns the objects that share the same establishment with the user, so that they can't see statuses that they shouldn't. What I want to know is whether there's an option to use only one class based view for both StatusDetail and StatusList, which would automatically know that when it gets a pk in the get request it returns the appropriate object, and when it doesn't, it should return the whole list of objects. Thanks for any help :)
downvote count: 0
tagged with: django

pass-by-reference
tags question: http://stackoverflow.com/q/47761734
type: Tag
tag name: pass-by-reference

http://stackoverflow.com/comment/82431482
has text: Put all the dictionaries in a dictionary, so you can look them up using a string.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47735442
score: 4

http://stackoverflow.com/q/47835004
has answer: http://stackoverflow.com/a/47835190
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47835661
has body: In a video lecture on pluralsight, they said that you cannot add a new element to tuple but you can concatenate new object to a tuple.
score: -2
tagged with: python
has comment: http://stackoverflow.com/comment/82633449
answer count: 4
has answer: http://stackoverflow.com/a/47835540
has answer: http://stackoverflow.com/a/47835059
has comment: http://stackoverflow.com/comment/82633353
has title: Is there any difference between adding object and concatenate object in tuple in python?
upvote count: 0
downvote count: 2
favorite count: 0
type: Question
tagged with: python-3.x

http://stackoverflow.com/comment/82403861
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47720594
has text: Also, please be more specific about the errors you are encountering with your attempted approach.
score: 0

http://stackoverflow.com/comment/82653986
type: Comment
type: QuestionComment
score: 0
has text: You can try `print(chr(92))`, but it doesn't use the functions you list.
comment on: http://stackoverflow.com/q/47844946

http://stackoverflow.com/a/47800875
has comment: http://stackoverflow.com/comment/82562982
has body: Let's try this: Correct some data: td=[((1, 1), 1), ((1, 2), 2), ((1, 3), 1), ((2, 1), 1), ((2, 2), 5), ((3, 2), 2), ((3, 1), 1)] Flatten tuples l = [(i[0],i[1],v) for i,v in td] lol = [list(e) for e in l] Create and reshape dataframe pd.DataFrame(lol).set_index([1,0]).rename_axis([None,None]).unstack()[2]\ .fillna(0).astype(int) Output: 1 2 3 1 1 1 1 2 2 5 2 3 1 0 0 To expand dataframe: pd.DataFrame(lol).set_index([1,0]).rename_axis([None,None]).unstack()[2]\ .reindex(index=np.arange(1,10), columns=np.arange(1,10)).fillna(0).astype(int) Output: 1 2 3 4 5 6 7 8 9 1 9 0 0 0 0 0 0 0 0 2 0 10 0 0 0 0 0 0 0 3 0 1 0 1 0 0 0 0 0 4 0 0 0 1 0 0 0 0 0 5 0 0 0 0 1 1 0 0 0 6 0 0 0 0 0 1 0 0 0 7 0 0 0 0 0 0 0 0 0 8 0 0 0 0 0 0 0 0 0 9 0 0 0 0 0 0 0 0 0
score: 3
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/82563426
has comment: http://stackoverflow.com/comment/82563500
answers question: http://stackoverflow.com/q/47800625
has comment: http://stackoverflow.com/comment/82562999
has comment: http://stackoverflow.com/comment/82563147
has comment: http://stackoverflow.com/comment/82563105
has comment: http://stackoverflow.com/comment/82563058
has comment: http://stackoverflow.com/comment/82575449
type: Answer

http://stackoverflow.com/comment/82422573
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47730818
has text: @RottenCandy thank you! It truly was a mix of spaces and tabs problem!
type: Comment

http://stackoverflow.com/q/47751594
tagged with: python
tagged with: pygame
has comment: http://stackoverflow.com/comment/82794670
linked to: http://stackoverflow.com/q/47639826
has answer: http://stackoverflow.com/a/47927467
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47927467
has title: Python pygame - avoiding accidental continuous clicking
answer count: 1
tagged with: button
downvote count: 0
has comment: http://stackoverflow.com/comment/82469874
has comment: http://stackoverflow.com/comment/82464808
upvote count: 1
linked to: http://stackoverflow.com/q/47460715
has comment: http://stackoverflow.com/comment/82796669
has comment: http://stackoverflow.com/comment/82467957
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82567224
has comment: http://stackoverflow.com/comment/82573381
has comment: http://stackoverflow.com/comment/82466801
has body: Edit: added a longer example code. I'm having trouble with coding buttons in pygame. I'm a newbie to the pygame module, so be gentle. Basically, the goal is to make a point-and-click telltale kind of game. The player gets presented with two choices each gameloop, ie "go left" or "go right". Accordingly, there are two buttons in each gameloop, all located at the same coordinates. Here is the function: import pygame import os import time pygame.init() display_width= 1280 display_height = 720 gameDisplay = pygame.display.set_mode((display_width, display_height)) clock = pygame.time.Clock() def button(msg,x, y, w, h, ic, ac, action=None): #message, x y location, width, height, inactive and active colour if action ==None: pygame.display.update() clock.tick(15) mouse = pygame.mouse.get_pos() click = pygame.mouse.get_pressed() if x+w &gt; mouse[0] &gt; x and y+h &gt; mouse[1] &gt; y: pygame.draw.rect(gameDisplay, ac,(x,y,w,h)) for event in pygame.event.get(): if event.type == pygame.MOUSEBUTTONDOWN: pygame.display.update() clock.tick(15) if action == "left1": game_loop("loop1-1.png",0,0,"left2","left2","","") else: pygame.draw.rect(gameDisplay, ic,(x,y,w,h)) smallText = pygame.font.SysFont('timesnewroman',20) textSurf, textRect = text_objects(msg, smallText, silver) textRect.center = ( (x+(w/2)), (y+(h/2)) ) gameDisplay.blit(textSurf, textRect) def game_loop(pic,width,heigth,act1,act2,left,right): intro = True while intro: for event in pygame.event.get(): print(event) if event.type == pygame.QUIT: pygame.quit() quit() gameDisplay.fill(white) gameDisplay.blit(get_image(pic), (0, 0)) #MAIN MENU PIC button(left,440,450,width,heigth, dark_gray, gray, action=act1)#start nupp button(right,740,450,width,heigth, dark_gray, gray, action=act2)#exit nupp pygame.display.update() clock.tick(15) The problem occurs when I click the button carelessly, meaning if I don't purposefully click on the left mouse button as fast as I can. Once game_loop1 is called and if I click for a bit longer,…
score: 1
has comment: http://stackoverflow.com/comment/82794931
has comment: http://stackoverflow.com/comment/82464935

http://stackoverflow.com/q/47800192
type: AnsweredQuestion
tagged with: python-2.7
upvote count: 0
has body: I have dict with data {'Credit Card': 'No', u'Room (0): Бюджетный трехместный номер': {'Info': {'Info': u'Питание не входит в цену данного номера. Размещение детей и предоставление дополнительных кроватей: Разрешается проживание детей любого возраста. При размещении до двух детей младше 6 лет на имеющихся кроватях проживание им предоставляется бесплатно . Дополнительные кровати в номере не предоставляются. Предоплата: Предоплата не взимается. Порядок отмены бронирования: В случае отмены или изменения бронирования в срок до 18:00 даты заезда штраф не взимается. В случае отмены или изменения бронирования позднее этого срока или в случае незаезда взимается 100 процентов от стоимости первой ночи проживания . '}, 'Guest': u'СИЛЬВЕСТР СТАЛОНЕ', 'Smoking people': 'No', 'Daily rates': ['2018-02-20: 1990.00 (Standard Rate)', '2018-02-21: 1990.00 (Standard Rate)', '2018-02-22: 1990.00 (Standard Rate)', '2018-02-23: 1990.00 (Standard Rate)'], 'Number of guests': '2', 'Price details': [u'городской налог: 10.0RUB (included in room daily rates)'], 'Meal': u'Питание не входит в цену данного номера. '}, 'ChannelHotelId': '2360119', 'Channel reservation id': '1884282051', 'Commission': '1194.00'} how can I convert it Cyrillic string ?
downvote count: 2
answer count: 1
has comment: http://stackoverflow.com/comment/82561625
has title: dict to Cyrillic string
favorite count: 0
type: Question
score: -2
accepted answer: http://stackoverflow.com/a/47800535
has comment: http://stackoverflow.com/comment/82561566
tagged with: python
has answer: http://stackoverflow.com/a/47800535
linked to: http://stackoverflow.com/q/18337407

http://stackoverflow.com/comment/82596683
has text: Thank you, works just fine! I'll have to study the code to understand it (because I'm a nooblet), but it did it!
score: 0
comment on: http://stackoverflow.com/a/47816707
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/82515771
comment on: http://stackoverflow.com/q/47777308
type: Comment
type: QuestionComment
score: 2
has text: You probably need to use identical python versions, not just matching major versions.

http://stackoverflow.com/q/47796396
has title: Tensor flow and RandomShuffleQueue "insufficient elements (requested 64, current size 0)"
tagged with: deep-learning
has answer: http://stackoverflow.com/a/47871000
type: AnsweredQuestion
tagged with: tensorflow
favorite count: 0
has answer: http://stackoverflow.com/a/47818967
type: Question
upvote count: 2
score: 2
answer count: 2
tagged with: training-data
downvote count: 0
has body: I currently playing around with tensorFlow, and even thoughthe tutorials were kinda simple to complete, the true work starts when we try to input our own datas. I used a very basic dataset composer of animals and background. I created 3 tfrecords (train/val/test). I then attempt to read them and to train a simple model (Alexnet here). I tried to use the "FLAGS.num_iter" to be sure i'm not out the iteration range. This code processing get me a nice RandomShuffleQueue "insufficient elements (requested 64, current size 0)" error. I tried to dig the web but i found no answer to my questions. Here they are: How do we fix this ? How can we check if our tfrecord contain any mistakes? Can we write any condition to ensure that we have enough elements? If You have any further question on my code, I stay around! Best regards, import tensorflow as tf import os.path from model import Model from alexnet import Alexnet FLAGS = tf.app.flags.FLAGS NUM_LABELS = 2 IMAGE_WIDTH = 64 IMAGE_HEIGHT = 64 NUMBER_OF_CHANNELS = 3 #SOURCE_DIR = './data/' #TRAINING_IMAGES_DIR = SOURCE_DIR + 'train/' #LIST_FILE_NAME = 'list.txt' BATCH_SIZE = 2 #TRAINING_SET_SIZE = 81112 TRAIN_FILE = '/home/sebv/SebV/datas/tfRecording/train.tfrecords' VAL_FILE = '/home/sebv/SebV/datas/tfRecording/val.tfrecor' def read_and_decode(filename_queue): reader = tf.TFRecordReader() _, serialized_example = reader.read(filename_queue) features = tf.parse_single_example( serialized_example, # Defaults are not specified since both keys are required. features={ 'image/encoded': tf.FixedLenFeature([], tf.string), 'image/format': tf.FixedLenFeature([], tf.string), 'image/class/label': tf.FixedLenFeature([], tf.int64), 'image/height': tf.FixedLenFeature([], tf.int64), 'image/width': tf.FixedLenFeature([], tf.int64), }) # Convert from a scalar string tensor (whose single string has # length mnist.IMAGE_PIXELS) to a uint8 tensor with shape # [mnist.IMAGE_PIXELS]. image = tf.image.decode_png(features['image/encoded'], 3, tf.uint8) #…
tagged with: python
accepted answer: http://stackoverflow.com/a/47871000
possible better answer: http://stackoverflow.com/a/47818967

http://stackoverflow.com/a/47836831
has comment: http://stackoverflow.com/comment/82637455
has comment: http://stackoverflow.com/comment/82638097
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47836347
has comment: http://stackoverflow.com/comment/92332150
score: 3
upvote count: 3
type: Answer
has comment: http://stackoverflow.com/comment/92345784
answers question: http://stackoverflow.com/q/47836347
has body: Using just the data in your question: &gt;&gt;&gt; df = pd.read_csv('rio.txt', sep='\|{4}', skip_blank_lines=True, engine='python') &gt;&gt;&gt; df CREATED_AT ID \ 0 Tue Nov 14 12:33:00 +0000 2017 930413253766791168 1 Tue Nov 14 12:34:00 +0000 2017 930413253766821456 TEXT IN_REPLY_TO_USER_ID \ 0 ICYMI: Football clubs join the craft beer revo... 1 I'm up for it NAME SCREEN_NAME DESCRIPTION \ 0 BAB BABBrewers Monthly homebrew meet-up at 1000 Trades, Jewel... 1 Misty MistyGrl You CAN DO it! FOLLOWERS_COUNT TIME_ZONE QUOTE_COUNT REPLY_COUNT RETWEET_COUNT \ 0 95 0 0 0 1 45 0 0 0 FAVORITE_COUNT 0 0 1 0 Notice the sep parameter. When it's more than one character long and not equal to '\s+' it's interpreted as a regular expression. But the '|' character has special meaning in a regex, hence it must be escaped, using the '\' character. I could simply have written sep='\|\|\|\|'; however, I've used an abbreviation.

pyglet
tags question: http://stackoverflow.com/q/47821756
type: Tag
tag name: pyglet

http://stackoverflow.com/comment/83378949
type: AnswerComment
score: 0
has text: I know you can represent numbers as integers or the same number in scientific notation. I'm testing the scientific values being returned from the database and checking them for accuracy. IOW: Does the database represent the number / scientific number correctly. I don't want the values munged in anyway. What is happening is the database will return a valid scientific value and performing the JSON load will cause the value to be be translated. Yes... to a valid scientific representation but I need the original value not the munged value. Any ideas would be greatly appreciated.
type: Comment
comment on: http://stackoverflow.com/a/48176304

http://stackoverflow.com/comment/82459677
type: QuestionComment
score: 0
has text: please put whatever you tried yet
comment on: http://stackoverflow.com/q/47749708
type: Comment

http://stackoverflow.com/q/47797661
has answer: http://stackoverflow.com/a/47802120
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47802160
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/72543142
tagged with: python
upvote count: 4
score: 3
answer count: 3
has body: Why do I have to assign the result of types.MethodType() to an attribute before I use it via p.** in my example below. As I think, the method types.MethodType() has already bind the method onto the instance. Hope someone can help. Thanks a lot. Here is my code: import types class Person(object): def __init__(self, newName): self.name = newName def eat(self, food): print("%s is eating %s" % (self.name, food)) def getName(self): print("My name is %s" % self.name) def main(): p = Person("Peter") p.eat("Pork bean") types.MethodType(getName, p) #p.getName = types.MethodType(getName, p) p.getName() if __name__ == "__main__": main() [ ] [ ]
downvote count: 1
has title: Python types.MethodType()

http://stackoverflow.com/comment/82410075
comment on: http://stackoverflow.com/a/47724652
type: AnswerComment
score: 1
has text: No need , also if you do not mind you can add ..`df[~df['col'].str.contains(r'^(?=.*@teddyb_h2o)(?=.*@casekeenum7)')]` :-)
type: Comment

http://stackoverflow.com/q/47758292
has comment: http://stackoverflow.com/comment/82480271
type: Question
has comment: http://stackoverflow.com/comment/82480010
has comment: http://stackoverflow.com/comment/82489450
answer count: 0
has comment: http://stackoverflow.com/comment/82490576
has body: I wrote a web app and I want to deploy it by heroku.I'm new to this and couldn't figure out this problem.I already searched everything about this but didn't work.Hope you guys can give me some suggestions. This is my requirements.txt alabaster==0.7.10 asn1crypto==0.22.0 astroid==1.4.9 astropy==1.3.2 Babel==2.4.0 backports.shutil-get-terminal-size==1.0.0 comtypes==1.1.2 conda==4.3.21 contextlib2==0.5.5 cryptography==1.8.1 cycler==0.10.0 Cython==0.25.2 cytoolz==0.8.2 dask==0.14.3 datashape==0.5.4 decorator==4.0.11 distributed==1.16.3 dj-database-url==0.4.2 dj-static==0.0.6 docutils==0.13.1 entrypoints==0.2.2 et-xmlfile==1.0.1 fastcache==1.0.2 Flask==0.12.2 Flask-Cors==3.0.2 gevent==1.2.1 greenlet==0.4.12 gunicorn==19.7.1 h5py==2.7.0 ....... xlwings==0.10.4 xlwt==1.2.0 zict==0.1.2 psycopg2==2.6.1 When I got error I'll delete the line in requirements.txt.At the first I thought that is only one but the truth is more the one not found.Everytime I will commit ater I change requirement.txt.I don't know why and how to debug.I hope it can run and I can deploy it. This is my error C:\Users\user\django_project&gt;git push heroku master Counting objects: 13090, done. Delta compression using up to 4 threads. Compressing objects: 100% (9553/9553), done. Writing objects: 100% (13090/13090), 118.21 MiB | 316.00 KiB/s, done. Total 13090 (delta 2753), reused 12586 (delta 2529) remote: Compressing source files... done. remote: Building source: remote: remote: -----&gt; Python app detected remote: -----&gt; Installing python-3.6.3 remote: -----&gt; Installing pip remote: -----&gt; Noticed cffi. Bootstrapping libffi. remote: -----&gt; Installing requirements with pip remote: Collecting alabaster==0.7.10 (from -r /tmp/build_62ec9f69c217d0564bde759554f34c5d/requirements.txt (line 1)) remote: Downloading alabaster-0.7.10-py2.py3-none-any.whl ....... remote: Could not find a version that satisfies the requirement comtypes==1.1.2 (from -r /tmp/build_62ec9f69c217d0564bde759554f34c5d/requiremen…
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82480214
tagged with: django
has title: heroku : git push heroku master
tagged with: python
tagged with: git
tagged with: heroku
score: 0

http://stackoverflow.com/comment/82632849
type: AnswerComment
comment on: http://stackoverflow.com/a/47833125
has text: Can you try saving your X and Y coordinates, go to cmd, and type "adb shell input tap x y" and do it fast enough to see if it works? I guess it won't work, but then you will have to try my python method with Threading for each tap
score: 0
type: Comment

http://stackoverflow.com/comment/82545209
has text: BTW, i recently see [this](https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags) post, i think is mandatory reading
type: Comment
score: 0
comment on: http://stackoverflow.com/a/47773805
type: AnswerComment

http://stackoverflow.com/q/47842086
type: AnsweredQuestion
has body: I'm just want to get base64 string of plot image(png) from matplotlib in remote ubuntu server by python for serving to web page. But, it is not working in remote server(ubuntu14.04, python3) like below. plt.plot(date, created, 'b', label='Created') plt.plot(date, closed, 'r', label='Closed') buf = io.BytesIO() plt.savefig(buf, format='png') img_base64 = base64.b64encode(buf.getvalue()).decode('utf8') plt.close() buf.close() _tkinter.TclError: no display name and no $DISPLAY environment variable Please help me...
score: 0
has title: Matplotlib: to get base64 of image from remote server
has answer: http://stackoverflow.com/a/47842399
duplicate of: http://stackoverflow.com/q/37604289
answer count: 1
type: Question
tagged with: matplotlib
tagged with: python
linked to: http://stackoverflow.com/q/37604289
has comment: http://stackoverflow.com/comment/82648356
accepted answer: http://stackoverflow.com/a/47842399

http://stackoverflow.com/q/47788605
has answer: http://stackoverflow.com/a/47813579
score: 1
tagged with: python
tagged with: web-crawler
type: Question
has title: How to use python to press the “load more” in imdb to get more reviews
has comment: http://stackoverflow.com/comment/82538210
downvote count: 0
upvote count: 1
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/82538162
tagged with: imdb
has comment: http://stackoverflow.com/comment/82538187
favorite count: 0
tagged with: beautifulsoup
has comment: http://stackoverflow.com/comment/82538245
has body: I am creating a web crawler now and I want to scrape the user reviews from imdb. It's easy to directly get the 10 reviews and rate from the origin page. For example http://www.imdb.com/title/tt1392170/reviews The problem is to get all reviews, I need to press the "load more" so that more reviews will be shown while the url address doesn't change! So I don't know how can I get all the reviews in Python3. What I use now are requests, bs4. My code now: from urllib.request import urlopen, urlretrieve from bs4 import BeautifulSoup url_link='http://www.imdb.com/title/tt0371746/reviews?ref_=tt_urv' html=urlopen(url_link) content_bs=BeautifulSoup(html) for b in content_bs.find_all('div',class_='text'): print(b) for rate_score in content_bs.find_all('span',class_='rating-other-user-rating'): print(rate_score)
linked to: http://stackoverflow.com/q/37799149

http://stackoverflow.com/q/47716531
has comment: http://stackoverflow.com/comment/82400920
favorite count: 0
type: Question
has body: What is the general mathematics principle behind the following problem? Take a vector containing integers e.g. [3, 3, 3, 3, 4, 6, 3, 4, 4, 5], and another vector representing loop indices that all begin at a value less than the first vector e.g. [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]. When each loop index is equal to its corresponding index in the first vector, reset it to one. Program ends when all indices are equal to one. This seems like integer factorization, but I don't know how to state this generally. What principle is at work here? What is a more computationally efficient way to achieve the same result? Thanks in advance. import numpy as np unityVec = np.ones((10), dtype=np.int) # create a vector of ones counter = 1 # initialize counter counterVec = np.ones((10), dtype=np.int) # initialize counter array counterVec = counterVec + 1 # make counter array &gt; ones array littleVec = ([3, 3, 3, 3, 4, 6, 3, 4, 4, 5]) # loop reset values while not (np.array_equal(unityVec, counterVec)): # compare counter to ones vector counterVec = counterVec + 1 for i in range(10): if counterVec[i] == littleVec[i]: counterVec[i] = 1 # reset counterVec element to 1 once it hits limit #print("Counter: ", counter, "\tIndex: ", i, "\tcounterVec: ", counterVec, "\tlittleVec: ", littleVec) counter = counter + 1 print("Indices converged after", counter-1, "iterations!") Expected result: a positive integer value that is less than or equal to the product of the first vector's values. Experimental result: with the sample values given, the indices converge after 59 loops.
tagged with: factorization
tagged with: python
has comment: http://stackoverflow.com/comment/82393800
upvote count: 2
tagged with: numpy
type: AnsweredQuestion
has title: Math principle behind converging loop indices?
score: 2
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/47717672
accepted answer: http://stackoverflow.com/a/47717672
has comment: http://stackoverflow.com/comment/82393777

http://stackoverflow.com/a/47730495
has comment: http://stackoverflow.com/comment/82430206
has comment: http://stackoverflow.com/comment/82421801
has comment: http://stackoverflow.com/comment/82421842
has comment: http://stackoverflow.com/comment/82421648
has comment: http://stackoverflow.com/comment/82423298
has comment: http://stackoverflow.com/comment/82423227
upvote count: 5
answers question: http://stackoverflow.com/q/47730349
type: Answer
accepted answer of: http://stackoverflow.com/q/47730349
has comment: http://stackoverflow.com/comment/82421664
has comment: http://stackoverflow.com/comment/82421800
score: 5
has comment: http://stackoverflow.com/comment/82421607
type: AcceptedAnswer
has body: Here's a solution based on the recurrence relation from OEIS: def onecount(n): if n == 0: return 0 if n % 2 == 0: m = n/2 return onecount(m) + onecount(m-1) + m m = (n-1)/2 return 2*onecount(m)+m+1 &gt;&gt;&gt; [onecount(i) for i in range(30)] [0, 1, 2, 4, 5, 7, 9, 12, 13, 15, 17, 20, 22, 25, 28, 32, 33, 35, 37, 40, 42, 45, 48, 52, 54, 57, 60, 64, 67, 71]
downvote count: 0

http://stackoverflow.com/q/47748388
tagged with: python
has answer: http://stackoverflow.com/a/47749856
type: Question
accepted answer: http://stackoverflow.com/a/47749746
answer count: 2
has answer: http://stackoverflow.com/a/47749746
possible better answer: http://stackoverflow.com/a/47749856
has body: From the daily stock price data, I want to sample and select end of the month price. I am accomplishing using the following code. import datetime from pandas_datareader import data as pdr import pandas as pd end = datetime.date.today() begin=end-pd.DateOffset(365*2) st=begin.strftime('%Y-%m-%d') ed=end.strftime('%Y-%m-%d') data = pdr.get_data_yahoo("AAPL",st,ed) mon_data=pd.DataFrame(data['Adj Close'].resample('M').apply(lambda x: x[-2])).set_index(data.index) The line above selects end of the month data and here is the output. If I want to select penultimate value of the month, I can do it using the following code. mon_data=pd.DataFrame(data['Adj Close'].resample('M').apply(lambda x: x[-2])) Here is the output. However the index shows end of the month value. When I choose penultimate value of the month, I want index to be 2015-12-30 instead of 2015-12-31. Please suggest the way forward. I hope my question is clear. Thanking you in anticipation. Regards, Abhishek
has title: Selecting specific date from pandas data-frame
type: AnsweredQuestion
score: 0
tagged with: pandas

http://stackoverflow.com/a/47763276
answers question: http://stackoverflow.com/q/47755980
type: Answer
upvote count: 2
score: 2
has body: Here is an example of working with AdBuddiz a similar solution can be applied with admob using jnius #ads.py from jnius import autoclass import logging import random log = logging.getLogger('kivy.funky.stuff') PythonActivity=autoclass("org.renpy.android.PythonActivity") AdBuddiz=autoclass("com.purplebrain.adbuddiz.sdk.AdBuddiz") AD_CHANCE = 0.06 def init(): AdBuddiz.setPublisherKey("some-token") #delete this before going to play at the store... AdBuddiz.setTestModeActive() AdBuddiz.cacheAds(PythonActivity.mActivity) def show(): if (random.random() &lt; AD_CHANCE): log.info("Showing Ad!!!") try: AdBuddiz.showAd(PythonActivity.mActivity) except Exception: log.exception("Pizza is not healthy...") else: log.warn("Skipping the AD this time ;)") to make this work you'll need to add pyjnius to your buildozer.spec as well as the java SDK (i.e. android.add_jars = %(source.dir)s/libs/*.jar).
downvote count: 0

http://stackoverflow.com/comment/82452049
has text: Friend I am talking about the urllib module. Try sending the HTTP request using the requests module. It is easier to understand. [Here](http://docs.python-requests.org/en/master/)
comment on: http://stackoverflow.com/q/47745749
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/47823277
has body: I assume that you have a string, I will recommend doing it like that : fixed_address = hex(int(address, 16))
upvote count: 4
score: 4
answers question: http://stackoverflow.com/q/47823221
downvote count: 0
type: Answer

http://stackoverflow.com/a/47840995
has comment: http://stackoverflow.com/comment/91375330
answers question: http://stackoverflow.com/q/47838059
has comment: http://stackoverflow.com/comment/117378051
has comment: http://stackoverflow.com/comment/91386897
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/91375128
score: 22
downvote count: 0
has comment: http://stackoverflow.com/comment/83003448
has comment: http://stackoverflow.com/comment/91387266
type: Answer
has body: Purpose of this question: to show / hide a fieldset if a specific option is selected in a Django admin form dropdown. Solution overview: you need to break fieldsets up into two instead of one, custom javascript, define Media class in ModelAdmin. [Step One] In my project named dropdown, I added the following folders / files: static (directory) static/dropdown (directory) static/dropdown/js (directory) static/dropdown/js/base.js (file) [Step Two] In admin.py, a few things to note: I broke fieldsets up into two instead of one. Notice that I'm defining classes for each fieldset. abcdefg is the name of the class of the fieldset I'm trying to show and hide. I defined class Media. This tells django where to look for custom javascript and css files. admin.py from django.contrib import admin from dropdown.models import DropdownModel from dropdown.forms import DropdownModelForm class DropdownModelAdmin(admin.ModelAdmin): fieldsets = ( ('Date Range', { 'fields': ('date_range',), 'classes': ('predefined',) }), (None, { 'fields': (('start_date', 'end_date'),), 'classes': ('abcdefg',) }) ) form = DropdownModelForm class Media: js = ('dropdown/js/base.js',) admin.site.register(DropdownModel, DropdownModelAdmin) [Step Three] Add javascript. I take no credit for this script; I only modified it slightly from here. base.js (function($) { $(function() { var selectField = $('#id_date_range'), verified = $('.abcdefg'); function toggleVerified(value) { if (value === 'Custom') { verified.show(); } else { verified.hide(); } } // show/hide on load based on existing value of selectField toggleVerified(selectField.val()); // show/hide on change selectField.change(function() { toggleVerified($(this).val()); }); }); })(django.jQuery); [Step Four] forms.py from django import forms from dropdown.models import DropdownModel class DropdownModelForm(forms.ModelForm): class Meta: model = DropdownModel fields = ('date_range',) widgets = { 'date_range': forms.Select(choices=DropdownModel.CHOICES) }
accepted answer of: http://stackoverflow.com/q/47838059
upvote count: 22

http://stackoverflow.com/comment/82367601
score: 0
comment on: http://stackoverflow.com/q/47703368
has text: When you create an object it doesn't show '-------'? It's the default django behaviour on create.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82635593
type: QuestionComment
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47835727
has text: hm - never saw it - only c-style `%s`. I don't code with python much

http://stackoverflow.com/q/47738532
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47738568
has answer: http://stackoverflow.com/a/47738568
downvote count: 0
has answer: http://stackoverflow.com/a/47738606
possible better answer: http://stackoverflow.com/a/47738585
tagged with: python
has title: Is __init__.py required for every python package? [new feature since python 3.3+]
tagged with: python-3.6
has body: I have see this in python tutorial: The __init__.py files are required to make Python treat the directories as containing packages; I make the directory hierarchy in pycharm like this, where the subdir1 doesn't contain __init__.py and subdir2 contains a __init__.py file. First, I add Directory into system.pyth. I write a hello function in hello1.py and hello2.py respectively. Then I call hello func in test files like this: # test1.py from subdir1 import hello1 hello1.hello() # test2.py from subdir2 import hello2 hello2.hello() They all succeed. It seems that the __init__.py does not necessary for import modules from different directories, right? So, I want to know in what situation a __init__.py is required. Thanks for your answering!
has answer: http://stackoverflow.com/a/47738585
has comment: http://stackoverflow.com/comment/82438359
type: AnsweredQuestion
score: 3
answer count: 3
upvote count: 3
linked to: http://stackoverflow.com/q/448271

http://stackoverflow.com/a/47699013
answers question: http://stackoverflow.com/q/47698756
upvote count: 1
downvote count: 2
type: Answer
score: -1
has body: Use client.invoke() instead of client(). You can refer to official guide.

http://stackoverflow.com/a/47793054
downvote count: 0
answers question: http://stackoverflow.com/q/47790526
has body: You can pass in a modified PATH for the subprocess with env=. from subprocess import Popen from os import environ from os.path import join as path_join myenv = environ.copy() if 'VIRTUAL_ENV' in environ: myenv['PATH'] = ':'.join( [x for x in environ['PATH'].split(':') if x != path_join(environ['VIRTUAL_ENV'], 'bin')]) Popen(['command', '--with', 'arguments'], env=myenv)
score: 3
type: Answer
upvote count: 3

http://stackoverflow.com/comment/82646962
type: QuestionComment
score: 0
has text: You should always supply a `newline=''` keyword argument when opening csv files in Python 3. Try adding that.
comment on: http://stackoverflow.com/q/47841302
type: Comment

http://stackoverflow.com/comment/82519826
has text: Welcome to Stackoverflow! Please fix the indentation in your code and make sure you have a [MCVE].
comment on: http://stackoverflow.com/q/47779291
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82695331
type: Comment
type: AnswerComment
has text: I give you an example of required fields, you might add somes new fields witch sould be passed to the create method.
comment on: http://stackoverflow.com/a/47853795
score: 0

http://stackoverflow.com/q/47792669
tagged with: django
type: AnsweredQuestion
has title: how to handle httpresponseredirect
has answer: http://stackoverflow.com/a/47792768
tagged with: python
type: Question
has body: test2/urls.py from django.conf.urls import url from .import views from .forms import forms urlpatterns=[ url(r'^$',views.index,name='index'), url(r'^thankyou/$',views.thankyou,name='thankyou') ] test1/urls.py from django.contrib import admin from django.conf.urls import url , include urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^test2/',include('test2.urls')), ] views.py this view should redirect to /test2/thankyou/ but why it is going to /thankyou and what to do enable the view given by redirect method from django.shortcuts import render from django.http import HttpResponseRedirect,HttpResponse from .forms import Get_name # Create your views here. def index(request): if request.method == 'POST': form = Get_name(request.POST) if form.is_valid(): return HttpResponseRedirect('/thankyou/') else: form = Get_name() return render(request, 'test2/name.html' , {'form':form}) def thankyou(request): return HttpResponse('sai chaitanya') name.html after submitting the form it should redirect to test2/thankyou but it is going to /thankyou. &lt;form action="/thankyou/" method="post"&gt; {% csrf_token %} {{ form.as_p }} &lt;input type="submit" value="Submit" /&gt; &lt;/form&gt; forms.py from django import forms user_choice =[('space',''),('passenger','Passenger'),('driver','Driver')] class Get_name(forms.Form): user_name = forms.CharField(label='user name',max_length='50',required=True) pass_word1 = forms.CharField(widget=forms.PasswordInput,max_length='20',label='Password') pass_word2 = forms.CharField(widget=forms.PasswordInput, max_length='20', label='Confirm Password') email = forms.EmailField(label='email',max_length='100') mobile = forms.CharField(label='contact number ',widget=forms.NumberInput,max_length='10') address = forms.CharField(label='Address',max_length='100') user_type = forms.CharField(label='select user type',widget=forms.Select(choices=user_choice))
score: 0
accepted answer: http://stackoverflow.com/a/47792768
answer count: 1

http://stackoverflow.com/a/47723651
has comment: http://stackoverflow.com/comment/82543601
has comment: http://stackoverflow.com/comment/82423713
has comment: http://stackoverflow.com/comment/82409546
has comment: http://stackoverflow.com/comment/82409531
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/82422120
downvote count: 0
has comment: http://stackoverflow.com/comment/82422981
has comment: http://stackoverflow.com/comment/82423360
has comment: http://stackoverflow.com/comment/82422897
has comment: http://stackoverflow.com/comment/82408835
has comment: http://stackoverflow.com/comment/82421798
has comment: http://stackoverflow.com/comment/82420860
answers question: http://stackoverflow.com/q/47723508
has body: If you want to write out each 5th row you can simply do df.iloc[::5, :].to_csv('file_name.csv') whereby df is a pandas dataframe created like this: import pandas as pd df = pd.read_csv('input.csv') Otherwise, you can also do # define all indexes here out_rows = [1, 5] df.iloc[out_rows, :].to_csv('file_name.csv') You need to specify in more detail what exactly you want to achieve, then we can help better. EDIT: As far as I understand now, you want to select based on floats close to certain values. This might be a bit hacky and also assumes that you don't leave out integers (which seems to be a reasonable assumption based on your description of the values): Let's say your df looks like this (replace by actual data): x, y 0 0.955425 1 1 0.602229 2 2 1.520194 6 3 1.748095 1 4 2.422760 0 5 2.051359 6 6 3.268572 9 7 3.981412 1 8 4.687532 0 9 4.215138 8 10 5.029877 7 11 5.197888 7 12 6.795040 1 13 6.452637 0 14 7.413032 8 15 7.127841 5 16 8.597014 7 17 8.002060 8 18 9.713273 3 19 9.912318 7 As written, first sort the values according to x, df = df.sort_values('x,') x, y 1 0.602229 2 0 0.955425 1 2 1.520194 6 3 1.748095 1 5 2.051359 6 4 2.422760 0 6 3.268572 9 7 3.981412 1 9 4.215138 8 8 4.687532 0 10 5.029877 7 11 5.197888 7 13 6.452637 0 12 6.795040 1 15 7.127841 5 14 7.413032 8 17 8.002060 8 16 8.597014 7 18 9.713273 3 19 9.912318 7 Then add a helper column where you floor the values in x, df['helper'] = df['x,'].apply(np.floor).astype(int) x, y helper 1 0.602229 2 0 0 0.955425 1 0 2 1.520194 6 1 3 1.748095 1 1 5 2.051359 6 2 4 2.422760 0 2 6 3.268572 9 3 7 3.981412 1 3 9 4.215138 8 4 8 4.687532 0 4 10 5.029877 7 5 11 5.197888 7 5 13 6.452637 0 6 12 6.795040 1 6 15 7.127841 5 7 14 7.413032 8 7 17 8.002060 8 8 16 8.597014 7 8 18 9.713273 3 9 19 9.912318 7 9 Now drop the duplicates in helper: df = df.drop_duplicates('helper') x, y helper 1 0.602229 2 0 2 1.520194 6 1 5 2.051359 6 2 6 3.268572 9 3 9 4.215138 8 4 10 5.029877 7 5 13 6.452637 0 6 15 7.127841 5 7 17 8.002060 8 …
has comment: http://stackoverflow.com/comment/82409521
has comment: http://stackoverflow.com/comment/82409112
has comment: http://stackoverflow.com/comment/82423316
type: Answer
has comment: http://stackoverflow.com/comment/82422503
has comment: http://stackoverflow.com/comment/82422081
has comment: http://stackoverflow.com/comment/82408890
has comment: http://stackoverflow.com/comment/82409539

http://stackoverflow.com/comment/82481499
type: AnswerComment
comment on: http://stackoverflow.com/a/47759916
score: 0
has text: My application requires some user input via console. Can I still use pyinstaller for that?
type: Comment

http://stackoverflow.com/comment/82548218
type: Comment
has text: `DoL["Face{}".format(i)]["FaceOuterBounds"] = fobId` should do it
score: 0
comment on: http://stackoverflow.com/q/47793442
type: QuestionComment

http://stackoverflow.com/comment/82562597
has text: @juanpa.arrivillaga I dont know if you are being sarcastic, but I actually mean it. Not C-Style for loops, namedtuple... and the readability will improve by a factor of over 9000. IMO.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47800252

http://stackoverflow.com/a/47789254
accepted answer of: http://stackoverflow.com/q/47788448
has body: Change to below and there should not be any issues. df1['EW'] = df1['EW'] + ' v ' + df1['WE'] df1['WE'] = df1['DA'] df1['DA'] = df1['DD'] df2['EW'] = df2['AB'] + ' v ' + df2['AC'] df2['EW'] = df2['AB'] + ' v ' + df2['AC'] df3 = pd.merge(df2, df1, on='EW') df3 = df3.rename(columns={'WE':'O1','AD':'O2'}) df3['D'] = df3['O2'].sub(df3['O1'], fill_value=0)
downvote count: 0
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47788448
score: 1
type: Answer

http://stackoverflow.com/a/47787367
score: -1
answers question: http://stackoverflow.com/q/47787289
upvote count: 0
has body: GOT IT :) just had to change status = soup.find('span',{'class':'classname'}).get_text to status = driver.find_element_by_xpath("xpath").text
downvote count: 1
has comment: http://stackoverflow.com/comment/82535761
type: Answer

http://stackoverflow.com/a/47844895
has body: Your solution sounds clean. You can also create a list of past defaults with defaults.append(..) then refer to defaults[-6] If the loan term is very long, you can use collections.deque with a fixed capacity of 6 instead of a list to avoid keeping excessive old calculations.
answers question: http://stackoverflow.com/q/47844719
has comment: http://stackoverflow.com/comment/82654555
type: Answer
accepted answer of: http://stackoverflow.com/q/47844719
score: 0
type: AcceptedAnswer

http://stackoverflow.com/q/47705520
favorite count: 0
has answer: http://stackoverflow.com/a/47705769
type: AnsweredQuestion
has body: My code here has a problem but I know what the problem is. There are 2 characters in grade, so 2 results are shown, each result is added by 0.3. That is a problem because only one result is supposed to be printed to the console. keydict = {'A': 4.0,'B': 3.0,'C': 2.0,'D': 1.0,'F': 0, '+': 0.3, '-': -0.3} grade = input('Grade:') def letter2number(letter): if len(grade) &gt; 2: print('Too many characters') letter2number(grade) for char in grade: if char in keydict: if '+' in grade: print(keydict[char] + keydict['+']) elif '-' in grade: print(keydict[char] + keydict['-']) else: print(keydict[char]) else: print(grade,'is an invalid input') return letter2number(grade) This is what gets printed to the screen after the user inputs "A+"(or any grade with a '+' or '-') I realize the for loop is causing this problem because there are 2 characters in the input. But I don't think there is another way to do it without using a for loop. The 4.3 is expected, the 0.6 is not what I want. Grade: A+ # &lt;&lt;&lt; Thats a user input 4.3 # &lt;&lt;&lt; YES 0.6 # &lt;&lt;&lt; How can I get this to NOT print Other than the 0.6 being printed, I have no other issue with the code. In other words, I don't want the 0.6 there, but the 4.3 should stay.
has answer: http://stackoverflow.com/a/47705698
possible better answer: http://stackoverflow.com/a/47705769
answer count: 4
type: Question
upvote count: 4
tagged with: python-3.x
has title: How can I get only 1 result to be printed to the console and not both of them?
has answer: http://stackoverflow.com/a/47705575
accepted answer: http://stackoverflow.com/a/47705638
downvote count: 0
has comment: http://stackoverflow.com/comment/82371249
tagged with: python
score: 4
has answer: http://stackoverflow.com/a/47705638

http://stackoverflow.com/a/47813574
has body: Reading each line in includes the trailing newline. Your print() also includes a newline so you will get an empty row. Try print(sentence, end='') as follows: filename = input("Enter file name: ") with open(filename, encoding="UTF-8") as f_input: for sentence in f_input: sentence = sentence.upper() for letter in sentence: if letter == "Ä": lause = sentence.replace(letter, "AE") elif letter == "Ö" or täht == "Õ": lause = sentence.replace(letter, "OE") elif letter == "Ü": lause = sentence.replace(letter, "UE") print(sentence, end='') Note: using with open(... will also automatically close your file afterwards. You might also want to consider the following approach: # -*- coding: utf-8 filename = input("Enter file name: ") replacements = [('Ä', 'AE'), ('ä', 'ae'), ('Ö', 'OE'), ('ö', 'oe'), ('Õ', 'OE'), ('õ', 'oe'), ('Ü', 'UE'), ('ü', 'ue')] with open(filename, encoding='utf-8') as f_input: text = f_input.read() for from_text, to_text in replacements: text = text.replace(from_text, to_text) print(text) This does each replacement on the whole text rather than line by line. It also preserves the case.
answers question: http://stackoverflow.com/q/47813448
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/47813448
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/82588610

http://stackoverflow.com/comment/82358750
comment on: http://stackoverflow.com/a/47699307
type: Comment
type: AnswerComment
score: 0
has text: @Mücahit Demirhan Great. The way this site works is that you can upvote the answer and mark it as accepted.

http://stackoverflow.com/comment/82543626
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47791050
has text: When I try that, I get the following error message: AttributeError: 'ClientTLSOptions' object has no attribute 'getContext'. I tried this before and it seemed to me that passing ClientTLSOptions to the Agent won't work.

http://stackoverflow.com/a/47820996
downvote count: 0
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47820757
has body: Short answer: Use from . import secondary Longer version: It looks like you assume Python 2 relative import semantics, when this is Python 3 with absolute import semantics. Have a look e.g. here for a more detailed explanation. If you do import secondary this is an absolute import, and thus is not resolved relative to the current package, but rather from sys.path. When you execute run.py as a Python script (not as a module with -m), the directory the script resides in gets added to sys.path automatically, which is why importing Vers.1_1.Main works, but import secondary does not.
answers question: http://stackoverflow.com/q/47820757
has comment: http://stackoverflow.com/comment/82604467
has comment: http://stackoverflow.com/comment/82604554
score: 1
has comment: http://stackoverflow.com/comment/82604514
type: Answer
has comment: http://stackoverflow.com/comment/82622248

http://stackoverflow.com/q/47822968
score: 1
upvote count: 1
tagged with: kivy
has answer: http://stackoverflow.com/a/47823446
favorite count: 0
accepted answer: http://stackoverflow.com/a/47823446
type: Question
answer count: 1
tagged with: python
has body: In the following code i don't explain two problems: If I use method __init__ --> Scene.canvas = None I don't underestand to relative position objects on image. I wanted to obtain knowledges about coordinates system from Kivy Manual, but without success. from kivy.app import App from kivy.uix.widget import Widget from kivy.core.window import Window from kivy.lang import Builder from kivy.uix.image import Image from kivy.graphics import Ellipse class Scene(Widget): """ def __init__(self): self.x = 0 self.y = 100 self.dir = 1 """ def set_par(self): self.x = 0 self.y = 100 self.dir = 1 def create_ball(self): with self.canvas: Ellipse(pos = (0,0), size = (40, 40)) img = Image(pos = (0,0), source = 'image1.png') # square 40x40pixels self.add_widget(img) class SceneApp(App): def build(self): scene = Scene() scene.create_ball() return scene if __name__ == '__main__': SceneApp().run() Printscreen form my code:
type: AnsweredQuestion
has title: Kivy: Coordinates
downvote count: 0

http://stackoverflow.com/comment/82427930
type: AnswerComment
comment on: http://stackoverflow.com/a/47733705
has text: Awesome! Thanks for your time.
score: 0
type: Comment

http://stackoverflow.com/comment/82794670
type: Comment
has text: https://www.youtube.com/watch?v=K5F-aGDIYaM&list=PL6gx4Cwl9DGAjkwJocj7vlc_mFU-4wXJq Here's the playlist. The suggestion on the other page worked partly, meaning that it doesn't click through all the loops now, but the button function now works at random times. I have to click multiple times to get to the next loop and it always proceeds whenever, at a random click. So I don't really know how to continue now.
comment on: http://stackoverflow.com/q/47751594
score: 0
type: QuestionComment

http://stackoverflow.com/comment/82653349
type: Comment
type: AnswerComment
score: 1
has text: Removed the list() around set and added a function based on your solution to reapply, hope you don't mind. +1
comment on: http://stackoverflow.com/a/47838216

http://stackoverflow.com/comment/86894184
comment on: http://stackoverflow.com/q/47766722
has text: @justin can you please suggest how to store the model to hdfs by using pickle option
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/47702285
possible better answer: http://stackoverflow.com/a/47702386
has comment: http://stackoverflow.com/comment/82364883
tagged with: python-3.x
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47702386
has answer: http://stackoverflow.com/a/47702499
tagged with: python
has answer: http://stackoverflow.com/a/47702539
has answer: http://stackoverflow.com/a/47702319
answer count: 4
has title: Replace random value in string with random value
type: Question
has comment: http://stackoverflow.com/comment/82364563
tagged with: list
tagged with: random
score: 1
accepted answer: http://stackoverflow.com/a/47702319
downvote count: 0
upvote count: 1
tagged with: string
has body: virus is supposed to be a string of nucleotides, and the function should return a string consisting of the same amount of nucleotides, but one is changed. def mutate(virus): mutations = ['A', 'T', 'C', 'G'] virus.split random.randrange(1, stop=len(virus), step=1) = random.choice(mutations) so for example if the virus is ATCG it should return something like ATCC or GTCG, how can I go about this, I tried making virus into a list, and replacing a random variable in it with a random of my possible mutations list. So it should probably make a list from the string virus, do a mutation, put the list back into a string and return the string.
favorite count: 0

http://stackoverflow.com/comment/82548004
comment on: http://stackoverflow.com/a/47778664
type: AnswerComment
score: 0
type: Comment
has text: Why pass `tk.Frame` in OptionMenu?

http://stackoverflow.com/q/47726858
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/47735892
favorite count: 0
tagged with: accordion
has body: I want to create an Accordion containing content consisting of an RstDocument and a button. The Accordion shall be scrollable as well as the content of the RstDocument when this content is larger than the given space. So I came up with the following code but after some clicks on AccordionItems all further interaction is blocking. What am I doing wrong here? from kivy.app import App from kivy.uix.scrollview import ScrollView from kivy.uix.rst import RstDocument from kivy.core.window import Window from kivy.uix.boxlayout import BoxLayout from kivy.uix.accordion import Accordion, AccordionItem from kivy.uix.button import Button class ShowrstApp (App): def update_size(self, instance, *args): instance.size = 60 * len(instance.children) def build (self): numitems = 10 root = BoxLayout() accheight = numitems * 60 accitems = Accordion(id='acc_panel', orientation='vertical', pos_hint={'top': 1}, size_hint_y=None, height=accheight, md_bg_color=(1, 1, 1, 1)) for i in xrange(numitems): item = AccordionItem(title='This is item: %d' % i) somecontent = BoxLayout(orientation='vertical') somecontent.add_widget(RstDocument(text='Some nicely formatted text here')) somecontent.add_widget(Button(text='click here', height=(42), size_hint=(1,None))) item.add_widget(somecontent) item.bind(children=self.update_size) accitems.add_widget(item) sv = ScrollView(do_scroll_x = False) sv.add_widget(accitems) root.add_widget(sv) return root Window.size = (350,650) showrst = ShowrstApp() showrst.run()
tagged with: python
has title: RstDocument in kivy Accordion is blocking all interaction
tagged with: kivy
type: Question
tagged with: kivy-language
has answer: http://stackoverflow.com/a/60606618
answer count: 2
type: UnansweredQuestion
downvote count: 0

http://stackoverflow.com/a/47737661
has body: In this case, update() behaves like this: for key, value in batman.items(): super_hero_names[key] = value Here, super_hero_names.update(batman) first checks whether super_hero_names has 'Batman' key. If exist, it overwrite (or update) the value. If not, it create 'Batman' and just assign the value to the key. Added: Here is a sample code. Instead of using dictionary as a data container, I used list to hold multiple superman dictionaries. As you said, dictionary is mutable, so update method modifies the contents in the list of super_hero_names. superman = {'Superman' : 'Clark Kent'} spiderman = {'Spiderman' : 'Peter Parker'} super_hero_names = [ superman, spiderman ] batman = {'Batman' : 'Bruce'} super_hero_names.append(batman) print(super_hero_names) # [{'Superman': 'Clark Kent'}, {'Spiderman': 'Peter Parker'}, {'Batman': 'Bruce'}] batman.update({'Batman': 'test'}) print(super_hero_names) # [{'Superman': 'Clark Kent'}, {'Spiderman': 'Peter Parker'}, {'Batman': 'test'}]
type: Answer
has comment: http://stackoverflow.com/comment/82436462
has comment: http://stackoverflow.com/comment/82436576
score: 0
has comment: http://stackoverflow.com/comment/82461174
has comment: http://stackoverflow.com/comment/82435639
answers question: http://stackoverflow.com/q/47737470

http://stackoverflow.com/q/47730785
has answer: http://stackoverflow.com/a/47744623
type: AnsweredQuestion
score: 2
tagged with: list
tagged with: vrml
upvote count: 2
answer count: 1
downvote count: 0
tagged with: coordinates
has comment: http://stackoverflow.com/comment/82423878
favorite count: 0
type: Question
has title: Parsing a file by blocks and extracting information from each of the blocks with Python
has comment: http://stackoverflow.com/comment/82424167
tagged with: python
accepted answer: http://stackoverflow.com/a/47744623
has body: I'm trying to parse some blocks of text in a vrml file. Specifically I'm interested in the information contained in the IndexedFaceSets which represents a series of triangles defined by its coordinate points (field Points) and the conectivity between the points (field coordIndex). I have managed to create a function that parses a single indexedFaceSet (the first one) of text but I cannot get my head around as to how to modify the code so I can store the following list [translate,verts,facets,normals] for each IndexedFaceSet. My function is: def extractDataFromVRML(root): #Lists to be populated translate=[] verts=[] facets=[] normals=[] #Parsing the vrml file f=open(root+'.wrl') while 1:# skip through initial stuff linney=str.split(f.readline()) # print linney if len(linney) == 4: if linney[0] == 'translation': #Not shown in th vrml example transx = float(linney[1]) transy = float(linney[2]) transz = float(linney[3]) t=[transx,transy,transz] translate.append(t) if linney == ['point', '[']: break #print 'Reading vertex coordinates.' while 1: xyz = f.readline() i = str.find(xyz,',') if i &lt; 0: # end of vertex coordinates break verts.append(xyz[:i]) # building a list of xyz strings print ('We have',len(verts)-1,'vertices.') #for v in verts: print v print ('Reading triangles.') while 1: linney=f.readline() if linney == '}\n': break # end of file abc = str.split(str.replace(linney,',',' ')) # l of vertex ids if len(abc) &lt; 3: continue # separation between groups of triangles # look up a vertex in the list to generate a triangle tuple xyz = str.split(verts[int(abc[0])]) p1=[float(xyz[0]),float(xyz[1]),float(xyz[2])] xyz = str.split(verts[int(abc[1])]) p2=[float(xyz[0]),float(xyz[1]),float(xyz[2])] xyz = str.split(verts[int(abc[2])]) p3=[float(xyz[0]),float(xyz[1]),float(xyz[2])] tri=[p1,p2,p3] facets.append(tri) #n=getNormals(p1[0],p1[1],p1[2],p2[0],p2[1],p2[2],p3[0],p3[1],p3[2]) #normals.append(n) print ('END') return [translate,verts,facets,normals] An example of a c…
tagged with: parsing

http://stackoverflow.com/q/47756222
type: UnansweredQuestion
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/82473622
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/82473669
has comment: http://stackoverflow.com/comment/82473514
tagged with: django-models
type: Question
has body: I'm trying to save some informations to my model, since my list of fieldname is dynamic I'd like to loop and save those informations to the fields rather than using conditions. models.py class Company(models.Model): name = ... email = ... phone = ... ... views.py company = get_object_or_404(Company, slug=slug) text_fields = ['name', 'email', 'phone', 'organisation', 'address', 'website'] #dynamic list, might change depending the user's interaction. for index, json_dt in enumerate(data): #data consists of JSON texts = json_dt['texts'] for text in texts.values(): for field in text_fields: # &lt;-- loop through the list of fieldnames if text['key'] == field: # if json key is equal to fieldname company.field = text['fields']['text'] # save the JSON key's value to the field # Doesn't work because 'field' is a string, what's the solution ? How can I achieve this ?
has comment: http://stackoverflow.com/comment/82474143
has title: How save to model from a string as fieldname?
has comment: http://stackoverflow.com/comment/82474166
has comment: http://stackoverflow.com/comment/82473963

flask-restless
type: Tag
tags question: http://stackoverflow.com/q/47752716
tag name: flask-restless

http://stackoverflow.com/comment/82548263
comment on: http://stackoverflow.com/a/47779053
type: AnswerComment
has text: @KirkBroadhurst Are you sure that, before running `pip install pyspark`, you didn't have Spark already downloaded in your machine?
score: 0
type: Comment

http://stackoverflow.com/comment/82388602
type: Comment
has text: Yes. I've my edited my answer with an example of how to do that. @user3439871
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47705025

http://stackoverflow.com/q/47795309
tagged with: python
has answer: http://stackoverflow.com/a/47795685
favorite count: 0
score: 2
tagged with: deep-learning
upvote count: 2
accepted answer: http://stackoverflow.com/a/47795663
tagged with: classification
has body: I'm using a DNNClassifier and a LinearClassifier (using two different models for the sake of comparison) in TensorFlow to conduct a binary classification on my data set. I've successfully gotten both models to work and output metrics about the accuracy. However, what I would like is to be able to get some type of array out containing all of the predictions the model made on the test. Ideally these predictions would have some probability associated with them as well. Searching on StackOverflow and the TensorFlow GitHub page led me to these lines of code to extract a prediction: sess = tf.Session() sess.run(tf.global_variables_initializer()) sess.run(results, feed_dict={?}) The only problem is that I have no idea what to put in the feed_dict. Most other askers of this question appear to not be using a premade estimator, and thus I was confused about where to find the equivalent of what they put in feed_dict within my own code. I tried using what I put in my test_input_fn method, but I got a TypeError. Some other key portions of my code look like this: def get_features(array): return {'policy_state': np.array(array[:, 2], dtype=str), 'tiv': np.array(array[:, 4], dtype=int), 'veh_count': np.array(array[:, 5], dtype=int), 'generation': np.array(array[:, 8], dtype=str), 'modern_classic_ind': np.array(array[:, 17], dtype=str), 'h_plus_ind': np.array(array[:, 7], dtype=str)} train_input_fn = tf.estimator.inputs.numpy_input_fn( x=get_features(my_data), y=np.array(np.array(my_data[:, 11], dtype=int)), num_epochs=None, shuffle=True) test_input_fn = tf.estimator.inputs.numpy_input_fn( x=get_features(test_data), y=np.array(np.array(test_data[:, 11], dtype=int)), num_epochs=None, shuffle=True) I am happy to provide additional code/information if necessary
downvote count: 0
has answer: http://stackoverflow.com/a/47795663
tagged with: machine-learning
possible better answer: http://stackoverflow.com/a/47795685
has answer: http://stackoverflow.com/a/47795583
tagged with: tensorflow
type: Question
type: AnsweredQuestion
has title: Estimators: What to use for placeholder in an accuracy prediction?
answer count: 3

http://stackoverflow.com/comment/82464921
has text: Thank you.. i tried above code... but this time "ValidationError at /post-new/ ['ManagementForm data is missing or has been tampered with']"
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47749232

http://stackoverflow.com/comment/82670203
score: 1
type: Comment
comment on: http://stackoverflow.com/q/47852868
has text: You have to pick a representation of your block for RSA to work with because RSA works with integers. The block hash itself would be a good candidate, since it's fixed-length and mitigates some types of attacks.
type: QuestionComment

http://stackoverflow.com/comment/82669104
has text: FWIW, instead of `self.root.after(self.delay,lambda:self.animate(1))` you can use `self.root.after(self.delay, self.animate, 1)`
comment on: http://stackoverflow.com/q/47851027
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82561578
type: QuestionComment
comment on: http://stackoverflow.com/q/47800007
score: 1
has text: `import re; p = re.compile(r'column1'); m = p.search(line); m.start(); m.group(0)`
type: Comment

http://stackoverflow.com/a/47751214
accepted answer of: http://stackoverflow.com/q/47751102
answers question: http://stackoverflow.com/q/47751102
score: 3
upvote count: 3
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82464131
type: Answer
has body: Strings are immutable in python, so if you're going to perform modifications on the string, it would be more efficient to convert the string to a list first. You can then call str.join on the string once you're done. string = list("hello Python program") # somewhat counterintuitive a name for i, j in enumerate([5, 8, 11, 13]): string.insert(i + j, ',') print(''.join(string)) 'hello, Py,tho,n ,program'

http://stackoverflow.com/a/47783651
upvote count: 2
has body: You can make the state group optional using the quantifier ?: à : (?P&lt;city&gt;\S+) (?:\((?P&lt;state&gt;\S+)\) )?\((?P&lt;country&gt;\S+)\) # ^^^ ^^ See the demo. In which case it will match both: à : (?P&lt;city&gt;\S+) \((?P&lt;state&gt;\S+)\) \((?P&lt;country&gt;\S+)\) and à : (?P&lt;city&gt;\S+) \((?P&lt;country&gt;\S+)\)
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47783593
type: Answer
score: 2
answers question: http://stackoverflow.com/q/47783593

http://stackoverflow.com/comment/82532675
type: AnswerComment
has text: If you have another question, please ask it by clicking the [Ask Question](//stackoverflow.com/questions/ask) button. @puneeth Don't rewrite the question.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47784026

http://stackoverflow.com/q/47732012
has body: I have started off by including Tweepy and managed to get a program that is able to output a correct output with a search parameter, however, while trying to create a program that can save and store a person timeline for data analysis I came across a TypeError: must be str, not ResultSet. import tweepy #API keys access auth = tweepy.OAuthHandler("", "") auth.set_access_token("", "") client = tweepy.API(auth) #Opening a file with the name of the user wanted screen = input("Enter the screen name: ") filename = (screen+".txt") file = open(filename, "w") #Getting the Users time line user = client.get_user(screen_name=screen) timeline = user.timeline() #Writing new found data to the file. file.write(timeline) file.close() This code keeps on spitting out the error: Traceback (most recent call last): File "GetTimeLine.py", line 20, in &lt;module&gt; file.write(timeline) TypeError: must be str, not ResultSet However for the set line: file.write(timeline) I add where I want it to become str through the user of file.write(str(timeline)) Throwing out an entirely different error. Traceback (most recent call last): File "GetTimeLine.py", line 20, in &lt;module&gt; file.write(str(timeline)) File "C:\Program Files (x86)\Python\lib\encodings\cp1252.py", line 19, in encode return codecs.charmap_encode(input,self.errors,encoding_table)[0] UnicodeEncodeError: 'charmap' codec can't encode characters in position 4122-4123: character maps to &lt;undefined&gt; To try and fix this I tried to add .(encode"utf-8") however with no luck. Any help greatly appreciated.
tagged with: tweepy
score: 0
linked to: http://stackoverflow.com/q/7782772
answer count: 1
has answer: http://stackoverflow.com/a/47732180
type: Question
type: UnansweredQuestion
tagged with: python
has title: Creating a program to store all the tweets off a page to be stored in a text file for analysis, however getting TypeErrors

http://stackoverflow.com/a/47826967
has body: When using input(), you entered 4 characters: 1,+,2,j. Together, they may have the same semantic value to you as the number 1+2j, but as far as Python is concerned, the former case is just four characters. Python doesn't have any way of knowing you think those characters should be converted to a single numerical value. You can observe the differences with a few print statements. And you can explicitly declare that this four-character string should be interpreted as a complex number, with complex(): a = input('') # input: "1+2j" print(a) # i+2j print(type(a)) # &lt;class 'str'&gt; b = complex(a) print(b) # (1+2j) print(type(b)) # &lt;class 'complex'&gt;
accepted answer of: http://stackoverflow.com/q/47826694
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/47826694
score: 0
has comment: http://stackoverflow.com/comment/83003764
has comment: http://stackoverflow.com/comment/83003564

http://stackoverflow.com/q/47773338
type: Question
has answer: http://stackoverflow.com/a/47775111
tagged with: h2o
has title: Get specific model in H2O stacked model
tagged with: python
type: AnsweredQuestion
score: 0
has body: So I have trained several GBM models using GridSearch in H2O. I then trained an ensemble model like so: from h2o.estimators.stackedensemble import H2OStackedEnsembleEstimator #List of all models in the GridSearch all_model_ids=grid_search_gbm.model_ids ensemble = H2OStackedEnsembleEstimator( model_id = 'ensemble_gbm' , base_models = all_model_ids ) ensemble.train( x=training_columns, y=response_column, training_frame=train, ) I can't how ever extract only specific models from "grid_search_gbm" and feed it into "H2OStackedEnsembleEstimator()". Is there a method for extracting this? For example the 3 best models in 'grid_search_gbm'?
answer count: 1
accepted answer: http://stackoverflow.com/a/47775111

http://stackoverflow.com/comment/82603358
type: AnswerComment
has text: It should work. I updated my answer with all the code that should produce the result except definition of `df`. Check again
comment on: http://stackoverflow.com/a/47818718
type: Comment
score: 0

http://stackoverflow.com/comment/82484055
type: QuestionComment
comment on: http://stackoverflow.com/q/47761036
has text: I have added the code, but it is just a simple plot since I haven't found the way to plot the contour yet.
score: 0
type: Comment

http://stackoverflow.com/q/47795738
has body: How to print logger output onto screen(stdout)? I just want to see the logs on the screen rather than open a file to check. This is just to check my logs. Any simple way to do this?
tagged with: stdout
tagged with: python
type: Question
score: 0
type: UnansweredQuestion
answer count: 1
has title: Python logger test by displaying on stdout
tagged with: logging
has answer: http://stackoverflow.com/a/47807930

http://stackoverflow.com/q/47824785
upvote count: 2
has body: I checked other solutions, but they weren't answering my question. My issue is that whenever I try to capture just one frame from a video (I want to basically take a picture with my webcam) I just get a black window. Code - import cv2 cam = cv2.VideoCapture(0) frame = cam.read()[1] cv2.imwrite('img2.png', frame) cv2.imshow("img1", frame) screenshot - https://i.sstatic.net/oOLCD.jpg My webcam is USB, 720p at 30fps. Thanks.
tagged with: python
downvote count: 1
favorite count: 0
tagged with: opencv
type: AnsweredQuestion
tagged with: webcam
accepted answer: http://stackoverflow.com/a/47824865
has answer: http://stackoverflow.com/a/47824865
score: 1
answer count: 1
tagged with: image
type: Question
has title: Capturing a single frame with Python (using a webcam)

http://stackoverflow.com/q/47782668
has comment: http://stackoverflow.com/comment/82529323
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47821856
accepted answer: http://stackoverflow.com/a/47821856
score: 1
answer count: 1
downvote count: 0
has title: Spyder python console output
tagged with: output
upvote count: 1
tagged with: console
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82528920
tagged with: spyder
tagged with: python
has body: I have a simple quesiton.. I understand that python console is removed for the recent Spyder versions. Is there a way to display outputs that would have been displayed in python console?

http://stackoverflow.com/comment/82533693
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47784369
score: 0
has text: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/161078/discussion-between-shengbao-shui-msft-and-francois).

http://stackoverflow.com/comment/82641746
has text: @JohnnyMopp is asking if `cmd` has `\r` (carriage return) and/or `\n` (newline) at the end of it. This would make the test `cmd.lower() == '#help'` fail. But something like `cmd.lower().startswith('#help')` could still succeed.
comment on: http://stackoverflow.com/q/47838706
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/82478852
score: 5
has text: If it's just one word why don't you just use `==`?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47758810

http://stackoverflow.com/comment/82432529
type: Comment
type: QuestionComment
has text: @xaav - This did not solve the error
comment on: http://stackoverflow.com/q/47735949
score: 0

http://stackoverflow.com/a/47754658
score: 0
has comment: http://stackoverflow.com/comment/82469989
type: Answer
answers question: http://stackoverflow.com/q/47752297
has body: If you wanted to import the sklearn naive_bayes module you should write: from sklearn.naive_bayes import ... but as you said it doesn't have any module with name Data and convert_to_float. So I think you should ask the author saimkhan92 what is the package he wants to import, as it doesn't seem to be any 'official' one.

http://stackoverflow.com/q/47763138
type: Question
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/47763353
has title: Python dict comprehension - access dict during creation
has comment: http://stackoverflow.com/comment/82488113
tagged with: python
has comment: http://stackoverflow.com/comment/82488088
has body: I have a code like this: dictionary = {} for x in dict_of_x: if x['duration_to_cancel'] == None or x['duration_to_cancel'] &gt; 5: key = x['key'] value = x['value'] if key not in dictionary or value &gt; dictionary[key]: dictionary[key] = value I want to make this code a dict comprehension: dictionary = {x['key'] : x['value'] for x in dict_of_x \ if ( True if x['duration_to_cancel'] == None else x['duration_to_cancel'] &gt; 5)} How can I include the second if statement in the 1st code box, to the dict comprehension?
has comment: http://stackoverflow.com/comment/82487693
answer count: 2
accepted answer: http://stackoverflow.com/a/47763354
has comment: http://stackoverflow.com/comment/82488272
score: 0
tagged with: dictionary-comprehension
has answer: http://stackoverflow.com/a/47763354
has answer: http://stackoverflow.com/a/47763353

http://stackoverflow.com/comment/82430140
has text: Sorry but how do I put the CORS headers in the mapping template? thanks
type: QuestionComment
comment on: http://stackoverflow.com/q/47719280
type: Comment
score: 0

http://stackoverflow.com/a/47723905
score: 0
answers question: http://stackoverflow.com/q/47720832
has body: When you click on the excel link it opens the following page : https://data.gov.in/node/ID/download It seems that the ID is the name of the first class of the link eg t.find('a')['class'][0]. Maybe there is a more concise method to get the id but it works as is using the classname Then the page https://data.gov.in/node/ID/download redirects to the final URL (of the file). The following is gathering all the URL in a list : import requests from bs4 import BeautifulSoup URL = 'https://data.gov.in/catalog/complete-towns-directory-indiastatedistrictsub-district-level-census-2011' src = requests.get(URL) soup = BeautifulSoup(src.content, 'html.parser') node_list = [ t.find('a')['class'][0] for t in soup.findAll("div", { "class" : "excel" }) ] url_list = [] for url in node_list: node = requests.get("https://data.gov.in/node/{0}/download".format(url)) soup = BeautifulSoup(node.content, 'html.parser') content = soup.find_all("meta")[1]["content"].split("=")[1] url_list.append(content) print(url_list) Complete code that downloads the files using default filename (using this post) : import requests from bs4 import BeautifulSoup import urllib2 import shutil import urlparse import os def download(url, fileName=None): def getFileName(url,openUrl): if 'Content-Disposition' in openUrl.info(): # If the response has Content-Disposition, try to get filename from it cd = dict(map( lambda x: x.strip().split('=') if '=' in x else (x.strip(),''), openUrl.info()['Content-Disposition'].split(';'))) if 'filename' in cd: filename = cd['filename'].strip("\"'") if filename: return filename # if no filename was found above, parse it out of the final URL. return os.path.basename(urlparse.urlsplit(openUrl.url)[2]) r = urllib2.urlopen(urllib2.Request(url)) try: fileName = fileName or getFileName(url,r) with open(fileName, 'wb') as f: shutil.copyfileobj(r,f) finally: r.close() URL = 'https://data.gov.in/catalog/complete-towns-directory-indiastatedistrictsub-district-level-census-2011' src = requests…
type: Answer

http://stackoverflow.com/q/47785229
tagged with: arrays
downvote count: 1
favorite count: 0
tagged with: optimization
type: Question
has answer: http://stackoverflow.com/a/47785252
tagged with: list
has comment: http://stackoverflow.com/comment/82532007
has comment: http://stackoverflow.com/comment/82532398
linked to: http://stackoverflow.com/q/311775
tagged with: python
has title: Why is it Pythonic to initialize lists as empty rather than having predetermined size?
has body: Short version of my question: Why is it common practice in Python to initialize an empty list even when the size of the list might change many times such as the following: arr = [] for i in range(10): arr.append(i) Isn't it computationally expensive to change the size of an array iteratively? Long version of my question: I'm used to using MATLAB and am relatively new to Python. When I want to create an array, it is common practice in MATLAB to initialize an array of zeros of appropriate size, and then replace the elements of the array with the elements you want to end up with. This is because changing the size of an array iteratively in MATLAB is computationally expensive. Is there something about Python that avoids this expense? When I see people answer Python questions on this website that involve preinitializing a list to be added to, they always create an empty list and subsequently change the size, something I have always regarded as inefficient.
has comment: http://stackoverflow.com/comment/82531866
score: 2
has answer: http://stackoverflow.com/a/47785259
duplicate of: http://stackoverflow.com/q/311775
answer count: 2
upvote count: 3
type: UnansweredQuestion

http://stackoverflow.com/comment/82567416
comment on: http://stackoverflow.com/q/47803002
score: 1
type: Comment
type: QuestionComment
has text: this smells suspiciously like one of those pesky Haskell monads would be useful, if I could only understand it.

virtualenv
tags question: http://stackoverflow.com/q/47772766
tags question: http://stackoverflow.com/q/47790526
tags question: http://stackoverflow.com/q/47854148
tags question: http://stackoverflow.com/q/47767236
tag name: virtualenv
tags question: http://stackoverflow.com/q/47745209
tags question: http://stackoverflow.com/q/47745147
tags question: http://stackoverflow.com/q/47728299
tags question: http://stackoverflow.com/q/47822740
tags question: http://stackoverflow.com/q/47724538
tags question: http://stackoverflow.com/q/47796427
tags question: http://stackoverflow.com/q/47812420
tags question: http://stackoverflow.com/q/47766521
tags question: http://stackoverflow.com/q/47764276
tags question: http://stackoverflow.com/q/47777683
tags question: http://stackoverflow.com/q/47734490
tags question: http://stackoverflow.com/q/47736881
type: Tag
tags question: http://stackoverflow.com/q/47733364
tags question: http://stackoverflow.com/q/47844326
tags question: http://stackoverflow.com/q/47806016
tags question: http://stackoverflow.com/q/47798698
tags question: http://stackoverflow.com/q/47748824

http://stackoverflow.com/comment/82437811
type: Comment
score: 0
type: AnswerComment
has text: Thank you! So, upon pressing the button the functions will be called and the window will close?
comment on: http://stackoverflow.com/a/47730266

http://stackoverflow.com/comment/82587148
score: 0
comment on: http://stackoverflow.com/q/47812714
type: Comment
type: QuestionComment
has text: *Connection* means an entry in the database - what you can do with it is what I proposed already. I can't think of other viable options.

http://stackoverflow.com/q/47744280
downvote count: 0
answer count: 1
has title: Python3/cloud9/lambda - making imported modules available to lambda
score: 6
favorite count: 0
tagged with: aws-lambda
type: Question
has body: Using sqlobject. When I import the module I get a unable to load module error when running lambda local or remote. The module is installed and if I get a command line python3 interpreter and import the module it imports just fine. How do I get 3rd party modules installed so they work with both lambda local and lambda remote? Code could not be simpler: import sqlobject
type: UnansweredQuestion
upvote count: 6
tagged with: python
tagged with: cloud9
has answer: http://stackoverflow.com/a/47784740

http://stackoverflow.com/comment/82561126
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47796453
has text: @Maxim Sorry, added

http://stackoverflow.com/q/47790728
favorite count: 0
type: Question
tagged with: kernel-density
type: UnansweredQuestion
answer count: 1
downvote count: 0
tagged with: gaussian
upvote count: 1
has title: How to work out how far the bandwidth of each gaussian kernel used in my kernel density estimation reaches in my x axis
has body: I have applied kernel density estimation to my binary data of 300 points (xs = 300) to create a continuous function. density = gaussian_kde(plane_pos) density.covariance_factor = lambda : .05 density._compute_covariance() density_p = density(xs) I want to know how the bandwidth, here calculated by .covariance_factor, relates the the dimensions of the x axis. Does each kernel used here have a width from end to end of how many days? How do I work this out?
score: 1
has answer: http://stackoverflow.com/a/47802993
tagged with: python

http://stackoverflow.com/a/47801485
has body: Use sort_level with level and axis parameters: df_out.sort_index(level=1, axis=1)
has comment: http://stackoverflow.com/comment/82742757
score: 3
has comment: http://stackoverflow.com/comment/82742404
type: Answer
has comment: http://stackoverflow.com/comment/82747666
accepted answer of: http://stackoverflow.com/q/47801302
upvote count: 3
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47801302

http://stackoverflow.com/comment/82572276
has text: It is unclear what you are asking. You mean that want to recognize a wrong URL even before the driver tries to navigate to it? Or do you expect an exception but not getting one?
comment on: http://stackoverflow.com/q/47803587
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47718768
tagged with: replace
linked to: http://stackoverflow.com/q/39086
type: Question
tagged with: python-3.x
downvote count: 4
has comment: http://stackoverflow.com/comment/82398337
has comment: http://stackoverflow.com/comment/82398509
has comment: http://stackoverflow.com/comment/82398484
upvote count: 0
accepted answer: http://stackoverflow.com/a/47719225
has comment: http://stackoverflow.com/comment/82397913
has comment: http://stackoverflow.com/comment/82398116
has comment: http://stackoverflow.com/comment/82398365
has comment: http://stackoverflow.com/comment/82398031
has answer: http://stackoverflow.com/a/47719225
tagged with: python
score: -4
has comment: http://stackoverflow.com/comment/82398379
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82397943
has comment: http://stackoverflow.com/comment/82398021
has comment: http://stackoverflow.com/comment/82398301
has body: I have tryed a bunch of other ways of doing it from other forums. But none of them seem to work. Maybe i am just writing them wrong. I have a text file that I want python to replace the "0" with a "1" my text file looks like this 0 hello more stuff meh i want it to be 1 hello more stuff meh Thanks, this is probably really simple. If anyone can post a way to replace the 0 with a 1 or delete a whole line and then rewrite it. Either one works. Thanks I also want it to work if the 0 was on the third line or some other line. You would of course have to change what line it targets
has comment: http://stackoverflow.com/comment/82397890
answer count: 1
has comment: http://stackoverflow.com/comment/82397810
has title: Replacing text certain line with some other text (python) closed
favorite count: 0
has comment: http://stackoverflow.com/comment/82397845
linked to: http://stackoverflow.com/q/16622754

http://stackoverflow.com/comment/82422897
has text: Cleb!: this sort function does not seems to work!. import pandas as pd df = pd.read_csv('file_2.csv') df = df.sort_values('x,'). It give me some error!
comment on: http://stackoverflow.com/a/47723651
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/52410660
upvote count: 5
answers question: http://stackoverflow.com/q/47713596
type: Answer
score: 5
has body: I answered a related question at Feature Importance Chart in neural network using Keras in Python. The only difference I can see here is that rather looking for an explanation of the feature importance for the ensemble metric, you want feature importance per individual prediction. In this case, the same package, ELI5, has functions which can explain individual predictions as well in eli5.sklearn.explain_prediction. I haven't yet had the need to use this functionality, but the documentation there seems straightforward.
downvote count: 0

http://stackoverflow.com/a/48070417
score: 0
type: Answer
answers question: http://stackoverflow.com/q/47814517
has body: Just ran into this problem recently, it might be because you used server = tf.train.Server(...) in your code and didn't pass a config argument, so TF default took all the memory of all your GPU, thus there's no memory left for the worker task. The solution might be: gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction = 0.5) config = tf.ConfigProto(gpu_options = gpu_options) server = tf.train.Server(..., config=config) Anyway, it worked for me, hope that helps you.

http://stackoverflow.com/comment/82676226
has text: Sorry @Steve and Michael Coxon i provided an example array now to make it clearer. I will check the provided answers now.
comment on: http://stackoverflow.com/q/47835565
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/47819525
type: UnansweredQuestion
has body: I've noticed that sometimes when I do a git pull from within the terminal in PyCharm, the focus will shift when the merge completes to whichever file I was editing before I clicked into the terminal. This seems to only happen when the pull command requires a merge and not when I'm "already up-to-date". This is so infuriating, because I almost always have a few more commands to enter into the terminal after pulling from the repo before I want to start editing files, and I almost always end up typing git checkout ... inside some random file. I've searched high and low through the settings, but I can't seem to find anything relevant. How do I turn this focus shift feature off??
tagged with: python
tagged with: pycharm
answer count: 0
score: 1
upvote count: 1
downvote count: 0
tagged with: git
favorite count: 0
has title: How do I turn off the automatic focus shift after "git pull" in PyCharm?
type: Question

http://stackoverflow.com/q/47764623
has body: I am wondering how to increase a variable if a key is held down for longer. I am using Python and PyGame. This is a sample of my code (speed, lap, and distance are defined in previous lines): distance_control = 1 for i in range(amount): x[i] += speedx[i] if x[i] &gt;= 800: x[i] -= 800 lap[i] += 1 if event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: x[2] += 1 distance[i] = (lap[i] - 1)*800 + x[i] I was wondering how to make it so that the longer you hold down the Space Bar, the higher the speed_control goes, and the max speed_control is 5, preferably using some sort of elapsed time thing.
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47764753
tagged with: python
tagged with: pygame
favorite count: 0
has title: How do you compute elapsed time for KEYDOWN. (Python)
accepted answer: http://stackoverflow.com/a/47764753
downvote count: 0
upvote count: 1
tagged with: elapsedtime
score: 1
answer count: 1

http://stackoverflow.com/comment/82418409
type: QuestionComment
comment on: http://stackoverflow.com/q/47728941
score: 0
has text: Actually you need to rethink your whole structure. You shouldn't create variable like that but create classes, use a database or nest them inside a dictionary.
type: Comment

http://stackoverflow.com/q/47713659
favorite count: 0
type: Question
tagged with: object
has body: I want to merge two arrays of objects. The keys are the same but the values might not always be the same. Any solution is appreciated preferably in javascript, but a python solution is fine as well. Here is the sample data: var g= [ { id: 36, name: 'AAA', goal: 'yes' , 'random':27}, { id: 40, name: 'BBB', goal: 'yes' }, { id: 39, name: 'JJJ', goal: 'yes' }, { id: 27, name: 'CCC', goal: 'yes' , lag: "23.3343"}]; var c= [ { id: 36, name: 'AAA', goal: 'yes', color:"purple" }, { id: 40, name: 'BBB', circle: 'yes', color:"purple" }, { id: 100, name: 'JJJ', circle: 'yes'} ]; My expected output should be : var finalData = [{ { id: 36, name: 'AAA', goal: 'yes' ,'random':27, color:"purple"}, { id: 40, name: 'BBB', circle: 'yes', color:"purple"}, { id: 39, name: 'JJJ', goal: 'yes' }, { id: 27, name: 'CCC', goal: 'yes' ,lag: "23.3343"}, { id: 100, name: 'JJJ', circle: 'yes' } }] Here is my current code, it works to some degree but it doesn't add keys it might have missed. var finalData = []; for(var i in g){ var shared = false; for (var j in c) if (c[j].name == g[i].name) { shared = true; break; } if(!shared) finalData.push(g[i]) } finalData = finalData.concat(c); finalData
has answer: http://stackoverflow.com/a/47713910
linked to: http://stackoverflow.com/q/7146217
type: UnansweredQuestion
tagged with: arrays
linked to: http://stackoverflow.com/q/63628199
has comment: http://stackoverflow.com/comment/82387254
downvote count: 0
tagged with: javascript
tagged with: python
has answer: http://stackoverflow.com/a/47714549
score: 3
answer count: 3
has title: Merge two array of objects with same keys, some object won't have the same value?
upvote count: 3
has answer: http://stackoverflow.com/a/47714013
has comment: http://stackoverflow.com/comment/82387377
linked to: http://stackoverflow.com/q/66985164

http://stackoverflow.com/a/47837381
accepted answer of: http://stackoverflow.com/q/47837122
type: Answer
has body: You can use the ipaddress module for Python 3: &gt;&gt;&gt; import ipaddress &gt;&gt;&gt; ip = ipaddress.IPv4Address('10.226.27.60') &gt;&gt;&gt; ip - 1 IPv4Address('10.226.27.59') The IPv4Address class allows for arithmetic operators Docs: https://docs.python.org/3/library/ipaddress.html#operators
upvote count: 4
score: 4
answers question: http://stackoverflow.com/q/47837122
has comment: http://stackoverflow.com/comment/82641180
has comment: http://stackoverflow.com/comment/82638702
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82641586
has comment: http://stackoverflow.com/comment/82639287
has comment: http://stackoverflow.com/comment/82639109

http://stackoverflow.com/comment/82637455
has text: Very neat answer ! +1
type: AnswerComment
comment on: http://stackoverflow.com/a/47836831
score: 0
type: Comment

http://stackoverflow.com/a/47722050
answers question: http://stackoverflow.com/q/47721867
type: Answer
accepted answer of: http://stackoverflow.com/q/47721867
score: 2
upvote count: 2
has body: It seems you want "unfair" dice, so to speak. One way to get this, if you know the desired odds of winning, is to first decide whether you win or not. If you win, then choose a number among the winning numbers. If you lose, choose a number among the losing numbers. For example: import random def die_roll(): if random.random() &lt; 0.26: return random.randrange(25) # 0 to 24 return random.randrange(25, 100) # 25 to 99
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82404818
downvote count: 0

http://stackoverflow.com/comment/82654745
has text: I would like to say create the file using pyinstaller on windows first of all, that's my preference instead of cx_freeze. But if you find cx_freeze easy ,that's all on you. Use windows to convert your .py file into executable and if you want to run the executable on ubuntu/linux distributions then use the wine package on the linux machine, then you can able to run the .exe file easily .
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47845063
score: 0

http://stackoverflow.com/q/47851054
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/47852845
has comment: http://stackoverflow.com/comment/82669849
tagged with: python
has comment: http://stackoverflow.com/comment/82697777
has comment: http://stackoverflow.com/comment/89538261
has comment: http://stackoverflow.com/comment/82697444
answer count: 2
score: 1
has comment: http://stackoverflow.com/comment/82669731
has answer: http://stackoverflow.com/a/47851272
downvote count: 0
has comment: http://stackoverflow.com/comment/82669883
has answer: http://stackoverflow.com/a/51404490
tagged with: django
upvote count: 1
tagged with: django-rest-framework
has title: DELETE method in Django Rest
has body: I am trying to DELETE record in Django Rest. views.py :- class ItemPartialView(generics.RetrieveUpdateDestroyAPIView): queryset = itemlist.objects.all() serializer_class = ItemlistSerializer def put(self, request, *args, **kwargs): return self.partial_update(request, *args, **kwargs) def destroy(self, request, *args, **kwargs): obj = self.get_object() if obj.survey: return Response(data={'message': "Too late to delete"}, status=status.HTTP_400_BAD_REQUEST) self.perform_destroy(obj) return Response(status=status.HTTP_204_NO_CONTENT) urls.py :- urlpatterns = { url(r'^itemlists/$', ItemView.as_view(), name="create"), url(r'^itemlists/(?P&lt;pk&gt;\d+)/$', ItemPartialUpdateView.as_view(), name="update") } Now, when I am sending DELETE request to itemlists/1/ , it is not deleting the record with id = 1 Error is showing Method DELETE not allowed (CREATE, READ, UPDATE are working except DELETE, so I don't think it's cors related issue).
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82669792

http://stackoverflow.com/comment/82394103
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/47716768
type: Comment
has text: @Revolver_Ocelot Prepending a single underscore to a name to mark it as private is merely a stylistic convention, the language does nothing to enforce privacy of such names in any way. Prepending a double underscore (with at most a single trailing underscore) invokes Python's [name-mangling](https://docs.python.org/3/tutorial/classes.html#private-variables) machinery, which _does_ give a form of privacy, but it's primary purpose is to prevent name clashes, and it doesn't really make the name private since the name mangling process is rather basic.

pyopenssl
tag name: pyopenssl
tags question: http://stackoverflow.com/q/47730630
type: Tag
tags question: http://stackoverflow.com/q/47835145

http://stackoverflow.com/comment/82552016
score: 0
has text: @timgeb are undefined.
type: Comment
comment on: http://stackoverflow.com/q/47794595
type: QuestionComment

http://stackoverflow.com/a/47710583
downvote count: 0
answers question: http://stackoverflow.com/q/47710452
has body: It seem that text is generated dynamically so you need to wait until target element contains any text: from selenium.webdriver.support.ui import WebDriverWait as wait element = driver.find_element_by_xpath("//node") text_content = wait(driver, 10).until(lambda driver: element.text)
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/comment/82438364
type: AnswerComment
has text: @JonClements I see. I just tried it with the OP's example using addition and subtraction, which worked. On SO I have seen now [this version](https://stackoverflow.com/a/2371789/8881141), how to parse mathematical expressions. Surely slightly more complicated than using `eval`.
comment on: http://stackoverflow.com/a/47738871
score: 0
type: Comment

http://stackoverflow.com/a/47819924
downvote count: 0
has comment: http://stackoverflow.com/comment/82602800
has comment: http://stackoverflow.com/comment/82602527
answers question: http://stackoverflow.com/q/47819728
has body: Try making the one subtle change in the last line as shown below. You were very close! with open('FILE.txt', 'rb') as f: textfile_temp = f.read() print textfile_temp.split('first ATOMIC CHARGES')[1].split("My charges : -0.0000000")[0] print textfile_temp.split('first ATOMIC CHARGES AND SPIN')[1].split("My charges : -1.0000000")[0] print textfile_temp.split('first ATOMIC CHARGES AND SPIN')[2].split("My charges : 1.0000000")[0] # ^ change this
type: Answer
upvote count: 2
score: 2

http://stackoverflow.com/q/47726706
tagged with: while-loop
has comment: http://stackoverflow.com/comment/82414100
has title: Inserting values into list
has answer: http://stackoverflow.com/a/47726743
has comment: http://stackoverflow.com/comment/82413886
has answer: http://stackoverflow.com/a/47726739
type: Question
has body: I am trying to insert values in a list which is part of while loop, instead of inserting the last value is replacing the one before, so the list will always have only one value!, I am trying to add the values not replacing them, here is my code: while X != 1: resultList = []; #extList = [] count += 1 if X % 2: X = 3 * X + 1 elif not X % 2: X = X // 2 #important to use double slash to have a integer division print(X) resultList.insert(count-1, X) #print("the resultList is " + str(resultList)) #extList.extend(resultList) print("The inputValue "+str(originalValue)+" took "+str(count)+" calculations to reach 1") print (resultList) any help is appreciated
answer count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82413893
tagged with: python
has comment: http://stackoverflow.com/comment/82413895
tagged with: list
score: 0

http://stackoverflow.com/comment/82606561
has text: You changed the order from the desired output; the `order` ordering is desired, not the `region` ordering. And your approach does a full scan of the `order` list *for each region*, so this is a O(NM) solution, while mine is a straight linear approach.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47821920
score: 0

http://stackoverflow.com/comment/105363083
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47793107
score: 0
has text: How could you load and augment images when pixels are already present in the Dataframe like in [this example](https://stackoverflow.com/questions/59596784/custom-imagedatagenerator-for-half-a-million-images-where-labels-and-pixels-ar)? Could you please it there?

http://stackoverflow.com/comment/82411115
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47725037
has text: @Onggia glad to help! This problem utilizes dictionary comprehension, which allows us to create a dictionary in one line. `.format(i)` precisely and elegantly inserts characters into a formatting string, the locations of which denoted by `{}`. `enumerate` iterations over an iterable, returning the current index and value corresponding to that index. Please let me know if you have any questions.
score: 0

http://stackoverflow.com/comment/82460506
type: Comment
score: 0
type: AnswerComment
has text: you are right. your solution is better. was very happy to learn about this TimeGrouper. such a useful tool.
comment on: http://stackoverflow.com/a/47749856

http://stackoverflow.com/comment/82514090
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47775499
type: AnswerComment
has text: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/161042/discussion-between-ice-fire-and-furas).

http://stackoverflow.com/q/47786082
upvote count: 1
favorite count: 0
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47786316
score: 1
has title: Python import class to use as nested/inner class in another class
tagged with: python
has comment: http://stackoverflow.com/comment/82533684
tagged with: class
has body: Python version: Python 3.6 I have this class: class Backup: class Create: @staticmethod def all(): print('create all') @staticmethod def user(username): print('create user: ' + username) @staticmethod def file(filename): print('create file: ' + filename) class Restore: @staticmethod def all(): print('restore all') @staticmethod def user(username): print('restore user: ' + username) @staticmethod def file(filename): print('restore file: ' + filename) class Delete: @staticmethod def all(): print('delete all') @staticmethod def user(username): print('delete user: ' + username) @staticmethod def file(filename): print('delete file: ' + filename) But I want to move the nested classes to their own modules and import them, but I am not sure how to do that. Here was my latest attempt based on some similar stack overflow questions. Obviously it didn't work: from Models.Create import Create class Backup(Create): Does anyone know how to achieve what I am trying to do so I can still call the methods in the classes like this: Backup.Create.all()
accepted answer: http://stackoverflow.com/a/47786316
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82533591
tagged with: inner-classes
answer count: 1
downvote count: 0
linked to: http://stackoverflow.com/q/576169

http://stackoverflow.com/comment/82485169
type: Comment
comment on: http://stackoverflow.com/q/47761782
score: 0
has text: Also, make sure you tokenize your file so that it all gets broken up word-by-word. You can use something like `open(...).read().split()`.
type: QuestionComment

http://stackoverflow.com/q/47747703
tagged with: python-2.7
has body: I have the following data frame df: name event_time ------------------------------------------ Mary [(S, 2017-12-03T03:40:20.000Z), (V, 2017-12-07T02:51:32.000Z)] Peter [(S, 2017-11-02T01:11:10.000Z), (V, 2017-11-19T07:23:12.000Z)] Andy [(S, 2017-12-01T10:31:15.000Z), (V, 2017-12-09T12:31:10.000Z)] I then used the following code to find the time duration of the two elements in the event_time field: df['duration'] = df.event_time.apply(lambda x:x[1][1]-x[0][1]) However, I got the following errors: TypeError unsupported operand type(s) for -: 'unicode' and 'unicode' TypeErrorTraceback (most recent call last) &lt;ipython-input-7-7a191c6f2678&gt; in &lt;module&gt;() ----&gt; 1 df['duration'] = df.event_time.apply(lambda x:x[1][1]-x[0][1]) /opt/conda/envs/python2/lib/python2.7/site-packages/pandas/core/series.py in apply(self, func, convert_dtype, args, **kwds) 2218 else: 2219 values = self.asobject -&gt; 2220 mapped = lib.map_infer(values, f, convert=convert_dtype) 2221 2222 if len(mapped) and isinstance(mapped[0], Series): pandas/src/inference.pyx in pandas.lib.map_infer (pandas/lib.c:62658)() &lt;ipython-input-7-7a191c6f2678&gt; in &lt;lambda&gt;(x) ----&gt; 1 df['duration'] = df.event_time.apply(lambda x:x[1][1]-x[0][1]) TypeError: unsupported operand type(s) for -: 'unicode' and 'unicode' Any idea what I did wrong here? Thanks!
tagged with: pandas
type: AnsweredQuestion
downvote count: 0
upvote count: 1
accepted answer: http://stackoverflow.com/a/47747755
score: 1
answer count: 1
has answer: http://stackoverflow.com/a/47747755
favorite count: 0
has comment: http://stackoverflow.com/comment/82455623
type: Question
has title: Pandas: apply function: TypeError: unsupported operand type(s) for -: 'unicode' and 'unicode'
has comment: http://stackoverflow.com/comment/82455549
tagged with: python

http://stackoverflow.com/comment/82657968
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47841981
has text: Is this python 2 or 3? **Edit:** nevermind see the print statement
type: Comment

http://stackoverflow.com/comment/82541076
type: Comment
has text: it partly works ... It does it only till it found one. all others behind are neglected it looks.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47788878

http://stackoverflow.com/a/47847358
type: Answer
has body: You can use dictionary comprehension: d = {'secondary info': {'location': 'Pune'}, 'primary info': {'age': 22, 'Id': 1234, 'name': 'Mark'}} new_id = 2344 new_d = {a:{c:new_id if c == "Id" else d for c, d in b.items() if c != 'age'} for a, b in d.items()} Output: {'primary info': {'Id': 2344, 'name': 'Mark'}, 'secondary info': {'location': 'Pune'}} Or, you can use recursion for a more robust solution: def update(d, new_id, delemeter='age'): if all(not isinstance(b, dict) for a, b in d.items()): return {a:new_id if a == "Id" else b for a, b in d.items() if a != delemeter} final_data = {a:update(b, new_id, delemeter=delemeter) for a, b in d.items()} return final_data Output: {'primary info': {'Id': 2344, 'name': 'Mark'}, 'secondary info': {'location': 'Pune'}}
score: 0
answers question: http://stackoverflow.com/q/47847282

http://stackoverflow.com/a/47701250
upvote count: 1
score: 1
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/47701206
has body: Something like this will probably work df['new col']=const1*df['is1']+.....+const6*df['im10']
accepted answer of: http://stackoverflow.com/q/47701206
downvote count: 0

http://stackoverflow.com/q/47755445
tagged with: python
score: 2
type: AnsweredQuestion
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/47760737
upvote count: 2
has answer: http://stackoverflow.com/a/47760737
answer count: 1
downvote count: 0
tagged with: pyqt5
has title: Second tray icon message popup crashes app
favorite count: 0
type: Question
has body: I'm building an app that can be "minimized to tray" using Python 3 and PyQt5 on Linux. Once it's hidden and a message shown via trayIcon.showMessage() is dismissed, trying to show the second message causes a segmentation fault. The app watches for changes to a file and notifies the user of occurrences of that match a particular regular expression. When it's hidden, the occurrences are shown to the user via messages with the tray icon. At first I thought it was a result of some threading issue which occurs when the window is hidden due to messages like QObject::startTimer: Timers can only be used with threads started with QThread in the console (and I have no clue why that happens, I didn't create any threads), so I decided to only update the window while it's visible, but that didn't work. I was able to narrow it down to the line that triggers the message: if self.trayIcon.isVisible(): print("about to show message") print(self.fileContentsList[-1]) self.trayIcon.showMessage( "New match!", self.fileContentsList[-1]) But I'm not sure why the segmentation fault happens. I've tried googling but it seems my case is somewhat unique. What could be the issue? EDIT: something i forgot to add: running the app with strace (strace python3 logwatch.py) somehow stopped the segmentation fault from happening. EDIT2: the code is available on GitHub at https://github.com/tehlordvortex/logwatch/ EDIT3: the specific line shown in PyCharm's console is: Process finished with exit code 139 (interrupted by signal 11: SIGSEGV) EDIT4: it seems attaching it to any form a debugger prevents the crash. I tried PyCharm's debugger and valgrind.

http://stackoverflow.com/a/47793201
upvote count: 3
answers question: http://stackoverflow.com/q/47793131
score: -3
type: Answer
has body: Would a shell script be okay? Such as: #!/usr/bin/bash scrapy crawl book -o book.json
downvote count: 6

http://stackoverflow.com/a/47841737
score: 0
answers question: http://stackoverflow.com/q/47841705
type: Answer
has body: Every time you hit 'else', you restart the search by calling search_movie_title(). Unless your search matches on the first entry of movies, you'll be in an infinite loop of else-clause. Remove the else and do that block if the for loop completes without finding a match.

http://stackoverflow.com/comment/82429355
type: QuestionComment
comment on: http://stackoverflow.com/q/47733961
type: Comment
has text: use button `{}` to correctly format code.
score: 0

http://stackoverflow.com/comment/82367176
score: 0
type: Comment
type: QuestionComment
has text: I have updated the post
comment on: http://stackoverflow.com/q/47703005

http://stackoverflow.com/q/47733178
type: Question
has comment: http://stackoverflow.com/comment/82426939
has comment: http://stackoverflow.com/comment/82427106
has title: catch multiple exception does not work
type: UnansweredQuestion
has body: I tried to use try except to catch multiple exception. however I still cannot catch both expection and error is print out as following. any help is appreciate def try_expection(self: try: el = self.element.test_function() except (AttributeError, TypeError): el = self.driver.test_function() Error: def try_expection(self): try: el = self.element.test_function() E AttributeError: 'NoneType' object has no attribute 'test_function'
tagged with: python
has comment: http://stackoverflow.com/comment/82427689
score: 0
has comment: http://stackoverflow.com/comment/82427237
answer count: 0
has comment: http://stackoverflow.com/comment/82426920
has comment: http://stackoverflow.com/comment/82426913

http://stackoverflow.com/a/48382888
answers question: http://stackoverflow.com/q/47817634
downvote count: 0
has body: When working with modbus, even if you're using an high-level library, it's always useful to have close at hand the offical modbus documentation. With the documentation, you can check what each byte of your frame means: 0x01 0x04 0x00 0x00 0x00 0x01 0x31 0xCA The first byte is the device address (0x01) The second byte is the function code (0x04, Read Input Registers) Third and fourth bytes are the starting position (0x00, 0x00) Fifth and sixth bytes are the quantity of outputs (0x00, 0x01) The last 2 bytes are the CRC control (0x31, 0xCA) This means that you are asking for one (0x00, 0x01) registers from the input registers (0x04) from the first position in memory (0x00, 0x00) from device with address 1 (0x01). The frame by itself is correct, and if the device software/firmware follows the modbus standard, you should have an answer: the register that you asked for OR an error frame (0x01, 0x80, crc, crc). This said, we can check why you do not receive an answer from your device. For doing this, if you're not sure about your code/on what you're asking/how your device behave, you can use an external tool to compare the results. I'd suggest you somethink like docklight, that helps you to set up your connection and send/receive modbus frame. First thing I'd check are the connection parameters: client = ModbusClient(method='rtu', port=SERIAL, stopbits=1, bytesize=8, timeout=3, baudrate=BAUD, parity='E') Method is correct, since is the protocol you're asking for. The port is correct, otherwise it gives back a system error. Timeout is what raise the error: in a given time, no response was received. Anyway the problem is probably not here, since you set a high value for timeout. Stopbits should not interfere with the frame reception. The problem could be in baudrate and parity: an error here can cause the error raised by your code. If you do not know the correct value for baudrate and/or parity, you can try with the most commons baudrates and the parity values: 'N', 'E', 'O'…
score: 6
type: Answer
upvote count: 6

http://stackoverflow.com/comment/82373877
comment on: http://stackoverflow.com/a/47705481
score: 1
type: Comment
has text: @user1767754 So you are saying that you think `cv2.imread('some_bogus_file.ext')` should error instead of returning `None`? That's something you can take up with the authors on a GitHub issue, but it is intended behavior. From the [docs for `imread()`](https://docs.opencv.org/master/d4/da8/group__imgcodecs.html#ga288b8b3da0892bd651fce07b3bbd3a56) "The function `imread` loads an image from the specified file and returns it. If the image cannot be read (because of missing file, improper permissions, unsupported or invalid format), the function returns an empty matrix (`Mat::data==NULL`)."
type: AnswerComment

http://stackoverflow.com/comment/82647429
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47769171
has text: df4 = pd.merge(sighting, effort'DATE', 'AREA', 'BEAU','P/S','EFFORT', on = ['DATE', 'AREA', 'BEAU','P/S'], how = 'left') This is equivalent to your code???

http://stackoverflow.com/a/47739274
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82441333
score: 3
has body: IIUC: Source DF: In [213]: this Out[213]: a b c 1 1 5 2 2 2 0 3 3 0 4 2 Solution: In [211]: newThis = pd.DataFrame(np.repeat(this.values, this['b'].replace(0,1).tolist(), axis=0), columns=this.columns) In [212]: newThis Out[212]: a b c 0 1 5 2 1 1 5 2 2 1 5 2 3 1 5 2 4 1 5 2 5 2 0 3 6 0 4 2 7 0 4 2 8 0 4 2 9 0 4 2
type: Answer
accepted answer of: http://stackoverflow.com/q/47739140
has comment: http://stackoverflow.com/comment/82444684
answers question: http://stackoverflow.com/q/47739140
upvote count: 3

http://stackoverflow.com/comment/82473647
score: 0
has text: ok, that's not in the code you show..
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47756176

http://stackoverflow.com/q/47806682
has comment: http://stackoverflow.com/comment/82574771
answer count: 2
has comment: http://stackoverflow.com/comment/82574686
has comment: http://stackoverflow.com/comment/82574862
has body: Any pointers to fix the complex arg below in "hours", i am getting SyntaxError: invalid syntax All I wanted is to reduce as much of the code as possible. i want it at the end to give a value corresponding to value of i. my code fails at (('($200 Hr) estimated at' if i ==1 ) or ('($130 Hr) estimated at' if i == 2 ) or ('($120 Hr) estimated at' if i == 3 ) or ('($125 Hr) estimated at' if i == 4) or ('($90 Hr) estimated at' if i == 5)) Code: brs_items_list.append({ 'desc' : kwargs["brs_d_{}".format(i)], 'hours' : kwargs["brs_hrs_{}".format(i)]+(' hour' if float(kwargs["brs_hrs_{}".format(i)])&lt;2 else ' hours')+ (('($200 Hr) estimated at' if i ==1 ) or ('($130 Hr) estimated at' if i == 2 ) or ('($120 Hr) estimated at' if i == 3 ) or ('($125 Hr) estimated at' if i == 4) or ('($90 Hr) estimated at' if i == 5)) , 'cost' : "${:,}".format(round(float(kwargs["brs_c_{}".format(i)]), 2)) })
has comment: http://stackoverflow.com/comment/82574739
has answer: http://stackoverflow.com/a/47806815
possible better answer: http://stackoverflow.com/a/47806815
has title: Streamlining if-statement condition: 'result1' if a==b else 'result 2' or
has answer: http://stackoverflow.com/a/47806813
type: AnsweredQuestion
score: 0
tagged with: if-statement
has comment: http://stackoverflow.com/comment/82574687
tagged with: python
has comment: http://stackoverflow.com/comment/82574888
type: Question
accepted answer: http://stackoverflow.com/a/47806813

http://stackoverflow.com/comment/82441440
has text: @PaulPanzer Added.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47740114
type: AnswerComment

http://stackoverflow.com/q/47814765
score: 2
answer count: 1
downvote count: 0
favorite count: 0
type: Question
tagged with: python-3.x
upvote count: 2
type: UnansweredQuestion
has body: _source is one method of namedtuple, specified in 8.3. collections — Container datatypes — Python 3.6.4rc1 documentation. An example of its usage: In [90]: Book = namedtuple('Book', 'name, author') In [91]: Book._source Out[91]: "from builtins import property as _property, tuple as _tuple\nfrom operator import itemgetter as _itemgetter\nfrom collections import OrderedDict\n\nclass Book(tuple):\n 'Book(name, author)'\n\n __slots__ = ()\n\n _fields = ('name', 'author')\n\n def __new__(_cls, name, author):\n 'Create new instance of Book(name, author)'\n return _tuple.__new__(_cls, (name, author))\n\n @classmethod\n def _make(cls, iterable, new=tuple.__new__, len=len):\n 'Make a new Book object from a sequence or iterable'\n result = new(cls, iterable)\n if len(result) != 2:\n raise TypeError('Expected 2 arguments, got %d' % len(result))\n return result\n\n def _replace(_self, **kwds):\n 'Return a new Book object replacing specified fields with new values'\n result = _self._make(map(kwds.pop, ('name', 'author'), _self))\n if kwds:\n raise ValueError('Got unexpected field names: %r' % list(kwds))\n return result\n\n def __repr__(self):\n 'Return a nicely formatted representation string'\n return self.__class__.__name__ + '(name=%r, author=%r)' % self\n\n def _asdict(self):\n 'Return a new OrderedDict which maps field names to their values.'\n return OrderedDict(zip(self._fields, self))\n\n def __getnewargs__(self):\n 'Return self as a plain tuple. Used by copy and pickle.'\n return tuple(self)\n\n name = _property(_itemgetter(0), doc='Alias for field number 0')\n\n author = _property(_itemgetter(1), doc='Alias for field number 1')\n\n" However, if we reference it using exec then subsequent calls to _source will raise an error. In [87]: Book = namedtuple('Book', 'name, author') In [88]: exec(Book._source) In [89]: Book._source AttributeError: type object 'Book' has no attribute '_source' What's the mechanism behind it?
has answer: http://stackoverflow.com/a/47815266
has comment: http://stackoverflow.com/comment/82591622
tagged with: python
has title: Namedtuple '_source' method is deactivated after being referenced using 'exec'

http://stackoverflow.com/q/47766158
possible better answer: http://stackoverflow.com/a/75425128
type: AnsweredQuestion
has body: I have a simple flask server defined like so: import sys import flask from flask import request app = flask.Flask(__name__) port = 4057 @app.route('/search', methods=['POST']) def search(): request.json['query'] results = ['fake', 'data'] return flask.jsonify(results) if __name__ == '__main__': app.config['TEMPLATES_AUTO_RELOAD'] = True app.run(host='0.0.0.0', port=port, debug=(port != 80)) I have a simple client defined like this: import json import requests headers = {'content-type': 'application/json'} resp = requests.post('http://localhost:4057/search', json.dumps({'query': 'foo'}), headers=headers) print resp.content The client works, but it takes like 3 seconds to complete the request. curl completes in like half a second: curl 'http://localhost:4057/search' -H 'Content-Type: application/json' -d '{"query": "foo"}'
has comment: http://stackoverflow.com/comment/82493576
has answer: http://stackoverflow.com/a/79066325
has comment: http://stackoverflow.com/comment/82493655
downvote count: 0
tagged with: python-requests
linked to: http://stackoverflow.com/q/19440364
has comment: http://stackoverflow.com/comment/82497042
favorite count: 0
has title: Why is python-requests to localhost slow?
type: Question
has comment: http://stackoverflow.com/comment/82493666
has comment: http://stackoverflow.com/comment/82493582
linked to: http://stackoverflow.com/q/11150343
has answer: http://stackoverflow.com/a/49513878
has comment: http://stackoverflow.com/comment/82493617
has answer: http://stackoverflow.com/a/75425128
accepted answer: http://stackoverflow.com/a/47766293
has comment: http://stackoverflow.com/comment/82493490
has comment: http://stackoverflow.com/comment/82493669
score: 6
has comment: http://stackoverflow.com/comment/82493600
has answer: http://stackoverflow.com/a/47766293
tagged with: python
upvote count: 6
has comment: http://stackoverflow.com/comment/82493494
answer count: 4

http://stackoverflow.com/comment/82673440
type: QuestionComment
score: 0
has text: Made some updates. The increment_value is passed into the script as an argument. I tried passing it in as part of the function call but I get the same results. I also queried the bad_steps variable within the function and it does contain the 2 expected results. It seems that the returned list is 'different'.
type: Comment
comment on: http://stackoverflow.com/q/47853765

http://stackoverflow.com/q/47794195
has comment: http://stackoverflow.com/comment/82549466
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47794513
has answer: http://stackoverflow.com/a/47794513
tagged with: pandas
has comment: http://stackoverflow.com/comment/82549811
has comment: http://stackoverflow.com/comment/82549763
has title: Count consecutives values in time series
tagged with: count
tagged with: python
has body: It's my first time asking a question here, so I hope I will do it right ! I have a Pandas Dataframe: df2.data Out[66]: date 2016-01-02 0.0 2016-01-03 1.0 2016-01-04 1.0 2016-01-05 1.0 2016-01-06 0.0 2016-01-07 0.0 2016-01-08 1.0 2016-01-09 2.0 2016-01-10 1.0 2016-01-11 0.0 Name: data, dtype: float64 I would like the following results : data trend trend_type date 2016-01-02 0.0 0 0 2016-01-03 1.0 0 0 2016-01-04 1.0 1 1 2016-01-05 1.0 2 1 2016-01-06 0.0 0 0 2016-01-07 0.0 1 0 2016-01-08 1.0 0 0 2016-01-09 2.0 0 0 2016-01-10 1.0 0 0 2016-01-11 0.0 0 0 My probleme is a bit related with How to use pandas to find consecutive same data in time series. So far, I managed to get the trend, but it is not efficient enough (about 8 sec for a 750 rows dataframe) df['grp'] = (df.close.diff(1) == 0).astype('int') df['trend'] = 0 start_time = time.time() for i in range(2, len(df['grp'])): if df.grp.iloc[i] == 1: df['trend'].iloc[i] = df['trend'].iloc[i-1] + 1
has comment: http://stackoverflow.com/comment/82549631
has comment: http://stackoverflow.com/comment/82549459
possible better answer: http://stackoverflow.com/a/47794645
has answer: http://stackoverflow.com/a/47794645
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/26911851
has comment: http://stackoverflow.com/comment/82549490
answer count: 2
tagged with: trend
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/82549584
has comment: http://stackoverflow.com/comment/82549379
downvote count: 0
has comment: http://stackoverflow.com/comment/82549947
has comment: http://stackoverflow.com/comment/82549696

http://stackoverflow.com/comment/82482171
has text: `total = 0; for i in range(30): total += values[i]` works...
score: 1
type: Comment
comment on: http://stackoverflow.com/q/47760454
type: QuestionComment

http://stackoverflow.com/q/47743198
downvote count: 1
tagged with: dataframe
tagged with: python
score: -1
tagged with: append
favorite count: 0
upvote count: 0
has comment: http://stackoverflow.com/comment/82446805
has comment: http://stackoverflow.com/comment/82446811
type: UnansweredQuestion
answer count: 1
has body: Hi, I am trying to append four variables (score, gender, class and initials) into a CSV file so it displays as so: with open ('untitled.csv','w') as file_out: file_out.write(score) file_out.write(real_player_class) file_out.write(current_player_gender) file_out.write(current_player_initials) df_test = pd.read_csv('untitled.csv') df_test I would like the result to look like this in a Dataframe: score gender class initials with the stats underneath them, like this: score gender class initials 1 M senior YTU Currently, in my code, this is what the dataframe looks like (in a dataframe): 0seniorMYTU Is there a way to solve this? How do I append the score, gender, class and initials variables into their respective columns? Thanks!
has title: How to append new rows to CSV file with Pandas
type: Question
has answer: http://stackoverflow.com/a/47743244
tagged with: http://stackoverflow.com/tag/csv

http://stackoverflow.com/comment/82633806
has text: As stated below on the answer comment, I've revised the getenv to match your parameter naming
score: 0
type: Comment
comment on: http://stackoverflow.com/q/47834898
type: QuestionComment

http://stackoverflow.com/q/47703471
has comment: http://stackoverflow.com/comment/82367386
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
score: 1
tagged with: python
has answer: http://stackoverflow.com/a/47703920
has body: I would like to use pandas.read_csv to infer only boolean types in the data. If I use dtypes=str, I do not have a simple way to convert my data back to boolean type as the following does not work well. df['bool_column'].astype(bool).eq(False) I do not want to infer all dtypes as I do not want to lose any integer types in the data. Is there a simple solution to this problem?
has title: Pandas read csv infer only bool
answer count: 2
downvote count: 0
tagged with: pandas
upvote count: 1
has answer: http://stackoverflow.com/a/47703711

http://stackoverflow.com/comment/82608573
type: Comment
type: QuestionComment
has text: Given, `l = [3,1,4]` : `a[l[0]:l[0]+l[2]] , b[l[1]:l[1]+l[2]]`?
score: 0
comment on: http://stackoverflow.com/q/47822873

http://stackoverflow.com/comment/82665886
has text: @JohnGordon I changed it to spacing. I do have a question though. If you had 5 spaces instead of four, wouldn't it read as a valid tab and one invalid character? Yeilding an invalid char error instead of an indent error/
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47850594
score: 0

http://stackoverflow.com/comment/82371526
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/47705416
has text: What you you want the output to be? If you just want the single numeric value of `GainFlatness` to appear in one cell, why don't you just write it there?
type: Comment

http://stackoverflow.com/q/47725016
has comment: http://stackoverflow.com/comment/82411287
has comment: http://stackoverflow.com/comment/82410887
answer count: 2
downvote count: 0
upvote count: 1
type: UnansweredQuestion
score: 1
has answer: http://stackoverflow.com/a/47861412
has comment: http://stackoverflow.com/comment/82410988
has comment: http://stackoverflow.com/comment/82411263
has body: I have this data (Small Example) that i import into a script. LastName StartTime EndTime Duration Period TeamAbbrev Position Bouwmeester 0:00 0:37 0:37 1 STL D Schwartz 0:00 0:40 0:40 1 STL W Foligno 0:00 0:40 0:40 1 MIN W Pietrangelo 0:00 0:48 0:48 1 STL D Suter 0:00 0:40 0:40 1 MIN D Staal 0:00 0:40 0:40 1 MIN C Niederreiter 0:00 0:40 0:40 1 MIN W Allen 0:00 20:00 20:00 1 STL G Steen 0:00 0:30 0:30 1 STL W Tarasenko 0:30 1:27 0:57 1 STL W Parayko 0:37 1:43 1:06 1 STL D This is the script import csv from itertools import combinations, product #Header = LastName StartTime EndTime Duration Period TeamAbbrev Position #Import Game with open('2017020397.csv', newline='') as f: next(f) skaters = '\n'.join(' '.join(row) for row in csv.reader(f)) data = skaters.splitlines() def to_secs(ms): ''' Convert a mm:ss string to seconds ''' m, s = map(int, ms.split(':')) return 60 * m + s # Store a list of (start, end) times for each player players = {} for row in data: name, start, end = row.split(None, 3)[:3] times = to_secs(start), to_secs(end) players.setdefault(name, []).append(times) for t in players.items(): print(t) print() # Determine the amount of overlapping time for each combination of players for p1, p2, p3 in combinations(sorted(players), 3): total = 0 # Check each pair of times for this pair of players for t1, t2, t3 in product(players[p1], players[p2], players[p3]): # Compute the overlap in this pair of times and # add it to the total for this pair of players start, end = zip(t1, t2, t3) total += max(0, min(end) - max(start)) if total: print(p1, p2, p3, total) Output: Allen Niederreiter Pietrangelo 5481 Allen Niederreiter Prosser 2088 Allen Niederreiter Reilly 1464 The Purpose of this is to see what Team Mate played with each other. From the Output we can see that Allen from STL is Paired up with Niederreiter from MIN. I only want like team combinations to combine. The TeamAbbrev is how that can be identified. The other stipulation is that the TeamAbbrev will change…
has comment: http://stackoverflow.com/comment/82411223
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47725332
tagged with: python
has title: Categorize data by name with python

http://stackoverflow.com/q/47709529
has title: How to minimize this equation by using cvxpy in python?
upvote count: 1
type: UnansweredQuestion
answer count: 1
downvote count: 1
favorite count: 0
score: 0
has comment: http://stackoverflow.com/comment/82392751
tagged with: cvxpy
has answer: http://stackoverflow.com/a/47710276
tagged with: python
has comment: http://stackoverflow.com/comment/82571608
type: Question
has body: i am new to CVXPY and would like to do some optimization, this is my code: from numpy.linalg import pinv AA=pinv(A) #m*n AAT=AA.T #n*m i1=np.transpose(np.matrix([1,0])) #m*1 i2=np.transpose(np.matrix([0,1])) #m*1 from cvxpy import * import numpy as np from numpy import * #construct the problem x=Variable(1,5) #1*n wx=np.matrix([x[0],x[1],x[2],x[3],x[4]]) #consraints constraints = [x[0]+x[1]+x[2]+x[3]+x[4]==1] for i in range(5): constraints += [ x[i] &lt;= 1, x[i] &gt;= 0, ] Q=wx*A*i1*wx*a*AAT*i1 P=wx*A*i2*wx*a*AAT*i2 objective = Minimize(Q-P) result=prob.solve() print(x.value) where wx is 1 by n matrix (the variable matrix, unknown, to be solved) A is n by m (known),i1 is m by 1 (known),i2 is m by 1 (known) a is n by n (known), AAT is n by m (known) I have A(n by m),and a(n by n): A=[[-4.10272297 -1.94100278] [-0.07551063 0.00533883] [-0.27742026 -0.17370814] [ 0.07785536 -1.02386256] [ 0.77757854 0.04405759]] a=[[ 80.81155556 0.82893333 2.87077778 2.97862222 -18.59855556] [ 0.82893333 0.01547111 0.04784444 -0.05957111 -0.09624444] [ 2.87077778 0.04784444 0.20449444 -0.00278333 -0.3157 ] [ 2.97862222 -0.05957111 -0.00278333 4.68989889 -3.28908889] [-18.59855556 -0.09624444 -0.3157 -3.28908889 9.14991111]] BUT i get the following error: TypeError: &lt;class 'cvxpy.atoms.affine.add_expr.AddExpression'&gt; is not a valid type for a Constant value. it seems I am not solving a convex problem, so the CVXPY doesn't work How can I handle this? I am new to CVXPY so please be specific!Thanks!
has comment: http://stackoverflow.com/comment/82571479
tagged with: nonlinear-optimization

http://stackoverflow.com/a/47734763
downvote count: 0
answers question: http://stackoverflow.com/q/47734686
upvote count: 1
score: 1
type: Answer
has body: I think you're looking for the setattr function. E.g: def func(obj, param, param_values): for param_value in param_values: setattr(obj, param, param_value) # do some stuff end

http://stackoverflow.com/comment/82388689
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47713953
type: AnswerComment
has text: I'm working SQL server, not with MySQL. How to proceed if the process of storing can not be changed? Is there a chance to identify new line characters in an existing database entry while importing it into Pyhton?

http://stackoverflow.com/comment/82597034
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47816669
score: 0
has text: @RyanSandridge: if it happens for the 100th time, it does (similar value for me). More importantly: if the files are not cached, it can take several seconds. So it's either type it and have the next `>>>` prompt available, or feel slightly bored, wait, maybe switch tasks, ...

http://stackoverflow.com/q/47851288
upvote count: 3
tagged with: linkedin-api
downvote count: 0
answer count: 1
has body: I'm currently attempting to scrape data from a specific page on LinkedIn. I have a script that is able to log into LinkedIn, but I run into a snag when I try to access the page containing the data. When I call requests.get(data_url), I end up with the html for the LinkedIn loading screen that is displayed before LinkedIn loads the actual page content. Is there a way to make requests wait for LinkedIn to display the site data before actually scraping the html data? I essentially need to let the page fully render before I can 'get' the contents. My current script is below. import requests from bs4 import BeautifulSoup client = requests.Session() HOMEPAGE_URL = 'https://www.linkedin.com' LOGIN_URL = 'https://www.linkedin.com/uas/login-submit' html = client.get(HOMEPAGE_URL).content soup = BeautifulSoup(html) csrf = soup.find(id="loginCsrfParam-login")['value'] login_information = { 'session_key':'EMAIL', 'session_password':'PASSWORD', 'loginCsrfParam': csrf, } client.post(LOGIN_URL, data=login_information) r = client.get(data_url)
tagged with: javascript
tagged with: web-scraping
accepted answer: http://stackoverflow.com/a/47851306
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47851306
type: AnsweredQuestion
score: 3
tagged with: http://stackoverflow.com/tag/html
has title: Wait for Webpage to fully load before scraping with python requests
tagged with: python

http://stackoverflow.com/a/47754940
accepted answer of: http://stackoverflow.com/q/47746758
has body: You're right, when tf.variable_scope is called with name_or_scope=None, a default_name argument is used and it's uniquified. So calling it in a loop will create different scopes. Not sure about Bahdanau attention, but tf.layers.Dense can be created with a custom scope via _scope argument: layer = Dense(units, ..., _scope=name) In fact, you can call tf.layers.dense with a specified name and this name is going to define tf.variable_scope(name). This way allows you to create dense layers in a loop.
answers question: http://stackoverflow.com/q/47746758
has comment: http://stackoverflow.com/comment/82488431
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/82499317
score: 1
type: Answer

http://stackoverflow.com/q/47828090
has comment: http://stackoverflow.com/comment/82619170
has comment: http://stackoverflow.com/comment/82619594
has comment: http://stackoverflow.com/comment/82618520
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/82618474
has body: I am trying to do a request using python. The API uses: curl -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' -d '{ \ "$class": "org.acme.model.sensor", \ "sensorId": "1", \ "type": "Temperature", \ "value": "10", \ "timestamp": 1234123 \ }' 'http://localhost:3000/api/sensor' to create a new sensor. I am trying to do it with python and I have created the proof of concept: data = { "$class": "org.acme.model.sensor", "sensorId": "", #change in the loop with i "type": "Temperature", "value": "10", "timestamp": 382453824 } header = { "Content-Type" : "application/json", "Accept":"application/json" } url = "http://localhost:3000/api/sensor" for i in range(2): data["sensorId"]=str(i+1) response = requests.post(url, data=data, headers=header) #Now I modify the data data["Temperature"]="50" response = requests.put(url, data=data, headers=header) Now, for erasing: for i in range(2): url="http://localhost:3000/api/sensor/"+str(i+1) response = requests.delete(url) With curl, it works properly but no with the python code. It fails even creating the object.
tagged with: curl
has title: API requests using python
has comment: http://stackoverflow.com/comment/82618852
has answer: http://stackoverflow.com/a/47828386
tagged with: api
score: 1
answer count: 1
downvote count: 0
upvote count: 1
tagged with: python-requests
favorite count: 0
type: Question

http://stackoverflow.com/a/64762394
has body: Use it in Singular form as find_element_by_css_selector instead of using find_elements_by_css_selector as it returns many webElements in List. So you need to loop through each webElement to use Attribute.
type: Answer
answers question: http://stackoverflow.com/q/47735375
score: 2
upvote count: 2
downvote count: 0

http://stackoverflow.com/q/47735771
has comment: http://stackoverflow.com/comment/82515497
has comment: http://stackoverflow.com/comment/82443180
has title: BeautifulSoup soup.find not returning values
score: 2
upvote count: 2
downvote count: 0
answer count: 1
favorite count: 0
has body: I'm trying to scrape a set of pages for some profiles, and I built a scraper that iterates over a list of urls (ex:https://myurl.com) from a csv file and feeds them into beautiful soul. However, soup.find returns no values, despite working when only one URL is given. For example this snippet works: page = requests.get('www.myurl.org') soup = BeautifulSoup(page.text, 'html.parser') name = soup.title.string specialty = soup.find('p', attrs={'id':"content_element_0_main_column_0_ctl09_Spec"}) birthdate = soup.find('p', attrs={'id' : "content_element_0_main_column_0_ctl17_Birth"}) gender = soup.find('p', attrs={'id':"content_element_0_main_column_0_ctl17_Gender"}) email = soup.find('p', attrs={'id':"content_element_0_main_column_0_ctl09_Web"}) f.writerow([name, specialty, birthdate, gender, email]) however, this only returns the field "name" in csv, and none of the subsequent: with open('linklistshort.csv') as inf: urls = (line.strip() for line in inf) for url in urls: print(url) site = urlopen(url).read() soup = BeautifulSoup(site, 'html.parser') name = soup.title.string specialty = soup.find('p', attrs={'id' :"content_element_0_main_column_0_ctl09_Spec"}) birthdate = soup.find('p', attrs={'id' : "content_element_0_main_column_0_ctl17_Birth"}) gender = soup.find('p', attrs={'id':"content_element_0_main_column_0_ctl17_Gender"}) email = soup.find('p', attrs={'id':"content_element_0_main_column_0_ctl09_Web"}) f.writerow([name, specialty, birthdate, gender, email]) The result should be a csv file with five columns, each including the correct data - and this is what I get from the first code block, for the individual url entered. However, the actual output returns five columns, the first filled with the "name" field and the others blank. Clearly, looping through the URLs is working, since name is returning for each url. The only difference in the beautifulSoup command is that I have page.text in the first and only site, however site.text breaks the looping functionality and…
tagged with: beautifulsoup
type: Question
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/52385798
tagged with: python

http://stackoverflow.com/a/47819418
type: Answer
has body: Also, like this maybe? (Inspired from one of my another answers ) In [100]: mask = ~(test == 'a') In [101]: mask Out[101]: array([[ True, True, False], [ True, True, True], [ True, False, True], [ True, True, True]], dtype=bool) In [102]: test[np.all(mask, axis=1), :] Out[102]: array([['4', '5', '6'], ['10', '11', '12']], dtype='&lt;U21') But, please note that here we're not deleting any rows from the original array. We're just slicing out the rows which doesn't have the alphabet a.
score: 3
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/82601019
answers question: http://stackoverflow.com/q/47819146

http://stackoverflow.com/q/47827850
has comment: http://stackoverflow.com/comment/82618021
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/82617960
type: UnansweredQuestion
downvote count: 0
upvote count: 1
tagged with: python
score: 1
has body: I have the following code: def post(self): data = UserActivation.parser.parse_args() check = UserConfirm.check_token(data['email'],data['token']) activate_user = UserConfirm.activate_user(data['email']) if check == False: return {"message": "Invalid Token or Email Address"}, 400 else: if activate_user: return {"message": "Your account is now active"}, 201 else: return {"message": "Error Activating Account"}, 500 that gets passed into UserConfirm class in the user models: def activate_user(email): query_users = "UPDATE users SET activated=1 WHERE email=%s" cursor.execute(query_users, (email,)) For some reason the code doesn't fail nor does it update the database. I tried to put in some error handling as follows just to see what was going on: try: email = data['email'] query_users = "UPDATE users SET activated=1 WHERE email=%s" cursor.execute(query_users, (email,)) return {"message": "done"}, 201 conn.commit() except MySQLdb.Error as e: error=e.args[0], e.args[1] return {"message": error}, 500 I'm using Postman to send the values to the end point and know that it is working properly because the check_token() function works just fine. The strange thing is that the query doesn't throw an error, but also doesn't update the DB. In PhpMyAdmin, I can write out the SQL query as above without any issues. Also, if I deliberately put in the wrong value, it still returns without errors. EDIT I've found the solution to be having to use conn.close()
favorite count: 0
has title: Python MySQL not updating field or returning error
has answer: http://stackoverflow.com/a/47827910
tagged with: mysql-python
tagged with: mysql
has answer: http://stackoverflow.com/a/47827997

http://stackoverflow.com/comment/82665035
type: Comment
type: QuestionComment
has text: Just `gaussian = GaussianNB()` and `treeclassifier = DecisionTreeClassifier()` should work
score: 0
comment on: http://stackoverflow.com/q/47850136

http://stackoverflow.com/q/47731301
tagged with: python-3.6
has comment: http://stackoverflow.com/comment/82423286
has answer: http://stackoverflow.com/a/47731376
favorite count: 0
accepted answer: http://stackoverflow.com/a/47731376
tagged with: list
downvote count: 0
has body: I have a dictionary like this: a= {1982: [(1,2,3,4)], 1542: [(4,5,6,7), (4,6,5,7)]} and I want to change the all the tuples (1,2,3,4),(4,5,6,7),(4,6,5,7) to lists, in this case: [1,2,3,4], [4,5,6,7], [4,6,5,7] I have tried for key, value in a.items(): for i in value: i = tuple(i) but it does now work. How can I achieve it?
upvote count: 1
has answer: http://stackoverflow.com/a/47731418
possible better answer: http://stackoverflow.com/a/47731418
has comment: http://stackoverflow.com/comment/82423257
has answer: http://stackoverflow.com/a/47787841
has title: Convert tuple to list in a dictionary
type: Question
tagged with: tuples
type: AnsweredQuestion
answer count: 3
score: 1
tagged with: python
tagged with: dictionary

http://stackoverflow.com/comment/82595074
score: 0
type: Comment
type: QuestionComment
has text: Did you test your query in any of MySQL editors? Could you also include the schema for the both of the tables?
comment on: http://stackoverflow.com/q/47816703

http://stackoverflow.com/a/47839519
score: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/82643235
type: Answer
has body: I think this is what you want: CouponCode.objects.get(code_number=coupon_code).code_available Using get instead of filter is better is this case, because get returns the object and filter a queryset. I imagine that code_number will be like a Primary Key in your case. And, for what I understand, queryset is used when you don't know how many objects will be returned from the query.
has comment: http://stackoverflow.com/comment/82643087
answers question: http://stackoverflow.com/q/47839218

http://stackoverflow.com/a/51973443
type: AcceptedAnswer
downvote count: 0
score: 3
accepted answer of: http://stackoverflow.com/q/47761090
type: Answer
has body: Python ctypes does not work with C++ types, such as std::string. However, ctypes does work with C language types, such as const char*. See Fundamental Data Types in the Python ctypes documentation.
answers question: http://stackoverflow.com/q/47761090
upvote count: 3

http://stackoverflow.com/comment/82595212
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47808863
has text: @cezar to abide by PEP-8, you need to have lines that are under a certain length. This is common syntax with Django ORM queries.
score: 0

http://stackoverflow.com/q/47707910
accepted answer: http://stackoverflow.com/a/47707931
type: Question
score: 0
has body: Let's say I want to have a list object like in my list_of_employees.py list = [{'name': "John Doe", 'age': 22, 'employed': True}, {'name': "Mary Doe", 'age': 24, 'employed': False}] and that's all that's in that file. How do I do it so that my list_of_employees file only really contains the list object, and how do I import it as an object to say, a employee_processing.py file?
upvote count: 1
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/82375763
favorite count: 0
has title: Importing a python file that only contains an object
has answer: http://stackoverflow.com/a/47707931
type: AnsweredQuestion
tagged with: python

http://stackoverflow.com/comment/82436325
has text: If you understood, close this question by accepting answer :)
score: 0
comment on: http://stackoverflow.com/a/47737634
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/82357293
type: QuestionComment
has text: perfect was looking for such type of knobs. thank you. checking...
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47698654

ode
tags question: http://stackoverflow.com/q/47792503
type: Tag
tags question: http://stackoverflow.com/q/47743164
tag name: ode
tags question: http://stackoverflow.com/q/47836772
tags question: http://stackoverflow.com/q/47711186

http://stackoverflow.com/comment/82599001
comment on: http://stackoverflow.com/q/47818459
score: 0
has text: Don't know; what were you searching for? The first Google result for `Python operator overload` has the information you seek.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82464304
has text: If your problem is indeed large I recommend using an external solver (within `scipy`) such as mosek (https://www.mosek.com/), which was the only solver capable of producing a solution in reasonable time for me.
comment on: http://stackoverflow.com/q/47751187
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/47699010
tagged with: python
type: Question
has body: I'm trying to accommodate a Bar Chart Y axis with a range from 0 to 1 with 1 decimal place like: 1.2 for tick labels: I can set it to start at 0 with: Thisvalue_axis.minimum_scale = 0 And I can set the top value with: Thisvalue_axis.major_unit = 1 But the intermediate tick labels are not showing here is my code: Thisvalue_axis = ThisChart.value_axis Thisvalue_axis.minimum_scale = 0 Thisvalue_axis.major_unit = 1 Thisvalue_axis.minor_tick_mark = XL_TICK_MARK.OUTSIDE Thisvalue_axis.has_minor_gridlines = True Is it possible to Make the values between 0 and 1 display and set the numberformat?
upvote count: 3
answer count: 1
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/47725741
tagged with: python-3.x
type: AnsweredQuestion
has title: Python PPTX - How to set chart axis number format and range
score: 3
has answer: http://stackoverflow.com/a/47725741
tagged with: python-pptx

http://stackoverflow.com/a/47822549
type: Answer
has body: Python datetime objects are comparable and therefore sortable. I assume that you currently don't use datetime objects but Strings. The following example code is taken from How to format date string via multiple formats in python import dateutil.parser dateutil.parser.parse(date_string) You would then convert a list of strings to datetime objects via list_of_dt_objs = [dateutil.parser.parse(str) for str in list_of_strings] Please note that dateutil is an extension lib. So you have to install it, for instance via pip.
score: 1
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47822473

http://stackoverflow.com/q/47723317
tagged with: pandas
has comment: http://stackoverflow.com/comment/82407975
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/82408926
tagged with: python
has comment: http://stackoverflow.com/comment/82407535
has title: Inconsistent time series given equal spacing in matplotlib
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/82408200
accepted answer: http://stackoverflow.com/a/47725120
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/82408908
answer count: 1
has answer: http://stackoverflow.com/a/47725120
has body: I'm plotting a stacked line chart from a pandas dataframe. The data was collected irregularly over the course of two days. In the image below, you can see that the time change between equal intervals varies (~7 hours to ~36 hours between equally spaced intervals). I don't want this to happen, I want points on the graph to be stretched and squeezed appropriately such that time scales linearly with the x-axis. How can I do this? The data was read in as follows: df = pd.read_csv("filepath", index_col=0) df = df.T Above, I had to transpose the dataframe for the pandas stacked line plot to work as I wanted it to. The plot was produced as follows: plot = df.plot.area(rot=90) plot.axhline(y=2450, color="black") In response to ImportanceOfBeingErnest, here is a minimal, complete, and verifiable example: import numpy as np import pandas as pd import matplotlib.pyplot as mpl dateTimeIndex = ["04.12.17 23:03", "05.12.17 00:09", "05.12.17 21:44", "05.12.17 22:34", "08.12.17 16:23"] d = {'one' : pd.Series(abs(np.random.randn(5)), index=dateTimeIndex), 'two' : pd.Series(abs(np.random.randn(5)), index=dateTimeIndex), 'three' : pd.Series(abs(np.random.randn(5)), index=dateTimeIndex)} df = pd.DataFrame(d) plot = df.plot.area(rot=90) Here is what the dataframe looks like (random values will vary): one three two 04.12.17 23:03 0.472832 0.283329 0.739657 05.12.17 00:09 3.166099 1.065015 0.561079 05.12.17 21:44 0.209190 0.674236 0.143453 05.12.17 22:34 1.275056 0.764328 0.650507 08.12.17 16:23 0.764038 0.265599 0.342435 and the plot produced: As you can tell, the dateTimeIndex entries are rather random but they are given equal spacing on the x-axis. I don't mind if the tick marks coincide with the data points. I only want time to scale linearly. How can this be achieved?
favorite count: 0
type: Question

http://stackoverflow.com/comment/82387732
has text: isn't that the byte order mark? (aka BOM)
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47713964

http://stackoverflow.com/comment/82404073
comment on: http://stackoverflow.com/q/47721524
score: 0
type: Comment
type: QuestionComment
has text: @quamrana in other words, I don't dispute what you're saying, but the benchmark might as well be representative of real work that you might want to do.

http://stackoverflow.com/a/47777951
downvote count: 0
score: 4
answers question: http://stackoverflow.com/q/47777776
type: Answer
upvote count: 4
has body: The line "something" + error raises an error which is discarded because you returned from finally. Due to the error the assignment to the dictionary temp is never performed giving the impression that nothing happens. This is stated in the documentation for try-except: If finally is present, it specifies a ‘cleanup’ handler. The try clause is executed, including any except and else clauses. If an exception occurs in any of the clauses and is not handled, the exception is temporarily saved. The finally clause is executed. If there is a saved exception it is re-raised at the end of the finally clause. If the finally clause raises another exception, the saved exception is set as the context of the new exception. If the finally clause executes a return or break statement, the saved exception is discarded. (Emphasis mine) Without an error (i.e temp['except'] = error you get the expected behavior: &gt;&gt;&gt; test() error is :something {'except': ValueError('something')}

http://stackoverflow.com/comment/82359693
type: Comment
comment on: http://stackoverflow.com/q/47699695
type: QuestionComment
has text: @glibdud I'm asking if there's a way of doing argument unpacking-like shorthand syntax, like you might with a list, but with a dict. I don't think the question is off-topic, broad or unclear (personally at least)
score: 0

http://stackoverflow.com/q/47710052
tagged with: multithreading
has title: Multithreading/Async download from single FTP server
downvote count: 0
tagged with: asynchronous
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82379935
score: 3
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47710419
has comment: http://stackoverflow.com/comment/131941624
tagged with: python
has body: I need to download many files from a single folder in a single server and so I'm looking for a way to do it quicker. After a little bit of reading it seems that either a multi-threading or asynchronous approach would work, but I can't seem to get either approach to work. The async approach I'm using is below. This works, i.e. no errors, but it only downloads one file at a time, and so doesn't improve speed. Is there away to modify it so that I do improve speed? async def get_file(self): async with aioftp.ClientSession(self.host, self.port, self.login, self.password) as client: async for path, info in client.list(recursive=True): if info["type"] == "file": await client.download(path, destination=self.dest_dir,write_into=True, block_size=self.block_size) def async_update(self): loop = asyncio.get_event_loop() loop.run_until_complete(self.get_file()) loop.close() Then I tried using the simple Pool() func in multiprocessing as below: def simple_fetch(self,file) file = open(self.dest_dir+filename, 'wb') ftp.retrbinary('RETR ' + filename, file.write, 8192*(2^3)) #, 8192) file.close() def multi_fetch(self): pool = Pool() pool.map(self.simple_fetch,self.update_files) pool.close() pool.join() But this fails with an error. I'll update with that error as soon as I'm back at the server.
tagged with: ftp
tagged with: pool
answer count: 2
has answer: http://stackoverflow.com/a/49121456
upvote count: 3

http://stackoverflow.com/q/47838558
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47842039
answer count: 1
downvote count: 0
has body: Using the Python API, is there a way to retrieve the currently saved view query from Google Big Query? I know I can get view metadata, but I need to be able to save off the actual query. Thanks.
upvote count: 1
accepted answer: http://stackoverflow.com/a/47842039
type: Question
has title: How to get saved query from view in bigquery
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/82643104
tagged with: python
tagged with: google-bigquery
has comment: http://stackoverflow.com/comment/82643809
favorite count: 0
has comment: http://stackoverflow.com/comment/82642213

http://stackoverflow.com/q/47731543
tagged with: sleep
has comment: http://stackoverflow.com/comment/82423927
type: Question
has title: time.sleep function within while loop keeps crashing program, solution or alternative method?
answer count: 2
has body: I am trying to make a space invaders game using turtle, and in order to move the bullet up the screen I am trying to update the y coordinate of the bullet every 0.5 seconds. I tried to do this with a while loop and the time.sleep() function, but everytime I try to fire a bullet, the program crashes. What's wrong, and how can I fix it? import turtle import time userx = 0 x = 0 y = -300 enemies = [(300,50, "left"), (400,50, "left"), (350, -50, "right")] bullets = [] gameover = False def frame(): pass ship = turtle.Turtle() ship.pu() ship.ht() ship.setpos(userx, -300) ship.pd() ship.circle(5) bullet = turtle.Turtle() bullet.pu() bullet.ht() bullet.setpos(x, y) bullet.pd() bullet.circle(2) def key_left(): global userx pass userx += -10 print(userx) def key_right(): global userx pass userx += 10 print(userx) def key_space(): pass # your code here global x global y global bullets x = userx while y <= 300: time.sleep(0.5) y += 4 else: y = 0 bullets += (x,y) def physics(): global bullets global enemies pass def ai(): global enemies global gameover pass def reset(): global enemies global bullets global userx global gameover pass def main(): turtle.tracer(0,0) turtle.hideturtle() turtle.onkey(key_left, "Left") turtle.onkey(key_right, "Right") turtle.onkey(key_space, "space") turtle.listen() reset() while not gameover: turtle.clear() physics() ai() frame() turtle.update() time.sleep(0.05) main()
tagged with: turtle-graphics
has comment: http://stackoverflow.com/comment/82424340
type: UnansweredQuestion
downvote count: 2
has comment: http://stackoverflow.com/comment/82423985
upvote count: 1
has comment: http://stackoverflow.com/comment/82423798
favorite count: 0
has answer: http://stackoverflow.com/a/47732019
has comment: http://stackoverflow.com/comment/82423808
has comment: http://stackoverflow.com/comment/82423728
linked to: http://stackoverflow.com/q/3295938
has answer: http://stackoverflow.com/a/47731754
has comment: http://stackoverflow.com/comment/82423911
has comment: http://stackoverflow.com/comment/82423790
tagged with: time
has comment: http://stackoverflow.com/comment/82423752
has comment: http://stackoverflow.com/comment/82423679
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/82423687
has comment: http://stackoverflow.com/comment/82423722

http://stackoverflow.com/q/47703486
favorite count: 0
has comment: http://stackoverflow.com/comment/82367690
tagged with: attributes
tagged with: tuples
type: Question
has title: AttributeError: 'tuple' object has no attribute 'low_connectivity_nodes'
has body: I am trying to following the 'Pandana network accessibility demo' Github repo (https://github.com/gboeing/urban-data-science/blob/2017/20-Accessibility-Walkability/pandana-accessibility-demo-full.ipynb). So far, when copying and pasting the code everything was fine but a problem has appeared when I ran this: start_time = time.time() if os.path.isfile(net_filename): # if a street network file already exists, just load the dataset from that network = pandana.network.Network.from_hdf5(net_filename) method = 'loaded from HDF5' else: # otherwise, query the OSM API for the street network within the specified bounding box network = osm.network_from_bbox(bbox[0], bbox[1], bbox[2], bbox[3]) method = 'downloaded from OSM' # identify nodes that are connected to fewer than some threshold of other nodes within a given distance lcn = network.low_connectivity_nodes(impedance=1000, count=10, imp_name='distance') network.save_hdf5(net_filename, rm_nodes=lcn) #remove low-connectivity nodes and save to h5 print('Network with {:,} nodes {} in {:,.2f} secs'.format(len(network.node_ids), method, time.time()-start_time)) This the error that I am getting: AttributeError Traceback (most recent call last) &lt;ipython-input-7-693cbbc8dc72&gt; in &lt;module&gt;() 10 11 # identify nodes that are connected to fewer than some threshold of other nodes within a given distance ---&gt; 12 lcn = network.low_connectivity_nodes(impedance=1000, count=10, imp_name='distance') 13 network.save_hdf5(net_filename, rm_nodes=lcn) #remove low-connectivity nodes and save to h5 14 AttributeError: 'tuple' object has no attribute 'low_connectivity_nodes'
has comment: http://stackoverflow.com/comment/82371785
type: UnansweredQuestion
tagged with: python
tagged with: python-2.7
downvote count: 0
upvote count: 1
score: 1
has answer: http://stackoverflow.com/a/61768005
answer count: 1

flask-socketio
tags question: http://stackoverflow.com/q/47716555
tags question: http://stackoverflow.com/q/47854951
tag name: flask-socketio
type: Tag
tags question: http://stackoverflow.com/q/47827827

http://stackoverflow.com/q/47780268
has comment: http://stackoverflow.com/comment/82521929
has body: I made a code like this to find the arithmetical mean for numbers the user has typed in but for some reason the program couldn't convert string to float in the end. What should I change? print("I'm going to find the arithmetical mean! \n") jnr = 0; sum = 0 negative = "-" while True: x = input(f"Type in {jnr}. nr. (To end press Enter): ") if negative not in x: jnr += 1 elif negative in x: pass elif x == "": break sum = sum + float(x) print("Aritmethmetical mean for these numbers is: "+str(round(sum/(jnr-1), 2))) I got his Error : Traceback (most recent call last): File "C:\Users\siims\Desktop\Koolitööd\individuaalne proge.py", line 11, in sum = sum + float(x) ValueError: could not convert string to float
has comment: http://stackoverflow.com/comment/82521899
upvote count: 4
has comment: http://stackoverflow.com/comment/82522134
score: 3
has comment: http://stackoverflow.com/comment/82522222
has title: Converting an empty string input to float
answer count: 3
has comment: http://stackoverflow.com/comment/82521774
downvote count: 1
has answer: http://stackoverflow.com/a/47780463
has comment: http://stackoverflow.com/comment/82522109
favorite count: 0
has comment: http://stackoverflow.com/comment/82521987
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82521926
has answer: http://stackoverflow.com/a/47780637
type: Question
has answer: http://stackoverflow.com/a/47780616
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82521884

http://stackoverflow.com/q/47781324
answer count: 2
has comment: http://stackoverflow.com/comment/82524237
downvote count: 0
has title: Python os.system: Order of commands
tagged with: python
possible better answer: http://stackoverflow.com/a/47781486
tagged with: git-bash
tagged with: python-os
type: AnsweredQuestion
score: 3
accepted answer: http://stackoverflow.com/a/47781368
upvote count: 3
has answer: http://stackoverflow.com/a/47781368
has body: Why does calling the file a.py with content import os print('Hi') os.system('cat a.py') yield the following output and how can I get them to print in the correct order? $ python a.py import os print('Hi') os.system('cat a.py') Hi You see that the cat command prints to stdout before print does. Happens when running Python 3.6 in GitBash on Windows 10. Does not happen with Python 3.6 on Ubuntu 17.10. Note: I'm aware that I can get around printing the content of a file with something like file.readlines() easily. This is just a simple example. However, when running something more complex, it can become important to understand why this happens and how to get around it
favorite count: 0
has comment: http://stackoverflow.com/comment/82524370
has answer: http://stackoverflow.com/a/47781486
type: Question
tagged with: python-3.x

http://stackoverflow.com/q/47702855
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47703973
accepted answer: http://stackoverflow.com/a/47703973
has title: Getting aggregate from Pandas for other categories
tagged with: python
type: Question
upvote count: 2
score: 2
downvote count: 0
tagged with: pandas
has body: I am trying to perform an aggregate calculation, but I want the calculation to apply to every other category. So, df.groupby(['index']).agg({data : [func1,func2]}) Will perform the aggregate calculations func1 and func2 on the data grouped by index, but I want to perform the calculations on all the data that isn't in the index. For example: index data A 1 A 2 A 1 B 2 B 2 B 4 B 4 C 1 C 3 D 4 D 1 I would want the results for A to be performed on the data in B,C,D. Is there a novel way to accomplish this?
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/82610310
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47823744
score: 1
has text: Thank you now I understand better. The code that you gave me is working. It still don't give me what I look for but I think it's because of the physical part. Now I know how to do the code so I just have to modify the formula untill it works ! Thanks for your patience !

http://stackoverflow.com/q/47722133
accepted answer: http://stackoverflow.com/a/47742992
tagged with: keyboard-events
score: 1
tagged with: winapi
has answer: http://stackoverflow.com/a/47742992
has body: I use win3api to simulate mouse events. For example: import win32api import win32con import time win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN) time.sleep(0.05) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP) For unknown reason, when the Task Manager is shown, these events will be ignored. This doesn't happen only when the Task Manager window is in focus, but when it's window isn't minimzed. Any suggentions?
tagged with: python
tagged with: mouseevent
type: AnsweredQuestion
has title: Python 2.7 - Can't simulate Windows events while Task Manager is shown
tagged with: taskmanager
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/comment/82432913
comment on: http://stackoverflow.com/a/47735963
type: AnswerComment
score: 0
type: Comment
has text: @PaulPanzer `np.shares_memory` is new to me.. Thanks you.

http://stackoverflow.com/comment/82369166
type: QuestionComment
has text: Many thanks, for the answer and the format hint:-)
score: 0
comment on: http://stackoverflow.com/q/47703909
type: Comment

http://stackoverflow.com/a/49488547
score: 3
type: Answer
has body: I was able to solve this issue by setting EMAIL_BACKEND and EMAIL_FILE_PATH (If applicable, depends on which backend you choose) in my Django settings. It seems like the error happens when it tries to send the confirmation email on registration. So in my case for local development: EMAIL_BACKEND = 'django.core.mail.backends.filebased.EmailBackend' EMAIL_FILE_PATH = os.path.join(BASE_DIR, 'tmp/email')
accepted answer of: http://stackoverflow.com/q/47806068
upvote count: 3
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47806068

http://stackoverflow.com/comment/82530216
type: QuestionComment
comment on: http://stackoverflow.com/q/47784215
score: 0
has text: Is it possible to fit or interpolate the data vs. depth to get the values at the even depth markers? That would seem to be the way to go.
type: Comment

http://stackoverflow.com/q/47769535
accepted answer: http://stackoverflow.com/a/47770196
tagged with: sniffer
has answer: http://stackoverflow.com/a/47770196
answer count: 1
type: Question
type: AnsweredQuestion
score: 0
has title: Pylint with sniffer not using updated source files
has comment: http://stackoverflow.com/comment/82500319
tagged with: pylint
tagged with: python
has comment: http://stackoverflow.com/comment/82501219
has body: I am using Pylint and Nose along with sniffer to lint and test my python application on every save. This is sniffer in case you are unaware https://pypi.python.org/pypi/sniffer Here is the runnable responsible for running nosetests and pylint from scent.py file for sniffer from sniffer.api import * # import the really small API from pylint import lint from subprocess import call import os import nose @runnable def zimmer_tests(*args): command = "nosetests some_module/test --nologcapture --with-coverage --cover-config-file=zimmer_coverage_config" lint.Run(['some_module/app'], exit=False) return call(command, shell=True) == 0 Here, first lint.Run() runs pylint on my app. Then nosetest is executed on the app using call() The Problem is that after I save the file nosetests run on updated version of the file however Pylint uses the same old version. I have to restart sniffer every time for pylint to get new version of files. I assume this is not a problem of sniffer's configuration since nosetests is able to get the new version of file every time. Still I am not sure. My pylintrc file is almost the same we get from generate command pylint --generate-rcfile &gt; .pylintrc with some minor application specific tweaks.

http://stackoverflow.com/q/47801056
has comment: http://stackoverflow.com/comment/82596409
accepted answer: http://stackoverflow.com/a/47817880
has answer: http://stackoverflow.com/a/47817880
has body: I want to do a pandas.rolling_apply involving multiple columns of a DataFrame. I can do it with one column of a DataFrame "df" like this: a = pd.Series(np.random.randn(12)) pd.rolling_apply(df['Col1'], 12, lambda x: x@a.values, min_periods=12) But I really want to incorporate two of the dataframe's columns into the rolling_apply. Is something like the following possible? pd.rolling_apply(df, 12, lambda x: x['Col1']@a.values+x['Col2']@a.values, min_periods=12) (Python complains if I try to bring a column reference inside the lambda this way.)
tagged with: python
tagged with: lambda
has title: Pandas.rolling_apply lambda on multiple columns of DataFrame
type: AnsweredQuestion
score: 0
tagged with: pandas
answer count: 1
tagged with: dataframe
has comment: http://stackoverflow.com/comment/82569120
type: Question

http://stackoverflow.com/q/47829428
has comment: http://stackoverflow.com/comment/82621842
tagged with: keras
has comment: http://stackoverflow.com/comment/82622747
tagged with: plot
has body: I am trying to plot a bunch of augmented images from the training directory. I am using Keras and Tensorflow. The visual library is matplotlib. I am using the code below to plot 256 X 256 X 1 gray images in 6 rows and columns. The error I am getting is Invalid Dimensions for image data. Here is the code I am using:- %matplotlib inline import matplotlib.pyplot as plt import numpy as np import keras from keras.preprocessing.image import ImageDataGenerator train_set = '/home/ai/IPI/Data/v1_single_model/Train/' # Use your own path batch_size = 4 gen = ImageDataGenerator(rescale = 1. / 255) train_batches = gen.flow_from_directory( 'data/train', target_size=(256, 256), batch_size=batch_size, class_mode='binary') def plot_images(img_gen, img_title): fig, ax = plt.subplots(6,6, figsize=(10,10)) plt.suptitle(img_title, size=32) plt.setp(ax, xticks=[], yticks=[]) plt.tight_layout(rect=[0, 0.03, 1, 0.95]) for (img, label) in img_gen: for i in range(6): for j in range(6): if i*6 + j &lt; 256: ax[i][j].imshow(img[i*6 + j]) break plot_images(train_batches, "Augmented Images") Below is the snapshot of error and python traceback:- --------------------------------------------------------------------------- TypeError Traceback (most recent call last) &lt;ipython-input-79-81bdb7f0d12e&gt; in &lt;module&gt;() ----&gt; 1 plot_images(train_batches, "Augmented Images") &lt;ipython-input-78-d1d4bba983d3&gt; in plot_images(img_gen, img_title) 8 for j in range(6): 9 if i*6 + j &lt; 32: ---&gt; 10 ax[i][j].imshow(img[i*6 + j]) 11 break ~/anaconda3/lib/python3.6/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: ~/anaconda3/lib/python3.6/site-packages/matplotlib/axes/_axes.py in imshow(self, X, cmap, norm, aspect, interpolation, alpha, vmin, vmax, origin, extent, shape, filternorm, filterrad, …
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82622454
accepted answer: http://stackoverflow.com/a/47830413
upvote count: 1
score: 1
tagged with: matplotlib
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/82622370
type: Question
has comment: http://stackoverflow.com/comment/82622575
tagged with: python-3.x
has title: Plot augmented images using matplotlib in python3.6
has answer: http://stackoverflow.com/a/47830413
has comment: http://stackoverflow.com/comment/82622965
has comment: http://stackoverflow.com/comment/82623120
answer count: 1
downvote count: 0

http://stackoverflow.com/q/47846234
tagged with: file
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
has title: Python readline() and readlines() not working
accepted answer: http://stackoverflow.com/a/47846303
tagged with: readlines
has answer: http://stackoverflow.com/a/47846303
tagged with: python
has comment: http://stackoverflow.com/comment/82656459
has body: I'm trying to read the contents of a 5GB file and then sort them and find duplicates. The file is basically just a list of numbers (each on a new line). There are no empty lines or any symbols other than digits. The numbers are all pretty big (at least 6 digits). I am currently using for line in f: do something to line to avoid memory problems. I am fine with using that. However, I am interested to know why readline() and readlines() didn't work for me. When I try print f.readline(10) the program always returns the same line no matter which number I use as a parameter. To be precise, if I do readline(0) it returns an empty line, even though the first line in the file is a big number. If I try readline(1) it returns 2, even though the number 2 is not in the file. When the parameter is >= 6, it always returns the same number: 291965. Additionally, the readlines() method always returns the same lines no matter what the parameter is. Even if I try to print f.readlines(2), it's still giving me a list of over 1000 numbers. I am not sure if I explained it very well. Sorry, English is not my first language. Anyway, I can make it work without the readline methods but I really want to know why they don't work as expected. This is what the first 10 lines of the file look like: 548098 968516 853181 485102 69638 689242 319040 610615 936181 486052
tagged with: readline
has comment: http://stackoverflow.com/comment/82656559
type: AnsweredQuestion
score: 0
answer count: 1

http://stackoverflow.com/q/47833578
tagged with: python-3.x
has title: Python - search files from the values in a list
tagged with: filesystems
has body: I'm very new to Python and I'm trying to solve the following problem. I want to iterate a List with words and lookup it in a file and if found return me the line number where the words are found. files = glob.iglob(os.path.join(in_dir, '*.*')) List = ['word1', 'word2',...'wordn'] for index, word in enumerate(List): print(index, word) for item in files: # Iterate all files in Input directory filename = os.path.basename(item) # Copy the filename without the path print('file: {0}'.format(filename)) with open(item, 'r') as f: for num, line in enumerate(f, 0): if word in line: print('num: {0}, line: {1}'.format(num, line)) But it doesn't seem to work, it only searched the first value o the list. What I want to do is to search all the List values in every file.
has answer: http://stackoverflow.com/a/47833977
tagged with: python
tagged with: python-3.6
type: AnsweredQuestion
upvote count: 3
tagged with: list
downvote count: 2
score: 1
accepted answer: http://stackoverflow.com/a/47833977
answer count: 1
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/1756096

http://stackoverflow.com/comment/82519150
score: 0
type: Comment
has text: @ForceBru Oh, I agree, the OP hasn't adequately specified their situation.
comment on: http://stackoverflow.com/a/47778755
type: AnswerComment

http://stackoverflow.com/comment/82530889
type: Comment
type: QuestionComment
has text: Do you need `r` or is it just an intermediary?
score: 0
comment on: http://stackoverflow.com/q/47784705

http://stackoverflow.com/a/62180032
has body: If you have named your file as youtube_dl.py, It will mix the programs mind. I am not seeing any problem in your code btw.
downvote count: 0
answers question: http://stackoverflow.com/q/47842104
score: 4
type: Answer
upvote count: 4

http://stackoverflow.com/comment/82669330
type: AnswerComment
has text: Thank you! If I could accept both answers I would have!!
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47852499

http://stackoverflow.com/comment/82513955
type: Comment
has text: Thanks for your reply. This is good, but I would need something like: if difference exists between a and b => add something in list c.
comment on: http://stackoverflow.com/a/47775764
type: AnswerComment
score: 0

http://stackoverflow.com/q/47740200
linked to: http://stackoverflow.com/q/37948836
tagged with: python
upvote count: 11
tagged with: choropleth
answer count: 2
has comment: http://stackoverflow.com/comment/84233972
downvote count: 0
has comment: http://stackoverflow.com/comment/108670826
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/59143504
score: 11
has comment: http://stackoverflow.com/comment/108697986
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/62822257
has comment: http://stackoverflow.com/comment/108674465
has title: Choropleth maps for Germany
has comment: http://stackoverflow.com/comment/99743467
has body: I am having Revenue data which I need to map on the German map. My data contains the postcodes, the corresponding latitude and longitude, as well as the value of revenue corresponding to that postcode, something like this - data = {'35447': {50.6022608,8.861908900000001,434224.45€}} I am using plotly Python library, which helps to create Choropleth/Point Maps. I referred to Pandas Choropleth Maps example, which explains how to use plotly, but for USA. In the example by setting locationmode = 'USA-states' locations = 'AL'# AL for Alabama, AZ for Arizona we could create Choropleth maps for USA. Similarly, by setting locationmode = 'USA-states' lon = -74.25908989999999 # Longitude lat = 40.4773991 # Latitude we could create Point Maps for USA. Question: How can we use library plotly to create Choropleth/Point maps for Germany? Or is it that plotly is only implemented for USA. pyGeoDb could have solved this problem, but it cannot be used for Python 3.+ As a side note, which may or may not be helpful - Choropleth maps are not implemented for zip codes and plotly confirms that.
tagged with: pandas

http://stackoverflow.com/q/47846900
type: Question
has comment: http://stackoverflow.com/comment/82658038
has comment: http://stackoverflow.com/comment/82658137
tagged with: python
has comment: http://stackoverflow.com/comment/82658355
has title: How to get these results in Python?
score: 0
has comment: http://stackoverflow.com/comment/82657904
answer count: 2
has comment: http://stackoverflow.com/comment/82658134
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47847489
has body: I am trying to fix a problem I have, but I can't get the answers right. """ Given is the following heading of a function to calculate the cosines. def cosines (x, number_of_terms): # x is a float; number_of_terms is an int This method calculates the cosines of x with the series x - x^3/3! + x^5/5! - x^7/7! + x^9/9! - ... x^n is the notation for "x to the power n" and n! is the notation for "the factorial of n". The number of terms that should be calculated is given by the parameter number_of_terms. Implement this method. Do this without using any functions from the module math. Assume: number_of_terms &gt;= 1. """ So, what I did is this: def cosines(x, number_of_terms): sign = 1 result = 0.0 counter = x denominator = 1.0 for i in range (number_of_terms, number_of_terms+1): fracture = counter / denominator term = sign * fracture result += term counter *= x denominator *= i sign = - sign return result first = cosines(90.0, 1) second = cosines(90.0, 4) third = cosines(90.0, 8) print "should be 30.000000: %f" % first print "should be -4546255.714286: %f" % second print "should be -7167780281079.437000: %f" % third This is the result I get: ---BEGIN TEST--- should be 30.000000: 90.000000 should be -4546255.714286: 90.000000 should be -7167780281079.437000: 90.000000 ----END TEST---- What am I doing wrong?
has comment: http://stackoverflow.com/comment/82658453
has answer: http://stackoverflow.com/a/47847344
has comment: http://stackoverflow.com/comment/82658239
has comment: http://stackoverflow.com/comment/82658153
has comment: http://stackoverflow.com/comment/82658080

http://stackoverflow.com/a/47709443
has body: CMD_LIST = ['ls -l', 'echo Mama Mia', 'echo bla bla bla'] for i in range(len(CMD_LIST)): subprocess.call(CMD_LIST[i]) Did you mean this?
answers question: http://stackoverflow.com/q/47709407
has comment: http://stackoverflow.com/comment/82378629
type: Answer
score: 0

http://stackoverflow.com/comment/82431125
score: 0
comment on: http://stackoverflow.com/q/47735267
type: Comment
type: QuestionComment
has text: You should rarely ever `def` within a loop

http://stackoverflow.com/comment/82391031
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47715486
has text: Cannot reproduce. Are you sure you don't have that defined somewhere?
type: Comment

http://stackoverflow.com/comment/82668680
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47852110
has text: "It doesn't work." means exactly?

http://stackoverflow.com/q/47729678
has comment: http://stackoverflow.com/comment/82420848
has comment: http://stackoverflow.com/comment/82420844
has comment: http://stackoverflow.com/comment/82420736
has comment: http://stackoverflow.com/comment/82420039
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/47730377
has comment: http://stackoverflow.com/comment/82420209
has answer: http://stackoverflow.com/a/47730377
tagged with: python
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/82420899
has title: Setting numpy array values to be more precise
has comment: http://stackoverflow.com/comment/82420666
has body: I have an array which has values, if calcualted precisely: [3.056565 3.924560] however in python it prints rounded numbers and the array is [3.06, 3.93]. The array is the used to calculate something else and the result is different than expected. How can I make that array to stop rounding itself? Here is the code where you can see that array is not precisely calcualted: import datetime import math import numpy as np def numGradient(f, x, h): n = len(x) g = [0]*n g = np.array(g) for i in range(n): e = [0]*n e[i] = 1 e=np.array(e) g[i] = (f(x+e*h)-f(x-e*h))//(2*h) return(g) def myFun(x) : return ( 0.6 + ((math.sin(x[0]**2-x[1]**2))**2-0.5)/((1+0.001*(x[0]**2+x[1]**2))**2) ) x_old=(3,4) xthis = x_old - 0.01*numGradient(myFun, x_old, 10**(-6)) print(xthis)
has comment: http://stackoverflow.com/comment/82419827
answer count: 1

http://stackoverflow.com/comment/82549561
has text: @AQ `blue=img[:,:,0]` means you just the blue channel, it's grayscale. `img[:,:,1]=img[:,:,2]=0 ` means you preserve the blue and set green and red to zeros, so it will show just in blue color. Remember, 2-D is grayscale, 3-D maybe in color (except B=G=R, still grayscale).
type: AnswerComment
comment on: http://stackoverflow.com/a/47793692
score: 0
type: Comment

http://stackoverflow.com/q/47802566
has body: I understand that the primary key autoincrements the primary key for each record inserted, but when I insert data using option 1, then display the data using option 2, it shows the PK as 1,2,3... etc. However, I would like it to store the PK as 4 digits, E.G. 0001,0002,0003 rather than 1,2,3. Is there any way to do this? PLEASE NOTE: this is example simplified code. import sqlite3 connection = sqlite3.connect('database.db') cursor = connection.cursor() create_table = ''' CREATE TABLE IF NOT EXISTS employee ( staff_ID INTEGER PRIMARY KEY NOT NULL, fname VARCHAR(20) NOT NULL, lname VARCHAR(30) NOT NULL, gender VARCHAR(20) NOT NULL);''' cursor.execute(create_table) print('press 1 to add new user') print('press 2 to show all users') option = input('1 or 2: ') if option == '1': #userid = input('User ID: ') first_name = input('First name : ') surname = input('Surname: ') gender = input('Gender: ') add_staff = '''INSERT INTO employee (fname, lname, gender) VALUES (?, ?, ?, ?);''' cursor.execute(add_staff, (first_name, surname, gender)) elif option == '2': cursor.execute('SELECT * FROM employee') print('fetchall:') result = cursor.fetchall() for r in result: print(r) cursor.execute('SELECT * FROM employee') connection.commit() connection.close() Also, how do I make sure that when the first name and surname are entered, they are only text values? I tried using 'text' in the CREATE section... any ide
linked to: http://stackoverflow.com/q/45557278
possible better answer: http://stackoverflow.com/a/47802683
answer count: 3
downvote count: 0
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/47802683
type: Question
type: AnsweredQuestion
tagged with: primary-key
has title: How do I make the primary key autoincrement like 0001, 0002 ,0003 rather than 1, 2, 3?
has answer: http://stackoverflow.com/a/47804743
tagged with: database
tagged with: sqlite
tagged with: python
accepted answer: http://stackoverflow.com/a/47802621
favorite count: 0
has answer: http://stackoverflow.com/a/47802621

http://stackoverflow.com/a/47941566
answers question: http://stackoverflow.com/q/47840633
score: 0
has body: Thinking laterally, a solution might be to run your application from Windows' Task Scheduler application* and set the task to Run whether user is logged on or not. The Run whether user is logged on or not setting causes the application to run invisibly, meaning no widnows, taskbar icons or console windows will be displayed on-screen. * Task Scheduler is installed in Windows by default. Type its name into Cortana to run
type: Answer

qfilesystemmodel
tag name: qfilesystemmodel
type: Tag
tags question: http://stackoverflow.com/q/47851152

http://stackoverflow.com/comment/82414112
comment on: http://stackoverflow.com/q/47726797
has text: no, I mean that you should start by writing a `Point` class with attributes such as `x_coord`, `y_coord`, `reach_west`, ... Then you can put instances of `Point` into a list. After that, augment your class with an `includes_other_point` method which solves the problem of overlapping rectangles.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82545261
score: 0
comment on: http://stackoverflow.com/q/47791643
has text: If that was the problem, why doesn't it error on `data.product_added` or `data.deleted`?
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/82472015
type: AnswerComment
score: 0
has text: "Can I get an explanation please as to why my post was downvoted?" => possibly because your answer is based on a tool that's not used by the OP and actually not necessary ? (nb : I'm not the downvoter).
type: Comment
comment on: http://stackoverflow.com/a/47755516

http://stackoverflow.com/q/47770687
tagged with: jwt
type: AnsweredQuestion
tagged with: python-2.7
score: 0
tagged with: http://stackoverflow.com/tag/json
answer count: 1
has body: I am using python client and php server and JWT coded messages for communications. I have created a message in PHP but the Python JWT encoder says this is not a JSON object. For PHP JWT I use the Firebase JWT encoder (but the other JWT encoder the jwt_helper.php is the same, what I found on net). PHP version: PHP7, python: 2.7 Here is the code in php: $obj = new stdClass(); $obj-&gt;result = 'OK'; $txt = json_encode($obj); $secret_key = 'secret_key'; $encoded = Firebase\JWT\JWT::encode($txt, $secret_key); $decoded = Firebase\JWT\JWT::decode($encoded, $secret_key, array('HS256')); echo $decoded; echo '&lt;br /&gt;'; echo $encoded; ?&gt; The output is: {"result":"OK"} eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.IntcInJlc3VsdFwiOlwiT0tcIn0i.dI4aO1UsXblWGCiLZbqQylRf8x6tgSWbeqYAw6rl5Sc Now, I am trying the decode it in Python: jwt.decode('eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.IntcInJlc3VsdFwiOlwiT0tcIn0i.dI4aO1UsXblWGCiLZbqQylRf8x6tgSWbeqYAw6rl5Sc','secret_key') Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/home/myuser/.local/lib/python2.7/site-packages/jwt/api_jwt.py", line 86, in decode raise DecodeError('Invalid payload string: must be a json object') jwt.exceptions.DecodeError: Invalid payload string: must be a json object Could you help me? Maybe am I using wrong packages or wrong character coding? I tried exactly added the JSON output in PHP file, like $txt="{'result':'OK'}";, but the same error. The other way works fine, if I create a JWT encoded string in Python, I can decode it in PHP. Thanks and regards, Kornel
type: Question
has title: Python can't decode PHP created JWT code
tagged with: python
tagged with: php
has answer: http://stackoverflow.com/a/47772594
accepted answer: http://stackoverflow.com/a/47772594

http://stackoverflow.com/comment/82678665
score: 1
type: Comment
has text: @JonasEphrem in your original code you were replacing occurrences of `path` with `os.path.basename(path)`, which returns empty string for `path = 'a/'`. We could remove the trailing slash to make sure the name is always non-empty. OTOH for that `path` `os.path.dirname` returned `'a'`, when I expected empty string, and removing trailing slashes solves that, too. You can use [`os.path.normpath`](https://docs.python.org/3/library/os.path.html#os.path.normpath) to perform full path normalization (and not just a part of that process).
type: AnswerComment
comment on: http://stackoverflow.com/a/47852184

http://stackoverflow.com/comment/82675316
score: 0
type: AnswerComment
has text: @A.Plattus Yes, I updated the answer, to handle that
comment on: http://stackoverflow.com/a/47846364
type: Comment

http://stackoverflow.com/comment/82363590
comment on: http://stackoverflow.com/q/47701756
has text: Welcome to stackoverflow. Url encoding a JSON string is not an easy problem, however this is how it is done in the python requests library. https://github.com/requests/requests/blob/master/requests/models.py#L60
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/q/47785835
tagged with: arrays
tagged with: python
has title: Python: split two dimensional array by column elements
score: 0
has body: I'm doing a study schedula application, and I want to turn: ['gafga',1,'dasd',1] ['gafga',1,'dasd',2] ['gafga',2,'dasd',2] ['gafga',3,'dasd',1] ['gafga',3,'dasd',1] into: ['gafga','dasd']['gafga','dasd'] ['gafga','dasd'] ['gafga','dasd'] ['gafga','dasd'] So the 2nd column became the indexes by the Y axis, and the 4th column became the indexes by the X axes. How to do that?
has comment: http://stackoverflow.com/comment/82532846
type: Question
has comment: http://stackoverflow.com/comment/82533380
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/82570211
comment on: http://stackoverflow.com/a/47804244
type: Comment
has text: @0rt They do have an effect!
score: 0
type: AnswerComment

http://stackoverflow.com/a/47727623
has body: The approach is correct. You just need to scale the axes such that the complete plot is within its range. import matplotlib.pyplot as plt import pandas as pd df = pd.DataFrame({"begin": [1,4,6,9], "end" : [3,5,8,12]}) fig, ax = plt.subplots() for x_1 , x_2 in zip(df['begin'].values ,df['end'].values): ax.add_patch(plt.Rectangle((x_1,0),x_2-x_1,0.5)) ax.autoscale() ax.set_ylim(-2,2) plt.show() It is worth noting that matplotlib has a function broken_barh, which simplifies the creation of such charts. import matplotlib.pyplot as plt import pandas as pd df = pd.DataFrame({"begin": [1,4,6,9], "end" : [3,5,8,12]}) fig, ax = plt.subplots() ax.broken_barh(list(zip(df["begin"].values, (df["end"] - df["begin"]).values)), (0, 0.5)) ax.set_ylim(-2,2) plt.show() Giving the same diagram as the above.
upvote count: 13
score: 13
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82416040
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47727339
answers question: http://stackoverflow.com/q/47727339
type: Answer

http://stackoverflow.com/a/47738357
has comment: http://stackoverflow.com/comment/82554281
has comment: http://stackoverflow.com/comment/82552392
answers question: http://stackoverflow.com/q/47737636
upvote count: 2
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/47737636
has body: If I'm going to write it as an answer then lets add some examples to demonstrate the difference. Say we have a simple iterable like: source_list = list(range(10)) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] If you want to turn it into a string list, there are a plethora of ways apart from the already mentioned map() which is designed for that purpose - you can do a simple generator: def gen_str(iterable): # this is equivalent to returning an in-line generator for element in iterable: yield str(element) test_gen = gen_str(source_list) for element in test_gen: print(repr(element), end=" ") # '0' '1' '2' '3' '4' '5' '6' '7' '8' '9' Or you can write a full iterator class: class iter_str(object): def __init__(self, iterable): self._iterable = iterable self._iterator = self._get_iter(self._iterable) def __iter__(self): return self def __next__(self): return str(next(self._iterator)) @staticmethod def _get_iter(iterable): # a generator for forward iteration for element in iterable: yield element test_iter = iter_str(source_list) for element in test_iter: print(repr(element), end=" ") # '0' '1' '2' '3' '4' '5' '6' '7' '8' '9' So far, they are the same - but what happens if you want to skip a few elements while iterating? You cannot instruct a generator to do so and in order to skip elements you need to add skipping-by-exhaustion logic within your iterating code itself, i.e.: test_gen = gen_str(source_list) for element in test_gen: if element == "5": for _ in range(3): next(test_gen) continue print(repr(element), end=" ") # '0' '1' '2' '3' '4' '9' On the other hand, with an iterator class you can encapsulate your control by adding a simple skip() method like: def skip(self, elements=1): for _ in range(elements): next(self._iterator) And then you can elegantly do the same as: test_iter = iter_str(source_list) for element in test_iter: if element == "5": element = test_iter.skip(3) continue print(repr(element), end=" ") # '0' '1' '2' '3' '4' '9' But that's just the tip of the iceberg - w…
score: 2

http://stackoverflow.com/comment/82406033
has text: If you are learning python, I suggest you read and understand this: https://nedbatchelder.com/text/names.html
comment on: http://stackoverflow.com/q/47722191
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/47784616
answers question: http://stackoverflow.com/q/47784223
downvote count: 0
upvote count: 1
has body: Go through each cell, one by one, check to see if the value is null and if it is then change it to a random number. First, import random. Then something like: df = df.where(df.a.isNull()).replace(null, random.randrange(min, max+1))
score: 1
type: Answer

http://stackoverflow.com/a/47851539
type: AcceptedAnswer
score: 0
accepted answer of: http://stackoverflow.com/q/47851337
type: Answer
answers question: http://stackoverflow.com/q/47851337
has body: Fixed version, see comments below: def binary_search(ls, num): # helper function to search the indices # we "know" ls and num from the outer-scope, so we'll pass only the indices def search(first=0, last=len(ls)): if first &lt; last: mid = (first + last) // 2 ban = ls[mid] if ban &gt; num: return search(first, mid-1) elif num &gt; ban: return search(mid+1, last) elif num == ban: return mid # return the index - not the number itself! else: return "not found!" return search() ls = list(range(1, 22)) # you should wrap range with list! print(binary_search(ls, 10)) print(binary_search(ls, 33))

http://stackoverflow.com/q/47776954
downvote count: 0
score: 1
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/82552192
has answer: http://stackoverflow.com/a/50480095
favorite count: 0
tagged with: home-automation
type: Question
has title: GUI button proformance in pythonista
has comment: http://stackoverflow.com/comment/82545732
type: UnansweredQuestion
tagged with: ios
tagged with: python
tagged with: pythonista
has comment: http://stackoverflow.com/comment/82603063
has body: I am trying to make (what I thought) would be fairly simple GUI with a lighting control switch. I am using Pythonista on iOS. It's not actually controlling a light. I just want something that prints to the console that the switch is on or off. I'm extremely new to coding, and just can't figure it out. When I run the code the GUI will appear and print the state of the switch (upon loading) but it will not print if the switch is used after that. #Lighting Control Switch import ui def lightControl(mySwitch): toggle.switch1 = mySwitch switch1 = "Off" or "On" action_On = False print(not action_On) action_Off = (not action_On) print(action_On) if action_On == True: print("Lights On") if action_Off == True: print("Lights Off") v = ui.load_view() v.present('sheet') I want a switch that indicates to the console that it has been used and whether it is currently on or off. No errors are printing and the GUI comes up as it should. Just not the result I want. I'm very new to coding and just trying to learn and figure things out.

http://stackoverflow.com/comment/82629785
type: Comment
comment on: http://stackoverflow.com/q/47829925
score: 0
has text: Did you try pybot -s option?
type: QuestionComment

http://stackoverflow.com/q/47782076
has body: I am working with oceanographic data in Python. I am currently trying to create a contour plot of time on the x axis, pressure on the y axis, and temperature as the contours. Right now I am trying to format the time array with values that I got from the data itself. The code I have only produces the day of the year without the corresponding hours added onto it. I need a way to add on 6 hours, 12 hours, and 18 hours to each day because the data came from profiles of the water column that ran 4 times each day, separated by 6 hours. There were 1260 profiles and i corresponds to the file for each profile. import numpy from matplotlib import pyplot as plt import math from datetime import tzinfo, timedelta, datetime, time import time i = 1 temp = numpy.zeros((1260, 1000)) pressure = numpy.zeros((1260, 1000)) time2 = numpy.zeros(1260) for i in range(1, 1260): filename = '/Users/ryanschubert/InternProject/itp47final/itp47grd' + str(i).zfill(4) + '.dat' if os.path.isfile(filename): data = open(filename, "r") else: continue depthcounter=-1 text = data.read() data.close() text = text.replace(' ', ',') #this line and the next 5 lines are text = text.replace(' ', ',') #fixing formatting errors in the code text = text.replace(' ', '') text = text.replace('NaN', '-98') text = text.replace(',,', ',') text = text.split('\n') for line in text: depthcounter=depthcounter+1 if depthcounter == 1: if i ==1: words4 = line.split(',') year = int(words4[0]) doy = float(words4[1]) - 1 hour = int((doy - math.floor(doy))*24) t = datetime(year=year, month=1, day=1, hour=hour,tzinfo=utc) + timedelta(days=int(doy)) time1 = t.timetuple().tm_yday timetemp = numpy.array([t + timedelta(days=j/4.) for j in xrange(1260)]) else: time2[i] = timetemp[i].timetuple().tm_yday print(time2[i])` The code currently returns values like this; 102 102.0 102.0 103.0 103.0 103.0 103.0 104.0 104.0 104.0 104.0 105.0 105.0 105.0 105.0 106.0 106.0 106.0 106.0 107.0 107.0 107.0 107.0 and so on... I need help adding 6 hours …
has answer: http://stackoverflow.com/a/47782122
answer count: 1
has comment: http://stackoverflow.com/comment/82525594
type: Question
tagged with: python-3.x
tagged with: contourf
type: UnansweredQuestion
tagged with: datetime
has title: How to add hours onto Day of Year
tagged with: python
score: 0

http://stackoverflow.com/q/47826934
answer count: 0
has body: HCL #405 opened Dec 14, 2017 by ssen I want to access datetime. How can I do this?
duplicate of: http://stackoverflow.com/q/1058599
has comment: http://stackoverflow.com/comment/82616131
tagged with: beautifulsoup
type: Question
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/1058599
has comment: http://stackoverflow.com/comment/82617446
tagged with: python
has title: How to select content of span class tag in python
score: 0

http://stackoverflow.com/comment/82630948
comment on: http://stackoverflow.com/q/47833818
type: QuestionComment
has text: yes .. just forgot it to change it for this example .. in my code it have the correct xpath (copied it from the control box)
type: Comment
score: 0

http://stackoverflow.com/q/47720537
favorite count: 0
type: Question
answer count: 2
tagged with: tkinter
possible better answer: http://stackoverflow.com/a/47720888
downvote count: 1
has answer: http://stackoverflow.com/a/47720556
linked to: http://stackoverflow.com/q/459083
has comment: http://stackoverflow.com/comment/82417879
type: AnsweredQuestion
has body: I'm trying to create a program which displays images using tkinter. The code I've written so far displays the image perfectly, however the program does not continue until the tkinter window is closed. I was wondering if there was any function instead of .mainloop() to keep the program running alongside the tkinter window? Any help much appreciated window = Tk() canvas1 = Canvas(window,height=600,width=600) file = PhotoImage(file = 'GoogleDrive.png') image = canvas1.create_image(300, 300, anchor = CENTER, image = file) canvas1.pack() canvas1.mainloop() print ('\nA: Google Drive') time.sleep(1) print ('B: Google Slides') time.sleep(1) print ('C: Google Photos')
score: 3
has title: how to keep program running after .mainloop()?
has comment: http://stackoverflow.com/comment/82403758
has answer: http://stackoverflow.com/a/47720888
tagged with: python
has comment: http://stackoverflow.com/comment/82417854
upvote count: 4
accepted answer: http://stackoverflow.com/a/47720556

http://stackoverflow.com/comment/82441477
type: QuestionComment
has text: sorry python manage.py runserver 0.0.0.0 8000 is what you need to run in the terminal
comment on: http://stackoverflow.com/q/47740521
score: 0
type: Comment

http://stackoverflow.com/q/47767305
has body: I'm reading the json file and extracting the required columns into the csv file .Please find the below code and let me know if am wrong df=pd.read_json(json_file) df=df['Person'] data1=pd.DataFrame(df,columns=['cols1','cols2','cols3','title']) print data1 df.to_csv("ptr1.csv",index = False) but i'm getting the error empty dataframe output .
answer count: 2
tagged with: pandas
score: 0
has answer: http://stackoverflow.com/a/47768550
has title: Unable to extract columns form the data frame pandas
type: Question
has comment: http://stackoverflow.com/comment/82496615
has answer: http://stackoverflow.com/a/47767362
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82496401
tagged with: python

http://stackoverflow.com/comment/82402411
has text: @sure i will do that
comment on: http://stackoverflow.com/a/47720471
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/47726113
has title: can somebody explain what exactly is going on with python functions?
accepted answer: http://stackoverflow.com/a/47726144
has comment: http://stackoverflow.com/comment/82412910
tagged with: class
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47726144
tagged with: oop
score: 1
has answer: http://stackoverflow.com/a/47726168
has answer: http://stackoverflow.com/a/47726160
has comment: http://stackoverflow.com/comment/82412808
answer count: 4
favorite count: 0
has body: what i know in python is i can write something like this blabla = Classname().somefunctions() but in this case both the "np.arange" and "reshape" are functions and it confuses me because "np.arange" is a function and is treated like a class. the question is how is this possible?? import numpy as np a = np.arange(15).reshape(3, 5) print(a)
type: Question
has answer: http://stackoverflow.com/a/47726177
downvote count: 0
possible better answer: http://stackoverflow.com/a/47726160
upvote count: 1
tagged with: python

http://stackoverflow.com/comment/82586456
has text: Looking into the [zip](https://docs.python.org/3.4/library/functions.html#zip) function would be a start.
type: QuestionComment
comment on: http://stackoverflow.com/q/47812597
score: 4
type: Comment

http://stackoverflow.com/comment/95600606
comment on: http://stackoverflow.com/a/47837473
score: 0
type: Comment
has text: Edit the file output by `import matplotlib; print(matplotlib.matplotlib_fname())`. There is a line that says `backend: xxx`. Change that.
type: AnswerComment

http://stackoverflow.com/q/47826446
possible better answer: http://stackoverflow.com/a/47826859
tagged with: cython
has body: I have a M×N numpy array. Before a FFT I need to pad it with zeros to get a (M+K)×(N+K) array where the M and N first indices are the original data and the K last indices along each dimension are zeros. Using Cython, is there an efficient way to do so without loosing the np.ndarray[DTYPE_t, ndim=2] type ?
has answer: http://stackoverflow.com/a/47826859
type: Question
has answer: http://stackoverflow.com/a/47827330
has title: Cython : memory-efficient padding of array
tagged with: python
has comment: http://stackoverflow.com/comment/82659272
tagged with: numpy
accepted answer: http://stackoverflow.com/a/47827330
type: AnsweredQuestion
score: 0
answer count: 2
tagged with: arrays

http://stackoverflow.com/comment/82372715
has text: What would `bar` be if you didn't open the progress bar?
comment on: http://stackoverflow.com/q/47706285
score: 1
type: Comment
type: QuestionComment

spyder
tag name: spyder
tags question: http://stackoverflow.com/q/47757009
tags question: http://stackoverflow.com/q/47738537
tags question: http://stackoverflow.com/q/47730966
tags question: http://stackoverflow.com/q/47772081
tags question: http://stackoverflow.com/q/47782668
tags question: http://stackoverflow.com/q/47837051
tags question: http://stackoverflow.com/q/47720098
type: Tag
tags question: http://stackoverflow.com/q/47784359
tags question: http://stackoverflow.com/q/47710379

http://stackoverflow.com/comment/82391120
type: Comment
type: QuestionComment
has text: @MattR hmm yes this might be one of the concerns also. if this happened, do you think it will be better to just label 1 and 0 to indicate? rather than storing the original data?
score: 0
comment on: http://stackoverflow.com/q/47715337

http://stackoverflow.com/comment/82563520
type: QuestionComment
has text: In addition to what @pauloscardine said, If you don't encapsulate your code in functions and classes it is very difficult, if not impossible, to write tests against it.
type: Comment
comment on: http://stackoverflow.com/q/47800626
score: 1

http://stackoverflow.com/q/47855539
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82695964
has answer: http://stackoverflow.com/a/47855853
has comment: http://stackoverflow.com/comment/82675680
tagged with: python
has body: I am writing a Python web-crawler for Quora, but need to log in using Google. I have searched the net, but nothing satisfies my problem. Here is my code: # -*- coding: utf-8 -*- import mechanize import os import requests import urllib2 from bs4 import BeautifulSoup import cookielib # Store the cookies and create an opener that will hold them cj = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) # Add our headers opener.addheaders = [('User-agent', 'RedditTesting')] # Install our opener (note that this changes the global opener to the one # we just made, but you can also just call opener.open() if you want) urllib2.install_opener(opener) # The action/ target from the form authentication_url = 'https://quora.com' # Input parameters we are going to send payload = { 'op': 'login-main', 'user': '&lt;username&gt;', 'passwd': '&lt;password&gt;' } # Use urllib to encode the payload data = urllib.urlencode(payload) # Build our Request object (supplying 'data' makes it a POST) req = urllib2.Request(authentication_url, data) # Make the request and read the response resp = urllib2.urlopen(req) contents = resp.read() # specify the url quote_page = "https://www.quora.com/" # query the website and return the html to the variable ‘page’ page = urllib2.urlopen(quote_page) # parse the html using beautiful soup and store in variable `soup` soup = BeautifulSoup(page, 'html.parser') # Take out the &lt;div&gt; of name and get its value name_box = soup.find('div', attrs={"class": "ContentWrapper"}) name = name_box.text.strip() # strip() is used to remove starting and trailing print name for link in soup.find_all('img'): image = link.get("src") os.path.split(image) image_name = os.path.split(image)[1] print(image_name) r2 = requests.get(image) with open(image_name, "wb") as f: f.write(r2.content) As I don't have any actual username for the site, I use my own Gmail account. In order to login, I used some code from a different question, but that does not w…
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/82675730
answer count: 1
downvote count: 0
tagged with: quora
score: 1
tagged with: web-scraping
has comment: http://stackoverflow.com/comment/82675296
upvote count: 1
accepted answer: http://stackoverflow.com/a/47855853
favorite count: 0
tagged with: beautifulsoup
type: Question
has title: Login to a website with Google using BeautifulSoup and Python 2.7

http://stackoverflow.com/a/54884414
has body: In my case, I had to change access permission of the appcfg.py file. https://en.wikipedia.org/wiki/Chmod read more about chmod here.
score: 0
answers question: http://stackoverflow.com/q/47767179
type: Answer

http://stackoverflow.com/comment/82508522
score: 0
comment on: http://stackoverflow.com/q/47706295
type: QuestionComment
has text: `driver.page_source` gives page HTML as one string and you need `lxml` or `BeautifulSoup` to find elelements.
type: Comment

http://stackoverflow.com/comment/82422485
has text: @ahmed i edited the question with more details and screenshot, please check it.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/47730486
type: AnswerComment

http://stackoverflow.com/comment/97222090
score: 0
comment on: http://stackoverflow.com/a/47820911
type: Comment
type: AnswerComment
has text: Is there any way I will be able to crop out the image based on the lines specified at Step 5.

http://stackoverflow.com/comment/82413151
has text: Please don't post links to your code and just add it to your question instead. Also, try to reduce it to a [minimal, complete and verifiable example](https://stackoverflow.com/help/mcve).
type: Comment
comment on: http://stackoverflow.com/q/47726023
type: QuestionComment
score: 2

http://stackoverflow.com/q/47719514
has comment: http://stackoverflow.com/comment/82399730
tagged with: python
has title: Python: 'Turtle' object has no attribute 'bye'
score: 1
tagged with: python-turtle
has answer: http://stackoverflow.com/a/47720067
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/82399479
upvote count: 1
favorite count: 0
type: Question
has body: I am trying to write turtle code where something is triggered and the turtle window closes, so I try to use turtle.bye() but I keep getting the error: Exception in Tkinter callback Traceback (most recent call last): File "C:\Program Files\Python36\lib\tkinter\__init__.py", line 1699, in __call__ return self.func(*args) File "C:\Program Files\Python36\lib\turtle.py", line 686, in eventfun fun() File "E:\Home made game\Chapter 1 Log Cabin.py", line 346, in k1 player.bye() AttributeError: 'Turtle' object has no attribute 'bye'
tagged with: turtle-graphics
type: UnansweredQuestion

aes
tag name: aes
tags question: http://stackoverflow.com/q/47721334
type: Tag

http://stackoverflow.com/q/47776516
upvote count: 1
tagged with: python
has body: I have a DataFrame. To do a statistical conditional test, I split it into two based on a boolean column ('mar'). I want to use the ratio of counts between the two tables to add a column expressing the proportion of true values in the 'mar' column for each combination of the other columns, as seen below. &gt;&gt;&gt; df_nomar alc cig mar cnt 1 1 1 0 538 3 1 0 0 456 5 0 1 0 43 7 0 0 0 279 &gt;&gt;&gt; df_mar alc cig mar cnt 0 1 1 1 911 2 1 0 1 44 4 0 1 1 3 6 0 0 1 2 &gt;&gt;&gt; df_mar.loc[:, 'prop'] = np.array(df_mar['cnt'])/(np.array(df_mar['cnt']) + np.array(df_nomar['cnt'])) /usr/local/lib/python3.5/dist-packages/pandas/core/indexing.py:296: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy self.obj[key] = _infer_fill_value(value) /usr/local/lib/python3.5/dist-packages/pandas/core/indexing.py:476: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy self.obj[item] = s &gt;&gt;&gt; df_mar alc cig mar cnt prop 0 1 1 1 911 0.628709 2 1 0 1 44 0.088000 4 0 1 1 3 0.065217 6 0 0 1 2 0.007117 I've gone to the suggested page to investigate the warning. When I assign the new column, I am using the form df_mar.loc[:, 'prop'] = ..., just as suggested. So why am I still getting this warning?
has comment: http://stackoverflow.com/comment/82515459
has title: Where does this pandas warning come from?
tagged with: pandas
has comment: http://stackoverflow.com/comment/82514782
has answer: http://stackoverflow.com/a/47776568
tagged with: dataframe
score: 1
favorite count: 0
type: Question
tagged with: python-3.x
linked to: http://stackoverflow.com/q/20625582
tagged with: chained-assignment
type: UnansweredQuestion
downvote count: 0
answer count: 1

http://stackoverflow.com/q/47729174
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47729474
upvote count: 1
tagged with: python
downvote count: 1
has comment: http://stackoverflow.com/comment/82419006
tagged with: class
type: AnsweredQuestion
score: 0
answer count: 3
possible better answer: http://stackoverflow.com/a/47729302
has body: Hi I'm trying to print 4 band members details using a class, however I'm only able to print one, ill give samples to give you an understanding below, this is my whole code class Person: def __init__(self, _firstname, _surname, d, m, y): self._firstname = _firstname self._surname = _surname self.d = d self.m = m self.y = y def __repr__(self): return '{} {} \n{} {} {}'.format(john._firstname, john._surname, john.d, john.m, john.y) return '{} {} \n{} {} {}'.format(paul._firstname, paul._surname, paul.d, paul.m, paul.y) return '{} {} \n{} {} {}'.format(george._firstname, george._surname, george.d, george.m, george.y) return '{} {} \n{} {} {}'.format(ringo._firstname, ringo._surname, ringo.d, ringo.m, ringo.y) john = Person('John','Lennon','8th','October','1940') paul = Person('Paul','McCartney','18th','June','1942') george = Person('George','Harrison','25th','February','1943') ringo = Person('Ringo','Starr','7th','July','1940') john._firstname = 'John' john._surname = 'Lennon' john.d = '8th' john.m = 'October' john.y = '1940' paul._firstname = 'Paul' paul._surname = 'McCartney' paul._d = '18th' paul._m = 'June' paul._y = '1942' george._firstname = 'George' george._surname = 'Harrison' george._d = '25th' george._m = 'February' george._y = '1943' ringo._firstname = 'Ringo' ringo._surname = 'Starr' ringo._d = '7th' ringo._m = 'July' ringo._y = '1940' print('{} {} \n{} {} {}'.format(john._firstname, john._surname, john.d, john.m, john.y)) print('{} {} \n{} {} {}'.format(paul._firstname, paul._surname, paul.d, paul.m, paul.y)) print('{} {} \n{} {} {}'.format(george._firstname, george._surname, george.d, george.m, george.y)) print('{} {} \n{} {} {}'.format(ringo._firstname, ringo._surname, ringo.d, ringo.m, ringo.y)) I receive, the correct output, which is this: John Lennon 8th October 1940 Paul McCartney 18th June 1942 George Harrison 25th February 1943 Ringo Starr 7th July 1940 I want to be able to type: print(john) print(george) print(paul) print(ringo) To get the same out…
has comment: http://stackoverflow.com/comment/82418998
accepted answer: http://stackoverflow.com/a/47729272
has comment: http://stackoverflow.com/comment/82418951
has comment: http://stackoverflow.com/comment/82419155
has answer: http://stackoverflow.com/a/47729302
tagged with: output
has title: Printing a Class
has answer: http://stackoverflow.com/a/47729272

http://stackoverflow.com/q/47796489
type: Question
score: 0
tagged with: python
type: UnansweredQuestion
has title: Bezier curve fitting to data with python
answer count: 1
has answer: http://stackoverflow.com/a/47799503
has body: I know there has been a lot of topics about curve fitting here but I have not found anything that would suite my needs. I'm trying to make a simple sail analysis app with python. The code "calculates" sail shape stripe and calculates some data from it but I cannot get the correct "entry angle" and "exit angle" as they are defined by the curve control points. See ref image: So my existing data is in form of x,y points and i would like to fit bezier curve to the existing data so I could calculate the entry and exit angles. I might also be possible to fit b-spline to the existing data but either way it should be so that the "mid point" and points next to it either side has same y-value.
linked to: http://stackoverflow.com/q/12643079
tagged with: bezier
has comment: http://stackoverflow.com/comment/82559916

http://stackoverflow.com/a/47706062
has comment: http://stackoverflow.com/comment/82402011
has comment: http://stackoverflow.com/comment/82401777
upvote count: 1
answers question: http://stackoverflow.com/q/47703227
score: 1
type: Answer
has body: Sounds like the pip you are using is not installing for the same python you are using. try which pip and which python the they should be in the same folder. Might want to make an alias or two if you have a bunch of pythons (sys, 2, 3, conda etc) or just start with a fresh virtual env for your project. &lt;- best imo.
downvote count: 0
has comment: http://stackoverflow.com/comment/82423236

http://stackoverflow.com/comment/82367461
type: AnswerComment
has text: @SuperStew, if you can't remember when its a problem and when its not then you should probably find out and incorporate it into this answer or just remove this answer.
comment on: http://stackoverflow.com/a/47703628
score: 0
type: Comment

http://stackoverflow.com/comment/82447231
type: Comment
comment on: http://stackoverflow.com/a/47743494
score: 0
type: AnswerComment
has text: When I do this I get `too many values to unpack (expected 2)` at `F,H = y0` but this is of course easily solvable by taking `F = y0[0], H = y0[1:]`. Thanks!

http://stackoverflow.com/a/47812132
type: Answer
accepted answer of: http://stackoverflow.com/q/47811739
downvote count: 0
upvote count: 1
type: AcceptedAnswer
has body: Content of gnewsclient.py class baby(): def method(self): print 'Method call' Content of test.py from gnewsclient import baby # from file_name.py import class_name b = baby() b.method() python test.py Output Method call
answers question: http://stackoverflow.com/q/47811739
score: 1

http://stackoverflow.com/comment/82605000
type: Comment
comment on: http://stackoverflow.com/q/47821229
score: 0
type: QuestionComment
has text: `x = str(i)` now x is a string. Summing a string cannot be done using `sum`

http://stackoverflow.com/q/47736316
type: Question
accepted answer: http://stackoverflow.com/a/47736364
has body: Trying to analyse some strings and compute the number of times they come up. This data is stored in a dictionary. If I were to use the max function only the first highest number encountered would be printed. count = {"cow": 4, "moo": 4, "sheep": 1} print(max(count.keys(), key=lambda x: count[x])) cow This would yield cow to be the max. How would I get "cow" and "moo" to both be printed count = {"cow": 4, "moo": 4, "sheep": 1} cow, moo
has answer: http://stackoverflow.com/a/47736364
tagged with: python
tagged with: dictionary
linked to: http://stackoverflow.com/q/12402015
has answer: http://stackoverflow.com/a/47736344
type: AnsweredQuestion
score: 0
has title: How to find multiple maximums in a dictionary
answer count: 2
possible better answer: http://stackoverflow.com/a/47736344

http://stackoverflow.com/a/47765364
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47764790
has comment: http://stackoverflow.com/comment/82493000
type: Answer
has body: You can pull back the line2d objects that display the ticks, and change their color based on their location. You will need to filter the ticklines to only include the displayed ticks (seems to be indicated by the marker). ax = plt.gca() for t, loc in zip(filter(lambda x: x.get_marker()==3, ax.xaxis.get_ticklines()), ax.xaxis.get_ticklocs()): if loc in (7,11,12,14,18,25,26): print(f'Changing tick line at {loc} to red') t.set_color('red')
score: 2
accepted answer of: http://stackoverflow.com/q/47764790
upvote count: 2

http://stackoverflow.com/comment/82508326
type: QuestionComment
comment on: http://stackoverflow.com/q/47773659
has text: you might want to use `from module import *` to import all of the functions from a module, if I understand you correctly
score: 0
type: Comment

http://stackoverflow.com/q/47705972
tagged with: python
tagged with: dictionary
tagged with: plot
has answer: http://stackoverflow.com/a/47706274
has comment: http://stackoverflow.com/comment/82372259
score: 4
linked to: http://stackoverflow.com/q/21195179
has answer: http://stackoverflow.com/a/47706037
type: AnsweredQuestion
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/82372243
accepted answer: http://stackoverflow.com/a/47749403
answer count: 3
has comment: http://stackoverflow.com/comment/82420693
has comment: http://stackoverflow.com/comment/82382310
downvote count: 0
has comment: http://stackoverflow.com/comment/82372189
has answer: http://stackoverflow.com/a/47749403
has title: How to plot keys and values from dictionary in histogram
has comment: http://stackoverflow.com/comment/82372154
favorite count: 0
has body: I need to plot a histogram with the following dictionary x = {5:289, 8:341, 1:1565, 4:655, 2:1337, 9:226, 7:399, 3:967, 6:405} I need first keys be ordered from 1 to 9. Then the values will be plotted in the histogram, showing a maximum probability of 1.0. I have tried the following (plus other stuff). import matplotlib.pyplot as plt import numpy as np plt.hist(x.keys(), x.values(), color='g', label = "Real distribution") plt.show() Or plt.hist (x, bins = np.arange(9), color = 'g', label = "Real distribution") plt.show() Or fsn_count_ = sorted(fsn_count) plt.hist (fsn_count_, bins = np.arange(9), color = 'b', label = "Real distribution") plt.plot ([0] + bf, color = 'g', label = "Benford Model") plt.xlabel ('Significant number') plt.ylabel ('Percentage') plt.xlim (1,9) plt.ylim (0,1) plt.legend (bbox_to_anchor = (1, 1), loc="upper right", borderaxespad=0.) plt.savefig (country_ + '.png') plt.show () plt.clf () distribution_sum = sum(bf) print('The sum of percentage distribution is:', distribution_sum)
has comment: http://stackoverflow.com/comment/82372265
upvote count: 4
possible better answer: http://stackoverflow.com/a/47706037
has comment: http://stackoverflow.com/comment/82372302
has comment: http://stackoverflow.com/comment/82372199
type: Question

http://stackoverflow.com/q/47816365
downvote count: 1
has title: Sort dictionary with Objects as keys
has body: I'm pretty new to python and I'm trying to sort a dict which has some objects as keys. I have a class Student(studID, name) which is the key of the dict and an array of grades that is the value of the dict. This is what it looks like: dictEx = { Student: [5,6], Student: [7,8], Student: [10,9] } That object Student has a method getName() to get the student name. What I'm trying to accomplish is to sort this dictionary first by the student name and then by the grades only if the students have the same name. (if I have two students named Andrew for example)
score: -1
favorite count: 0
has comment: http://stackoverflow.com/comment/82594433
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47816512
upvote count: 0
tagged with: python
type: UnansweredQuestion
tagged with: dictionary
answer count: 1
tagged with: python-2.7
type: Question
has comment: http://stackoverflow.com/comment/82594291

http://stackoverflow.com/comment/82630874
type: AnswerComment
has text: If you are familiar with `numpy` using `pd.DataFrame({'Column': df.values.reshape(-1)})` could be easier to remember.
comment on: http://stackoverflow.com/a/47833875
score: 1
type: Comment

http://stackoverflow.com/a/47841898
type: Answer
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47841887
upvote count: 1
answers question: http://stackoverflow.com/q/47841887
has body: You're looking at the if statement from the wrong angle. What you wrote evaluates to: either v.selection equals v.operations[2] OR v.operations[3] is not false. for that matter, anything that isn't 0 is not false. Here's an example: a = 5; b = 6; c = 7; if (a == b or c): print("hey") else: print("nay") which results in: hey
score: 1

http://stackoverflow.com/q/47785798
tagged with: load-balancing
has title: How to perform load balancing for a python API
tagged with: python
has comment: http://stackoverflow.com/comment/82532809
has body: I have build as application with REST API. I have to send request from a cluster (of about 10 nodes) to get some information from this API. Now if I run it on single system, it is expected that it may become a bottleneck and mapreduce job will take a lot of time to complete. Is there any way or solution that I can run this service on multiple systems for load balancing?. I am using Linux OS. My service is built in Python and I am using Flash to get it via REST.
has comment: http://stackoverflow.com/comment/82533949
answer count: 0
score: 0
tagged with: mapreduce
type: Question
tagged with: rest
has comment: http://stackoverflow.com/comment/82533007
has comment: http://stackoverflow.com/comment/82533038
type: UnansweredQuestion

http://stackoverflow.com/comment/82449222
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47740762
type: Comment
has text: I tried that one before, it works, but how can I return it as a set?

http://stackoverflow.com/comment/82610126
type: Comment
comment on: http://stackoverflow.com/q/47823694
score: 8
has text: In python a common practice is EAFP, or it's easier to ask for forgiveness than permission, go with the `try...except`
type: QuestionComment

http://stackoverflow.com/comment/82657257
type: Comment
type: QuestionComment
has text: @daveydave400 thanks for replying! I Don't really know.. when I run my python code, it should give the valua I send via pubnub, but instead it just stops the program and shows me that sentence.
comment on: http://stackoverflow.com/q/47842106
score: 0

http://stackoverflow.com/q/47714181
tagged with: python
has comment: http://stackoverflow.com/comment/82388605
accepted answer: http://stackoverflow.com/a/47714796
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47714796
tagged with: pandas
upvote count: 2
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/82388261
has title: pandas groupby: TOP 3 values in each group and store in DataFrame
linked to: http://stackoverflow.com/q/47703606
has body: This is a followup to pandas groupby: TOP 3 values for each group The solution described there is perfect if the number of rows in each group is at least 3, but it fails if at least one of the groups isn't big enough. I propose here a new data set that requires another solution. Some data are saved at random times and I need to find the highest 3 values for each hour: VAL TIME 2017-12-08 00:55:00 29 2017-12-08 01:10:00 56 2017-12-08 01:25:00 82 2017-12-08 01:40:00 13 2017-12-08 01:55:00 35 2017-12-08 02:10:00 53 2017-12-08 02:25:00 25 2017-12-08 02:40:00 23 2017-12-08 02:55:00 21 2017-12-08 03:10:00 12 2017-12-08 03:25:00 15 it should return this DataFrame, without the time when a max was detected: VAL1 VAL2 VAL3 TIME 2017-12-08 00:00:00 29 None None 2017-12-08 01:00:00 82 56 35 2017-12-08 02:00:00 53 25 23 2017-12-08 03:00:00 15 12 None None are in groups where less than 3 rows are available. The code to generate the data set is: from datetime import * import pandas as pd import numpy as np df = pd.DataFrame() date_ref = datetime(2017,12,8,0,55,0) days = pd.date_range(date_ref, date_ref + timedelta(0.11), freq='15min') np.random.seed(seed=1111) data1 = np.random.randint(1, high=100, size=len(days)) df = pd.DataFrame({'TIME': days, 'VAL': data1}) df = df.set_index('TIME') # groupby group1 = df.groupby(pd.Grouper(freq='1H')) largest3 = pd.DataFrame(group1["VAL"].nlargest(3)) My question is how is it possible to save these values into a new DataFrame, perhaps getting them from largest3: VAL TIME TIME 2017-12-08 00:00:00 2017-12-08 00:55:00 29 2017-12-08 01:00:00 2017-12-08 01:25:00 82 2017-12-08 01:10:00 56 2017-12-08 01:55:00 35 2017-12-08 02:00:00 2017-12-08 02:10:00 53 2017-12-08 02:25:00 25 2017-12-08 02:40:00 23 2017-12-08 03:00:00 2017-12-08 03:25:00 15 2017-12-08 03:10:00 12 EDIT: Added reset_index largest3 = pd.DataFrame(group1["VAL"].nlargest(3)).reset_index(level=1, drop=True) returns a better overview but I don't know how to move on from here: VAL TIME 2017…
favorite count: 0
type: Question

http://stackoverflow.com/comment/82521486
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47779711
has text: Your app is called `browser`. The table for `PollsChoice` should be called `browser_pollschoice`, unless you have messed something in the `Meta` options. Have you had any app called `test_vcc`? Have you renamed some apps?

http://stackoverflow.com/q/47729164
possible better answer: http://stackoverflow.com/a/47729360
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47730439
tagged with: testing
has title: How to use token authentication while testing REST API
tagged with: django
tagged with: python
tagged with: django-rest-framework
accepted answer: http://stackoverflow.com/a/47730439
has answer: http://stackoverflow.com/a/47729360
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47729808
answer count: 3
tagged with: token
score: 1
has body: I am trying to use test the API request by using tokens. I was able to extract the token but I struggle to find a way to use it. This is how I get my token: @pytest.mark.django_db class TestUserAPI(APITestCase): def setUp(self): self.created_user = UserFactory() User.objects.create_user(username='test', password='pass1234') def test_authentification(self): request = self.client.post('http://localhost:8000/api/v1/auth/', { "username": "test", "password": "pass1234" }) TestUserAPI.token = request.data["token"] assert request.status_code == 200 and this is how I use it: def test_profile(self): request = self.client.get('http://localhost:8000/api/v1/profile/', TokenAuthentication = 'token {}'.format(TestUserAPI.token)) assert request.status_code == status.HTTP_200_OK It gives me 401 error. What is the correct way of using token?
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/47714730
score: 0
type: Answer
answers question: http://stackoverflow.com/q/47714688
has body: Your __init__ is declared as taking a name and an address: def __init__(self, name, address): This means that you need to provide both of them, so the following is not valid: p = Person('Swaroop') If you have use cases where the address cannot be provided, then you can make the argument optional: def __init__(self, name, address=None): The above statement will give address a default value of None if the argument is not provided. Taking a closer look at your code it seems you wanted to provide a name and an address as two separate objects: p = Person('Swaroop') # name q = Person('Duisburg') # address Note that arguments are identified by position, so on q, Duisburg will correspond to the name argument. You can achieve what you want by using just one object: p = Person('Swaroop', 'Duisburg') p.say_name() p.say_address()

http://stackoverflow.com/a/47725783
has comment: http://stackoverflow.com/comment/82412203
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47725715
has body: You can use apply with lambda for that column of row: df['words']=df['words'].apply(lambda row: eliminate_space(row)) Testing with example: df = pd.DataFrame({'words':['word is 1', 'word is 2', 'word is 3']}) print(df) Initial dataframe: words 0 word is 1 1 word is 2 2 word is 3 Using function: df['words']=df['words'].apply(lambda row: eliminate_space(row)) Result: words 0 wordis1 1 wordis2 2 wordis3
answers question: http://stackoverflow.com/q/47725715
type: Answer
has comment: http://stackoverflow.com/comment/82412216
score: 2
upvote count: 2

http://stackoverflow.com/comment/82671620
type: AnswerComment
comment on: http://stackoverflow.com/a/47853768
score: 0
type: Comment
has text: this will load the data directly into the df, correct? That might be awfully big...

http://stackoverflow.com/a/47764753
has comment: http://stackoverflow.com/comment/82491101
has comment: http://stackoverflow.com/comment/82491170
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47764623
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/82532668
has comment: http://stackoverflow.com/comment/82535516
has comment: http://stackoverflow.com/comment/82533764
answers question: http://stackoverflow.com/q/47764623
has body: You can use the pygame.time.get_ticks() function which returns the time since the program start to compute the elapsed time. Set the start_time to the current time in the event loop when the user presses the key and in the while loop you can check if it is still held down with pygame.key.get_pressed() and compute the elapsed time. import pygame as pg def main(): screen = pg.display.set_mode((320, 240)) clock = pg.time.Clock() start_time = 0 done = False while not done: for event in pg.event.get(): if event.type == pg.QUIT: done = True elif event.type == pg.KEYDOWN: if event.key == pg.K_SPACE: start_time = pg.time.get_ticks() keys = pg.key.get_pressed() if keys[pg.K_SPACE]: # The spacebar is held. current_time = pg.time.get_ticks() elapsed_time = current_time-start_time # milliseconds print(elapsed_time) screen.fill((30, 30, 30)) pg.display.flip() clock.tick(30) if __name__ == '__main__': pg.init() main() pg.quit() If you just want to count the frames: import pygame as pg def main(): screen = pg.display.set_mode((320, 240)) clock = pg.time.Clock() counter = 0 done = False while not done: for event in pg.event.get(): if event.type == pg.QUIT: done = True elif event.type == pg.KEYDOWN: if event.key == pg.K_SPACE: counter = 0 # Set it back to 0. keys = pg.key.get_pressed() if keys[pg.K_SPACE]: # The spacebar is held. # Increment the counter every frame. counter += 1 print(counter) screen.fill((30, 30, 30)) pg.display.flip() clock.tick(30) if __name__ == '__main__': pg.init() main() pg.quit()
type: Answer

http://stackoverflow.com/a/47723166
type: Answer
answers question: http://stackoverflow.com/q/47723131
score: -1
upvote count: 0
has comment: http://stackoverflow.com/comment/82407322
downvote count: 1
has body: Simple as frames = [df1.set_index('col1'), df2.set_index('col1'), axis = 1] result = pd.concat(frames)

http://stackoverflow.com/comment/139803463
score: 0
has text: This answer resulted in cut-off legends for me. However, simply swapping the bbox_to_anchor values for both legends fixed my problem.
comment on: http://stackoverflow.com/a/47762472
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/82610756
comment on: http://stackoverflow.com/q/47815669
score: 1
type: Comment
has text: Fortunately you set this clearly and unambiguously in the post...
type: QuestionComment

http://stackoverflow.com/comment/82503997
has text: OK sure anything to speed up...please help me with your suggested change in function...In the memory used section - i have 34GB of memory free though - but please suggest any change. free -m total used free shared buffers cached Mem: 85632 51278 34354
comment on: http://stackoverflow.com/q/47769818
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47819350
has comment: http://stackoverflow.com/comment/82607043
has answer: http://stackoverflow.com/a/47828982
has comment: http://stackoverflow.com/comment/82602615
score: 1
tagged with: python
has body: I need a wordcloud in which the same word could appear twice with different colors; red indicating negative associations, and green positive. I am already able to generate a wordcloud with repeated words using MultiDicts (see the code below): However, I need one of the homes to appear in green color. Is this possible with the wordcloud libray? Can somebody recommend another library that support this? from wordcloud import WordCloud from multidict import MultiDict class WordClouder(object): def __init__(self, words, colors): self.words = words self.colors = colors def get_color_func(self, word, **args): return self.colors[word] def makeImage(self, path): wc = WordCloud(background_color="white", width=200, height=100) # generate word cloud wc.generate_from_frequencies(self.words) # color the wordclound wc.recolor(color_func=self.get_color_func) image = wc.to_image() image.save(path) if __name__ == '__main__': # Ideally this would be used somewhere colors_valence = { '+': 'green', '-': 'red', } colors = { 'home': 'red', 'car': 'green', } words = MultiDict({ 'home': 2.0, # This home should be green 'car': 20.0, }) words.add('home',10) , # This home should be red wc = WordClouder(words, colors) wc.makeImage('wordcloud.png')
linked to: http://stackoverflow.com/q/2444680
has comment: http://stackoverflow.com/comment/82606237
has comment: http://stackoverflow.com/comment/82619557
type: UnansweredQuestion
answer count: 1
downvote count: 0
upvote count: 1
tagged with: word-cloud
has comment: http://stackoverflow.com/comment/82619719
favorite count: 0
has title: How to create a wordcloud with the same word several times but with different colors?
type: Question

http://stackoverflow.com/comment/82709101
comment on: http://stackoverflow.com/a/47823072
score: 0
type: Comment
has text: I included the matchlist that I am using
type: AnswerComment

http://stackoverflow.com/comment/82366745
comment on: http://stackoverflow.com/a/47702633
type: AnswerComment
has text: Program in still running but no output response, same as before. Should I be using data.decode('utf-8') to get my output in string ? And am'i missing command response ?
score: 0
type: Comment

http://stackoverflow.com/a/47781387
type: Answer
has body: Here is an elaboration of the idea I put in my comment. Use the mean of the signal as a threshold value. Then compute the median value for the parts of the signal that are above the threshold, and for those below. Use these to transform your data. med_high = signal[signal &gt; signal.mean()].median() med_low = signal[signal &lt; signal.mean()].median() print (med_low, med_high) new_signal = signal.transform(lambda x: med_low if x &lt; signal.mean() else med_high) plt.figure(figsize = (7,3)) plt.plot(new_signal, color = "firebrick") plt.axhline(0.5, linestyle = ":") plt.show() The result:
answers question: http://stackoverflow.com/q/47780379
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47780379
score: 1

http://stackoverflow.com/q/47773057
has comment: http://stackoverflow.com/comment/82507102
score: 0
linked to: http://stackoverflow.com/q/42086276
answer count: 0
duplicate of: http://stackoverflow.com/q/42086276
type: Question
has body: Is there a way to get the default colormap in matplotlib? I like it, and I have a number of plot pairs that I want to plot in "parallel" colors, e.g. draw one curve with a solid line and another in the same color that is dotted. import matplotlib.pyplot as plt fig = plt.figure(...) ax = plt.add_subplot(1,1,1) # obtain data from somewhere t = ... data_primary = ... # list of y-axis data arrays data_secondary = ... # list of y-axis data arrays # colormap = ????????? # get colormap from somewhere k = 0 for y_a, y_b in zip(data_primary, data_secondary): ax.plot(t,y_a,color = colormap[k], linestyle = '-') ax.plot(t,y_b,color = colormap[k], linestyle = ':') k += 1
type: UnansweredQuestion
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/82507894
tagged with: python
has title: How to get the default colormap in matplotlib

http://stackoverflow.com/comment/83196127
type: AnswerComment
has text: Thanks for the response. Yes, I used such a setup file, and ran it the way you did. Everything works locally, but fails in Dataflow.
score: 1
type: Comment
comment on: http://stackoverflow.com/a/47909078

http://stackoverflow.com/a/47818967
type: Answer
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/47796396
has body: Using the queue runner API for I/O is deprecated. Instead, I recommend using tf.data API. Here is a detailed example of an input function for AlexNet data that can be used along with an Estimator: def input_fn(params): """Passes data to the estimator as required.""" batch_size = params["batch_size"] def parser(serialized_example): """Parses a single tf.Example into a 224x224 image and label tensors.""" final_image = None final_label = None if FLAGS.preprocessed: features = tf.parse_single_example( serialized_example, features={ "image": tf.FixedLenFeature([], tf.string), "label": tf.FixedLenFeature([], tf.int64), }) image = tf.decode_raw(features["image"], tf.float32) image.set_shape([224 * 224 * 3]) final_label = tf.cast(features["label"], tf.int32) else: features = tf.parse_single_example( serialized_example, features={ "image/encoded": tf.FixedLenFeature([], tf.string), "image/class/label": tf.FixedLenFeature([], tf.int64), }) image = tf.image.decode_jpeg(features["image/encoded"], channels=3) image = tf.image.resize_images( image, size=[224, 224]) final_label = tf.cast(features["image/class/label"], tf.int32) final_image = (tf.cast(image, tf.float32) * (1. / 255)) - 0.5 return final_image, final_label file_pattern = os.path.join(FLAGS.data_dir, "train-*") dataset = tf.data.Dataset.list_files(file_pattern) if FLAGS.filename_shuffle_buffer_size &gt; 0: dataset = dataset.shuffle(buffer_size=FLAGS.filename_shuffle_buffer_size) dataset = dataset.repeat() def prefetch_map_fn(filename): dataset = tf.data.TFRecordDataset( filename, buffer_size=FLAGS.dataset_reader_buffer_size) if FLAGS.prefetch_size is None: dataset = dataset.prefetch(batch_size) else: if FLAGS.prefetch_size &gt; 0: dataset = dataset.prefetch(FLAGS.prefetch_size) return dataset if FLAGS.use_sloppy_interleave: dataset = dataset.apply( tf.contrib.data.sloppy_interleave( prefetch_map_fn, cycle_length=FLAGS.cycle_length)) else: dataset = dataset.interleave( prefetch_map_fn, cycle_length=FLAGS.cycle_length) …

http://stackoverflow.com/q/47735661
has comment: http://stackoverflow.com/comment/82488706
type: UnansweredQuestion
has title: Send dynamically updating data from python server to many clients
has comment: http://stackoverflow.com/comment/82488241
has comment: http://stackoverflow.com/comment/82432617
tagged with: multipoint
type: Question
has comment: http://stackoverflow.com/comment/82533413
tagged with: python-multithreading
tagged with: sockets
tagged with: python
score: 0
has body: first I'll apologise if I've made some large error, I'm new to python. I'm trying to write software using python sockets to generate a random number every 10 seconds and send it to multiple clients. So far I have been able to create a server and connect multiple clients, but the random numbers that are being generated and sent to each client are different. I'm trying to make them the same. Here is my server code: import sys, time, socket, threading, random def newClient(c): global data c.send("Connected to stream".encode()) while True: c.sendall(str(data).encode()) time.sleep(10) def setData(): data = random.random() return data def readData(): global data while True: data = setData() port = 12312 ssock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ssock.bind(('', port)) ssock.listen(5) data = random.random() threading.Thread(target=readData).start() while True: c, addr = ssock.accept() print("[-] Connected to " + addr[0] + ":" + str(addr[1])) threading.Thread(target=newClient, args=(c,)).start() If someone could point me in the right direction, so that my server sends the same data to both clients, I would be very grateful.
answer count: 0

http://stackoverflow.com/comment/82523159
comment on: http://stackoverflow.com/a/47780832
type: Comment
has text: @MCBama so any function I define inside that class has acess to the variables in the __init__ method?
score: 0
type: AnswerComment

http://stackoverflow.com/comment/82544062
has text: Your C program is not "correct": it invokes undefined behavior and could just as well crash on access to `arr[5]`, or do some even worse thing. You're not guaranteed to get any value, even a garbage one. In Python you are guaranteed to get an `IndexError` instead.
type: Comment
score: 11
comment on: http://stackoverflow.com/q/47791378
type: QuestionComment

http://stackoverflow.com/comment/82367527
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47703686
score: 0
has text: Yes, I need stop and return True if len == 0

http://stackoverflow.com/comment/82426624
type: AnswerComment
comment on: http://stackoverflow.com/a/47732946
has text: @DannyWatson what specifically do you wish to do with the values in the first row of each column?
type: Comment
score: 0

http://stackoverflow.com/q/47806397
downvote count: 0
answer count: 3
score: 1
upvote count: 1
tagged with: http://stackoverflow.com/tag/json
accepted answer: http://stackoverflow.com/a/47806482
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/47806485
has title: Extracting Json Data from List using python
has answer: http://stackoverflow.com/a/47806485
has answer: http://stackoverflow.com/a/47806527
has comment: http://stackoverflow.com/comment/82574226
tagged with: python
has answer: http://stackoverflow.com/a/47806482
type: AnsweredQuestion
has body: I have this sample json data in a list: data = [ { "Name": "John_Doe", "Age" : 25 } { "Name": "Jane_Roe", "Age" : 26 } ] I need a way to extract the all the key value pairs from an element in the list based on the 'Name' Key. If my variable = 'John_Doe', then the script should only return the values related to John_Doe, i, e only the following values : { "Name": "John_Doe", "Age" : 25 }

http://stackoverflow.com/q/47824285
has title: How can we efficiently check whether a list of string contains a word from another list of strings?
has answer: http://stackoverflow.com/a/47824310
accepted answer: http://stackoverflow.com/a/47824377
downvote count: 0
has body: Supposed I have a list of cursewords curseword = ['fuxx', 'die', 'damn'] and if I am iterating through a list of sentence(list of string) to check if the sentence contains the curse word. text = [ ['i','am','a','boy'] , [....] , [....] ] I tried to do something like for i in curse_words: for t in text: if i in t: // exsits but it seems wrong and inefficient. How can I do this efficiently?
tagged with: python
type: AnsweredQuestion
answer count: 3
has answer: http://stackoverflow.com/a/47824377
score: 1
upvote count: 1
possible better answer: http://stackoverflow.com/a/47824310
has answer: http://stackoverflow.com/a/47825920
favorite count: 0
type: Question

http://stackoverflow.com/comment/82376156
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47707712
score: 0
has text: Ya, I just did something like r = list(map(float, r)), although your way may be cleaner

http://stackoverflow.com/q/47769348
has answer: http://stackoverflow.com/a/47786621
accepted answer: http://stackoverflow.com/a/47786621
tagged with: python
has body: I have a simple flask app, i want to test it using pytest. my conftest.py: @pytest.fixture def app(self): app = create_app(TestingConfig) return app my test_view.py: class TestMainView: def test_ping(self, client): res = client.get(url_for('main.index')) assert res.status_code == 200 when i run the test's using pytest it's throwing an error saying: fixture 'client' not found &gt; available fixtures: app, cache, capfd, capfdbinary, caplog, capsys, capsysbinary, doctest_namespace, monkeypatch, pytestconfig, record_xml_property, recwarn, tmpdir, tmpdir_factory &gt; use 'pytest --fixtures [testpath]' for help on them. i have another testing file where i test default configs and it passes: class TestTestingClass(object): app = create_app(TestingConfig) def test_app_is_test(self): ''' test the test enviroment is set okay and works''' assert self.app.config['SECRET_KEY'] == 'something hard' assert self.app.config['DEBUG'] == True assert self.app.config['TESTING'] == True assert current_app is not None assert self.app.config['SQLALCHEMY_DATABASE_URI'] == 'sqlite:////tmp/testing.db' edit: i was able to pass an empty test by changing to: conftest.py: @pytest.fixture def app(): app = create_app(TestingConfig) return app @pytest.fixture def client(app): return app.test_client() and my test file to: def test_index(client): assert True but, still i can't pass the test_index if it was: def test_index(client): assert client.get(url_for('main.index')).status_code == 200 but this time, I'm getting an error stating that says: RuntimeError: Attempted to generate a URL without the application context being pushed. This has to be executed when application context is available.
tagged with: flask
type: AnsweredQuestion
tagged with: pytest
answer count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/66813409
possible better answer: http://stackoverflow.com/a/47788058
upvote count: 10
score: 10
has title: Why can't pytest find the 'client' fixture when testing a Flask app?
has answer: http://stackoverflow.com/a/47788058
favorite count: 0
type: Question

http://stackoverflow.com/q/47847621
type: Question
tagged with: pyinstaller
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82660286
tagged with: python
has title: Failure of python compilation with pyinstaller [ImportError: DLL load failed]
score: 0
has body: I compiled this project with pyinstaller, but when I run an exe file, I get this error C:\Users\lik47\Desktop\LaZagne-master\Windows\dist&gt;laZagne.exe Traceback (most recent call last): File "laZagne.py", line 4, in File "c:\python27\Lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 396, in load_module exec(bytecode, module.dict) File "lazagne\softwares\browsers\mozilla.py", line 13, in File "c:\python27\Lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 396, in load_module exec(bytecode, module.dict) File "build\bdist.win32\egg\Crypto\Cipher\DES3.py", line 67, in File "c:\python27\Lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 396, in load_module exec(bytecode, module.dict) File "build\bdist.win32\egg\Crypto\Cipher_DES3.py", line 7, in File "build\bdist.win32\egg\Crypto\Cipher_DES3.py", line 6, in bootstrap ImportError: DLL load failed: ═х эрщфхэ єърчрээ√щ ьюфєы№. [1184] Failed to execute script laZagne ran on windows 10 x64 without compilation (just from python script) it works
answer count: 0
has comment: http://stackoverflow.com/comment/82668233

http://stackoverflow.com/comment/82380039
type: Comment
has text: You could do `conditions[0] = lambda ope : ope[0] == 1` and so on. Fill up a list with all the conditions as lambda functions inside, then in the list comprehension, select the one condition you want to use with `a = [ope for ope in operations if conditions[0](ope)]`.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47709795

http://stackoverflow.com/comment/82534198
score: 4
type: QuestionComment
has text: `my_list = list(map(lambda x :x[0], my_list))`
comment on: http://stackoverflow.com/q/47786568
type: Comment

http://stackoverflow.com/comment/82469159
type: AnswerComment
comment on: http://stackoverflow.com/a/47725824
has text: @Mike Great News !!! Can you Accept the Answer by clicking on the tick mark beside my Answer, just below vote Up/Down arrows, so the tick mark turns Green? Thanks
type: Comment
score: 0

on-the-fly
type: Tag
tag name: on-the-fly
tags question: http://stackoverflow.com/q/47699711

http://stackoverflow.com/comment/82461182
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47749965
has text: Can you show your curl command ?
score: 0

http://stackoverflow.com/comment/82547026
has text: I just added a piece of the data file
type: Comment
comment on: http://stackoverflow.com/q/47792979
type: QuestionComment
score: 0

http://stackoverflow.com/comment/82424870
type: QuestionComment
comment on: http://stackoverflow.com/q/47730829
type: Comment
score: 0
has text: read doc for [Sprite.update()](http://pygame.org/docs/ref/sprite.html#pygame.sprite.Sprite) - "The default implementation of this method does nothing; it’s just a convenient “hook” that you can override." - it means you don't have to use it in Player

http://stackoverflow.com/comment/82408893
comment on: http://stackoverflow.com/q/47724075
type: QuestionComment
has text: use button `{}` to correctly format code.
score: 0
type: Comment

http://stackoverflow.com/comment/82371559
type: AnswerComment
has text: @Tom , iTadreik's code prints the second value (0.6) because he implemented a loop `for char in grade:` -> there are 2 chars in `grade` (`A` and `+`). Loop works with every character, and at the 2nd iteration of the loop (when loop works with `+`) block `if '+' in grade:` executes `print(keydict[char] + keydict['+'])` (when `char` here is `+`). This is the reason why the 2nd result is 0.6.
type: Comment
comment on: http://stackoverflow.com/a/47705575
score: 2

http://stackoverflow.com/a/47794982
has comment: http://stackoverflow.com/comment/82784369
score: 0
has body: To save the first view that user see, you have to tweak the configuration of pageLoadStrategy through DesiredCapabilities which is by default set as normal to none as follows : from selenium import webdriver from selenium.webdriver.common.desired_capabilities import DesiredCapabilities caps = DesiredCapabilities().PHANTOMJS.copy() caps["pageLoadStrategy"] = "none" browser = webdriver.PhantomJS(desired_capabilities=caps, executable_path=r'C:\path\to\bin\phantomjs.exe') browser.set_window_size(1920, 1080) browser.set_page_load_timeout(60) browser.get("https://accounts.google.com/signin") browser.save_screenshot('./Screenshots/filename.png') You can find a detailed discussion about pageLoadStrategy here.
has comment: http://stackoverflow.com/comment/82785795
has comment: http://stackoverflow.com/comment/82786007
answers question: http://stackoverflow.com/q/47788417
has comment: http://stackoverflow.com/comment/82785616
has comment: http://stackoverflow.com/comment/82788645
has comment: http://stackoverflow.com/comment/82787508
type: Answer
has comment: http://stackoverflow.com/comment/82788342

http://stackoverflow.com/a/47773614
type: Answer
score: 0
has body: It appears that the libraries you are using haven't been updated to use the new version of SeleniumLibrary. They are trying to import modules that no longer exist, or exist under another name. You'll either need to upgrade the libraries yourself, or switch back to using version 2.x of Selenium2Library.
answers question: http://stackoverflow.com/q/47769741

http://stackoverflow.com/q/47735062
favorite count: 0
type: Question
type: AnsweredQuestion
has title: Python - Tkinter (Canvas) - Top Left Corner Pixels Missing?
has body: I have come across this weird behavior of Tkinter where the first 3 lines in both x and y directions (x=0,1,2 and y=0,1,2) don't actually show up. For example if I run the following code, from tkinter import * master = Tk() w = Canvas(master, width=200, height=200) w.pack() w.create_line(0, 0, 0, 100, fill="red") w.create_line(1, 0, 1, 100, fill="blue") w.create_line(2, 0, 2, 100, fill="green") w.create_line(3, 0, 3, 100, fill="black") w.create_line(0, 0, 100, 0, fill="red") w.create_line(0, 1, 100, 1, fill="blue") w.create_line(0, 2, 100, 2, fill="green") w.create_line(0, 3, 100, 3, fill="black") mainloop() I would get this result, note how in both directions, the red, blue and green lines don't show up. Only the black lines show up. I tried searching but couldn't find anything related to this issue. Thank you in advance!
score: 1
has answer: http://stackoverflow.com/a/47735152
tagged with: python
tagged with: tkinter
accepted answer: http://stackoverflow.com/a/47735152
answer count: 1
tagged with: tkinter-canvas
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/82665587
score: 0
type: Comment
type: QuestionComment
has text: @user2357112 Kudos for U for going to my profile and seeing my most common tag :)
comment on: http://stackoverflow.com/q/47850352

http://stackoverflow.com/comment/82418257
type: QuestionComment
has text: I've never heard of such a thing in c#. Maybe a good open source project for you.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47728754

http://stackoverflow.com/q/47793178
has answer: http://stackoverflow.com/a/47793410
downvote count: 0
has comment: http://stackoverflow.com/comment/82547801
has comment: http://stackoverflow.com/comment/82556578
answer count: 1
upvote count: 8
favorite count: 0
score: 8
has comment: http://stackoverflow.com/comment/82555812
type: Question
has comment: http://stackoverflow.com/comment/82558863
has title: How to force tkinter text widget to stay on one line
tagged with: python-3.x
tagged with: tkinter
has comment: http://stackoverflow.com/comment/82548748
accepted answer: http://stackoverflow.com/a/47793410
has comment: http://stackoverflow.com/comment/82547574
has body: I want to create an object akin to Label, however I want it to also be selectable for copy-pasting. I have done so using the Text widget: class CopyLabel (Text): def __init__ (self, master, text = '', font = None): if font is None: super().__init__(master = master, height = 1, borderwidth = 0, width = len(text), bg = master['background']) else: super().__init__(master = master, height = 1, borderwidth = 0, font = font, width = len(text), bg = master['background']) self.insert(1.0, text) self.configure(state = 'disabled') I end up displaying this widget with a grid. However, I randomly find the last 1 or 2 characters not showing. When investigating this, it seems the Text widget is splitting those characters off to a new line (when selecting the text, it is possible to drag down to see this second line). The biggest problem is the unpredictable nature of this splitting (I tried doing width = len(text) + 2, but I still occasionally get this line splitting behaviour). Is there any way to remedy this behaviour? EDIT: setting wrap = 'none' fixed the line splitting behaviour, but the text is still getting cutoff. Now I have to scroll horizontally instead of vertically to see the text, but I guess that is a different question from what I posed.
tagged with: python
linked to: http://stackoverflow.com/q/19029157
has comment: http://stackoverflow.com/comment/82547733
has comment: http://stackoverflow.com/comment/82548695
has comment: http://stackoverflow.com/comment/82548517
has comment: http://stackoverflow.com/comment/82549507
type: AnsweredQuestion

http://stackoverflow.com/comment/82510615
score: 0
has text: You need to use `tk.Frame` instead.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47774809

http://stackoverflow.com/a/48326746
score: 2
has body: From ImportanceOfBeingErnest's answer here, I got the following on translating tick labels in a general, arbitrary way: import matplotlib.transforms as mtrans # ... trans = mtrans.Affine2D().translate(20, 0) for t in ax.get_xticklabels(): t.set_transform(t.get_transform()+trans)
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/47835572
type: Answer

http://stackoverflow.com/comment/82482469
type: QuestionComment
score: 1
type: Comment
comment on: http://stackoverflow.com/q/47760496
has text: typo: `with open('final_directory/MINP.txt','w') as f:` should be `with open(os.path.join(final_directory,'MINP.txt'),'w') as f`

http://stackoverflow.com/q/47774958
has title: Reg Ex for specific number in string
answer count: 3
possible better answer: http://stackoverflow.com/a/47775235
type: Question
has answer: http://stackoverflow.com/a/47775235
has answer: http://stackoverflow.com/a/47775287
has comment: http://stackoverflow.com/comment/82510931
has comment: http://stackoverflow.com/comment/82515128
tagged with: python
tagged with: regex
has body: I'd like to match numbers (int and real) in a string, but not if they are part of an identifier; e.g., i'd like to match 5.5 or 42, but not x5. Strings are roughly of the form "x5*1.1+42*y=40". So far, I came up with ([0-9]*[.])?[0-9]+[^.*+=&lt;&gt;] This correctly ignores x0, but also 0 or 0.5 (12.45, however, works). Changing the + to * leads to wrong matchings. It would be very nice if someone could point out my error. Thanks!
has answer: http://stackoverflow.com/a/47777017
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47777017
score: 0

http://stackoverflow.com/comment/82539119
type: Comment
comment on: http://stackoverflow.com/q/47788884
type: QuestionComment
has text: What kind of data does your 3 dimensional action vector contains? Categorical or continuous?
score: 0

http://stackoverflow.com/q/47738671
has comment: http://stackoverflow.com/comment/82558848
score: 3
has comment: http://stackoverflow.com/comment/82439313
tagged with: anaconda
upvote count: 3
has body: Can someone help me with the error I'm getting when I try to install pythonnet in Anaconda. On the website it is stated that I just need to enterconda install -c pythonnet pythonnet or through pip pip install -i https://pypi.anaconda.org/pythonnet/simple pythonnet and both doesn't work. When I'm trying to do it with anaconda it says PackageNotFoundError: Packages missing in current channels: - pythonnet and when I do it with pip it says failed with error code 1. It's not my first time installing packeges in anaconda and normally it always worked.
tagged with: python
has comment: http://stackoverflow.com/comment/82605943
favorite count: 0
type: Question
tagged with: python.net
has comment: http://stackoverflow.com/comment/82605963
answer count: 0
has comment: http://stackoverflow.com/comment/82564557
has title: Anaconda installing pythonnet
type: UnansweredQuestion
tagged with: package
tagged with: pythonnet
downvote count: 0
has comment: http://stackoverflow.com/comment/82558879

http://stackoverflow.com/q/47841088
type: AnsweredQuestion
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/47841162
has title: Graph in logarithmic scale for ordinates for the Jacobi method
type: Question
has answer: http://stackoverflow.com/a/47841162
has body: I have to program the Jacobi, Gauss Seidel and SOR methods to resolve Ax=b. We use a decomposition A=M-N. For the Jacobi method, for example, we use M=diag(A) and N=M-A. I programmed a function jacobi(A,b,Imax,err,x0) with the matrix A, the column vector b, a maximum number of iterations Imax, a tolerance err, for the Jacobi method. I used a "stop test" where is the "residual" at the step k. Here is my code : import numpy as np import scipy.linalg as la def jacobi(A,b,Imax,eps,x0): M=np.diag(np.diag(A)) N=M-A r=np.dot(A,x0)-b x=x0 i=0 err=1+eps res=[] while ((i&lt;Imax) and ((la.norm(r))&gt;=eps)): x=np.dot(np.dot((la.inv(M)),N),x)+np.dot((la.inv(M)),b) r=np.dot(A,x)-b err = la.norm(r,2) res.append(err) i=i+1 return (x,i,res) and the test : A=np.array([[2,0,0],[4,5.4,0],[7,8,9]]) x0=np.array([[1],[1],[1]]) b=np.array([[20],[8],[7]]) print(jacobi(A,b,1000,10**(-3),x0)) Now, I have to represent on a graph (in logarithmic scale for ordinates) the values in function of n. I just would like to know how to represent a graph in logarithmic scal ? I'm beginner in Python and I don't know how to represent a graph... I tried to be clear, sorry for my bad English...
tagged with: math
tagged with: python
tagged with: numpy

http://stackoverflow.com/q/47852761
has body: I'm fairly new to web scraping, but I collected a large amount of data which I wrote to file using file.write() since I was unaware that json.dumps() existed. I'm attempting to remedy this by reformatting the data so that it can be loaded back into Python 3 as JSON. I need to be able to replace all of the single quotes (with double quotes) in a string without replacing any of the ones that come immediately after the backslash. For example: {'please':'don\'t touch friend\'s cat'} Would become: {"please":"don\'t touch friend\'s cat"} Any other advice on reformatting would also be greatly appreciated.
accepted answer: http://stackoverflow.com/a/47852817
type: Question
tagged with: python-3.x
has title: Replacing all single quotes except for ones immediately after backslash
tagged with: python
has answer: http://stackoverflow.com/a/47852817
has answer: http://stackoverflow.com/a/47852838
type: AnsweredQuestion
score: 0
answer count: 3
has comment: http://stackoverflow.com/comment/82669932
has answer: http://stackoverflow.com/a/47852821
possible better answer: http://stackoverflow.com/a/47852821
tagged with: http://stackoverflow.com/tag/json

http://stackoverflow.com/comment/82520352
type: AnswerComment
comment on: http://stackoverflow.com/a/47779618
score: 0
type: Comment
has text: Why did you copy my answer as your own?

http://stackoverflow.com/comment/82462344
has text: What is the problem with using the solution from the linked question?
score: 0
comment on: http://stackoverflow.com/q/47750639
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47845672
has title: How can I get the count of different values of one colum
tagged with: pandas
upvote count: 2
has body: I have a table like this DURATION FLAG 1 1 1 1 1 1 1 0 1 0 2 1 2 1 2 0 2 0 2 0 3 1 3 0 3 0 3 0 3 0 There are only two kinds of values of column FLAG, that are 1 and 0. And I want count the count of each value of FLAG the result looks like this DURATION FLAG_1_COUNT FLAG_0_COUNT 1 3 2 2 2 3 3 1 4 How can I get the above result. I tried the following code but didn't return the right result. df.groupby(['DURATION', 'FLAG']).size().reset_index(name='count')
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47845723
score: 1
downvote count: 1
answer count: 1
favorite count: 0
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/47845723

http://stackoverflow.com/q/47765066
score: 2
type: AnsweredQuestion
has title: Python: Add elements to second axis of numpy array in a loop
has body: This link suggests that we can use a Python list to add elements to it and convert it to numpy array using np.array with unknown length like this: a = [] for x in y: a.append(x) a = np.array(a) Let's say x is a numpy.ndarray with shape (h,w) but h and w are unknown, how can we add elements to second axis of ndarray a in a loop to make a becomes (h,w,d) where d is the number of iterations? I understand we can use dstack to add elements together to become (h,w,d) but I am not too sure how to do this in a loop.
has comment: http://stackoverflow.com/comment/82493970
linked to: http://stackoverflow.com/q/10121926
accepted answer: http://stackoverflow.com/a/47765651
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/47765651
favorite count: 0
type: Question
tagged with: numpy
upvote count: 2
tagged with: python

http://stackoverflow.com/q/47783829
tagged with: binary
has answer: http://stackoverflow.com/a/47784162
linked to: http://stackoverflow.com/q/15505514
upvote count: 2
has answer: http://stackoverflow.com/a/47785132
tagged with: arrays
has body: Say I am given a numpy integer array of the form a=np.array([0,0,0,1,1,0,1,0,1,0,1]) Now suppose I want to extract part of that array from positions i1:i2 and convert it to a base 10 representation. For instance, take i1=4 and i2=8. Then: base_2=a[i1:i2] # base_2 = np.array([1,0,1,0]) And I would expect the function to return 10=2+8. My question is the following : What is a fast way to achieve this in Python ? Consider a function with the following signature: def base_2_to_10_array(my_array,i1,i2): return """your awesome answer here"""
has comment: http://stackoverflow.com/comment/82529216
tagged with: python
duplicate of: http://stackoverflow.com/q/15505514
type: AnsweredQuestion
has title: Fast way of converting parts of a bit numpy array to base 10
answer count: 3
accepted answer: http://stackoverflow.com/a/47785005
score: 1
has comment: http://stackoverflow.com/comment/82529052
has comment: http://stackoverflow.com/comment/82529018
has answer: http://stackoverflow.com/a/47785005
possible better answer: http://stackoverflow.com/a/47784162
downvote count: 1
favorite count: 0
type: Question
tagged with: numpy

http://stackoverflow.com/comment/123052265
has text: @MichaelGreen then you're not comparing `True` to `True` - You are comparing `1` to `True` which is different.
comment on: http://stackoverflow.com/a/47778970
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47845817
has comment: http://stackoverflow.com/comment/82656002
has answer: http://stackoverflow.com/a/47847534
has title: Python - Inheritance from a Tk class
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/82655879
has comment: http://stackoverflow.com/comment/82656492
has comment: http://stackoverflow.com/comment/82655863
answer count: 1
downvote count: 1
has body: I'm trying to create a modular class ( for some gui buttons ). CoreButton should consist of most methods for a common button, including tk frame. Goal is to inheret CoreButton - and to use its frame to build rest of button's GUI - it does not appear. any help will be appriciated class CoreButton(ttk.Frame): def __init__(self, master,nickname, hw_in=[], hw_out=[],ip_in='', ip_out='', sched_vector=[]): ttk.Frame.__init__(self, master) self.master = master if ip_in == '': ip_in = ip_out # in case remote input is not defined self.grid() #####Rest of code and class that inherits: class ToggleBut2(CoreButton): def __init__(self, master, hw_in=[], hw_out=[],ip_in='', ip_out='', sched_vector=[]): CoreButton.__init__(self, master, nickname="JOHM", hw_in=hw_in, hw_out=hw_out, ip_in=ip_in, ip_out=ip_out, sched_vector=sched_vector) self.master = master def build_gui(self, nickname='babe', height=3, width=13): self.button = tk.Checkbutton(self, text=nickname, variable=self.but_var, indicatoron=0, height=height, width=width, command=self.sf_button_press) self.button.grid(row=0, column=0)
favorite count: 0
type: Question
tagged with: tkinter
has comment: http://stackoverflow.com/comment/82658512
has comment: http://stackoverflow.com/comment/82655821
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/47847534
tagged with: inheritance

http://stackoverflow.com/q/47818881
has comment: http://stackoverflow.com/comment/82600992
tagged with: python
tagged with: vectorization
has title: Create Counter from pandas dataframe without iterrows
score: 0
answer count: 0
tagged with: pandas
linked to: http://stackoverflow.com/q/20109391
tagged with: dataframe
has comment: http://stackoverflow.com/comment/82601245
type: Question
has comment: http://stackoverflow.com/comment/82600887
has comment: http://stackoverflow.com/comment/82600918
has body: I have a pandas dataframe which looks like this: { 'entry': string, 'category': string, 'cat_1_score': float, 'cat_2_score': float, 'cat_3_score': float } A piece of this dataframe: **entry** **category** Entry161 cat_1 Entry37 cat_2; cat_1 Entry209 cat_1 Entry161 cat_1 Entry161 cat_1 Entry46 cat_1 Entry47 cat_3; cat_1 Entry37 cat_2; cat_1 Entry75 cat_1 Entry161 cat_1 Reproducible: df = pd.DataFrame([['Entry161', 'cat_1'], ['Entry137', 'cat_2; cat_1'], ['Entry209', 'cat_1'], ['Entry161', 'cat_1'], ['Entry161', 'cat_1'], ['Entry46', 'cat_1'], ['Entry47', 'cat_3; cat_1'], ['Entry37', 'cat_2; cat_1'], ['Entry75', 'cat_1'], ['Entry161', 'cat_1']], columns=['entry', 'category']) and I want to create a Python Counter Object that will be a nested dictionary of the form {'entry': {'category': count}}. Values of entry are non-unique, and values of category can be one or more of cat_1, cat_2, cat_3. For example, in the first row, since there is only cat_1, the value for cat_1_score will be greater than zero, and the values for cat_2_score and cat_3_score will be zero. In the example above, the Python Counter should look like: {'Entry161': {'cat_1': 4}, 'Entry37': {'cat_1':2, 'cat_2': 2}...} In the case that category only takes single values, the straightforward, albeit inefficient way of doing this would be iterating over the rows of the DataFrame like this: my_counter = defaultdict(Counter) for i, row in df.iterrows(): my_counter[row.entry][row.category] += 1 Depending on the value of category (one of cat_1, cat_2, cat_3) the appropriate _score is nonzero. So there has to be faster way to generate these counters without iterating over rows of the dataframe, and using vectorization instead. Unfortunately this gets more complicated if there is the option of having multiple entries in the category column, separated by a semi colon, for example one row can have cat_1; cat_3 as an entry to this column, and the counter needs to take into account both cases. In that case, my way to…
type: UnansweredQuestion

http://stackoverflow.com/comment/82612064
type: AnswerComment
has text: Normally I don't like this sort of answer, but I feel like you've captured the essence of the problem so well that +1.
type: Comment
comment on: http://stackoverflow.com/a/47824545
score: 0

http://stackoverflow.com/a/47841445
score: 1
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47841332
has comment: http://stackoverflow.com/comment/82652872
has comment: http://stackoverflow.com/comment/82699415
type: Answer
has body: One solution would be to associate an index with the filename which you can accomplish using enumerate; I think you can just change your loop to for i, fn in enumerate(r_2dp): for j, ti in enumerate(theta): for filename in os.listdir('C:/Users/myName/ex2/all'): if filename.startswith('H2O'): filename = 'H2O.r{}theta{}.out'.format(fn,ti) E[j,i] = extract(filename) Please note that I changed E[i,j] to E[j,i] to get the dimensions correctly; you could also change the order of the two for-loops or initialize E the other way round... Untested, as we cannot access your file, but the general idea should work...
answers question: http://stackoverflow.com/q/47841332
has comment: http://stackoverflow.com/comment/82655419
downvote count: 0

http://stackoverflow.com/a/47786108
has body: Add __init__.py to exchanges folder make it as a python package import sys sys.path(path_to_modules_directory) By doing so you can import all modules by using this way from exchanges import *
type: Answer
has comment: http://stackoverflow.com/comment/82534476
score: 0
has comment: http://stackoverflow.com/comment/82533357
answers question: http://stackoverflow.com/q/47785950

wrapper
tag name: wrapper
type: Tag
tags question: http://stackoverflow.com/q/47835853
tags question: http://stackoverflow.com/q/47724911

http://stackoverflow.com/comment/83717040
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47768570
has text: From the article you are reading: "Note that existing entries will not be automatically modified, a read-write of the entity is required before the new properties will be persisted to Datastore." You need to re-put the old entities to the datastore with the new schema. Hope this helps...
score: 0

http://stackoverflow.com/comment/82500389
type: QuestionComment
has text: are you using a different VE for each project?
comment on: http://stackoverflow.com/q/47769641
score: 1
type: Comment

http://stackoverflow.com/comment/82518314
comment on: http://stackoverflow.com/q/47778550
type: QuestionComment
score: 1
has text: Does `import tkinter` work? If it does tkinter is installed. Tkinter is installed by default on all Windows machines as far as I know so it seems to be a mathplotlib problem.
type: Comment

http://stackoverflow.com/q/47750439
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47901923
has comment: http://stackoverflow.com/comment/82545614
tagged with: database
has comment: http://stackoverflow.com/comment/82551075
has comment: http://stackoverflow.com/comment/82551328
tagged with: python
tagged with: mysql
has title: Getting data from multiple databases with same tablenames in django
has comment: http://stackoverflow.com/comment/82551558
has answer: http://stackoverflow.com/a/47901923
has answer: http://stackoverflow.com/a/47807751
possible better answer: http://stackoverflow.com/a/47807751
type: AnsweredQuestion
answer count: 2
has comment: http://stackoverflow.com/comment/82551635
downvote count: 0
has comment: http://stackoverflow.com/comment/82545595
has comment: http://stackoverflow.com/comment/82551851
has body: I need to get data from different imported MySQL-databases in Django (Django 1.11.7, Python 3.5.2). I run manage.py inspectdb --database '&lt;db&gt;' and then use the models in django. Until now, I only had to access tables with different names. For this purpose, I used the using keyword in the queryset to specify the appropriate database and then concatenated the result, like this: from ..models.db1 import Members from ..models.db2 import Actor context['db1_data'] = Members.objects.using('db1').filter... context['db2_data'] = Actor.objects.using('db1').filter... context["member_list"] = list(chain( context["db1_data"], context["db2_data"], )) return context Now I have the problem that there are tables with the same model names in two databases. I get the following error when using the above-mentioned method (I substituted the names): RuntimeError: Conflicting '&lt;table-name&gt;' models in application '&lt;app&gt;': &lt;class '&lt;app&gt;.&lt;subfolder&gt;.models.&lt;db1&gt;.&lt;table-name&gt;'&gt; and &lt;class '&lt;app&gt;.&lt;subfolder&gt;.models.&lt;db2&gt;.&lt;table-name&gt;'&gt;. I already tried importing the model with a different name, like this: from ..models.db3 import Members as OtherMembers but the error still comes up. Shouldn't from ..models.db1 and from ..models.db2 be clear enough for Django to spot the difference between the two models? One option would probably be to rename the models themselves, but that would mean to rename every database model with the same names. Since I will use many more databases in the future, this is not an option for me. I tried from models import db1, db2 and then db1.Members etc., which still raises the error. I read about the meta db_table = 'dbname.tablename'-option, but since the model is auto-generated through inspectdb, it already has something like this on every class: class MyModel(models.Model): &lt;models&gt; class Meta: managed = False db_table = 'my_model' As described before, the other database has the exac…
tagged with: django
score: 13
upvote count: 13

http://stackoverflow.com/q/47818227
type: Question
tagged with: pandas
possible better answer: http://stackoverflow.com/a/47818701
type: AnsweredQuestion
score: 0
has body: Given some data about dishes, the location of the restaurant and its sales: &gt;&gt;&gt; import pandas &gt;&gt;&gt; df1 = pandas.DataFrame({"dish" : ["fish", "chicken", "fish", "chicken", "chicken"], ... "location" : ["central", "central", "north", "north", "south"], ... "sales" : [1,3,5,2,4]}) &gt;&gt;&gt; df1 dish location sales 0 fish central 1 1 chicken central 3 2 fish north 5 3 chicken north 2 4 chicken south 4 &gt;&gt;&gt; df2 = df1"dish", "location" &gt;&gt;&gt; df2["sales_contrib"] = 0.0 &gt;&gt;&gt; df2 dish location sales_contrib 0 fish central 0.0 1 chicken central 0.0 2 fish north 0.0 3 chicken north 0.0 4 chicken south 0.0 Right now, I would like to do the following: Iterate through each row of df2 Calculate the sales contrib. of that location for that dish . So for fish, central contributes 1/6 16.67% of total revenue and north contributes the remaining 83.3% The resultant df is dish location sales_contrib 0 fish central 16.67 1 chicken central 33.33 2 fish north 83.33 3 chicken north 22.22 4 chicken south 44.45 I tried using iteritems() but could not get results.
tagged with: dataframe
accepted answer: http://stackoverflow.com/a/47818635
has answer: http://stackoverflow.com/a/47818635
answer count: 2
has answer: http://stackoverflow.com/a/47818701
has title: Update the values of a dataframe
tagged with: python

http://stackoverflow.com/a/47776649
has comment: http://stackoverflow.com/comment/103535672
has comment: http://stackoverflow.com/comment/103535435
upvote count: 48
score: 48
has comment: http://stackoverflow.com/comment/85727893
has comment: http://stackoverflow.com/comment/83350712
type: Answer
accepted answer of: http://stackoverflow.com/q/47776486
has comment: http://stackoverflow.com/comment/109086099
has comment: http://stackoverflow.com/comment/109097308
has comment: http://stackoverflow.com/comment/82514553
answers question: http://stackoverflow.com/q/47776486
has body: The communication protocol between processes uses pickling, and the pickled data is prefixed with the size of the pickled data. For your method, all arguments together are pickled as one object. You produced an object that when pickled is larger than fits in a i struct formatter (a four-byte signed integer), which breaks the assumptions the code has made. You could delegate reading of your dataframes to the child process instead, only sending across the metadata needed to load the dataframe. Their combined size is nearing 1GB, way too much data to share over a pipe between your processes. Quoting from the Programming guidelines section: Better to inherit than pickle/unpickle When using the spawn or forkserver start methods many types from multiprocessing need to be picklable so that child processes can use them. However, one should generally avoid sending shared objects to other processes using pipes or queues. Instead you should arrange the program so that a process which needs access to a shared resource created elsewhere can inherit it from an ancestor process. If you are not running on Windows and use either the spawn or forkserver methods, you could load your dataframes as globals before starting your subprocesses, at which point the child processes will 'inherit' the data via the normal OS copy-on-write memory page sharing mechanisms. Note that this limit was raised for non-Windows systems in Python 3.8, to an unsigned long long (8 bytes), and so you can now send and receive 4 EiB of data. See this commit, and Python issues #35152 and #17560. If you can't upgrade and you can't make use of resource inheriting, and are not running on Windows, then use this patch: import functools import logging import struct import sys logger = logging.getLogger() def patch_mp_connection_bpo_17560(): """Apply PR-10305 / bpo-17560 connection send/receive max size update See the original issue at https://bugs.python.org/issue17560 and https://github.com/python/cpython/pull/10305 f…
downvote count: 0
has comment: http://stackoverflow.com/comment/82514472
has comment: http://stackoverflow.com/comment/83350754
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82514576

http://stackoverflow.com/q/47731029
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82423353
has comment: http://stackoverflow.com/comment/82423233
tagged with: python
upvote count: 3
score: 3
downvote count: 0
has title: Convert 8 bit image to 24 bit
linked to: http://stackoverflow.com/q/902761
has body: So I am trying to convert my grayscale image (8 bit) to 24 bit with python. And I tried to do it with numpy. But how do i save it as a .png image? import numpy as np img = np.array(NewGrayScaleImage, dtype=np.uint16) img *= 384 #256 for 16 bit
favorite count: 0
type: Question
tagged with: numpy
tagged with: python-3.x
duplicate of: http://stackoverflow.com/q/902761
answer count: 0

http://stackoverflow.com/comment/82359783
score: 0
type: AnswerComment
has text: Thanks Paul! That's simple, flexible and all in one line--exactly what I expect from Python. Appreciate it!
comment on: http://stackoverflow.com/a/47698218
type: Comment

http://stackoverflow.com/comment/82497560
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47768206
has text: If you found the entire word, the length of the match is the length of the word you were searching for, no?
type: Comment

http://stackoverflow.com/a/47778880
type: Answer
score: 0
answers question: http://stackoverflow.com/q/47770545
has body: To answer your specific question: what does this mean?: import turtle The import command is used to bring additional collections of code into Python for you to use. The turtle library is an example of such -- Python doesn't respond to turtle commands until you bring them into Python via this import statement. There is online documentation for Turtle. For quick lookups, you can check what you loaded via: &gt;&gt;&gt; import turtle &gt;&gt;&gt; dir(turtle) and lookup individual functions via: &gt;&gt;&gt; help(turtle.forward) from within the interactive Python shell.

http://stackoverflow.com/q/47824811
has comment: http://stackoverflow.com/comment/82612494
score: 0
has comment: http://stackoverflow.com/comment/82612298
has comment: http://stackoverflow.com/comment/82612416
tagged with: user-interface
has title: Tkinter Image Updating Image + lambda Error
has comment: http://stackoverflow.com/comment/82612391
has answer: http://stackoverflow.com/a/47824856
answer count: 1
type: Question
tagged with: ttk
tagged with: python
type: UnansweredQuestion
has body: As of late I have been basically self-teaching myself Tkinter. I've been working on this project for about a week now and I feel like it's coming along rather nicely. Today while I was working on it I got this code, which when ran successfully sets up the GUI. However, when I try to change the image via the Combobox, it fails and gives me the following error: Exception in Tkinter callback Traceback (most recent call last): File "C:\Users\user\AppData\Local\Programs\Python\Python36-32\lib\tkinter\__init__.py", line 1699, in __call__ return self.func(*args) TypeError: &lt;lambda&gt;() takes 0 positional arguments but 1 was given After a quick search I found that using lambda x: would fix this error. After making this change, the GUI initiates as normal, however the images will still not change, in fact, the second panel glitches out and removes the image if an item is selected from the first Combobox. Complete removal of 'lambda' causes the panels to not be initiated at all. Basically, I would like to know what is causing these glitches and how to get my images to update. from tkinter import * from tkinter.ttk import * from PIL import Image, ImageTk import os class App(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent parent.title('Vainglory DMG Calculator | BETA') self.dyn_panel = [] self.dyn_combobox = [] self.dyn_image_path = ['', ''] self.dyn_img = ['', ''] self.cwd = os.getcwd() self.hero_list = ('Adagio', 'Alpha', 'Ardan', 'Baptiste', 'Baron', 'Blackfeather', \ 'Catherine', 'Celeste', 'Churnwalker', 'Flicker', 'Fortress', \ 'Glaive', 'Grace', 'Grumpjaw', 'Gwen', 'Idris', 'Joule', \ 'Kestrel', 'Koshka', 'Krul', 'Lance', 'Lorelai', 'Lyra', 'Ozo', \ 'Petal', 'Phinn', 'Reim', 'Reza', 'Ringo', 'Rona', 'Samuel', \ 'SAW', 'Skaarf', 'Skye', 'Taka', 'Varya', 'Vox') for i in range(2): self.create_hero_combo_box(parent, i) self.set_image(i) self.create_hero_panel(parent, self.dyn_img[i], i) def create_hero_panel(self, window, img, index)…
tagged with: tkinter
has comment: http://stackoverflow.com/comment/82612168

http://stackoverflow.com/a/47714552
type: Answer
answers question: http://stackoverflow.com/q/47714423
downvote count: 0
score: 1
upvote count: 1
has body: Here is one possibility: import itertools a = [ [33,3,3,0] , [34,1,0,4] ] list(map(list, map(filter, itertools.repeat(bool), a))) # [[33, 3, 3], [34, 1, 4]]

http://stackoverflow.com/a/47811709
has body: I am using urllib instead of requests import urllib url = "http://62.138.7.10/downloads/Bh2g2m.Bh2g.06.DR.M0viesC0unter.mp4?st=6MVZyTUL7X22v7ILOtB2XA&amp;e=1502823147" file_name = 'trial_video.mp4' response = urllib.urlopen(url) with open(file_name,'wb') as f: f.write(response.read()) Hope this will help you
answers question: http://stackoverflow.com/q/47811129
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/112816221
has comment: http://stackoverflow.com/comment/112801877
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/47727727
type: Answer
score: 0
has body: The opinion on whether from &lt;module&gt; import &lt;identifier&gt; is Pythonic itself is quite split - it hides away the origin of a method so it's not easy to figure out whence a certain variable/function comes from just by perusing the code. On the other hand, it reduces verbosity which some people consider Pythonic even tho it's not specifically mandated. Either way, Pythonic is as elusive term as you're going to get and more often than not it means "the way I think Python code should look like" backed up by several PEPs and obscure mail list posts while conveniently omitting the ones that go against one's notion of Pythonic. from os import path.join doesn't work because os defines the os.path module (by directly writing to sys.modules of all things), it's not an identifier in the os module itself. path, however, is an identifier in the os module pointing to the os.path module so you can do from os import path or from os.path import join. Finally, succinct and Pythonic are not synonyms, in fact PEP 8 for example prescribes using multiple lines for multiple imports even tho you can succinctly write import &lt;module1&gt;, &lt;module2&gt;, &lt;module3&gt; .... It says that it's OK to import multiple identifiers like that, tho, but keep in mind that os and os.path are two different modules so based on PEP 8 they shouldn't be on the same line and therefore should be written as: from os import &lt;identifier_1&gt;, &lt;identifier_2&gt; from os.path import &lt;identifier_3&gt;, &lt;identifier_4&gt; Now, I would go as far as claiming that this is Pythonic but it makes the most sense based on PEP 8, at least to me.
answers question: http://stackoverflow.com/q/47727497

http://stackoverflow.com/comment/82503537
type: AnswerComment
comment on: http://stackoverflow.com/a/47755357
type: Comment
has text: I agree with this, would you be able to make some comments next to the lines to help describe what is going on (e.g. special cases?).
score: 0

http://stackoverflow.com/comment/82454985
comment on: http://stackoverflow.com/a/47745092
has text: 20 and 30 are the weights that add to a capacity of 180. It's giving you the value + the weight. opt_value[0] will get you your 180.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/82426895
comment on: http://stackoverflow.com/q/47733165
type: Comment
has text: use raw_input in python 2 and input in python 3
type: QuestionComment
score: 2

http://stackoverflow.com/a/47786626
downvote count: 1
answers question: http://stackoverflow.com/q/47786568
has comment: http://stackoverflow.com/comment/82552933
upvote count: 1
score: 0
type: Answer
has body: It's as simple as this if you want a quick fix - for i in range(len(my_list)): my_list[i]=my_list[i][0]

http://stackoverflow.com/q/47699767
has comment: http://stackoverflow.com/comment/82360583
has comment: http://stackoverflow.com/comment/82359745
type: Question
tagged with: serialization
has body: In my Django REST framework project i have this model: class ml_request(models.Model): model_id = models.CharField(max_length=100) created = models.DateTimeField(auto_now=True) p_country = models.CharField(max_length=100, blank=False, default='') p_description = models.TextField(null=False, blank=False) p_designation = models.CharField(max_length=200, blank=False, default='') p_points = models.IntegerField(default=00) p_price = models.IntegerField(default=00, blank=False) p_province = models.CharField(max_length=100, blank=False, default='') p_region_1 = models.CharField(max_length=100, blank=False, default='') p_region_2 = models.CharField(max_length=100, blank=False, default='') p_variety = models.CharField(max_length=100, blank=False, default='') p_winery = models.CharField(max_length=100, blank=False, default='') owner = models.ForeignKey('auth.User', related_name='req_owner', on_delete=models.CASCADE) highlighted = models.TextField() class Meta: ordering = ('created',) then i create my serializer like this: from rest_framework import serializers from botoapi.models import ml_request, ml_response, LANGUAGE_CHOICES, STYLE_CHOICES, ml_logs from django.contrib.auth.models import User class RequestSerializer(serializers.HyperlinkedModelSerializer): id = serializers.IntegerField(label='ID', read_only=True) highlight = serializers.HyperlinkedIdentityField(view_name='request-highlight', format='html') owner = serializers.ReadOnlyField(source='owner.username') class Meta: model = ml_request fields = ('id', 'model_id', 'highlight', 'created', 'p_country', 'p_description', 'p_designation', 'p_points', 'p_price', 'p_province', 'p_region_1', 'p_region_2', 'p_variety', 'p_winery', 'owner') def create(self, validated_data): log_save = ml_logs(l_verbose=validated_data, l_method="CREATE", l_action=validated_data.get("model_id", None)) log_save.save() return validated_data and is my view code: class RequestViewSet(viewsets.ModelViewSet): queryset = ml_request.objects.all() seria…
has comment: http://stackoverflow.com/comment/82359553
type: UnansweredQuestion
tagged with: restful-url
tagged with: django
tagged with: python
tagged with: django-rest-framework
score: 0
has answer: http://stackoverflow.com/a/47701387
has title: Django REST framework serialization error on pk field
answer count: 1

http://stackoverflow.com/comment/82473963
type: Comment
comment on: http://stackoverflow.com/q/47756222
score: 0
has text: Or possibly even use a `ModelForm` with non-required fields which are the subset of what you want to update, then use that to retrieve/save your model with the json data - added bonus is that you then also get added validation/write custom validation as appropriate.
type: QuestionComment

http://stackoverflow.com/comment/82633116
type: QuestionComment
comment on: http://stackoverflow.com/q/47764902
type: Comment
has text: Sorry, but I'm going to have to ask for a [mcve] of the code. It's hard for me to think of how you've multiplied your input size so much
score: 0

http://stackoverflow.com/comment/82487464
comment on: http://stackoverflow.com/q/47762735
has text: Also, it would be really helpful if you gave some example inputs with expected outputs. I think I know what you are trying to do, but it would be a lot more clear (and your questions will be better received) if you provide example input and expected output.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47722615
type: Answer
has body: Provided the same structure, you can easily unwrap it within list comprehension by joining the two indices of each inner list: data = [('KOR', [3, 1, 0]), ('ITA', [1, 0, 0]), ('TPE', [0, 1, 1]), ('CHN', [0, 1, 0]), ('JPN', [0, 1, 0]), ('AUS', [0, 0, 1]), ('GBR', [0, 0, 1]), ('UKR', [0, 0, 1])] flattened = [" ".join(str(e) for e in [item[0]] + item[1]) for item in data] # ['KOR 3 1 0', 'ITA 1 0 0', 'TPE 0 1 1', 'CHN 0 1 0', 'JPN 0 1 0', 'AUS 0 0 1', # 'GBR 0 0 1', 'UKR 0 0 1']
downvote count: 0
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/47722433

http://stackoverflow.com/comment/82643447
has text: I could have been more explicit in my description I suppose, but I never provided that input or said it was a tree :) Also - isn't your first example really doing a BFS? It looks like you process the children `xs` left to right. How would this work if you are dealing with a graph structure where you want to enter at a specific point, generate children, and proceed from there - rather than processing the entire tree sequentially.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/47790682
type: AnswerComment

http://stackoverflow.com/comment/82530656
comment on: http://stackoverflow.com/a/47774144
type: AnswerComment
score: 0
has text: ok now I see, generally those images are due to an invalid property or an invalid format of color .Remove the unfocus property and try it again on qpython
type: Comment

http://stackoverflow.com/q/47825072
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82612852
linked to: http://stackoverflow.com/q/2804543
tagged with: python
has answer: http://stackoverflow.com/a/47825180
has title: A program that launches another program and acts as its stdout
has comment: http://stackoverflow.com/comment/82612926
duplicate of: http://stackoverflow.com/q/18421757
has comment: http://stackoverflow.com/comment/82612778
has comment: http://stackoverflow.com/comment/82612868
has comment: http://stackoverflow.com/comment/82612782
score: 0
tagged with: bash
has comment: http://stackoverflow.com/comment/82612794
duplicate of: http://stackoverflow.com/q/4417546
answer count: 1
tagged with: stdout
has comment: http://stackoverflow.com/comment/82612773
upvote count: 1
has comment: http://stackoverflow.com/comment/82612814
linked to: http://stackoverflow.com/q/4417546
downvote count: 1
duplicate of: http://stackoverflow.com/q/803265
favorite count: 0
type: Question
has body: I want my program to launch some other program and somehow receive all of it's printing output. The bash/terminall/shell (not sure about my terminology here) does exactly that - you tell it what program to open and it acts as standard output for that program. How can that be implemented? (Asking for a Python version here, but of course C/C++ way is good to know!) Thanks!
tagged with: stdin
duplicate of: http://stackoverflow.com/q/2804543

http://stackoverflow.com/a/47815540
type: Answer
answers question: http://stackoverflow.com/q/47815181
score: 0
has body: This should do what you want: import itertools def main(): newkeywords = [] keywords = ["".join(i) for i in itertools.product(["11", "22", "33"], repeat = 2)] for item in keywords: newitem = "".join(sorted(item)) if "3" not in newitem and newitem not in newkeywords: newkeywords.append(newitem) print(newkeywords) main() results: ['1111', '1122', '2222'] It makes a new list, and if that sorted item (which makes 1122 the same as 2211) exists or the number "3" exists, don't add it to the new list.

http://stackoverflow.com/comment/82513590
has text: Yes, it is similar, @Wen
type: Comment
comment on: http://stackoverflow.com/a/47776077
type: AnswerComment
score: 1

http://stackoverflow.com/a/47736668
type: Answer
accepted answer of: http://stackoverflow.com/q/47736598
has body: According to the documentation, it looks like ndarray uses __new__() to do its initialization, not __init__(). In particular, the dtype of the array is already set before your __init__() method runs, which makes sense because ndarray needs to know what its dtype is to know how much memory to allocate. (Memory allocation is associated with __new__(), not __init__().) So you'll need to override __new__() to provide the dtype parameter to ndarray. class MyArray(numpy.ndarray): def __new__(cls, dim): return numpy.ndarray.__new__(cls, dim, dtype=object) Of course, you can also have an __init__() method in your class. It will run after __new__() has finished, and that would be the appropriate place to set additional attributes or anything else you may want to do that doesn't have to modify the behavior of the ndarray constructor. Incidentally, if the only reason you're subclassing ndarray is so that you can pass dtype=object to the constructor, I'd just use a factory function instead. But I'm assuming there's more to it in your real code.
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47736598
score: 1
upvote count: 1

http://stackoverflow.com/comment/97796451
has text: Yes, they will block. You can wrap the calls to these functions with `asyncio.run_in_executor` and await that (by default runs the functions in another thread). Alternatively you can switch to a asyncio based alternative library.
type: Comment
comment on: http://stackoverflow.com/a/48491565
type: AnswerComment
score: 0

http://stackoverflow.com/q/47698528
accepted answer: http://stackoverflow.com/a/47698601
type: AnsweredQuestion
has title: How to get a key in a dictionary in a dictionary
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/82356955
has body: here's my list : data_config = [{'music': {' extension': 'mp3'}}, {'reports/INFOB131': {' extension': ['doc', 'docx', 'pdf'], ' max_size': '100000', ' name_contains': 'INFOB131'}}, {'reports/INFOB132': {' extension': ['doc', 'docx', 'pdf'], ' max_size': '100000', ' name_contains': 'INFOB132'}}, {'games': {' name_contains': ['SC2', 'Wesnoth']}}, {'pictures/Namur': {' extension': 'jpeg', ' min_size': '5000000', ' name_contains': 'cercle'}}, {'pictures/autres': {' extension': 'jpeg', ' min_size': '5000000'}}] When I do these instructions, I get : for i in data_config[0]['music']: print(data_config[0]['music'][i]) output : mp3 But when I do this, I get an error: print(data_config[0]['music']['extension']) output : --------------------------------------------------------------------------- KeyError Traceback (most recent call last) &lt;ipython-input-9-f71c5ad09034&gt; in &lt;module&gt;() ----&gt; 1 print(data_config[0]['music']['extension']) KeyError: 'extension' Does anyone have an idea ? Thank you !
has answer: http://stackoverflow.com/a/47698664
possible better answer: http://stackoverflow.com/a/47698664
type: Question
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/47698601

http://stackoverflow.com/comment/82438482
type: QuestionComment
score: 0
has text: Unfortunately, without knowing a little more about the underlying framework, we'll not be able to help. Is this Flask? Django?
comment on: http://stackoverflow.com/q/47739105
type: Comment

http://stackoverflow.com/comment/82484736
type: Comment
type: QuestionComment
score: 0
has text: Also, don't use `with open` context manager anew for every `while` loop iteration. use `with open...: while...`
comment on: http://stackoverflow.com/q/47761597

http://stackoverflow.com/q/47700386
tagged with: list-comprehension
score: 0
has body: How to check whether '111' exists in dic1? dic1 = {'images':[000,111,222,333,444],'name':['foo','bar','baz']} I tried using List comprehensions but unable to get the boolean answer? I got the error 'int' object is not iterable.
answer count: 1
has answer: http://stackoverflow.com/a/47700404
has comment: http://stackoverflow.com/comment/82360797
type: Question
has comment: http://stackoverflow.com/comment/82361007
type: UnansweredQuestion
has title: How to Check whether a element exists in a python dictionary value which is a list?
tagged with: python
tagged with: dictionary

http://stackoverflow.com/q/47743497
has title: How to update Tkinter label with sensor data every 2 seconds
tagged with: raspberry-pi3
has comment: http://stackoverflow.com/comment/82447487
downvote count: 1
has comment: http://stackoverflow.com/comment/82447519
favorite count: 0
type: Question
duplicate of: http://stackoverflow.com/q/24849265
upvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82447450
has comment: http://stackoverflow.com/comment/82447467
tagged with: python
has answer: http://stackoverflow.com/a/47743697
score: -1
has comment: http://stackoverflow.com/comment/82447958
has body: I am trying to update my label in Tkinter with the value of "x" for every time that "x" changes value. Almost like a live counter. This is a simplified loop because I am working on Pycharm. Eventually I would like to modify this code so that the label is updated with the values from a temperature sensor connected to my Raspberry Pi. Please can some assistance be provided on this topic, Thanks :) from Tkinter import * import tkFont import time # Window root = Tk() root.geometry("700x600+550+100") # Font font = tkFont.Font(family = 'Halvetica', size = 36, weight = 'bold') x = 0 def do(): list = [1, 2, 3, 4] for x in list: temp = Label(root, text=x, fg="black", heigh=2, width=15, font=font) temp.pack() time.sleep(2) #temp["text"] = x do() root.mainloop() I expected the program to print 1, then replace 1 with 2 and so forth. I do not want 1,2,3,4 to be presented all together. When I execute the code it presents me with the numbers 1 to 4 but it did not update it live and they are below each other which is not that I want
tagged with: tkinter
linked to: http://stackoverflow.com/q/24849265
tagged with: sensors
tagged with: user-interface
answer count: 1

http://stackoverflow.com/comment/82497984
score: 0
type: Comment
type: QuestionComment
has text: @furas, I mean after I call Gtk.main(), everything stops working. Cannot add new indicators etc.
comment on: http://stackoverflow.com/q/47767596

http://stackoverflow.com/comment/82652763
type: Comment
type: QuestionComment
score: 0
has text: Probably a memory issue. Why are you reading an infinite amount of frames? Why aren'y you immediately doing something with them and releasing? Print a counter every iteration to see where you get "stuck", and know you're limits.
comment on: http://stackoverflow.com/q/47844276

http://stackoverflow.com/comment/82440698
type: Comment
comment on: http://stackoverflow.com/a/47740216
type: AnswerComment
score: 0
has text: with the second solution I get AttributeError: 'DataFrameGroupBy' object has no attribute 'ngroup'

http://stackoverflow.com/comment/82465933
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47752733
type: Comment
has text: or just `return [y.pop(np.argmin(y)) for _ in x]`

http://stackoverflow.com/a/47699706
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: It appears that you are attemping to pass a variable into a function to be used as the return value. This is not Pythonic and in general will not work. Instead, your function should be returning a value and you should be assigning that value to a new "variable." def function(arg): if arg: return 'Pass' else: return 'Fail' status = function(False) print(status) # 'Fail' In Python, you don't want to try to write a function that calls by reference, because variables don't exist in Python in the same way that they do in C. Instead, what we have are names which are more akin to placeholders and can be used to retrieve objects. This article and many other Stack Overflow answers go into this in more depth.
has comment: http://stackoverflow.com/comment/82361131
accepted answer of: http://stackoverflow.com/q/47699625
has comment: http://stackoverflow.com/comment/82361991
answers question: http://stackoverflow.com/q/47699625
type: Answer
has comment: http://stackoverflow.com/comment/82361762

http://stackoverflow.com/comment/82487075
score: 0
comment on: http://stackoverflow.com/q/47762735
type: QuestionComment
has text: `bin'n + 1'` is not a valid python synthax
type: Comment

http://stackoverflow.com/comment/82457128
comment on: http://stackoverflow.com/q/47725080
type: Comment
score: 0
type: QuestionComment
has text: What happens if you print `grid.eval()[0, :, :, 0]` right before the call to `imsave`? What is the dtype of `grid.eval()[0, :, :, 0]`? Also, are the images actually the same?

http://stackoverflow.com/q/47845403
has comment: http://stackoverflow.com/comment/82670402
has comment: http://stackoverflow.com/comment/82655183
type: Question
has comment: http://stackoverflow.com/comment/82672158
tagged with: python-3.x
tagged with: mongodb
type: UnansweredQuestion
tagged with: python
tagged with: levenshtein-distance
has body: I am very beginner to python. I have two tables named as Table A and Table B, In Table A have 1M record is available and Table B have 14M records is available and each record is a very big sentence(Paragraph) with special character numbers etc.., I want to split the sentences into words of each record and compare the each row of Table A Column 1 into each and row of the Table B column 1 and I would like to the find top 5 highest match(Most relevant match) from the Table B record. And, if I compare like 1M*14M it tooks more time could you please suggest any one the right way to do in python with mongodb
score: 0
has title: Python with mongodb
answer count: 0

http://stackoverflow.com/a/47750748
has body: You need groupby and aggregate mean: df1 = df.groupby('marker').mean() And if need marker as column in output: df1 = df.groupby('marker', as_index=False).mean() df1 = df.groupby('marker').mean().reset_index()
upvote count: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47750718
answers question: http://stackoverflow.com/q/47750718
type: Answer
score: 2

http://stackoverflow.com/q/47772081
favorite count: 0
has title: Python: Is it possible to debug with breakpoints across modules in Spyder?
has comment: http://stackoverflow.com/comment/82583436
tagged with: spyder
upvote count: 6
type: Question
has comment: http://stackoverflow.com/comment/82522330
tagged with: debugging
tagged with: ipdb
answer count: 0
has body: I use the ipython debugger interactively in Spyder. I need to debug with breakpoints across modules i.e. I'd like the debugger to step into a function that is contained within a particular .py file which isn't the .py file I start the debugger on. At the moment, I can't seem to make this work. The debugger only 'sees' the breakpoints (which I manually add before running the debugger) in the current module. But I can't have every function in this module because it'll grow too large and it's not good practise. For testing, I really need to step into these smaller, generic functions that I hope to place in other modules. Thanks
type: UnansweredQuestion
downvote count: 0
score: 6
tagged with: python

http://stackoverflow.com/comment/82421692
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47723790
has text: It is not my suggestion. My suggestion was `query = """INSERT INTO saferdb_question( "DOT_Number") VALUES('1234')"""` Please be more careful.
score: 1

http://stackoverflow.com/q/47740657
possible better answer: http://stackoverflow.com/a/47741211
has answer: http://stackoverflow.com/a/47741211
has title: Test .py file in another file
type: Question
accepted answer: http://stackoverflow.com/a/47740949
tagged with: testing
answer count: 2
has answer: http://stackoverflow.com/a/47740949
tagged with: python
type: AnsweredQuestion
score: 0
has body: I have one .py file with my algorithm. In init(self) of this file I have some variables that need to be the same in all scenerios and 2 variables that I want to change for testing. I also created another .py file that is responsible to run my first file x times but every time with the same variables. My question is how should I properly create a testing enviroment for my first file to run it 10 times with different variables? Sample of my .py file that I want to test in 10 different scenerios. class A: def __init__(self): self.xsize = 50 self.ysize = 50 self.max_tx_power = 200 # Variable to change self.min_tx_pow = 10 # Variable to change def alforithm(self): power_steps = range(self.min_tx_pow, self.max_tx_power + 1)[0::10] def generator(self): self.algorithm() if __name__ == "__main__": a = A() a.generator()

http://stackoverflow.com/q/47804393
upvote count: 1
tagged with: python
tagged with: flask-sqlalchemy
favorite count: 0
tagged with: postgresql
has comment: http://stackoverflow.com/comment/82576197
score: 1
has comment: http://stackoverflow.com/comment/82570514
has title: SQLAlchemy: One select is executing multiple selects against Postgres DB
has comment: http://stackoverflow.com/comment/82578516
tagged with: sqlalchemy
has body: Can anyone with deeper SQLAlchemy knowledge explain why it appears to be sending multiple queries to the DB instead of just the one as explained below? The query looks like the following: session.query(Orders).filter( Orders.user_id == user_id, Orders.created_on &lt;= now, Orders.created_on &gt; 30_days_ago ).order_by( Orders.status, Orders.created_on.desc() ).all() (Orders.status is simply an integer like 1 => "shipped" 2 => "complete" 3 => "returned") I expected a single query emitted to the DB with reasonably the same logic as (in Postgres): SELECT * FROM Orders WHERE user_id = :user_id and created_on &lt; now() and created_on &gt;= now() - interval '30 days' ORDER BY status, created_on DESC; Assume the above query returned 10 rows with ids 1-11. What was actually seen emitted to the DB from the Postgres logs was an individual query for each row that would have been retrieved. SELECT * FROM Orders WHERE id = 1; SELECT * FROM Orders WHERE id = 2; SELECT * FROM Orders WHERE id = 3; ... Ended up having to use session.execute() instead of session.query(). Luckily in this case the app is not dependent on the session being up to date. Edit - adding more info about Orders model Base = declarative_base() class Orders(Base) __tablename__ = "Orders" id = Column(Integer, primary_key=True) user_id = Column(Integer, nullable=False, index=True) name = Column(String, nullable=False, index=True, index=True) category = Column(String, nullable=False) status = Column(Float, nullable=False) created_on = Column(DateTime, nullable=False) def __init__(self, user_id, name, category, status, created_on): self.user_id = user_id self.name = name self.category = category self.status = priority self.created_on = datetime.datetime.utcnow() The table has an index on the user_id column and the name column.
type: Question
has comment: http://stackoverflow.com/comment/86421084
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82570298
downvote count: 0

http://stackoverflow.com/comment/82462202
has text: @YvesLeBorg I have added my current code. and the problem is also given. please help
comment on: http://stackoverflow.com/q/47728841
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/82619982
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47828678
has text: whats the `obj` means there? do you mean it is the logined user? or do you mean the `obj` is the data(User's data)?

http://stackoverflow.com/a/47841187
accepted answer of: http://stackoverflow.com/q/47840620
type: Answer
has body: Based on the calculations I have done, the value 0.5 only holds for large n; please check whether I made a mistake (did not check the paper in detail). import pandas as pd from itertools import combinations l = pd.Series(list(range(3))) n = len(l) C = n * (n - 1) / 2. # get all pairs in l pairs = list(combinations(l, 2)) So pairs then looks as follows: [(0, 1), (0, 2), (1, 2)] We can now store that in a dataframe as you already work with pandas which makes subsequent calculations quite easy: # store pairs in dataframe df_pairs = pd.DataFrame(pairs).rename(columns={0: 'zi', 1: 'zj'}) # get max / min for each pair max_val = df_pairs.max(axis=1) min_val = df_pairs.min(axis=1) df_pairs['max_z'] = max_val df_pairs['min_z'] = min_val # absolute difference between z df_pairs['diff_z_abs'] = (df_pairs['zi'] - df_pairs['zj']).abs() df_pairs['ratio_diff_max'] = df_pairs['diff_z_abs'] / df_pairs['max_z'] df_pairs['one_minus_ratio'] = 1. - df_pairs['min_z'] / df_pairs['max_z'] By now the dataframe looks like this: zi zj max_z min_z diff_z_abs ratio_diff_max one_minus_ratio 0 0 1 1 0 1 1.0 1.0 1 0 2 2 0 2 1.0 1.0 2 1 2 2 1 1 0.5 0.5 The value PV is then simply: PV = df_pairs['ratio_diff_max'].sum() / C For this example it is 0.83333333, so much higher than 0.5. However, if we now change l = pd.Series(list(range(3))) to larger values, PV then approaches 0.5. For example, for l = pd.Series(list(range(5000))) I obtain 0.500199 So it probably only holds for n towards infinity.
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/47840620

http://stackoverflow.com/comment/93169960
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47872756
has text: What is Y_train in model.fit? What is its shape? If it has been specified that loss=triplet loss, then what is the need of lamba layers. please explain
type: Comment

http://stackoverflow.com/comment/82523905
score: 0
has text: Please let me know if my answer works for you.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47740558

http://stackoverflow.com/a/47817357
score: 0
has comment: http://stackoverflow.com/comment/82707352
has comment: http://stackoverflow.com/comment/82642345
answers question: http://stackoverflow.com/q/47810508
type: Answer
has body: Try: for product in price_errors: print product.price.final_price
has comment: http://stackoverflow.com/comment/82603437

http://stackoverflow.com/q/47805588
type: UnansweredQuestion
answer count: 1
downvote count: 0
tagged with: spectrogram
favorite count: 0
tagged with: colormap
score: 2
tagged with: colors
tagged with: matplotlib
has title: How do I add colors to my spectrogram?
tagged with: python
type: Question
has answer: http://stackoverflow.com/a/47805731
has body: so I found the following code that spits out a spectrogram. However, i'd like to add some random colours to it via colormap or other methods. I've read the cmap documentation and didn't understand a thing. The code: import matplotlib.pyplot as plt from scipy.io import wavfile def graph_spectrogram(wav_file): rate, data = get_wav_info(wav_file) nfft = 256 fs = 256 pxx, freqs, bins, im = plt.specgram(data, nfft,fs) plt.axis('off') plt.savefig('sp_xyz.png', dpi=100, # Dots per inch frameon='false', aspect='normal', bbox_inches='tight', pad_inches=0) plt.show() def get_wav_info(wav_file): rate, data = wavfile.read(wav_file) return rate, data if __name__ == '__main__': # Main function wav_file = 'song.wav' graph_spectrogram(wav_file) Thanks in advance for your help!
upvote count: 2

http://stackoverflow.com/comment/82481371
type: Comment
has text: It looks like it's behaving correctly to me. It's removing those items that are in `exist`. When I ran it, `exist` contains 0, 2, 3, 1, 4, and 6, and the buttons I see are 5, 7, and 8.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47759657

http://stackoverflow.com/q/47704925
has answer: http://stackoverflow.com/a/47705072
downvote count: 0
score: 1
upvote count: 1
has title: Pandas: Selecting value from preceding row and different column
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/47705074
has comment: http://stackoverflow.com/comment/82370234
tagged with: pandas
has answer: http://stackoverflow.com/a/47705074
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/82370047
favorite count: 0
accepted answer: http://stackoverflow.com/a/47705072
type: Question
tagged with: numpy
has body: I need to make a new dataframe from an existing one. The example below will explain what I mean. For each value in column2 and column3 I need to make a new row that includes the value from column1 that precedes it. I'm not sure how to select that value using pandas. index column1 column2 column3 0 shop1 1 34 0 2 32 0 3 35 1 4 shop2 5 52 1 6 57 0 Resulting dataframe: index column1 column2 column3 0 shop1 34 0 1 shop1 32 0 2 shop1 35 1 3 shop2 52 1 4 shop2 57 0 I've searched stackoverflow and the pandas documentation, but cannot find how to do this. Any help is appreciated, thank you.
answer count: 2

http://stackoverflow.com/comment/82411056
type: AnswerComment
comment on: http://stackoverflow.com/a/47725037
has text: @oh nevermind, I have my list named something different. And your codes worked fine, thank you! What I'm doing is self-learning from an assignment from my textbook. But I'm not clear on what you did there, could you either explain that to me?(I don't understand the ".format(i)" "a inenumerate(l,start =1)") and I'm also new to coding in general, how would I able to put in display in column as showed above in my og post?
type: Comment
score: 0

http://stackoverflow.com/comment/82523823
type: Comment
comment on: http://stackoverflow.com/a/47779053
has text: @MikeEvers just google 'how to use conda environments'. e.g. https://conda.io/docs/user-guide/getting-started.html#managing-envs
type: AnswerComment
score: 0

http://stackoverflow.com/a/47753646
score: 4
upvote count: 4
answers question: http://stackoverflow.com/q/47753510
downvote count: 0
has body: You initialized all tkinter's objects, except StringVar, you should do this: name = StringVar() instead of name = StringVar Now your variable name - instance of class StringVar and instances automatically pass argument 'self'.
type: Answer

http://stackoverflow.com/comment/82622742
type: QuestionComment
has text: @Ev. Kounis my mistake :)
type: Comment
score: 0
comment on: http://stackoverflow.com/q/47829676

http://stackoverflow.com/a/47718418
type: Answer
score: 0
has body: If you want to know the number of rows for each unique InvoiceNo, you can do df.groupby('InvoiceNo').size() If you want to group all the unique InvoiceNo's together and sum the 'Quantity' rows within each group, you do df.groupby('InvoiceNo').agg(np.sum)['Quantity']
answers question: http://stackoverflow.com/q/47717740

http://stackoverflow.com/comment/82566162
type: QuestionComment
score: 0
has text: @CharlesDuffy Thanks! It is a Spyder "issue" and my assumption is right. When I run my script __file__ is working!
comment on: http://stackoverflow.com/q/47802020
type: Comment

http://stackoverflow.com/a/47808067
type: Answer
has comment: http://stackoverflow.com/comment/82577753
has comment: http://stackoverflow.com/comment/82577322
has comment: http://stackoverflow.com/comment/82584954
has comment: http://stackoverflow.com/comment/82583843
upvote count: 2
score: 2
has body: Use duplicated with boolean indexing, last remove # by position with str[1:] or by str.strip: print (df) a 0 #1 1 #2 2 #2 3 #3 4 #3 5 #3 6 #3 7 #4 8 #4 9 #5 df = df.loc[df['a'].duplicated(), 'a'].str[1:] print (df) 2 2 4 3 5 3 6 3 8 4 Name: a, dtype: object Or: df = df.loc[df['a'].duplicated(), 'a'].str.strip('#') print (df) 2 2 4 3 5 3 6 3 8 4 Name: a, dtype: object Detail: print (df['a'].duplicated()) 0 False 1 False 2 True 3 False 4 True 5 True 6 True 7 False 8 True 9 False Name: a, dtype: bool EDIT: df = df[df['a'].duplicated()] df['a'] = df['a'].str.strip('#')
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47808033
answers question: http://stackoverflow.com/q/47808033

http://stackoverflow.com/q/47804542
type: Question
tagged with: tkinter
type: UnansweredQuestion
downvote count: 0
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/47804624
has body: I try to have a tkinter.Frame that have a full screen image and some buttons underneath it WIDTH, HEIGHT = 800, 600 root = Tk() mainframe = Frame(root, padding="3 3 12 12") mainframe.pack(fill=BOTH, expand=True) infovariable = StringVar() infovariable_label = Label(mainframe, textvariable=infovariable, anchor=S) infovariable_label.pack(fill=X, side=TOP) label = Label(mainframe) label.pack(fill=BOTH, expand=True) image_base = Image.open('hello.jpg') # setting the photo image = (image_base .resize(2500, 1000) .crop(0, 0, WIDTH,HEIGHT)) label.configure(image=photo) When I do a window resize, I want my photo to be the same dimensions (width/height), if I do that: def onResize(event): global WIDTH, HEIGHT WIDTH = event.width HEIGHT = max(0, event.height - 50) # setting the photo image = (image_base .resize(2500, 1000) .crop(0, 0, WIDTH,HEIGHT)) root.bind('&lt;Configure&gt;', onResize) The resize, makes the image change size, then call the resize again, having a window that infinitely resizes. I have the same problem as this thread: odd behavior with &#39;&lt;Configure&gt;&#39; callback
has title: Tkinter recursive behavior with '<Configure>' callback
score: 1
linked to: http://stackoverflow.com/q/17226261
answer count: 1
linked to: http://stackoverflow.com/q/2458026
favorite count: 0

http://stackoverflow.com/a/47865063
has comment: http://stackoverflow.com/comment/82695210
has comment: http://stackoverflow.com/comment/82695770
type: Answer
answers question: http://stackoverflow.com/q/47816191
has comment: http://stackoverflow.com/comment/82695125
score: 0
has comment: http://stackoverflow.com/comment/82695178
accepted answer of: http://stackoverflow.com/q/47816191
type: AcceptedAnswer
has body: Here's an example showing how to overrride get_success_url(). You haven't provided implementation of view class, so I've assumed it to be a standard FormView. class OrderFormView(FormView): def form_valid(self, form): # form handling logic super(OrderFormView, self).form_valid(form) def get_success_url(self): clientcode = self.kwargs['clientcode'] url = '/' + clientcode + '/dashboard/' return url You can refer to Django docs for details.

http://stackoverflow.com/comment/82396330
type: QuestionComment
score: 0
has text: @scharette Speed is very important. my program gives a result in about 4-6 seconds.. sometimes 3 but i need it to be under 2 (a similar code runs in 1 second written in C#. I haven't checked its code though. but the result is the same. I want to believe Python can be as fast. I will keep your suggestion in mind and might convert all similar statements with sets. Thank you! **ScottHunter I am kind of new.. I have been reading on how to test my program since last night. I will do so once i figure the best (and simplest) way in Python3
comment on: http://stackoverflow.com/q/47717159
type: Comment

http://stackoverflow.com/q/47766364
has title: Debugging c++ code behind python
accepted answer: http://stackoverflow.com/a/47767340
tagged with: python
has answer: http://stackoverflow.com/a/47766436
tagged with: c++
type: AnsweredQuestion
tagged with: python-2.7
answer count: 2
has answer: http://stackoverflow.com/a/47767340
downvote count: 0
tagged with: gdb
upvote count: 1
score: 1
possible better answer: http://stackoverflow.com/a/47766436
has body: I am trying to debug C++ code behind python for this library (faster rcnn). I followed the instruction here. Say I like to stop a break point at solver.cpp and line 188. gdb -ex r --args python ./tools/train_faster_rcnn_alt_opt.py --gpu 0 --net_name headhand --weights data/imagenet_models/VGG_CNN_M_1024.v2.caffemodel --imdb headhand_train --cfg experiments/cfgs/config.yml I press Ctrl + c then gdb python 8504 break solver.cpp:188 then type c and enter But never break at solver.cpp. How can I debug?
favorite count: 0
type: Question

google-api
tags question: http://stackoverflow.com/q/47705344
tags question: http://stackoverflow.com/q/47830305
tag name: google-api
tags question: http://stackoverflow.com/q/47758790
tags question: http://stackoverflow.com/q/47838831
tags question: http://stackoverflow.com/q/47782592
tags question: http://stackoverflow.com/q/47841565
tags question: http://stackoverflow.com/q/47851487
type: Tag
tags question: http://stackoverflow.com/q/47763808

http://stackoverflow.com/comment/82527284
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47782780
has text: What do you get when you do: `print(os.path.abspath(__file__))` instead?

http://stackoverflow.com/comment/82427252
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47733345
score: 2
has text: Please post your code in the question itself as *formatted text*

http://stackoverflow.com/a/47723605
has body: Your answer is very broad and needs more explanation. It is also likely that it has been answered in other posts on StackOverflow. A very basic answer to your question: to_print = [1, 5, 10, 1000] with open('input_file.csv', 'r') as fr: with open('write_here.csv', 'w') as fw: for i, row in enumerate(fr): if i in to_print: fw.write(row) This simply writes every line that you specify in to_print to another csv file. If you want to print every fifth line between 0 and 1000, you can consider setting to_print = range(0, 1000, 5) or, if you don't know the number of lines of your file: with open('input_file.csv', 'r') as fr: with open('write_here.csv', 'w') as fw: for i, row in enumerate(fr): if i % 5 == 0: fw.write(row)
has comment: http://stackoverflow.com/comment/82420887
has comment: http://stackoverflow.com/comment/82408860
type: Answer
score: 0
answers question: http://stackoverflow.com/q/47723508

aix
type: Tag
tag name: aix
tags question: http://stackoverflow.com/q/47764837

http://stackoverflow.com/comment/82510652
score: 1
type: Comment
type: QuestionComment
has text: In addition, it should be `self.frame.pack()` not `frame.pack()` in `__init__`
comment on: http://stackoverflow.com/q/47774809

http://stackoverflow.com/q/47811469
has answer: http://stackoverflow.com/a/47820438
type: AnsweredQuestion
score: 1
upvote count: 1
has body: I have a custom type in application using the SQLAlchemy ORM mapper. For some complex queries I need to use the SQL expression module, but this makes handling of the custom types non-transparent. How can I tell SQLAlchemy to use my custom types for mapping when not using the ORM? Below is a quick example demonstrating the problem. Note that the first query works, but I have to manually cast it first to str in Python and next to INET for PostgreSQL even though I have my custom type defined. I understand that the SQL expression module is unaware of the custom type as it is defined one layer above it in the ORM. But I wonder if there is no way I could wire that custom type somehow into the SQL layer making usage of types and values much more transparent. And additionally ensuring that any operation (clean-ups and so on) defined in the custom type are consistently applied no matter what layer of SA is being used. from sqlalchemy.orm import sessionmaker from sqlalchemy.sql.expression import any_ from sqlalchemy.types import TypeDecorator Base = declarative_base() class PgIpInterface(TypeDecorator): """ A codec for :py:mod:`ipaddress` interfaces. """ impl = INET def process_bind_param(self, value, dialect): return str(value) if value else None def process_result_value(self, value, dialect): return ip_interface(value) if value else None def process_literal_param(self, value, dialect): raise NotImplementedError('Not yet implemented') class Network(Base): __tablename__ = 'example_table' cidr = Column(PgIpInterface, primary_key=True) def execute(query): import logging LOG = logging.getLogger() try: print(query) print(query.all()) except: LOG.exception('!!! failed') engine = create_engine('postgresql://malbert@/malbert') Base.metadata.create_all(engine) Session = sessionmaker(bind=engine) session = Session() ranges = [ ip_interface('192.168.1.0/24'), ip_interface('192.168.3.0/24'), ] # Query with manual casting print(' Manual Casting via "str" '.center(80, '-')) arr = array([c…
tagged with: sqlalchemy
favorite count: 0
accepted answer: http://stackoverflow.com/a/47820438
type: Question
downvote count: 0
answer count: 1
tagged with: python
has title: How can I adapt custom types in SQL Expression statements?

http://stackoverflow.com/a/47832486
has comment: http://stackoverflow.com/comment/82628143
score: 5
has comment: http://stackoverflow.com/comment/82627848
upvote count: 6
type: Answer
has comment: http://stackoverflow.com/comment/82629071
downvote count: 1
has comment: http://stackoverflow.com/comment/82628210
has body: Okay, IIUC, use string.punctuation and perform replacement with replace - import string data1.replace(r'[{}]'.format(string.punctuation), '', regex=True) 0 0 привет Вася 1 как дела 2 уиии Where, string.punctuation '!"#$%&amp;\'()*+,-./:;&lt;=&gt;?@[\\]^_`{|}~' If you want to exclude a particular character / set of chars, here's one way to do it, using set.difference - c = set(string.punctuation) p_to_exclude = ['?', ...] c = c.difference(p_to_exclude) Now, you can use c as before - data1.replace(r'[{}]'.format(re.escape(''.join(c))), '', regex=True) 0 0 привет Вася 1 как дела? 2 уиии Another thing here is to use re.escape, because [ and ] are considered metacharacters, and need to be escaped.
has comment: http://stackoverflow.com/comment/82628097
answers question: http://stackoverflow.com/q/47832354

http://stackoverflow.com/comment/82606022
comment on: http://stackoverflow.com/a/47820174
score: 0
type: Comment
has text: so sorry i think I have mistaken dataframe for series, since I wanted the columns to "merge" into only one column, which means its really a series rather than a dataframe.
type: AnswerComment

http://stackoverflow.com/q/47773827
tagged with: optimization
has answer: http://stackoverflow.com/a/47944769
has comment: http://stackoverflow.com/comment/82857787
has body: I am new in python. I have one script with many functions. so it was taking about 10 seconds to finish. To improve speed, I have divided one script into two (so now I have two scripts with independent functions) independent scripts. I am importing one script from another. so it can work simultaneously. but in doing so the behaviour of the logger is completely changed. it supposes to be creating and writing in the new log file (every time I run the script). but now it is writing also in previous log files. so my guess is that my logger configurations are not working in both scripts simultaneously. because of that threading is also running slow. can anyone please check out my code and help me to find mistakes in it?? script_1.py script_path = os.path.dirname(os.path.realpath(sys.argv[0])) dat = str(datetime.datetime.now().strftime('%Y_%m_%d_%H_%M_%S')) logger = logging.getLogger("main_script") logger.setLevel(logging.INFO) fh = logging.FileHandler(script_path + '\\..\\main_script_' + dat".log") logger_file_path = script_path + '\\..\\main_script_' + dat + ".log" formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') fh.setFormatter(formatter) logger.addHandler(fh) def CloseLogger(): """CloseLogger function closes the logger """ handler = logger.handlers[:] for i in handler: i.flush() i.close() logger.removeHandler(i) #other independent functions if__name__== "__main__": main_1() script_2.py from threading import Thread from script_1 import * run_script1 = Thread(target = main_1) run_script1.start() logger = logging.getLogger('main_script.script_2') # second part of original script #other independent functions if__name__== "__main__": run_script2 = Thread(target = main_2) run_script2.start() run_script2.join() run_script2.join() I think either I am doing mistakes in threading or in logger configuration. please help me to find my mistakes. if you need more information please let me know. thank you enter image description here
has comment: http://stackoverflow.com/comment/82515551
has comment: http://stackoverflow.com/comment/82858163
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82516710
has comment: http://stackoverflow.com/comment/82515469
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82858082
type: Question
has comment: http://stackoverflow.com/comment/82516788
score: 0
tagged with: multithreading
has comment: http://stackoverflow.com/comment/82514952
tagged with: python
accepted answer: http://stackoverflow.com/a/47944769
answer count: 1
has title: how to do logging in one file from 2 script which are executing simultaneously?
tagged with: logging

http://stackoverflow.com/a/47778106
accepted answer of: http://stackoverflow.com/q/47776318
type: Answer
answers question: http://stackoverflow.com/q/47776318
downvote count: 0
score: 7
upvote count: 7
has comment: http://stackoverflow.com/comment/82540692
type: AcceptedAnswer
has body: Using a colormap In principle the matrix with RGB values is some kind of colormap. It makes sense to use a colormap in matplotlib to get the colors for a plot. What makes this a little more complicated here is that the values are not well spaced. So one idea would be to map them to integers starting at 0 first. Then creating a colormap from those values and using it with a BoundaryNorm allows to have a equidistant colorbar. Finally one may set the ticklabels of the colorbar back to the initial values. import numpy as np import matplotlib.pyplot as plt import matplotlib.colors a =np.array([[156, 138, 156], [1300, 137, 156], [138, 138, 1300], [137, 137, 137]]) ca = np.array([[156,200,200,200], [138,170,255,245], [137,208,130,40], [1300,63,165,76]]) u, ind = np.unique(a, return_inverse=True) b = ind.reshape((a.shape)) colors = ca[ca[:,0].argsort()][:,1:]/255. cmap = matplotlib.colors.ListedColormap(colors) norm = matplotlib.colors.BoundaryNorm(np.arange(len(ca)+1)-0.5, len(ca)) plt.imshow(b, cmap=cmap, norm=norm) cb = plt.colorbar(ticks=np.arange(len(ca))) cb.ax.set_yticklabels(np.unique(ca[:,0])) plt.show() Plotting RGB array You may create an RGB array from your data to directly plot as imshow. To this end you may index the original array with the colors from the color array and reshape the resulting array such that it is in the correct shape to be plotted with imshow. import numpy as np import matplotlib.pyplot as plt a =np.array([[156, 138, 156], [1300, 137, 156], [138, 138, 1300], [137, 137, 137]]) ca = np.array([[156,200,200,200], [138,170,255,245], [137,208,130,40], [1300,63,165,76]]) u, ind = np.unique(a, return_inverse=True) c = ca[ca[:,0].argsort()][:,1:]/255. b = np.moveaxis(c[ind][:,:,np.newaxis],1,2).reshape((a.shape[0],a.shape[1],3)) plt.imshow(b) plt.show() The result is the same as above, but without colorbar (as there is no quantity to map here).
has comment: http://stackoverflow.com/comment/82542061

http://stackoverflow.com/q/47845126
has body: class Project(models.Model): project_name = models.CharField(max_length=100,default=None) user = models.ForeignKey(User, on_delete=models.CASCADE) intro = models.TextField(default=None) start_date = models.DateField() end_date = models.DateField() def __str__(self): return self.project_name class UserResource(ModelResource): class Meta: class ProjectResource(ModelResource): user = fields.ToManyField(UserResource, 'user', full=True) class Meta: queryset = Project.objects.all() resource_name = 'project' allowed_methods = ['post', 'get'] authorization = DjangoAuthorization() Newbie in tastypie, When i follow the documents i get attribute error on api url (api/project/) dont know the meaning of query_terms, tried searching , thanks in advance File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.5/dist-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/usr/local/lib/python3.5/dist-packages/tastypie/resources.py", line 221, in wrapper response = callback(request, *args, **kwargs) File "/usr/local/lib/python3.5/dist-packages/tastypie/resources.py", line 461, in dispatch_list return self.dispatch('list', request, **kwargs) File "/usr/local/lib/python3.5/dist-packages/tastypie/resources.py", line 493, in dispatch response = method(request, **kwargs) File "/usr/local/lib/python3.5/dist-packages/tastypie/resources.py", line 1348, in get_list objects = self.obj_get_list(bundle=base_bundle, **self.remove_api_resource_names(kwargs)) File "/usr/local/lib/python3.5/dist-packages/tastypie…
has comment: http://stackoverflow.com/comment/82664091
favorite count: 0
type: Question
score: 3
has title: AttributeError at /api/project/ 'Query' object has no attribute 'query_terms' tastypie
type: UnansweredQuestion
tagged with: django
tagged with: python
tagged with: tastypie
has comment: http://stackoverflow.com/comment/82682004
upvote count: 3
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/48937201

http://stackoverflow.com/comment/82527003
type: Comment
comment on: http://stackoverflow.com/a/47765287
score: 0
has text: I updated my answer to show how to create a tuple of tuples.
type: AnswerComment

http://stackoverflow.com/a/47706725
downvote count: 0
has comment: http://stackoverflow.com/comment/82374568
has comment: http://stackoverflow.com/comment/82389600
has body: The key will be the filename you want to download for example http://s3.amazonaws.com/goat-bucket/farms/andys/goat.png bucket: goat-bucket key: farms/andys/goat.png If you don't know the object name, you can list out the object names of goat bucket like so: import boto3 s3 = boto3.resource('s3') bucket = s3.Bucket('goat-bucket') # Using the bucket name above for object in bucket.objects.all(): print('Bucket name: ' + object.bucket_name) print('Object key: ' + object.key) Would output: Bucket name: goat-bucket Object key: farms/andys/goat.png
answers question: http://stackoverflow.com/q/47706693
upvote count: 2
has comment: http://stackoverflow.com/comment/82373614
accepted answer of: http://stackoverflow.com/q/47706693
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/82373571
has comment: http://stackoverflow.com/comment/82373657
has comment: http://stackoverflow.com/comment/82373644
score: 2

http://stackoverflow.com/q/47759577
favorite count: 0
type: Question
tagged with: numpy
accepted answer: http://stackoverflow.com/a/47762586
possible better answer: http://stackoverflow.com/a/47763145
linked to: http://stackoverflow.com/q/42339786
has answer: http://stackoverflow.com/a/47762586
has title: Creating a mixture of probability distributions for sampling
has answer: http://stackoverflow.com/a/79515380
has answer: http://stackoverflow.com/a/51165543
has answer: http://stackoverflow.com/a/47763145
score: 18
tagged with: python
answer count: 6
upvote count: 18
has comment: http://stackoverflow.com/comment/82480619
has answer: http://stackoverflow.com/a/72315113
has answer: http://stackoverflow.com/a/79161432
type: AnsweredQuestion
has body: Is there a general way to join SciPy (or NumPy) probability distributions to create a mixture probability distribution which can then be sampled from? I have such a distribution for display using something like: mixture_gaussian = (norm.pdf(x_axis, -3, 1) + norm.pdf(x_axis, 3, 1)) / 2 which if then plotted looks like: However, I can't sample from this generated model, as it's just a list of points which will plot as the curve. Note, this specific distribution is just a simple example. I'd like to be able to generate several kinds of distributions (including "sub"-distributions which are not just normal distributions). Ideally, I would hope there would be someway for the function to be automatically normalized (i.e. not having to do the / 2 explicitly as in the code above. Does SciPy/NumPy provide some way of easily accomplishing this? This answer provides a way that such a sampling from a multiple distributions could be done, but it certainly requires a bit of handcrafting for a given mixture distribution, especially when wanting to weight different "sub"-distributions differently. This is usable, but I would hope for method that's a bit cleaner and straight forward if possible. Thanks!
linked to: http://stackoverflow.com/q/42552117
downvote count: 0
tagged with: scipy
tagged with: probability-density

http://stackoverflow.com/a/47794851
downvote count: 0
answers question: http://stackoverflow.com/q/47794752
upvote count: 5
type: Answer
has body: You should to use parameters to avoid sql injection: for item in changes: sql_command = """INSERT INTO changes (short_description) VALUES (?);""" cursor.execute(sql_command, (item.short_description,) ) cursor.commit()
accepted answer of: http://stackoverflow.com/q/47794752
score: 5
has comment: http://stackoverflow.com/comment/126164527
type: AcceptedAnswer

http://stackoverflow.com/comment/82600854
type: Comment
has text: Sorry, I got the code the wrong way round in my example before the edit, but now it's fixed
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47819235

http://stackoverflow.com/q/47750068
upvote count: 2
type: AnsweredQuestion
score: 2
has answer: http://stackoverflow.com/a/47750114
has body: I have a table looked like below: id price 1 10 1 10 1 10 2 30 2 33 2 30 3 15 3 15 3 15 How can I determine the number of ids that has the same price(such that their price stays constant) throughout the table? In the table above, the answer will be 2, for id=1 and id=3
downvote count: 0
tagged with: pandas
answer count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47750114
tagged with: python
has title: Find the amount of ID that has same price in entire table

http://stackoverflow.com/q/47819197
downvote count: 0
tagged with: python
has title: Additive color with Tkinter
type: AnsweredQuestion
score: 2
tagged with: python-2.7
answer count: 3
accepted answer: http://stackoverflow.com/a/47822061
has body: I'm trying to reproduce additive color with Tkinter. My function : def synthese(red,green,blue): win2 = Tk() win2.title("ADDITIVE COLOR") win2.geometry("500x500") win2.resizable(0,0) hred = "#%02x%02x%02x" % (red, 0, 0) #RGB to Hexadecimal hgreen = "#%02x%02x%02x" % (0, green, 0) hblue = "#%02x%02x%02x" % (0, 0, blue) r = 50 Width = 450 Height = 450 win3 = Canvas(win2, width = Width, height = Height, bg = 'white') win3.pack(padx=5,pady=5) win3.create_oval(10,150,300,440, outline=hred, fill=hred) win3.create_oval(150,150,440,440, outline=hblue, fill=hblue) win3.create_oval(75,10,375,300, outline=hgreen, fill=hgreen) win2.mainloop() What I get : And what I would like : It is possible to merge the colors or I need to find the collision zones?
has answer: http://stackoverflow.com/a/47822061
possible better answer: http://stackoverflow.com/a/47821915
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47821915
tagged with: tkinter
tagged with: canvas
upvote count: 2
has comment: http://stackoverflow.com/comment/82600717
has answer: http://stackoverflow.com/a/47822088

http://stackoverflow.com/q/47767055
has comment: http://stackoverflow.com/comment/82495214
tagged with: macos
has body: I have python libraries in the following folders on my mac /usr/local/lib/python2.7/site-packages/ /usr/local/lib/python3.6/site-packages/ and, the corresponding binaries as the following files /usr/local/bin/python2.7 /usr/local/bin/python3.6 But, the ipython binary is in /usr/local/Cellar/ipython/6.2.1/bin/ipython and the ipython file /usr/local/bin/ipython has the following line in it - PYTHONPATH="/usr/local/Cellar/ipython/6.2.1/libexec/lib/python3.6/site-packages:/usr/local/Cellar/ipython/6.2.1/libexec/vendor/lib/python3.6/site-packages" exec "/usr/local/Cellar/ipython/6.2.1/libexec/bin/ipython" "$@" Therefore, on executing ipython in the terminal the default interpreter is taken as python3.6 by the system. How can I modify these files to change the python interpreter from 3.6 to 2.7? Following is a screenshot of all the ipython* files in my mac.
type: Question
tagged with: python-3.x
has title: How to change the python interpreter for ipython on mac?
has comment: http://stackoverflow.com/comment/82495167
accepted answer: http://stackoverflow.com/a/47767824
answer count: 1
tagged with: python
tagged with: macos-sierra
type: AnsweredQuestion
tagged with: python-2.7
score: 0
has answer: http://stackoverflow.com/a/47767824

http://stackoverflow.com/comment/82651063
score: 0
type: AnswerComment
has text: ??? Yeah he said he wants to sort by the second value of the list... to get the original output (i.e. sorted by first value): sorted(listo, key= lambda num: num[0])
type: Comment
comment on: http://stackoverflow.com/a/47843563

http://stackoverflow.com/comment/82605644
has text: @Marmaduke I can't reproduce that. When I comment-out the line, the profiler skips it.
type: Comment
comment on: http://stackoverflow.com/a/47819826
score: 0
type: AnswerComment

http://stackoverflow.com/a/47764473
has comment: http://stackoverflow.com/comment/82490748
answers question: http://stackoverflow.com/q/47761274
upvote count: 2
has body: You can use Popen from the subprocess module. Here's a simple example, first script to prompt for input and return some output, test_input.py: first = input("Enter your first name: ") second = input("Enter your second name: ") print(first+second) Then the script to call the first script: import subprocess values = (("A", "B"), ("C", "D"), ("E", "F")) command = "python test_input.py" for first, second in values: # lazy use of universal_newlines to prevent the need for encoding/decoding p = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True, universal_newlines=True) output, err = p.communicate(input="{}\n{}\n".format(first, second)) # stderr is not connected to a pipe, so err is None print(first, second, "-&gt;", end="") # we just want the result of the command print(output[output.rfind(" "):-1]) # -1 to strip the final newline This will print: A B -&gt; AB C D -&gt; CD E F -&gt; EF If you have problems getting it working with your java program, a quick solution may be to specify shell=True in the Popen function call. But you'll want to be aware of the security considerations.
downvote count: 0
score: 2
type: Answer

http://stackoverflow.com/q/47788361
has comment: http://stackoverflow.com/comment/82537784
answer count: 6
possible better answer: http://stackoverflow.com/a/47788483
score: 19
upvote count: 19
has body: This question is motivated by an answer I gave a while ago. Let's say I have a dataframe like this import numpy as np import pandas as pd df = pd.DataFrame({'a': [1, 2, np.nan], 'b': [3, np.nan, 10], 'c':[np.nan, 5, 34]}) a b c 0 1.0 3.0 NaN 1 2.0 NaN 5.0 2 NaN 10.0 34.0 and I want to replace the NaN by the maximum of the row, I can do df.apply(lambda row: row.fillna(row.max()), axis=1) which gives me the desired output a b c 0 1.0 3.0 3.0 1 2.0 5.0 5.0 2 34.0 10.0 34.0 When I, however, use df.apply(lambda row: row.fillna(max(row)), axis=1) for some reason it is replaced correctly only in two of three cases: a b c 0 1.0 3.0 3.0 1 2.0 5.0 5.0 2 NaN 10.0 34.0 Indeed, if I check by hand max(df.iloc[0, :]) max(df.iloc[1, :]) max(df.iloc[2, :]) Then it prints 3.0 5.0 nan When doing df.iloc[0, :].max() df.iloc[1, :].max() df.iloc[2, :].max() it prints the expected 3.0 5.0 34.0 My question is why max() fails in 1 of three cases but not in all 3. Why are the NaN sometimes ignored and sometimes not?
has comment: http://stackoverflow.com/comment/82537876
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/73968305
downvote count: 0
linked to: http://stackoverflow.com/q/31706700
tagged with: pandas
has title: Why does max() sometimes return nan and sometimes ignores it?
has answer: http://stackoverflow.com/a/47788537
tagged with: python
has answer: http://stackoverflow.com/a/47788524
has comment: http://stackoverflow.com/comment/128592098
accepted answer: http://stackoverflow.com/a/47788524
favorite count: 0
has answer: http://stackoverflow.com/a/47788483
tagged with: replace
type: Question
has answer: http://stackoverflow.com/a/47788507
has answer: http://stackoverflow.com/a/78270360
tagged with: missing-data

http://stackoverflow.com/comment/82593730
type: Comment
comment on: http://stackoverflow.com/q/47813386
type: QuestionComment
has text: `test = driver.find_elements_by_xpath(".//span[@class='ws-value']")` will return the Node. What are you trying to print exactly? **84**, **69** ?
score: 0

http://stackoverflow.com/a/47731041
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: Am I doing something wrong here? Do not panic, many users do the very same - Paid more than received. This is a common lecture not on using some "promising" syntax-constructor, but on paying the actual costs for using it. The story is long, the effect was straightforward - you expected a low hanging fruit, but had to pay an immense cost of process-instantiation, work-package re-distribution and for collection of results, all that circus just for doing but a few rounds of func()-calls. Wow? Stop! Parallelisation was brought to me that will SPEEDUP processing?!? Well, who told you that any such ( potential ) speedup is for free? Let's be quantitative and instead measure the actual code-execution time. Benchmarking is always a fair move. It helps us to escape from just expectations and get ourselves into quantitative evidence-supported knowledge: from zmq import Stopwatch; aClk = Stopwatch() # this is a handy tool to do so AS-IS test: Before moving forwards, one ought record this pair: >>> aClk.start(); _ = [ func( SEQi ) for SEQi in inp ]; aClk.stop() # [SEQ] >>> HowMuchWillWePAY2RUN( func, 4, 100 ) # [RUN] >>> HowMuchWillWePAY2MAP( func, 4, 100 ) # [MAP] This will set the span among the performance envelopes from a pure-[SERIAL] [SEQ]-of-calls, to an un-optimised joblib.Parallel() or any other, if one wishes to extend the experiment with any other tools, like a said multiprocessing.Pool() or other. Test-case A: Intent: so as to measure the cost of a { process | job }-instantiation, we need a NOP-work-package payload, that will spend almost nothing "there" but return "back" and will not require to pay any additional add-on costs ( be it for any input parameters' transmissions or returning any value ) def a_NOP_FUN( aNeverConsumedPAR ): """ __doc__ The intent of this FUN() is indeed to do nothing at all, so as to be able to benchmark all the process-instantiation add-on overhead costs. """ pass So, the setup-overhead add-on costs comparison is here: #------------------…
accepted answer of: http://stackoverflow.com/q/47728862
type: Answer
answers question: http://stackoverflow.com/q/47728862
score: 1

http://stackoverflow.com/a/47841636
downvote count: 0
has comment: http://stackoverflow.com/comment/82647468
upvote count: 3
score: 3
type: Answer
has body: This is possible if you make your class inherit from dict class PropDict(dict): __getattr__= dict.__getitem__ __setattr__= dict.__setitem__ __delattr__= dict.__delitem__
answers question: http://stackoverflow.com/q/47841598

http://stackoverflow.com/q/47849791
type: Question
accepted answer: http://stackoverflow.com/a/47850062
has comment: http://stackoverflow.com/comment/82664079
has answer: http://stackoverflow.com/a/47850062
has comment: http://stackoverflow.com/comment/82664095
has body: Lately, I was presented with a challenge exercise, aiming to create a program which checks the length of a password and then assesses it strength based on it being mixed case and containing numbers. The part which determines whether the length of the password is suitable works absolutely fine, however the rest of the program seems to not work. I am unsure whether this is a logical or syntax error of some sort. I hope you can help me in some way. import re #score variable, responsible for later defining if passwords is weak, medium or strong Score = 0 Password = "" #inputs password Password = input("Please enter a password:") Password_length = len(Password) #checks password length (6-12), asks user to re-input until password is within boundaries while Password_length &lt; 6 or Password_length &gt; 12: if Password_length &lt; 6: Outputted_length = "too short" Outputted_criteria = "no shorter than 6 characters" else: Outputted_length = "too long" Outputted_criteria = "no longer than 12 characters" print("Your password is", Outputted_length, ". It has to be", Outputted_criteria, ".") Password = input("Please enter a password:") Password_length = len(Password) else: #defines function for checking for presence of numbers in password def hasNumbers(s): return any(i.isdigit() for i in s) #checks if password is all upper case Is_upper = Password.isupper() if Is_upper == "True": Score = Score - 1 else: Score = Score + 1 #checks if passwords is all lower case Is_lower = Password.islower() if Is_lower == "False": Score = Score - 1 else: Score = Score + 1 #checks if password contains a number Number_presence = hasNumbers(Password) if Number_presence == "True": Score = Score + 1 else: Score = Score - 1 #checks if password is just numbers Only_numbers = Password.isdigit() if Only_numbers == "True": Score = Score - 1 #outputs weak, medium or strong to user based on score value if Score &lt;= 0: print("Your password is absolutely rubbish!") if Score == 1: print("Your password is wea…
tagged with: python
has comment: http://stackoverflow.com/comment/82664100
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/82664119
answer count: 1
upvote count: 1
has title: Python: Problems with final result of password strength program
has comment: http://stackoverflow.com/comment/82664344
downvote count: 1
favorite count: 0

http://stackoverflow.com/comment/82583627
has text: thanks! could you pls reffer to my 3rd question as well as df.drop(columns=['empty']) not working for me
type: AnswerComment
comment on: http://stackoverflow.com/a/47809582
score: 0
type: Comment

http://stackoverflow.com/q/47825900
has answer: http://stackoverflow.com/a/47826089
has title: Where can I write the after query logic in RetrieveAPIView?
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/82614433
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82614340
score: 0
has body: Where can I write the after query logic in RetrieveAPIView? In my models.py I have a Message class: class Message(models.Model): """ message """ message_num = models.CharField(default=getMessageNum, max_length=16) title = models.CharField(max_length=64) content = models.CharField(max_length=1024) is_read = models.DateTimeField(null=True, blank=True) create_user = models.ForeignKey(User, related_name="created_messages") receive_user = models.ManyToManyField(User, related_name="received_messages") ctime = models.DateTimeField(auto_now_add=True) uptime = models.DateTimeField(auto_now=True) def __str__(self): return self.title In the views.py: # the message list class UserMessageListAPIView(ListAPIView): serializer_class = UserMessageSerializer permission_classes = [] def get_queryset(self): user = self.request.user messages = user.received_messages.all() return messages # the message detail class UserMessageRetrieveAPIView(RetrieveAPIView): serializer_class = UserMessageSerializer permission_classes = [] def get_queryset(self): user = self.request.user messages = user.received_messages.all() return messages You see, in the UserMessageRetrieveAPIView I can retrieve the message instance. How can I do the logic to set the message's is_read ? Where I can set it? EDIT I mean, if its possible, I want to get the retrieved message, then updated it, but I don't know how to get it.
has comment: http://stackoverflow.com/comment/82614416
answer count: 1
tagged with: django-rest-framework
has comment: http://stackoverflow.com/comment/82614315
has comment: http://stackoverflow.com/comment/82614289
type: Question
has comment: http://stackoverflow.com/comment/82614361
accepted answer: http://stackoverflow.com/a/47826089

mendeley
tags question: http://stackoverflow.com/q/47777288
tag name: mendeley
type: Tag

http://stackoverflow.com/comment/82385198
has text: didn't know that (+1)...!
score: 1
comment on: http://stackoverflow.com/a/47707516
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47707528
has body: In Pandas, I can use .apply to apply functions to two columns. For example, df = pd.DataFrame({'A':['a', 'a', 'a', 'b'], 'B':[3, 3, 2, 5], 'C':[2, 2, 2, 8]}) formula = lambda x: (x.B + x.C)**2 df.apply(formula, axis=1) But, notice that results on the first two rows are the same since all the inputs are the same. In large dataset with complicated operations. These repeated calculations is likely to slow down my program. Is there a way that I can program it so that I can save time with these repeated calculations?
upvote count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47707607
downvote count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/82375252
favorite count: 0
has title: Save repeated calculations in Python Pandas
has answer: http://stackoverflow.com/a/47707580
tagged with: pandas
has comment: http://stackoverflow.com/comment/82375310
linked to: http://stackoverflow.com/q/32568012
type: Question
score: 2
answer count: 2

http://stackoverflow.com/comment/82390812
type: QuestionComment
comment on: http://stackoverflow.com/q/47715289
has text: Try capturing the random float value before the if condition in a variable `rand1=random.random() if random.random() < reproductionProb:`
score: 0
type: Comment

http://stackoverflow.com/q/47827795
has comment: http://stackoverflow.com/comment/82618013
has answer: http://stackoverflow.com/a/49520944
type: UnansweredQuestion
has body: Help, I used zendesk api v2 python to static zendesk ticket and compare with zendesk custom report but have different result. custom start December 14, 2017 end December 15, 2017 but have two different results: custom 161 new ticket but api code return 84 ticket only. I try other different custom report, and have similar issues What is wrong with my case? Thanks for help r = requests.get('https://mydomain.zendesk.com/api/v2/search.json?query=type:ticket%20created%3E2017-12-14T00:00:00Z%20created%3C2017-12-15T00:00:00Z&amp;page=1&amp;sort_by=created_at&amp;sort_order=desc',auth=('myauth', 'mypass')) print json.dumps(r.json(), sort_keys=True, indent=10)
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/82617865
tagged with: zendesk
score: 1
downvote count: 0
answer count: 1
tagged with: zendesk-api
has title: Zendesk api v2 python to static zendesk ticket
favorite count: 0
type: Question

http://stackoverflow.com/a/47725519
score: 1
answers question: http://stackoverflow.com/q/47724525
has body: You have two options : first option: use ordered dict: As suggested by @user1767754 : from collections import OrderedDict nodes = ['Unix', 'BSD', 'Linux'] uniques = OrderedDict((x, True) for x in nodes).keys() Second method keep track of index and values: so first create a dict with index,values : nodes = ['Unix', 'BSD', 'Linux'] order={} for i,j in enumerate(nodes): order[i]=j print(order) it will give: {0: 'Unix', 1: 'BSD', 2: 'Linux'} Now do your stuff like converting list to set or whatever you want and at last convert again to list something like this: new=[] for i in set(nodes): for k,j in order.items(): if i==j: new.insert(k,j) print(new) Now it will give: ['Unix', 'BSD', 'Linux']
type: Answer
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/82471863
comment on: http://stackoverflow.com/a/47755516
score: 0
type: Comment
has text: Can I get an explanation please as to why my post was downvoted?
type: AnswerComment

http://stackoverflow.com/q/47761882
linked to: http://stackoverflow.com/q/4257394
has body: Just ran into this fun problem but I can't figure it out correctly You have a matrix: | 1 2 3 | | 4 5 6 | | 7 8 9 | and your given two coordinates: (1,1) and (2,2) find the corresponding submatrix: so (1,1) and (2,2) will create |5 6| |8 9| my code: def get_submatrix(matrix, coor): m = len(matrix) #chooses what rows lstart = coor[0][0] lend = coor[1][0] #chooses what columns estart = coor[0][1] eend = coor[1][1] subgrid = [] print('coors: (%s, %s), (%s, %s) ' % (lstart, estart, lend, eend)) #iterate through the matrices for i in range(lstart,lend+1): # print('matrix index: %s' % i) print('matrix: %s' % matrix[i]) row = matrix[i] subgrid.append(row[estart:len(row)]) print('subgrid: %s' % subgrid) return subgrid My code uses len(row) to pull the end of the row. which might work for some cases but not all cases. Any help on crafting the for loop to obtain the submatrix?
has comment: http://stackoverflow.com/comment/82490314
tagged with: logic
score: 0
has title: Python Summation of Submatrix
has comment: http://stackoverflow.com/comment/82485260
tagged with: matrix
tagged with: python
has comment: http://stackoverflow.com/comment/82486744
has comment: http://stackoverflow.com/comment/82486158
type: Question
has comment: http://stackoverflow.com/comment/82485236
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/a/47701447
has comment: http://stackoverflow.com/comment/82363235
accepted answer of: http://stackoverflow.com/q/47699464
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/47699464
has body: We using merge_asof df['Year']=df['date'].dt.year df1['Year']=df1['date'].dt.year A=[] for x in range(len(df)): Temp=pd.merge_asof(df1.sort_values('date'),df.sort_values('date').iloc[[x],:],on='date',by=['Year','season'],direction='forward',allow_exact_matches =False).dropna().drop('Week',1) Temp.binary=np.nan A.append(Temp) A.append(df) target=pd.concat(A).sort_values(['Name','date']) target Out[262]: Name Year binary date season 0 Apple 2016 NaN 2016-03-28 MAM 1 Apple 2016 NaN 2016-04-04 MAM 2 Apple 2016 NaN 2016-04-11 MAM 3 Apple 2016 NaN 2016-04-18 MAM 0 Apple 2016 1.0 2016-04-24 MAM 0 Banana 2016 NaN 2016-03-28 MAM 1 Banana 2016 NaN 2016-04-04 MAM 2 Banana 2016 NaN 2016-04-11 MAM 3 Banana 2016 NaN 2016-04-18 MAM 4 Banana 2016 NaN 2016-04-25 MAM 1 Banana 2016 1.0 2016-05-01 MAM 0 Berry 2016 NaN 2016-03-28 MAM 1 Berry 2016 NaN 2016-04-04 MAM 2 Berry 2016 NaN 2016-04-11 MAM 3 Berry 2016 NaN 2016-04-18 MAM 4 Berry 2016 NaN 2016-04-25 MAM 2 Berry 2016 1.0 2016-05-01 MAM 47 Berry 2017 NaN 2017-10-02 OND 48 Berry 2017 NaN 2017-10-09 OND 49 Berry 2017 NaN 2017-10-16 OND 50 Berry 2017 NaN 2017-10-23 OND 51 Berry 2017 NaN 2017-10-30 OND 3 Berry 2017 1.0 2017-11-05 OND 20 Kiwi 2017 NaN 2017-03-13 MAM 21 Kiwi 2017 NaN 2017-03-20 MAM 5 Kiwi 2017 1.0 2017-03-27 MAM 12 Orange 2016 NaN 2016-10-03 OND 13 Orange 2016 NaN 2016-10-10 OND 14 Orange 2016 NaN 2016-10-17 OND 15 Orange 2016 NaN 2016-10-24 OND 16 Orange 2016 NaN 2016-10-31 OND 17 Orange 2016 NaN 2016-11-07 OND 18 Orange 2016 NaN 2016-11-14 OND 19 Orange 2016 NaN 2016-11-21 OND 4 Orange 2016 1.0 2016-11-27 OND
upvote count: 1
type: AcceptedAnswer
score: 1
has comment: http://stackoverflow.com/comment/82363288

http://stackoverflow.com/q/47725993
has comment: http://stackoverflow.com/comment/82412654
favorite count: 0
type: Question
upvote count: 2
downvote count: 2
has comment: http://stackoverflow.com/comment/82412637
has answer: http://stackoverflow.com/a/47729843
accepted answer: http://stackoverflow.com/a/47729843
tagged with: django
tagged with: python
tagged with: aws-api-gateway
tagged with: amazon-web-services
has comment: http://stackoverflow.com/comment/82412668
has comment: http://stackoverflow.com/comment/82412608
tagged with: boto
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/82413021
has title: User Authentication for aws using Python
has body: I'm working on a project with Python(3.6) &amp; Django(1.10) in which I'm using aws apis but I'm new to aws and don't know how to authenticate a user. My scenario is: I need to access user's aws resources like projects list, buckets list etc, for that, I need to authenticate the user when making a request to a particular API. How can I do that in python? I'm new to aws.So, please don't mind my question. Update: Here's what i have tried: From views.py: def boto3_with_role(role_arn, session_prefix, external_id, **kwargs): """ Create a partially applied session to assume a role with an external id. A unique session_name will be generated by {session_prefix}_{time} `session` can be passed, otherwise the default sesion will be used see: http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_switch-role-api.html """ sts = boto3.client('sts') res = sts.assume_role( RoleArn=role_arn, RoleSessionName='{}_{}'.format(session_prefix, int(time.time())), ExternalId=external_id, ) creds = res['Credentials'] return partial(boto3.session.Session, aws_access_key_id=creds['AccessKeyId'], aws_secret_access_key=creds['SecretAccessKey'], aws_session_token=creds['SessionToken'] ) class AwsAuthentication(LoginRequiredMixin, CreateView): def post(self, request, *args, **kwargs): AwsSession = boto3_with_role('ARN_LINK_FROM_CUSTOMER', 'MyPrefix', 'EXTERNAL_ID_FROM_CUSTOMER') my_session = AwsSession() client = my_session.resource('s3') for bucket in client.buckets.all(): print(bucket.name) return HttpResponse('Your Bucket is: {}'.format(bucket.name)) Now, it returns: botocore.exceptions.ClientError: An error occurred (InvalidClientTokenId) when calling the AssumeRole operation: The security token included in the request is invalid. Help me, please! Thanks in advance!
has comment: http://stackoverflow.com/comment/82412945
has answer: http://stackoverflow.com/a/54473738
answer count: 3
has comment: http://stackoverflow.com/comment/82412767
has comment: http://stackoverflow.com/comment/82412620
has answer: http://stackoverflow.com/a/47727850
possible better answer: http://stackoverflow.com/a/47727850

http://stackoverflow.com/q/47733601
type: Question
has body: I am making a trivia game; I am still new to python. Where should I place my try and except statements to prevent the user entering a letter and an amount higher than xScore(a or b)? class Question: def __init__(self, question, answera, answerb, answerc, answerd, correct): self.question = question self.answers = [answera, answerb, answerc, answerd] self.correct = correct def ask(self): print(self.question) for n in range(0, 4): print(" ", n + 1, ")", self.answers[n]) answer = int(input("enter your answer &gt;")) return answer == self.correct def right(x): x * 2 return int(x) def questions1(): aScore = 10 print('you are able to wager up to', aScore) bet = int(input('Enter points to wager:')) question1 = Question("What does the NFL stand for?", "National Football League", "National Fun Live", "No Fun League", "Narcs Fuzz and Larp", 1) if question1.ask() == True: print("You are correct") aScore += right(bet) else: print("incorrect") aScore -= bet print('you are able to wager up to', aScore) bet = int(input('Enter points to wager:')) question2 = Question("Who won the superbowl last year (2016)", "Atlanta Falcons", "New England Patriots", "Carolina Panthers", "Toronto Maple Leafs", 2) if question2.ask() == True: print("You are correct") aScore += right(bet) else: print("incorrect") aScore -= bet
type: UnansweredQuestion
tagged with: python
answer count: 1
duplicate of: http://stackoverflow.com/q/23294658
has title: Where to put try and except statement to prevent user entering: a letter and above given amount?
linked to: http://stackoverflow.com/q/23294658
score: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47733749

http://stackoverflow.com/a/47803657
upvote count: 1
downvote count: 0
score: 1
type: Answer
has body: Have you tried: cursor = conn.cursor() for entry in entries: cursor.execute(UPDATE_QUERY.format(entry.field1, entry.field2)) cursor.close() You can profile this code with https://docs.python.org/3/library/profile.html
answers question: http://stackoverflow.com/q/47803623
has comment: http://stackoverflow.com/comment/82753626

http://stackoverflow.com/comment/82392759
type: Comment
has text: Oh, I think I have noticed what's wrong. `await update_ocr_task()` is concurrent with other coroutines such as `await task_manager.async_get_task_status(session, task)`, but not itself. `gather` makes all `update_ocr_task` concurrent. That is the point. BTW, the reason why I wrap the whole loop into a function is that I want to run async event loop in a separate thread/process as my main thread is a sync task.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47714212

http://stackoverflow.com/q/47833840
has comment: http://stackoverflow.com/comment/82630786
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47834100
tagged with: format
has answer: http://stackoverflow.com/a/47834100
has comment: http://stackoverflow.com/comment/82691226
tagged with: python
score: -2
has title: Python text file formatting
type: AnsweredQuestion
has body: I need to do some text file formatting using Python. I have data from serial port, all in one file, one character after another. I know how to find and replace text in the file, but I need to do something like this: Find string int file, (there will be many strings in the file, don't know how many) Set add a space (or another character) after this string. I can't find how to manipulate cursor position in file. How to get the position of string found in a file? For example, data in a file is like this: (this is basically hex data from serial port, but converted to string before saving to file. So in the file this data is just text. There could also be something like "Hello world" inside. How to convert this: 00000001030001000151CD0203000100015D1E00000406001000545E5C00000001030001000151CD0203000100015D1E00000406001000545E5C00000001030001000151CD0203000100015D1E00000406001000545E5C00000001030001000151CD0203000100015D1E00000406001000545E5C00000001030001000151CD0203000100015D1E00000406001000545E5C00000001030001000151CD0203000100015D1E00000406001000545E5C00000001030001000151CD0203000100015D1E00000406001000545E5C00000001030001000151CD0203000100015D1E00000406001000545E5C I would like to find parts starting from "0103" (it is device address), then put "\n" before "0103", then after four following characters put another space and text "this was device number one": into this: 000000 0103"this was device number one"0001000151CD0203000100015D1E00000406001000545E5C000000 0103"this was device number one"0001000151CD0203000100015D1E00000406001000545E5C000000 0103"this was device number one"0001000151CD0203000100015D1E00000406001000545E5C000000 0103"this was device number one"0001000151CD0203000100015D1E00000406001000545E5C000000 0103"this was device number one"0001000151CD0203000100015D1E00000406001000545E5C000000 0103"this was device number one"0001000151CD0203000100015D1E00000406001000545E5C000000 0103"this was device number one"0001000151CD0203000100015D1E00000406001000545E5C000…
upvote count: 0
downvote count: 2
answer count: 1
tagged with: file

http://stackoverflow.com/q/47735862
tagged with: python
has comment: http://stackoverflow.com/comment/82432280
score: 2
has answer: http://stackoverflow.com/a/47736142
answer count: 3
has answer: http://stackoverflow.com/a/47736016
tagged with: pandas
has answer: http://stackoverflow.com/a/47737614
has comment: http://stackoverflow.com/comment/82432232
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82432270
has comment: http://stackoverflow.com/comment/82432432
has body: thanks for your help. I have a large csv pseuodo-patient dataset, that generally it looks like this. Average Covered Charges , Total Discharges , Average Medicare Payments 32963.07 , 91 , 4763.73 15131.85 , 14 , 4976.71 37560.37 , , The problem that I am facing is that I am trying to get the total number of discharges greater than 100, ... BUT because one of the columns has one more value at the end than all the other cells, the last cell of the other columns just has empty space which is being counted as an item in the length of the dataset. I've loaded this csv file into a pandas dataframe and I've removed the NAs, and my dataset still looks like this. So NAs, None, etc ... is not the problem. It's an empty cell which is making the last two columns have the datatype "object", and because it has a blank cell/empty space, it is impossible to change the "object" datatype to "int" If I could change my dataframe to look like this by removing all rows in the dataset for which there are any empty cells in any of the the columns then all my problems would go away. So I would like my dataset to look like this: Average Covered Charges , Total Discharges , Average Medicare Payments 32963.07 , 91 , 4763.73 15131.85 , 14 , 4976.71 I'm surprised that I'm having such a hard time doing this. But from what I've read about Pandas, the documentation assumes that those are NAs and so I can just drop them, but I can't get Pandas to believe that at all. import pandas as pd inpatients_df = pd.read_csv("inpatient_payment_system.csv", low_memory = False) inpatients_df.dropna(axis = 0, how = 'any') # Remove NA values. I've already loaded in the dataset and removed all NAs, not like it matters. Note: There are much more than 3 columns in this dataset. It just takes one column to have more entres than the other columns for this to happen, and the issue is actually at the last row of the csv file.
upvote count: 2
type: UnansweredQuestion
has title: Removing the rows for which cells are empty in Pandas?
has comment: http://stackoverflow.com/comment/82432309
downvote count: 0

http://stackoverflow.com/comment/82510790
comment on: http://stackoverflow.com/a/47774474
score: 0
type: AnswerComment
has text: Hey thanks for editing my comment to make it more legible. Your answer does provide the solution so thanks! However it does work if you scale it to any arbitrary 2 dimensional array with an even number of rows. For example if I want to to this for a N by M array where M is even. For example: x = np.array([[1,5,3,8],[1,2,3,4]]) with desired output: array([[4,5],[1,1]])
type: Comment

http://stackoverflow.com/a/47806109
has body: IIUC, you don't need a function. Let's use boolean indexing as follows: cond1 = df['G'] &lt;= 0.01 cond2 = (((df.D - df.C + 1)*1.0)/global_map[df.A]) &gt;= 0.66 cond3 = (((df.F - df.E + 1)*1.0)/global_map[df.B]) &gt;= 0.66 mask = cond1 &amp; (cond2 | cond3) df[mask]
downvote count: 0
has comment: http://stackoverflow.com/comment/82574050
type: Answer
upvote count: 4
has comment: http://stackoverflow.com/comment/82573933
has comment: http://stackoverflow.com/comment/82573543
has comment: http://stackoverflow.com/comment/82573935
accepted answer of: http://stackoverflow.com/q/47805789
has comment: http://stackoverflow.com/comment/82573651
has comment: http://stackoverflow.com/comment/82573668
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82573881
answers question: http://stackoverflow.com/q/47805789
has comment: http://stackoverflow.com/comment/82573595
score: 4
has comment: http://stackoverflow.com/comment/82573733

http://stackoverflow.com/q/47775591
score: 0
has comment: http://stackoverflow.com/comment/82513973
has title: Changing array values to certain values/interval?
has comment: http://stackoverflow.com/comment/82512295
has comment: http://stackoverflow.com/comment/82512281
answer count: 1
tagged with: scipy
tagged with: rotation
type: Question
accepted answer: http://stackoverflow.com/a/47786394
tagged with: python
has comment: http://stackoverflow.com/comment/82512488
has answer: http://stackoverflow.com/a/47786394
has comment: http://stackoverflow.com/comment/82512681
has body: I rotate different arrays (dtype: np.float32) of shape 3x3, 5x5, 31x31, ... using scipy.ndimage.rotate. The input arrays always have a sum &lt;= 1.0 and in most cases the sum is equal to 1.0 minus a very small epsilon. The minimum of these arrays is always &gt;= 0.0. My expectation was that I should always get arrays which values are in the interval [0.0, 1.0] as the result of scipy.ndimage.rotate, but sometimes I get very small negative values as a minimum, like -1.0755285551056204e-16. I guess this appears due to floating point number inaccuracies?! However, I would like to squash the output arrays' values into the expected interval [0.0, 1.0] (while also ensuring a sum &lt;= 1.0). How can I achieve this as fast as possible (computation time)? Something like a softmax would not be good idea, since it rescales the array's values in a way (exponentially) that already high values get even higher. In some rare cases the returned array of scipy.ndimage.rotate also had a sum > 1.0 (positive float imprecision?!), thus I think simply using a sigmoid function would not be good idea, because I would just scale the values independently, not checking for the sum being &lt;= 1.0.
tagged with: numpy
has comment: http://stackoverflow.com/comment/82513292
type: AnsweredQuestion

http://stackoverflow.com/a/47731304
score: 3
has comment: http://stackoverflow.com/comment/82424313
upvote count: 3
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82424300
answers question: http://stackoverflow.com/q/47731211
has comment: http://stackoverflow.com/comment/82424239
has comment: http://stackoverflow.com/comment/82423705
has comment: http://stackoverflow.com/comment/82423958
accepted answer of: http://stackoverflow.com/q/47731211
downvote count: 0
type: Answer
has body: You are opening fileresp with r+ mode. When you call readlines(), the file's position will be set to the end of the file. Subsequent calls to write() will then append to the file. If you want to overwrite the original contents as opposed to append, you should try this instead: allLines = fileresp.readlines() fileresp.seek(0) # Set position to the beginning fileresp.truncate() # Delete the contents for line in allLines: fileresp.write(...) Update It's difficult to see what you're trying to accomplish with r+ mode here but it seems you have two separate input and output files. If that's the case consider: def translate(input, output, languagef, languaget): file = open(input, 'r').read() fileresp = open(output, 'w') # Use w mode instead subs = list(srt.parse(file)) for sub in subs: try: linefromsub = sub.content translationSentence = pydeepl.translate(linefromsub, languaget.upper(), languagef.upper()) print(str(sub.index) + ' ' + translationSentence) fileresp.write(translationSentence) # Write the translated sentence except IndexError: print("Error parsing data from deepl")

http://stackoverflow.com/comment/82630686
comment on: http://stackoverflow.com/q/47833620
type: Comment
has text: How would that work. I have django.shortcuts import render up top. that's fine right? I need to change it in the view then, correct?
score: 0
type: QuestionComment

http://stackoverflow.com/q/47755844
tagged with: python-3.x
has title: Pandas aggragation error (an integer is required)
downvote count: 0
upvote count: 1
score: 1
has answer: http://stackoverflow.com/a/47755949
answer count: 1
favorite count: 0
type: Question
type: AnsweredQuestion
tagged with: pandas-groupby
accepted answer: http://stackoverflow.com/a/47755949
linked to: http://stackoverflow.com/q/45255236
has body: df_act = pd.DataFrame({'A': {0: 'CHEMBL264', 1: 'CHEMBL4124', 2: 'CHEMBL264', 3: 'CHEMBL233', 4: 'CHEMBL233', 5: 'CHEMBL237', 6: 'CHEMBL236', 7: 'CHEMBL312', 8: 'CHEMBL3820', 9: 'CHEMBL3820'}, 'B': {0: 8.6999999999999993, 1: 8.1600000000000001, 2: 8.3000000000000007, 3: 7.2400000000000002, 4: 8.0, 5: 6.1600000000000001, 6: 6.4400000000000004, 7: 4.8200000000000003, 8: 7.5899999999999999, 9: 7.4299999999999997}}) Doing this works: df_act.groupby(['A'])['B'].median() However, using a custom function to apply it on the groupby object fails: def fun(x): name = {'B_median': x['B'].median()} return(pd.Series(names, index = ['B_median'])) df_act.groupby(['A'])['B'].apply(fun) returns: --------------------------------------------------------------------------- TypeError Traceback (most recent call last) pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc (pandas/_libs/index.c:5126)() pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item (pandas/_libs/hashtable.c:14010)() TypeError: an integer is required Of course, in both examples I am using the same dataframe, so I don't understand the error. Edit: add df_act definition
tagged with: python

http://stackoverflow.com/q/47804976
tagged with: gurobi
has body: So I'm using the Gurobi optimizer, and my decision variables are in a list called decision_bi, that looks like this: &lt;gurobi.Var dc0_st0_1/0 (value 0.0)&gt; I have managed to filter these down to the ones with the variable name containing '_1/0' with the following (I think): matching = filter(lambda x: '_1/0' in x, decision_bi) But now, I need to extract only those of this matching list that have (value 1.0), like so: &lt;gurobi.Var dc5_st1099_1/0 (value 1.0)&gt; I have managed to get it into a flat list (I was having issues with it being only accessible by decision_bi[i][j].X and .VarName which was not cooperating), and am trying regex on filtering on the 1.0 numbers with the following code: import re flat_list=[] for sublist in matching: for item in sublist: flat_list.append(item) results=[] for i in len(flat_list): results[i] = re.search('.*?1\\.0', flat_list[i], flags=0) However, it is telling me that the list is not iterable... and I don't know why? Using type on flat_list returns a list. My ultimate goal is writing two different lists containing the numbers after the dc and st parts of the string in the middle to our database, if it matters.
tagged with: python
tagged with: regex
accepted answer: http://stackoverflow.com/a/47805014
has comment: http://stackoverflow.com/comment/82571726
has answer: http://stackoverflow.com/a/47806607
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82571959
has answer: http://stackoverflow.com/a/47805014
answer count: 2
has comment: http://stackoverflow.com/comment/82571840
downvote count: 0
score: 1
upvote count: 1
possible better answer: http://stackoverflow.com/a/47806607
favorite count: 0
has title: Python: getting elements out of strange list that are 1.0?
type: Question

http://stackoverflow.com/comment/129806844
type: AnswerComment
has text: If you have a new question, please ask it by clicking the [Ask Question](https://stackoverflow.com/questions/ask) button. Include a link to this question if it helps provide context. - [From Review](/review/late-answers/32536205)
comment on: http://stackoverflow.com/a/73434261
score: 0
type: Comment

http://stackoverflow.com/a/47973210
accepted answer of: http://stackoverflow.com/q/47836266
has body: This is, as it stands, an MKL bug which has been kindly reported by @brd490 as per the discussion in SciPy issue 8205 and is accepted by the Intel MKL team Note that OpenBLAS-built SciPy does not have this issue. However, in the mean time, we have also noticed that the optimal workspace array sizes were not correct in the scipy.linalg.eigh.That is also going to be corrected once the decision over how to change the signature of the the underlying ?SYEVR/?HEEVR wrappers. As a bonus, probably one would be able to compute the eigenvalues selectively since originally these routines allow for it but were not exposed in scipy.linalg.eigh.
score: 2
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47836266
upvote count: 2
downvote count: 0
type: Answer

periodicity
tag name: periodicity
tags question: http://stackoverflow.com/q/47744143
type: Tag

http://stackoverflow.com/comment/82649957
comment on: http://stackoverflow.com/q/47842958
has text: maybe there are two elements on page so you get two prints. ie link with title and the same link with image.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47806024
tagged with: react-native
tagged with: mobile
type: UnansweredQuestion
tagged with: android
tagged with: ios
tagged with: python
score: 11
upvote count: 11
has title: Use python libraries in React Native
downvote count: 0
answer count: 1
has body: I want to use some Python libraries (for machine learning etc) in a React Native app. Is it possible to do it without using a server (i.e. run the Python code within the mobile app) so that no internet is required?
has answer: http://stackoverflow.com/a/47806842
favorite count: 0
type: Question

http://stackoverflow.com/a/47723877
score: 3
answers question: http://stackoverflow.com/q/47723819
downvote count: 0
has body: You can dump the passwords into a set (for quick lookups) and use one of the many online available dictionaries for actually frequently used passwords. (Most of them come from leaks, so it should be pretty much valid) https://github.com/danielmiessler/SecLists/tree/master/Passwords passwords = set(line.strip() for line in open('mostUsedPasswords.txt')) if "matrix" in passwords: print("This password is frequently used")
type: Answer
upvote count: 3

http://stackoverflow.com/a/47744937
has comment: http://stackoverflow.com/comment/82450159
has comment: http://stackoverflow.com/comment/82450118
has body: Note that your function does not take advantage of numpy's vectorisation. There are a few possible options. Option 1 This seems like a good use case for np.where - y = np.where(x &gt; 10, 0, np.sin(x)) Which returns values based on the mask provided. Here's a sample - x array([ 0.1, 0.2, 0.3, 11. , 0.1, 11. ]) np.where(x &gt; 10, 0, np.sin(x)) array([ 0.09983342, 0.19866933, 0.29552021, 0. , 0.09983342, 0. ]) Note that this method still calls the "expensive function" for each element. Option 2 Another possibility is to use a mask and set values conditionally - y = np.sin(x) y[x &gt; 10] = 0 Similar to above, you could multiply x by a mask and call np.sin on the result - y = np.sin(x * (x &lt; 10)) As Divakar mentioned, you can use numexpr with this condition - import numexpr as ne y = ne.evaluate("sin(x * (x &lt; 10))") This should be faster than the ones above.
has comment: http://stackoverflow.com/comment/82450151
type: Answer
answers question: http://stackoverflow.com/q/47744927
score: 2
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/82450207
has comment: http://stackoverflow.com/comment/82449963

http://stackoverflow.com/comment/82651444
comment on: http://stackoverflow.com/q/47843681
type: QuestionComment
type: Comment
has text: Could you correct the indentation of the code in your post?
score: 0

pendulum
tag name: pendulum
type: Tag
tags question: http://stackoverflow.com/q/47835657
tags question: http://stackoverflow.com/q/47849342

http://stackoverflow.com/q/47825938
tagged with: web-scraping
downvote count: 1
has comment: http://stackoverflow.com/comment/82614219
tagged with: beautifulsoup
has body: I keep getting the following error in Beatiful Soup 4 and Python 3. Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "C:\Python34\lib\encodings\cp437.py", line 19, in encode return codecs.charmap_encode(input,self.errors,encoding_map)[0] UnicodeEncodeError: 'charmap' codec can't encode character '\u2019' in position 33362: character maps to &lt;undefined&gt; The actual code: import requests from bs4 import BeautifulSoup url='https://www.yelp.com/search?find_desc=Restaurants&amp;find_loc=' yelp_r = requests.get(url) yelp_soup = BeautifulSoup(yelp_r.text, 'html.parser') print(yelp_soup.prettify())
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/82614308
has answer: http://stackoverflow.com/a/47825963
favorite count: 0
type: Question
has title: Codec can't encode character error using Beautiful soup 4 python 3
has comment: http://stackoverflow.com/comment/82633265
type: UnansweredQuestion
upvote count: 0
has comment: http://stackoverflow.com/comment/82614209
answer count: 1

http://stackoverflow.com/comment/82466488
score: 0
comment on: http://stackoverflow.com/q/47714993
type: Comment
type: QuestionComment
has text: No, when I install from local, even if the project is unziped, it does not install the requirements. I have to run pip install -r req... before running pip install . , later today i'll give some more attention to it and try to solve the error. From what I see you should be able to create a mock project and run the setup.py and get exactly the same error I have, if you do not have an error it would be very interesting to compare the steps that we made and how they differ. Thanks!

http://stackoverflow.com/comment/82515812
has text: Also, consider serializing your data into a format such as json instead of using shelve.
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47777308

http://stackoverflow.com/q/47788748
has comment: http://stackoverflow.com/comment/82540586
tagged with: sed
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/82542357
has answer: http://stackoverflow.com/a/47793531
possible better answer: http://stackoverflow.com/a/47793531
tagged with: python
score: -1
accepted answer: http://stackoverflow.com/a/47790309
has comment: http://stackoverflow.com/comment/82538570
has body: I have a space separated file (file1.csv) on which I perform 3 UNIX operations manually, namely: step1. removing all double quotes(") from each line. sed 's/"//g' file1.csv &gt; file_tmp1.csv step2. removing all white spaces at the beginning of any line. sed 's/^ *//' file_tmp1.csv &gt; file_tmp2.csv step3. removing all additional white spaces in between texts of each line. cat file_tmp2.csv | tr -s " " &gt; file1_processed.csv So, i wanted to know if there's any better approach to this and that to in a Pythonic way without much of a computation-time. These 3 steps takes about ~5 min(max) when done using UNIX commands. Please note the file file1.csv is a space-separated file and I want it to stay space-separated. Also if your solution suggests loading entire file1.csv into memory then I would request you to suggest a way where this is done in chunks because the file is way too big (~20 GB or so) to load into memory every time. thanks in advance.
has comment: http://stackoverflow.com/comment/82538668
has comment: http://stackoverflow.com/comment/82540461
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82540817
answer count: 2
downvote count: 2
has answer: http://stackoverflow.com/a/47790309
upvote count: 1
has comment: http://stackoverflow.com/comment/82538766
tagged with: unix
has title: doing basic UNIX operations Pythonic way
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82540543
has comment: http://stackoverflow.com/comment/82540849

http://stackoverflow.com/comment/82524098
score: 0
has text: Changing "count" to "contains" helps to save a bit of time. I'll rewrite my code to try pd.isnull(test["col"]). Thank you
type: Comment
comment on: http://stackoverflow.com/a/47769579
type: AnswerComment

http://stackoverflow.com/comment/82366548
type: Comment
comment on: http://stackoverflow.com/q/47702536
type: QuestionComment
has text: @HeatherBa so the output directory already has the same sub-directory structure, just no files?
score: 0

http://stackoverflow.com/comment/82648128
has text: Unless the board class is doing something unusual, they don't need to implement a method at all; `copy.deepcopy` will "just work".
comment on: http://stackoverflow.com/a/47841958
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/82396101
type: QuestionComment
has text: id that bad ? @Alasdair?
comment on: http://stackoverflow.com/q/47717866
score: 0
type: Comment

http://stackoverflow.com/a/47804286
upvote count: 2
downvote count: 2
answers question: http://stackoverflow.com/q/47804215
has body: Because it is checking for just 'y' in target. You need something like this: target = 'abc1234y' if 'y' in target and 'x' in target: print('x and y are in target')
type: Answer
score: 0

http://stackoverflow.com/comment/82610441
has text: The problem now is that I don't want the parentheses to be gone, I've tried putting them on again but I can't seem to do it.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47819915
type: Comment

http://stackoverflow.com/comment/82567325
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47802936
has text: Could you specify what error are you getting ?
type: Comment

http://stackoverflow.com/a/47729647
has comment: http://stackoverflow.com/comment/82423258
score: 1
type: Answer
answers question: http://stackoverflow.com/q/47729512
has comment: http://stackoverflow.com/comment/82432313
has comment: http://stackoverflow.com/comment/82419966
accepted answer of: http://stackoverflow.com/q/47729512
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: Your error on b = a.split("\n\n") is because you seem to think that f.writelines() will return something. It doesn't, so a has the value None and can't be split. The documentation says this about what writelines() does: writelines(lines) Write a list of lines to the stream. Line separators are not added, so it is usual for each of the lines provided to have a line separator at the end. So, if you want there to be linefeeds in your output file, you have to put them there before you call writelines(). But you should not be calling writelines()at all, because it expects a list of strings, and recognize_google() returns a string. Since you are getting one long string of words, and you want 5 per line, you need to break the text up into lines with 5 words and call write() for each line. Something like this: recognized_text = r.recognize_google(audio) remainder = recognized_text.split() while remainder: line, remainder = remainder[:5], remainder[5:] f.write(' '.join(line) + "\n")

http://stackoverflow.com/comment/82647778
has text: I had already gotten this fixed(Not sure how to close a question)- you can refer to my latest comment. regardless I am going to mark your response as the answer since I pretty much had done the same to solve the issue
type: AnswerComment
comment on: http://stackoverflow.com/a/47841338
score: 0
type: Comment

http://stackoverflow.com/comment/82391504
score: 0
type: Comment
has text: Also you can numbers as keys, just an fyi. They don't have to be strings.
comment on: http://stackoverflow.com/q/47715457
type: QuestionComment

http://stackoverflow.com/comment/82383671
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/47711767
type: Comment
has text: See: https://stackoverflow.com/questions/19508703/how-to-open-a-file-through-python and others. You should really be using `with` to handle your files.

http://stackoverflow.com/q/47730071
has body: I am interested if we can use pandas.core.groupby.DataFrameGroupBy.agg function to make arithmetic operations on multiple columns columns. For example: import numpy as np import pandas as pd df = pd.DataFrame(np.arange(15).reshape(5, 3)) df['C'] = [0, 0, 2, 2, 5] print(df.groupby('C').mean()[0] - df.groupby('C').mean()[1]) print(df.groupby('C').agg({0: 'mean', 1: 'sum', 2: 'nunique', 'C': 'mean0-mean1'})) Is it somehow possible that we receive result like in this example: the difference between means of column 0 and column 1 grouped by column 'C'? df 0 1 2 C 0 0 1 2 0 1 3 4 5 0 2 6 7 8 2 3 9 10 11 2 4 12 13 14 5 Groupped difference C 0 -1.0 2 -1.0 5 -1.0 dtype: float64 I am not interested with solutions that does not use agg method. I am curious only if agg method can take multiple columns as argument and then do some operations on them to return one columns after job is done.
has comment: http://stackoverflow.com/comment/82421136
tagged with: multiple-columns
type: Question
has comment: http://stackoverflow.com/comment/82420839
has answer: http://stackoverflow.com/a/47730311
tagged with: aggregate
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82423411
tagged with: python
score: 0
has title: Pandas agg fuction with operations on multiple columns
tagged with: pandas
answer count: 1

http://stackoverflow.com/comment/82485831
score: 0
type: QuestionComment
has text: use string formatting to get correct number of spaces between columns - [PyFormat.info](https://pyformat.info/)
type: Comment
comment on: http://stackoverflow.com/q/47761650

http://stackoverflow.com/comment/82601678
has text: How can it be a problem with the tour_length function when that is what determines the best_solution? When i print best_solution, the final print is different to that which is returned. When I check the tour length of the final print, it is the same as the best_solution_cost. For some reason what is being returned is different to the final print of best_solution. It is also in NONE of the prints. If possible, i'd like to assign that final print to a variable and then store that but that's probably not possible.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47819301

http://stackoverflow.com/q/47849523
type: Question
has title: PyCharm & console don't let me use local modules
tagged with: package
accepted answer: http://stackoverflow.com/a/47850825
has body: I'm absolutely frustraded about the fact that I can't start my Python journey. I have a simple service which I use as a training with Python which is new for me. I've downloaded PyCharm and as long as I had one file, everything was fine. That I decided to to some structure and suddenly my project stopped working. I have a structure like: project/ project/employees project/employees/__init__.py project/employees/employees.py project/server.py project/venv/ project/venv/(...) The project is a source root. And yet I have something like this: Traceback (most recent call last): File "C:/Users/user/PycharmProjects/project/server.py", line 5, in &lt;module&gt; from employees.employees import Employees, EmployeesName File "C:\Users\user\PycharmProjects\project\employees\employees.py", line 4, in &lt;module&gt; from server import db_connect File "C:\Users\user\PycharmProjects\project\server.py", line 5, in &lt;module&gt; from employees.employees import Employees, EmployeesName ImportError: cannot import name 'Employees' I tested this with VS Code and CMD and the same happend. I would be grateful for any suggestions! EDIT: employees.py: from flask_jsonpify import jsonify from flask_restful import Resource from server import db_connect class Employees(Resource): (...) class EmployeesName(Resource): (...)
has comment: http://stackoverflow.com/comment/82664075
has answer: http://stackoverflow.com/a/47850825
tagged with: python
tagged with: module
type: AnsweredQuestion
score: 2
tagged with: pycharm
upvote count: 2
has comment: http://stackoverflow.com/comment/82664403
answer count: 1
downvote count: 0
tagged with: import
favorite count: 0

http://stackoverflow.com/comment/82458036
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47748581
has text: this is the right code: with open("test.txt",'r') as f: a = f.read() b = a.strip() c = eval(b) print c

http://stackoverflow.com/comment/82578149
comment on: http://stackoverflow.com/a/47791671
type: Comment
has text: @Olaf yes that was an oversimplification indeed - I made it clearer and added a link to a more detailed explanation.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/82447645
type: QuestionComment
score: 0
has text: data is actual time and it is never less than 5 digits, it starts at 60000(6:00:00) and ends at 140000(14:00:00)
comment on: http://stackoverflow.com/q/47743704
type: Comment

http://stackoverflow.com/comment/82414454
score: 1
comment on: http://stackoverflow.com/a/47725888
has text: Absolutely brilliant edit to handle the more difficult case.
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/82666099
type: QuestionComment
has text: what is `save_relationship` here according to you ?
comment on: http://stackoverflow.com/q/47850198
score: 1
type: Comment

http://stackoverflow.com/comment/82674928
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47855220
score: 0
has text: Your code is more of an idiomatic example of what functional programming is not. Why do you bring it up in your title?

http://stackoverflow.com/q/47745397
tagged with: resnet
tagged with: tensorflow
favorite count: 0
has answer: http://stackoverflow.com/a/49335798
type: Question
upvote count: 9
has title: Why use fixed padding when building resnet model in tensorflow
has comment: http://stackoverflow.com/comment/85703608
tagged with: python
has answer: http://stackoverflow.com/a/49496115
score: 9
answer count: 2
downvote count: 0
has body: Tensorflow has an official realization of resnet in github. And it uses fixed padding instead of normal tf.layers.conv2d. Something like this: def conv2d_fixed_padding(inputs, filters, kernel_size, strides, data_format): """Strided 2-D convolution with explicit padding.""" # The padding is consistent and is based only on `kernel_size`, not on the # dimensions of `inputs` (as opposed to using `tf.layers.conv2d` alone). if strides &gt; 1: inputs = fixed_padding(inputs, kernel_size, data_format) return tf.layers.conv2d( inputs=inputs, filters=filters, kernel_size=kernel_size, strides=strides, padding=('SAME' if strides == 1 else 'VALID'), use_bias=False, kernel_initializer=tf.variance_scaling_initializer(), data_format=data_format) What's the purpose of doing this? We can get a 16x16 feature map if we input a image of size 32x32 and use tf.layer.conv2d setting padding method to SAME, stride 2. But in the code above, it will pad zero in both side of image and then use padding method VALID.
type: UnansweredQuestion

http://stackoverflow.com/q/47830954
has answer: http://stackoverflow.com/a/47831141
accepted answer: http://stackoverflow.com/a/47831141
type: AnsweredQuestion
score: 2
has body: I was wondering if it was possible to change or remove the "display: none;" in the element to make it visible with selenium in python. I already tried this: driver.execute_script("document.getElementById('g-recaptcha-response').style.display = '1';") but apparently it does not work. Any help would be apprreciated. :)
has comment: http://stackoverflow.com/comment/82624681
answer count: 1
tagged with: selenium
favorite count: 0
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/82624839
has title: How can I change/remove style attibute with selenium python?
downvote count: 0
tagged with: python

http://stackoverflow.com/a/64343218
score: 7
type: Answer
answers question: http://stackoverflow.com/q/47826086
downvote count: 0
has body: Similar answer, with an example of schema and another source from google.cloud import bigquery # Construct a BigQuery client object. client = bigquery.Client() # TODO(developer): Set table_id to the ID of the table to create. # table_id = "your-project.your_dataset.your_table_name" schema = [ bigquery.SchemaField("full_name", "STRING", mode="REQUIRED"), bigquery.SchemaField("age", "INTEGER", mode="REQUIRED"), ] table = bigquery.Table(table_id, schema=schema) table = client.create_table(table) # Make an API request. print( "Created table {}.{}.{}".format(table.project, table.dataset_id, table.table_id) )
upvote count: 7

http://stackoverflow.com/comment/82358223
comment on: http://stackoverflow.com/q/47698221
type: Comment
type: QuestionComment
score: 0
has text: your have to loop row by row over your `data_in` and code skips/corrections the way you want to have it with if statements etc. Then it's a matter of taste if you put your corrected rows in a list and write that at the end, or if you write row by row as they are processed.

http://stackoverflow.com/comment/82528714
comment on: http://stackoverflow.com/q/47783463
score: 1
type: Comment
has text: I'm actually pretty curious as to how the POSIX-specified `newgrp` command sets egid to a secondary group -- that is, which syscalls it's using, and whether they're available in the `os` module; it appears to operate properly in situations where `os.setegid()` returns `EPERM`.
type: QuestionComment

http://stackoverflow.com/comment/82560173
has text: your error is coming from `request.get(url)`. Look at the prints of your urls. they are NOT valid urls.
comment on: http://stackoverflow.com/q/47799418
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47834999
score: 2
type: AnsweredQuestion
tagged with: boolean
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/82633453
has answer: http://stackoverflow.com/a/47835175
has comment: http://stackoverflow.com/comment/82633563
upvote count: 2
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/82633441
has title: Checking for at least one instance of keyword in list
favorite count: 0
type: Question
tagged with: python-3.x
has body: I'm using Clarifai's API in Python to get concept names from a photo and would like to determine if any of them match a local variable. The following command invokes a list: In [1]: p1_response = model.predict_by_filename(filename='PATH_TO_FILE') p1_concepts = p1_response['outputs'][0]['data']['concepts'] for concept in p1_concepts: print(concept['name']) Out [2]: street outdoors architecture travel city horizontal plane pavement road house town urban car no person building stock luxury traffic apartment business tourism My local variable is a keyword defined as "car". I tried running if keyword in concept['name'], but my console listed 11 Falses before a True. Effectively, I'd like to make a function that does something if there is at least one instance of keyword in concept['name']. If anyone would chime in, I would much appreciate the help.
has comment: http://stackoverflow.com/comment/82633416
tagged with: python
has comment: http://stackoverflow.com/comment/82633679
has comment: http://stackoverflow.com/comment/82633341
accepted answer: http://stackoverflow.com/a/47835175
tagged with: clarifai

http://stackoverflow.com/q/47699711
tagged with: http://stackoverflow.com/tag/zip
tagged with: on-the-fly
tagged with: stream
answer count: 1
accepted answer: http://stackoverflow.com/a/47720277
type: Question
type: AnsweredQuestion
score: 0
has body: How to upload a file to SFTP server while zipping it on the fly. Or in other words, how to take a local file, zip it and upload it to SFTP server at the same time.
tagged with: python
has answer: http://stackoverflow.com/a/47720277
has title: Python: How to zip a file on the fly while uploading it to SFTP?

http://stackoverflow.com/a/47775678
has body: If you do not want to use lambda, you can try this: new_data = sorted([i for i in data if "price" in i], reverse=True)+[i for i in data if "errorCode" in i] Output: [{u'price': 5222.0, u'Name': u'United Kingdon'}, {u'price': 5237.0, u'Name': u'US'}, {u'price': 5283.0, u'Name': u'General'}, {u'errorCode': u'500', u'errorMsg': u'Pfffbt. server down.'}, {u'errorCode': u'500', u'errorMsg': u'Pfffbt. server down.'}]
answers question: http://stackoverflow.com/q/47775624
has comment: http://stackoverflow.com/comment/82513077
upvote count: 2
downvote count: 0
type: Answer
score: 2

http://stackoverflow.com/comment/82467957
score: 1
comment on: http://stackoverflow.com/q/47751594
type: Comment
type: QuestionComment
has text: Possible duplicate of [Pygame button single click](https://stackoverflow.com/questions/47639826/pygame-button-single-click)

http://stackoverflow.com/a/47847372
answers question: http://stackoverflow.com/q/47840527
score: 4
upvote count: 4
downvote count: 0
has body: I was looking through the losses of keras. Apparently logcosh has same properties as huber loss. More details of their similarity can be seen here.
type: Answer

http://stackoverflow.com/a/70271399
score: 0
answers question: http://stackoverflow.com/q/47703923
has body: The new version of Django does not allow the use from django.urls import include, url or from django.conf.urls import url maybe you can use re_path from django.urls import include, re_path urlpatterns = [ re_path(r'^index/$', views.index, name='index'), re_path(r'^bio/(?P&lt;username&gt;\w+)/$', views.bio, name='bio'), re_path(r'^weblog/', include('blog.urls')), ... ]
type: Answer
has comment: http://stackoverflow.com/comment/124221194

http://stackoverflow.com/a/47738611
answers question: http://stackoverflow.com/q/47737482
has comment: http://stackoverflow.com/comment/82438403
type: Answer
accepted answer of: http://stackoverflow.com/q/47737482
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: You could make your listAttributes method a classmethod and try the following: class Model(object): @classmethod def listAttributes(cls): return [ a for a in dir(cls) if not callable(getattr(cls, a)) and not a.startswith("__") ] If you just want to have the attributes that are of your "Fields" type (FieldChar, FieldInt...) then you could make a base class for the fields called e.g. ModelField and also check your attributes against this base type: class Model(object): @classmethod def listAttributes(cls): attributes = [] for a in dir(cls): if ((not callable(getattr(cls, a)) and not a.startswith("__") and getattr(cls, a).__class__.__bases__[0] == ModelField)): attributes.append(a) You could even return the objects instead of just the names. Or append the objects to a dict in your Model class (to make usage in your code easier). I constructed my ORM like this: class ModelField(object): ... class IntField(ModelField): ... class Model(object): id = IntField(pk=True) def __init__(self, *args, **kwargs): try: self.modelFields except AttributeError: self.__class__.introspect() for key, modelfield in self.modelFields.items(): setattr(self, key, kwargs.get(key, None)) @classmethod def introspect(cls): cls.modelFields = {} for a in dir(cls): if ((not callable(getattr(cls, a)) and not a.startswith("__") and getattr(cls, a).__class__.__bases__[0] == ModelField)): cls.modelFields[a] = getattr(cls, a) Then i used cls.introspect to set up the modelFields dict and use this dict to e.g. autogenerate a db-table or construct querys by using attributes of the ModelField class.

http://stackoverflow.com/q/47723402
answer count: 0
has comment: http://stackoverflow.com/comment/82407624
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/82407843
favorite count: 0
type: Question
has title: How to read Scikit learn documentation?
has comment: http://stackoverflow.com/comment/82407612
has comment: http://stackoverflow.com/comment/82407560
linked to: http://stackoverflow.com/q/40378427
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82407587
has body: I am a bit new to Python and was confused on how to read documentation. In particular, the Scikit learn documentation for their Logistic Regression classifier describes a function fit with the following parameters: Parameters: X : {array-like, sparse matrix}, shape (n_samples, n_features) Training vector, where n_samples is the number of samples and n_features is the number of features. y : array-like, shape (n_samples,) Target vector relative to X. The first part of X seems to ask for a dictionary ... and but the shape is a tuple? I'm confused - what type of input is the function expecting for X here?
has comment: http://stackoverflow.com/comment/82407692
has comment: http://stackoverflow.com/comment/82407563
tagged with: python
has comment: http://stackoverflow.com/comment/82407815
score: 2
upvote count: 2
downvote count: 0

http://stackoverflow.com/a/47702201
score: 0
has body: This is easier than you think. in Django. Note that to these links. please many to many in django model and many to one in django model
type: Answer
answers question: http://stackoverflow.com/q/47700981

http://stackoverflow.com/a/47704868
downvote count: 0
has comment: http://stackoverflow.com/comment/82370167
upvote count: 4
type: Answer
score: 4
has comment: http://stackoverflow.com/comment/82370053
has body: you can make use of pd.PeriodIndex: In [145]: df.groupby(pd.PeriodIndex(df.columns, freq='M'), axis=1).mean() Out[145]: 2013-01 2013-02 A 1.5 3.5 B 5.5 7.5
answers question: http://stackoverflow.com/q/47704702

http://stackoverflow.com/comment/82622535
score: 0
has text: That string does not look binary. Try doing `new Buffer(decodeURIComponent(byteString))`
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47829609

http://stackoverflow.com/q/47722238
score: 20
tagged with: python-2.7
tagged with: elasticsearch-5
answer count: 1
downvote count: 0
favorite count: 0
type: Question
has title: Python elasticsearch.helpers.scan example
accepted answer: http://stackoverflow.com/a/47732771
upvote count: 20
has answer: http://stackoverflow.com/a/47732771
tagged with: elasticsearch
tagged with: python
has body: Can someone provide scan API example of python elasticsearch helpers client? res = elasticsearch.helpers.scan(....) How can i get all results from elasticsearch with res object?
type: AnsweredQuestion

http://stackoverflow.com/comment/82485502
type: AnswerComment
has text: @demetriwolf - check the update, it parses out IP addresses from WMI
score: 0
comment on: http://stackoverflow.com/a/47761536
type: Comment

http://stackoverflow.com/comment/82520450
score: 0
type: Comment
has text: np. It's good to look for the "new answers on this question" prior to submitting.
type: AnswerComment
comment on: http://stackoverflow.com/a/47779618

http://stackoverflow.com/comment/82477637
comment on: http://stackoverflow.com/q/47758127
score: 1
type: Comment
type: QuestionComment
has text: Are you using `pandas` here? You might want to remove a few of the tags not necessary here and add that one - look to provide a [mcve]

http://stackoverflow.com/comment/82672140
type: QuestionComment
comment on: http://stackoverflow.com/q/47759123
has text: @AnandCU I resized the images to 32x32, so the training takes from about 5-10 minutes on CPU (depending on epochs). Since the images were to big to train in the beginning, im afraid I am loosing to much, so I hoped to increase the accuracy by having less features to train. The loss went down over time (training), but stables on a point and goes a bit up again.
score: 0
type: Comment

http://stackoverflow.com/comment/82492368
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47761481
score: 0
has text: That was also very useful, thank you furas!

http://stackoverflow.com/comment/82592973
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/47815710
has text: Can't reproduce. This code does for me what you say it should do. What version of python are you using?
type: Comment

http://stackoverflow.com/q/47825127
has answer: http://stackoverflow.com/a/47825998
has answer: http://stackoverflow.com/a/47825213
downvote count: 0
accepted answer: http://stackoverflow.com/a/47825213
upvote count: 1
has title: Append 2 lists into 1 with alternate from every iteration
has answer: http://stackoverflow.com/a/47825257
favorite count: 0
has answer: http://stackoverflow.com/a/47825634
type: AnsweredQuestion
answer count: 9
has answer: http://stackoverflow.com/a/47825187
tagged with: list
possible better answer: http://stackoverflow.com/a/47825187
has body: I have 2 lists W = ['w1', 'w2'] D = [1,2,3,4,5,6] I want to iterate over them such that I get a final list final = [ [' w1', 1], ['w2', 2], ['w1', 3], ['w2', 4], ['w1', 5], ['w2', 6]] (in the same order) I was trying to iterate over W and D for i in W: for j in D: if j % 2 == 1 and i == 'w1' : final. append ([i, j] my logic was to divide by %2 to find whether it is odd or even, but it's not working.
score: 1
tagged with: python
has answer: http://stackoverflow.com/a/47825346
has answer: http://stackoverflow.com/a/47825214
type: Question
has answer: http://stackoverflow.com/a/47825159
has answer: http://stackoverflow.com/a/47825154

http://stackoverflow.com/comment/82471264
score: 0
has text: Thank you for the solution. But this does not filter the rating to only ratings posted by the user. I would need something like: @property def rating(self): return self.placeratings.filter(user=request.user)[0].rating .. which is not accepted by Django.
comment on: http://stackoverflow.com/a/47744295
type: Comment
type: AnswerComment

http://stackoverflow.com/a/47764885
type: Answer
score: 0
has body: You could try: my_dict = dict( key1 = 'value1' ) It's a different notation. Not sure why PyCharm is complaining about what you entered before. But you should also make sure you have the latest edition of PyCharm. Also, click on the "more..." link (shown in your image) to see what it says. It might even be helpful! :)
answers question: http://stackoverflow.com/q/47763792

http://stackoverflow.com/a/47777436
downvote count: 1
has comment: http://stackoverflow.com/comment/82523439
has body: You need to first read in all three of z's dimensions (lat, lon, depth) and then extract values across each of those dimensions. Here are a few examnples. # Read in all 3 dimensions [lat x lon x depth] z = fh.variables['z'][:,:,:] # Topography at a single lat/lon/depth (1 value): z_1 = z[5,5,5] # Topography at all depths for a single lat/lon (1D array): z_2 = z[5,5,:] # Topography at all latitudes and longitudes for a single depth (2D array): z_3 = z[:,:,5] Note that the number you enter for lat/lon/depth is the index in that dimension, not an actual latitude, for instance. You'll need to determine the indices of the values you are looking for beforehand.
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/47771152
has comment: http://stackoverflow.com/comment/82523888
score: 0

http://stackoverflow.com/q/47787955
has title: Not able to get JSON response due to UnicodeDecodeError?
has answer: http://stackoverflow.com/a/47788577
possible better answer: http://stackoverflow.com/a/47788577
tagged with: python
type: AnsweredQuestion
score: 0
answer count: 2
tagged with: http://stackoverflow.com/tag/json
has answer: http://stackoverflow.com/a/47790260
has body: I am not able to get JSON response when I try to run python core-backup.py file: In code FB_SHORT_ACCESS_TOKEN and FB_LONG_ACCESS_TOKEN are same. core-backup.py : import os from os.path import join import requests def refresh_short_token(): """ Refresh short access token """ request_url = FB_URL + 'oauth/access_token' request_payload = { 'grant_type': 'fb_exchange_token', 'client_id': FB_APP_ID, 'client_secret': FB_APP_SECRET, 'fb_exchange_token': FB_SHORT_ACCESS_TOKEN } response = REQ_SESSION.get(request_url, params=request_payload).json() # dotenvfile = find_dotenv() # load_dotenv(dotenvfile) # dotenv.set_key(dotenvfile, "FB_LONG_ACCESS_TOKEN", response['access_token']) FB_LONG_ACCESS_TOKEN = response["access_token"] # PAYLOAD['access_token'] = dotenv.get_key(dotenvfile, "FB_LONG_ACCESS_TOKEN") PAYLOAD['access_token'] = FB_LONG_ACCESS_TOKEN ''' TODO: refresh_long_token() A function to refresh the long term access token Current validity: 60 days ''' def get_feed(): """ Fetch feed """ request_url = FB_URL + LTTK_GROUP_ID + '/feed' response = REQ_SESSION.get(request_url, params=PAYLOAD) if response.status_code == 400: refresh_short_token() print(response.json()) return response.json() def main(): """ Fetch posts from a Facebook group and populate in database """ get_feed() if __name__ == "__main__": main() I am getting UnicodeDecodeError in windows7 after running core-backup.py file. How to fix this issue. See screenshot for more clarity: Entire code of file can be found out here: https://gist.github.com/anonymous/2ab9e023d631a7cc4dad15237104ee34
accepted answer: http://stackoverflow.com/a/47790260
tagged with: facebook-graph-api
type: Question

http://stackoverflow.com/comment/131298611
has text: Happens to me too, the test suite started failing after I updated my python libraries. The XML is "re-started" just after a [`Builtin.Sleep`](https://robotframework.org/robotframework/latest/libraries/BuiltIn.html#Sleep), but there may be some threading stuff in the background.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47807679

http://stackoverflow.com/q/47839546
tagged with: python-3.x
has body: Im coming from an R background where it is trivial to do str(X) to get a text output of a data structure and its values. Is there a similar functionality in Python? Note that in Python type(X) does not return the data structure- just the class of X which is not what I am looking for. print(X) returns the values but not their type (num in the R code below) Example using R of my goal: &gt; df&lt;-data.frame(1,2,3) &gt; str(df) 'data.frame': 1 obs. of 3 variables: $ X1: num 1 $ X2: num 2 $ X3: num 3
tagged with: python
tagged with: data-structures
has comment: http://stackoverflow.com/comment/82643114
score: 2
type: AnsweredQuestion
has title: How do you view the structure of data stored in a Python variable?
upvote count: 2
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/47839830
has comment: http://stackoverflow.com/comment/82643005
favorite count: 0
has answer: http://stackoverflow.com/a/47839830
has comment: http://stackoverflow.com/comment/82643078
type: Question

http://stackoverflow.com/comment/82658394
comment on: http://stackoverflow.com/q/47847111
score: 1
type: QuestionComment
has text: what is your input format like?
type: Comment

http://stackoverflow.com/q/47849366
tagged with: pyqt
linked to: http://stackoverflow.com/q/38796335
tagged with: treeview
answer count: 1
type: Question
tagged with: qt
has title: PyQT: QPushButton delegate in column of a treeview
accepted answer: http://stackoverflow.com/a/47851155
linked to: http://stackoverflow.com/q/37972839
tagged with: python
tagged with: c++
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82666062
score: 0
has body: I know there has been a question with the same goal in C++, but I didn't succeed implementing a button delegate in a treeview. So I ask a new question here, even if I know there was a previous question with the same goal. I just ask for further explanation. So since a few days, I manage to implement a multi-node tree model within a treeview thanks to this video tutorial with the code source here and here but now I would like to add a delegate pushbutton next to each child of the last level of the tree model. After consulting Qt documentation about model/view programming, searching around and reading chapter 14, 15 and 16 from the book of Mark Summerfield Rapid GUI Programming with Python and QT and searching how to add Qwidget delegate by using createEditor(), setEditordata() and setModelData() I still struggle to display "The" button… So I started to create the button class delegate: class ButtonDelegate(QtGui.QItemDelegate): """ A delegate that places a fully functioning Button in every cell of the column to which it's applied """ def __init__(self, parent): QtGui.QItemDelegate.__init__(self, parent) def createEditor(self, parent, option, index): button = QtGui.QPushButton("Simple button", parent) self.connect(button, QtCore.SIGNAL("clicked()"), self, QtCore.SLOT("handle_button()")) return button @QtCore.pyqtSlot() def handle_button(self): sender = self.sender() print("Button pushed: {}".format(self.sender())) Here you see that I didn't implement setEditordata() and setModelData(), because I have connected the button to def handle_button(self) and I just want to print the name of the child for the moment (just to make it simple). I use setItemDelegateForColumn(int, AbstractItemDelegate) for setting up the delegate I also know that for displaying the button you have to specify this method to the treeview QAbstractItemView.openPersistentEditor(QModelIndex). But I don't know what to put as argument... Again I am sorry to "repost" a question but at the moment I am in …
has answer: http://stackoverflow.com/a/47851155
linked to: http://stackoverflow.com/q/11777637

http://stackoverflow.com/comment/82577671
type: Comment
comment on: http://stackoverflow.com/a/47807682
score: 0
type: AnswerComment
has text: Yes, python show list with `()` but pg show list with `{}`.

http://stackoverflow.com/comment/82667301
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47851027
type: Comment
has text: It won't help very much, but you should load the image once, and then pull all the frames out, rather than loading the image from the HDD for every frame. [Here's how I did that](https://stackoverflow.com/a/43770948/2229945). Also, notice the proper way to create a tkinter widget: by subclassing a current widget. That way you can treat it like any other widget in your code (pack, grid, tkraise, etc).

http://stackoverflow.com/comment/82674032
type: QuestionComment
comment on: http://stackoverflow.com/q/47854733
type: Comment
has text: You need to interpolate. Perhaps nearest neighbor scaling if you want to keep the data discrete.
score: 1

http://stackoverflow.com/comment/82606911
type: Comment
has text: Use {% for error in form.hora_inicio.errors %}{{ error|escape }}{% endfor %} to check validation errors.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47820798

http://stackoverflow.com/comment/82480010
type: QuestionComment
comment on: http://stackoverflow.com/q/47758292
type: Comment
score: 0
has text: Are you required to use version 1.1.2 for `comtypes`, or can you upgrade it to 1.1.3?

http://stackoverflow.com/q/47728288
answer count: 1
favorite count: 0
tagged with: google-maps-api-3
accepted answer: http://stackoverflow.com/a/47730960
has comment: http://stackoverflow.com/comment/82464093
type: Question
has answer: http://stackoverflow.com/a/47730960
has body: I have made a Google Maps with dive location in the Netherlands. The next step is that an user can search on the page for a dive location and that the search results are showing on the Google Maps. So it must replace the exisitng map. I'm a new to Django and never worked with Javascript before. The problem is that I don't know how to make a new map with dive locations that are getting back from the search result. Urls.py from django.conf.urls import url from . import views app_name = 'kaart' urlpatterns = [ # /gis url(r'^$', views.index, name='index'), # Voor ajax zoekfunctie url(r'^search/$', views.search_duik_locaties, name='search_duik_locaties'), # /gis/id_number/ url(r'^(?P&lt;duik_id&gt;[0-9]+)/$', views.detail, name='detail'), ] views.py from django.shortcuts import render, get_object_or_404 from .models import Duikplaats def index(request): all_duik_locaties = Duikplaats.objects.all() longitude = Duikplaats.objects.values('longitude') latitude = Duikplaats.objects.values('latitude') content = { 'all_duik_locaties': all_duik_locaties, 'longitude': longitude, 'latitude': latitude, } return render(request, 'kaart/index.html', content) def detail(request, duik_id): duikplaats = get_object_or_404(Duikplaats, pk=duik_id) return render(request, 'kaart/details.html', {'duikplaats': duikplaats}) def search_duik_locaties(request): query = request.GET.get('q') if query is not None and query != '' and request.is_ajax(): zoek_duik_locaties = Duikplaats.objects.filter(duik_locatie__icontains=query) lat = zoek_duik_locaties.values('latitude') con = { 'zoek_duik_locaties': zoek_duik_locaties, 'lat': lat } return render(request, 'kaart/ajax_search.html', con) return render(request, 'kaart/ajax_search.html') index.html (part of the Ajxax Call) $('#search').keyup(function (event) { var query =($('#search').val()); if (query != '' || query != ' ') { $.ajax({ type: 'GET', url: '/gis/search', data: { 'csrfmiddlewaretoken': '{{ csrf_token }}', 'q': query }, {# dataType: 'json',#} …
tagged with: python
score: 1
has title: Create a new Google Maps after Ajax success with Django
tagged with: google-maps
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/82422391
tagged with: django
tagged with: javascript
upvote count: 1

http://stackoverflow.com/a/47731034
type: Answer
has body: gmpy2, due to Alex Martella et al, seems to perform better, at least on my Win10 machine. from time import time import gmpy2 def onecount(n): if n == 0: return 0 if n % 2 == 0: m = n/2 return onecount(m) + onecount(m-1) + m m = (n-1)/2 return 2*onecount(m)+m+1 N = 10000 initial = time() for _ in range(N): for i in range(30): onecount(i) print (time()-initial) initial = time() for _ in range(N): total = 0 for i in range(30): total+=gmpy2.popcount(i) print (time()-initial) Here's the output: 1.7816979885101318 0.07404899597167969 If you want a list, and you're using >Py3.2: &gt;&gt;&gt; from itertools import accumulate &gt;&gt;&gt; result = list(accumulate([gmpy2.popcount(_) for _ in range(30)])) &gt;&gt;&gt; result [0, 1, 2, 4, 5, 7, 9, 12, 13, 15, 17, 20, 22, 25, 28, 32, 33, 35, 37, 40, 42, 45, 48, 52, 54, 57, 60, 64, 67, 71]
score: 1
upvote count: 1
downvote count: 0
answers question: http://stackoverflow.com/q/47730349

http://stackoverflow.com/comment/82410945
type: Comment
has text: I've tried to unindented by one and replace numb by x but still no lucks. My goal is find out the mean values of each individual list and put into a column as I illustrated.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47724998

http://stackoverflow.com/a/47797076
has comment: http://stackoverflow.com/comment/82555131
score: 2
has body: This is kind of a wild guess: If your self.board is "a 7x7 matrix", it's probably a list of lists, so you should use copy.deepcopy to copy the board. Otherwise, the inner lists will still be the same, and as you modify the current board, you also modify all the "copies". def save_state(self): copied_board = copy.deepcopy(self.board) self.saved_states.append(copied_board) Alternatively, instead of storing the board layouts for each turn, store the moves performed by the players and replay the game accordingly.
accepted answer of: http://stackoverflow.com/q/47796896
upvote count: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82555578
downvote count: 0
has comment: http://stackoverflow.com/comment/82559143
has comment: http://stackoverflow.com/comment/82555370
answers question: http://stackoverflow.com/q/47796896
type: Answer

http://stackoverflow.com/a/47804505
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47804372
has body: I suggest the two almost similar solution depending on your use case: Using caching class Person(models.Model): """ The 'a' from my above example """ @property def iter_important_treats(self): return (pet.treat_id for pet in self.pets.all()) # will use the cached objects if they exist person = Person.objects.get(id=person_id).select_related('pets') # to cache the pets list within the person object avoiding future additional queries treats = Treat.objects.filter(id__in=person.iter_importent_treats) Without Using caching: class Person(models.Model): """ The 'a' from my above example """ @property def iter_important_treats(self): return iter(self.pets.values_list('treat_id', flat=True)) # caching will not affect the query behviour person = Person.objects.get(id=person_id) treats = Treat.objects.filter(id__in=person.iter_importent_treats) NB: we use treat_id instead treat__id to avoid additional join queries, because the django saves already the treat_id at the Pet object level but if you use treat__id then you force a join query. Limiting the property to an iterator of IDs is just for reversibility and maintainability sake
accepted answer of: http://stackoverflow.com/q/47804372
type: Answer
score: 4
upvote count: 4

http://stackoverflow.com/comment/82673953
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47854442
has text: I think making all the instances aware of each other would probably require another server and all the instances broadcasting "wait I'm using DB" and some kind of queue... I wonder if somebody did something like that before in python... maybe using separate table in DB for that ? just thinking out loud....

http://stackoverflow.com/a/47824606
answers question: http://stackoverflow.com/q/47824510
downvote count: 0
score: 2
has body: You can construct a function to truncate strings that are too long, and wrap that around the format inputs. def truncate(*inputs, max_length=18): return tuple(s[:max_length] for s in inputs) STRING_FORMATTER = '{0:13}{1:18}{2:18}{3:30}{4:10}\n' content = STRING_FORMATTER.format( *truncate('addr', 'bit', 'value', 'name', 'type')) content = content + STRING_FORMATTER.format( *truncate('0123', 'LONG STRING THAT EXCEEDS 18 SPACES!!!!!!!!!!!!!!!!', '', '', 'reg')) content = content + STRING_FORMATTER.format( *truncate('00', '0', '0xAD', 'NAME', 'bit'))
type: Answer
upvote count: 2

http://stackoverflow.com/a/47852713
has body: In manage.py runserver, the manage.py is only a file, not a command! You can not do this since the Linux(shell) could only execute binary executable image. If you want to run manage.py without python, you could add (supposed that you used Linux) #!/usr/bin/env python at the head of manage.py, and make it executable with chmod +x manage.py. And now, you could run ./manage.py runserver
answers question: http://stackoverflow.com/q/47852394
downvote count: 1
upvote count: 0
type: Answer
score: -1

http://stackoverflow.com/a/47778502
has comment: http://stackoverflow.com/comment/82519379
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/82523353
downvote count: 0
has comment: http://stackoverflow.com/comment/82523394
type: Answer
has body: The trick is to maximize compute versus memory ratio here. The output is of length N, one index and distance for each pt in A. We could reduce it to one loop with one output element per iteration and this will process through all B pts per iteration, which is bringing in the high compute ratio. Thus, leveraging einsum and matrix-multiplication inspired from this post, for each point pt in A, we would get the squared euclidean distances, like so - for pt in A: d = np.einsum('ij,ij-&gt;i',B,B) + pt.dot(pt) - 2*B.dot(pt) Thus, generalizing it cover all points in A and pre-computing np.einsum('ij,ij-&gt;i',B,B), we would have an implementation like so - min_idx = np.empty(N, dtype=int) min_dist = np.empty(N) Bsqsum = np.einsum('ij,ij-&gt;i',B,B) for i,pt in enumerate(A): d = Bsqsum + pt.dot(pt) - 2*B.dot(pt) min_idx[i] = d.argmin() min_dist[i] = d[min_idx[i]] min_dist = np.sqrt(min_dist) Working in chunks Now, a fully vectorized solution would be - np.einsum('ij,ij-&gt;i',B,B)[:,None] + np.einsum('ij,ij-&gt;i',A,A) - 2*B.dot(A.T) So, to work in chunks, we would slice out rows off A and to do so would be easier to simply reshape to 3D, like so - chunk_size= 100 # Edit this as per memory setup available # More means more memory needed A.shape = (A.shape[0]//chunk_size, chunk_size,-1) min_idx = np.empty((N//chunk_size, chunk_size), dtype=int) min_dist = np.empty((N//chunk_size, chunk_size)) Bsqsum = np.einsum('ij,ij-&gt;i',B,B)[:,None] r = np.arange(chunk_size) for i,chnk in enumerate(A): d = Bsqsum + np.einsum('ij,ij-&gt;i',chnk,chnk) - 2*B.dot(chnk.T) idx = d.argmin(0) min_idx[i] = idx min_dist[i] = d[idx,r] min_dist = np.sqrt(min_dist) min_idx.shape = (N,) min_dist.shape = (N,) A.shape = (N,-1)
has comment: http://stackoverflow.com/comment/82519271
answers question: http://stackoverflow.com/q/47778117

http://stackoverflow.com/q/47845212
accepted answer: http://stackoverflow.com/a/47845291
tagged with: python
has comment: http://stackoverflow.com/comment/82654579
has answer: http://stackoverflow.com/a/47845291
linked to: http://stackoverflow.com/q/4915361
type: AnsweredQuestion
tagged with: python-2.7
answer count: 1
duplicate of: http://stackoverflow.com/q/4915361
downvote count: 0
score: 1
upvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has title: Difference of input() in python2/3
has comment: http://stackoverflow.com/comment/82654582
has body: This is to be a simple mathematics program for my child to help with arithmetic. However, the IF statement does not work in Python3 but does in Python2! Please may I ask what has changed (as I can't seem to find the answer)? #import from library import random import sys #display the python version print(sys.version) #computer selects two random numbers between 1 and 10 x = random.randint(1,10) y = random.randint(1,10) #print x and y values print("For x =", x, "and y =", y) #calculate the correct answer to the sum of the two numbers and store it in the variable named "correct" correct = x + y #ask the user what is the sum of the two random numbers and provide a response answer = input("What is the sum of x plus y ? ") if answer == correct: print("well done") else: print("Incorrect. The correct answer is", correct)

http://stackoverflow.com/q/47803706
answer count: 0
has title: Python While Loop Admin-Server
has comment: http://stackoverflow.com/comment/82569168
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82569282
has comment: http://stackoverflow.com/comment/82568931
type: Question
has comment: http://stackoverflow.com/comment/82569264
has body: Well i am doing an exercise which you have A server, an Admin and the clients.Admin should show the IP and the Port of the client. I made all of them.But i got a problem at the Admin with the loop.As u see with the code below i made an infinity loop.If 3 clients are online i am gonna recieve only the one of them's IP and Port.Instead of One i need to get all the ip and port that are online on the server.But for some reason this doesnt work. players = a.recv(80).decode() print("Current players playing " + players) x = 1 while True: client_list = a.recv(80).decode() print(client_list) x += 1 input() But if i make a loop like this for players in range(0, 3): client_list = a.recv(80).decode() print(client_list) input() then this works but for only 3 times.I dont have idea what i am doing wrong. Thanks for your time. CLIENT CODE import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(('127.0.0.1', 4000)) helloMSG = ("Hello\r\n") s.send(helloMSG.encode()) greetings = s.recv(80).decode() print(greetings) gameMSG = ("Game\r\n") s.send(gameMSG.encode()) readyMSG = s.recv(80).decode() running = 1 while running: guess = input("My guess is:") guessstring = "My Guess is: " + str(guess) + "\r\n" s.send(guessstring.encode()) result = s.recv(80).decode() print(result) if (result == "Correct\r\n"): running = 0 s.close() AND THE ADMIN CODE ` import socket a = socket.socket(socket.AF_INET, socket.SOCK_STREAM) a.connect(('127.0.0.1', 4001)) print("connected!\n") message = "Hello\r\n" a.send(message.encode()) result = a.recv(80).decode() print(result) message = "Who\r\n" a.send(message.encode()) players = a.recv(80).decode() print("Current players playing " + players) x = 1 while True: client_list = a.recv(80).decode() print(client_list) x += 1 input()
tagged with: python
score: 0

http://stackoverflow.com/comment/123440843
has text: this will not train the embedding layer.
type: Comment
comment on: http://stackoverflow.com/a/47738941
score: 0
type: AnswerComment

http://stackoverflow.com/comment/82619641
comment on: http://stackoverflow.com/q/47828481
has text: pandas has `read_html()` which can find all ` ` in file.
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82546786
type: Comment
comment on: http://stackoverflow.com/q/47786568
type: QuestionComment
score: 2
has text: I sometimes miss Ruby when I write in Python : `['item1','item2', 'item3', 'item4'].flatten(1)`. To be fair, it happens in both direction.

http://stackoverflow.com/q/47708123
score: 1
downvote count: 0
answer count: 1
upvote count: 1
has answer: http://stackoverflow.com/a/47708322
favorite count: 0
type: Question
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
tagged with: dictionary
has title: Create list of dictionaries from CSV in the same order using Python
has comment: http://stackoverflow.com/comment/82376276
has body: Consider a CSV, col1, col2, col3 1000, Star, True 2000, Moon, False How to create a list of dictionaries in the same order like this [{'col1': '1000', 'col2': 'Star', 'col3': 'TRUE'}, {'col1': '2000', 'col2': 'Moon', 'col3': 'FALSE'}] I have tried with following code but not getting in the same order with open('sample.csv') as f: rows = [{k: v for k, v in row.items()} for row in csv.DictReader(f, skipinitialspace=True)] Output of above code, [{'col2': 'Star', 'col3': 'TRUE', 'col1': '1000'}, {'col2': 'Moon', 'col3': 'FALSE', 'col1': '2000'}] Is there any solution to get in the same order? Thanks!
accepted answer: http://stackoverflow.com/a/47708322
linked to: http://stackoverflow.com/q/1885324
type: AnsweredQuestion
tagged with: list

http://stackoverflow.com/comment/82562208
type: QuestionComment
has text: NB: If you're trying to build pyside for python3.4 do not use python2.7 to run setup/configure scripts. In general, you must always use the executable for the *specific python installation* you want to build against. To avoid problems, always use the *full path* to the python exectutable.
score: 0
comment on: http://stackoverflow.com/q/47798863
type: Comment

http://stackoverflow.com/a/47901660
score: 0
type: AcceptedAnswer
has body: nvm i'm such an idiot it's seems you cant declare QWidget twice so i change one of them as QDialog, i'm still learning so please bear with me X__X widgeta.py : class widgetA(QDialog): def __init__(self, parent=None): super(widgetA, self).__init__(parent) self.initUI() then this is in widgetb.py : from widgeta import widgetA class widgetB(QWidget): def __init__(self, parent=None): super(widgetB, self).__init__(parent) self.initUI() self.show() def initUI(self): self.setFixedSize(254, 380) self.center() button = QPushButton('open', self) button.clicked.connect(self.openwindow) self.openwindow = widgetA() def openwindow(self): self.openwindow.exec()
accepted answer of: http://stackoverflow.com/q/47853024
type: Answer
answers question: http://stackoverflow.com/q/47853024

http://stackoverflow.com/comment/82523503
has text: Yes, columns are comma separated but you also have to specify the datatype. The placeholders are one for each column, so yes in my example the two `%s` instances correspond to `seasonId` and `playerName`. Google "postgres create table" and they will show you some examples. If this works, consider [accepting the answer](https://stackoverflow.com/help/someone-answers).
score: 0
comment on: http://stackoverflow.com/a/47779093
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/82369026
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47704341
type: Comment
has text: I am having problems. When I define a dictionary locally in an imported module, and I try to "return" it at the end of a function in that module, the main function reports an empty dictionary although I can see via print statements in the imported module it is not empty. So I was trying to declare a variable globally to allow the imported module to operate on it.

firefox
type: Tag
tags question: http://stackoverflow.com/q/47739636
tags question: http://stackoverflow.com/q/47772911
tags question: http://stackoverflow.com/q/47805212
tags question: http://stackoverflow.com/q/47813919
tags question: http://stackoverflow.com/q/47728687
tags question: http://stackoverflow.com/q/47801788
tag name: firefox
tags question: http://stackoverflow.com/q/47785882
tags question: http://stackoverflow.com/q/47782650
tags question: http://stackoverflow.com/q/47759491
tags question: http://stackoverflow.com/q/47728220

http://stackoverflow.com/q/47704469
has body: I wrote an encryption program in Python 3.6 that uses the module pycryptodome, specificly these imports: from Crypto.Cipher import AES from Crypto.Hash import SHA256 from Crypto.Random import get_random_bytes The program works, but it cannot be used without the user installing the pycryptodome module themselves. Is there any way to include that package somehow or can I create a "first time setup" to install it for the end user?
downvote count: 1
tagged with: python-module
answer count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82369958
has answer: http://stackoverflow.com/a/47904413
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82369256
has title: How can I include a pip installed module with my python script?
has comment: http://stackoverflow.com/comment/82369266
linked to: http://stackoverflow.com/q/12332975
tagged with: python
tagged with: end-user
has comment: http://stackoverflow.com/comment/82369500
score: 2
has comment: http://stackoverflow.com/comment/82369093
upvote count: 3

http://stackoverflow.com/a/47767591
has body: Since you're dealing with 0/1s, here's another alternative using diff + cumsum - df['group'] = df.condition.diff().abs().cumsum().fillna(0).astype(int) + 1 df condition H t group index 0 1 2.0 1.1 1 1 1 7.0 1.5 1 2 0 1.0 0.9 2 3 0 6.5 1.6 2 4 1 7.0 1.1 3 5 1 9.0 1.8 3 6 1 22.0 2.0 3 If you don't mind floats, this can be made a little faster. df['group'] = df.condition.diff().abs().cumsum() + 1 df.loc[0, 'group'] = 1 df index condition H t group 0 0 1 2.0 1.1 1.0 1 1 1 7.0 1.5 1.0 2 2 0 1.0 0.9 2.0 3 3 0 6.5 1.6 2.0 4 4 1 7.0 1.1 3.0 5 5 1 9.0 1.8 3.0 6 6 1 22.0 2.0 3.0 Here's the version with numpy equivalents - df['group'] = 1 df.loc[1:, 'group'] = np.cumsum(np.abs(np.diff(df.condition))) + 1 df condition H t group index 0 1 2.0 1.1 1 1 1 7.0 1.5 1 2 0 1.0 0.9 2 3 0 6.5 1.6 2 4 1 7.0 1.1 3 5 1 9.0 1.8 3 6 1 22.0 2.0 3 On my machine, here are the timings - df = pd.concat([df] * 100000, ignore_index=True) %timeit df['group'] = df.condition.diff().abs().cumsum().fillna(0).astype(int) + 1 10 loops, best of 3: 25.1 ms per loop %%timeit df['group'] = df.condition.diff().abs().cumsum() + 1 df.loc[0, 'group'] = 1 10 loops, best of 3: 23.4 ms per loop %%timeit df['group'] = 1 df.loc[1:, 'group'] = np.cumsum(np.abs(np.diff(df.condition))) + 1 10 loops, best of 3: 21.4 ms per loop %timeit df['group'] = df['condition'].ne(df['condition'].shift()).cumsum() 100 loops, best of 3: 15.8 ms per loop
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/47767461
has comment: http://stackoverflow.com/comment/82497049
has comment: http://stackoverflow.com/comment/82496991
score: 4
accepted answer of: http://stackoverflow.com/q/47767461
has comment: http://stackoverflow.com/comment/82496932
type: Answer
has comment: http://stackoverflow.com/comment/82497096
upvote count: 4
has comment: http://stackoverflow.com/comment/82496997
has comment: http://stackoverflow.com/comment/82497233
has comment: http://stackoverflow.com/comment/82496889
has comment: http://stackoverflow.com/comment/82496902
has comment: http://stackoverflow.com/comment/82496956
downvote count: 0

http://stackoverflow.com/comment/82553103
comment on: http://stackoverflow.com/q/47783007
has text: https://stackoverflow.com/questions/38311503/django-1-9-drop-foreign-key-in-migration
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47819024
has comment: http://stackoverflow.com/comment/82600065
has comment: http://stackoverflow.com/comment/82600218
has comment: http://stackoverflow.com/comment/82600739
downvote count: 1
favorite count: 0
tagged with: http://stackoverflow.com/tag/r
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82601139
has comment: http://stackoverflow.com/comment/82600652
has body: To understand my question, I should first point out that R datatables aren't just R dataframes with syntaxic sugar, there are important behavioral differences : column assignation/modification by reference in datatables avoids the copying of the whole object in memory (see the example in this quora answer) as it is the case in dataframes. I've found on multiple occasions that the speed and memory differences that arise from data.table's behavior is a crucial element that allows one to work with some big datasets while it wouldn't be possible with data.frame's behavior. Therefore, what I'm wondering is : in Python, how do Pandas' dataframes behave in this regard ? Bonus question : if Pandas' dataframes are closer to R dataframes than to R datatables, and have the same down side (a full copy of the object when assigning/modifying column), is there a Python equivalent to R's data.table package ? EDIT per comment request : Code examples : R dataframes : # renaming a column colnames(mydataframe)[1] &lt;- "new_column_name" R datatables : # renaming a column library(data.table) setnames(mydatatable, 'old_column_name', 'new_column_name') In Pandas : mydataframe.rename(columns = {'old_column_name': 'new_column_name'}, inplace=True)
tagged with: pandas
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/82605629
has comment: http://stackoverflow.com/comment/82601060
upvote count: 10
has comment: http://stackoverflow.com/comment/82601040
linked to: http://stackoverflow.com/q/19758364
score: 9
type: Question
has title: Are Pandas' dataframes (Python) closer to R's dataframes or datatables?
has comment: http://stackoverflow.com/comment/82600290
accepted answer: http://stackoverflow.com/a/47819826
tagged with: data.table
has comment: http://stackoverflow.com/comment/82600955
has comment: http://stackoverflow.com/comment/82600649
has answer: http://stackoverflow.com/a/47819826
answer count: 1

http://stackoverflow.com/comment/82486795
score: 0
type: AnswerComment
has text: @Coal_, I read the SO page describing [what is off-topic](https://stackoverflow.com/help/on-topic) and my take away is that the OP's question is more on-topic than off. (There's nothing about it that would attract opinionated answers and spam.) Please cite from that page where the OP went wrong. I also believe that downvoting my answer based not on the quality of its content but on one's opinion of the OP's question is a worse infraction than I may, or may not, have made.
comment on: http://stackoverflow.com/a/47761080
type: Comment

http://stackoverflow.com/a/47827459
upvote count: 2
answers question: http://stackoverflow.com/q/47826673
score: 2
downvote count: 0
type: Answer
has body: Your scoring function is incorrect. The syntax should be sil_score(y_true,y_pred) where y_true are the ground truth lables and y_pred are the predicted labels. Also you need not separately predict the labels using the ensemble object inside your scoring function. Also in your case it makes more sense to directly use silhouette_score as the scoring function since you are calling your ensemble to predict labels inside the scoring function which is not required at all. Just pass the silhouette_score as the scoring function and GridSearchCV will take care of predicting the scoring on it's own. Here is an example if you want to see how it works.

http://stackoverflow.com/comment/82651869
type: QuestionComment
comment on: http://stackoverflow.com/q/47843889
has text: If you're on Windows OS then `'selenium\\webdriver\\remote\\getAttribute.js` seem to be invalid absolute path.
score: 0
type: Comment

http://stackoverflow.com/q/47732891
answer count: 0
score: 1
has comment: http://stackoverflow.com/comment/82686289
favorite count: 0
type: Question
tagged with: python-3.x
has title: Python Subprocess: what am I doing wrong?
tagged with: subprocess
tagged with: automation
type: UnansweredQuestion
tagged with: wget
downvote count: 0
upvote count: 1
tagged with: python
has body: Overview: I am trying to use the Python subprocess module to execute complex wget commands. I am using Python because I can randomly switch between HTTP header values for each job, better organize results, etc. I like wget instead of the similar Python packages because I know wget quite well and prefer it. I also like how easy it is to route the job through the Tor relay via torsocks. For reference, I am an Ubuntu user. I really appreciate the assistance. Problem: having little experience in the subprocess module, I've spent a lot of time on Python.org and Stackoverflow to learn how to correctly employ subprocess. However, I can't seem to connect what I've learned there to a solution for my problem. In some cases, Python will create the time-date stamped results directory correctly, but I'll then find the results in some other place, like the pwd. In other cases, directory creation works, but the wget functions seem to fail. When I looked at the wget logfile, the error I saw pop up from time to time was "Scheme missing." This error may be tied to directory creation. Relevant code: targetURL="https://www.wikipedia.org" targethost="Wikipedia" # the general wget results folder root_dir='/home/me/Documents/wget/' # the exact results folder based on the target URL and date/time results_dir=root_dir+targethost+"/"+str(datetime.datetime.now().strftime("%Y-%m-%d")) if not os.path.exists(results_dir): os.makedirs(results_dir) # args is a list of all wget variables subprocess.call(args, stdin=None, stdout=None, stderr=None, shell=False, timeout=None) Example values from the args variable pushed to subprocess: ['torsocks', 'wget', '-w 300', '--random-wait', '-e robots=off', '--append-output', '--directory-prefix=/home/me/Documents/wget/Wikipedia/2017-12-09', "--user-agent='Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.91 Safari/537.36'", "--header='Accept: application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png…
has comment: http://stackoverflow.com/comment/82669334

http://stackoverflow.com/comment/82437976
score: 0
type: Comment
type: QuestionComment
has text: you can open file in write mode with 'w', it will erase every content from file; in read mode 'r' you can read content of your file and append mode 'a' to append anything at end of your file
comment on: http://stackoverflow.com/q/47738712

http://stackoverflow.com/a/47766293
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/105212544
downvote count: 0
upvote count: 21
has body: Try 127.0.0.1 There maybe some odd name resolution rules fumbling requests. Ah ok, this is my work machine. I took a look at /etc/hosts and saw ~200 routes defined that I didn't realize were there As mention in the comments, this does not explain the odd behavior replicated using curl.
score: 21
type: Answer
accepted answer of: http://stackoverflow.com/q/47766158
has comment: http://stackoverflow.com/comment/82494165
answers question: http://stackoverflow.com/q/47766158
has comment: http://stackoverflow.com/comment/82493740

http://stackoverflow.com/a/47837770
upvote count: 4
score: 4
has comment: http://stackoverflow.com/comment/82639569
downvote count: 0
has comment: http://stackoverflow.com/comment/82639577
type: AcceptedAnswer
has body: You're on the right track. Once you split, you can either assign id back, or concat the two pieces i = df.activities.str.split(',', expand=True).add_prefix('activity_') i activity_0 activity_1 activity_2 activity_3 activity_4 0 541 589 235 45 None 1 213 213 None None None 2 458 88 999 150 360 j = i.assign(id=df['id']) # assign id back j = pd.concat([df'id', i], 1) # concat the two pieces j id activity_0 activity_1 activity_2 activity_3 activity_4 0 1 541 589 235 45 None 1 2 213 213 None None None 2 3 458 88 999 150 360
answers question: http://stackoverflow.com/q/47837733
accepted answer of: http://stackoverflow.com/q/47837733
type: Answer

http://stackoverflow.com/q/47725320
has body: I am new to Python and building a function to read CSV. I am trying to use the pandas.read_csv() inside my function,and while the code gets compiled-i dont see the dataset (I know its an overkill, but am trying to learn it using a trial and error method). &gt;&gt;&gt; def CSV(filename): dataset=pd.read_csv(filename) I expect that when i run CSV('abc.csv'), it should create a df in my variable explorer. Unfortunately, the function gets compiled, but nothing is there def CSV(filename): dataset=pd.read_csv(filename) CSV('banking.csv')
possible better answer: http://stackoverflow.com/a/66724057
tagged with: pandas
has title: Building a function to read CSV
tagged with: http://stackoverflow.com/tag/csv
upvote count: 0
has answer: http://stackoverflow.com/a/66724057
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/82411342
has comment: http://stackoverflow.com/comment/82411388
has comment: http://stackoverflow.com/comment/82411451
score: -2
downvote count: 2
has comment: http://stackoverflow.com/comment/82411426
tagged with: python
has comment: http://stackoverflow.com/comment/82411351
has comment: http://stackoverflow.com/comment/82411341
accepted answer: http://stackoverflow.com/a/47725385
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47725385
has comment: http://stackoverflow.com/comment/82411380
answer count: 2

http://stackoverflow.com/comment/82619715
type: AnswerComment
has text: Also, the fragment I showed originally had the node and element data in dictionaries and as you noted, getting the data out of them can be slow, but I only use these data structures for one model import path. My preferred approach for larger models is to import via hdf5 and I get the data quickly into numpy arrays that way so overall the import is fast. Now the bottleneck is with vtk. It takes me less than a second to populate the vtk data structures from disk (warm start, hdf5 files in the windows filesystem cache) but then it takes vtk 25 seconds to render........
comment on: http://stackoverflow.com/a/47825111
type: Comment
score: 0

http://stackoverflow.com/comment/82545335
has text: I don't know but line_product_total jquery says no such variable :(
score: 0
comment on: http://stackoverflow.com/q/47791643
type: Comment
type: QuestionComment

http://stackoverflow.com/q/47841879
answer count: 1
score: 1
has answer: http://stackoverflow.com/a/47852997
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/82662800
has body: I need to padding zeros to a tensor ('ARRAY' in the code snippet) reading from a TFRecord file. Because the training model I use requires that their shapes should be the same. However, my inputs have different widths and lengths. Therefore, I tried to calculate the number of zeros ('paddings = tf.Variable([[0, targetLength],[0, targetWidth]])' in the code snippet) I should padding. However, tensorflow raised the InvalidArgumentError and the value "arg0" never occurred in my code. An example for variable ARRAY is as follows: [1,0,1,0] [2,0,2,0] and I should padding it to [1,0,1,0,0,0] [2,0,2,0,0,0] [0,0,0,0,0,0] There can be many large arrays so I want to pad it right before the training. Here are my code snippets. def my_input_fn(file_path, perform_shuffle=True, repeat_count=1): global width, length # two int64 variables. batchNum = 32 def parse_ARRAY(tfrecord): features = tf.parse_single_example( tfrecord, # Defaults are not specified since both keys are required. features={ 'label': tf.FixedLenFeature([], tf.int64), 'length': tf.FixedLenFeature([], tf.int64), 'width': tf.FixedLenFeature([], tf.int64), 'ARRAY': tf.FixedLenFeature([], tf.string) }) ARRAY = tf.decode_raw(features['ARRAY'], tf.int64) label = tf.cast(features['label'], tf.int64) ARRAYLength = tf.cast(features['length'], tf.int64) ARRAYWidth = tf.cast(features['width'], tf.int64) ARRAYshape = tf.stack([ARRAYLength, ARRAYWidth]) ARRAY = tf.reshape(ARRAY, ARRAYshape) TFWidth = tf.convert_to_tensor(width, tf.int64) TFLength = tf.convert_to_tensor(length, tf.int64) targetWidth = tf.subtract(TFWidth, ARRAYWidth) targetLength = tf.subtract(TFLength, ARRAYLength) paddings = tf.Variable([[0, targetLength],[0, targetWidth]]) with tf.Session() as sess: sess.run(paddings.initializer) tf.pad(ARRAY, paddings, "CONSTANT") return {"ARRAY":ARRAY}, label dataset = tf.data.TFRecordDataset(file_path) dataset = dataset.map(parse_ARRAY) if perform_shuffle: dataset = dataset.shuffle(buffer_size=256) dataset = dataset.repeat(…
favorite count: 0
type: Question
has title: Tensorflow: InvalidArgumentError (see above for traceback): You must feed a value for placeholder tensor 'arg0' with dtype string
type: UnansweredQuestion
downvote count: 0
tagged with: tfrecord
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/82657004

http://stackoverflow.com/comment/82553858
score: 0
comment on: http://stackoverflow.com/a/47790514
has text: This is exactly what I need- thanks! I might be running an older version of matplotlib, but for some reason I had to insert a path for set_facecolor, ie `ax.patch.set_facecolor(col2colors[i])`
type: Comment
type: AnswerComment

http://stackoverflow.com/a/47868690
score: 0
has body: OK, found the source of the problem and @zwer was in the right place. When called from by full script the Increment_value argument was coming in as a string. So to fix the problem I modified the following line to convert it to an int increment_value = int(args.increment) It worked in the standalone because it was declared as an int from the start. Thanks for all you help on this!
answers question: http://stackoverflow.com/q/47853765
type: Answer

http://stackoverflow.com/a/47712639
has body: I'm not exactly sure what you mean by proper format as your first csv is already in csv form. But to fill your na results, you can do this: df.fillna('0')
upvote count: 2
answers question: http://stackoverflow.com/q/47712295
type: Answer
score: 2
downvote count: 0

http://stackoverflow.com/q/47749257
has comment: http://stackoverflow.com/comment/82489813
has comment: http://stackoverflow.com/comment/82489817
type: AnsweredQuestion
score: 3
tagged with: python-2.7
upvote count: 3
has comment: http://stackoverflow.com/comment/82466975
tagged with: rsa
answer count: 1
downvote count: 0
favorite count: 0
tagged with: digital-signature
type: Question
has comment: http://stackoverflow.com/comment/82489965
has body: I'm new member, I have waited two days to find solution verify signature from android client to python server. First I create Key pair and generate signature from private key. Thank you pedrofb I have updated full code. verify done in python server. protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); KeyPairGenerator keyPairGenerator = null; try { KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore"); keyStore.load(null); //keyStore.deleteEntry("key1"); keyPairGenerator = KeyPairGenerator.getInstance( KeyProperties.KEY_ALGORITHM_RSA, "AndroidKeyStore"); try { KeyGenParameterSpec.Builder builder = new KeyGenParameterSpec.Builder("key1", KeyProperties.PURPOSE_SIGN) .setKeySize(2048) .setBlockModes(KeyProperties.BLOCK_MODE_CBC) .setDigests(KeyProperties.DIGEST_SHA256) .setSignaturePaddings(KeyProperties.SIGNATURE_PADDING_RSA_PKCS1); keyPairGenerator.initialize(builder.build()); } catch (InvalidAlgorithmParameterException e) { e.printStackTrace(); } KeyPair keyPair = keyPairGenerator.generateKeyPair(); PrivateKey privateKey = (PrivateKey) keyStore.getKey("key1", null); PublicKey publicKey = keyStore.getCertificate("key1").getPublicKey(); String publicKeyStr = Base64.encodeToString(publicKey.getEncoded(), Base64.NO_WRAP); Log.d("Hahaha", publicKeyStr); Signature signature = Signature.getInstance("SHA256withRSA"); signature.initSign(privateKey); String data = "haha"; signature.update(data.getBytes()); byte[] signatureBytes = signature.sign(); String signatureBase64 = Base64.encodeToString(signatureBytes, Base64.NO_WRAP); Log.d("Hahaha", signatureBase64); Signature verifySignature = Signature.getInstance("SHA256withRSA"); verifySignature.initVerify(publicKey); verifySignature.update(data.getBytes()); boolean isVerify = verifySignature.verify(Base64.decode(signatureBase64, Base64.NO_WRAP)); Log.d("Hahaha", isVerify + ""); } catch (Exception e) { e.printStackTrace(); } } public static String s…
has title: Android/Python How to verify Signature SHA256withRSA and PKCS1 Padding
has comment: http://stackoverflow.com/comment/82467511
tagged with: android
tagged with: python
has comment: http://stackoverflow.com/comment/82495038
has answer: http://stackoverflow.com/a/47767023
accepted answer: http://stackoverflow.com/a/47767023

http://stackoverflow.com/q/47774601
upvote count: 0
answer count: 2
has comment: http://stackoverflow.com/comment/82514356
tagged with: apache-spark
has body: I have a very simple csv file that looks like this: time,is_boy,is_girl 135,1,0 136,0,1 137,0,1 I have this csv file sitting in a Hive table also, where all the values have been created as doubles in the table. Behind the scenes, this table is actually enormous, and has an enormous number of rows, so I have chosen to use Spark 2 to solve this problem. I would like to use this clustering library, with Python: https://spark.apache.org/docs/2.2.0/ml-clustering.html If anyone knows how to load this data, either directly from the csv or by using some Spark SQL magic, and preprocess it correctly, using Python, so that it can be passed into the kmeans fit() method and calculate a model, I would be very grateful. I also think it would be useful for others as I haven't found an example for csvs and for this library yet.
linked to: http://stackoverflow.com/q/47585723
has title: How to preprocess csv data for Spark 2.0 clustering?
has comment: http://stackoverflow.com/comment/82515350
downvote count: 2
has answer: http://stackoverflow.com/a/47774819
possible better answer: http://stackoverflow.com/a/47774819
favorite count: 0
has comment: http://stackoverflow.com/comment/82510129
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47814804
accepted answer: http://stackoverflow.com/a/47814804
has comment: http://stackoverflow.com/comment/82515433
has comment: http://stackoverflow.com/comment/82557491
score: -2
tagged with: http://stackoverflow.com/tag/csv
tagged with: pyspark
tagged with: python
has comment: http://stackoverflow.com/comment/82515552
type: Question

http://stackoverflow.com/q/47792430
tagged with: scapy
answer count: 1
type: Question
type: UnansweredQuestion
tagged with: python
tagged with: packet-sniffers
has answer: http://stackoverflow.com/a/47811167
tagged with: pyshark
tagged with: wireshark
score: 0
has title: Is there a way to convert byte arrays to PyShark dataframe?
has body: I used scapy to sniff packets, but Scapy can't return the packet info like PyShark(Wireshark). For example: &gt;&gt;&gt; cap = pyshark.FileCapture('test.pcap', only_summaries=True) &gt;&gt;&gt; cap[1].info 'FTP Data: 1460 bytes' &gt;&gt;&gt; cap[2].info 'Response: 150 Opening BINARY mode data connection for Notes chapter2.pdf(14868284 bytes)' &gt;&gt;&gt; type(cap[2]) &lt;class 'pyshark.packet.packet_summary.PacketSummary'&gt; This feature is what I really want, but I only have packet raw byte array or Scapy dataframe. Is it a solution to convert byte array to PyShark dataframe? Because my computer has weird issues when sniffing using PyShark.

mechanicalsoup
tag name: mechanicalsoup
tags question: http://stackoverflow.com/q/47796717
type: Tag

http://stackoverflow.com/a/47806733
type: Answer
accepted answer of: http://stackoverflow.com/q/47806693
has comment: http://stackoverflow.com/comment/82576723
has comment: http://stackoverflow.com/comment/82574918
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/47806693
score: 3
has comment: http://stackoverflow.com/comment/82575733
upvote count: 3
has body: You have to use regex group instead of character class for to match this or that word. character classes [] are used to do OR function on single characters, it won't work with group of characters. Use either capturing or non-capturing group with | as delimiter inorder to do OR operation on group of chars. r'\b\d{1,2}\.\d{1,2}\s?(?:[ap]m\b)?'

mod-wsgi
tags question: http://stackoverflow.com/q/47749188
type: Tag
tags question: http://stackoverflow.com/q/47799480
tags question: http://stackoverflow.com/q/47732203
tags question: http://stackoverflow.com/q/47814599
tags question: http://stackoverflow.com/q/47736881
tags question: http://stackoverflow.com/q/47770941
tag name: mod-wsgi

http://stackoverflow.com/q/47755377
answer count: 1
downvote count: 3
favorite count: 0
type: Question
tagged with: opencv
has comment: http://stackoverflow.com/comment/82471661
has answer: http://stackoverflow.com/a/47755675
has title: reading pixel value in binary using python
has body: how to read pixel value in binary image? import cv2 img = cv2.imread('sc.jpg') px = sc[1, 1] print px but the results I get are 3 red channels green and blue [255 255 255] based on the reference I have the pixel value on the binary image is 1 and 0 sp i am confused with this condition thankyou :)
tagged with: python-imaging-library
type: UnansweredQuestion
score: -3
tagged with: python
has comment: http://stackoverflow.com/comment/82471739
upvote count: 0

http://stackoverflow.com/comment/82751456
type: Comment
has text: The arguments are fractions of figure size. If you want the right side of the subplots (in this case the one subplot) to be tight at the right figure edge, you set `right=1` (meaning 100% of the figure width). The left subplot side is set to 0, so essentially there is no space left between the figure edge and the subplot. In other words `plt.subplots_adjust(0,0,1,1)` makes the subplot exactly as large as the figure itself. (This works well in this case because the figure has the same aspect as the subplot, both being square.)
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/47855504

http://stackoverflow.com/comment/82572569
has text: i tried while(1) loop but, if it is turned off once it isn't turning on again
comment on: http://stackoverflow.com/q/47739887
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/82627577
has text: Please mark the question as answered (the check mark next to a response) if you feel it has been answered completely.
score: 2
comment on: http://stackoverflow.com/q/47832205
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82571661
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/47804307
type: Comment
has text: "_I'm not absolutely sure if this is useful_" -- it is absolutely necessary, but the way you have it is **wrong**, and it's wrong in Perl in this way, too. The pattern `p1|p2|...` need be built so that the longest words come first; otherwise a short sub-word can get replaced wrongly (`no` in `nothing`, when `nothing` happens before `no` in target). However, in Perl `sort` by default does it _alphabetically_ and here we need it by length; see my answer. In Python you also must tell it how it should be `sorted` and you want to use `key` parameter. Fix it please.

http://stackoverflow.com/comment/82610029
score: 0
type: AnswerComment
type: Comment
has text: You could just send all the packets on one socket, with a data field, and then wait for the replies. There's no real reason to do it fully concurrently.
comment on: http://stackoverflow.com/a/47823379

http://stackoverflow.com/comment/82381106
type: QuestionComment
type: Comment
score: 0
has text: Why is this upvoted? A quick search on this would have shown there is a duplicate question on SO and OP didn't even tell if he tried at least anything to make it work.
comment on: http://stackoverflow.com/q/47710356

http://stackoverflow.com/q/47730869
has comment: http://stackoverflow.com/comment/82422313
answer count: 4
type: AnsweredQuestion
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47730992
accepted answer: http://stackoverflow.com/a/47730886
has answer: http://stackoverflow.com/a/57017313
tagged with: web-scraping
type: Question
possible better answer: http://stackoverflow.com/a/47730975
score: 0
has answer: http://stackoverflow.com/a/47730975
has answer: http://stackoverflow.com/a/47730886
has body: I've written a tiny script in python using BeautifulSoup to parse some items out of some element stored within content variable within the below script. I do not wish to append items to the previously created empty dictionary; rather, i wish to parse it on the fly. However, I tried but could not achieve that. Any help would be highly appreciated. This is my attempt: from bs4 import BeautifulSoup content=""" hot cold day night """ soup = BeautifulSoup(content,'lxml') for items in soup.select('tr'): data = [item.text for item in items.select("td")] dict_val = {data[0] : data[1]} print(dict_val) The way I'm getting the output: {'hot': 'cold'} {'day': 'night'} The way I expect to have the output: {'hot': 'cold','day': 'night'}
tagged with: python
tagged with: dictionary
has title: Unable to store parsed items as dictionary

http://stackoverflow.com/comment/82456262
type: Comment
comment on: http://stackoverflow.com/a/47741601
score: 0
type: AnswerComment
has text: @AnushaPrasanth I had changed only in models.py file see the updated results now!

http://stackoverflow.com/comment/82528289
comment on: http://stackoverflow.com/q/47782788
type: Comment
type: QuestionComment
has text: @SuperStew Yeah sadly I'm not seeing it. Hmmm... I mean the script I'm using works swimmingly, but I don't understand what params the original writer knew to use.
score: 0

http://stackoverflow.com/q/47708771
answer count: 3
has answer: http://stackoverflow.com/a/47708861
has comment: http://stackoverflow.com/comment/82377480
has comment: http://stackoverflow.com/comment/82377363
has comment: http://stackoverflow.com/comment/82377392
type: Question
has answer: http://stackoverflow.com/a/47713112
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/47713112
has title: Get first few elements of tuples from list of list of tuples
has body: I have a structure of list of list of tuples like:- [[(1, 1, 96), (1, 2, 95), (0, 5, 23), (0, 6, 22)], [(2, 1, 145), (1, 2, 144), (10, 3, 143), (2, 4, 142)]] I basically want to obtain 2 list of list of tuples from this. One tuple for the first 2 columns, and the other tuple for the third column. Desired output:- [[(1, 1), (1, 2), (0, 5), (0, 6)], [(2, 1), (1, 2), (10, 3), (2, 4)]] &amp;&amp; [[(96,), (95,), (23,), (22,)], [(145,), (144,), (143,), (142,)]] How can this be done in python?
has comment: http://stackoverflow.com/comment/82377431
possible better answer: http://stackoverflow.com/a/47708861
tagged with: python
has answer: http://stackoverflow.com/a/47709021
type: AnsweredQuestion
score: 0

http://stackoverflow.com/comment/82595343
type: QuestionComment
comment on: http://stackoverflow.com/q/47816716
score: 0
has text: I'm sorry I'm not quite sure I understand, why is it adding a null to the last value of the arduino data then because I've written it so only 5 values are added to it and only 1 adding to the myTimeStamp column
type: Comment

http://stackoverflow.com/comment/82640938
type: Comment
has text: Nice, but maybe use `s.partition(".")[2]`, otherwise it will fail if the input is an integer value, i.e. has no `.`.
score: 0
comment on: http://stackoverflow.com/a/47838416
type: AnswerComment

http://stackoverflow.com/q/47815140
upvote count: 13
score: 13
answer count: 0
tagged with: pandas
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/24870306
downvote count: 0
has title: Check if multiple columns exist in a df
duplicate of: http://stackoverflow.com/q/38070072
favorite count: 0
has comment: http://stackoverflow.com/comment/82592212
type: Question
tagged with: python-3.x
duplicate of: http://stackoverflow.com/q/24870306
tagged with: dataframe
tagged with: python
has body: I am wondering how to properly check if multiple columns exist in a df, say if I want to test if both columns A and B exist in df: if `A` in df and `B` in df: # some code is there a better way to do this checking? tested with ['A', 'B'] in df, but failed. UPDATE pd.Series(['A', 'B']).isin(df.columns).all() will do the work.
has comment: http://stackoverflow.com/comment/82591696

pca
tag name: pca
tags question: http://stackoverflow.com/q/47820537
type: Tag
tags question: http://stackoverflow.com/q/47770920
tags question: http://stackoverflow.com/q/47770674

http://stackoverflow.com/a/47778915
has comment: http://stackoverflow.com/comment/82519397
upvote count: 2
has comment: http://stackoverflow.com/comment/82519841
answers question: http://stackoverflow.com/q/47778667
has comment: http://stackoverflow.com/comment/82519913
has comment: http://stackoverflow.com/comment/82520381
has comment: http://stackoverflow.com/comment/82519786
score: 2
has comment: http://stackoverflow.com/comment/82519673
downvote count: 0
has body: This may Help You from django.utils.safestring import mark_safe class PictureWidget(forms.widgets.Widget): def render(self, name, value, attrs=None): html = Template("""&lt;img src="$link"/&gt;""") return mark_safe(html.substitute(link=value) class AlbumCreateForm(forms.ModelForm): logo = ImageField(widget=PictureWidget) class Meta: model = Album fields = [ 'title', 'artist', 'release_date', 'logo' ] And aslo add in form tag add this property enctype="multipart/form-data"
has comment: http://stackoverflow.com/comment/92315830
type: Answer
has comment: http://stackoverflow.com/comment/92315792

http://stackoverflow.com/q/47810893
tagged with: sqlalchemy
type: Question
type: UnansweredQuestion
has title: SELECT fails after insert duplicate key error
has body: I am running MySQL at its default isolation level (REPEATABLE-READ). My python code uses sqlalchemy to manage a transaction which can (and is quite often) running at the same time within two concurent processes. c.begin(); # this SELECT establishes the transaction snapshot from which all other SELECTs will read data c.execute("SELECT something FROM sometable;") try: c.execute("INSERT INTO othertable (unique_key) VALUES (1)") except sqlalchemy.exc.IntegrityError as e: code, msg = e.orig if code != 1062: raise # duplicate key: another transaction commited the above INSERT so I can't rely on LAST_INSERT_ID rows = c.execute("SELECT * FROM table WHERE unique_key=1") inserted_id = None for id, in rows: inserted_id = id break assert inserted_id is not None else: inserted_id = c.last_insert_id() c.commit() The exact code is obviously a bit more complex with many more queries but the crux of the issue is that this code hits the assert in the exception handler quite often. The reason is that this transaction is often running at the same time in different processes: the SELECT which is triggered on the duplicate key exception fails because the DB snapshot established by the first SELECT does not contain the newly-inserted row (it was inserted by another transaction after the first SELECT and before the INSERT). Now, I understand I could change my SELECTs to use FOR UPDATE and that would punch a hole in the snapshot to read the actual value inserted. However, I am reluctant to do this because it would force me to sprinkle this in quite a few places and I see this as being relatively fragile. Are there other, more robust, more standard, less fugly ways to deal with these concurent inserts (they are a fact of life that I have to deal with).
tagged with: python
score: 0
tagged with: transactions
has answer: http://stackoverflow.com/a/47812312
answer count: 1
tagged with: mysql

http://stackoverflow.com/a/47851973
has body: the problem was my method of making query for search, there are specific ways how you can make query in documents for example \"search key words\" ---> this will look for the exact match in documents (in my case I was making query like this which was wrong) "search key words" ---> Retrieves documents that contains at least one occurrence of the words irrespective if their order for more details kindly view this https://cloud.google.com/appengine/docs/standard/python/search/query_strings#Python_Queries_on_text_and_HTML_fields
score: 0
answers question: http://stackoverflow.com/q/47797480
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47797480
type: Answer

http://stackoverflow.com/a/47842131
answers question: http://stackoverflow.com/q/47841933
score: 3
upvote count: 3
type: Answer
has body: To handle the RuntimeError, use a try-except block: try: popt,pcov = curve_fit(gaus,x,y,p0=[1,mean,sigma]) except RuntimeError: print("No fit found") # whatever you want to do here Some ways to reduce the running time: Reduce the maximal value of function calls maxfev, so that the routine will fail faster: e.g., curve_fit(gaus, x, y, p0=[1,0,1], maxfev=400) Sample your data points. If you have 10000 points, pick 1000 of them at random, and find that there is a Gaussian curve that fits them well, it will probably fit well to the rest of data points. Or at least it will make a good starting point for subsequent refinement of parameters with the full data set.
accepted answer of: http://stackoverflow.com/q/47841933
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/47844573
has comment: http://stackoverflow.com/comment/82653306
has answer: http://stackoverflow.com/a/47844609
downvote count: 0
has comment: http://stackoverflow.com/comment/82658095
score: 1
upvote count: 1
tagged with: http://stackoverflow.com/tag/json
answer count: 1
has comment: http://stackoverflow.com/comment/82653428
has comment: http://stackoverflow.com/comment/82654437
favorite count: 0
type: Question
tagged with: numpy
has title: Convert dtype='<U55201' into numpy array
type: UnansweredQuestion
has body: I have a dataset that I didn't create myself. I disassembled the file in matlab to get the arrays that I am interested in and converted to json there. The array I wanna import into Python is called 'Y_test.mat'. This is part of my code: mat = spio.loadmat('Y_test.mat', squeeze_me=False) print mat This gives me an output like this: {'__version__': '1.0', '__header__': 'MATLAB 5.0 MAT-file, Platform: MACI64, Created on: Sat Dec 16 10:25:44 2017', 'Y_test': array([ u'[1,2,3]'], dtype='&lt;U55201'), '__globals__': []} Now I wanna convert the Y_test into a numpy array but I just can't get it. I tried np.array(ast.literal_eval()) but this gives me the followig error: ValueError: malformed string I am in no way an expert in python so please excuse me if I missed something utterly obvious. Thanks in advance. Alex
tagged with: python

mysql-python
tags question: http://stackoverflow.com/q/47700347
tags question: http://stackoverflow.com/q/47728705
tags question: http://stackoverflow.com/q/47827850
tags question: http://stackoverflow.com/q/47729665
type: Tag
tags question: http://stackoverflow.com/q/47854442
tag name: mysql-python

http://stackoverflow.com/q/47734949
type: Question
has body: I have implemented a big query job application in python and deployed in app engine and need some help with increasing the efficiency of the below filter that filter to just the user email that is fed as input credentials = GoogleCredentials.get_application_default() bq_conn= discovery.build('bigquery', 'v2', credentials=credentials) job_query_dict = [] ###Create the big query client client =bigquery.Client(project=project_id) ###List the jobs in the client jobs = client.list_jobs(all_users=True) # API request print( [job for job in list(client.list_jobs(all_users=True)) if job.user_email==user_email][0]) How do I print the jobs of the user given in the user_email input better than this ?
tagged with: iterator
has comment: http://stackoverflow.com/comment/82432035
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/47998207
has comment: http://stackoverflow.com/comment/82833612
has comment: http://stackoverflow.com/comment/82836102
tagged with: python
has title: Increasing the speed of the python iterator
downvote count: 0
score: 1
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/82430893
tagged with: gcloud
favorite count: 0

http://stackoverflow.com/q/47843529
favorite count: 0
type: Question
tagged with: django
tagged with: python
possible better answer: http://stackoverflow.com/a/47844457
score: 2
has answer: http://stackoverflow.com/a/47844457
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47844584
answer count: 2
has title: Does my Django app have to be the same name as the project directory?
upvote count: 2
has body: I've pulled my django repo from bitbucket onto my digital ocean server. My project folder name in my server is project whereas my initial app from my repo (the one with settings.py is called app. Does this cause any problems? Because I know when you create a django project offline, the first directory is always the same as the parent directory.
has answer: http://stackoverflow.com/a/47844584
downvote count: 0

http://stackoverflow.com/comment/82488859
has text: It looks like you've found a bug in p4a (it should exit when it says it will, instead of crashing on the following line), but the real issue seems to be that you haven't passed p4a the location of the Android SDK or NDK. Have you tried to do that some other way?
comment on: http://stackoverflow.com/q/47746196
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/47802521
has comment: http://stackoverflow.com/comment/82578890
tagged with: praw
accepted answer: http://stackoverflow.com/a/47893387
has comment: http://stackoverflow.com/comment/82566507
favorite count: 0
type: Question
tagged with: reddit
has comment: http://stackoverflow.com/comment/82570422
downvote count: 0
has comment: http://stackoverflow.com/comment/82566788
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47893387
score: 3
has title: How can I get all submission id's from a subreddit?
has comment: http://stackoverflow.com/comment/82578824
upvote count: 3
answer count: 1
has body: I'm trying to write a chat bot and I want to feed it data from specific subreddits, e.g. https://www.reddit.com/r/leagueoflegends/ I'm already able to crawl all comments while recursively looping reddit = praw.Reddit() submission = reddit.submission(submissionId) #id: https://redd.it/7jjtoq -&gt; "7jjtoq" I have already tried different approaches to receive (all) submission ids from the subreddit: subreddits = reddit.subreddits.search_by_name('leagueoflegends', include_nsfw=True, exact=False) or for submission in reddit.get_new(limit=300): ... Is there any way to receive all of the id's from a subreddit?

http://stackoverflow.com/q/47756425
has answer: http://stackoverflow.com/a/47756850
type: Question
has body: I keep getting this error when running my code: ValueError: list.remove(x): x not in list With this code I'm supposed to check the elements in lst and in listOfOperatorsDomains. If they are the same (I used [if x in y] and not [if x == y] because of the context), then I append those two values to another list (listOfRequestsAssigned) and remove the element y from lst. However, the line where I remove the element y is giving me that error. My code: for y in lst: for k in listOfOperatorsDomains: if y[2] in k: element = listOfOperatorsDomains.index(k) listOfRequestsAssigned.append([y[0],operators[element][0],"assigned"]) lst.remove(y) return listOfRequestsAssigned
has comment: http://stackoverflow.com/comment/82474282
upvote count: 0
type: UnansweredQuestion
tagged with: list
has title: ValueError: list.remove(x): x not in list (python 3.2)
answer count: 1
downvote count: 1
tagged with: python
score: -1
favorite count: 0

http://stackoverflow.com/comment/82583822
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/47811265
has text: how are you displaying your form? With formsets you need to also add the `managementform` in the template.

http://stackoverflow.com/q/47706005
tagged with: scipy
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/47708171
has body: I made a function f that takes a long time to run. The constraints are calculated at the end of f's routine. How can I return these constraints to cobyla without evaluating f twice? import numpy as np from scipy.optimize import fmin_cobyla as mini def f(x, returncons=True): if returncons: return x[1] - x[0] else: return (x[0] - 2)**2 + 4 * (x[1] -x[0]**2)**2 x_opt = mini(f, [1., 1.], args=(False,), cons=f)
has title: Constrained optimization where the constraint is computed as a part of objective function
has comment: http://stackoverflow.com/comment/82372182
has comment: http://stackoverflow.com/comment/82375137
tagged with: python
has comment: http://stackoverflow.com/comment/82372276
tagged with: optimization
has answer: http://stackoverflow.com/a/47708171
type: AnsweredQuestion
upvote count: 1
score: 1
answer count: 1
downvote count: 0

http://stackoverflow.com/q/47723131
upvote count: 1
accepted answer: http://stackoverflow.com/a/47723173
has answer: http://stackoverflow.com/a/47723166
favorite count: 0
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47723173
tagged with: pandas
score: 1
tagged with: dataframe
tagged with: python
type: Question
has body: I'm looking for a combination of two DataFrame structures in Python using a (shared) index value column. Data snippet: d1 = {'col1': ['entry1', 'entry2', 'entry3'], 'col2': [1, 2,3]} df1 = pd.DataFrame(data=d1) d2= {'col1': ['entry2', 'entry3', 'entry1'], 'priority': [4, 2 , 7]} df2 = pd.DataFrame(data=d2) The result should be something like col1 col2 priority ---- ---- ---- entry1 1 7 entry2 2 4 entry3 3 2 How can I achieve that?
has title: How to combine two DataFrame Structures in Python
answer count: 2
downvote count: 0
possible better answer: http://stackoverflow.com/a/47723166

http://stackoverflow.com/a/47736127
has body: Just merge + the lists together, and sort based on the second element of each list with operator.itemgetter(): from operator import itemgetter a = [[1,128,"11:18:23.456",2,0,0,"P"],[2,1345,"22:18:23.456",2,1,0,"Q"],[3,1365,"24:18:23.456",1,0,0,"N"]] b = [[1,128,"11:18:23.456",2,0,0,"P"],[2,1345,"22:18:23.456",2,1,0,"Q"],[2,1345,"22:18:23.456",2,1,0,"Q"]] c_before_sort = a + b c_after_sort = sorted(c_before_sort, key = itemgetter(1)) print(c_after_sort) # [[1, 128, '11:18:23.456', 2, 0, 0, 'P'], [1, 128, '11:18:23.456', 2, 0, 0, 'P'], [2, 1345, '22:18:23.456', 2, 1, 0, 'Q'], [2, 1345, '22:18:23.456', 2, 1, 0, 'Q'], [2, 1345, '22:18:23.456', 2, 1, 0, 'Q'], [3, 1365, '24:18:23.456', 1, 0, 0, 'N']] # easy peezy lemon squeezy
answers question: http://stackoverflow.com/q/47735855
type: Answer
score: 0

http://stackoverflow.com/comment/82594455
type: Comment
has text: Did you include the '=' character between --host-rules and "MAP.."? It is missing in your question.
comment on: http://stackoverflow.com/a/47815507
score: 0
type: AnswerComment

http://stackoverflow.com/q/47790164
has title: Add domain on fields.Reference
has body: I want to a add a domain on a fields.Reference. class CategoryWizard(models.TransientModel): _name = 'category.wizard' _description = 'Category Tree Manipulation' tree1_type = fields.Reference(selection=[('product.public.category', 'Website Category Tree'), ('product.category', 'Internal Category Tree')], string="First Tree", domain="['parent_id', '=', False]") tree2_type = fields.Reference(selection=[('product.public.category', 'WebSite Category Tree'), ('product.category', 'Internal Category Tree')], string="Second Tree") In my example i want only to show the Category Tree Head with the domain="['parent_id', '=', False]") after selecting the Model
answer count: 1
downvote count: 0
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/47791800
favorite count: 0
tagged with: odoo
score: 1
type: Question
type: UnansweredQuestion

http://stackoverflow.com/q/47822586
has comment: http://stackoverflow.com/comment/82637780
has title: Cannot set up robotframework for PyCharm
has comment: http://stackoverflow.com/comment/82609422
tagged with: robotframework
answer count: 0
type: UnansweredQuestion
downvote count: 0
tagged with: selenium
has comment: http://stackoverflow.com/comment/82636750
tagged with: testing
has comment: http://stackoverflow.com/comment/82609398
has comment: http://stackoverflow.com/comment/82637194
upvote count: 1
score: 1
tagged with: python
has body: I am struggling with install robotframework. I have downloaded and installed fresh Python 2.7.14. I have added it and scripts to PATH. Next I have downloaded robotframework with pip (pip install robotframework). Next I have downloaded and installed selenium library (pip install robotframework-seleniumlibrary). Next I have downloaded and installed Intellibot plugin for PyCharm. Now I see that *.robot files are associated with Intellibot (robot icon) BUT after I wrote this simple "test": *** Settings *** Documentation simple test Library SeleniumLibrary *** Test Cases *** This is some test case Open Browser http://google.pl chrome Close Browser SeleniumLibrary in Settings is not marked as error. I think everything is good there. There is no autocomplete for "Open Browser" and "Close Browser" commands. Both are with red underline and info "Keyword definition not found". After I run this test I got error: "SessionNotCreatedException: Message: Unable to find a matching set of capabilities" (browser don't open at all). Need some advice here...
favorite count: 0
type: Question

http://stackoverflow.com/comment/82447034
type: Comment
type: QuestionComment
score: 0
has text: @furas I use MacOS
comment on: http://stackoverflow.com/q/47743402

http://stackoverflow.com/a/47792768
type: Answer
upvote count: 2
score: 2
accepted answer of: http://stackoverflow.com/q/47792669
downvote count: 0
type: AcceptedAnswer
has body: It is going to /thankyou/ because you have hardcoded the URL /thankyou/: return HttpResponseRedirect('/thankyou/') You can redirect to /test2/thankyou/ by changing the code to: return HttpResponseRedirect('/test2/thankyou/') However the best practice is to reverse the URL instead of hardcoding it: from django.urls import reverse return HttpResponseRedirect(reverse('thankyou')) This can be simplified using the redirect shortcut: from django.shortcuts import redirect return redirect('thankyou')
answers question: http://stackoverflow.com/q/47792669

http://stackoverflow.com/q/47734132
tagged with: http://stackoverflow.com/tag/xml
has answer: http://stackoverflow.com/a/47734332
type: Question
tagged with: python-3.x
answer count: 1
has comment: http://stackoverflow.com/comment/82429074
has comment: http://stackoverflow.com/comment/82428843
accepted answer: http://stackoverflow.com/a/47734332
type: AnsweredQuestion
score: 0
has title: Unable to parse XML from file with ElementTree in Python 3
tagged with: python
has body: I'm trying the module ElementTree of Python 3 to parse XML but I can't make it work. I have a XML file: <?xml version="1.0" encoding="UTF-8"?> Name 1 79 Name 2 382 And I want to check, given a name, if it exist on the XML and get the number. So when I write the code, I do: show_input = show.lower() file_to_parse = findXMLshowFile(show_input) file_path = os.path.join(LOCATION_URL, file_to_parse) root = etree.parse(file_path) shows = root.findall('show') for element in shows: name = element.find('name').text if name.lower() == show: show_name = name show_number = int(element.find('number').text) break return [show_name, show_number] I get empty name and number. Debugging, when I do shows = root.findall('show') it has 2 objects but they are empty. I'm reading the documentation and I don't know what I'm doing wrong. Someone can tell me where it's my mistake? Regards
tagged with: elementtree

http://stackoverflow.com/comment/82512879
type: QuestionComment
has text: Well, I guess that was mentioned in comments somewhere: That the behaviour of the `print` function changed with Python 3.3 and that change was not backported.
comment on: http://stackoverflow.com/q/47772711
score: 0
type: Comment

http://stackoverflow.com/a/47709277
has body: Have a look into the below code logging in the file can be done as per requirement : for i in range(0,n): try: list =['name','age'] for word in list: if word in str: print('output verified') else: # instead of a generic exception a specific exception can be raised raise Exception('unmatched values') print('unmatched values for iteration n') except Exception: TestCase.status = FAIL print "Log you result in a file " # raise ex - need not be here Happy Coding :)
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47708963
answers question: http://stackoverflow.com/q/47708963
type: Answer

http://stackoverflow.com/comment/82458092
type: QuestionComment
has text: BTW: do you have to create function inside another function ? can't you create normal method in class - with `self` ?
score: 0
comment on: http://stackoverflow.com/q/47748918
type: Comment

http://stackoverflow.com/a/47838688
accepted answer of: http://stackoverflow.com/q/47838632
has comment: http://stackoverflow.com/comment/82642082
has comment: http://stackoverflow.com/comment/82641793
has comment: http://stackoverflow.com/comment/82734504
score: 10
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/47838632
has comment: http://stackoverflow.com/comment/82714320
has body: You'll want to read the Django documentation about Password Validation. To summarize, you'll need to update the AUTH_PASSWORD_VALIDATORS setting in your settings.py. Django comes with a few built-in password validators: UserAttributeSimilarityValidator (checks for similarity between the password and a set of attributes of the user) MinimumLengthValidator (checks whether the password meets a minimum length) CommonPasswordValidator (checks whether the password occurs in a list of common passwords) NumericPasswordValidator (checks whether the password isn’t entirely numeric) Based on the example validations you state in your question, you'll want to use the MinimumLengthValidator and the UserAttributeSimilarityValidator. Since you are using a form, you need to manually trigger the password validation as described in the Django docs) by calling django.contrib.auth.password_validation.validate_password when you validate the form.
upvote count: 10
has comment: http://stackoverflow.com/comment/82641844
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82654618

ipv6
tag name: ipv6
tags question: http://stackoverflow.com/q/47725484
type: Tag

http://stackoverflow.com/comment/82628561
has text: @user1050619 is this a certain and very near future or a "I think that perhaps at some point in the future I might add other methods" future ?-)
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47832583
score: 0

http://stackoverflow.com/q/47822062
has title: Plot graph with pyplot using input from tkinter spinbox
score: 0
tagged with: tkinter
answer count: 1
has body: I am working in a project which needs to plot a graph dynamically as the inputs in a tkinter spinbox is changed. I have a sample code: from tkinter import * from tkinter import font from tkinter.font import Font from tkinter import messagebox print("'Tkinter' module is found as tkinter.") import matplotlib matplotlib.use('TkAgg') import matplotlib.pyplot as plt from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg from matplotlib.backend_bases import key_press_handler from matplotlib.figure import Figure print("Importing matplotlib from libraries.") master = Tk() def ok(x_val=1000,y_val=20): fig = Figure(figsize=(5,5),dpi=70) ax = fig.subplots() ax.set_title("Right Ear") ax.set_ylabel("db HL") ax.set_xlabel("Frequency") ax.set_xlim(100,9000) ax.set_ylim(130,-10) ax.set_facecolor("#ffd2d2") x = [125,250,500,1000,2000,4000,8000] ticks = [125,250,500,"1K","2K","4K","8K"] xm = [750,1500,3000,6000] ax.set_xscale('log', basex=2) ax.set_xticks(x) ax.set_xticks(xm, minor=True) ax.set_xticklabels(ticks) ax.set_xticklabels([""]*len(xm), minor=True) ax.yaxis.set_ticks([120,110,100,90,80,70,60,50,40,30,20,10,0,-10]) ax.plot([x_val],[y_val],'r+',markersize=15.0,mew=2) ax.grid(color="grey") ax.grid(axis="x", which='minor',color="grey", linestyle="--") canvas = FigureCanvasTkAgg(fig, master=master) canvas.show() canvas.get_tk_widget().grid(column=0,row=2,columnspan=3,rowspan=15) def action(): print(spin.get()) canvas.draw() ok(spin.get(),10) spin = Spinbox(master, from_=125,to=8000,command=action) spin.grid(column=5,row=2) ok() This code does not change the plot, I cannot understand how to change it, to be precise, how to use canvas.draw() here to do the work. The spinbox has value range from 125 to 8000, I could not figure out how to take the value of the spinbox every time it changes (can use command= but how to implement) and feed it to the x axis of ax.plot() and plot dynamically. As the value of spinbox changes the plot also changes to the n…
tagged with: plot
type: Question
accepted answer: http://stackoverflow.com/a/47822742
linked to: http://stackoverflow.com/q/47843511
tagged with: matplotlib
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47822742

http://stackoverflow.com/q/47819417
has comment: http://stackoverflow.com/comment/82601014
has title: Ascending order sorting in list of dict
upvote count: 0
has comment: http://stackoverflow.com/comment/82601239
answer count: 1
downvote count: 3
has body: How can I sort a list in ascending order without key matching? Every key is unique and need sorting keys. Input: [{23: (1, 5)}, {59: (2, 3)}, {45: (2, 9)}, {28: (3, 6)}] The output should be like this (Sorting based on keys of dict): [{23: (1, 5)}, {28: (3, 6)}, {45: (2, 9)}, {59: (2, 3)}]
has comment: http://stackoverflow.com/comment/82601418
has comment: http://stackoverflow.com/comment/82601477
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/82600898
has comment: http://stackoverflow.com/comment/82600921
score: -3
has comment: http://stackoverflow.com/comment/82601005
tagged with: python
tagged with: sorting
tagged with: dictionary
has comment: http://stackoverflow.com/comment/82601176
has comment: http://stackoverflow.com/comment/82601333
accepted answer: http://stackoverflow.com/a/47819459
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/72899
has answer: http://stackoverflow.com/a/47819459
tagged with: list

http://stackoverflow.com/comment/82485632
type: AnswerComment
comment on: http://stackoverflow.com/a/47762109
score: 0
type: Comment
has text: Probably need to remove the currency sign too.

http://stackoverflow.com/comment/82393567
type: Comment
comment on: http://stackoverflow.com/a/47709026
type: AnswerComment
score: 0
has text: Indeed, they have the exact same behavior and are just a matter of preference. Don't forget to select the answer if you consider it answers your question the best.

http://stackoverflow.com/q/47747136
downvote count: 0
tagged with: neural-network
tagged with: keras
tagged with: tensorflow
favorite count: 0
has comment: http://stackoverflow.com/comment/82461601
type: Question
score: 3
has title: Keras Conv1D with dilation and "causal" padding isn't reducing the size of the sequence
tagged with: convolution
type: UnansweredQuestion
tagged with: python
has body: In Keras, if you run x = Input(shape=(seq_length, dim)) y = Conv1D(num_filts, 2, dilation_rate=8, padding="causal")(x) print(y.shape) Then the shape printed out will be (?, seq_length, dim), which means the sequence length wasn't changed at all. But isn't this incorrect? Because the dilation makes the effective kernel width of the convolution 9, shouldn't the sequence length of the output be decremented by 8 because the causal kernel needs 9 values to perform its dot product and so doesn't output on the first 8 samples in the sequence? Is this a problem with Keras?
has comment: http://stackoverflow.com/comment/85206689
answer count: 0
upvote count: 3

http://stackoverflow.com/comment/82521093
type: QuestionComment
comment on: http://stackoverflow.com/q/47779391
has text: *Before you decide to use this or publish it anywhere:* Don't reinvent the wheel. You're using a non-CS RNG (Mersenne twister) to create passwords. That's a no-go. There's plenty of packages out there that do the same thing quicker and more safely and that have a friendly API. If you insist on doing this yourself, use `os.urandom` or the `secrets` objects as a source for randomness.
score: 0
type: Comment

http://stackoverflow.com/q/47852919
has comment: http://stackoverflow.com/comment/82671034
score: 1
has answer: http://stackoverflow.com/a/47853528
tagged with: kafka-consumer-api
tagged with: python
has title: Python - Kafka: consumer failing
has body: I have a simple Producer-Consumer setup: 1 producer(as a thread) and 2 consumers(as 2 processes). The run method of producer: def run(self): producer = KafkaProducer(bootstrap_servers=self.bootstrap_servers, api_version=(0, 10)) while not self.stop_event.is_set(): self.logger.info("Checking for new changes") self.check_for_new_changes(producer) self.logger.info("Sleeping for {minutes} minutes...".format(minutes=self.time_to_sleep / 60)) time.sleep(self.time_to_sleep) producer.close() Basically it checks for changes, sends messages if new changes found and then goes to sleep for 5 minutes. The run method: def run(self): if self.group_id: consumer = KafkaConsumer(bootstrap_servers=self.bootstrap_servers, consumer_timeout_ms=1000, api_version=(0, 10), group_id=self.group_id) else: consumer = KafkaConsumer(bootstrap_servers=self.bootstrap_servers, consumer_timeout_ms=1000, api_version=(0, 10)) consumer.subscribe(['new_change']) while not self.stop_event.is_set(): for msg in consumer: self.logger.info("New message:\n{msg}".format(msg=msg)) self.process_new_change(json.loads(msg.value)) if self.stop_event.is_set(): consumer.close() return consumer.close() It seems to work fine but after running for a while I get these messages in the coordinator log: [2017-12-17 02:06:40,639] INFO [GroupCoordinator 0]: Member kafka-python-1.3.5-f5cdcad3-bc1a-4623-a42b-f5de5e8bded1 in group meta_data_consumer has failed, removing it from the group (kafka.coordinator.group.GroupCoordinator) [2017-12-17 02:06:40,659] INFO [GroupCoordinator 0]: Preparing to rebalance group meta_data_consumer with old generation 15 (__consumer_offsets-6) (kafka.coordinator.group.GroupCoordinator) [2017-12-17 02:06:40,659] INFO [GroupCoordinator 0]: Group meta_data_consumer with generation 16 is now empty (__consumer_offsets-6) (kafka.coordinator.group.GroupCoordinator) [2017-12-17 02:06:41,784] INFO [GroupCoordinator 0]: Member kafka-python-1.3.5-bdea8ce3-922f-4ee1-9959-13341e1730f5 in group failures_consumer …
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/82670771
accepted answer: http://stackoverflow.com/a/47853528
downvote count: 0
answer count: 1
upvote count: 1
favorite count: 0
type: Question
tagged with: kafka-producer-api

http://stackoverflow.com/a/47742291
answers question: http://stackoverflow.com/q/47742258
score: 2
upvote count: 2
downvote count: 0
has body: You can perform the desired action using deepcopy. Here's an example: import copy listA = [1,2,3,4] listB = copy.deepcopy(listA) listB[0] = 7 print("List A: {}".format(listA)) # List A: [1,2,3,4] print("List B: {}".format(listB)) # List B: [7,2,3,4] This will create an entirely new list listB with the same values as listA. When performing a simple assignment, such as: listA = [1,2,3,4] listB = listA print(listA is listB) # True this will print True as the listA and listB refer to the same object. A deepcopy will create a new object: import copy listA = [1,2,3,4] listB = copy.deepcopy(listA) print(listA is listB) # False Alternatively, you can create a new list using the list constructor. listA = [1,2,3,4] listB = list(listA) print(listA is listB) # False
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/47742258
type: Answer

http://stackoverflow.com/q/47743692
favorite count: 0
type: Question
score: 9
answer count: 2
tagged with: telegram
has answer: http://stackoverflow.com/a/54686250
type: UnansweredQuestion
has body: I'm having a problem forwarding messages with multiple media files (in my particular case, photos). I'm using forwardMessage method to forward the message that user sends to bot (which, in some cases, might contain more than one photo): bot.forwardMessage(admin_id, from_chat_id, message_id) But, the thing is, according to Telegram API v3.5, the message which contain media group breaks up into array of messages, and hence the bot breaks up the message from user into multiple messages. E.g. if user have sent a message with 3 photos, then the bot forwards 3 messages, each of which contains a photo. What I want is to forward a message with multiple media files as it is, as one message, not as multiple messages. I know that probably I can take each photo from each message that the bot receives, put them one-by-one into array, and then send it from the bot using sendMediaGroup method, but I'd like to know if I can get it working with forwardMessage method. Thanks in advance.
downvote count: 0
has answer: http://stackoverflow.com/a/47745521
has title: Forward a message with multiple media files using bot Telegram API
tagged with: bots
upvote count: 9
has comment: http://stackoverflow.com/comment/126740581
tagged with: python
linked to: http://stackoverflow.com/q/71440069
has comment: http://stackoverflow.com/comment/107662892

http://stackoverflow.com/comment/82710825
comment on: http://stackoverflow.com/a/47833125
score: 0
has text: "adb shell input tap x y" This command fast enough works well, so i presume appium is just to slow ... However i have found another solution which works fine (but not really pretty) : import shlex toto = 'adb shell input tap 100 100 && input tap 100 100 && input tap 100 100 && input tap 100 100 && input tap 100 100 && input tap 100 100 && input tap 100 100 && input tap 100 100 && input tap 100 100 && input tap 100 100' subprocess.Popen(shlex.split(toto),stdin = subprocess.PIPE) (sorry for the double post)
type: Comment
type: AnswerComment

http://stackoverflow.com/q/47740814
answer count: 2
has answer: http://stackoverflow.com/a/78646073
downvote count: 0
has title: How do you move a pygame.circle?
favorite count: 0
type: Question
has body: I am trying to make a circle that moves but I don't know how to make it work. I am using pygame as the package. I think it'll work if you update the circle but I don't know how to do that. import os, sys, math, pygame, pygame.mixer from pygame.locals import * black = (0,0,0) red = (255,0,0) green = (0,255,0) blue = (0,0,255) white = (255,255,255) run_me = True screen_size = screen_width, screen_height = 600, 400 screen = pygame.display.set_mode(screen_size) pygame.display.set_caption('ha ha ha ha ha') clock = pygame.time.Clock() fps_limit = 60 #circle colorcircle = (red) posx = 300 posy = 200 circle = pygame.draw.circle(screen, colorcircle, (posx, posy), 50) while run_me: clock.tick(fps_limit) for event in pygame.event.get(): if event.type == pygame.QUIT: run_me = False if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: posx = posx - 10 if event.type == pygame.KEYDOWN: if event.key == pygame.K_RIGHT: posx = posx + 10 if event.type == pygame.KEYDOWN: if event.key == pygame.K_UP: posy = posy + 10 if event.type == pygame.KEYDOWN: if event.key == pygame.K_DOWN: posy = posy - 10 pygame.display.flip() pygame.quit() I want the to circle move somewhere depending on input. However, the circle does nothing!
type: UnansweredQuestion
tagged with: python
tagged with: pygame
score: 4
has answer: http://stackoverflow.com/a/47741049
upvote count: 4

http://stackoverflow.com/comment/82525486
type: QuestionComment
comment on: http://stackoverflow.com/q/47781895
has text: Look at `res.content`. That URL returns a form. You need to figure out how fill out that form first (what values would you enter manually?). From there you start building a POST request to download each file.
score: 0
type: Comment

http://stackoverflow.com/comment/82576358
has text: Could you please adapt your answer to include the extra custom transformer? In that case I will gladly accept it.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47792121
type: Comment

http://stackoverflow.com/comment/82448574
type: Comment
has text: You need itertools.[permutations](https://docs.python.org/3/library/itertools.html#itertools.permutations)/[combinations](https://docs.python.org/3/library/itertools.html#itertools.combinations).
score: 1
comment on: http://stackoverflow.com/q/47744234
type: QuestionComment

http://stackoverflow.com/comment/82449165
type: Comment
has text: To be sure, but there are some details -- ie. the need to close stdout after writing to it -- that might make it appropriate to show both forms explicitly.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47744500

http://stackoverflow.com/comment/82555764
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/47793671
score: 0
has text: yes @gayo . 'saleRatio' is basically revenue percentage earned by that product.

http://stackoverflow.com/comment/82644446
comment on: http://stackoverflow.com/q/47840056
type: QuestionComment
type: Comment
score: 0
has text: from tsne import bh_sne

http://stackoverflow.com/comment/82524462
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/47781373
type: Comment
has text: I tried it but it still had and issue with the index range. I also tried just to matrix.append([]) without an if, but it still had the same error...

http://stackoverflow.com/q/47707293
tagged with: python
has comment: http://stackoverflow.com/comment/82376463
tagged with: ms-access-2010
has comment: http://stackoverflow.com/comment/82376433
score: 1
has comment: http://stackoverflow.com/comment/82381094
has body: I am using pyodbc driver to get long binary data from Microsoft Access i.e. .mdb file. Following is the code snippet and output. code: import pyodbc conn = pyodbc.connect('DRIVER={Microsoft Access Driver (*.mdb)};DBQ=d:\\testarea\\test.mdb') sqlcommand = 'select * from FORMULA_GROUP' result = cur.execute(sqlcommand).fetchall() result[0][0] but I get this string as output b'\x01\x06\xa4w\xae\xd6\xad\xe3\x01\x00\x04\x00\xff\xff\x01\x00\x08\x00CFormula\x05\x00\x080G9yHh&gt;d\x02\x00\x00\x00\x01\x00\x00\x00\xc8B\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x16w\x82x\x8f\x8a\xe4@\x00\x07A\x04S\x06\x00\xff\xff\x01\x00\n\x00CDyeAmount\x02\x0cA3302||A3302\x120G;6QAfb||66455C17\n\xd7\xa3=\x01\x00\x03\x80\x02\x0cA3317||A3317\x120G;6Xdh0||151273AE\x17\xd9N?\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' anyone know how to decode it??
answer count: 1
downvote count: 0
upvote count: 1
has title: use pyodbc to read Microsoft access long binary data
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47708526
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82374821

http://stackoverflow.com/comment/82546224
comment on: http://stackoverflow.com/q/47791576
score: 0
type: Comment
type: QuestionComment
has text: yes, template extends base.html and html tags are correct. If I put the example-form directly in post_detail.html, the csrf_token/csrf protection works just fine. Is it maybe because of mark_safe()?

http://stackoverflow.com/a/47770498
downvote count: 0
has body: Here is a way you can achieve the desired result. Lets take example of demo.py which have class Sample Sample class has init ,getting_path() as methods class Sample(object): def __init__(self,path,device): self.device=device self.path = path def getting_path(self): return self.path Lets use these methods in Robotfile *** Settings *** #in the Library section you reference python class in below format # (file.class_name) so file is demo.py and class is Sample Library demo.Sample ${path} ${device} WITH NAME obj #path and device are two arguments required by __init__,'obj' will be used to #access the methods in python class Library Collections *** Variables *** ${path} c: ${device} samsung *** Test Cases *** Test Test_python_class *** Keywords *** Test_python_class #with obj you now call the method of python file ${result} = obj.getting_path #if method need any argument , this can be passed like #${result} = obj.getting_path ${arg1} ${arg2} log to console ${result}
answers question: http://stackoverflow.com/q/47765335
upvote count: 4
score: 4
type: Answer
has comment: http://stackoverflow.com/comment/135667878

http://stackoverflow.com/comment/82398100
has text: As noted previously, without more information we can't really help more than this.
type: Comment
comment on: http://stackoverflow.com/a/47710363
score: 0
type: AnswerComment

http://stackoverflow.com/q/47781571
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/82535760
downvote count: 0
tagged with: ssh
tagged with: python
tagged with: paramiko
linked to: http://stackoverflow.com/q/373639
answer count: 0
score: 1
upvote count: 1
has body: I'm trying to set a new password on a router using paramiko. In Ubuntu terminal it looks like that: admin:~$ ssh admin@IP_address IP_address's password: password You logged in: router command line : router_1&gt;set_password Changing admin's password type old password : type new password : retype new password : So when I'm trying to do the same with python as soon as it comes to set password import paramiko ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(hostname='IPaddress', username='admin', password='password') stdin, stdout, stderr = ssh.exec_command(command='set_password') it pops out a window or a line asking to input old password Is it possible to input thous passwords automatically ?
has title: paramiko. answering questions asked by equipment
duplicate of: http://stackoverflow.com/q/373639
favorite count: 0
type: Question
tagged with: linux

http://stackoverflow.com/comment/82630360
comment on: http://stackoverflow.com/q/47833620
type: QuestionComment
has text: What URL are you going to, and what do you actually see?
score: 1
type: Comment

http://stackoverflow.com/comment/82389806
comment on: http://stackoverflow.com/a/47714371
score: 0
type: AnswerComment
has text: Actually, it is the same question but thank you very much
type: Comment

http://stackoverflow.com/comment/82576772
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/47807770
has text: So what is `if True`? Does it have any meaning?
type: Comment

http://stackoverflow.com/q/47777460
type: Question
has comment: http://stackoverflow.com/comment/101393593
has title: Matlab datetime in Python
upvote count: 5
type: UnansweredQuestion
has body: I am trying to read some Matlab files with waveforms in which the timestamp was stored in Matlab datetime format (not datenum, for which there are several questions already). I get the data with: import scipy.io as spio mat_data = spio.loadmat(file_path, squeeze_me=True) The variables in Matlab are t and data, and in mat_data I get: In[64]: mat_data Out[64]: {'None': MatlabOpaque([ (b't', b'MCOS', b'datetime', array([3707764736, 2, 1, 1, 1, 1], dtype=uint32))], dtype=[('s0', 'O'), ('s1', 'O'), ('s2', 'O'), ('arr', 'O')]), '__function_workspace__': array([[ 0, 1, 73, ..., 0, 0, 0]], dtype=uint8), '__globals__': [], '__header__': b'MATLAB 5.0 MAT-file, Platform: PCWIN64, Created on: Fri Dec 01 14:44:33 2017', '__version__': '1.0', 'data': array([ 0.70606027, 0.70559802, 0.70583525, ..., 20.45188265, 20.45204609, 20.4512548 ])} I think the datetime data from t is in the keys 'None' and 'function_workspace', but I am not capable to understand how to get the time from them. mat_data['__function_workspace__'].shape Out[65]: (1, 20736704) mat_data['data'].shape Out[66]: (2591959,) Any idea on how to read those values?
tagged with: datetime
tagged with: python
tagged with: matlab
score: 5
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/101105988
favorite count: 0

http://stackoverflow.com/q/47844877
has answer: http://stackoverflow.com/a/47848454
answer count: 2
upvote count: 0
tagged with: scrapy
downvote count: 1
favorite count: 0
type: Question
has body: I am using the following code to bring back prices from an ecommerce website: response.css('div.price.regularPrice::text').extract() but getting the following result: '\r\n\t\t\tDhs 5.00\r\n\t\t\t\t\t\t\t\t', '\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t', I do not want the slashes and letters and only the number 5. How do I get this?
has comment: http://stackoverflow.com/comment/82660970
has title: Getting slashes and letters while I only want number
type: UnansweredQuestion
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/82660987
has answer: http://stackoverflow.com/a/47844982

http://stackoverflow.com/comment/82422557
type: QuestionComment
comment on: http://stackoverflow.com/q/47730861
type: Comment
has text: However, you should not be using `input` in Python 2: it evaluates your input, which can do unexpected things (like it's doing here), and it can be a security hole. Just use `raw_input`. Or switch to Python 3.
score: 0

http://stackoverflow.com/a/47738072
answers question: http://stackoverflow.com/q/47731633
type: Answer
has body: ok, its sorted at tsql/FreeTDS level. Figured out the password policy &amp; password I changed wasn't saved to docker image. had to enable TDS logging and it was obvious. When I tried with old password, it worked like I was stupid. TDS protocol version seems to unofficially support SQL Server 2017 Developer. many thanks @cricket_007
score: 0

http://stackoverflow.com/comment/82481962
comment on: http://stackoverflow.com/a/47759253
score: 0
type: AnswerComment
has text: I suggest you google "python command line arguments" or "python parseargs" to find some documentation and tutorials.
type: Comment

http://stackoverflow.com/comment/82427301
comment on: http://stackoverflow.com/q/47733345
score: 0
type: Comment
type: QuestionComment
has text: Why would you enter all this code at the Python prompt? Write your code in a file.

http://stackoverflow.com/a/47801935
has body: Using stack with groupby df.set_index('id').stack().reset_index().groupby(0).id.apply(list) Out[137]: 0 a1 [P1, P4] a2 [P1, P2] a3 [P4] a4 [P1, P2] a5 [P3] a6 [P2] a7 [P2, P3] Name: id, dtype: object
answers question: http://stackoverflow.com/q/47801886
score: 1
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47801886
upvote count: 1
has comment: http://stackoverflow.com/comment/82567029
has comment: http://stackoverflow.com/comment/82566038
has comment: http://stackoverflow.com/comment/82565284
type: Answer

http://stackoverflow.com/comment/82499717
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/47769232
has text: The actual response is much longer - 3000-4000 characters. I just pasted a representative portion of it above. The entire structure of the response is exactly the same as what I have posted.
score: 0

http://stackoverflow.com/comment/82766005
type: AnswerComment
comment on: http://stackoverflow.com/a/47897178
type: Comment
has text: Ok, Thanks. I will try BOW and other distance measures and check if it works for me. If possible, kindly upvote the question so that others who know some other approaches can share their ideas too.
score: 0

http://stackoverflow.com/q/47699695
type: Question
has comment: http://stackoverflow.com/comment/82359666
has answer: http://stackoverflow.com/a/47700040
has comment: http://stackoverflow.com/comment/82359752
has comment: http://stackoverflow.com/comment/82359772
has answer: http://stackoverflow.com/a/47700030
has comment: http://stackoverflow.com/comment/82359693
tagged with: python
tagged with: python-3.6
downvote count: 1
has comment: http://stackoverflow.com/comment/82359542
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/82359932
answer count: 3
has body: I have a CSV file I'd like to parse as a Dict, so that the first item with the key of "key" can be unpacked to a variable, then the rest of the values as a list of keyed languages. Is there a nice, clean way of doing this? My CSV is like so: key,english,spanish wanna_play_a_game,"Wanna play a game?","¿Quiero jugar a un juego?" something_else,"Hello!","hola!" Dict object as such: [{'key': 'wanna_play_a_game', 'english': 'Wanna play a game?', 'spanish': '¿Quiero jugar a un juego?'}, {'key': 'something_else', 'english': 'Hello', 'spanish': 'hola!'}] I did have a go but then realised that unpacking isn't the same with dicts (I assume) because they're not ordered like with lists. Am I overcomplicating things and should just saved the row['key'] to a variable and then remove it from the dict? Python isn't my bread &amp; butter language so I'm not that knowledgable on the more magicky bits of the syntax. This is what I was kinda getting at before realising I'm lost: import csv class Translate: def __init__(self): self.translations = self.readCSV('translations.csv') def readCSV(self, filename): with open(filename, 'rt') as csvfile: reader = csv.DictReader(csvfile) return [dict(d) for d in reader] def parse(self, line): # for t_key, *langs in self.translations: # for k, (t_key, *langs) in self.translations: # ... some magic function? The basic thing I'm trying to get is t_key to be "wanna_play_a_game" and langs to be ('english': 'Wanna play a game?', 'spanish': '¿Quiero jugar a un juego?')
has comment: http://stackoverflow.com/comment/82359650
possible better answer: http://stackoverflow.com/a/47699816
upvote count: 1
has title: Argument unpacking with a Dict
linked to: http://stackoverflow.com/q/6612769
has answer: http://stackoverflow.com/a/47699816
accepted answer: http://stackoverflow.com/a/47700040
favorite count: 0

http://stackoverflow.com/a/47704471
score: 1
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82380602
upvote count: 1
has comment: http://stackoverflow.com/comment/82369405
accepted answer of: http://stackoverflow.com/q/47704438
has body: UPDATE: same answer applied to an updated DF: In [134]: df Out[134]: 0 1 2 0 0.414143 13.898568 17.322851 1 24.348445 0.514046 36.663878 0 0.776340 11.541118 21.312318 0 11.700539 56.442854 22.853285 2 11.599149 12.977594 4.905724 1 22.944083 0.501586 42.553746 0 4.092333 39.273114 23.406309 In [135]: df[~df.eq(df.min(1), axis=0)] = 0 In [136]: df Out[136]: 0 1 2 0 0.414143 0.000000 0.000000 1 0.000000 0.514046 0.000000 0 0.776340 0.000000 0.000000 0 11.700539 0.000000 0.000000 2 0.000000 0.000000 4.905724 1 0.000000 0.501586 0.000000 0 4.092333 0.000000 0.000000 Old answer: One of many possible ways: In [108]: df[~df.eq(df.min(1), axis=0)] = 0 In [109]: df Out[109]: 0 1 1 0.000000 13.898568 1 0.000000 0.514046 1 0.000000 11.541118 1 0.000000 12.977594 0 11.700539 0.000000 1 0.000000 0.501586 0 2.358687 0.000000 0 22.853285 0.000000
has comment: http://stackoverflow.com/comment/82369511
type: Answer
answers question: http://stackoverflow.com/q/47704438

http://stackoverflow.com/a/47837536
type: Answer
has body: When you create widgets, like Frames and Labels and Entry's and Buttons, the first arg you pass is the "parent" or "master" arg. That arg determines where Tkinter puts the widget. So, if you want your widgets to show up in a certain frame, then pass that frame rather than ArootA when you create the widgets. In particular, since you want the widgets inside f2, pass f2 instead of ArootA as the first arg when creating those widgets. When you create the Frames, you should pass in the root widget, ArootA. So: f2 = Frame(width=400, ... should really be: f2 = Frame(ArootA, width=400, ... And since you want the widgets to be in f2, change: AnameL = Label(ArootA, ... to AnameL = Label(f2, ... etc, and that should give you the result that you want.
upvote count: 1
accepted answer of: http://stackoverflow.com/q/47837300
score: 1
answers question: http://stackoverflow.com/q/47837300
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/47952325
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/47845059
has body: There is a tag called 'object' in the xml file, so instead directly read attribute of points I should have first found all objects, then drawn the contour defined by each object.
score: 1
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47845059

http://stackoverflow.com/q/47792373
linked to: http://stackoverflow.com/q/8000022
has answer: http://stackoverflow.com/a/47792449
tagged with: django
tagged with: python
type: AnsweredQuestion
has title: Invalid filter error in django custom template filter
score: 0
answer count: 1
type: Question
tagged with: django-templates
accepted answer: http://stackoverflow.com/a/47792449
has body: I'm trying to create a custom template filter but, getting Invalid filter error. TemplateSyntaxError at /attainment/reportcard/ Invalid filter: 'get_item' Request Method: POST Request URL: http://127.0.0.1:8000/attainment/reportcard/ Django Version: 1.11.5 Exception Type: TemplateSyntaxError Exception Value: Invalid filter: 'get_item' Exception Location: /media/itsd/ITSD/ROFI/Projects/Rise/venv/lib/python3.5/site-packages/django/template/base.py in find_filter, line 606 Python Executable: /media/itsd/ITSD/ROFI/Projects/Rise/venv/bin/python Python Version: 3.5.2 I've created a filter in template_filters.py and registered. template_filters.py from django.template.defaulttags import register # Custom template filter to get data from a dictionary using key in template @register.filter def get_item(dictionary, key): return dictionary.get(key) And I've used the filter in the template as follows. {% for subject in subjects %} {% endfor %} What am I missing ?? N.B: I've followed this answer.

http://stackoverflow.com/q/47849750
tagged with: python
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/47849816
answer count: 1
tagged with: formatting
has body: so I just finished up my first semester of Java and am trying to convert some of our projects into python code. We have a PetRecord class that needs to have a name (str), age (double), and weight (double). The project required creating getters and setters for all of these, as well as a toString. I found an example __str__ method being used that allows a python object's attributes to be printed to screen just by print(object_name). I'm not sure why my formatting isn't working properly. If someone could enlighten my on why it's throwing: Traceback (most recent call last): File "PetRecord.py", line 92, in &lt;module&gt; print(TestPet) File "PetRecord.py", line 49, in __str__ return('Name: {self.__name} \nAge: {self.__age} \nWeight:{self.__weight}').format(**self.__dict__) # this is printing literally KeyError: 'self' The code itself (changed the line formatting a bit for this post): class PetRecord(object): ''' All pets come with names, age and weight ''' def __init__(self, name='No Name', age=-1.0, weight=-1.0): # data fields self.__name = name self.__age = age self.__weight = weight def __str__(self): # toString() return('Name: {self.__name} \nAge: {self.__age} \nWeight:{self.__weight}').format( **self.__dict__) # this is printing literally Any help at all would be greatly appreciated.
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/47849816
has title: Formatting output string for __str__ in python3 class
linked to: http://stackoverflow.com/q/1301346

http://stackoverflow.com/comment/82647953
type: QuestionComment
has text: OK, I'll take a look at the updated material.
score: 0
comment on: http://stackoverflow.com/q/47840395
type: Comment

http://stackoverflow.com/q/47722919
score: 0
has answer: http://stackoverflow.com/a/47723187
answer count: 3
has body: Is there a pythonic shorter version for the flowing code: def method(a,b) if a &gt; b: pass else: a, b = b, a
possible better answer: http://stackoverflow.com/a/47722942
has comment: http://stackoverflow.com/comment/82406501
type: Question
has answer: http://stackoverflow.com/a/47722942
accepted answer: http://stackoverflow.com/a/47723187
has title: Switching the value with order
tagged with: python
has answer: http://stackoverflow.com/a/47722973
type: AnsweredQuestion

http://stackoverflow.com/a/47734442
upvote count: 1
has body: You can do it 3 different ways. 1) Via matplotlib import matplotlib #pip install matplotlib print matplotlib.colors.cnames["blue"] # prints u'#0000FF' If you want convert from hex to rgb you can use following function: def hex_to_rgb(hexcode): rgb = tuple(map(ord,hexcode[1:].decode('hex'))) return rgb 2) with this github 3) You can also use webcolors package link
type: Answer
accepted answer of: http://stackoverflow.com/q/47734322
answers question: http://stackoverflow.com/q/47734322
score: 1
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/82395130
comment on: http://stackoverflow.com/a/47717156
type: Comment
score: 0
type: AnswerComment
has text: Yup. And to add a bit of explanation as to why.

http://stackoverflow.com/a/47707152
score: 0
type: Answer
answers question: http://stackoverflow.com/q/47707008
has body: Your json string is wrong. It contains an array of objects which should be within the square [] brackets. Change your json string to json_string = """[{"Id":3429058,"Rcvr":11182,"HasSig":true,"Sig":6,"Icao":"3452C2","Bad":false,"FSeen":"\/Date(1512567030924)\/","CMsgs":2,"AltT":0,"Tisb":false,"TrkH":false,"Sqk":"","VsiT":0,"WTC":0,"Species":0,"EngType":0,"EngMount":0,"Mil":false,"Cou":"Spain","HasPic":false,"Interested":false,"FlightsCount":0,"SpdTyp":0,"CallSus":false,"TT":"a","Trt":1}, {"Id":4509293,"Rcvr":13019,"HasSig":false,"Icao":"44CE6D","Bad":false,"Reg":"OO-SSM","FSeen":"\/Date(1512567029549)\/","TSecs":1,"CMsgs":1,"Alt":23700,"GAlt":23700,"AltT":0,"Tisb":false,"TrkH":false,"Type":"A319","Mdl":"Airbus A319 112","Man":"Airbus","CNum":"1388","Op":"Brussels Airlines","OpIcao":"BEL","Sqk":"","VsiT":0,"WTC":2,"Species":1,"Engines":"2","EngType":3,"EngMount":0,"Mil":false,"Cou":"Belgium","HasPic":false,"Interested":false,"FlightsCount":0,"Gnd":false,"SpdTyp":0,"CallSus":false,"TT":"a","Trt":1,"Year":"2000"}, {"Id":4960709,"Rcvr":11071,"HasSig":true,"Sig":15,"Icao":"4BB1C5","Bad":false,"Reg":"TC-LNE","FSeen":"\/Date(1512567029189)\/","TSecs":1,"CMsgs":4,"Alt":41000,"GAlt":41000,"AltT":0,"Tisb":false,"TrkH":false,"Type":"A333","Mdl":"Airbus A330 303","Man":"Airbus","CNum":"1706","Op":"Turkish Airlines","OpIcao":"THY","Sqk":"","VsiT":0,"WTC":3,"Species":1,"Engines":"2","EngType":3,"EngMount":0,"Mil":false,"Cou":"Turkey","HasPic":false,"Interested":false,"FlightsCount":0,"Gnd":false,"SpdTyp":0,"CallSus":false,"TT":"a","Trt":1,"Year":"2015"}, {"Id":11260420,"Rcvr":11012,"HasSig":true,"Sig":30,"Icao":"ABD204","Bad":false,"Reg":"N8606C","FSeen":"\/Date(1512567029096)\/","TSecs":2,"CMsgs":1,"AltT":0,"Tisb":false,"TrkH":false,"Type":"B738","Mdl":" BOEING 737-8H4","Man":"Boeing","CNum":"35964","Op":"Southwest Airlines","OpIcao":"SWA","Sqk":"","VsiT":0,"WTC":2,"Species":1,"Engines":"2","EngType":3,"EngMount":0,"Mil":false,"Cou":"United States","HasPic":false,"Interested":fa…

http://stackoverflow.com/a/47838560
upvote count: 1
downvote count: 0
answers question: http://stackoverflow.com/q/47822799
has comment: http://stackoverflow.com/comment/82642623
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/99374644
has body: I will talk from the java point of view, but I would guess the python side have the same. did you try the seek method in the DataFileReader object? it allows random access to the file and speed up your process, the complex problem will be point to the correct sync point. I would recommend save the sync point during the writing of the files. UPDATE: The link has been changed to point to the most recent docs.

http://stackoverflow.com/comment/82592951
type: QuestionComment
comment on: http://stackoverflow.com/q/47803865
type: Comment
score: 0
has text: @JonathonReinhart I did. The post you mentioned was about efficiency. My question is about writing in in the most compact way regardless of efficiency. Even though one of the answers is the same, the intend is clearly different, that's why I asked (And that's why it isnt exactly a duplicate)

http://stackoverflow.com/q/47815178
type: Question
type: AnsweredQuestion
has title: Regex: Ignore the first match of continuous same characters
has comment: http://stackoverflow.com/comment/82615553
tagged with: python
score: -2
tagged with: regex
has comment: http://stackoverflow.com/comment/82598525
has body: I'm trying to ignore the first \ in a string in a continuous sequence by using regex. So that when there is only \, we will not match it. When there are two \\, we only match one \. For example: I got: {\"url\":\"http:\\/\\/p1.pstatp.com\\/origin\\/tuchong.fullscreen\\/29016715_tt\"} what regex I can use to make it become: {"url":"http:\/\/p1.pstatp.com\/origin\/tuchong.fullscreen\/29016715_tt"} How to make this happen?
accepted answer: http://stackoverflow.com/a/47815566
has answer: http://stackoverflow.com/a/47815566
answer count: 1
downvote count: 3
upvote count: 1
favorite count: 0

http://stackoverflow.com/comment/82591561
score: 1
has text: I feel you should be able to use that function without requiring a db value, as long as the polygon is in WKT or other postgis format. eg `SELECT ST_MAKEVALID(POLYGON('WKT text here'));`
comment on: http://stackoverflow.com/q/47778132
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82539070
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/47788152
has text: Thanks so much for your help. Makes sense. @PM2Ring

http://stackoverflow.com/q/47842654
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/47842683
score: 0
tagged with: django-models
has title: django error: 'subjects' object has no attribute 'get'
type: Question
accepted answer: http://stackoverflow.com/a/47842683
answer count: 1
has body: I'm working in my first django project. Unfortunately, I'm facing an issue that should be straightforward. my scenario: models.py from django.db import models # Create your models here. ## 1. Model for user registration class subjects(models.Model): description = models.CharField(max_length=500) def __Str__(self): return self.description views.py from django.contrib.auth import login , authenticate from django.shortcuts import render , redirect from poc_teaching.models import subjects # Create your views here. def list_subj(request): subj = subjects.objects.all() return render (request,'subjects.html',{'subjects': subj}) urls.py from django.conf.urls import url #from . import views from poc_teaching import views as poc_views urlpatterns = [ url('subjects/$',poc_views.subjects,name ='subjects'), ] html &lt;head&gt; "hello world" &lt;/head&gt; &lt;div&gt; {{ subjects }} &lt;/div&gt; I'm getting the error: 'subjects' object has no attribute 'get' I've gone thru the admin console to add objects. So, I'm pretty sure I should get results. I have gone thru many documents but really I dont understand where is my issue. I appreciate your help.
tagged with: django
tagged with: python

http://stackoverflow.com/a/47824310
has comment: http://stackoverflow.com/comment/82611218
upvote count: 4
score: 2
downvote count: 2
answers question: http://stackoverflow.com/q/47824285
has comment: http://stackoverflow.com/comment/82611364
has body: You can cast cursewords to a set for increased lookup efficiency and use list comprehension which is more efficient than more generic looping in smaller cases: curseword = {'fuxx', 'die', 'damn'} text = [ ['i','am','a','boy'] , [....] , [....] ] new_text = map(int, [all(b not in curseword for b in i) for i in text])
type: Answer

http://stackoverflow.com/q/47828926
tagged with: javascript
tagged with: python
has body: I'm trying to add twitter-bootstrap to a django project. I've got a html file called base.html which acts as a wrapper file for other html code which is placed inside of it before it gets send back in the HttpResponse. base.html {% load static %} TITLE {% autoescape off %}{{ content }}{% endautoescape %} This file is the only file which will ever get send back to the visitor of the webside so I would imagine that if I add the files bootstrap needs inside base.html that it would work also on the code in content. Infact, all the css stuff seems to work fine but whenever I try to open a dropdown menu in the navbar of my site, it does not show up. This is the source code of the page that has difficulties: TITLE Home (current) testchannel Disabled Search Username Visit Channel Statistics Settings A TEST HEADER Clicking on the "/static/css/bootstrap.min.css" or "/static/js/bootstrap.min.js" both redirects me to a file (no 404 error pops up). what could be the problem causing the navbar to not work? How can I fix it? EDIT: As requested the settings.py part that handles static: # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # some more stuff here like INSTALLED_APPS and TEMPLATES STATICFILES_DIRS = ( '/home/<name>/Desktop/django/myproject/Bootstrap', ) STATIC_URL = '/static/'
score: 0
tagged with: twitter-bootstrap
answer count: 1
tagged with: django
has title: bootstrap navbar dropdowns not showing with django
type: Question
has answer: http://stackoverflow.com/a/47829001
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/html

http://stackoverflow.com/q/47728754
has answer: http://stackoverflow.com/a/47729596
accepted answer: http://stackoverflow.com/a/47729596
favorite count: 0
has body: I want to convert a python code to c# code,in python code there is a method that name is calendar.monthcalendar(year,month) I don't know how can i convert it c# code. monthcalendar() method The monthrange() method is used to get a matrix representing a month’s calendar. Each row represents a week; days outside of the month a represented by zeros. Each week begins with Monday unless set by setfirstweekday().
type: Question
tagged with: c#
has comment: http://stackoverflow.com/comment/82418438
answer count: 1
tagged with: python
type: AnsweredQuestion
upvote count: 0
has title: Is there like python monthcalendar method in c#?
downvote count: 1
score: -1
has comment: http://stackoverflow.com/comment/82418257

http://stackoverflow.com/a/50253635
has comment: http://stackoverflow.com/comment/103800275
has comment: http://stackoverflow.com/comment/101864730
has comment: http://stackoverflow.com/comment/97159142
has comment: http://stackoverflow.com/comment/107849585
downvote count: 0
has body: Warning: Unless you have a very specific reason not to, just follow the official installation instructions from https://pytorch.org. They are far more likely to be accurate and up-to-date. Here is how to install the PyTorch package from the official channel, on Windows using Anaconda, as of the time of writing this comment (31/03/2020): PyTorch without CUDA: conda install pytorch torchvision cpuonly -c pytorch PyTorch with CUDA 10.1: conda install pytorch torchvision cudatoolkit=10.1 -c pytorch
has comment: http://stackoverflow.com/comment/107476344
answers question: http://stackoverflow.com/q/47754749
score: 31
type: Answer
has comment: http://stackoverflow.com/comment/107476282
has comment: http://stackoverflow.com/comment/107850968
upvote count: 31

http://stackoverflow.com/comment/82649987
comment on: http://stackoverflow.com/a/47790277
score: 0
type: Comment
has text: Hi developper i have found the solution for this. we can pass data in "_prepare_procurement_group(self):" method in sale_order
type: AnswerComment

http://stackoverflow.com/comment/82509897
type: Comment
has text: And how? With my other google drive account from company it work's fine
comment on: http://stackoverflow.com/a/47772437
type: AnswerComment
score: 0

http://stackoverflow.com/a/47823472
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82640258
has comment: http://stackoverflow.com/comment/82640699
answers question: http://stackoverflow.com/q/47823460
has comment: http://stackoverflow.com/comment/82664814
has comment: http://stackoverflow.com/comment/82640317
has comment: http://stackoverflow.com/comment/82640340
has comment: http://stackoverflow.com/comment/82632357
has body: By using fillna df.content=df.content.fillna(df.target) df Out[268]: content target 0 1.0 0 1 3.0 1 2 6.0 0 3 2.0 2 4 1.0 4 5 59.0 5 6 5.0 5 EDIT df.ffill() Out[487]: content target 0 1.0 0 1 3.0 1 2 6.0 0 3 6.0 2 4 1.0 4 5 59.0 5 6 59.0 5 I guess you need this df.content.reindex(df.target) Out[492]: target 0 1.0 1 3.0 0 1.0 2 6.0 4 1.0 5 59.0 5 59.0 Name: content, dtype: float64 After assign it back df.content=df.content.reindex(df.target).values df Out[494]: content target 0 1.0 0 1 3.0 1 2 1.0 0 3 6.0 2 4 1.0 4 5 59.0 5 6 59.0 5 Let me edit again df.content.fillna(df.content.reindex(df.target).reset_index(drop=True)) Out[508]: 0 1.0 1 3.0 2 1.0 3 6.0 4 1.0 5 59.0 6 1.0 Name: content, dtype: float64
has comment: http://stackoverflow.com/comment/82643968
type: Answer
has comment: http://stackoverflow.com/comment/82640811
has comment: http://stackoverflow.com/comment/82640321
has comment: http://stackoverflow.com/comment/82632390
has comment: http://stackoverflow.com/comment/82612444
has comment: http://stackoverflow.com/comment/82611431
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/47823460
downvote count: 0
has comment: http://stackoverflow.com/comment/82640611

http://stackoverflow.com/comment/82598540
has text: Thank you. I knew it was something simple I was missing.
comment on: http://stackoverflow.com/a/47801400
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/47838055
accepted answer of: http://stackoverflow.com/q/47833828
downvote count: 0
has body: The problem may be with ArgParser() class. I don't know what that is, though it may be a customized argparse.ArgumentParser (as subclass). add_parser makes sure there is a prog in the kwargs, which it then passes to parser = self._parser_class(**kwargs). _parser_class is the class of the main parser unless an alternative is specified in the add_subparsers line. So I'm guessing that ArgParser does not accept a prog keyword, even though ArgumentParser does. But I don't think we can help you without knowing more about its source.
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82690890
answers question: http://stackoverflow.com/q/47833828
score: 1
type: Answer

http://stackoverflow.com/a/47797283
score: 1
upvote count: 1
has body: df=pd.concat([X,Y.reindex(columns=X.columns)],keys=['x','y'],axis=1) x=df.groupby(level=1,axis=1).sum().add_prefix('sum_') df.columns=df.columns.map('{0[1]}{0[0]}'.format) pd.concat([df,x],1) Out[58]: ax bx ay by sum_a sum_b 0 1 2 10 NaN 11.0 2.0 1 3 4 20 NaN 23.0 4.0 2 5 6 30 NaN 35.0 6.0
type: Answer
answers question: http://stackoverflow.com/q/47797150
downvote count: 0

http://stackoverflow.com/q/47727306
has comment: http://stackoverflow.com/comment/82415063
type: UnansweredQuestion
tagged with: django
tagged with: python
has body: I write a blog according by the book Django by Example. # blog/models.py from django.contrib.auth.models import User from django.db import models from django.utils import timezone # Create your models here. class Post(models.Model): title = models.CharField(max_length=200) slug = models.SlugField(max_length=200, unique_for_date='publish') author = models.ForeignKey( User, related_name='blog_posts', on_delete=models.CASCADE) body = models.TextField() publish = models.DateTimeField(default=timezone.localtime) class Meta: ordering = ('-publish', ) def __str__(self): return self.title url config: # blog/urls.py from django.urls import path from . import views urlpatterns = [ path('&lt;int:year&gt;/&lt;int:month&gt;/&lt;int:day&gt;/&lt;str:slug&gt;', views.post_detail, name='post_detail'), ] When I get a post in blog/views.py: def post_detail(request, year, month, day, slug): post = get_object_or_404( Post, slug=slug, publish__year=year, publish__month=month, publish__day=day ) return render(request, 'blog/post_detail.html', {'post': post}) It returns 404. Page not found (404) Request Method: GET Request URL: http://localhost/blog/2017/12/9/its-code-now Raised by: blog.views.post_detail No Post matches the given query. If I modify blog/views.py, just filter year, it returns fine: def post_detail(request, year, month, day, slug): post = get_object_or_404( Post, slug=slug, publish__year=year, ) return render(request, 'blog/post_detail.html', {'post': post}) It seems the problem is publish__month. But Django support this method. I can't figure out how to fix it.
has comment: http://stackoverflow.com/comment/82416289
score: 0
answer count: 0
has title: Can't get object through publish__month
type: Question
has comment: http://stackoverflow.com/comment/82415231

http://stackoverflow.com/comment/82594395
comment on: http://stackoverflow.com/a/47816149
type: AnswerComment
score: 0
has text: I have updated my answer with a potential solution to that.
type: Comment

http://stackoverflow.com/comment/82357744
has text: @AgapwIesu Yes, but the proper way to implement that would be `while currentChar:`. Adding the `not` will cause the loop to never run unless the file is empty.
comment on: http://stackoverflow.com/q/47698647
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/47819569
type: Answer
answers question: http://stackoverflow.com/q/47819146
has body: To sum up, there are a few possible ways such as : test[np.all(test != 'a', axis=1), :] Or test[(test != 'a').all(axis=1)]
upvote count: 2
downvote count: 0
score: 2

timedelta
tags question: http://stackoverflow.com/q/47841502
type: Tag
tag name: timedelta

http://stackoverflow.com/q/47730240
score: 21
has answer: http://stackoverflow.com/a/68753321
possible better answer: http://stackoverflow.com/a/58110312
tagged with: compression
downvote count: 0
tagged with: selenium
has answer: http://stackoverflow.com/a/69947370
has answer: http://stackoverflow.com/a/58110312
upvote count: 21
favorite count: 0
has body: How do I use UPX with pyinstaller? I am following the docs. I have downloaded UPX. My file looks like: import csv import selenium import pandas print('Hello') I then run: pyinstaller -F --upx-dir C:\Users\DD\Downloads\upx394w\upx394w\123\upx308w\upx.exe zz.spec This does not affect the size of the file. Any idea how I can get this to work? # -*- mode: python -*- block_cipher = None a = Analysis(['zz.py'], pathex=['C:\\Users\\DA\\13\\14'], binaries=[], datas=[], hiddenimports=[], hookspath=[], runtime_hooks=[], excludes=[], win_no_prefer_redirects=False, win_private_assemblies=False, cipher=block_cipher) pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher) exe = EXE(pyz, a.scripts, a.binaries, a.zipfiles, a.datas, name='zz', debug=False, strip=False, upx=True, runtime_tmpdir=None, console=True )
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/72627206
tagged with: pyinstaller
has answer: http://stackoverflow.com/a/58276182
tagged with: python
answer count: 6
accepted answer: http://stackoverflow.com/a/47821887
has answer: http://stackoverflow.com/a/47821887
type: AnsweredQuestion
has title: How do I use UPX with pyinstaller?

http://stackoverflow.com/comment/86421084
type: QuestionComment
comment on: http://stackoverflow.com/q/47804393
type: Comment
has text: Moreover, if a table has any FK, sqlalchemy will make additional SELECT for each fk value to linked table. Whata madness
score: 0

http://stackoverflow.com/a/47819586
has body: Here's one way to do this with groupby. We tell groupby to look for strings that start with 'splitter'. This creates two kinds of groups: strings that start with 'splitter', and all the other strings. Eg, from itertools import groupby data = ['splitter001','stringA','stringB','splitter_1234','stringC'] for k, g in groupby(data, key=lambda s: s.startswith('splitter')): print(k, list(g)) output True ['splitter001'] False ['stringA', 'stringB'] True ['splitter_1234'] False ['stringC'] So we can put those groups into two lists and then zip them together to make the final list. from itertools import groupby data = ['splitter001','stringA','stringB','splitter_1234','stringC'] head = [] tail = [] for k, g in groupby(data, key=lambda s: s.startswith('splitter')): if k: head.append(list(g)) else: tail.append(list(g)) out = [u+v for u, v in zip(head, tail)] print(out) output [['splitter001', 'stringA', 'stringB'], ['splitter_1234', 'stringC']] Here's a more compact way to do the same thing, using a list of lists to store the head and tail lists: from itertools import groupby data = ['splitter001','stringA','stringB','splitter_1234','stringC'] results = [[], []] for k, g in groupby(data, key=lambda s: s.startswith('splitter')): results[k].append(list(g)) out = [v+u for u, v in zip(*results)] print(out) output [['splitter001', 'stringA', 'stringB'], ['splitter_1234', 'stringC']] If you want to print each sublist on a separate line, the simple way is to do it with a for loop instead of creating the out list. for u, v in zip(*results): print(v + u) output ['splitter001', 'stringA', 'stringB'] ['splitter_1234', 'stringC'] Another way is to convert the sublists to strings and then join them together with newlines to create one big string. print('\n'.join([str(v + u) for u, v in zip(*results)])) This final variation stores both kinds of groups into a single iterator object. I think you'll agree that the previous versions are easier to read. :) it = iter(list(g) for k, g in groupby(d…
has comment: http://stackoverflow.com/comment/82603551
has comment: http://stackoverflow.com/comment/82601467
score: 3
accepted answer of: http://stackoverflow.com/q/47819144
upvote count: 3
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82603174
has comment: http://stackoverflow.com/comment/82601893
answers question: http://stackoverflow.com/q/47819144
has comment: http://stackoverflow.com/comment/82601815
type: Answer

http://stackoverflow.com/comment/90949302
type: Comment
comment on: http://stackoverflow.com/a/47855622
has text: Since the shape of the input data is (samples, time_steps, features), a DataFrame cannot hold the data, since it can only store 2D data, isn't it?
type: AnswerComment
score: 0

http://stackoverflow.com/a/47756539
answers question: http://stackoverflow.com/q/47756183
type: Answer
upvote count: 4
has body: All depends on what you call "name"... &gt;&gt;&gt; class Foo(object): ... pass ... &gt;&gt;&gt; _Foo = Foo &gt;&gt;&gt; def Foo(): ... return _Foo() ... &gt;&gt;&gt; f = Foo() &gt;&gt;&gt; print(Foo) &lt;function Foo at 0x7f74a5fec8c0&gt; &gt;&gt;&gt; print(type(f)) &lt;class '__main__.Foo'&gt; &gt;&gt;&gt; As you can see, you here have a function exposed as Foo and having it's __name__ == "Foo", and a class exposed as _Foo but having __name__ == "Foo" too. To answer your question: you cannot have the same name (=> variable) bound to more than one object at a given time in a given namespace. But you can have has many objects has you want having the same value for a .__name__ attribute.
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/82480499
downvote count: 0
accepted answer of: http://stackoverflow.com/q/47756183
score: 4

http://stackoverflow.com/comment/82638727
type: Comment
has text: @hpaulj `type magic` would show it.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/47834140

http://stackoverflow.com/comment/82513534
score: 0
type: Comment
type: AnswerComment
has text: Yes. The division was just a random problem. but I just realized that there is also the apply_along_axis: https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.apply_along_axis.html
comment on: http://stackoverflow.com/a/47776225

http://stackoverflow.com/q/47793315
duplicate of: http://stackoverflow.com/q/21406057
tagged with: flask
downvote count: 1
has body: I am trying to put contents of web form to python script. I have used below code, when i hit submit, i must see the output on the webpage. Basically Hello, (taken from web page as input). I encounter a type error. #!/bin/python import os from flask import Flask from flask import request from flask import render_template app = Flask(__name__) @app.route('/') def my_form(): return render_template("index.html") @app.route('/', methods=['POST']) def my_form_post(): text = request.form['text'] cmd = "sh relay.sh " + text rep = os.system(cmd) return rep if __name__ == '__main__': app.run() I am getting the following error when i run this. I am basically trying to pass some info from a webpage (text box). I just entered 'Damnnn' to check output. Hello, Damnnn 10.x.x.x - - [19/Jan/2017 0227:11:51] "POST / HTTP/1.1" 500 - Traceback (most recent call last): File "/usr/lib64/python2.7/site-packages/flask/app.py", line 1997, in __call__ return self.wsgi_app(environ, start_response) File "/usr/lib64/python2.7/site-packages/flask/app.py", line 1985, in wsgi_app response = self.handle_exception(e) File "/usr/lib64/python2.7/site-packages/flask/app.py", line 1540, in handle_exception reraise(exc_type, exc_value, tb) File "/usr/lib64/python2.7/site-packages/flask/app.py", line 1982, in wsgi_app response = self.full_dispatch_request() File "/usr/lib64/python2.7/site-packages/flask/app.py", line 1615, in full_dispatch_request return self.finalize_request(rv) File "/usr/lib64/python2.7/site-packages/flask/app.py", line 1630, in finalize_request response = self.make_response(rv) File "/usr/lib64/python2.7/site-packages/flask/app.py", line 1740, in make_response rv = self.response_class.force_type(rv, request.environ) File "/usr/lib/python2.7/site-packages/werkzeug/wrappers.py", line 911, in force_type response = BaseResponse(*_run_wsgi_app(response, environ)) File "/usr/lib/python2.7/site-packages/werkzeug/test.py", line 884, in run_wsgi_app app_rv = app(environ, start_response) TypeErr…
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/21406057
tagged with: typeerror
tagged with: python
score: -1
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/47793703
has title: Getting a TypeError error when i return a variable of a Python program
upvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/47793703

http://stackoverflow.com/a/47838873
score: 1
has comment: http://stackoverflow.com/comment/82642170
answers question: http://stackoverflow.com/q/47838733
has comment: http://stackoverflow.com/comment/82648814
has comment: http://stackoverflow.com/comment/82642184
has comment: http://stackoverflow.com/comment/82676691
has body: Use a function with two parameter , one is your desired string and second is your list : Data is : data=[(0, '0.897*"allah" + 0.120*"indeed" + 0.117*"lord" + 0.110*"said" + 0.101*"people" + 0.093*"upon" + 0.083*"shall" + 0.082*"unto" + 0.072*"believe" + 0.070*"earth"'), (1, '0.495*"lord" + 0.398*"said" + -0.377*"allah" + 0.252*"shall" + 0.241*"people" + 0.236*"unto" + 0.195*"indeed" + 0.131*"upon" + 0.117*"come" + 0.109*"thou"'), (2, '-0.682*"lord" + 0.497*"shall" + 0.350*"unto" + 0.125*"thee" + 0.125*"thou" + -0.098*"indeed" + -0.092*"said" + 0.092*"come" + 0.091*"people" + 0.080*"truth"'), (3, '-0.615*"shall" + 0.520*"people" + -0.395*"lord" + 0.259*"said" + 0.227*"indeed" + 0.103*"would" + 0.081*"sent" + 0.078*"among" + -0.059*"deeds" + -0.053*"good"'), (4, '0.675*"unto" + -0.425*"shall" + -0.335*"indeed" + 0.214*"thou" + 0.180*"thee" + 0.161*"lord" + -0.105*"said" + 0.099*"hath" + -0.075*"upon"'), (5, '-0.760*"said" + 0.356*"indeed" + 0.261*"upon" + 0.157*"would" + -0.130*"shall" + 0.109*"earth" + -0.108*"allah" + 0.105*"lord" + 0.100*"truth" + 0.096*"good"')] Detailed solution : def search_strin(stri,list_1): final_list=[] for tup in list_1: for item in tup: if isinstance(item,str): if stri in item: final_list.append(tup) return final_list print(search_strin('people',data)) output: Its returning only those group which have 'people' in string. [(0, '0.897*"allah" + 0.120*"indeed" + 0.117*"lord" + 0.110*"said" + 0.101*"people" + 0.093*"upon" + 0.083*"shall" + 0.082*"unto" + 0.072*"believe" + 0.070*"earth"'), (1, '0.495*"lord" + 0.398*"said" + -0.377*"allah" + 0.252*"shall" + 0.241*"people" + 0.236*"unto" + 0.195*"indeed" + 0.131*"upon" + 0.117*"come" + 0.109*"thou"'), (2, '-0.682*"lord" + 0.497*"shall" + 0.350*"unto" + 0.125*"thee" + 0.125*"thou" + -0.098*"indeed" + -0.092*"said" + 0.092*"come" + 0.091*"people" + 0.080*"truth"'), (3, '-0.615*"shall" + 0.520*"people" + -0.395*"lord" + 0.259*"said" + 0.227*"indeed" + 0.103*"would" + 0.081*"sent" + 0.078*"among" + -…
has comment: http://stackoverflow.com/comment/82657962
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/82642758
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/82642230
accepted answer of: http://stackoverflow.com/q/47838733

http://stackoverflow.com/q/47767394
type: Question
answer count: 0
type: UnansweredQuestion
downvote count: 0
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/82496324
has title: how to install Basemap?
has body: I'm a complete novice learning python. I'm trying to install basemap on windows 64 and am having trouble with it. I've been trying to follow the instructions from https://matplotlib.org/basemap/users/installing.html, but being the novice that I am, I'm confused about the steps. Can anyone clarify it a little bit? Any help would be appreciated!
has comment: http://stackoverflow.com/comment/82566242
has comment: http://stackoverflow.com/comment/82502793
tagged with: matplotlib
score: 1
tagged with: matplotlib-basemap
favorite count: 0

http://stackoverflow.com/q/47772556
has comment: http://stackoverflow.com/comment/82506539
has comment: http://stackoverflow.com/comment/82508053
has comment: http://stackoverflow.com/comment/82506397
has comment: http://stackoverflow.com/comment/82506486
answer count: 1
downvote count: 3
upvote count: 1
has comment: http://stackoverflow.com/comment/82506467
has comment: http://stackoverflow.com/comment/82506338
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/47772828
has comment: http://stackoverflow.com/comment/82506084
has title: How to perform group by in python
type: UnansweredQuestion
score: -2
has body: I am trying to find the average of certain numbers in python For example: A={('A','B',1):1,('A','B',2):4,('A1','B1',2):5,('A1','B1',1):6} A is dictionary and my output should be B={('A','B'):1+4/2,('A1','B1'):11/2)} I got the logic by using some FOR loops and IF condition but it is too time consuming. Can anyone tell me a faster way of getting the output. my logic for i in A: # lis.append(i) lis.append((i, A[i])) for j in lis: if (j[0][0], j[0][1]) not in pro_loc_comb: pro_loc_comb.append((j[0][0], j[0][1])) B= {} print pro_loc_comb for x in pro_loc_comb: a = 0 count = 0 for j in lis: if (x[0] == j[0][0]): if (x[1] == j[0][1]): count = count + 1 a = (a + j[1]) B[(x[0], x[1])] = a / float(count) print B Thanks in advance
tagged with: python

http://stackoverflow.com/q/47828437
has comment: http://stackoverflow.com/comment/82634513
type: Question
tagged with: python-3.x
has body: I am getting the following error when I m trying to import from sklearn.cluster: The same thing has been working for a few days but suddenly it stopped working and I tried to update the sklearn in terminal but it doesn't help. Can someone figure out where the error is from?
has answer: http://stackoverflow.com/a/65987290
type: UnansweredQuestion
has title: Import Error: cannot import name 'BaseEstimator'
has comment: http://stackoverflow.com/comment/82619421
tagged with: python
has comment: http://stackoverflow.com/comment/82619264
score: 0
tagged with: anaconda
answer count: 1

http://stackoverflow.com/q/47784981
answer count: 1
accepted answer: http://stackoverflow.com/a/47786204
type: Question
has title: Using JAVA on heroku Flask App
tagged with: heroku
has comment: http://stackoverflow.com/comment/82531582
tagged with: python
has answer: http://stackoverflow.com/a/47786204
type: AnsweredQuestion
score: 0
has body: I have created and deployed a Flask app on heroku, but some of the code for my app, requires Java. When I run the code it says that JAVAHOME is not set. I tried heroku run 'which java' But nothing happens, and I cannot find java executable, nor the directory to set JAVAHOME manually. My question is, is it possible to have a Flask app which uses code that needs java (a java.jar)?
tagged with: java

http://stackoverflow.com/comment/82478559
comment on: http://stackoverflow.com/q/47742311
type: Comment
score: 0
has text: could you please add the full traceback error?
type: QuestionComment

http://stackoverflow.com/a/47842232
answers question: http://stackoverflow.com/q/47836728
type: Answer
has comment: http://stackoverflow.com/comment/82650848
upvote count: 2
score: 2
accepted answer of: http://stackoverflow.com/q/47836728
downvote count: 0
type: AcceptedAnswer
has body: The correct order in which you apply decorators is sometimes hard to figure out without knowing what the decorator does, but unfortunately the wrong order will make the application behave incorrectly. For decorators that do something "before" the view function runs, as in this case, you typically have to put the decorators in the order in which you want them to execute. So I think your code will do what you expect when you use Flask-HTTPAuth's login_required before your must_be_admin: @core.route("/admin") @auth.login_required @must_be_admin def admin(): return render_template("admin.html") In this way, the credentials will be checked first, and if missing or invalid login_required will return a 401 error to the browser, which will make the login prompt appear. Only after credentials are determined to be valid you want to evaluate the admin decorator.

http://stackoverflow.com/comment/83479657
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48113501
has text: Sorry, I didn't finshed the sentences. X is a vtkCompositeDataArray and not a vtkGenericDataArray. Can be this the problem? I'm using Praview 5.4.1 for Windows 64 bit.
score: 0

http://stackoverflow.com/comment/82561363
has text: @debasis Did you read the xpath documentation? If you've found the div with `Carolina Brights`, you need to find it's sibling ` `, and then you need that's divs `` child tag, and that's what you click. That search looks kind of, but not quite, like this (read the xpath docs to figure out the error): `//div[text()="Carolina Brights"]/followingsibling:div/a`
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/47783343

http://stackoverflow.com/comment/82566604
score: 0
comment on: http://stackoverflow.com/q/47802480
has text: Can you specify very clearly what it means to be within range? Does it mean `255 >= r >= 200 and 255 >= g >= 200 and 0 <= g <= 50`?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/82704517
has text: Well if the expected result has definitely ones on the diag then there is something wrong with the formula.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/47854297
type: AnswerComment

http://stackoverflow.com/comment/82616168
score: 0
type: AnswerComment
has text: Then it must be about the url or post data, make sure they are correct. If you save `r.text` as .html file and open it in a browser it might give you a clue.
comment on: http://stackoverflow.com/a/47825174
type: Comment

http://stackoverflow.com/a/47818554
type: Answer
answers question: http://stackoverflow.com/q/47817947
score: 0
has body: You can map those lists of dicts to dicts of dicts and then update one with the other: &gt;&gt;&gt; list1_as_dict = collections.OrderedDict(((d["host"],d["name"]), d) for d in list_of_dicts1) &gt;&gt;&gt; list1_as_dict.update({(d["host"], d["name"]): d for d in list_of_dicts2}) &gt;&gt;&gt; list(list1_as_dict.values()) [{'name': 'Disk', 'id': '111', 'host': 'host01'}, {'name': 'Disk', 'id': '444', 'host': 'host02'}, {'name': 'CPU', 'id': '333', 'host': 'host02'}, {'name': 'Disk', 'id': '555', 'host': 'host03'}] Or shorter, defining a function for extracting the entries; same result: &gt;&gt;&gt; entry = lambda d: ((d["host"], d["name"]), d) &gt;&gt;&gt; list1_as_dict = collections.OrderedDict(map(entry, list_of_dicts1)) &gt;&gt;&gt; list1_as_dict.update(map(entry, list_of_dicts2)) The complexity of this will be O(n).

http://stackoverflow.com/a/47839203
score: 0
answers question: http://stackoverflow.com/q/47829925
has body: Wrapping @pankaj and @Bryan answers with official docs: Have a look into robot docs about test execution: Test cases are always executed within a test suite. A test suite created from a test case file has tests directly, whereas suites created from directories have child test suites which either have tests or their own child suites. By default all the tests in an executed suite are run, but it is possible to select tests using options --test, --suite, --include and --exclude. Suites containing no tests are ignored. As @Bryan said, robot will run testcases in testsuite file, if folder is selected,all inherited testcases and testsuites will be executed If you need to select testcases from testsuites to run,exclude some or execute based on tag, check this section Test suites and test cases can be selected by their names with the command line options --suite (-s) and --test (-t), respectively. Both of these options can be used several times to select several test suites or cases. Arguments to these options are case- and space-insensitive, and there can also be simple patterns matching multiple names. If both the --suite and --test options are used, only test cases in matching suites with matching names are selected. It is possible to include and exclude test cases by tag names with the --include (-i) and --exclude (-e) options, respectively. If the --include option is used, only test cases having a matching tag are selected, and with the --exclude option test cases having a matching tag are not. If both are used, only tests with a tag matching the former option, and not with a tag matching the latter, are selected. About argument file and syntax, here is appropriate part Arg files are useful if your command line gets too long or can be predefined and shared.
type: Answer

http://stackoverflow.com/comment/82368704
type: Comment
has text: Converting it to a list would also be an option, then you can keep the dictionary. `choices=list(USER_TYPE.items())`
comment on: http://stackoverflow.com/a/47704191
type: AnswerComment
score: 0

http://stackoverflow.com/comment/82433491
type: AnswerComment
comment on: http://stackoverflow.com/a/47735114
score: 1
type: Comment
has text: With all due respect, sharing ( of any kind and fashion ) is to be avoided, where possible. Lightweight, "just-enough"-equipped design is a direction to go into. Immense instantiation costs are overheads to be ( always ) avoided -- just benchmark the add-on costs and look into overhead-strict Amdahl's Law, how any technically feasible speedup get devastated in cases, where add-on overheads actually paid have consumed more, than any N-CPU-concurrent process-flows can deliver ( also note the atomicity of ZIP-processing, that sets the max( )-part in the re-formulated Amdahl's Law denominator ).

multithreading
tags question: http://stackoverflow.com/q/47844389
tags question: http://stackoverflow.com/q/47824517
tags question: http://stackoverflow.com/q/47725932
tags question: http://stackoverflow.com/q/47705691
tags question: http://stackoverflow.com/q/47804241
tags question: http://stackoverflow.com/q/47788587
tags question: http://stackoverflow.com/q/47851895
tags question: http://stackoverflow.com/q/47701885
tags question: http://stackoverflow.com/q/47773827
type: Tag
tags question: http://stackoverflow.com/q/47773848
tags question: http://stackoverflow.com/q/47698654
tags question: http://stackoverflow.com/q/47768394
tags question: http://stackoverflow.com/q/47807271
tags question: http://stackoverflow.com/q/47840586
tags question: http://stackoverflow.com/q/47712093
tags question: http://stackoverflow.com/q/47820743
tags question: http://stackoverflow.com/q/47846063
tags question: http://stackoverflow.com/q/47759603
tags question: http://stackoverflow.com/q/47795836
tags question: http://stackoverflow.com/q/47805088
tags question: http://stackoverflow.com/q/47779169
tags question: http://stackoverflow.com/q/47778761
tags question: http://stackoverflow.com/q/47710052
tags question: http://stackoverflow.com/q/47849631
tags question: http://stackoverflow.com/q/47784653
tags question: http://stackoverflow.com/q/47760335
tags question: http://stackoverflow.com/q/47726887
tags question: http://stackoverflow.com/q/47793417
tags question: http://stackoverflow.com/q/47846946
tags question: http://stackoverflow.com/q/47847953
tags question: http://stackoverflow.com/q/47823332
tags question: http://stackoverflow.com/q/47733928
tags question: http://stackoverflow.com/q/47721524
tags question: http://stackoverflow.com/q/47745719
tags question: http://stackoverflow.com/q/47801457
tags question: http://stackoverflow.com/q/47756139
tags question: http://stackoverflow.com/q/47831444
tags question: http://stackoverflow.com/q/47818790
tags question: http://stackoverflow.com/q/47786567
tags question: http://stackoverflow.com/q/47847392
tags question: http://stackoverflow.com/q/47736420
tag name: multithreading
tags question: http://stackoverflow.com/q/47757888
tags question: http://stackoverflow.com/q/47813835
tags question: http://stackoverflow.com/q/47806824
tags question: http://stackoverflow.com/q/47754354

http://stackoverflow.com/q/47824519
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/47824608
tagged with: return
tagged with: return-value
type: UnansweredQuestion
downvote count: 0
upvote count: 1
tagged with: python
has body: I'm building a local website in python to press a button, so the door to my room will open from my phone by using a raspberry pi. I already have made a python program, which, if ran, will open the door flawlessly, however, I am trying to make a button in HTML that will return something to execute the file which will open the door. This is what I already have: from flask import Flask, render_template from test import open_door app = Flask(__name__) @app.route('/open/door') def doorOpen(): return render_template('door.html') @app.route('/opendoor') def openDoor(): open_door() return 'the door should be open' if __name__ == '__main__': app.run(debug=True, host='0.0.0.0') Here is test.py the file which will open the door if executed, and door.html is the following: Open for me please It is not something fancy but it only has to work for now. It looks to me like the return is not doing anything since i also added a return and a print function in the openDoor() function withouth any response. I couln't find any awnsers on the internet so i am curious what the problem is! p.s. This is my first time with python and i am a beginner with HTML edit: this is test.py: import RPi.GPIO as GPIO import time testPin = 18 GPIO.setmode(GPIO.BCM) GPIO.setup(testPin, GPIO.OUT) counter =0 def open_door(): try: while counter < 900000: GPIO.output(testPin, GPIO.HIGH) counter += 1 except: print ("Everything is oke!") finally: GPIO.cleanup()
score: 1
has title: return HTML output to python
tagged with: http://stackoverflow.com/tag/html
answer count: 1
favorite count: 0

http://stackoverflow.com/a/62162057
downvote count: 0
answers question: http://stackoverflow.com/q/47784802
score: 3
upvote count: 3
type: Answer
has body: As of Python 3.4 (per the docs), there is an easier way to accomplish what you are trying to do: from io import StringIO from contextlib import redirect_stdout temp_stdout = StringIO() with redirect_stdout(temp_stdout): result = pytest.main(sys.argv) stdout_str = temp_stdout.getvalue() # or whatever you want to do with it print(stdout_str.upper())

http://stackoverflow.com/q/47847953
type: UnansweredQuestion
has title: python - stop waiting for input() when a condition (not timer) is met
has comment: http://stackoverflow.com/comment/82660684
tagged with: sockets
has answer: http://stackoverflow.com/a/59628312
tagged with: python
has comment: http://stackoverflow.com/comment/82660282
has comment: http://stackoverflow.com/comment/82660152
has comment: http://stackoverflow.com/comment/82660162
score: 0
has comment: http://stackoverflow.com/comment/82660417
tagged with: multithreading
answer count: 1
has body: I am a novice programming that really enjoys programming with python. I am currently working on a program that uses python to set up sockets to establish a tcp connection between two hosts. My goal is to create a program that could serve an incoming connection and also initiate the establishment of a connection. In other words once the program is started it would go through the regular socket setup for a server and start listening for an incoming connection. While the program is listening for an incoming connection, it would also offer the user the option of initiating a connection by inputting an IP address in the console. The goal is... if the user never input an IP address the program would simply continue to listen for an incoming connection. If an incoming connection was made the program would exit out of the user input and notify the user an incoming connection was made, then disallow the option of establishing an outgoing connection via console input. (I know both could be handled with threading, but I want the program to only handle one connection, whether that be as server or client). However, if the user typed an IP address the program would attempt to establish a connection to the inputted IP. If a connection was established it would stop listening for an incoming connection and focus on the outgoing connection. I highlighted my problem above. I need a way of exiting out of the input() prompt when a condition is met (when an incoming connection is established). Currently, when a connection is made, I print "Incoming Connection Established!" however, after this is printed the terminal still waits for the user to input... import socket import sys from _thread import * ipForInitiating = '' host = '' port = 5555 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: s.bind((host, port)) except socket.error as e: print(str(e)) s.listen(2) def checkForIncoming(): while ipForInitiating == '': conn, addr = s.accept() print('################################\nI…
has comment: http://stackoverflow.com/comment/82660228
type: Question
has comment: http://stackoverflow.com/comment/82660348